@k-msg/webhook 0.30.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,68 @@
1
- import type { WebhookDeliveryStore, WebhookEndpointStore, WebhookRuntimeFieldCryptoOptions } from "../runtime/types";
1
+ import { type FieldCryptoConfig } from "@k-msg/core";
2
+ import type { WebhookDeliveryStore, WebhookEndpointStore, WebhookPersistence, WebhookRuntimeFieldCryptoOptions, WebhookTenantMigrationResult } from "../runtime/types";
3
+ import type { WebhookDelivery, WebhookEndpoint } from "../types/webhook.types";
4
+ export declare function protectFieldValue(config: FieldCryptoConfig | undefined, input: {
5
+ value: string | undefined;
6
+ path: string;
7
+ aad: Record<string, string>;
8
+ tenantId?: string;
9
+ }): Promise<string | undefined>;
10
+ /**
11
+ * @evidence docs/security/field-crypto-v1.md#threat-model
12
+ * Decrypts with the tenant-bound AAD, falling back to the tenant-less AAD
13
+ * only when acceptLegacyAad is set, as migrateWebhookFieldCryptoToTenant
14
+ * does to re-encrypt values written before tenant binding.
15
+ * @evidenceReview docs/security/field-crypto-v1.md#threat-model #98761bf
16
+ * Read revealFieldValue and migrateWebhookFieldCryptoToTenant, and ran
17
+ * field-crypto.test.ts: a tenant-less value is rejected by default and
18
+ * read with acceptLegacyAad, and the migration re-encrypts it with the
19
+ * tenant, from the runtime too, stopping at a value neither AAD decrypts
20
+ * instead of storing a fallback.
21
+ */
22
+ export declare function revealFieldValue(config: FieldCryptoConfig | undefined, input: {
23
+ value: string | undefined;
24
+ path: string;
25
+ aad: Record<string, string>;
26
+ tenantId?: string;
27
+ acceptLegacyAad?: boolean;
28
+ }): Promise<string | undefined>;
29
+ /**
30
+ * @evidence docs/security/field-crypto-v1.md#field-policy-modes
31
+ * Accepts only encrypt and encrypt+hash for the endpoint secret and the
32
+ * delivery payload, which the storage always encrypts.
33
+ * @evidenceReview docs/security/field-crypto-v1.md#field-policy-modes #d6936dd
34
+ * Read assertWebhookFieldMode and protectFieldValue, which encrypts
35
+ * whenever crypto is enabled and stores no hash, and ran
36
+ * webhook.registry.crypto.test.ts, which rejects a missing, plain, or mask
37
+ * mode for secret and payload and accepts both encrypt modes.
38
+ */
2
39
  export declare function validateWebhookFieldCryptoOptions(options: WebhookRuntimeFieldCryptoOptions | undefined): void;
40
+ export declare function protectEndpoint(endpoint: WebhookEndpoint, options: WebhookRuntimeFieldCryptoOptions | undefined): Promise<WebhookEndpoint>;
41
+ export declare function revealEndpoint(endpoint: WebhookEndpoint, options: WebhookRuntimeFieldCryptoOptions | undefined): Promise<WebhookEndpoint>;
42
+ export declare function protectDelivery(delivery: WebhookDelivery, options: WebhookRuntimeFieldCryptoOptions | undefined): Promise<WebhookDelivery>;
43
+ export declare function revealDelivery(delivery: WebhookDelivery, options: WebhookRuntimeFieldCryptoOptions | undefined): Promise<WebhookDelivery>;
3
44
  export declare function wrapWebhookEndpointStoreWithFieldCrypto(store: WebhookEndpointStore, options: WebhookRuntimeFieldCryptoOptions | undefined): WebhookEndpointStore;
4
45
  export declare function wrapWebhookDeliveryStoreWithFieldCrypto(store: WebhookDeliveryStore, options: WebhookRuntimeFieldCryptoOptions | undefined): WebhookDeliveryStore;
46
+ /**
47
+ * Re-encrypts endpoint secrets and delivery payloads written before
48
+ * ciphertext was bound to `options.tenantId`, so they read without
49
+ * `acceptLegacyAad`. Pass the stores the runtime persists to, not wrapped
50
+ * ones. Values already bound to the tenant are left as they are, so running
51
+ * it again is safe. The migration runs fail-closed whatever `failMode` says,
52
+ * so a value that cannot be read with either AAD stops it rather than being
53
+ * replaced by a fallback.
54
+ *
55
+ * Run it once every instance runs a version that binds the tenant: an
56
+ * instance still on an older version keeps writing tenant-less values,
57
+ * which this run can miss (running it again after the rollout picks them
58
+ * up). An endpoint is rewritten only if its secret has not changed since
59
+ * the migration read it, keeping its other fields as they are then, and
60
+ * `runtime.migrateFieldCryptoToTenant()` also holds that runtime's own
61
+ * endpoint writes until it finishes. An update from another process can
62
+ * still land between that check and the write and be lost, so pause
63
+ * endpoint changes elsewhere while it runs. Deliveries, which the runtime
64
+ * never rewrites, are read a page at a time with the `before` cursor and
65
+ * written back with the delivery store's `replace()`; a custom store must
66
+ * support both.
67
+ */
68
+ export declare function migrateWebhookFieldCryptoToTenant(persistence: Pick<WebhookPersistence, "endpointStore" | "deliveryStore">, options: WebhookRuntimeFieldCryptoOptions): Promise<WebhookTenantMigrationResult>;
@@ -97,6 +97,10 @@ export declare class LoadBalancer extends EventEmitter {
97
97
  * 건강 상태 확인 시작
98
98
  */
99
99
  private startHealthChecks;
100
+ /**
101
+ * 모든 엔드포인트 건강 상태 확인
102
+ */
103
+ private checkAllEndpoints;
100
104
  /**
101
105
  * 로드 밸런서 종료
102
106
  */
@@ -62,6 +62,10 @@ export declare class QueueManager extends EventEmitter {
62
62
  * 지연된 작업 스케줄링
63
63
  */
64
64
  private scheduleDelayedJob;
65
+ /**
66
+ * 지연된 작업 활성화
67
+ */
68
+ private activateDelayedJob;
65
69
  /**
66
70
  * TTL 정리 작업 시작
67
71
  */
package/dist/index.cjs ADDED
@@ -0,0 +1,5 @@
1
+ var{defineProperty:Ze,getOwnPropertyNames:gn,getOwnPropertyDescriptor:yn}=Object,bn=Object.prototype.hasOwnProperty;function xn(e){return this[e]}var _n=(e)=>{var t=($t??=new WeakMap).get(e),r;if(t)return t;if(t=Ze({},"__esModule",{value:!0}),e&&typeof e==="object"||typeof e==="function"){for(var n of gn(e))if(!bn.call(t,n))Ze(t,n,{get:xn.bind(e,n),enumerable:!(r=yn(e,n))||r.enumerable})}return $t.set(e,t),t},$t;var vn=(e)=>e;function wn(e,t){this[e]=vn.bind(null,t)}var En=(e,t)=>{for(var r in t)Ze(e,r,{get:t[r],enumerable:!0,configurable:!0,set:wn.bind(t,r)})};var Xo={};En(Xo,{DEFAULT_ENDPOINT_VALIDATION_OPTIONS:()=>te,DefaultHttpClient:()=>Ae,RetryManager:()=>ee,SecurityManager:()=>ae,WebhookDeliverySchema:()=>cn,WebhookDispatcher:()=>ce,WebhookEndpointSchema:()=>an,WebhookEventSchema:()=>sn,WebhookEventType:()=>V,WebhookRuntimeService:()=>kt,addEndpoints:()=>fn,createInMemoryWebhookPersistence:()=>ge,endpointMatchesEvent:()=>_e,migrateWebhookFieldCryptoToTenant:()=>ye,probeEndpoint:()=>pn,resolveEndpointValidationOptions:()=>re,resolveWebhookSecurityOptions:()=>hn,validateEndpointUrl:()=>N});module.exports=_n(Xo);var Oe;((g)=>{g.INVALID_REQUEST="INVALID_REQUEST";g.AUTHENTICATION_FAILED="AUTHENTICATION_FAILED";g.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE";g.TEMPLATE_NOT_FOUND="TEMPLATE_NOT_FOUND";g.RATE_LIMIT_EXCEEDED="RATE_LIMIT_EXCEEDED";g.NETWORK_ERROR="NETWORK_ERROR";g.NETWORK_TIMEOUT="NETWORK_TIMEOUT";g.NETWORK_SERVICE_UNAVAILABLE="NETWORK_SERVICE_UNAVAILABLE";g.REQUEST_ABORTED="REQUEST_ABORTED";g.PROVIDER_ERROR="PROVIDER_ERROR";g.MESSAGE_SEND_FAILED="MESSAGE_SEND_FAILED";g.CRYPTO_CONFIG_ERROR="CRYPTO_CONFIG_ERROR";g.CRYPTO_ENCRYPT_FAILED="CRYPTO_ENCRYPT_FAILED";g.CRYPTO_DECRYPT_FAILED="CRYPTO_DECRYPT_FAILED";g.CRYPTO_HASH_FAILED="CRYPTO_HASH_FAILED";g.CRYPTO_POLICY_VIOLATION="CRYPTO_POLICY_VIOLATION";g.UNKNOWN_ERROR="UNKNOWN_ERROR"})(Oe||={});var kn={["INVALID_REQUEST"]:{ko:"잘못된 요청입니다",en:"Invalid request"},["AUTHENTICATION_FAILED"]:{ko:"인증에 실패했습니다",en:"Authentication failed"},["INSUFFICIENT_BALANCE"]:{ko:"잔액이 부족합니다",en:"Insufficient balance"},["TEMPLATE_NOT_FOUND"]:{ko:"템플릿을 찾을 수 없습니다",en:"Template not found"},["RATE_LIMIT_EXCEEDED"]:{ko:"요청 한도를 초과했습니다",en:"Rate limit exceeded"},["NETWORK_ERROR"]:{ko:"네트워크 오류가 발생했습니다",en:"Network error"},["NETWORK_TIMEOUT"]:{ko:"네트워크 요청 시간이 초과되었습니다",en:"Network timeout"},["NETWORK_SERVICE_UNAVAILABLE"]:{ko:"서비스를 일시적으로 사용할 수 없습니다",en:"Service temporarily unavailable"},["REQUEST_ABORTED"]:{ko:"요청이 취소되었습니다",en:"Request aborted"},["PROVIDER_ERROR"]:{ko:"제공자 오류가 발생했습니다",en:"Provider error"},["MESSAGE_SEND_FAILED"]:{ko:"메시지 전송에 실패했습니다",en:"Message send failed"},["CRYPTO_CONFIG_ERROR"]:{ko:"암호화 설정 오류가 발생했습니다",en:"Crypto configuration error"},["CRYPTO_ENCRYPT_FAILED"]:{ko:"암호화에 실패했습니다",en:"Encryption failed"},["CRYPTO_DECRYPT_FAILED"]:{ko:"복호화에 실패했습니다",en:"Decryption failed"},["CRYPTO_HASH_FAILED"]:{ko:"해시 생성에 실패했습니다",en:"Hash generation failed"},["CRYPTO_POLICY_VIOLATION"]:{ko:"암호화 정책 위반이 발생했습니다",en:"Crypto policy violation"},["UNKNOWN_ERROR"]:{ko:"알 수 없는 오류가 발생했습니다",en:"Unknown error"}},Qo=new Set(Object.values(Oe));var Te=(e)=>{if(typeof e!=="number"||Number.isNaN(e)||!Number.isFinite(e))return;return Math.trunc(e)};class fe extends Error{code;details;providerErrorCode;providerErrorText;httpStatus;requestId;retryAfterMs;attempt;causeChain;constructor(e,t,r,n={}){super(t);if(this.name="KMsgError",this.code=e,this.details=r,this.providerErrorCode=n.providerErrorCode,this.providerErrorText=n.providerErrorText,this.httpStatus=Te(n.httpStatus),this.requestId=typeof n.requestId==="string"?n.requestId:void 0,this.retryAfterMs=Te(n.retryAfterMs),this.attempt=Te(n.attempt),Array.isArray(n.causeChain))this.causeChain=n.causeChain;else if(n.causeChain!==void 0)this.causeChain=[n.causeChain];let o=Error.captureStackTrace;if(o)o(this,fe)}getLocalizedMessage(e="ko"){let t=kn[this.code];if(t?.[e])return t[e];return this.message}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,providerErrorCode:this.providerErrorCode,providerErrorText:this.providerErrorText,httpStatus:this.httpStatus,requestId:this.requestId,retryAfterMs:this.retryAfterMs,attempt:this.attempt,causeChain:this.causeChain}}}function Cn(e){switch(e){case"config":return"CRYPTO_CONFIG_ERROR";case"encrypt":return"CRYPTO_ENCRYPT_FAILED";case"decrypt":return"CRYPTO_DECRYPT_FAILED";case"hash":return"CRYPTO_HASH_FAILED";case"policy":return"CRYPTO_POLICY_VIOLATION"}}class v extends fe{kind;fieldPath;failMode;openFallback;constructor(e,t,r,n={}){super(Cn(e),t,r,n);this.name="FieldCryptoError",this.kind=e,this.fieldPath=typeof n.fieldPath==="string"?n.fieldPath:void 0,this.failMode=n.failMode,this.openFallback=n.openFallback}toJSON(){return{...super.toJSON(),kind:this.kind,fieldPath:this.fieldPath,failMode:this.failMode,openFallback:this.openFallback}}}function Le(e){return typeof e==="function"}function At(e){if(typeof e!=="string")return;let t=e.trim();return t.length>0?t:void 0}function Pt(e,t,r){let n=e.fields[t];if(n)return n;if(t.startsWith("metadata.")){let o=e.fields["metadata.*"];if(o)return o}return r}var $n=["closed","open"],Rt=["masked","plaintext","null"];function he(e){return e.failMode==="open"?"open":"closed"}function Fe(e){let t=e.openFallback;return t!==void 0&&Rt.includes(t)?t:"masked"}function An(e,t={}){let r=[];if(!e||typeof e!=="object")return{valid:!1,issues:[{message:"fieldCrypto config must be an object",rule:"fieldCrypto.config.object",hint:"Provide a valid FieldCryptoConfig object"}]};if(!e.provider||typeof e.provider!=="object")r.push({message:"fieldCrypto provider is required",rule:"fieldCrypto.provider.required",path:"provider",hint:"Set provider with encrypt/decrypt/hash methods"});else{if(!Le(e.provider.encrypt))r.push({message:"provider.encrypt must be a function",rule:"fieldCrypto.provider.encrypt.required",path:"provider.encrypt"});if(!Le(e.provider.decrypt))r.push({message:"provider.decrypt must be a function",rule:"fieldCrypto.provider.decrypt.required",path:"provider.decrypt"});if(!Le(e.provider.hash))r.push({message:"provider.hash must be a function",rule:"fieldCrypto.provider.hash.required",path:"provider.hash"})}if(!e.fields||typeof e.fields!=="object")r.push({message:"fieldCrypto.fields must be an object",rule:"fieldCrypto.fields.object",path:"fields",hint:"Define policies such as to, from, metadata.phoneNumber"});else{let i=Object.entries(e.fields);if(i.length===0)r.push({message:"fieldCrypto.fields must not be empty",rule:"fieldCrypto.fields.non_empty",path:"fields",hint:"Add at least one field mode mapping"});for(let[s,a]of i){if(!At(s))r.push({message:"field path must be a non-empty string",rule:"fieldCrypto.fields.path.non_empty",path:"fields"});if(a!=="plain"&&a!=="encrypt"&&a!=="encrypt+hash"&&a!=="mask")r.push({message:`unsupported field mode: ${String(a)}`,rule:"fieldCrypto.fields.mode.supported",path:`fields.${s}`})}}if(e.failMode!==void 0&&!$n.includes(e.failMode))r.push({message:`unsupported failMode: ${String(e.failMode)}`,rule:"fieldCrypto.fail_mode.supported",path:"failMode",hint:'Use "closed" (default) or "open"'});if(e.openFallback!==void 0&&!Rt.includes(e.openFallback))r.push({message:`unsupported openFallback: ${String(e.openFallback)}`,rule:"fieldCrypto.open_fallback.supported",path:"openFallback",hint:'Use "masked" (default), "null", or "plaintext"'});let n=he(e),o=Fe(e);if(n==="open"&&o==="plaintext"&&e.unsafeAllowPlaintextStorage!==!0)r.push({message:"openFallback=plaintext requires unsafeAllowPlaintextStorage=true",rule:"fieldCrypto.fail_open.plaintext_guard",path:"openFallback",hint:"Use masked/null fallback, or explicitly enable unsafe plaintext"});if(Array.isArray(e.aadFields)){if(e.aadFields.length===0)r.push({message:"aadFields must not be empty when provided",rule:"fieldCrypto.aad_fields.non_empty",path:"aadFields"});for(let i=0;i<e.aadFields.length;i+=1){let s=e.aadFields[i];if(!At(s))r.push({message:"aadFields cannot include empty key",rule:"fieldCrypto.aad_fields.no_empty_key",path:`aadFields[${i}]`})}}if(t.secureMode&&!t.compatPlainColumns){let i=Pt(e,"to","encrypt+hash"),s=Pt(e,"from","encrypt+hash");if(i==="plain")r.push({message:"secure mode requires non-plain policy for `to` when compatPlainColumns=false",rule:"fieldCrypto.secure_mode.to_non_plain",path:"fields.to",hint:"Use encrypt+hash for lookup fields"});if(s==="plain")r.push({message:"secure mode requires non-plain policy for `from` when compatPlainColumns=false",rule:"fieldCrypto.secure_mode.from_non_plain",path:"fields.from",hint:"Use encrypt+hash for lookup fields"})}return{valid:r.length===0,issues:r}}function Ne(e,t={}){let r=An(e,t);if(r.valid)return;let n=r.issues[0];if(!n)throw new v("config","fieldCrypto config validation failed",{rule:"fieldCrypto.config.invalid",issues:r.issues});throw new v("config",n.message,{rule:n.rule,path:n.path,hint:n.hint,issues:r.issues},{fieldPath:n.path})}function Pn(e){if(typeof e==="string")return e;return JSON.stringify(e)}function Rn(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.v==="number"&&typeof t.alg==="string"&&typeof t.kid==="string"&&typeof t.iv==="string"&&typeof t.tag==="string"&&typeof t.ct==="string"}function St(e=3,t=2){return(r)=>{let n=String(r??"");if(n.length<=e+t)return"*".repeat(Math.max(0,n.length));let o=n.slice(0,e),i=n.slice(-t);return`${o}${"*".repeat(n.length-e-t)}${i}`}}function Sn(e){let t=Rn(e);if(t&&e.v===1&&e.alg==="A256GCM")return;let r=e&&typeof e==="object"?e:{};throw new v("policy","ciphertext envelope must be v1 A256GCM with string kid, iv, tag, and ct",{rule:"fieldCrypto.envelope.v1",shapeValid:t,v:r.v,alg:r.alg})}function zt(e){if(typeof e==="string")return e;Sn(e);let{v:t,alg:r,kid:n,iv:o,tag:i,ct:s}=e;return Pn({v:t,alg:r,kid:n,iv:o,tag:i,ct:s})}var zn=["to","from","phone","phoneNumber","recipient","sender","secret","apiKey","apiSecret","authorization","auth","token","password","payload","message","content","text"],J=String.raw`\w.[\]"'-`,Mn=new RegExp(String.raw`^[${J}]*(?:(?:secret|password|passwd|passphrase|token|credential|private[-_.]?key|api[-_.]?key)[${J}]*|auth(?:orization)?(?:[.[\]"'][${J}]*)?)$`,"i");function It(e){return Mn.test(e.replace(/\s+/g,"_"))}function In(e){if(It(e))return!0;let t=e.toLowerCase();return zn.some((r)=>t.includes(r.toLowerCase()))}function Dt(e){let t=e.trim();if(t.length<=4)return"***";if(t.includes("@")){let[o,i]=t.split("@");return`${o.slice(0,2)}${"*".repeat(Math.max(1,o.length-2))}@${i}`}let r=t.slice(0,3),n=t.slice(-2);return`${r}${"*".repeat(Math.max(1,t.length-5))}${n}`}var Dn=new RegExp([String.raw`(?:\+82[-.\s]?(?:\(0\)[-.\s]?|0)?|0)(?:1[016789]|2|70|80|50\d|[3-6]\d)[-.\s]?\d{3,4}[-.\s]?\d{4}`,String.raw`\(0\d{1,2}\)[-.\s]?\d{3,4}[-.\s]?\d{4}`,String.raw`1[5-9]\d{2}[-\s]\d{4}`].map((e)=>String.raw`(?<![\w+])${e}(?!\w)`).join("|"),"g"),Zn=/(\b[a-z][\w+.-]{0,31}:\/\/[^\s/:@]*):[^\s/?#]*@/gi,Tn=[String.raw`"(?:\\.|[^"\\\n])*"?`,String.raw`'(?:\\.|[^'\\\n])*'?`,String.raw`\\"(?:\\\\(?:\\.|[^\\\n])|\\[^"\\\n]|[^\\\n])*(?:\\")?`,String.raw`\\'(?:\\\\(?:\\.|[^\\\n])|\\[^'\\\n]|[^\\\n])*(?:\\')?`],On=new RegExp(String.raw`(?<![${J}])((?:["']?(?:api|private)[ \t]+)?[${J}]+)((?:\\?["'])?\s*[:=]\s*)`,"gi"),Mt=new RegExp(String.raw`${Tn.join("|")}|((?:Bearer|Basic)\s+)?[^\s"',;&]+`,"iy");function Ln(e){let t="",r=0;for(let n of e.matchAll(On)){let[o,i=""]=n;if(n.index<r||!It(i))continue;let s=n.index+o.length;Mt.lastIndex=s;let a=Mt.exec(e);if(!a)continue;let l=/^\\?["']/.exec(a[0])?.[0];t+=e.slice(r,s),t+=l?`${l}[REDACTED]${l}`:`${a[1]??""}[REDACTED]`,r=s+a[0].length}return t+e.slice(r)}function me(e){return Ln(e.replace(Zn,"$1:[REDACTED]@").replace(Dn,(t)=>Dt(t)))}function Ue(e,t){if(t===void 0||t===null)return t;if(In(e)){if(typeof t==="string")return Dt(t);if(typeof t==="number"||typeof t==="boolean")return"***";if(Array.isArray(t))return"[REDACTED]";if(typeof t==="object")return"[REDACTED]"}if(Array.isArray(t))return t.map((r)=>Ue(e,r));if(typeof t==="object"){let r={};for(let[n,o]of Object.entries(t))r[n]=Ue(n,o);return r}if(typeof t==="string")return me(t);return t}function Fn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=Ue(r,n);return t}class Be{config;context;constructor(e={},t={}){this.context=e,this.config={level:"INFO",enableConsole:!0,enableJson:!1,enableColors:!0,...t}}shouldLog(e){let t=["DEBUG","INFO","WARN","ERROR"];return t.indexOf(e)>=t.indexOf(this.config.level)}formatMessage(e){let t=Fn(e.context),r=me(e.message),n=e.error&&{name:e.error.name,message:me(e.error.message),stack:e.error.stack?me(e.error.stack):void 0};if(this.config.enableJson)return JSON.stringify({level:e.level,message:r,timestamp:e.timestamp.toISOString(),context:t,...n&&{error:n},...e.duration&&{duration:e.duration}});let o=e.timestamp.toISOString(),i=this.config.enableColors?this.colorizeLevel(e.level):e.level,s=Object.keys(t).length>0?` [${Object.entries(t).map(([l,u])=>`${l}=${u}`).join(", ")}]`:"",a=`${o} ${i}${s}: ${r}`;if(e.duration!==void 0)a+=` (${e.duration}ms)`;if(n)a+=`
2
+ ${n.stack??`${n.name}: ${n.message}`}`;return a}colorizeLevel(e){if(!this.config.enableColors)return e;return`${{["DEBUG"]:"\x1B[36m",["INFO"]:"\x1B[32m",["WARN"]:"\x1B[33m",["ERROR"]:"\x1B[31m"}[e]}${e}\x1B[0m`}writeLog(e){if(!this.shouldLog(e.level))return;let t=this.formatMessage(e);if(this.config.enableConsole)(e.level==="ERROR"?console.error:e.level==="WARN"?console.warn:console.log)(t);if(this.config.enableFile&&this.config.filePath);}debug(e,t={}){this.writeLog({level:"DEBUG",message:e,timestamp:new Date,context:{...this.context,...t}})}info(e,t={}){this.writeLog({level:"INFO",message:e,timestamp:new Date,context:{...this.context,...t}})}warn(e,t={},r){this.writeLog({level:"WARN",message:e,timestamp:new Date,context:{...this.context,...t},error:r})}error(e,t={},r){this.writeLog({level:"ERROR",message:e,timestamp:new Date,context:{...this.context,...t},error:r})}child(e){return new Be({...this.context,...e},this.config)}time(e){let t=Date.now();return()=>{let r=Date.now()-t;this.info(`${e} completed`,{duration:r})}}async measure(e,t,r={}){let n=Date.now(),o={...r,operation:e};this.debug(`Starting ${e}`,o);try{let i=await t(),s=Date.now()-n;return this.info(`Completed ${e}`,{...o,duration:s}),i}catch(i){let s=Date.now()-n;throw this.error(`Failed ${e}`,{...o,duration:s},i instanceof Error?i:Error(String(i))),i}}}var We;function Nn(e,t){return new Be(e,t)}function F(){if(!We)We=Nn();return We}var Q={debug:(e,t)=>F().debug(e,t),info:(e,t)=>F().info(e,t),warn:(e,t,r)=>F().warn(e,t,r),error:(e,t,r)=>F().error(e,t,r),child:(e)=>F().child(e),time:(e)=>F().time(e),measure:(e,t,r)=>F().measure(e,t,r)};function Wn(e,t){return t.updatedAt.getTime()-e.updatedAt.getTime()}function Un(e,t){let r=t.createdAt.getTime()-e.createdAt.getTime();if(r!==0)return r;if(e.id<t.id)return 1;if(e.id>t.id)return-1;return 0}function je(e,t){let r=e.createdAt.getTime(),n=t.createdAt.getTime();return r<n||r===n&&e.id<t.id}function Bn(e,t){if(t.endpointId&&e.endpointId!==t.endpointId)return!1;if(t.eventType&&e.eventType!==t.eventType)return!1;if(t.before&&!je(e,t.before))return!1;if(t.status&&e.status!==t.status)return!1;return!0}class Zt{endpoints=new Map;async add(e){this.endpoints.set(e.id,e)}async update(e,t){if(!this.endpoints.has(e))throw Error(`Webhook endpoint ${e} not found`);this.endpoints.set(e,t)}async remove(e){this.endpoints.delete(e)}async get(e){return this.endpoints.get(e)??null}async list(){return Array.from(this.endpoints.values()).sort(Wn)}}class Tt{deliveries=new Map;async add(e){this.deliveries.set(e.id,e)}async replace(e){this.deliveries.set(e.id,e)}async list(e={}){let t=Array.from(this.deliveries.values()).filter((n)=>Bn(n,e)).sort(Un),r=typeof e.limit==="number"&&Number.isFinite(e.limit)?Math.max(0,Math.floor(e.limit)):100;return t.slice(0,r)}}function ge(){return{endpointStore:new Zt,deliveryStore:new Tt}}function Ke(e){if(typeof e!=="string")return;let t=e.trim();return t.length>0?t:void 0}function Nt(e,t){let r=Fe(e);if(r==="plaintext"){if(!e.unsafeAllowPlaintextStorage)throw new v("policy","openFallback=plaintext requires unsafeAllowPlaintextStorage=true",{rule:"fieldCrypto.fail_open.plaintext_guard",path:"openFallback"},{fieldPath:"openFallback",failMode:"open",openFallback:"plaintext"});return t}if(r==="null")return"";return St()(t)}function Wt(e,t,r){if(e instanceof v){if(e.fieldPath)return e;return new v(e.kind,e.message,e.details,{providerErrorCode:e.providerErrorCode,providerErrorText:e.providerErrorText,httpStatus:e.httpStatus,requestId:e.requestId,retryAfterMs:e.retryAfterMs,attempt:e.attempt,openFallback:e.openFallback,fieldPath:t,failMode:"closed",causeChain:[e]})}return new v(r,`Field crypto ${r} failed for ${t}`,{cause:e instanceof Error?e.message:String(e)},{fieldPath:t,failMode:"closed",causeChain:[e]})}function He(e,t){return t?{...e,tenantId:t}:e}async function Ut(e,t){let r=Ke(t.value);if(!r)return;if(!e||e.enabled===!1)return r;let n=he(e),o=e.keyResolver;try{let i={tenantId:t.tenantId,tableName:t.aad.tableName,fieldPath:t.path,messageId:t.aad.messageId,providerId:t.aad.providerId},s=o?await o.resolveEncryptKey(i):void 0,a=Ke(s?.kid),l=await e.provider.encrypt({value:r,path:t.path,aad:He(t.aad,t.tenantId),...a?{kid:a}:{}});return zt(l.ciphertext)}catch(i){if(n==="closed")throw Wt(i,t.path,"encrypt");return Nt(e,r)}}async function Ye(e,t){let r=Ke(t.value);if(!r)return;if(!e||e.enabled===!1)return r;let n=he(e);try{let o={tenantId:t.tenantId,tableName:t.aad.tableName,fieldPath:t.path,messageId:t.aad.messageId,providerId:t.aad.providerId},i=e.keyResolver?.resolveDecryptKeys?await e.keyResolver.resolveDecryptKeys({...o,ciphertext:r}):void 0,s=(a)=>e.provider.decrypt({ciphertext:r,path:t.path,aad:a,...Array.isArray(i)&&i.length>0?{candidateKids:i}:{}});if(!t.tenantId)return await s(t.aad);if(!t.acceptLegacyAad)return await s(He(t.aad,t.tenantId));try{return await s(He(t.aad,t.tenantId))}catch(a){try{return await s(t.aad)}catch(l){throw AggregateError([a,l],"decrypt failed with both the tenant-bound and the legacy AAD")}}}catch(o){if(n==="closed")throw Wt(o,t.path,"decrypt");return Nt(e,r)}}var jn=["encrypt","encrypt+hash"];function Ot(e,t){if(e.enabled===!1)return;let r=e.fields[t];if(r!==void 0&&jn.includes(r))return;throw new v("config",r===void 0?`webhook storage always encrypts ${t}; set fields.${t} to "encrypt" or "encrypt+hash"`:`webhook storage always encrypts ${t}; fields.${t} must be "encrypt" or "encrypt+hash", not "${r}"`,{rule:"fieldCrypto.webhook.encrypt_only",path:`fields.${t}`},{fieldPath:`fields.${t}`})}function Xe(e){if(!e)return;if(e.endpoint)Ne(e.endpoint),Ot(e.endpoint,"secret");if(e.delivery)Ne(e.delivery),Ot(e.delivery,"payload")}function Je(e,t){if(t===void 0)return e;if(t)return{...e,secret:t};let r={...e};return delete r.secret,r}function Qe(e){return{tableName:"webhook_endpoint",messageId:e.id}}function et(e){return{tableName:"webhook_delivery",messageId:e.id,providerId:e.endpointId}}async function Ve(e,t){let r=await Ut(t?.endpoint,{value:e.secret,path:"secret",aad:Qe(e),tenantId:t?.tenantId});return Je(e,r)}async function Ge(e,t){let r=await Ye(t?.endpoint,{value:e.secret,path:"secret",aad:Qe(e),tenantId:t?.tenantId,acceptLegacyAad:t?.acceptLegacyAad});return Je(e,r)}async function qe(e,t){let r=await Ut(t?.delivery,{value:e.payload,path:"payload",aad:et(e),tenantId:t?.tenantId});return{...e,payload:r??e.payload}}async function Bt(e,t){let r=await Ye(t?.delivery,{value:e.payload,path:"payload",aad:et(e),tenantId:t?.tenantId,acceptLegacyAad:t?.acceptLegacyAad});return{...e,payload:r??e.payload}}function jt(e,t){if(!t?.endpoint)return e;return{async add(r){await e.add(await Ve(r,t))},async update(r,n){await e.update(r,await Ve(n,t))},async remove(r){await e.remove(r)},async get(r){let n=await e.get(r);if(!n)return null;return await Ge(n,t)},async list(){let r=await e.list();return await Promise.all(r.map((n)=>Ge(n,t)))}}}function Kt(e,t){if(!t?.delivery)return e;let r=e.replace?.bind(e);return{async add(n){await e.add(await qe(n,t))},async list(n){let o=await e.list(n);return await Promise.all(o.map((i)=>Bt(i,t)))},...r?{async replace(n){await r(await qe(n,t))}}:{}}}var Kn=200,Lt=3;function Ft(e){return e?{...e,failMode:"closed"}:void 0}async function Ht(e,t){try{return await Ye(e,t),!0}catch{return!1}}async function Vt(e,t,r,n){try{return await e()}catch(o){throw new v("decrypt",`Cannot migrate webhook ${t} ${r}: its ${n} could not be read with the tenant-bound or the legacy AAD (see causeChain)`,{recordId:r},{fieldPath:n,failMode:"closed",causeChain:[o]})}}async function Hn(e,t,r,n){let o={...n,acceptLegacyAad:!0};for(let i=1;;i+=1){let s=await e.get(t);if(!s)return!1;let a={value:s.secret,path:"secret",aad:Qe(s),tenantId:n.tenantId};if(await Ht(r,a))return!1;let l=await Vt(()=>Ge(s,o),"endpoint",t,"secret"),{secret:u}=await Ve(l,n),c=await e.get(t);if(!c)return!1;if(c.secret===s.secret)return await e.update(t,Je(c,u)),!0;if(i===Lt)throw new v("config",`Cannot migrate webhook endpoint ${t}: its secret changed during each of ${Lt} attempts; pause endpoint updates and run the migration again`,{rule:"fieldCrypto.webhook.tenant_migration",path:"secret"},{fieldPath:"secret"})}}async function ye(e,t){Xe(t);let r=t.tenantId;if(typeof r!=="string"||r.trim().length===0)throw new v("config","migrating webhook ciphertext to the tenant requires fieldCrypto.tenantId",{rule:"fieldCrypto.webhook.tenant_migration",path:"tenantId"},{fieldPath:"tenantId"});let n=e.deliveryStore,o=n.replace?.bind(n);if(t.delivery!==void 0&&t.delivery.enabled!==!1&&!o)throw new v("config","migrating webhook deliveries needs a delivery store with replace(); the built-in stores implement it",{rule:"fieldCrypto.webhook.tenant_migration",path:"deliveryStore"},{fieldPath:"deliveryStore"});let s={tenantId:r,endpoint:Ft(t.endpoint),delivery:Ft(t.delivery)},a={...s,acceptLegacyAad:!0},l={endpoints:0,deliveries:0},u=s.endpoint;if(u&&u.enabled!==!1){let p=e.endpointStore;for(let{id:d}of await p.list())if(await Hn(p,d,u,s))l.endpoints+=1}let c=s.delivery;if(o&&c&&c.enabled!==!1){let p;for(;;){let d=await n.list({limit:Kn,...p?{before:p}:{}}),h=d[0],f=d.at(-1);if(!h||!f)break;if(p&&!je(h,p))throw new v("config","migrating webhook deliveries needs a delivery store whose list() honors the `before` cursor; the built-in stores do",{rule:"fieldCrypto.webhook.tenant_migration",path:"deliveryStore"},{fieldPath:"deliveryStore"});for(let b of d){let k={value:b.payload,path:"payload",aad:et(b),tenantId:r};if(await Ht(c,k))continue;let g=await Vt(()=>Bt(b,a),"delivery",b.id,"payload");await o(await qe(g,s)),l.deliveries+=1}p={createdAt:f.createdAt,id:f.id}}}return l}class ee{config;constructor(e){this.config={maxRetries:e.maxRetries,baseDelayMs:e.retryDelayMs,maxDelayMs:e.maxDelayMs||300000,backoffMultiplier:e.backoffMultiplier||2,jitter:e.jitter!==!1}}calculateNextRetry(e){if(e>=this.config.maxRetries)throw Error(`Maximum retry attempts (${this.config.maxRetries}) exceeded`);let t=this.config.baseDelayMs*this.config.backoffMultiplier**e;if(t=Math.min(t,this.config.maxDelayMs),this.config.jitter)t=t*(0.5+Math.random()*0.5);return new Date(Date.now()+t)}shouldRetry(e,t){if(e>=this.config.maxRetries)return!1;if(t)return this.isRetryableError(t);return!0}isRetryableError(e){let t=e.message.toLowerCase();return["timeout","network","connection","econnreset","enotfound","econnrefused","socket hang up"].some((n)=>t.includes(n))}shouldRetryStatus(e){if(e>=400&&e<500)return[408,429].includes(e);if(e>=500)return!0;return!1}calculateRetryStats(e){if(e.length===0)return{totalAttempts:0,successfulAttempts:0,failedAttempts:0,averageDelayMs:0,totalTimeMs:0};let t=e.filter((s)=>s.success).length,r=e.length-t,n=0;for(let s=1;s<e.length;s++)n+=e[s].timestamp.getTime()-e[s-1].timestamp.getTime();let o=e.length>1?n/(e.length-1):0,i=e.length>0?e[e.length-1].timestamp.getTime()-e[0].timestamp.getTime():0;return{totalAttempts:e.length,successfulAttempts:t,failedAttempts:r,averageDelayMs:o,totalTimeMs:i}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}getBackoffDelay(e){let t=this.config.baseDelayMs*this.config.backoffMultiplier**e;return Math.min(t,this.config.maxDelayMs)}}var te={allowPrivateHosts:!1,allowHttpForLocalhost:!0};function Vn(e){let t=e.toLowerCase();if(t.startsWith("[")&&t.endsWith("]"))t=t.slice(1,-1);return t.replace(/\.+$/,"")}function tt(e){let t=e.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(!t)return null;let r=t.slice(1).map(Number);return r.every((n)=>n<=255)?r:null}function Gt(e){if(e.length===0)return[];let t=[];for(let r of e.split(":"))if(r.includes(".")){let n=tt(r);if(!n)return null;t.push(n[0]<<8|n[1],n[2]<<8|n[3])}else if(/^[0-9a-f]{1,4}$/.test(r))t.push(Number.parseInt(r,16));else return null;return t}function qt(e){if(!e.includes(":"))return null;let t=e.split("::");if(t.length>2)return null;let r=Gt(t[0]??""),n=t.length===2?Gt(t[1]??""):[];if(!r||!n)return null;if(t.length===1)return r.length===8?r:null;let o=8-r.length-n.length;if(o<1)return null;return[...r,...Array(o).fill(0),...n]}function be(e){let[t=0,r=0,n=0]=e;return t===0||t===10||t===100&&r>=64&&r<=127||t===127||t===169&&r===254||t===172&&r>=16&&r<=31||t===192&&r===0&&n===0||t===192&&r===168||t===198&&(r===18||r===19)||t>=224}function xe(e){let t=e[6]??0,r=e[7]??0;return[t>>8,t&255,r>>8,r&255]}function Gn(e){let[t=0,r=0]=e,n=(o)=>e.slice(0,o).every((i)=>i===0);if(n(6))return e[6]===0&&(e[7]??0)<=1||be(xe(e));if(n(5)&&e[5]===65535)return be(xe(e));if(t===100&&r===65435&&e.slice(2,6).every((o)=>o===0))return be(xe(e));return(t&65024)===64512||(t&65472)===65152||(t&65472)===65216||(t&65280)===65280}function Yt(e){return e==="localhost"||e.endsWith(".localhost")}function qn(e){if(Yt(e))return!0;let t=tt(e);if(t)return t[0]===127;let r=qt(e);if(!r)return!1;if(r.slice(0,7).every((n)=>n===0)&&r[7]===1)return!0;return r.slice(0,5).every((n)=>n===0)&&r[5]===65535&&xe(r)[0]===127}function Yn(e){if(Yt(e))return!0;if(e.includes("%"))return!0;let t=tt(e);if(t)return be(t);let r=qt(e);if(r)return Gn(r);return e.endsWith(".local")||e.endsWith(".internal")}function re(e){return{allowPrivateHosts:e?.allowPrivateHosts??te.allowPrivateHosts,allowHttpForLocalhost:e?.allowHttpForLocalhost??te.allowHttpForLocalhost}}function N(e,t=te){let r;try{r=new URL(e)}catch{throw Error("Invalid webhook URL")}let n=Vn(r.hostname),o=qn(n);if(r.protocol!=="https:"){if(!(t.allowHttpForLocalhost&&o&&r.protocol==="http:"))throw Error("Webhook URL must use HTTPS")}if(!t.allowPrivateHosts&&Yn(n))throw Error("Private hosts are not allowed for webhook endpoints");return r}function rt(e,t){if(!e||e.length===0)return!0;if(!t)return!1;return e.includes(t)}function _e(e,t){if(!e.active||e.status!=="active")return!1;if(!e.events.includes(t.type))return!1;let r=e.filters;if(!r)return!0;if(!rt(r.providerId,t.metadata.providerId))return!1;if(!rt(r.channelId,t.metadata.channelId))return!1;if(!rt(r.templateId,t.metadata.templateId))return!1;return!0}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Xn(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Xt(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function W(e,...t){if(!Xn(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function Jt(e){if(typeof e!=="function"||typeof e.create!=="function")throw Error("Hash should be wrapped by utils.createHasher");Xt(e.outputLen),Xt(e.blockLen)}function q(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Qt(e,t){W(e);let r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}function P(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ve(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function A(e,t){return e<<32-t|e>>>t}function we(e,t){return e<<t|e>>>32-t>>>0}var Jn=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),Qn=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function nt(e){if(W(e),Jn)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Qn[e[r]];return t}function eo(e){if(typeof e!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function ne(e){if(typeof e==="string")e=eo(e);return W(e),e}class oe{}function Ee(e){let t=(n)=>e().update(ne(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}class ot extends oe{constructor(e,t){super();this.finished=!1,this.destroyed=!1,Jt(e);let r=ne(t);if(this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),P(o)}update(e){return q(this),this.iHash.update(e),this}digestInto(e){q(this),W(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:r,finished:n,destroyed:o,blockLen:i,outputLen:s}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var ke=(e,t,r)=>new ot(e,t).update(r).digest();ke.create=(e,t)=>new ot(e,t);function to(e,t,r,n){if(typeof e.setBigUint64==="function")return e.setBigUint64(t,r,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),a=Number(r&i),l=n?4:0,u=n?0:4;e.setUint32(t+l,s,n),e.setUint32(t+u,a,n)}function Ce(e,t,r){return e&t^~e&r}function $e(e,t,r){return e&t^e&r^t&r}class ie extends oe{constructor(e,t,r,n){super();this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=ve(this.buffer)}update(e){q(this),e=ne(e),W(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let s=Math.min(n-this.pos,o-i);if(s===n){let a=ve(e);for(;n<=o-i;i+=n)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){q(this),Qt(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;if(t[i++]=128,P(this.buffer.subarray(i)),this.padOffset>n-i)this.process(r,0),i=0;for(let c=i;c<n;c++)t[c]=0;to(r,n-8,BigInt(this.length*8),o),this.process(r,0);let s=ve(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen should be aligned to 32bit");let l=a/4,u=this.get();if(l>u.length)throw Error("_sha2: outputLen bigger than state");for(let c=0;c<l;c++)s.setUint32(4*c,u[c],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:r,length:n,finished:o,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=o,e.length=n,e.pos=s,n%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var S=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var se=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),M=new Uint32Array(80);class it extends ie{constructor(){super(64,20,8,!1);this.A=se[0]|0,this.B=se[1]|0,this.C=se[2]|0,this.D=se[3]|0,this.E=se[4]|0}get(){let{A:e,B:t,C:r,D:n,E:o}=this;return[e,t,r,n,o]}set(e,t,r,n,o){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0}process(e,t){for(let a=0;a<16;a++,t+=4)M[a]=e.getUint32(t,!1);for(let a=16;a<80;a++)M[a]=we(M[a-3]^M[a-8]^M[a-14]^M[a-16],1);let{A:r,B:n,C:o,D:i,E:s}=this;for(let a=0;a<80;a++){let l,u;if(a<20)l=Ce(n,o,i),u=1518500249;else if(a<40)l=n^o^i,u=1859775393;else if(a<60)l=$e(n,o,i),u=2400959708;else l=n^o^i,u=3395469782;let c=we(r,5)+l+s+u+M[a]|0;s=i,i=o,o=we(n,30),n=r,r=c}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,this.set(r,n,o,i,s)}roundClean(){P(M)}destroy(){this.set(0,0,0,0,0),P(this.buffer)}}var er=Ee(()=>new it);var tr=er;var ro=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),I=new Uint32Array(64);class rr extends ie{constructor(e=32){super(64,e,8,!1);this.A=S[0]|0,this.B=S[1]|0,this.C=S[2]|0,this.D=S[3]|0,this.E=S[4]|0,this.F=S[5]|0,this.G=S[6]|0,this.H=S[7]|0}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:s,H:a}=this;return[e,t,r,n,o,i,s,a]}set(e,t,r,n,o,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=s|0,this.H=a|0}process(e,t){for(let c=0;c<16;c++,t+=4)I[c]=e.getUint32(t,!1);for(let c=16;c<64;c++){let p=I[c-15],d=I[c-2],h=A(p,7)^A(p,18)^p>>>3,f=A(d,17)^A(d,19)^d>>>10;I[c]=f+I[c-7]+h+I[c-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:l,H:u}=this;for(let c=0;c<64;c++){let p=A(s,6)^A(s,11)^A(s,25),d=u+p+Ce(s,a,l)+ro[c]+I[c]|0,f=(A(r,2)^A(r,13)^A(r,22))+$e(r,n,o)|0;u=l,l=a,a=s,s=i+d|0,i=o,o=n,n=r,r=d+f|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,n,o,i,s,a,l,u)}roundClean(){P(I)}destroy(){this.set(0,0,0,0,0,0,0,0),P(this.buffer)}}var nr=Ee(()=>new rr);class ae{config;encoder=new TextEncoder;constructor(e){this.config={algorithm:e.algorithm||"sha256",header:e.signatureHeader||"X-Webhook-Signature",prefix:e.signaturePrefix||"sha256="}}createSignedPayload(e,t){return`${t}.${e}`}generateSignature(e,t){let r=this.generateSignatureDigest(e,t);return this.config.prefix?`${this.config.prefix}${r}`:r}generateSignatureWithTimestamp(e,t,r){return this.generateSignature(this.createSignedPayload(e,t),r)}verifySignature(e,t,r){try{let n=this.generateSignature(e,r);return this.constantTimeCompare(t,n)}catch(n){return Q.error("Signature verification failed",void 0,n instanceof Error?n:Error(String(n))),!1}}verifySignatureWithTimestamp(e,t,r,n){return this.verifySignature(this.createSignedPayload(e,t),r,n)}extractSignature(e){let t=this.config.header.toLowerCase();for(let[r,n]of Object.entries(e))if(r.toLowerCase()===t)return n;return null}createSecurityHeaders(e,t){let r=Math.floor(Date.now()/1000).toString(),n=this.generateSignatureWithTimestamp(e,r,t);return{[this.config.header]:n,"X-Webhook-Timestamp":r,"X-Webhook-ID":this.generateWebhookId(),"User-Agent":"K-Message-Webhook/1.0"}}verifyTimestamp(e,t=300){try{let r=(()=>{if(/^[0-9]+$/.test(e.trim()))return parseInt(e,10);let i=new Date(e);if(Number.isNaN(i.getTime()))return NaN;return Math.floor(i.getTime()/1000)})(),n=Math.floor(Date.now()/1000);return Math.abs(n-r)<=t}catch{return!1}}generateWebhookId(){let e=new Uint8Array(16);if(globalThis.crypto?.getRandomValues)globalThis.crypto.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return`wh_${nt(e)}`}generateSignatureDigest(e,t){let r=this.encoder.encode(t),n=this.encoder.encode(e),o=this.config.algorithm==="sha1"?ke(tr,r,n):ke(nr,r,n);return nt(o)}constantTimeCompare(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}}class Ae{async fetch(e,t){return fetch(e,t)}}class no{responses=new Map;defaultResponse=new Response(JSON.stringify({status:"ok"}),{status:200,statusText:"OK",headers:{"content-type":"application/json"}});setMockResponse(e,t){this.responses.set(e,t)}setDefaultResponse(e){this.defaultResponse=e}async fetch(e,t){let r=this.responses.get(e);if(r)return r;return this.defaultResponse}}class ce{config;httpClient;securityManager;retryManager;constructor(e,t){this.config=e,this.httpClient=t||new Ae,this.securityManager=new ae(e),this.retryManager=new ee(e)}async dispatch(e,t){let r=JSON.stringify(e),n=(()=>{if(e.timestamp instanceof Date)return e.timestamp;let s=new Date(e.timestamp);return Number.isNaN(s.getTime())?new Date:s})(),o=Math.floor(n.getTime()/1000).toString(),i={id:this.generateDeliveryId(),endpointId:t.id,eventId:e.id,eventType:e.type,url:t.url,httpMethod:"POST",headers:this.buildHeaders(t,e,r,o),payload:r,attempts:[],status:"pending",createdAt:new Date};return await this.executeDelivery(i,t),i}async executeDelivery(e,t){let r=t.retryConfig?.maxRetries??this.config.maxRetries;for(let n=1;n<=r+1;n++){let o=await this.makeHttpRequest(e,t,n);if(e.attempts.push(o),o.httpStatus&&o.httpStatus>=200&&o.httpStatus<300){e.status="success",e.completedAt=new Date;return}if(!(n<=r&&this.shouldRetryAttempt(o))){e.status="failed",e.completedAt=new Date;return}let s=this.calculateRetryDelay(n,t);e.nextRetryAt=new Date(Date.now()+s),await this.sleep(s)}e.status="exhausted",e.completedAt=new Date}shouldRetryAttempt(e){if(typeof e.httpStatus==="number")return this.retryManager.shouldRetryStatus(e.httpStatus);if(e.error)return this.retryManager.isRetryableError(Error(e.error));return!0}async makeHttpRequest(e,t,r){let n=Date.now(),o={attemptNumber:r,timestamp:new Date,latencyMs:0};try{let i=await this.httpClient.fetch(e.url,{method:e.httpMethod,headers:e.headers,body:e.payload,redirect:"manual",signal:AbortSignal.timeout(this.config.timeoutMs)});o.httpStatus=i.status,o.responseBody=await i.text();let s={};if(i.headers.forEach((a,l)=>{s[l]=a}),o.responseHeaders=s,o.latencyMs=Date.now()-n,!i.ok)o.error=`HTTP ${i.status}: ${i.statusText}`}catch(i){o.latencyMs=Date.now()-n,o.error=i instanceof Error?i.message:"Unknown error"}return o}buildHeaders(e,t,r,n){let o={"Content-Type":"application/json","X-Webhook-ID":t.id,"X-Webhook-Event":t.type,"X-Webhook-Timestamp":n,"User-Agent":"K-Message-Webhook/1.0"};if(e.headers)Object.assign(o,e.headers);if(this.config.enableSecurity){let i=(typeof e.secret==="string"&&e.secret.length>0?e.secret:typeof this.config.secretKey==="string"&&this.config.secretKey.length>0?this.config.secretKey:void 0)||void 0;if(i){let s=this.securityManager.generateSignatureWithTimestamp(r,n,i),a=this.securityManager.getConfig().header;o[a]=s}}return o}calculateRetryDelay(e,t){let r=t.retryConfig?.retryDelayMs||this.config.retryDelayMs,n=t.retryConfig?.backoffMultiplier||this.config.backoffMultiplier||2,o=r*n**e;if(typeof this.config.maxDelayMs==="number")o=Math.min(o,this.config.maxDelayMs);if(this.config.jitter!==!1)o=o*(0.5+Math.random()*0.5);return Math.max(0,Math.floor(o))}sleep(e){return new Promise((t)=>setTimeout(t,e))}generateDeliveryId(){return`delivery_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}async shutdown(){}}function at(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function or(e,t){if(typeof t==="bigint")return t.toString();return t}class ir{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function sr(e){return new ir(e)}function ar(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function cr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}var ct="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Pe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function ur(e){if(Pe(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(Pe(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}var lr=new Set(["string","number","symbol"]);function dr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Re(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function w(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function pr(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}function Z(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function fr(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function B(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function ue(e){return typeof e==="string"?e:e?.message}function ut(e,t,r){var n;for(let o=t;o<e.length;o++)(n=e[o]).schema??(n.schema=r)}function T(e,t,r){var n;let o=e.inst?._zod?.traits;if(o?.has("$ZodType"))if(o.has("$ZodCheck"))(n=e).schema??(n.schema=e.inst);else e.schema=e.inst;let i=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,s=e.message?e.message:ue(e.inst?._zod.def?.error?.(e))??ue(i?.(e))??ue(t?.error?.(e))??ue(r.customError?.(e))??ue(r.localeError?.(e))??"Invalid input",a={};for(let l of Object.keys(e)){if(l==="inst"||l==="schema"||l==="continue"||l==="input"||l==="__proto__")continue;a[l]=e[l]}if(a.path??(a.path=[]),a.message=s,t?.reportInput)a.input=e.input;return a}function hr(e,t){for(let r in t){let n=Object.getOwnPropertyDescriptor(t,r);if(n.get)Object.defineProperty(e,r,{...n,enumerable:!1});else oo(e,r,n.value)}}function U(e,t,r,n=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:n,value:r}),r}function mr(e,t,r){return U(e,t,r,!1)}function oo(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:U(this,t,r.bind(this))},set(n){U(this,t,n)}})}function io(e,t){let r=Object.getPrototypeOf(e);return t in r?void 0:r}var st,D=!1,so={configurable:!0,get(){D=!0;return}};function R(e,t,r){let n=Object.getPrototypeOf(e._zod);if(t in n&&st!==e._zod){st=void 0;return}st=e._zod,Object.defineProperty(n,t,{configurable:!0,get(){Object.defineProperty(this,t,so);let o=D;D=!1;try{let i=r(this);if(D)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i});return D=D||o,i}catch(i){throw delete this[t],D=D||o,i}},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o})}})}function gr(e,t,r,n){let o=io(e,t);if(!o)return;Object.defineProperty(o,t,{configurable:!0,get(){let i={configurable:!0,writable:!0,enumerable:n,value:void 0};return Object.defineProperty(this,t,i),i.value=r(this),Object.defineProperty(this,t,i),i.value},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:n,value:i})}})}var yr;var lt={value:void 0,enumerable:!1},br="captureStackTrace"in Error?Error:null;function ao(e){let t=br;if(t){let r=t.stackTraceLimit;if(typeof r==="number"){try{t.stackTraceLimit=0}catch{return br=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}function m(e,t,r,n){let o={};function i(d){this.def=d,this.constr=p,this.traits=new Set}i.prototype=o;let s=r,a=s&&new WeakSet;function l(d,h){if(!d._zod){lt.value=new i(h);try{Object.defineProperty(d,"_zod",lt)}finally{lt.value=void 0}}else if(d._zod.traits.has(e))return;if(d._zod.traits.add(e),t(d,h),a){let b=Object.getPrototypeOf(d),k=d._zod.constr.prototype,g=b;while(g&&g!==k)g=Object.getPrototypeOf(g);let G=g??b;if(!a.has(G))a.add(G),hr(G,s)}let f=p.prototype;for(let b in f){if(!Object.prototype.hasOwnProperty.call(f,b))continue;if(!(b in d))d[b]=f[b].bind(d)}}let u=n?.Parent??Object;class c extends u{}Object.defineProperty(c,"name",{value:e});function p(d){let h=n?.Parent?ao(c):this;l(h,d);let f=h._zod.deferred;if(f){for(let k of f)k();h._zod.deferred=void 0}let b=globalThis.__zod_globalConfig?.postProcessor;if(b)b(h);return h}return Object.defineProperty(p,"init",{value:l}),Object.defineProperty(p,Symbol.hasInstance,{value:(d)=>{if(n?.Parent&&d instanceof n.Parent)return!0;return d?._zod?.traits?.has(e)}}),Object.defineProperty(p,"name",{value:e}),p}class z extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class dt extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(yr=globalThis).__zod_globalConfig??(yr.__zod_globalConfig={});var j=globalThis.__zod_globalConfig;function O(e){if(e)Object.assign(j,e);return j}function co(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,or,2)),e.message}function uo(e){this._zod.message=e}var lo={get:co,set:uo,enumerable:!0,configurable:!0},ft={value:void 0,enumerable:!1},xr=new WeakSet([Object.prototype,Error.prototype]),_r=(e,t)=>{e.name="$ZodError",ft.value=t,Object.defineProperty(e,"issues",ft),ft.value=void 0,Object.defineProperty(e,"message",lo);let r=Object.getPrototypeOf(e);if(!xr.has(r))xr.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){let n=()=>this.message;return Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0})}})},Ui=m("$ZodError",_r),le=m("$ZodError",_r,void 0,{Parent:Error});var fo=(e)=>{let t=(r,n,o,i)=>{let s=o?{...o,async:!1}:{async:!1},a=r._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new z;if(a.issues.length){let l=new(i?.Err??e)(a.issues.map((u)=>T(u,s,O())));throw ct(l,i?.callee??t),l}return a.value};return t},ht=fo(le),ho=(e)=>{let t=async(r,n,o,i)=>{let s=o?{...o,async:!0}:{async:!0},a=r._zod.run({value:n,issues:[]},s);if(a instanceof Promise)a=await a;if(a.issues.length){let l=new(i?.Err??e)(a.issues.map((u)=>T(u,s,O())));throw ct(l,i?.callee??t),l}return a.value};return t},mt=ho(le),mo=(e)=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new z;return i.issues.length?vr(e,i.issues,o):{success:!0,data:i.value}},gt=mo(le);function vr(e,t,r){let n;return{success:!1,get error(){if(!n)n=new e(t.map((o)=>T(o,r,O()))),t=void 0,r=void 0;return n},set error(o){n=o,t=void 0,r=void 0}}}var go=(e)=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)i=await i;return i.issues.length?vr(e,i.issues,o):{success:!0,data:i.value}},yt=go(le);var wr=/^https?$/;var Er=/^[\s\S]{0,}$/;var bt=/^-?\d+(?:\.\d+)?$/,kr=/^(?:true|false)$/i;var X=m("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])});var Se={number:"number",bigint:"bigint",object:"date"},$r=m("$ZodCheckLessThan",(e,t)=>{X.init(e,t);let r=Se[typeof t.value];e._zod.check=(n)=>{if(t.inclusive?n.value<=t.value:n.value<t.value)return;n.issues.push({origin:Se[typeof n.value]??r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ar=m("$ZodCheckGreaterThan",(e,t)=>{X.init(e,t);let r=Se[typeof t.value];e._zod.check=(n)=>{if(t.inclusive?n.value>=t.value:n.value>t.value)return;n.issues.push({origin:Se[typeof n.value]??r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}});var Pr=m("$ZodCheckStringFormat",(e,t)=>{var r,n;if(X.init(e,t),t.pattern)(r=e._zod).check??(r.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(n=e._zod).check??(n.check=()=>{})});var Sr={major:4,minor:6,patch:5};var E=m("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Sr;let n=e._zod.def.checks,o=e._zod.traits.has("$ZodCheck")?[e,...n??[]]:n?.length?[...n]:[];for(let i of o)for(let s of i._zod.onattach)s(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(a,l,u)=>{if(a.memo)return a;let c=Z(a),p;for(let d of l){if(d._zod.def.when){if(fr(a))continue;if(!d._zod.def.when(a))continue}else if(c)continue;let h=a.issues.length,f=d._zod.check(a);if(f instanceof Promise&&u?.async===!1)throw new z;if(p||f instanceof Promise)p=(p??Promise.resolve()).then(async()=>{if(await f,a.issues.length===h)return;if(ut(a.issues,h,e),!c)c=Z(a,h)});else{if(a.issues.length===h)continue;if(ut(a.issues,h,e),!c)c=Z(a,h)}}if(p)return p.then(()=>a);return a},s=(a,l,u)=>{if(Z(a))return a.aborted=!0,a;let c=i(l,o,u);if(c instanceof Promise){if(u.async===!1)throw new z;return c.then((p)=>e._zod.parse(p,u))}return e._zod.parse(c,u)};e._zod.run=(a,l)=>{if(l.skipChecks)return e._zod.parse(a,l);if(l.direction==="backward"){let c=e._zod.parse({value:a.value,issues:[]},{...l,skipChecks:!0});if(c instanceof Promise)return c.then((p)=>s(p,a,l));return s(c,a,l)}let u=e._zod.parse(a,l);if(u instanceof Promise){if(l.async===!1)throw new z;return u.then((c)=>i(c,o,l))}return i(u,o,l)}}},{get "~standard"(){return mr(this,"~standard",xo(this))},set "~standard"(e){U(this,"~standard",e)}}),Dr=(e,t)=>e.issues.length?{issues:e.issues.map((r)=>T(r,t,O()))}:{value:e.value};async function bo(e,t){let r={async:!0};return Dr(await e._zod.run({value:t,issues:[]},r),r)}function xo(e){return{validate:(t)=>{let r={async:!1};try{let n=e._zod.run({value:t,issues:[]},r);if(!(n instanceof Promise))return Dr(n,r)}catch(n){}return bo(e,t)},vendor:"zod",version:1}}var xt=m("$ZodString",(e,t)=>{E.init(e,t),e._zod.pattern=t.pattern??Er,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(o){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),_t=m("$ZodStringFormat",(e,t)=>{Pr.init(e,t),xt.init(e,t)});var Zr=1,Me=2;function _o(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function vo(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return _o(e)||Me;return wo(e,t)}function wo(e,t){if(!t.normalize&&t.protocol?.source===wr.source&&!/^https?:\/\//i.test(e))return Zr;try{if(typeof URL<"u"){let r=URL;if(typeof r.parse==="function")return r.parse(e)??Me}return new URL(e)}catch{return Me}}var Eo=/[\t\n\r]/g;function zr(e){return e.replace(Eo,"")}function ko(e,t){return t.lastIndex=0,t.test(e.hostname)}function Co(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var Tr=m("$ZodURL",(e,t)=>{_t.init(e,t),e._zod.check=(r)=>{try{let n=r.value.trim(),o=vo(n,t);if(o===Zr){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}if(o===Me){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort});return}if(o===!0){r.value=zr(n);return}if(t.hostname&&!ko(o,t.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort});if(t.protocol&&!Co(o,t.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort});r.value=t.normalize?o.href:zr(n);return}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}});var Or=m("$ZodNumber",(e,t)=>{E.init(e,t),e._zod.pattern=bt,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(s){}let o=r.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o==="number"?Number.isNaN(o)?"NaN":!Number.isFinite(o)?String(o):void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),r}});var Lr=m("$ZodBoolean",(e,t)=>{E.init(e,t),e._zod.pattern=kr,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(i){}let o=r.value;if(typeof o==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}});var Fr=m("$ZodAny",(e,t)=>{E.init(e,t),e._zod.parse=(r)=>r});var Nr=m("$ZodDate",(e,t)=>{E.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch(a){}let o=r.value,i=o instanceof Date;if(i&&!Number.isNaN(o.getTime()))return r;return r.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:e}),r}});function Mr(e,t,r){if(e.issues.length)t.issues.push(...B(r,e.issues));t.value[r]=e.value}var Wr=m("$ZodArray",(e,t)=>{E.init(e,t);let r=j.memoizer;r?.attach(e),e._zod.parse=(n,o)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=r?r.alloc(e,n,Array(i.length),o):Array(i.length);let s=[],a=o?.abortEarly;for(let l=0;l<i.length;l++){let u=i[l],c=t.element._zod.run({value:u,issues:[]},o);if(c instanceof Promise)s.push(c.then((p)=>Mr(p,n,l)));else if(Mr(c,n,l),a&&c.issues.length!==0&&Z(c))break}if(s.length)return Promise.all(s).then(()=>n);return n}});function Ie(e,t,r,n,o,i){let s=r in n,a=i==="optional";if(!s&&a&&o==="optional")return;if(e.issues.length){if(o!==void 0&&a&&!s)return;t.issues.push(...B(r,e.issues))}if(!s&&o===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(s||o==="defaulted"&&!a)t.value[r]=void 0}else t.value[r]=e.value}var $o=[];function Ao(e){let t=Object.keys(e.shape),r=Object.getOwnPropertySymbols(e.shape),n=r.length?r:$o,o=n.length?[...t,...n]:t;for(let s of o)if(!e.shape?.[s]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(s)}": expected a Zod schema`);let i=pr(e.shape);return{...e,allKeys:o,symbolKeys:n,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(i)}}function Po(e,t,r,n,o,i,s){let a=[],l=o.keySet,u=o.catchall._zod,c=u.def.type,{optin:p,optout:d}=u,h=0;for(let f in t){if(s&&r.issues.length!==h){if(Z(r,h))break;h=r.issues.length}if(l.has(f))continue;if(f==="__proto__"){if(c==="never")a.push(f);continue}if(c==="never"){a.push(f);continue}let b=u.run({value:t[f],issues:[]},n);if(b instanceof Promise)e.push(b.then((k)=>Ie(k,r,f,t,p,d)));else Ie(b,r,f,t,p,d)}if(a.length)r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i,continue:!0});if(!e.length)return r;return Promise.all(e).then(()=>r)}var Ur=m("$ZodObject",(e,t)=>{E.init(e,t);let r=Object.getOwnPropertyDescriptor(t,"shape"),n=r?.get?r.get.raw:t.shape??{};if(n){let u=()=>{let c={...n};return Object.defineProperty(t,"shape",{value:c}),u.raw=c,c};u.raw=n,Object.defineProperty(t,"shape",{get:u})}let o=sr(()=>Ao(t));R(e,"propValues",(u)=>{let c=u.def.shape,p={};for(let d in c){let h=c[d]._zod;if(h.values){if(!Object.prototype.hasOwnProperty.call(p,d))cr(p,d,new Set);for(let f of h.values)p[d].add(f);if(h.optin!==void 0)p[d].add(void 0)}}return p});let i=Pe,s=t.catchall,a,l=j.memoizer;l?.attach(e),e._zod.parse=(u,c)=>{a??(a=o.value);let p=u.value;if(!i(p))return u.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),u;u.value=l?l.alloc(e,u,{},c):{};let d=[],h=a.shape,f=c?.abortEarly,b=u.issues.length;for(let k of a.allKeys){if(f&&u.issues.length!==b){if(Z(u,b))break;b=u.issues.length}if(k==="__proto__")continue;let g=h[k],G=g._zod.optin,Ct=g._zod.optout,_=g._zod.run({value:p[k],issues:[]},c);if(_ instanceof Promise)d.push(_.then((mn)=>Ie(mn,u,k,p,G,Ct)));else Ie(_,u,k,p,G,Ct)}if(!s)return d.length?Promise.all(d).then(()=>u):u;return Po(d,p,u,c,o.value,e,f===!0)}});var Br=m("$ZodRecord",(e,t)=>{E.init(e,t);let r=j.memoizer;r?.attach(e),e._zod.parse=(n,o)=>{let i=n.value;if(!ur(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;let s=[],a=t.keyType._zod.values;if(a&&!t.partial){n.value=r?r.alloc(e,n,{},o):{};let l=new Set;for(let c of a)if(typeof c==="string"||typeof c==="number"||typeof c==="symbol"){if(l.add(typeof c==="number"?c.toString():c),c==="__proto__")continue;let p=t.keyType._zod.run({value:c,issues:[]},o);if(p instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(p.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map((f)=>T(f,o,O())),input:c,path:[c],inst:e});continue}let d=p.value;if(d==="__proto__")continue;let h=t.valueType._zod.run({value:i[c],issues:[]},o);if(h instanceof Promise)s.push(h.then((f)=>{if(f.issues.length)n.issues.push(...B(c,f.issues));n.value[d]=f.value}));else{if(h.issues.length)n.issues.push(...B(c,h.issues));n.value[d]=h.value}}let u;for(let c in i)if(!l.has(c))if(t.mode==="loose"){if(c==="__proto__")continue;n.value[c]=i[c]}else u=u??[],u.push(c);if(u&&u.length>0)n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:u,continue:!0})}else{n.value=r?r.alloc(e,n,{},o):{};let l;for(let u of Reflect.ownKeys(i)){if(u==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(i,u))continue;let c=t.keyType._zod.run({value:u,issues:[]},o);if(c instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof u==="string"&&bt.test(u)&&c.issues.length){let f=t.keyType._zod.run({value:Number(u),issues:[]},o);if(f instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(f.issues.length===0)c=f}if(c.issues.length){if(t.mode==="loose")n.value[u]=i[u];else if(a)l=l??[],l.push(u);else n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map((f)=>T(f,o,O())),input:u,path:[u],inst:e});continue}let d=c.value;if(d==="__proto__")continue;let h=t.valueType._zod.run({value:i[u],issues:[]},o);if(h instanceof Promise)s.push(h.then((f)=>{if(f.issues.length)n.issues.push(...B(u,f.issues));n.value[d]=f.value}));else{if(h.issues.length)n.issues.push(...B(u,h.issues));n.value[d]=h.value}}if(l&&l.length>0)n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:l,continue:!0})}if(s.length)return Promise.all(s).then(()=>n);return n}});var jr=m("$ZodEnum",(e,t)=>{E.init(e,t);let r=at(t.entries),n=new Set(r);e._zod.values=n,R(e,"pattern",(o)=>{let i=at(o.def.entries).filter((s)=>lr.has(typeof s));return new RegExp(i.length?`^(${i.map((s)=>dr(s.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,i)=>{let s=o.value;if(n.has(s))return o;return o.issues.push({code:"invalid_value",values:r,input:s,inst:e}),o}});var Kr=m("$ZodTransform",(e,t)=>{E.init(e,t),e._zod.optin="optional",j.memoizer?.guard(e),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new dt(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then((s)=>(r.value=s,r));if(o instanceof Promise)throw new z;return r.value=o,r}});function Ir(e,t){return e.value=t.issues.length?void 0:t.value,e}var Hr=m("$ZodOptional",(e,t)=>{E.init(e,t),R(e,"optin",(r)=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",R(e,"values",(r)=>{let n=r.def.innerType._zod.values;return n?new Set([...n,void 0]):void 0}),R(e,"pattern",(r)=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${ar(n.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(r.value===void 0){if(t.innerType._zod.optin!=="defaulted")return r;let o=t.innerType._zod.run({value:r.value,issues:[]},n);if(o instanceof Promise)return o.then((i)=>Ir(r,i));return Ir(r,o)}return t.innerType._zod.run(r,n)}});var Vr=m("$ZodPipe",(e,t)=>{E.init(e,t),R(e,"values",(r)=>r.def.in._zod.values),R(e,"optin",(r)=>r.def.in._zod.optin),R(e,"optout",(r)=>r.def.out._zod.optout),R(e,"propValues",(r)=>r.def.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let i=t.out._zod.run(r,n);if(i instanceof Promise)return i.then((s)=>ze(s,t.in,n));return ze(i,t.in,n)}let o=t.in._zod.run(r,n);if(o instanceof Promise)return o.then((i)=>ze(i,t.out,n));return ze(o,t.out,n)}});function ze(e,t,r){if(e.issues.some((n)=>n.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},r)}function Gr(e){if(e.checks)e.checks=[...e.checks];return e}function qr(e,t){return new e(Gr({type:"string",...w(t)}))}function Yr(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...w(t)})}function Xr(e,t){return new e(Gr({type:"number",checks:[],...w(t)}))}function Jr(e,t){return new e({type:"boolean",...w(t)})}function Qr(e){return new e({type:"any"})}function en(e,t){return new e({type:"date",...w(t)})}function De(e,t){return new $r({check:"less_than",...w(t),value:e,inclusive:!0})}function de(e,t){return new Ar({check:"greater_than",...w(t),value:e,inclusive:!0})}var C=m("ZodMiniType",(e,t)=>{if(!e._zod)throw Error("Uninitialized schema in ZodMiniType.");E.init(e,t),e.def=t,e.type=t.type},{get with(){return this.check},set with(e){U(this,"with",e)},parse(e,t){return ht(this,e,t,{callee:this.parse})},parseAsync(e,t){return mt(this,e,t,{callee:this.parseAsync})},safeParse(e,t){return gt(this,e,t)},safeParseAsync(e,t){return yt(this,e,t)},check(...e){let t=this.def;return this.clone({...t,checks:[...t.checks??[],...e.map((r)=>typeof r==="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]},{parent:!0})},clone(e,t){return Re(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},apply(e,...t){return t.length===0?e(this):e(this,...t)}}),rn=m("ZodMiniString",(e,t)=>{xt.init(e,t),C.init(e,t)});function y(e){return qr(rn,e)}var zo=m("ZodMiniStringFormat",(e,t)=>{_t.init(e,t),rn.init(e,t)});var Mo=m("ZodMiniURL",(e,t)=>{Tr.init(e,t),zo.init(e,t)});function nn(e){return Yr(Mo,e)}var Io=m("ZodMiniNumber",(e,t)=>{Or.init(e,t),C.init(e,t)});function K(e){return Xr(Io,e)}var Do=m("ZodMiniBoolean",(e,t)=>{Lr.init(e,t),C.init(e,t)});function Zo(e){return Jr(Do,e)}var To=m("ZodMiniAny",(e,t)=>{Fr.init(e,t),C.init(e,t)});function Oo(){return Qr(To)}var Lo=m("ZodMiniDate",(e,t)=>{Nr.init(e,t),C.init(e,t)});function L(e){return en(Lo,e)}var Fo=m("ZodMiniArray",(e,t)=>{Wr.init(e,t),C.init(e,t)});function pe(e,t){return new Fo({type:"array",element:e,...w(t)})}var No=m("ZodMiniObject",(e,t)=>{Ur.init(e,t),C.init(e,t),gr(e,"shape",(r)=>r._zod.def.shape,!1)});function H(e,t){let r={type:"object",shape:e??{},...w(t)};return new No(r)}var tn=m("ZodMiniRecord",(e,t)=>{Br.init(e,t),C.init(e,t)});function vt(e,t,r){if(!t||!t._zod)return new tn({type:"record",keyType:y(),valueType:e,...w(t)});return new tn({type:"record",keyType:e,valueType:t,...w(r)})}var on=m("ZodMiniEnum",(e,t)=>{jr.init(e,t),C.init(e,t),e.options=[...e._zod.values]});function wt(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new on({type:"enum",entries:r,...w(t)})}function Et(e,t){return new on({type:"enum",entries:e,...w(t)})}var Wo=m("ZodMiniTransform",(e,t)=>{Kr.init(e,t),C.init(e,t)});function Uo(e){return new Wo({type:"transform",transform:e})}var Bo=m("ZodMiniOptional",(e,t)=>{Hr.init(e,t),C.init(e,t)});function x(e){return new Bo({type:"optional",innerType:e})}var jo=m("ZodMiniPipe",(e,t)=>{Vr.init(e,t),C.init(e,t)});function Ko(e,t){return new jo({type:"pipe",in:e,out:t})}var V;((_)=>{_.MESSAGE_SENT="message.sent";_.MESSAGE_DELIVERED="message.delivered";_.MESSAGE_FAILED="message.failed";_.MESSAGE_CLICKED="message.clicked";_.MESSAGE_READ="message.read";_.TEMPLATE_CREATED="template.created";_.TEMPLATE_APPROVED="template.approved";_.TEMPLATE_REJECTED="template.rejected";_.TEMPLATE_UPDATED="template.updated";_.TEMPLATE_DELETED="template.deleted";_.CHANNEL_CREATED="channel.created";_.CHANNEL_VERIFIED="channel.verified";_.SENDER_NUMBER_ADDED="sender_number.added";_.SENDER_NUMBER_VERIFIED="sender_number.verified";_.QUOTA_WARNING="system.quota_warning";_.QUOTA_EXCEEDED="system.quota_exceeded";_.PROVIDER_ERROR="system.provider_error";_.SYSTEM_MAINTENANCE="system.maintenance";_.ANOMALY_DETECTED="analytics.anomaly_detected";_.THRESHOLD_EXCEEDED="analytics.threshold_exceeded"})(V||={});var Vo=H({providerId:x(y()),channelId:x(y()),templateId:x(y()),messageId:x(y()),userId:x(y()),organizationId:x(y()),correlationId:x(y()),retryCount:x(K())}),Go=H({maxRetries:K().check(de(0),De(10)),retryDelayMs:K().check(de(1000)),backoffMultiplier:K().check(de(1),De(5))}),qo=H({providerId:x(pe(y())),channelId:x(pe(y())),templateId:x(pe(y()))}),Yo=H({attemptNumber:K(),timestamp:L(),httpStatus:x(K()),responseBody:x(y()),responseHeaders:x(vt(y(),y())),error:x(y()),latencyMs:K()}),sn=H({id:y(),type:Et(V),timestamp:Ko(Uo((e)=>{if(e instanceof Date)return e;if(typeof e==="string"||typeof e==="number")return new Date(e);return e}),L()),data:Oo(),metadata:Vo,version:y()}),an=H({id:y(),url:nn(),name:x(y()),description:x(y()),active:Zo(),events:pe(Et(V)),headers:x(vt(y(),y())),secret:x(y()),retryConfig:x(Go),filters:x(qo),createdAt:L(),updatedAt:L(),lastTriggeredAt:x(L()),status:wt(["active","inactive","error","suspended"])}),cn=H({id:y(),endpointId:y(),eventId:y(),eventType:x(Et(V)),url:nn(),httpMethod:wt(["POST","PUT","PATCH"]),headers:vt(y(),y()),payload:y(),attempts:pe(Yo),status:wt(["pending","success","failed","exhausted"]),createdAt:L(),completedAt:x(L()),nextRetryAt:x(L())});function un(e){return e?"active":"inactive"}function ln(e,t){if(typeof e!=="number"||!Number.isFinite(e))return t;return Math.max(0,Math.floor(e))}function dn(e){let t=e.timestamp instanceof Date?e.timestamp:new Date(e.timestamp);return{...e,timestamp:Number.isNaN(t.getTime())?new Date:t}}class kt{config;dispatcher;endpointStore;deliveryStore;securityOptions;persistence;fieldCrypto;eventQueue=[];batchProcessor=null;initPromise=null;activeBatch=null;endpointWrites=Promise.resolve();shuttingDown=!1;constructor(e){this.config=e.delivery,this.dispatcher=new ce(e.delivery,e.httpClient),this.securityOptions=re(e.security);let t=this.resolvePersistence(e);if(this.persistence=t,this.fieldCrypto=e.fieldCrypto,Xe(e.fieldCrypto),this.endpointStore=jt(t.endpointStore,e.fieldCrypto),this.deliveryStore=Kt(t.deliveryStore,e.fieldCrypto),e.autoStart??!0)this.startBatchProcessor()}async addEndpoint(e){return N(e.url,this.securityOptions),this.writeEndpoints(async()=>(await this.ensureInitialized(),this.insertEndpoint(e)))}async addEndpoints(e){for(let[t,r]of e.entries())try{N(r.url,this.securityOptions)}catch(n){let o=n instanceof Error?n.message:String(n);throw Error(`Webhook endpoint ${t} in the batch: ${o}`,{cause:n})}return this.writeEndpoints(async()=>{await this.ensureInitialized();let t=[];for(let r of e)t.push(await this.insertEndpoint(r));return t})}async insertEndpoint(e){N(e.url,this.securityOptions);let t=new Date,r=e.active??(e.status?e.status==="active":!0),n=e.status??un(r),o={...e,id:e.id??this.generateEndpointId(),active:r,status:n,createdAt:t,updatedAt:t};return await this.endpointStore.add(o),o}updateEndpoint(e,t){return this.writeEndpoints(async()=>(await this.ensureInitialized(),this.applyEndpointUpdate(e,t)))}async applyEndpointUpdate(e,t){let r=await this.endpointStore.get(e);if(!r)throw Error(`Webhook endpoint ${e} not found`);if(t.url&&t.url!==r.url)N(t.url,this.securityOptions);let n=new Date,o={...r,...t,id:r.id,createdAt:r.createdAt,updatedAt:n,active:t.active??(t.status?t.status==="active":r.active),status:t.status??(t.active!==void 0?un(t.active):r.status)};return await this.endpointStore.update(e,o),o}removeEndpoint(e){return this.writeEndpoints(async()=>{await this.ensureInitialized(),await this.endpointStore.remove(e)})}async getEndpoint(e){return await this.ensureInitialized(),this.endpointStore.get(e)}async listEndpoints(){return await this.ensureInitialized(),this.endpointStore.list()}async probeEndpoint(e){await this.ensureInitialized();let t=typeof e==="string"?e:e.endpointId,r=await this.endpointStore.get(t);if(!r)throw Error(`Webhook endpoint ${t} not found`);let n=this.createProbeEvent(t,typeof e==="string"?void 0:e.event),o=Date.now();try{let i=await this.dispatcher.dispatch(n,r);return await this.deliveryStore.add(i),{endpointId:t,url:r.url,success:i.status==="success",httpStatus:i.attempts[0]?.httpStatus,responseTime:Date.now()-o,testedAt:new Date}}catch(i){return{endpointId:t,url:r.url,success:!1,error:i instanceof Error?i.message:"Unknown error",responseTime:Date.now()-o,testedAt:new Date}}}async emit(e){if(this.validateEvent(e),!this.config.enabledEvents.includes(e.type))return;if(await this.ensureInitialized(),this.eventQueue.push(dn(e)),this.eventQueue.length>=this.config.batchSize&&this.activeBatch===null)await this.processBatch()}async emitSync(e){if(this.validateEvent(e),!this.config.enabledEvents.includes(e.type))return[];await this.ensureInitialized();let t=dn(e),r=await this.getMatchingEndpoints(t),n=[];for(let o of r){let i=await this.dispatcher.dispatch(t,o);await this.deliveryStore.add(i),n.push(i)}return n}async flush(){await this.ensureInitialized();while(this.eventQueue.length>0||this.activeBatch!==null)await this.processBatch()}async listDeliveries(e={}){return await this.ensureInitialized(),this.deliveryStore.list({...e,limit:ln(e.limit,100)})}migrateFieldCryptoToTenant(){return this.writeEndpoints(async()=>(await this.ensureInitialized(),ye(this.persistence,this.fieldCrypto??{})))}async shutdown(){if(this.shuttingDown=!0,this.batchProcessor)clearInterval(this.batchProcessor),this.batchProcessor=null;if(await this.flush(),await this.endpointWrites,await this.dispatcher.shutdown(),typeof this.persistence.close==="function")await this.persistence.close()}resolvePersistence(e){if(e.persistence)return{endpointStore:e.endpointStore??e.persistence.endpointStore,deliveryStore:e.deliveryStore??e.persistence.deliveryStore,init:e.persistence.init,close:e.persistence.close};if(e.endpointStore&&e.deliveryStore)return{endpointStore:e.endpointStore,deliveryStore:e.deliveryStore};if(e.endpointStore||e.deliveryStore)throw Error("Both endpointStore and deliveryStore must be provided together");return ge()}writeEndpoints(e){if(this.shuttingDown)return Promise.reject(Error("Webhook endpoints cannot be changed after shutdown() has started"));let t=()=>e(),r=this.endpointWrites.then(t,t);return this.endpointWrites=r.catch(()=>{return}),r}async ensureInitialized(){if(!this.initPromise)this.initPromise=(async()=>{if(typeof this.persistence.init==="function")await this.persistence.init()})().catch((e)=>{throw this.initPromise=null,e});await this.initPromise}validateEvent(e){if(!e.id)throw Error("Event ID is required");if(!e.type)throw Error("Event type is required");if(!e.timestamp)throw Error("Event timestamp is required");let t=e.timestamp instanceof Date?e.timestamp:new Date(e.timestamp);if(Number.isNaN(t.getTime()))throw Error("Event timestamp must be a valid Date");if(!e.version)throw Error("Event version is required")}processBatch(){if(this.activeBatch!==null)return this.activeBatch;if(this.eventQueue.length===0)return Promise.resolve();let e=this.eventQueue.splice(0,this.config.batchSize);return this.activeBatch=this.dispatchBatch(e).finally(()=>{this.activeBatch=null}),this.activeBatch}async dispatchBatch(e){let t=0;try{for(let r of e){let n=await this.getMatchingEndpoints(r),o=await Promise.allSettled(n.map(async(i)=>{let s=await this.dispatcher.dispatch(r,i);return await this.deliveryStore.add(s),s}));for(let i of o)if(i.status==="rejected")Q.error("Failed to dispatch webhook",void 0,i.reason instanceof Error?i.reason:Error(String(i.reason)));t+=1}}catch(r){throw this.eventQueue.unshift(...e.slice(t)),r}}async getMatchingEndpoints(e){return(await this.endpointStore.list()).filter((r)=>_e(r,e))}createProbeEvent(e,t){let r=new Date,n={id:`probe_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,type:"system.maintenance",timestamp:r,data:{test:!0,message:"Webhook endpoint probe"},metadata:{correlationId:`probe_${e}_${Date.now()}`},version:"1.0"};if(!t)return n;return{...n,...t,metadata:{...n.metadata,...t.metadata??{}},timestamp:t.timestamp instanceof Date?t.timestamp:t.timestamp?new Date(t.timestamp):n.timestamp}}generateEndpointId(){return`webhook_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}startBatchProcessor(){let e=ln(this.config.batchTimeoutMs,5000);this.batchProcessor=setInterval(()=>{if(this.activeBatch!==null)return;this.processBatch().catch((t)=>{Q.error("Webhook batch processor error",void 0,t instanceof Error?t:Error(String(t)))})},e)}}function pn(e,t){return e.probeEndpoint(t)}function fn(e,t){return e.addEndpoints(t)}function hn(e){return re(e)}
3
+
4
+ //# debugId=9B812455809A93E064756E2164756E21
5
+ //# sourceMappingURL=index.cjs.map
package/dist/index.d.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  /**
2
2
  * Runtime webhook APIs
3
3
  */
4
+ export { migrateWebhookFieldCryptoToTenant } from "./crypto/field-crypto";
4
5
  export { RetryManager } from "./retry/retry.manager";
5
6
  export { DEFAULT_ENDPOINT_VALIDATION_OPTIONS, type EndpointValidationOptions, resolveEndpointValidationOptions, validateEndpointUrl, } from "./runtime/endpoint-validation";
6
7
  export { endpointMatchesEvent } from "./runtime/event-matcher";
7
8
  export { createInMemoryWebhookPersistence } from "./runtime/persistence";
8
- export type { WebhookDeliveryListOptions, WebhookDeliveryStore, WebhookEndpointInput, WebhookEndpointStore, WebhookPersistence, WebhookRuntime, WebhookRuntimeConfig, WebhookRuntimeFieldCryptoOptions, WebhookRuntimeSecurityOptions, WebhookRuntimeTestPayload, } from "./runtime/types";
9
+ export type { WebhookDeliveryListOptions, WebhookDeliveryStore, WebhookEndpointInput, WebhookEndpointStore, WebhookPersistence, WebhookRuntime, WebhookRuntimeConfig, WebhookRuntimeFieldCryptoOptions, WebhookRuntimeSecurityOptions, WebhookRuntimeTestPayload, WebhookTenantMigrationResult, } from "./runtime/types";
9
10
  export { addEndpoints, type HttpClient, probeEndpoint, resolveWebhookSecurityOptions, WebhookRuntimeService, } from "./runtime/webhook-runtime.service";
10
11
  export { SecurityManager } from "./security/security.manager";
11
12
  export { DefaultHttpClient, WebhookDispatcher, } from "./services/webhook.dispatcher";