meta-cloud-api 3.9.0 → 3.9.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.
package/dist/index.mjs CHANGED
@@ -19,5 +19,5 @@ Your key format is not recognized. Please ensure it is in PKCS#8 format.`),Error
19
19
  ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██╔══██║ ██╔═══╝ ██║
20
20
  ╚██████╗ ███████╗ ╚██████╔╝ ╚██████╔╝ ██████╔╝ ██║ ██║ ██║ ██║
21
21
  ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝
22
- `)}function jn(){return`3.9.0`}function Mn(){return`WhatsApp-Nodejs-SDK/${jn()} (${Xt()})`}const q=new N(`WHATSAPP`,I());var Nn=class{config;requester;blockUsers;business;calling;commerce;contactBook;groups;marketingMessages;messageHistory;messages;media;payments;phoneNumbers;solutions;threadControl;twoStepVerification;flows;businessProfile;templates;encryption;qrCode;registration;waba;constructor(e){An(),this.config=cn(e),this.requester=new kn(this.config.CLOUD_API_VERSION,this.config.WA_PHONE_NUMBER_ID,this.config.CLOUD_API_ACCESS_TOKEN,this.config.WA_BUSINESS_ACCOUNT_ID,this.getUserAgent(),this.config.retry,this.config.onRateLimitInfo),this.blockUsers=new rt(this.config,this.requester),this.business=new it(this.config,this.requester),this.calling=new at(this.config,this.requester),this.commerce=new ot(this.config,this.requester),this.contactBook=new st(this.config,this.requester),this.groups=new mt(this.config,this.requester),this.marketingMessages=new ht(this.config,this.requester),this.messageHistory=new bt(this.config,this.requester),this.messages=new k(this.config,this.requester),this.media=new gt(this.config,this.requester),this.payments=new xt(this.config,this.requester),this.phoneNumbers=new St(this.config,this.requester),this.solutions=new Dt(this.config,this.requester),this.threadControl=new Ht(this.config,this.requester),this.twoStepVerification=new Ut(this.config,this.requester),this.flows=new lt(this.config,this.requester),this.businessProfile=new wt(this.config,this.requester),this.templates=new Bt(this.config,this.requester),this.encryption=new ct(this.config,this.requester),this.qrCode=new Tt(this.config,this.requester),this.registration=new Et(this.config,this.requester),this.waba=new Wt(this.config,this.requester),q.log(`\n${ln(this.config)}`)}updateTimeout(e){this.config.REQUEST_TIMEOUT=e,this.requester.updateTimeout(e),q.log(`Timeout updated to ${e}ms`)}updateSenderNumberId(e){this.config.WA_PHONE_NUMBER_ID=e,q.log(`Sender number ID updated to ${e}`)}updateAccessToken(e){this.config.CLOUD_API_ACCESS_TOKEN=e,this.requester.updateAccessToken(e),q.log(`Access token updated`)}getLastRateLimitInfo(){return this.requester.getLastRateLimitInfo()}version(){return jn()}static get Enums(){return r}getUserAgent(){return Mn()}generateEncryption(e){return dn(e||this.config.FLOW_API_PASSPHRASE)}},Pn=class{maxEntries;entries=new Map;constructor(e={}){let t=e.maxEntries??1e4;if(!Number.isInteger(t)||t<1)throw Error(`MemoryDedupeStore maxEntries must be a positive integer, got ${t}`);this.maxEntries=t}async has(e){return this.lookup(e,Date.now())!==void 0}async setIfAbsent(e,t){let n=Date.now(),r=this.lookup(e,n);return r===void 0?(this.entries.set(e,n+t*1e3),this.evict(n),!0):(this.entries.delete(e),this.entries.set(e,r),!1)}get size(){return this.entries.size}clear(){this.entries.clear()}lookup(e,t){let n=this.entries.get(e);if(n!==void 0){if(n<=t){this.entries.delete(e);return}return n}}evict(e){for(let[t,n]of this.entries)n<=e&&this.entries.delete(t);for(let e of this.entries.keys()){if(this.entries.size<=this.maxEntries)break;this.entries.delete(e)}}};function Fn(e){if(!e)return;let t=e===!0?{}:e,n=t.ttlSeconds??86400;if(!Number.isFinite(n)||n<=0)throw Error(`dedupe.ttlSeconds must be a positive number, got ${n}`);return{store:t.store??new Pn,ttlSeconds:n}}function In(e){return typeof e==`object`&&!!e}function J(e){return typeof e==`string`}const Ln=[`data_exchange`,`INIT`,`BACK`],Rn=[`data_exchange`,`INIT`];function zn(e){if(!(`flow_token`in e&&J(e.flow_token)&&`action`in e))return!1;let{action:t,version:n,screen:r,data:i}=e,a=n===`3.0`,o=Ln.includes(t),s=r===void 0||J(r)&&r!==`SUCCESS`,c=t===`data_exchange`||In(i);return a&&o&&s&&c}function Bn(e){if(!(`flow_token`in e&&J(e.flow_token)&&`action`in e))return!1;let{action:t,screen:n,data:r}=e,i=Rn.includes(t),a=J(n),o=In(r)&&`error_key`in r&&J(r.error)&&`error_message`in r&&J(r.error_message);return i&&a&&o}function Vn(e){return`action`in e&&e.action===`ping`}const Y=new N(`WEBHOOK_UTILS`,I()),Hn={account_update:`accountUpdateHandler`,account_review_update:`accountReviewUpdateHandler`,account_alerts:`accountAlertsHandler`,account_settings_update:`accountSettingsUpdateHandler`,automatic_events:`automaticEventsHandler`,business_capability_update:`businessCapabilityUpdateHandler`,business_status_update:`businessStatusUpdateHandler`,business_username_updates:`businessUsernameUpdatesHandler`,calls:`callsHandler`,flows:`flowsHandler`,group_lifecycle_update:`groupLifecycleUpdateHandler`,group_participants_update:`groupParticipantsUpdateHandler`,group_settings_update:`groupSettingsUpdateHandler`,group_status_update:`groupStatusUpdateHandler`,history:`historyHandler`,message_echoes:`messageEchoesHandler`,message_template_components_update:`messageTemplateComponentsUpdateHandler`,message_template_quality_update:`messageTemplateQualityUpdateHandler`,message_template_status_update:`messageTemplateStatusUpdateHandler`,messaging_handovers:`messagingHandoversHandler`,partner_solutions:`partnerSolutionsHandler`,payment_configuration_update:`paymentConfigurationUpdateHandler`,phone_number_name_update:`phoneNumberNameUpdateHandler`,phone_number_quality_update:`phoneNumberQualityUpdateHandler`,security:`securityHandler`,smb_app_state_sync:`smbAppStateSyncHandler`,smb_message_echoes:`smbMessageEchoesHandler`,standby:`standbyHandler`,template_category_update:`templateCategoryUpdateHandler`,template_correct_category_detection:`templateCorrectCategoryDetectionHandler`,tracking_events:`trackingEventsHandler`,user_preferences:`userPreferencesHandler`};function Un(e){return Object.hasOwn(Hn,e)}const Wn={calls:e=>Kn(`calls`,Gn(e?.calls,e=>e?.id?`${e.id}:${e.event}${e.call_status?`:${e.call_status}`:``}`:void 0)),smb_message_echoes:e=>Kn(`smb_message_echoes`,Gn(e?.message_echoes,e=>e?.id)),message_echoes:e=>Kn(`message_echoes`,Gn(e?.messaging,e=>e?.message?.mid))};function Gn(e,t){return Array.isArray(e)?e.map(t):void 0}function Kn(e,t){if(!(!t||t.length===0||t.some(e=>!e)))return`${e}:${t.join(`,`)}`}function qn(e,t){let n=Wn[e];return n?.(t)}async function Jn(e,t){if(!e||!t)return!1;try{return await e.store.setIfAbsent(t,e.ttlSeconds)?!1:(Y.log(`Skipping duplicate webhook delivery: ${t}`),!0)}catch(e){return Y.error(`Dedupe store failed; processing the webhook anyway:`,{key:t,error:e}),!1}}async function Yn(e,t,n,r={}){try{let i=await e.text();if(r.verifySignature){if(!r.appSecret)return Y.error(`verifyWebhookSignature is on but appSecret is not configured; rejecting webhook`),new Response(JSON.stringify({error:`Webhook signature verification misconfigured`}),{status:500,headers:{"Content-Type":`application/json`}});if(!await $n(i,e.headers.get(`x-hub-signature-256`),r.appSecret))return Y.warn(`Rejected webhook with missing or invalid X-Hub-Signature-256`),new Response(JSON.stringify({error:`Invalid signature`}),{status:401,headers:{"Content-Type":`application/json`}})}let a=JSON.parse(i),o={headers:e.headers,rawBody:i,method:e.method,url:e.url},s=r.dedupe?{store:r.dedupe.store,ttlSeconds:r.dedupe.ttlSeconds??86400}:void 0;if(n.rawHandler){let{rawHandler:e,rawHandlerFields:r}=n,i=a;if(r&&r.length>0){let e={...i,entry:i.entry.map(e=>({...e,changes:e.changes.filter(e=>r.includes(e.field))})).filter(e=>e.changes.length>0)};i=e.entry.length===0?null:e}i&&await e(t,i,o)}if(a.object!==`whatsapp_business_account`){let e=`Received webhook for non-WhatsApp event`;return Y.warn(e),new Response(JSON.stringify({error:e}),{status:404})}let c=[];for(let e of a.entry)try{let r=e.changes;for(let i of r){let r=i.field;if(r===`messages`)await rr(e.id,i.value,t,n,o,s);else if(Un(r)){let a=n.fieldHandlers?.get(r)??n[Hn[r]];await sr(e.id,{field:r,value:i.value},a,t,o,s)}else Y.warn(`Unhandled webhook field: ${i.field}`)}}catch(t){let n=`Error processing webhook: ${t}`;Y.error(n,{entry:e,error:t}),c.push(n)}return new Response(c.length>0?JSON.stringify({errors:c}):null,{status:200})}catch(e){return Y.error(`Error processing webhook:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500})}}function Xn(){return{version:`3.0`,data:{status:`active`}}}function Zn(){return{data:{acknowledged:!0}}}async function Qn(e,t,n,r){try{let i=await e.text(),a={headers:e.headers,rawBody:i,method:e.method,url:e.url},o=e.headers.get(`x-hub-signature-256`),s=t.M4D_APP_SECRET||t.WEBHOOK_VERIFICATION_TOKEN||``;if(t.M4D_APP_SECRET||Y.warn(`appSecret not configured; verifying Flow signature with the webhook verification token`),!await $n(i,o,s))return Y.warn(`Invalid request signature`),new Response(JSON.stringify({error:`Unauthorized`}),{status:401});let{decryptedBody:c,aesKeyBuffer:l,initialVectorBuffer:u}=await _n(JSON.parse(i),t),d=Vn(c),f=Bn(c),p=zn(c),m;m=d?`ping`:f?`error`:p?`data_exchange`:`*`;let h=r.get(m);if(!h){if(m===`ping`)h=()=>Xn();else if(m===`error`)h=()=>Zn();else if(h=r.get(`*`),!h)return Y.warn(`No handler registered for flow type:`,{flowType:m,action:c.action}),new Response(JSON.stringify({error:`Handler not found`}),{status:404})}let g=await h(n,c,a);if(f){Y.warn(`Flow error notification received`,{error:c.data});let e=g||Zn();return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":`application/json`}})}if(d||p){let e=await vn(g,l,u);return new Response(e,{status:200,headers:{"Content-Type":`text/plain`}})}return Y.warn(`Unknown flow request type:`,c),new Response(JSON.stringify({error:`Unknown request type`}),{status:400})}catch(e){return Y.error(`Error handling flow request:`,e),new Response(JSON.stringify({error:`Internal server error`}),{status:500})}}async function $n(e,t,n){if(!t||!n)return!1;let r=t.startsWith(`sha256=`)?t.slice(7):t,i=await an(n,e);return rn(r.toLowerCase(),i)}function er(e,t,n){if(!t||!n)return!1;let r=R(`isValidWebhookSignature`),i=t.startsWith(`sha256=`)?t.slice(7):t,a=r.createHmac(`sha256`,n).update(e,`utf8`).digest(`hex`);return rn(i.toLowerCase(),a)}function tr(e,t){return`${e[`x-forwarded-proto`]||`http`}://${e.host||`localhost`}${t||`/`}`}function nr(e){return e.id?e.id:(e.type===`interactive`||e.type===`button`)&&`context`in e&&e.context?.id?e.context.id:``}async function rr(e,t,n,r,i,a){let o=t.metadata,s=e,c=o.display_phone_number,l=o.phone_number_id;if(`user_actions`in t&&t.user_actions){let e=t;for(let t of e.user_actions){let e={wabaId:s,phoneNumberId:l,displayPhoneNumber:c,action:t};await or(r.userActionHandler,n,e,i)}return}if(`statuses`in t&&t.statuses){let e=t;for(let t of e.statuses){if(!r.statusHandler||await Jn(a,t.id?`status:${t.id}:${t.status}`:void 0))continue;let e={wabaId:s,phoneNumberId:l,displayPhoneNumber:c,status:t};await ar(r.statusHandler,n,e,i)}return}if(`messages`in t&&t.messages){let e=t,o=e.contacts?.[0]?.profile?.name||``;for(let t of e.messages){let u={wabaId:s,phoneNumberId:l,displayPhoneNumber:c,profileName:o,message:t,messageId:nr(t),...e.conversation_context&&{conversationContext:e.conversation_context}},d=t.type,f=r.messageHandlers.get(d);!r.preProcessHandler&&!f&&!r.postProcessHandler||await Jn(a,u.messageId?`message:${u.messageId}`:void 0)||(await ir(r.preProcessHandler,n,u,i,`pre-process`),await ir(f,n,u,i,d),await ir(r.postProcessHandler,n,u,i,`post-process`))}}}async function ir(e,t,n,r,i){if(e)try{await e(t,n,r)}catch(e){Y.error(`Error in ${i} handler:`,{error:e,messageId:n.messageId})}}async function ar(e,t,n,r){if(e)try{await e(t,n,r)}catch(e){Y.error(`Error in status handler:`,{error:e,statusId:n.status.id})}}async function or(e,t,n,r){if(e)try{await e(t,n,r)}catch(e){Y.error(`Error in user action handler:`,{error:e,actionType:n.action.action_type})}}async function sr(e,t,n,r,i,a){if(n&&!await Jn(a,qn(t.field,t.value)))try{await n(r,{wabaId:e,value:t.value},i)}catch(n){Y.error(`Error in ${t.field} handler:`,{error:n,wabaId:e})}}const X=new N(`WEBHOOK_PROCESSOR`,I());function cr(e,t){if(e===`messages`)throw Error(`${t}('messages') is not supported. Use onMessage/onText/... for messages, onStatus for statuses and onUserAction for marketing user actions.`);if(!Un(e))throw Error(`${t}('${e}'): unknown webhook field`)}var Z=class{config;client;messageHandlers=new Map;statusHandler=void 0;userActionHandler=void 0;preProcessHandler=void 0;postProcessHandler=void 0;rawHandler=void 0;flowHandlers=new Map;fieldHandlers=new Map;verifySignature;dedupe;constructor(e){this.config=cn(e),this.verifySignature=e.verifyWebhookSignature===!0,this.dedupe=Fn(e.dedupe),this.client=new Nn(e),X.log(`WebhookProcessor instantiated`)}async processVerification(e,t,n){return e===`subscribe`&&t===this.config.WEBHOOK_VERIFICATION_TOKEN?{status:200,body:n||``,headers:{"Content-Type":`text/plain`}}:{status:403,body:JSON.stringify({error:`Forbidden`}),headers:{"Content-Type":`application/json`}}}async processWebhook(e){try{let t=await Yn(e,this.client,{messageHandlers:this.messageHandlers,statusHandler:this.statusHandler,userActionHandler:this.userActionHandler,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler,rawHandler:this.rawHandler?.handler,rawHandlerFields:this.rawHandler?.fields,fieldHandlers:this.fieldHandlers},{appSecret:this.config.M4D_APP_SECRET,verifySignature:this.verifySignature,dedupe:this.dedupe}),n=await t.text(),r=t.headers.get(`content-type`)||`application/json`;return{status:t.status,body:n,headers:{"Content-Type":r}}}catch(e){return X.log(`Error processing webhook: ${e}`),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async processFlow(e){try{let t=await Qn(e,this.config,this.client,this.flowHandlers),n=await t.text(),r=t.headers.get(`content-type`)||`text/plain`;return{status:t.status,body:n,headers:{"Content-Type":r}}}catch(e){return X.log(`Error processing flow: ${e}`),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}onMessage(e,t){if(e===`statuses`)throw Error(`MessageTypesEnum.Statuses is deprecated. Use onStatus(handler) instead of onMessage(MessageTypesEnum.Statuses, handler)`);this.messageHandlers.set(e,t),X.log(`Registered message handler for ${e}`)}onStatus(e){this.statusHandler=e,X.log(`Registered status handler`)}onUserAction(e){this.userActionHandler=e,X.log(`Registered user action handler`)}onMessagePreProcess(e){this.preProcessHandler=e,X.log(`Registered pre-process handler`)}onMessagePostProcess(e){this.postProcessHandler=e,X.log(`Registered post-process handler`)}onRaw(e,t){this.rawHandler={handler:e,fields:t},X.log(`Registered raw webhook handler${t?` for fields: ${t.join(`, `)}`:``}`)}onFlow(e,t){this.flowHandlers.set(e,t),X.log(`Registered flow handler for ${e}`)}on(e,t){cr(e,`on`),this.fieldHandlers.set(e,t),X.log(`Registered ${e} handler`)}off(e){cr(e,`off`),this.fieldHandlers.delete(e),X.log(`Removed ${e} handler`)}onText(e){this.messageHandlers.set(`text`,e),X.log(`Registered text message handler`)}onImage(e){this.messageHandlers.set(`image`,e),X.log(`Registered image message handler`)}onVideo(e){this.messageHandlers.set(`video`,e),X.log(`Registered video message handler`)}onAudio(e){this.messageHandlers.set(`audio`,e),X.log(`Registered audio message handler`)}onDocument(e){this.messageHandlers.set(`document`,e),X.log(`Registered document message handler`)}onSticker(e){this.messageHandlers.set(`sticker`,e),X.log(`Registered sticker message handler`)}onInteractive(e){this.messageHandlers.set(`interactive`,e),X.log(`Registered interactive message handler`)}onButton(e){this.messageHandlers.set(`button`,e),X.log(`Registered button message handler`)}onLocation(e){this.messageHandlers.set(`location`,e),X.log(`Registered location message handler`)}onContacts(e){this.messageHandlers.set(`contacts`,e),X.log(`Registered contacts message handler`)}onReaction(e){this.messageHandlers.set(`reaction`,e),X.log(`Registered reaction message handler`)}onOrder(e){this.messageHandlers.set(`order`,e),X.log(`Registered order message handler`)}onSystem(e){this.messageHandlers.set(`system`,e),X.log(`Registered system message handler`)}onAccountUpdate(e){this.on(`account_update`,e)}onAccountReviewUpdate(e){this.on(`account_review_update`,e)}onAccountAlerts(e){this.on(`account_alerts`,e)}onBusinessCapabilityUpdate(e){this.on(`business_capability_update`,e)}onPhoneNumberNameUpdate(e){this.on(`phone_number_name_update`,e)}onPhoneNumberQualityUpdate(e){this.on(`phone_number_quality_update`,e)}onMessageTemplateStatusUpdate(e){this.on(`message_template_status_update`,e)}onTemplateCategoryUpdate(e){this.on(`template_category_update`,e)}onMessageTemplateQualityUpdate(e){this.on(`message_template_quality_update`,e)}onFlows(e){this.on(`flows`,e)}onSecurity(e){this.on(`security`,e)}onHistory(e){this.on(`history`,e)}onSmbMessageEchoes(e){this.on(`smb_message_echoes`,e)}onSmbAppStateSync(e){this.on(`smb_app_state_sync`,e)}onAccountSettingsUpdate(e){this.on(`account_settings_update`,e)}onAutomaticEvents(e){this.on(`automatic_events`,e)}onBusinessStatusUpdate(e){this.on(`business_status_update`,e)}onBusinessUsernameUpdates(e){this.on(`business_username_updates`,e)}onCalls(e){this.on(`calls`,e)}onGroupLifecycleUpdate(e){this.on(`group_lifecycle_update`,e)}onGroupParticipantsUpdate(e){this.on(`group_participants_update`,e)}onGroupSettingsUpdate(e){this.on(`group_settings_update`,e)}onGroupStatusUpdate(e){this.on(`group_status_update`,e)}onMessageEchoes(e){this.on(`message_echoes`,e)}onMessageTemplateComponentsUpdate(e){this.on(`message_template_components_update`,e)}onMessagingHandovers(e){this.on(`messaging_handovers`,e)}onPartnerSolutions(e){this.on(`partner_solutions`,e)}onPaymentConfigurationUpdate(e){this.on(`payment_configuration_update`,e)}onStandby(e){this.on(`standby`,e)}onTemplateCorrectCategoryDetection(e){this.on(`template_correct_category_detection`,e)}onTrackingEvents(e){this.on(`tracking_events`,e)}onUserPreferences(e){this.on(`user_preferences`,e)}offMessage(e){this.messageHandlers.delete(e),X.log(`Removed message handler for ${e}`)}offMessagePreProcess(){this.preProcessHandler=void 0,X.log(`Removed pre-process handler`)}offMessagePostProcess(){this.postProcessHandler=void 0,X.log(`Removed post-process handler`)}offStatus(){this.statusHandler=void 0,X.log(`Removed status handler`)}offUserAction(){this.userActionHandler=void 0,X.log(`Removed user action handler`)}offRaw(){this.rawHandler=void 0,X.log(`Removed raw webhook handler`)}offFlow(e){this.flowHandlers.delete(e),X.log(`Removed flow handler for ${e}`)}removeAllHandlers(){this.messageHandlers.clear(),this.statusHandler=void 0,this.userActionHandler=void 0,this.preProcessHandler=void 0,this.postProcessHandler=void 0,this.rawHandler=void 0,this.flowHandlers.clear(),this.fieldHandlers.clear(),X.log(`Removed all handlers`)}getClient(){return this.client}getConfig(){return this.config}},lr=class{processor;constructor(e){this.processor=new Z(e)}async processVerification(e,t,n){return await this.processor.processVerification(e,t,n)}async processWebhook(e){return await this.processor.processWebhook(e)}async processFlow(e){return await this.processor.processFlow(e)}constructFullUrl(e,t=``){return tr(e,t)}applyHeaders(e,t){t.setHeader&&Object.entries(e.headers).forEach(([e,n])=>{t.setHeader?.(e,n)})}async autoRoute(e,t,...n){switch(e.method?.toUpperCase()){case`GET`:return await this.handleGet(e,t,...n);case`POST`:return await this.handlePost(e,t,...n);default:if(t.status&&t.json)return t.status(405).json({error:`Method Not Allowed`});throw Error(`Method Not Allowed`)}}get webhookProcessor(){return this.processor}},ur=class extends lr{async handleGet(e,t,n){try{let{"hub.mode":n,"hub.verify_token":r,"hub.challenge":i}=e.query,a=await this.processVerification(n||null,r||null,i||null);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return n(e),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async handlePost(e,t,n){try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody??(e.method===`POST`?JSON.stringify(e.body):void 0),i=new globalThis.Request(n,{method:e.method,headers:e.headers,body:r}),a=await this.processWebhook(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return n(e),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async handleFlow(e,t,n){try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody??(e.method===`POST`?JSON.stringify(e.body):void 0),i=new globalThis.Request(n,{method:e.method,headers:e.headers,body:r}),a=await this.processFlow(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return n(e),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}getHandlers(){return{GET:(e,t,n)=>this.handleGet(e,t,n),POST:(e,t,n)=>this.handlePost(e,t,n),webhook:(e,t,n)=>this.autoRoute(e,t,n),flow:(e,t,n)=>this.handleFlow(e,t,n),processor:this.webhookProcessor}}};const dr=new Map;function fr(e){return`express:${e.phoneNumberId??`default`}`}function pr(e){let t=fr(e),n=dr.get(t);if(n)return n;let r=new ur(e),i={...r.getHandlers(),destroy:()=>{r.webhookProcessor.removeAllHandlers(),dr.delete(t)}};return dr.set(t,i),i}const mr=new Map;function hr(e){return`fastify:${e.phoneNumberId??`default`}`}function gr(e,t){e.code(t.status);for(let[n,r]of Object.entries(t.headers))e.header(n,r);return e.send(t.body)}function _r(e){return e.code(500).header(`Content-Type`,`application/json`).send(JSON.stringify({error:`Internal Server Error`}))}function vr(e,t){if(typeof e!=`object`||!e)return null;let n=e[t];return Array.isArray(n)?typeof n[0]==`string`?n[0]:null:typeof n==`string`?n:null}function yr(e){let t=new Headers;for(let[n,r]of Object.entries(e))r!==void 0&&(n===`content-length`||n===`transfer-encoding`||t.set(n,Array.isArray(r)?r.join(`, `):r));return t}function br(e){if(e.rawBody!==void 0)return e.rawBody;if(!(e.body===void 0||e.body===null))return typeof e.body==`string`?e.body:JSON.stringify(e.body)}function xr(e){let t=e.method===`GET`||e.method===`HEAD`?void 0:br(e);return new Request(tr(e.headers,e.url),{method:e.method,headers:yr(e.headers),body:t})}function Sr(e){let t=hr(e),n=mr.get(t);if(n)return n;let r=Cr(e,t);return mr.set(t,r),r}function Cr(e,t){let n=new Z(e),r=async(e,t)=>{try{return gr(t,await n.processVerification(vr(e.query,`hub.mode`),vr(e.query,`hub.verify_token`),vr(e.query,`hub.challenge`)))}catch(e){return console.error(`Webhook verification error:`,e),_r(t)}},i=async(e,t)=>{try{return gr(t,await n.processWebhook(xr(e)))}catch(e){return console.error(`Webhook processing error:`,e),_r(t)}};return{GET:r,POST:i,webhook:async(e,t)=>{switch(e.method.toUpperCase()){case`GET`:return r(e,t);case`POST`:return i(e,t);default:return t.code(405).header(`Content-Type`,`application/json`).header(`Allow`,`GET, POST`).send(JSON.stringify({error:`Method Not Allowed`}))}},flow:async(e,t)=>{try{return gr(t,await n.processFlow(xr(e)))}catch(e){return console.error(`Flow processing error:`,e),_r(t)}},processor:n,destroy:()=>{n.removeAllHandlers(),mr.delete(t)}}}const wr=new Map;function Tr(e){return`hono:${e.phoneNumberId??`default`}`}function Er(e){return new Response(e.body,{status:e.status,headers:e.headers})}function Dr(){return new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}async function Or(e){let t=e.req.raw;return!t.bodyUsed||!e.req.text?t:new Request(t.url,{method:t.method,headers:t.headers,body:await e.req.text()})}function kr(e){let t=Tr(e),n=wr.get(t);if(n)return n;let r=Ar(e,t);return wr.set(t,r),r}function Ar(e,t){let n=new Z(e),r=async e=>{try{let{searchParams:t}=new URL(e.req.raw.url);return Er(await n.processVerification(t.get(`hub.mode`),t.get(`hub.verify_token`),t.get(`hub.challenge`)))}catch(e){return console.error(`Webhook verification error:`,e),Dr()}},i=async e=>{try{return Er(await n.processWebhook(await Or(e)))}catch(e){return console.error(`Webhook processing error:`,e),Dr()}};return{GET:r,POST:i,webhook:async e=>{switch(e.req.raw.method.toUpperCase()){case`GET`:return r(e);case`POST`:return i(e);default:return new Response(JSON.stringify({error:`Method Not Allowed`}),{status:405,headers:{"Content-Type":`application/json`,Allow:`GET, POST`}})}},flow:async e=>{try{return Er(await n.processFlow(await Or(e)))}catch(e){return console.error(`Flow processing error:`,e),Dr()}},processor:n,destroy:()=>{n.removeAllHandlers(),wr.delete(t)}}}const jr=new Map;function Mr(e){return`nextjs-app:${e.phoneNumberId??`default`}`}function Nr(e){let t=Mr(e),n=jr.get(t);if(n)return n;let r=Pr(e,t);return jr.set(t,r),r}function Pr(e,t){let n=new Z(e);return{GET:async e=>{try{let{searchParams:t}=new URL(e.url),r=t.get(`hub.mode`),i=t.get(`hub.verify_token`),a=t.get(`hub.challenge`),o=await n.processVerification(r,i,a);return new Response(o.body,{status:o.status,headers:o.headers})}catch(e){return console.error(`Webhook verification error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let t=await n.processWebhook(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}},webhook:{GET:async e=>{try{let{searchParams:t}=new URL(e.url),r=t.get(`hub.mode`),i=t.get(`hub.verify_token`),a=t.get(`hub.challenge`),o=await n.processVerification(r,i,a);return new Response(o.body,{status:o.status,headers:o.headers})}catch(e){return console.error(`Webhook verification error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let t=await n.processWebhook(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}}},flow:{GET:async e=>{try{let t=await n.processFlow(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Flow GET error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}},POST:async e=>{try{let t=await n.processFlow(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Flow POST error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}}},processor:n,destroy:()=>{n.removeAllHandlers(),jr.delete(t)}}}var Fr=class extends lr{async parseRequestBody(e,t=!1){if(e.method===`POST`&&!e.body){let n=[];if(typeof e[Symbol.asyncIterator]==`function`){for await(let t of e)n.push(t);let r=Buffer.concat(n).toString();if(t&&(e.rawBody=r),r.trim())try{e.body=JSON.parse(r)}catch{throw Error(`Invalid JSON in request body`)}else e.body={}}}}async handleGet(e,t){try{let{"hub.mode":n,"hub.verify_token":r,"hub.challenge":i}=e.query,a=await this.processVerification(n||null,r||null,i||null);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return console.error(`Webhook verification error:`,e),t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async handlePost(e,t){try{await this.parseRequestBody(e,!0)}catch(e){return console.error(`Webhook processing error:`,e),e instanceof Error&&e.message===`Invalid JSON in request body`?(t.status(400).json({error:`Invalid JSON`}),{status:400,body:JSON.stringify({error:`Invalid JSON`}),headers:{"Content-Type":`application/json`}}):(t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}})}try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody??(e.method===`POST`?JSON.stringify(e.body):void 0),i=new Request(n,{method:`POST`,headers:e.headers,body:r}),a=await this.processWebhook(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return console.error(`Webhook processing error:`,e),t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async handleFlow(e,t){try{await this.parseRequestBody(e,!0)}catch(e){return console.error(`Flow body parsing error:`,e),e instanceof Error&&e.message===`Invalid JSON in request body`?(t.status(400).json({error:`Invalid JSON`}),{status:400,body:JSON.stringify({error:`Invalid JSON`}),headers:{"Content-Type":`application/json`}}):(t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}})}try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody??(e.method===`POST`?JSON.stringify(e.body):void 0),i=new Request(n,{method:e.method,headers:e.headers,body:r}),a=await this.processFlow(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return console.error(`Flow error:`,e),t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}getHandlers(){return{GET:(e,t)=>this.handleGet(e,t),POST:(e,t)=>this.handlePost(e,t),webhook:(e,t)=>this.autoRoute(e,t),flow:(e,t)=>this.handleFlow(e,t),processor:this.webhookProcessor}}};const Ir=new Map;function Lr(e){return`nextjs-page:${e.phoneNumberId??`default`}`}function Rr(e){let t=Lr(e),n=Ir.get(t);if(n)return n;let r=new Fr(e),i={...r.getHandlers(),destroy:()=>{r.webhookProcessor.removeAllHandlers(),Ir.delete(t)}};return Ir.set(t,i),i}function zr(e){switch(e.type){case`text`:return e.text.body;case`image`:return e.image.caption||`[Image]`;case`video`:return e.video.caption||`[Video]`;case`audio`:return e.audio.voice?`[Voice Message]`:`[Audio]`;case`document`:return e.document.caption||e.document.filename||`[Document]`;case`sticker`:return e.sticker.animated?`[Animated Sticker]`:`[Sticker]`;case`interactive`:{let t=e.interactive;return t.type===`button_reply`?t.button_reply.title:t.type===`list_reply`?t.list_reply.title:t.type===`nfm_reply`?t.nfm_reply.body||t.nfm_reply.name||`[Form Reply]`:`[Interactive]`}case`button`:return e.button.text;case`location`:return e.location.name||e.location.address||`📍 ${e.location.latitude}, ${e.location.longitude}`;case`contacts`:{let t=e.contacts.map(e=>e.name.formatted_name);return t.length===1?`👤 ${t[0]}`:`👤 ${t.length} contacts`}case`reaction`:return e.reaction.emoji||`[Reaction removed]`;case`order`:{let t=e.order.product_items.length;return`🛒 Order: ${t} item${t>1?`s`:``}`}case`system`:return e.system.body;case`unsupported`:return`[Unsupported message]`;default:return`[${e.type}]`}}const Br=(e,t)=>R(`generateXHub256Sig`).createHmac(`sha256`,t).update(e,`utf-8`).digest(`hex`),Vr=(e,t)=>an(t,e);function Hr(e){return e.type===`text`}function Ur(e){return e.type===`image`}function Wr(e){return e.type===`video`}function Gr(e){return e.type===`audio`}function Kr(e){return e.type===`document`}function qr(e){return e.type===`sticker`}function Q(e){return e.type===`interactive`}function Jr(e){return e.type===`button`}function Yr(e){return e.type===`location`}function Xr(e){return e.type===`contacts`}function Zr(e){return e.type===`reaction`}function Qr(e){return e.type===`order`}function $r(e){return e.type===`system`}function ei(e){return Q(e)&&e.interactive.type===`button_reply`}function ti(e){return Q(e)&&e.interactive.type===`list_reply`}function ni(e){return Q(e)&&e.interactive.type===`nfm_reply`}function ri(e){return Ur(e)?{id:e.image.id,mimeType:e.image.mime_type,sha256:e.image.sha256,caption:e.image.caption}:Wr(e)?{id:e.video.id,mimeType:e.video.mime_type,sha256:e.video.sha256,caption:e.video.caption}:Gr(e)?{id:e.audio.id,mimeType:e.audio.mime_type,sha256:e.audio.sha256,voice:e.audio.voice}:Kr(e)?{id:e.document.id,mimeType:e.document.mime_type,sha256:e.document.sha256,caption:e.document.caption,filename:e.document.filename}:qr(e)?{id:e.sticker.id,mimeType:e.sticker.mime_type,sha256:e.sticker.sha256,animated:e.sticker.animated}:null}function ii(e){return Q(e)?e.interactive.type===`button_reply`?{type:`button_reply`,id:e.interactive.button_reply.id,title:e.interactive.button_reply.title}:e.interactive.type===`list_reply`?{type:`list_reply`,id:e.interactive.list_reply.id,title:e.interactive.list_reply.title,description:e.interactive.list_reply.description}:e.interactive.type===`nfm_reply`?{type:`nfm_reply`,id:e.interactive.nfm_reply.name,title:e.interactive.nfm_reply.body,responseJson:e.interactive.nfm_reply.response_json}:null:null}function ai(e){return Yr(e)?{latitude:e.location.latitude,longitude:e.location.longitude,name:e.location.name,address:e.location.address,url:e.location.url}:null}function oi(e){return Xr(e)?e.contacts.map(e=>({formattedName:e.name.formatted_name,firstName:e.name.first_name,lastName:e.name.last_name,phones:e.phones?.map(e=>e.phone)||[],emails:e.emails?.map(e=>e.email)||[]})):[]}function si(e){return Zr(e)?{messageId:e.reaction.message_id,emoji:e.reaction.emoji||null}:null}function ci(e){return Qr(e)?{catalogId:e.order.catalog_id,text:e.order.text,items:e.order.product_items.map(e=>({productId:e.product_retailer_id,quantity:e.quantity,price:e.item_price,currency:e.currency}))}:null}const li={Authentication:`AUTHENTICATION`,Marketing:`MARKETING`,Utility:`UTILITY`},ui={Authentication:`authentication`,Service:`service`,Utility:`utility`},di={Approved:`APPROVED`,Pending:`PENDING`,Rejected:`REJECTED`},fi={Get:`GET`,Post:`POST`,Put:`PUT`,Delete:`DELETE`},pi={Audio:`audio`,Contacts:`contacts`,Document:`document`,Image:`image`,Interactive:`interactive`,Location:`location`,Reaction:`reaction`,Sticker:`sticker`,Template:`template`,Text:`text`,Video:`video`,Button:`button`,Order:`order`,System:`system`,Unsupported:`unsupported`,Unknown:`unknown`,Statuses:`statuses`,All:`*`},mi={Action:`ACTION`,CouponCode:`COUPON_CODE`,Currency:`CURRENCY`,DateTime:`DATE_TIME`,Document:`DOCUMENT`,ExpirationTimeMs:`EXPIRATION_TIME_MS`,Image:`IMAGE`,LimitedTimeOffer:`LIMITED_TIME_OFFER`,Location:`LOCATION`,OrderStatus:`ORDER_STATUS`,Payload:`PAYLOAD`,Product:`PRODUCT`,Text:`TEXT`,TtlMinutes:`TTL_MINUTES`,Video:`VIDEO`,WebviewInteraction:`WEBVIEW_INTERACTION`,WebviewPresentation:`WEBVIEW_PRESENTATION`},hi={Button:`button`,List:`list`,Product:`product`,ProductList:`product_list`,CtaUrl:`cta_url`,Carousel:`carousel`,LocationRequest:`location_request_message`,AddressMessage:`address_message`,Flow:`flow`,VoiceCall:`voice_call`},gi={First:1,Second:2,Third:3,Fourth:4,Fifth:5},_i={Catalog:`CATALOG`,CopyCode:`COPY_CODE`,Flow:`FLOW`,Mpm:`MPM`,OrderDetails:`ORDER_DETAILS`,QuickReply:`QUICK_REPLY`,Reminder:`REMINDER`,Url:`URL`,VoiceCall:`VOICE_CALL`},vi={Header:`HEADER`,Body:`BODY`,Button:`BUTTON`,Footer:`FOOTER`},yi={BusinessInitiated:`business_initiated`,CustomerInitiated:`customer_initiated`,ReferralConversion:`referral_conversion`},bi={Delivered:`delivered`,Read:`read`,Sent:`sent`},xi={Mp4:`video/mp4`,Threegp:`video/3gp`},Si={Webp:`image/webp`},Ci={Jpeg:`image/jpeg`,Png:`image/png`},wi={Text:`text/plain`,Pdf:`application/pdf`,Ppt:`application/vnd.ms-powerpoint`,Word:`application/msword`,Excel:`application/vnd.ms-excel`,OpenDoc:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,OpenPres:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,OpenSheet:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`},Ti={Aac:`audio/aac`,Mp4:`audio/mp4`,Mpeg:`audio/mpeg`,Amr:`audio/amr`,Ogg:`audio/ogg`},Ei={Audio:`audio`,Button:`button`,Document:`document`,Text:`text`,Image:`image`,Interactive:`interactive`,Order:`order`,Sticker:`sticker`,System:`system`,Unknown:`unknown`,Video:`video`},Di={CustomerChangedNumber:`customer_changed_number`,CustomerIdentityChanged:`customer_identity_changed`,UserChangedNumber:`user_changed_number`,UserIdentityChanged:`user_identity_changed`,UserChangedUserId:`user_changed_user_id`},Oi={Ad:`ad`,Post:`post`},ki={Sms:`SMS`,Voice:`VOICE`},Ai={Afrikaans:`af`,Albanian:`sq`,Arabic:`ar`,Azerbaijani:`az`,Bengali:`bn`,Bulgarian:`bg`,Catalan:`ca`,Chinese_CHN:`zh_CN`,Chinese_HKG:`zh_HK`,Chinese_TAI:`zh_TW`,Croatian:`hr`,Czech:`cs`,Danish:`da`,Dutch:`nl`,English:`en`,English_UK:`en_GB`,English_US:`en_US`,Estonian:`et`,Filipino:`fil`,Finnish:`fi`,French:`fr`,Georgian:`ka`,German:`de`,Greek:`el`,Gujarati:`gu`,Hausa:`ha`,Hebrew:`he`,Hindi:`hi`,Hungarian:`hu`,Indonesian:`id`,Irish:`ga`,Italian:`it`,Japanese:`ja`,Kannada:`kn`,Kazakh:`kk`,Kinyarwanda:`rw_RW`,Korean:`ko`,Kyrgyz_Kyrgyzstan:`ky_KG`,Lao:`lo`,Latvian:`lv`,Lithuanian:`lt`,Macedonian:`mk`,Malay:`ms`,Malayalam:`ml`,Marathi:`mr`,Norwegian:`nb`,Persian:`fa`,Polish:`pl`,Portuguese_BR:`pt_BR`,Portuguese_POR:`pt_PT`,Punjabi:`pa`,Romanian:`ro`,Russian:`ru`,Serbian:`sr`,Slovak:`sk`,Slovenian:`sl`,Spanish:`es`,Spanish_ARG:`es_AR`,Spanish_SPA:`es_ES`,Spanish_MEX:`es_MX`,Swahili:`sw`,Swedish:`sv`,Tamil:`ta`,Telugu:`te`,Thai:`th`,Turkish:`tr`,Ukrainian:`uk`,Urdu:`ur`,Uzbek:`uz`,Vietnamese:`vi`,Zulu:`zu`},ji={AU:`AU`,ID:`ID`,IN:`IN`,JP:`JP`,SG:`SG`,KR:`KR`,DE:`DE`,CH:`CH`,GB:`GB`,BR:`BR`,BH:`BH`,ZA:`ZA`,AE:`AE`,CA:`CA`},Mi=3600*1e3,Ni=24*Mi,Pi=72*Mi,Fi=168*Mi,Ii=1e11;function $(e,t){let n;if(e instanceof Date)n=e.getTime();else if(typeof e==`number`)n=Math.abs(e)<Ii?e*1e3:e;else if(typeof e==`string`){let t=e.trim();if(/^\d+(\.\d+)?$/.test(t)){let e=Number(t);n=e<Ii?e*1e3:e}else n=t===``?NaN:Date.parse(t)}else n=NaN;if(!Number.isFinite(n)||!Number.isFinite(new Date(n).getTime()))throw new E(`${t} is not a valid timestamp: ${String(e)}`);return n}function Li(e,t,n){if(e===void 0)return n;if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw new E(`${t} must be a non-negative number of milliseconds`);return e}function Ri(e,t,n,r){if(!Number.isFinite(new Date(t).getTime()))throw new E(`Window expiry is outside the supported timestamp range`);let i=Math.max(0,t-e),a=t-r,o=Math.min(Math.max(0,a-n),i);return{isOpen:o>0,expiresAt:new Date(t),remainingMs:o}}const zi=Object.freeze({isOpen:!1,expiresAt:null,remainingMs:0});function Bi(e,t={}){let n=Li(t.safetyMarginMs,`safetyMarginMs`,0),r=t.now===void 0?Date.now():$(t.now,`now`);if(e==null)return{...zi};let i=$(e,`lastInboundAt`);return Ri(i,i+Ni,r,n)}function Vi(e,t={}){return Bi(e,t).isOpen}function Hi(e,t={}){let n=Li(t.safetyMarginMs,`safetyMarginMs`,0),r=Li(t.durationMs,`durationMs`,Pi),i=t.now===void 0?Date.now():$(t.now,`now`);if(e==null)return{...zi};let a=$(e,`openedAt`);return Ri(a,t.expiresAt===void 0?a+r:$(t.expiresAt,`expiresAt`),i,n)}export{he as AUTHORIZATION_ERROR_CODES,Ti as AudioMediaTypes,ie as AudioMediaTypesEnum,be as BLOCK_USER_ERROR_CODES,rt as BlockUsersApi,it as BusinessApi,wt as BusinessProfileApi,fe as BusinessVerticalEnum,gi as ButtonPosition,d as ButtonPositionEnum,xe as CALLING_ERROR_CODES,Ni as CUSTOMER_SERVICE_WINDOW_MS,at as CallingApi,li as Category,i as CategoryEnum,ot as CommerceApi,vi as ComponentType,p as ComponentTypesEnum,st as ContactBookApi,yi as ConversationTypes,h as ConversationTypesEnum,ue as CurrencyCodesEnum,ji as DataLocalizationRegion,de as DataLocalizationRegionEnum,wi as DocumentMediaTypes,re as DocumentMediaTypesEnum,ct as EncryptionApi,ye as FLOW_ERROR_CODES,Pi as FREE_ENTRY_POINT_WINDOW_MS,ft as FlowActionEnum,lt as FlowApi,dt as FlowCategoryEnum,ut as FlowStatusEnum,pt as FlowTypeEnum,Se as GROUP_ERROR_CODES,mt as GroupsApi,fi as HttpMethods,s as HttpMethodsEnum,_e as INTEGRITY_ERROR_CODES,Ci as ImageMediaTypes,ne as ImageMediaTypesEnum,hi as InteractiveTypes,u as InteractiveTypesEnum,Ai as Languages,le as LanguagesEnum,N as Logger,Fi as MAX_FREE_ENTRY_POINT_WINDOW_MS,ht as MarketingMessagesApi,gt as MediaApi,Pn as MemoryDedupeStore,k as MessageApi,k as MessagesApi,ui as MessageCategory,a as MessageCategoryEnum,bt as MessageHistoryApi,pi as MessageTypes,c as MessageTypesEnum,mi as ParametersTypes,l as ParametersTypesEnum,xt as PaymentsApi,St as PhoneNumberApi,Tt as QrCodeApi,Oi as ReferralSourceTypes,se as ReferralSourceTypesEnum,Et as RegistrationApi,ki as RequestCodeMethods,ce as RequestCodeMethodsEnum,ve as SEND_MESSAGE_ERROR_CODES,Dt as SolutionsApi,bi as Status,g as StatusEnum,Si as StickerMediaTypes,te as StickerMediaTypesEnum,_i as SubType,f as SubTypeEnum,Di as SystemChangeTypes,oe as SystemChangeTypesEnum,ge as THROTTLING_ERROR_CODES,Bt as TemplateApi,di as TemplateStatus,o as TemplateStatusEnum,Ht as ThreadControlApi,Ut as TwoStepVerificationApi,xi as VideoMediaTypes,ee as VideoMediaTypesEnum,pe as WHATSAPP_ERROR_CODES,Gt as WabaAccountReviewStatus,qt as WabaAccountStatus,Wt as WabaApi,Jt as WabaBusinessVerificationStatus,m as WabaConfigEnum,Kt as WabaHealthStatusCanSendMessage,Z as WebhookProcessor,Ei as WebhookTypes,ae as WebhookTypesEnum,Nn as WhatsApp,Nn as default,b as WhatsAppApiError,Be as WhatsAppAuthorizationError,S as WhatsAppBlockUserError,C as WhatsAppCallingError,y as WhatsAppError,Ue as WhatsAppFlowError,w as WhatsAppGroupError,Ve as WhatsAppIntegrityError,We as WhatsAppNetworkError,He as WhatsAppSendMessageError,x as WhatsAppThrottlingError,Ge as WhatsAppUnknownError,E as WhatsAppValidationError,Ct as buildFieldsQueryString,Vi as canSendFreeformMessage,tr as constructFullUrl,Mt as createAuthenticationTemplate,Nt as createCatalogTemplate,Pt as createCouponTemplate,Ft as createLimitedTimeOfferTemplate,Lt as createMPMTemplate,It as createMediaCardCarouselTemplate,jt as createOTPTemplate,Rt as createProductCardCarouselTemplate,zt as createSPMTemplate,At as createTemplate,T as createWhatsAppApiError,fn as decryptFlowRequest,_n as decryptFlowRequestAsync,pn as encryptFlowResponse,vn as encryptFlowResponseAsync,pr as expressWebhookHandler,zr as extractMessageText,Sr as fastifyWebhookHandler,ln as formatConfigTable,dn as generateEncryption,Br as generateXHub256Sig,Vr as generateXHub256SigAsync,oi as getContactsInfo,Bi as getCustomerServiceWindow,Hi as getFreeEntryPointWindow,ii as getInteractiveReply,ai as getLocationInfo,ri as getMediaInfo,ci as getOrderInfo,si as getReactionInfo,kr as honoWebhookHandler,v as isApiPermissionErrorCode,Gr as isAudioMessage,Me as isAuthorizationErrorCode,Le as isBlockUserErrorCode,Jr as isButtonMessage,ei as isButtonReply,Re as isCallingErrorCode,Xr as isContactsMessage,Kr as isDocumentMessage,zn as isFlowDataExchangeRequest,Ie as isFlowErrorCode,Bn as isFlowErrorRequest,Vn as isFlowPingRequest,ze as isGroupErrorCode,Ur as isImageMessage,Pe as isIntegrityErrorCode,Q as isInteractiveMessage,ti as isListReply,Yr as isLocationMessage,D as isMetaError,ni as isNfmReply,Qr as isOrderMessage,Zr as isReactionMessage,Fe as isSendMessageErrorCode,qr as isStickerMessage,$r as isSystemMessage,Hr as isTextMessage,Ne as isThrottlingErrorCode,er as isValidWebhookSignature,Wr as isVideoMessage,Ke as isWhatsAppApiErrorResponse,qe as isWhatsAppAuthorizationError,Qe as isWhatsAppBlockUserError,$e as isWhatsAppCallingError,je as isWhatsAppErrorCode,Ze as isWhatsAppFlowError,et as isWhatsAppGroupError,Ye as isWhatsAppIntegrityError,Xe as isWhatsAppSendMessageError,Je as isWhatsAppThrottlingError,Nr as nextjsAppWebhookHandler,Rr as nextjsPagesWebhookHandler,tt as normalizeMetaError,_ as objectToQueryString,wn as parseRateLimitHeaders,Cn as parseRetryAfter,Qn as processFlowRequest,Yn as processWebhookMessages,$n as verifyWebhookSignature};
22
+ `)}function jn(){return`3.9.1`}function Mn(){return`WhatsApp-Nodejs-SDK/${jn()} (${Xt()})`}const q=new N(`WHATSAPP`,I());var Nn=class{config;requester;blockUsers;business;calling;commerce;contactBook;groups;marketingMessages;messageHistory;messages;media;payments;phoneNumbers;solutions;threadControl;twoStepVerification;flows;businessProfile;templates;encryption;qrCode;registration;waba;constructor(e){An(),this.config=cn(e),this.requester=new kn(this.config.CLOUD_API_VERSION,this.config.WA_PHONE_NUMBER_ID,this.config.CLOUD_API_ACCESS_TOKEN,this.config.WA_BUSINESS_ACCOUNT_ID,this.getUserAgent(),this.config.retry,this.config.onRateLimitInfo),this.blockUsers=new rt(this.config,this.requester),this.business=new it(this.config,this.requester),this.calling=new at(this.config,this.requester),this.commerce=new ot(this.config,this.requester),this.contactBook=new st(this.config,this.requester),this.groups=new mt(this.config,this.requester),this.marketingMessages=new ht(this.config,this.requester),this.messageHistory=new bt(this.config,this.requester),this.messages=new k(this.config,this.requester),this.media=new gt(this.config,this.requester),this.payments=new xt(this.config,this.requester),this.phoneNumbers=new St(this.config,this.requester),this.solutions=new Dt(this.config,this.requester),this.threadControl=new Ht(this.config,this.requester),this.twoStepVerification=new Ut(this.config,this.requester),this.flows=new lt(this.config,this.requester),this.businessProfile=new wt(this.config,this.requester),this.templates=new Bt(this.config,this.requester),this.encryption=new ct(this.config,this.requester),this.qrCode=new Tt(this.config,this.requester),this.registration=new Et(this.config,this.requester),this.waba=new Wt(this.config,this.requester),q.log(`\n${ln(this.config)}`)}updateTimeout(e){this.config.REQUEST_TIMEOUT=e,this.requester.updateTimeout(e),q.log(`Timeout updated to ${e}ms`)}updateSenderNumberId(e){this.config.WA_PHONE_NUMBER_ID=e,q.log(`Sender number ID updated to ${e}`)}updateAccessToken(e){this.config.CLOUD_API_ACCESS_TOKEN=e,this.requester.updateAccessToken(e),q.log(`Access token updated`)}getLastRateLimitInfo(){return this.requester.getLastRateLimitInfo()}version(){return jn()}static get Enums(){return r}getUserAgent(){return Mn()}generateEncryption(e){return dn(e||this.config.FLOW_API_PASSPHRASE)}},Pn=class{maxEntries;entries=new Map;constructor(e={}){let t=e.maxEntries??1e4;if(!Number.isInteger(t)||t<1)throw Error(`MemoryDedupeStore maxEntries must be a positive integer, got ${t}`);this.maxEntries=t}async has(e){return this.lookup(e,Date.now())!==void 0}async setIfAbsent(e,t){let n=Date.now(),r=this.lookup(e,n);return r===void 0?(this.entries.set(e,n+t*1e3),this.evict(n),!0):(this.entries.delete(e),this.entries.set(e,r),!1)}get size(){return this.entries.size}clear(){this.entries.clear()}lookup(e,t){let n=this.entries.get(e);if(n!==void 0){if(n<=t){this.entries.delete(e);return}return n}}evict(e){for(let[t,n]of this.entries)n<=e&&this.entries.delete(t);for(let e of this.entries.keys()){if(this.entries.size<=this.maxEntries)break;this.entries.delete(e)}}};function Fn(e){if(!e)return;let t=e===!0?{}:e,n=t.ttlSeconds??86400;if(!Number.isFinite(n)||n<=0)throw Error(`dedupe.ttlSeconds must be a positive number, got ${n}`);return{store:t.store??new Pn,ttlSeconds:n}}function In(e){return typeof e==`object`&&!!e}function J(e){return typeof e==`string`}const Ln=[`data_exchange`,`INIT`,`BACK`],Rn=[`data_exchange`,`INIT`];function zn(e){if(!(`flow_token`in e&&J(e.flow_token)&&`action`in e))return!1;let{action:t,version:n,screen:r,data:i}=e,a=n===`3.0`,o=Ln.includes(t),s=r===void 0||J(r)&&r!==`SUCCESS`,c=t===`data_exchange`||In(i);return a&&o&&s&&c}function Bn(e){if(!(`flow_token`in e&&J(e.flow_token)&&`action`in e))return!1;let{action:t,screen:n,data:r}=e,i=Rn.includes(t),a=J(n),o=In(r)&&`error_key`in r&&J(r.error)&&`error_message`in r&&J(r.error_message);return i&&a&&o}function Vn(e){return`action`in e&&e.action===`ping`}const Y=new N(`WEBHOOK_UTILS`,I()),Hn={account_update:`accountUpdateHandler`,account_review_update:`accountReviewUpdateHandler`,account_alerts:`accountAlertsHandler`,account_settings_update:`accountSettingsUpdateHandler`,automatic_events:`automaticEventsHandler`,business_capability_update:`businessCapabilityUpdateHandler`,business_status_update:`businessStatusUpdateHandler`,business_username_updates:`businessUsernameUpdatesHandler`,calls:`callsHandler`,flows:`flowsHandler`,group_lifecycle_update:`groupLifecycleUpdateHandler`,group_participants_update:`groupParticipantsUpdateHandler`,group_settings_update:`groupSettingsUpdateHandler`,group_status_update:`groupStatusUpdateHandler`,history:`historyHandler`,message_echoes:`messageEchoesHandler`,message_template_components_update:`messageTemplateComponentsUpdateHandler`,message_template_quality_update:`messageTemplateQualityUpdateHandler`,message_template_status_update:`messageTemplateStatusUpdateHandler`,messaging_handovers:`messagingHandoversHandler`,partner_solutions:`partnerSolutionsHandler`,payment_configuration_update:`paymentConfigurationUpdateHandler`,phone_number_name_update:`phoneNumberNameUpdateHandler`,phone_number_quality_update:`phoneNumberQualityUpdateHandler`,security:`securityHandler`,smb_app_state_sync:`smbAppStateSyncHandler`,smb_message_echoes:`smbMessageEchoesHandler`,standby:`standbyHandler`,template_category_update:`templateCategoryUpdateHandler`,template_correct_category_detection:`templateCorrectCategoryDetectionHandler`,tracking_events:`trackingEventsHandler`,user_preferences:`userPreferencesHandler`};function Un(e){return Object.hasOwn(Hn,e)}const Wn={calls:e=>Kn(`calls`,Gn(e?.calls,e=>e?.id?`${e.id}:${e.event}${e.call_status?`:${e.call_status}`:``}`:void 0)),smb_message_echoes:e=>Kn(`smb_message_echoes`,Gn(e?.message_echoes,e=>e?.id)),message_echoes:e=>Kn(`message_echoes`,Gn(e?.messaging,e=>e?.message?.mid))};function Gn(e,t){return Array.isArray(e)?e.map(t):void 0}function Kn(e,t){if(!(!t||t.length===0||t.some(e=>!e)))return`${e}:${t.join(`,`)}`}function qn(e,t){let n=Wn[e];return n?.(t)}async function Jn(e,t){if(!e||!t)return!1;try{return await e.store.setIfAbsent(t,e.ttlSeconds)?!1:(Y.log(`Skipping duplicate webhook delivery: ${t}`),!0)}catch(e){return Y.error(`Dedupe store failed; processing the webhook anyway:`,{key:t,error:e}),!1}}async function Yn(e,t,n,r={}){try{let i=await e.text();if(r.verifySignature){if(!r.appSecret)return Y.error(`verifyWebhookSignature is on but appSecret is not configured; rejecting webhook`),new Response(JSON.stringify({error:`Webhook signature verification misconfigured`}),{status:500,headers:{"Content-Type":`application/json`}});if(!await $n(i,e.headers.get(`x-hub-signature-256`),r.appSecret))return Y.warn(`Rejected webhook with missing or invalid X-Hub-Signature-256`),new Response(JSON.stringify({error:`Invalid signature`}),{status:401,headers:{"Content-Type":`application/json`}})}let a=JSON.parse(i),o={headers:e.headers,rawBody:i,method:e.method,url:e.url},s=r.dedupe?{store:r.dedupe.store,ttlSeconds:r.dedupe.ttlSeconds??86400}:void 0;if(n.rawHandler){let{rawHandler:e,rawHandlerFields:r}=n,i=a;if(r&&r.length>0){let e={...i,entry:i.entry.map(e=>({...e,changes:e.changes.filter(e=>r.includes(e.field))})).filter(e=>e.changes.length>0)};i=e.entry.length===0?null:e}i&&await e(t,i,o)}if(a.object!==`whatsapp_business_account`){let e=`Received webhook for non-WhatsApp event`;return Y.warn(e),new Response(JSON.stringify({error:e}),{status:404})}let c=[];for(let e of a.entry)try{let r=e.changes;for(let i of r){let r=i.field;if(r===`messages`)await rr(e.id,i.value,t,n,o,s);else if(Un(r)){let a=n.fieldHandlers?.get(r)??n[Hn[r]];await sr(e.id,{field:r,value:i.value},a,t,o,s)}else Y.warn(`Unhandled webhook field: ${i.field}`)}}catch(t){let n=`Error processing webhook: ${t}`;Y.error(n,{entry:e,error:t}),c.push(n)}return new Response(c.length>0?JSON.stringify({errors:c}):null,{status:200})}catch(e){return Y.error(`Error processing webhook:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500})}}function Xn(){return{version:`3.0`,data:{status:`active`}}}function Zn(){return{data:{acknowledged:!0}}}async function Qn(e,t,n,r){try{let i=await e.text(),a={headers:e.headers,rawBody:i,method:e.method,url:e.url},o=e.headers.get(`x-hub-signature-256`),s=t.M4D_APP_SECRET||t.WEBHOOK_VERIFICATION_TOKEN||``;if(t.M4D_APP_SECRET||Y.warn(`appSecret not configured; verifying Flow signature with the webhook verification token`),!await $n(i,o,s))return Y.warn(`Invalid request signature`),new Response(JSON.stringify({error:`Unauthorized`}),{status:401});let{decryptedBody:c,aesKeyBuffer:l,initialVectorBuffer:u}=await _n(JSON.parse(i),t),d=Vn(c),f=Bn(c),p=zn(c),m;m=d?`ping`:f?`error`:p?`data_exchange`:`*`;let h=r.get(m);if(!h){if(m===`ping`)h=()=>Xn();else if(m===`error`)h=()=>Zn();else if(h=r.get(`*`),!h)return Y.warn(`No handler registered for flow type:`,{flowType:m,action:c.action}),new Response(JSON.stringify({error:`Handler not found`}),{status:404})}let g=await h(n,c,a);if(f){Y.warn(`Flow error notification received`,{error:c.data});let e=g||Zn();return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":`application/json`}})}if(d||p){let e=await vn(g,l,u);return new Response(e,{status:200,headers:{"Content-Type":`text/plain`}})}return Y.warn(`Unknown flow request type:`,c),new Response(JSON.stringify({error:`Unknown request type`}),{status:400})}catch(e){return Y.error(`Error handling flow request:`,e),new Response(JSON.stringify({error:`Internal server error`}),{status:500})}}async function $n(e,t,n){if(!t||!n)return!1;let r=t.startsWith(`sha256=`)?t.slice(7):t,i=await an(n,e);return rn(r.toLowerCase(),i)}function er(e,t,n){if(!t||!n)return!1;let r=R(`isValidWebhookSignature`),i=t.startsWith(`sha256=`)?t.slice(7):t,a=r.createHmac(`sha256`,n).update(e,`utf8`).digest(`hex`);return rn(i.toLowerCase(),a)}function tr(e,t){return`${e[`x-forwarded-proto`]||`http`}://${e.host||`localhost`}${t||`/`}`}function nr(e){return e.id?e.id:(e.type===`interactive`||e.type===`button`)&&`context`in e&&e.context?.id?e.context.id:``}async function rr(e,t,n,r,i,a){let o=t.metadata,s=e,c=o.display_phone_number,l=o.phone_number_id;if(`user_actions`in t&&t.user_actions){let e=t;for(let t of e.user_actions){let e={wabaId:s,phoneNumberId:l,displayPhoneNumber:c,action:t};await or(r.userActionHandler,n,e,i)}return}if(`statuses`in t&&t.statuses){let e=t;for(let t of e.statuses){if(!r.statusHandler||await Jn(a,t.id?`status:${t.id}:${t.status}`:void 0))continue;let e={wabaId:s,phoneNumberId:l,displayPhoneNumber:c,status:t};await ar(r.statusHandler,n,e,i)}return}if(`messages`in t&&t.messages){let e=t,o=e.contacts?.[0]?.profile?.name||``;for(let t of e.messages){let u={wabaId:s,phoneNumberId:l,displayPhoneNumber:c,profileName:o,message:t,messageId:nr(t),...e.conversation_context&&{conversationContext:e.conversation_context}},d=t.type,f=r.messageHandlers.get(d);!r.preProcessHandler&&!f&&!r.postProcessHandler||await Jn(a,u.messageId?`message:${u.messageId}`:void 0)||(await ir(r.preProcessHandler,n,u,i,`pre-process`),await ir(f,n,u,i,d),await ir(r.postProcessHandler,n,u,i,`post-process`))}}}async function ir(e,t,n,r,i){if(e)try{await e(t,n,r)}catch(e){Y.error(`Error in ${i} handler:`,{error:e,messageId:n.messageId})}}async function ar(e,t,n,r){if(e)try{await e(t,n,r)}catch(e){Y.error(`Error in status handler:`,{error:e,statusId:n.status.id})}}async function or(e,t,n,r){if(e)try{await e(t,n,r)}catch(e){Y.error(`Error in user action handler:`,{error:e,actionType:n.action.action_type})}}async function sr(e,t,n,r,i,a){if(n&&!await Jn(a,qn(t.field,t.value)))try{await n(r,{wabaId:e,value:t.value},i)}catch(n){Y.error(`Error in ${t.field} handler:`,{error:n,wabaId:e})}}const X=new N(`WEBHOOK_PROCESSOR`,I());function cr(e,t){if(e===`messages`)throw Error(`${t}('messages') is not supported. Use onMessage/onText/... for messages, onStatus for statuses and onUserAction for marketing user actions.`);if(!Un(e))throw Error(`${t}('${e}'): unknown webhook field`)}var Z=class{config;client;messageHandlers=new Map;statusHandler=void 0;userActionHandler=void 0;preProcessHandler=void 0;postProcessHandler=void 0;rawHandler=void 0;flowHandlers=new Map;fieldHandlers=new Map;verifySignature;dedupe;constructor(e){this.config=cn(e),this.verifySignature=e.verifyWebhookSignature===!0,this.dedupe=Fn(e.dedupe),this.client=new Nn(e),X.log(`WebhookProcessor instantiated`)}async processVerification(e,t,n){return e===`subscribe`&&t===this.config.WEBHOOK_VERIFICATION_TOKEN?{status:200,body:n||``,headers:{"Content-Type":`text/plain`}}:{status:403,body:JSON.stringify({error:`Forbidden`}),headers:{"Content-Type":`application/json`}}}async processWebhook(e){try{let t=await Yn(e,this.client,{messageHandlers:this.messageHandlers,statusHandler:this.statusHandler,userActionHandler:this.userActionHandler,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler,rawHandler:this.rawHandler?.handler,rawHandlerFields:this.rawHandler?.fields,fieldHandlers:this.fieldHandlers},{appSecret:this.config.M4D_APP_SECRET,verifySignature:this.verifySignature,dedupe:this.dedupe}),n=await t.text(),r=t.headers.get(`content-type`)||`application/json`;return{status:t.status,body:n,headers:{"Content-Type":r}}}catch(e){return X.log(`Error processing webhook: ${e}`),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async processFlow(e){try{let t=await Qn(e,this.config,this.client,this.flowHandlers),n=await t.text(),r=t.headers.get(`content-type`)||`text/plain`;return{status:t.status,body:n,headers:{"Content-Type":r}}}catch(e){return X.log(`Error processing flow: ${e}`),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}onMessage(e,t){if(e===`statuses`)throw Error(`MessageTypesEnum.Statuses is deprecated. Use onStatus(handler) instead of onMessage(MessageTypesEnum.Statuses, handler)`);this.messageHandlers.set(e,t),X.log(`Registered message handler for ${e}`)}onStatus(e){this.statusHandler=e,X.log(`Registered status handler`)}onUserAction(e){this.userActionHandler=e,X.log(`Registered user action handler`)}onMessagePreProcess(e){this.preProcessHandler=e,X.log(`Registered pre-process handler`)}onMessagePostProcess(e){this.postProcessHandler=e,X.log(`Registered post-process handler`)}onRaw(e,t){this.rawHandler={handler:e,fields:t},X.log(`Registered raw webhook handler${t?` for fields: ${t.join(`, `)}`:``}`)}onFlow(e,t){this.flowHandlers.set(e,t),X.log(`Registered flow handler for ${e}`)}on(e,t){cr(e,`on`),this.fieldHandlers.set(e,t),X.log(`Registered ${e} handler`)}off(e){cr(e,`off`),this.fieldHandlers.delete(e),X.log(`Removed ${e} handler`)}onText(e){this.messageHandlers.set(`text`,e),X.log(`Registered text message handler`)}onImage(e){this.messageHandlers.set(`image`,e),X.log(`Registered image message handler`)}onVideo(e){this.messageHandlers.set(`video`,e),X.log(`Registered video message handler`)}onAudio(e){this.messageHandlers.set(`audio`,e),X.log(`Registered audio message handler`)}onDocument(e){this.messageHandlers.set(`document`,e),X.log(`Registered document message handler`)}onSticker(e){this.messageHandlers.set(`sticker`,e),X.log(`Registered sticker message handler`)}onInteractive(e){this.messageHandlers.set(`interactive`,e),X.log(`Registered interactive message handler`)}onButton(e){this.messageHandlers.set(`button`,e),X.log(`Registered button message handler`)}onLocation(e){this.messageHandlers.set(`location`,e),X.log(`Registered location message handler`)}onContacts(e){this.messageHandlers.set(`contacts`,e),X.log(`Registered contacts message handler`)}onReaction(e){this.messageHandlers.set(`reaction`,e),X.log(`Registered reaction message handler`)}onOrder(e){this.messageHandlers.set(`order`,e),X.log(`Registered order message handler`)}onSystem(e){this.messageHandlers.set(`system`,e),X.log(`Registered system message handler`)}onAccountUpdate(e){this.on(`account_update`,e)}onAccountReviewUpdate(e){this.on(`account_review_update`,e)}onAccountAlerts(e){this.on(`account_alerts`,e)}onBusinessCapabilityUpdate(e){this.on(`business_capability_update`,e)}onPhoneNumberNameUpdate(e){this.on(`phone_number_name_update`,e)}onPhoneNumberQualityUpdate(e){this.on(`phone_number_quality_update`,e)}onMessageTemplateStatusUpdate(e){this.on(`message_template_status_update`,e)}onTemplateCategoryUpdate(e){this.on(`template_category_update`,e)}onMessageTemplateQualityUpdate(e){this.on(`message_template_quality_update`,e)}onFlows(e){this.on(`flows`,e)}onSecurity(e){this.on(`security`,e)}onHistory(e){this.on(`history`,e)}onSmbMessageEchoes(e){this.on(`smb_message_echoes`,e)}onSmbAppStateSync(e){this.on(`smb_app_state_sync`,e)}onAccountSettingsUpdate(e){this.on(`account_settings_update`,e)}onAutomaticEvents(e){this.on(`automatic_events`,e)}onBusinessStatusUpdate(e){this.on(`business_status_update`,e)}onBusinessUsernameUpdates(e){this.on(`business_username_updates`,e)}onCalls(e){this.on(`calls`,e)}onGroupLifecycleUpdate(e){this.on(`group_lifecycle_update`,e)}onGroupParticipantsUpdate(e){this.on(`group_participants_update`,e)}onGroupSettingsUpdate(e){this.on(`group_settings_update`,e)}onGroupStatusUpdate(e){this.on(`group_status_update`,e)}onMessageEchoes(e){this.on(`message_echoes`,e)}onMessageTemplateComponentsUpdate(e){this.on(`message_template_components_update`,e)}onMessagingHandovers(e){this.on(`messaging_handovers`,e)}onPartnerSolutions(e){this.on(`partner_solutions`,e)}onPaymentConfigurationUpdate(e){this.on(`payment_configuration_update`,e)}onStandby(e){this.on(`standby`,e)}onTemplateCorrectCategoryDetection(e){this.on(`template_correct_category_detection`,e)}onTrackingEvents(e){this.on(`tracking_events`,e)}onUserPreferences(e){this.on(`user_preferences`,e)}offMessage(e){this.messageHandlers.delete(e),X.log(`Removed message handler for ${e}`)}offMessagePreProcess(){this.preProcessHandler=void 0,X.log(`Removed pre-process handler`)}offMessagePostProcess(){this.postProcessHandler=void 0,X.log(`Removed post-process handler`)}offStatus(){this.statusHandler=void 0,X.log(`Removed status handler`)}offUserAction(){this.userActionHandler=void 0,X.log(`Removed user action handler`)}offRaw(){this.rawHandler=void 0,X.log(`Removed raw webhook handler`)}offFlow(e){this.flowHandlers.delete(e),X.log(`Removed flow handler for ${e}`)}removeAllHandlers(){this.messageHandlers.clear(),this.statusHandler=void 0,this.userActionHandler=void 0,this.preProcessHandler=void 0,this.postProcessHandler=void 0,this.rawHandler=void 0,this.flowHandlers.clear(),this.fieldHandlers.clear(),X.log(`Removed all handlers`)}getClient(){return this.client}getConfig(){return this.config}},lr=class{processor;constructor(e){this.processor=new Z(e)}async processVerification(e,t,n){return await this.processor.processVerification(e,t,n)}async processWebhook(e){return await this.processor.processWebhook(e)}async processFlow(e){return await this.processor.processFlow(e)}constructFullUrl(e,t=``){return tr(e,t)}applyHeaders(e,t){t.setHeader&&Object.entries(e.headers).forEach(([e,n])=>{t.setHeader?.(e,n)})}async autoRoute(e,t,...n){switch(e.method?.toUpperCase()){case`GET`:return await this.handleGet(e,t,...n);case`POST`:return await this.handlePost(e,t,...n);default:if(t.status&&t.json)return t.status(405).json({error:`Method Not Allowed`});throw Error(`Method Not Allowed`)}}get webhookProcessor(){return this.processor}},ur=class extends lr{async handleGet(e,t,n){try{let{"hub.mode":n,"hub.verify_token":r,"hub.challenge":i}=e.query,a=await this.processVerification(n||null,r||null,i||null);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return n(e),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async handlePost(e,t,n){try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody??(e.method===`POST`?JSON.stringify(e.body):void 0),i=new globalThis.Request(n,{method:e.method,headers:e.headers,body:r}),a=await this.processWebhook(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return n(e),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async handleFlow(e,t,n){try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody??(e.method===`POST`?JSON.stringify(e.body):void 0),i=new globalThis.Request(n,{method:e.method,headers:e.headers,body:r}),a=await this.processFlow(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return n(e),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}getHandlers(){return{GET:(e,t,n)=>this.handleGet(e,t,n),POST:(e,t,n)=>this.handlePost(e,t,n),webhook:(e,t,n)=>this.autoRoute(e,t,n),flow:(e,t,n)=>this.handleFlow(e,t,n),processor:this.webhookProcessor}}};const dr=new Map;function fr(e){return`express:${e.phoneNumberId??`default`}`}function pr(e){let t=fr(e),n=dr.get(t);if(n)return n;let r=new ur(e),i={...r.getHandlers(),destroy:()=>{r.webhookProcessor.removeAllHandlers(),dr.delete(t)}};return dr.set(t,i),i}const mr=new Map;function hr(e){return`fastify:${e.phoneNumberId??`default`}`}function gr(e,t){e.code(t.status);for(let[n,r]of Object.entries(t.headers))e.header(n,r);return e.send(t.body)}function _r(e){return e.code(500).header(`Content-Type`,`application/json`).send(JSON.stringify({error:`Internal Server Error`}))}function vr(e,t){if(typeof e!=`object`||!e)return null;let n=e[t];return Array.isArray(n)?typeof n[0]==`string`?n[0]:null:typeof n==`string`?n:null}function yr(e){let t=new Headers;for(let[n,r]of Object.entries(e))r!==void 0&&(n===`content-length`||n===`transfer-encoding`||t.set(n,Array.isArray(r)?r.join(`, `):r));return t}function br(e){if(e.rawBody!==void 0)return e.rawBody;if(!(e.body===void 0||e.body===null))return typeof e.body==`string`?e.body:JSON.stringify(e.body)}function xr(e){let t=e.method===`GET`||e.method===`HEAD`?void 0:br(e);return new Request(tr(e.headers,e.url),{method:e.method,headers:yr(e.headers),body:t})}function Sr(e){let t=hr(e),n=mr.get(t);if(n)return n;let r=Cr(e,t);return mr.set(t,r),r}function Cr(e,t){let n=new Z(e),r=async(e,t)=>{try{return gr(t,await n.processVerification(vr(e.query,`hub.mode`),vr(e.query,`hub.verify_token`),vr(e.query,`hub.challenge`)))}catch(e){return console.error(`Webhook verification error:`,e),_r(t)}},i=async(e,t)=>{try{return gr(t,await n.processWebhook(xr(e)))}catch(e){return console.error(`Webhook processing error:`,e),_r(t)}};return{GET:r,POST:i,webhook:async(e,t)=>{switch(e.method.toUpperCase()){case`GET`:return r(e,t);case`POST`:return i(e,t);default:return t.code(405).header(`Content-Type`,`application/json`).header(`Allow`,`GET, POST`).send(JSON.stringify({error:`Method Not Allowed`}))}},flow:async(e,t)=>{try{return gr(t,await n.processFlow(xr(e)))}catch(e){return console.error(`Flow processing error:`,e),_r(t)}},processor:n,destroy:()=>{n.removeAllHandlers(),mr.delete(t)}}}const wr=new Map;function Tr(e){return`hono:${e.phoneNumberId??`default`}`}function Er(e){return new Response(e.body,{status:e.status,headers:e.headers})}function Dr(){return new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}async function Or(e){let t=e.req.raw;return!t.bodyUsed||!e.req.text?t:new Request(t.url,{method:t.method,headers:t.headers,body:await e.req.text()})}function kr(e){let t=Tr(e),n=wr.get(t);if(n)return n;let r=Ar(e,t);return wr.set(t,r),r}function Ar(e,t){let n=new Z(e),r=async e=>{try{let{searchParams:t}=new URL(e.req.raw.url);return Er(await n.processVerification(t.get(`hub.mode`),t.get(`hub.verify_token`),t.get(`hub.challenge`)))}catch(e){return console.error(`Webhook verification error:`,e),Dr()}},i=async e=>{try{return Er(await n.processWebhook(await Or(e)))}catch(e){return console.error(`Webhook processing error:`,e),Dr()}};return{GET:r,POST:i,webhook:async e=>{switch(e.req.raw.method.toUpperCase()){case`GET`:return r(e);case`POST`:return i(e);default:return new Response(JSON.stringify({error:`Method Not Allowed`}),{status:405,headers:{"Content-Type":`application/json`,Allow:`GET, POST`}})}},flow:async e=>{try{return Er(await n.processFlow(await Or(e)))}catch(e){return console.error(`Flow processing error:`,e),Dr()}},processor:n,destroy:()=>{n.removeAllHandlers(),wr.delete(t)}}}const jr=new Map;function Mr(e){return`nextjs-app:${e.phoneNumberId??`default`}`}function Nr(e){let t=Mr(e),n=jr.get(t);if(n)return n;let r=Pr(e,t);return jr.set(t,r),r}function Pr(e,t){let n=new Z(e);return{GET:async e=>{try{let{searchParams:t}=new URL(e.url),r=t.get(`hub.mode`),i=t.get(`hub.verify_token`),a=t.get(`hub.challenge`),o=await n.processVerification(r,i,a);return new Response(o.body,{status:o.status,headers:o.headers})}catch(e){return console.error(`Webhook verification error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let t=await n.processWebhook(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}},webhook:{GET:async e=>{try{let{searchParams:t}=new URL(e.url),r=t.get(`hub.mode`),i=t.get(`hub.verify_token`),a=t.get(`hub.challenge`),o=await n.processVerification(r,i,a);return new Response(o.body,{status:o.status,headers:o.headers})}catch(e){return console.error(`Webhook verification error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let t=await n.processWebhook(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}}},flow:{GET:async e=>{try{let t=await n.processFlow(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Flow GET error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}},POST:async e=>{try{let t=await n.processFlow(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Flow POST error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}}},processor:n,destroy:()=>{n.removeAllHandlers(),jr.delete(t)}}}var Fr=class extends lr{async parseRequestBody(e,t=!1){if(e.method===`POST`&&!e.body){let n=[];if(typeof e[Symbol.asyncIterator]==`function`){for await(let t of e)n.push(t);let r=Buffer.concat(n).toString();if(t&&(e.rawBody=r),r.trim())try{e.body=JSON.parse(r)}catch{throw Error(`Invalid JSON in request body`)}else e.body={}}}}async handleGet(e,t){try{let{"hub.mode":n,"hub.verify_token":r,"hub.challenge":i}=e.query,a=await this.processVerification(n||null,r||null,i||null);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return console.error(`Webhook verification error:`,e),t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async handlePost(e,t){try{await this.parseRequestBody(e,!0)}catch(e){return console.error(`Webhook processing error:`,e),e instanceof Error&&e.message===`Invalid JSON in request body`?(t.status(400).json({error:`Invalid JSON`}),{status:400,body:JSON.stringify({error:`Invalid JSON`}),headers:{"Content-Type":`application/json`}}):(t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}})}try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody??(e.method===`POST`?JSON.stringify(e.body):void 0),i=new Request(n,{method:`POST`,headers:e.headers,body:r}),a=await this.processWebhook(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return console.error(`Webhook processing error:`,e),t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async handleFlow(e,t){try{await this.parseRequestBody(e,!0)}catch(e){return console.error(`Flow body parsing error:`,e),e instanceof Error&&e.message===`Invalid JSON in request body`?(t.status(400).json({error:`Invalid JSON`}),{status:400,body:JSON.stringify({error:`Invalid JSON`}),headers:{"Content-Type":`application/json`}}):(t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}})}try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody??(e.method===`POST`?JSON.stringify(e.body):void 0),i=new Request(n,{method:e.method,headers:e.headers,body:r}),a=await this.processFlow(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return console.error(`Flow error:`,e),t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}getHandlers(){return{GET:(e,t)=>this.handleGet(e,t),POST:(e,t)=>this.handlePost(e,t),webhook:(e,t)=>this.autoRoute(e,t),flow:(e,t)=>this.handleFlow(e,t),processor:this.webhookProcessor}}};const Ir=new Map;function Lr(e){return`nextjs-page:${e.phoneNumberId??`default`}`}function Rr(e){let t=Lr(e),n=Ir.get(t);if(n)return n;let r=new Fr(e),i={...r.getHandlers(),destroy:()=>{r.webhookProcessor.removeAllHandlers(),Ir.delete(t)}};return Ir.set(t,i),i}function zr(e){switch(e.type){case`text`:return e.text.body;case`image`:return e.image.caption||`[Image]`;case`video`:return e.video.caption||`[Video]`;case`audio`:return e.audio.voice?`[Voice Message]`:`[Audio]`;case`document`:return e.document.caption||e.document.filename||`[Document]`;case`sticker`:return e.sticker.animated?`[Animated Sticker]`:`[Sticker]`;case`interactive`:{let t=e.interactive;return t.type===`button_reply`?t.button_reply.title:t.type===`list_reply`?t.list_reply.title:t.type===`nfm_reply`?t.nfm_reply.body||t.nfm_reply.name||`[Form Reply]`:`[Interactive]`}case`button`:return e.button.text;case`location`:return e.location.name||e.location.address||`📍 ${e.location.latitude}, ${e.location.longitude}`;case`contacts`:{let t=e.contacts.map(e=>e.name.formatted_name);return t.length===1?`👤 ${t[0]}`:`👤 ${t.length} contacts`}case`reaction`:return e.reaction.emoji||`[Reaction removed]`;case`order`:{let t=e.order.product_items.length;return`🛒 Order: ${t} item${t>1?`s`:``}`}case`system`:return e.system.body;case`unsupported`:return`[Unsupported message]`;default:return`[${e.type}]`}}const Br=(e,t)=>R(`generateXHub256Sig`).createHmac(`sha256`,t).update(e,`utf-8`).digest(`hex`),Vr=(e,t)=>an(t,e);function Hr(e){return e.type===`text`}function Ur(e){return e.type===`image`}function Wr(e){return e.type===`video`}function Gr(e){return e.type===`audio`}function Kr(e){return e.type===`document`}function qr(e){return e.type===`sticker`}function Q(e){return e.type===`interactive`}function Jr(e){return e.type===`button`}function Yr(e){return e.type===`location`}function Xr(e){return e.type===`contacts`}function Zr(e){return e.type===`reaction`}function Qr(e){return e.type===`order`}function $r(e){return e.type===`system`}function ei(e){return Q(e)&&e.interactive.type===`button_reply`}function ti(e){return Q(e)&&e.interactive.type===`list_reply`}function ni(e){return Q(e)&&e.interactive.type===`nfm_reply`}function ri(e){return Ur(e)?{id:e.image.id,mimeType:e.image.mime_type,sha256:e.image.sha256,caption:e.image.caption}:Wr(e)?{id:e.video.id,mimeType:e.video.mime_type,sha256:e.video.sha256,caption:e.video.caption}:Gr(e)?{id:e.audio.id,mimeType:e.audio.mime_type,sha256:e.audio.sha256,voice:e.audio.voice}:Kr(e)?{id:e.document.id,mimeType:e.document.mime_type,sha256:e.document.sha256,caption:e.document.caption,filename:e.document.filename}:qr(e)?{id:e.sticker.id,mimeType:e.sticker.mime_type,sha256:e.sticker.sha256,animated:e.sticker.animated}:null}function ii(e){return Q(e)?e.interactive.type===`button_reply`?{type:`button_reply`,id:e.interactive.button_reply.id,title:e.interactive.button_reply.title}:e.interactive.type===`list_reply`?{type:`list_reply`,id:e.interactive.list_reply.id,title:e.interactive.list_reply.title,description:e.interactive.list_reply.description}:e.interactive.type===`nfm_reply`?{type:`nfm_reply`,id:e.interactive.nfm_reply.name,title:e.interactive.nfm_reply.body,responseJson:e.interactive.nfm_reply.response_json}:null:null}function ai(e){return Yr(e)?{latitude:e.location.latitude,longitude:e.location.longitude,name:e.location.name,address:e.location.address,url:e.location.url}:null}function oi(e){return Xr(e)?e.contacts.map(e=>({formattedName:e.name.formatted_name,firstName:e.name.first_name,lastName:e.name.last_name,phones:e.phones?.map(e=>e.phone)||[],emails:e.emails?.map(e=>e.email)||[]})):[]}function si(e){return Zr(e)?{messageId:e.reaction.message_id,emoji:e.reaction.emoji||null}:null}function ci(e){return Qr(e)?{catalogId:e.order.catalog_id,text:e.order.text,items:e.order.product_items.map(e=>({productId:e.product_retailer_id,quantity:e.quantity,price:e.item_price,currency:e.currency}))}:null}const li={Authentication:`AUTHENTICATION`,Marketing:`MARKETING`,Utility:`UTILITY`},ui={Authentication:`authentication`,Service:`service`,Utility:`utility`},di={Approved:`APPROVED`,Pending:`PENDING`,Rejected:`REJECTED`},fi={Get:`GET`,Post:`POST`,Put:`PUT`,Delete:`DELETE`},pi={Audio:`audio`,Contacts:`contacts`,Document:`document`,Image:`image`,Interactive:`interactive`,Location:`location`,Reaction:`reaction`,Sticker:`sticker`,Template:`template`,Text:`text`,Video:`video`,Button:`button`,Order:`order`,System:`system`,Unsupported:`unsupported`,Unknown:`unknown`,Statuses:`statuses`,All:`*`},mi={Action:`ACTION`,CouponCode:`COUPON_CODE`,Currency:`CURRENCY`,DateTime:`DATE_TIME`,Document:`DOCUMENT`,ExpirationTimeMs:`EXPIRATION_TIME_MS`,Image:`IMAGE`,LimitedTimeOffer:`LIMITED_TIME_OFFER`,Location:`LOCATION`,OrderStatus:`ORDER_STATUS`,Payload:`PAYLOAD`,Product:`PRODUCT`,Text:`TEXT`,TtlMinutes:`TTL_MINUTES`,Video:`VIDEO`,WebviewInteraction:`WEBVIEW_INTERACTION`,WebviewPresentation:`WEBVIEW_PRESENTATION`},hi={Button:`button`,List:`list`,Product:`product`,ProductList:`product_list`,CtaUrl:`cta_url`,Carousel:`carousel`,LocationRequest:`location_request_message`,AddressMessage:`address_message`,Flow:`flow`,VoiceCall:`voice_call`},gi={First:1,Second:2,Third:3,Fourth:4,Fifth:5},_i={Catalog:`CATALOG`,CopyCode:`COPY_CODE`,Flow:`FLOW`,Mpm:`MPM`,OrderDetails:`ORDER_DETAILS`,QuickReply:`QUICK_REPLY`,Reminder:`REMINDER`,Url:`URL`,VoiceCall:`VOICE_CALL`},vi={Header:`HEADER`,Body:`BODY`,Button:`BUTTON`,Footer:`FOOTER`},yi={BusinessInitiated:`business_initiated`,CustomerInitiated:`customer_initiated`,ReferralConversion:`referral_conversion`},bi={Delivered:`delivered`,Read:`read`,Sent:`sent`},xi={Mp4:`video/mp4`,Threegp:`video/3gp`},Si={Webp:`image/webp`},Ci={Jpeg:`image/jpeg`,Png:`image/png`},wi={Text:`text/plain`,Pdf:`application/pdf`,Ppt:`application/vnd.ms-powerpoint`,Word:`application/msword`,Excel:`application/vnd.ms-excel`,OpenDoc:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,OpenPres:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,OpenSheet:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`},Ti={Aac:`audio/aac`,Mp4:`audio/mp4`,Mpeg:`audio/mpeg`,Amr:`audio/amr`,Ogg:`audio/ogg`},Ei={Audio:`audio`,Button:`button`,Document:`document`,Text:`text`,Image:`image`,Interactive:`interactive`,Order:`order`,Sticker:`sticker`,System:`system`,Unknown:`unknown`,Video:`video`},Di={CustomerChangedNumber:`customer_changed_number`,CustomerIdentityChanged:`customer_identity_changed`,UserChangedNumber:`user_changed_number`,UserIdentityChanged:`user_identity_changed`,UserChangedUserId:`user_changed_user_id`},Oi={Ad:`ad`,Post:`post`},ki={Sms:`SMS`,Voice:`VOICE`},Ai={Afrikaans:`af`,Albanian:`sq`,Arabic:`ar`,Azerbaijani:`az`,Bengali:`bn`,Bulgarian:`bg`,Catalan:`ca`,Chinese_CHN:`zh_CN`,Chinese_HKG:`zh_HK`,Chinese_TAI:`zh_TW`,Croatian:`hr`,Czech:`cs`,Danish:`da`,Dutch:`nl`,English:`en`,English_UK:`en_GB`,English_US:`en_US`,Estonian:`et`,Filipino:`fil`,Finnish:`fi`,French:`fr`,Georgian:`ka`,German:`de`,Greek:`el`,Gujarati:`gu`,Hausa:`ha`,Hebrew:`he`,Hindi:`hi`,Hungarian:`hu`,Indonesian:`id`,Irish:`ga`,Italian:`it`,Japanese:`ja`,Kannada:`kn`,Kazakh:`kk`,Kinyarwanda:`rw_RW`,Korean:`ko`,Kyrgyz_Kyrgyzstan:`ky_KG`,Lao:`lo`,Latvian:`lv`,Lithuanian:`lt`,Macedonian:`mk`,Malay:`ms`,Malayalam:`ml`,Marathi:`mr`,Norwegian:`nb`,Persian:`fa`,Polish:`pl`,Portuguese_BR:`pt_BR`,Portuguese_POR:`pt_PT`,Punjabi:`pa`,Romanian:`ro`,Russian:`ru`,Serbian:`sr`,Slovak:`sk`,Slovenian:`sl`,Spanish:`es`,Spanish_ARG:`es_AR`,Spanish_SPA:`es_ES`,Spanish_MEX:`es_MX`,Swahili:`sw`,Swedish:`sv`,Tamil:`ta`,Telugu:`te`,Thai:`th`,Turkish:`tr`,Ukrainian:`uk`,Urdu:`ur`,Uzbek:`uz`,Vietnamese:`vi`,Zulu:`zu`},ji={AU:`AU`,ID:`ID`,IN:`IN`,JP:`JP`,SG:`SG`,KR:`KR`,DE:`DE`,CH:`CH`,GB:`GB`,BR:`BR`,BH:`BH`,ZA:`ZA`,AE:`AE`,CA:`CA`},Mi=3600*1e3,Ni=24*Mi,Pi=72*Mi,Fi=168*Mi,Ii=1e11;function $(e,t){let n;if(e instanceof Date)n=e.getTime();else if(typeof e==`number`)n=Math.abs(e)<Ii?e*1e3:e;else if(typeof e==`string`){let t=e.trim();if(/^\d+(\.\d+)?$/.test(t)){let e=Number(t);n=e<Ii?e*1e3:e}else n=t===``?NaN:Date.parse(t)}else n=NaN;if(!Number.isFinite(n)||!Number.isFinite(new Date(n).getTime()))throw new E(`${t} is not a valid timestamp: ${String(e)}`);return n}function Li(e,t,n){if(e===void 0)return n;if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw new E(`${t} must be a non-negative number of milliseconds`);return e}function Ri(e,t,n,r){if(!Number.isFinite(new Date(t).getTime()))throw new E(`Window expiry is outside the supported timestamp range`);let i=Math.max(0,t-e),a=t-r,o=Math.min(Math.max(0,a-n),i);return{isOpen:o>0,expiresAt:new Date(t),remainingMs:o}}const zi=Object.freeze({isOpen:!1,expiresAt:null,remainingMs:0});function Bi(e,t={}){let n=Li(t.safetyMarginMs,`safetyMarginMs`,0),r=t.now===void 0?Date.now():$(t.now,`now`);if(e==null)return{...zi};let i=$(e,`lastInboundAt`);return Ri(i,i+Ni,r,n)}function Vi(e,t={}){return Bi(e,t).isOpen}function Hi(e,t={}){let n=Li(t.safetyMarginMs,`safetyMarginMs`,0),r=Li(t.durationMs,`durationMs`,Pi),i=t.now===void 0?Date.now():$(t.now,`now`);if(e==null)return{...zi};let a=$(e,`openedAt`);return Ri(a,t.expiresAt===void 0?a+r:$(t.expiresAt,`expiresAt`),i,n)}export{he as AUTHORIZATION_ERROR_CODES,Ti as AudioMediaTypes,ie as AudioMediaTypesEnum,be as BLOCK_USER_ERROR_CODES,rt as BlockUsersApi,it as BusinessApi,wt as BusinessProfileApi,fe as BusinessVerticalEnum,gi as ButtonPosition,d as ButtonPositionEnum,xe as CALLING_ERROR_CODES,Ni as CUSTOMER_SERVICE_WINDOW_MS,at as CallingApi,li as Category,i as CategoryEnum,ot as CommerceApi,vi as ComponentType,p as ComponentTypesEnum,st as ContactBookApi,yi as ConversationTypes,h as ConversationTypesEnum,ue as CurrencyCodesEnum,ji as DataLocalizationRegion,de as DataLocalizationRegionEnum,wi as DocumentMediaTypes,re as DocumentMediaTypesEnum,ct as EncryptionApi,ye as FLOW_ERROR_CODES,Pi as FREE_ENTRY_POINT_WINDOW_MS,ft as FlowActionEnum,lt as FlowApi,dt as FlowCategoryEnum,ut as FlowStatusEnum,pt as FlowTypeEnum,Se as GROUP_ERROR_CODES,mt as GroupsApi,fi as HttpMethods,s as HttpMethodsEnum,_e as INTEGRITY_ERROR_CODES,Ci as ImageMediaTypes,ne as ImageMediaTypesEnum,hi as InteractiveTypes,u as InteractiveTypesEnum,Ai as Languages,le as LanguagesEnum,N as Logger,Fi as MAX_FREE_ENTRY_POINT_WINDOW_MS,ht as MarketingMessagesApi,gt as MediaApi,Pn as MemoryDedupeStore,k as MessageApi,k as MessagesApi,ui as MessageCategory,a as MessageCategoryEnum,bt as MessageHistoryApi,pi as MessageTypes,c as MessageTypesEnum,mi as ParametersTypes,l as ParametersTypesEnum,xt as PaymentsApi,St as PhoneNumberApi,Tt as QrCodeApi,Oi as ReferralSourceTypes,se as ReferralSourceTypesEnum,Et as RegistrationApi,ki as RequestCodeMethods,ce as RequestCodeMethodsEnum,ve as SEND_MESSAGE_ERROR_CODES,Dt as SolutionsApi,bi as Status,g as StatusEnum,Si as StickerMediaTypes,te as StickerMediaTypesEnum,_i as SubType,f as SubTypeEnum,Di as SystemChangeTypes,oe as SystemChangeTypesEnum,ge as THROTTLING_ERROR_CODES,Bt as TemplateApi,di as TemplateStatus,o as TemplateStatusEnum,Ht as ThreadControlApi,Ut as TwoStepVerificationApi,xi as VideoMediaTypes,ee as VideoMediaTypesEnum,pe as WHATSAPP_ERROR_CODES,Gt as WabaAccountReviewStatus,qt as WabaAccountStatus,Wt as WabaApi,Jt as WabaBusinessVerificationStatus,m as WabaConfigEnum,Kt as WabaHealthStatusCanSendMessage,Z as WebhookProcessor,Ei as WebhookTypes,ae as WebhookTypesEnum,Nn as WhatsApp,Nn as default,b as WhatsAppApiError,Be as WhatsAppAuthorizationError,S as WhatsAppBlockUserError,C as WhatsAppCallingError,y as WhatsAppError,Ue as WhatsAppFlowError,w as WhatsAppGroupError,Ve as WhatsAppIntegrityError,We as WhatsAppNetworkError,He as WhatsAppSendMessageError,x as WhatsAppThrottlingError,Ge as WhatsAppUnknownError,E as WhatsAppValidationError,Ct as buildFieldsQueryString,Vi as canSendFreeformMessage,tr as constructFullUrl,Mt as createAuthenticationTemplate,Nt as createCatalogTemplate,Pt as createCouponTemplate,Ft as createLimitedTimeOfferTemplate,Lt as createMPMTemplate,It as createMediaCardCarouselTemplate,jt as createOTPTemplate,Rt as createProductCardCarouselTemplate,zt as createSPMTemplate,At as createTemplate,T as createWhatsAppApiError,fn as decryptFlowRequest,_n as decryptFlowRequestAsync,pn as encryptFlowResponse,vn as encryptFlowResponseAsync,pr as expressWebhookHandler,zr as extractMessageText,Sr as fastifyWebhookHandler,ln as formatConfigTable,dn as generateEncryption,Br as generateXHub256Sig,Vr as generateXHub256SigAsync,oi as getContactsInfo,Bi as getCustomerServiceWindow,Hi as getFreeEntryPointWindow,ii as getInteractiveReply,ai as getLocationInfo,ri as getMediaInfo,ci as getOrderInfo,si as getReactionInfo,kr as honoWebhookHandler,v as isApiPermissionErrorCode,Gr as isAudioMessage,Me as isAuthorizationErrorCode,Le as isBlockUserErrorCode,Jr as isButtonMessage,ei as isButtonReply,Re as isCallingErrorCode,Xr as isContactsMessage,Kr as isDocumentMessage,zn as isFlowDataExchangeRequest,Ie as isFlowErrorCode,Bn as isFlowErrorRequest,Vn as isFlowPingRequest,ze as isGroupErrorCode,Ur as isImageMessage,Pe as isIntegrityErrorCode,Q as isInteractiveMessage,ti as isListReply,Yr as isLocationMessage,D as isMetaError,ni as isNfmReply,Qr as isOrderMessage,Zr as isReactionMessage,Fe as isSendMessageErrorCode,qr as isStickerMessage,$r as isSystemMessage,Hr as isTextMessage,Ne as isThrottlingErrorCode,er as isValidWebhookSignature,Wr as isVideoMessage,Ke as isWhatsAppApiErrorResponse,qe as isWhatsAppAuthorizationError,Qe as isWhatsAppBlockUserError,$e as isWhatsAppCallingError,je as isWhatsAppErrorCode,Ze as isWhatsAppFlowError,et as isWhatsAppGroupError,Ye as isWhatsAppIntegrityError,Xe as isWhatsAppSendMessageError,Je as isWhatsAppThrottlingError,Nr as nextjsAppWebhookHandler,Rr as nextjsPagesWebhookHandler,tt as normalizeMetaError,_ as objectToQueryString,wn as parseRateLimitHeaders,Cn as parseRetryAfter,Qn as processFlowRequest,Yn as processWebhookMessages,$n as verifyWebhookSignature};
23
23
  //# sourceMappingURL=index.mjs.map
@@ -3725,7 +3725,7 @@ type WabaBanState = 'SCHEDULE_FOR_DISABLE' | 'DISABLE' | 'REINSTATE';
3725
3725
  /**
3726
3726
  * Restriction types imposed on WABA — present on ACCOUNT_RESTRICTION events.
3727
3727
  */
3728
- type RestrictionType = 'RESTRICTION_ADD_PHONE_NUMBER_ACTION' | 'RESTRICTED_BIZ_INITIATED_MESSAGING' | 'RESTRICTED_CUSTOMER_INITIATED_MESSAGING';
3728
+ type RestrictionType = 'RESTRICTED_ADD_PHONE_NUMBER_ACTION' /** @deprecated Misspelled legacy value; Meta sends `RESTRICTED_ADD_PHONE_NUMBER_ACTION`. */ | 'RESTRICTION_ADD_PHONE_NUMBER_ACTION' | 'RESTRICTED_BIZ_INITIATED_MESSAGING' | 'RESTRICTED_CUSTOMER_INITIATED_MESSAGING' | 'RESTRICTED_BIZ_INITIATED_AND_USER_INITIATED_CALLING' | 'RESTRICTED_BUSINESS_INITIATED_CALLING' | 'RESTRICTED_USER_INITIATED_CALLING' | 'RESTRICTED_USER_INITIATED_CALLING_CALL_BUTTON_HIDDEN' | 'RESTRICTED_DIRECT_SEND_UTILITY_TEMPLATES' | 'RESTRICTED_UTILITY_TEMPLATES';
3729
3729
  /**
3730
3730
  * Reason for the disconnection — present on PARTNER_REMOVED events where
3731
3731
  * the business used both WhatsApp Business app and Cloud API.
@@ -3813,7 +3813,12 @@ interface PartnerClientCertificationInfo {
3813
3813
  rejection_reasons?: string[];
3814
3814
  }
3815
3815
  interface AccountUpdateValue {
3816
- /** Phone number associated with the WABA, if applicable */
3816
+ /**
3817
+ * Business display phone number the event applies to (e.g. "15550783881").
3818
+ * Only included for events about a single business phone number, such as
3819
+ * ACCOUNT_VIOLATION and calling-related ACCOUNT_RESTRICTION events.
3820
+ * Absent on WABA-wide events.
3821
+ */
3817
3822
  phone_number?: string;
3818
3823
  /**
3819
3824
  * Event type describing what changed.