meta-cloud-api 0.2.8 → 0.2.11

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
@@ -1,3 +1,3 @@
1
- var Me=Object.defineProperty;var Be=(r,t)=>{for(var s in t)Me(r,s,{get:t[s],enumerable:!0})};var $={};Be($,{AudioMediaTypesEnum:()=>ae,BusinessVerticalEnum:()=>he,ButtonPositionEnum:()=>E,ButtonTypesEnum:()=>z,CategoryEnum:()=>X,ComponentTypesEnum:()=>C,ConversationTypesEnum:()=>ee,CurrencyCodesEnum:()=>de,DataLocalizationRegionEnum:()=>ge,DocumentMediaTypesEnum:()=>re,HttpMethodsEnum:()=>w,ImageMediaTypesEnum:()=>oe,InteractiveTypesEnum:()=>Q,LanguagesEnum:()=>fe,MessageTypesEnum:()=>L,ParametersTypesEnum:()=>Z,ReferralSourceTypesEnum:()=>le,RequestCodeMethodsEnum:()=>ce,StatusEnum:()=>te,StickerMediaTypesEnum:()=>ie,SystemChangeTypesEnum:()=>pe,TemplateStatusEnum:()=>Y,VideoMediaTypesEnum:()=>se,WabaConfigEnum:()=>A,WebhookTypesEnum:()=>ne});var X=(i=>(i.Authentication="AUTHENTICATION",i.Marketing="MARKETING",i.Utility="UTILITY",i))(X||{}),Y=(i=>(i.Approved="APPROVED",i.Pending="PENDING",i.Rejected="REJECTED",i))(Y||{}),w=(o=>(o.Get="GET",o.Post="POST",o.Put="PUT",o.Delete="DELETE",o))(w||{}),L=(d=>(d.Audio="audio",d.Contacts="contacts",d.Document="document",d.Image="image",d.Interactive="interactive",d.Location="location",d.Reaction="reaction",d.Sticker="sticker",d.Template="template",d.Text="text",d.Video="video",d.Button="button",d.Order="order",d.System="system",d.Unknown="unknown",d["*"]="*",d))(L||{}),Z=(p=>(p.Currency="currency",p.DateTime="date_time",p.Document="document",p.Image="image",p.Text="text",p.Video="video",p.Payload="payload",p))(Z||{}),Q=(l=>(l.Button="button",l.List="list",l.Product="product",l.ProductList="product_list",l.CtaUrl="cta_url",l.LocationRequest="location_request_message",l.AddressMessage="address_message",l.Flow="flow",l))(Q||{}),z=(s=>(s.QuickReply="quick_reply",s.URL="url",s))(z||{}),E=(i=>(i[i.First=0]="First",i[i.Second=1]="Second",i[i.Third=2]="Third",i))(E||{}),C=(o=>(o.Header="HEADER",o.Body="BODY",o.Button="BUTTON",o.Footer="FOOTER",o))(C||{}),A=(d=>(d.AppId="M4D_APP_ID",d.Port="WA_PORT",d.AppSecret="M4D_APP_SECRET",d.PhoneNumberId="WA_PHONE_NUMBER_ID",d.BusinessAcctId="WA_BUSINESS_ACCOUNT_ID",d.APIVersion="CLOUD_API_VERSION",d.AccessToken="CLOUD_API_ACCESS_TOKEN",d.WebhookEndpoint="WEBHOOK_ENDPOINT",d.WebhookVerificationToken="WEBHOOK_VERIFICATION_TOKEN",d.ListenerPort="LISTENER_PORT",d.MaxRetriesAfterWait="MAX_RETRIES_AFTER_WAIT",d.RequestTimeout="REQUEST_TIMEOUT",d.Debug="DEBUG",d.PrivatePem="FLOW_API_PRIVATE_PEM",d.Passphrase="FLOW_API_PASSPHRASE",d))(A||{}),ee=(i=>(i.BusinessInitiated="business_initiated",i.CustomerInitiated="customer_initiated",i.ReferralConversion="referral_conversion",i))(ee||{}),te=(i=>(i.Delivered="delivered",i.Read="read",i.Sent="sent",i))(te||{}),se=(s=>(s.Mp4="video/mp4",s.Threegp="video/3gp",s))(se||{}),ie=(t=>(t.Webp="image/webp",t))(ie||{}),oe=(s=>(s.Jpeg="image/jpeg",s.Png="image/png",s))(oe||{}),re=(l=>(l.Text="text/plain",l.Pdf="application/pdf",l.Ppt="application/vnd.ms-powerpoint",l.Word="application/msword",l.Excel="application/vnd.ms-excel",l.OpenDoc="application/vnd.openxmlformats-officedocument.wordprocessingml.document",l.OpenPres="application/vnd.openxmlformats-officedocument.presentationml.presentation",l.OpenSheet="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",l))(re||{}),ae=(n=>(n.Aac="audio/aac",n.Mp4="audio/mp4",n.Mpeg="audio/mpeg",n.Amr="audio/amr",n.Ogg="audio/ogg",n))(ae||{}),ne=(R=>(R.Audio="audio",R.Button="button",R.Document="document",R.Text="text",R.Image="image",R.Interactive="interactive",R.Order="order",R.Sticker="sticker",R.System="system",R.Unknown="unknown",R.Video="video",R))(ne||{}),pe=(s=>(s.CustomerChangedNumber="customer_changed_number",s.CustomerIdentityChanged="customer_identity_changed",s))(pe||{}),le=(s=>(s.Ad="ad",s.Post="post",s))(le||{}),ce=(s=>(s.Sms="SMS",s.Voice="VOICE",s))(ce||{}),fe=(a=>(a.Afrikaans="af",a.Albanian="sq",a.Arabic="ar",a.Azerbaijani="az",a.Bengali="bn",a.Bulgarian="bg",a.Catalan="ca",a.Chinese_CHN="zh_CN",a.Chinese_HKG="zh_HK",a.Chinese_TAI="zh_TW",a.Croatian="hr",a.Czech="cs",a.Danish="da",a.Dutch="nl",a.English="en",a.English_UK="en_GB",a.English_US="en_US",a.Estonian="et",a.Filipino="fil",a.Finnish="fi",a.French="fr",a.Georgian="ka",a.German="de",a.Greek="el",a.Gujarati="gu",a.Hausa="ha",a.Hebrew="he",a.Hindi="hi",a.Hungarian="hu",a.Indonesian="id",a.Irish="ga",a.Italian="it",a.Japanese="ja",a.Kannada="kn",a.Kazakh="kk",a.Kinyarwanda="rw_RW",a.Korean="ko",a.Kyrgyz_Kyrgyzstan="ky_KG",a.Lao="lo",a.Latvian="lv",a.Lithuanian="lt",a.Macedonian="mk",a.Malay="ms",a.Malayalam="ml",a.Marathi="mr",a.Norwegian="nb",a.Persian="fa",a.Polish="pl",a.Portuguese_BR="pt_BR",a.Portuguese_POR="pt_PT",a.Punjabi="pa",a.Romanian="ro",a.Russian="ru",a.Serbian="sr",a.Slovak="sk",a.Slovenian="sl",a.Spanish="es",a.Spanish_ARG="es_AR",a.Spanish_SPA="es_ES",a.Spanish_MEX="es_MX",a.Swahili="sw",a.Swedish="sv",a.Tamil="ta",a.Telugu="te",a.Thai="th",a.Turkish="tr",a.Ukrainian="uk",a.Urdu="ur",a.Uzbek="uz",a.Vietnamese="vi",a.Zulu="zu",a))(fe||{}),de=(e=>(e.AFN="AFN",e.EUR="EUR",e.ALL="ALL",e.DZD="DZD",e.USD="USD",e.AOA="AOA",e.XCD="XCD",e.ARS="ARS",e.AMD="AMD",e.AWG="AWG",e.AUD="AUD",e.AZN="AZN",e.BSD="BSD",e.BHD="BHD",e.BDT="BDT",e.BBD="BBD",e.BYN="BYN",e.BZD="BZD",e.XOF="XOF",e.BMD="BMD",e.INR="INR",e.BTN="BTN",e.BOB="BOB",e.BOV="BOV",e.BAM="BAM",e.BWP="BWP",e.NOK="NOK",e.BRL="BRL",e.BND="BND",e.BGN="BGN",e.BIF="BIF",e.CVE="CVE",e.KHR="KHR",e.XAF="XAF",e.CAD="CAD",e.KYD="KYD",e.CLP="CLP",e.CLF="CLF",e.CNY="CNY",e.COP="COP",e.COU="COU",e.KMF="KMF",e.CDF="CDF",e.NZD="NZD",e.CRC="CRC",e.HRK="HRK",e.CUP="CUP",e.CUC="CUC",e.ANG="ANG",e.CZK="CZK",e.DKK="DKK",e.DJF="DJF",e.DOP="DOP",e.EGP="EGP",e.SVC="SVC",e.ERN="ERN",e.SZL="SZL",e.ETB="ETB",e.FKP="FKP",e.FJD="FJD",e.XPF="XPF",e.GMD="GMD",e.GEL="GEL",e.GHS="GHS",e.GIP="GIP",e.GTQ="GTQ",e.GBP="GBP",e.GNF="GNF",e.GYD="GYD",e.HTG="HTG",e.HNL="HNL",e.HKD="HKD",e.HUF="HUF",e.ISK="ISK",e.IDR="IDR",e.XDR="XDR",e.IRR="IRR",e.IQD="IQD",e.ILS="ILS",e.JMD="JMD",e.JPY="JPY",e.JOD="JOD",e.KZT="KZT",e.KES="KES",e.KPW="KPW",e.KRW="KRW",e.KWD="KWD",e.KGS="KGS",e.LAK="LAK",e.LBP="LBP",e.LSL="LSL",e.ZAR="ZAR",e.LRD="LRD",e.LYD="LYD",e.CHF="CHF",e.MOP="MOP",e.MKD="MKD",e.MGA="MGA",e.MWK="MWK",e.MYR="MYR",e.MVR="MVR",e.MRU="MRU",e.MUR="MUR",e.XUA="XUA",e.MXN="MXN",e.MXV="MXV",e.MDL="MDL",e.MNT="MNT",e.MAD="MAD",e.MZN="MZN",e.MMK="MMK",e.NAD="NAD",e.NPR="NPR",e.NIO="NIO",e.NGN="NGN",e.OMR="OMR",e.PKR="PKR",e.PAB="PAB",e.PGK="PGK",e.PYG="PYG",e.PEN="PEN",e.PHP="PHP",e.PLN="PLN",e.QAR="QAR",e.RON="RON",e.RUB="RUB",e.RWF="RWF",e.SHP="SHP",e.WST="WST",e.STN="STN",e.SAR="SAR",e.RSD="RSD",e.SCR="SCR",e.SLL="SLL",e.SGD="SGD",e.XSU="XSU",e.SBD="SBD",e.SOS="SOS",e.SSP="SSP",e.LKR="LKR",e.SDG="SDG",e.SRD="SRD",e.SEK="SEK",e.CHE="CHE",e.CHW="CHW",e.SYP="SYP",e.TWD="TWD",e.TJS="TJS",e.TZS="TZS",e.THB="THB",e.TOP="TOP",e.TTD="TTD",e.TND="TND",e.TRY="TRY",e.TMT="TMT",e.UGX="UGX",e.UAH="UAH",e.AED="AED",e.USN="USN",e.UYU="UYU",e.UYI="UYI",e.UYW="UYW",e.UZS="UZS",e.VUV="VUV",e.VES="VES",e.VND="VND",e.YER="YER",e.ZMW="ZMW",e.ZWL="ZWL",e.XBA="XBA",e.XBB="XBB",e.XBC="XBC",e.XBD="XBD",e.XTS="XTS",e.XXX="XXX",e.XAU="XAU",e.XPD="XPD",e.XPT="XPT",e.XAG="XAG",e.AFA="AFA",e.FIM="FIM",e.ALK="ALK",e.ADP="ADP",e.ESP="ESP",e.FRF="FRF",e.AOK="AOK",e.AON="AON",e.AOR="AOR",e.ARA="ARA",e.ARP="ARP",e.ARY="ARY",e.RUR="RUR",e.ATS="ATS",e.AYM="AYM",e.AZM="AZM",e.BYB="BYB",e.BYR="BYR",e.BEC="BEC",e.BEF="BEF",e.BEL="BEL",e.BOP="BOP",e.BAD="BAD",e.BRB="BRB",e.BRC="BRC",e.BRE="BRE",e.BRN="BRN",e.BRR="BRR",e.BGJ="BGJ",e.BGK="BGK",e.BGL="BGL",e.BUK="BUK",e.HRD="HRD",e.CYP="CYP",e.CSJ="CSJ",e.CSK="CSK",e.ECS="ECS",e.ECV="ECV",e.GQE="GQE",e.EEK="EEK",e.XEU="XEU",e.GEK="GEK",e.DDM="DDM",e.DEM="DEM",e.GHC="GHC",e.GHP="GHP",e.GRD="GRD",e.GNE="GNE",e.GNS="GNS",e.GWE="GWE",e.GWP="GWP",e.ITL="ITL",e.ISJ="ISJ",e.IEP="IEP",e.ILP="ILP",e.ILR="ILR",e.LAJ="LAJ",e.LVL="LVL",e.LVR="LVR",e.LSM="LSM",e.ZAL="ZAL",e.LTL="LTL",e.LTT="LTT",e.LUC="LUC",e.LUF="LUF",e.LUL="LUL",e.MGF="MGF",e.MVQ="MVQ",e.MLF="MLF",e.MTL="MTL",e.MTP="MTP",e.MRO="MRO",e.MXP="MXP",e.MZE="MZE",e.MZM="MZM",e.NLG="NLG",e.NIC="NIC",e.PEH="PEH",e.PEI="PEI",e.PES="PES",e.PLZ="PLZ",e.PTE="PTE",e.ROK="ROK",e.ROL="ROL",e.STD="STD",e.CSD="CSD",e.SKK="SKK",e.SIT="SIT",e.RHD="RHD",e.ESA="ESA",e.ESB="ESB",e.SDD="SDD",e.SDP="SDP",e.SRG="SRG",e.CHC="CHC",e.TJR="TJR",e.TPE="TPE",e.TRL="TRL",e.TMM="TMM",e.UGS="UGS",e.UGW="UGW",e.UAK="UAK",e.SUR="SUR",e.USS="USS",e.UYN="UYN",e.UYP="UYP",e.VEB="VEB",e.VEF="VEF",e.VNC="VNC",e.YDD="YDD",e.YUD="YUD",e.YUM="YUM",e.YUN="YUN",e.ZRN="ZRN",e.ZRZ="ZRZ",e.ZMK="ZMK",e.ZWC="ZWC",e.ZWD="ZWD",e.ZWN="ZWN",e.ZWR="ZWR",e.XFO="XFO",e.XRE="XRE",e.XFU="XFU",e))(de||{}),ge=(P=>(P.AU="AU",P.ID="ID",P.IN="IN",P.JP="JP",P.SG="SG",P.KR="KR",P.DE="DE",P.CH="CH",P.GB="GB",P.BR="BR",P.BH="BH",P.ZA="ZA",P.AE="AE",P.CA="CA",P))(ge||{}),he=(m=>(m.ALCOHOL="ALCOHOL",m.APPAREL="APPAREL",m.AUTO="AUTO",m.BEAUTY="BEAUTY",m.EDU="EDU",m.ENTERTAIN="ENTERTAIN",m.EVENT_PLAN="EVENT_PLAN",m.FINANCE="FINANCE",m.GOVT="GOVT",m.GROCERY="GROCERY",m.HEALTH="HEALTH",m.HOTEL="HOTEL",m.NONPROFIT="NONPROFIT",m.ONLINE_GAMBLING="ONLINE_GAMBLING",m.OTC_DRUGS="OTC_DRUGS",m.OTHER="OTHER",m.PHYSICAL_GAMBLING="PHYSICAL_GAMBLING",m.PROF_SERVICES="PROF_SERVICES",m.RESTAURANT="RESTAURANT",m.RETAIL="RETAIL",m.TRAVEL="TRAVEL",m))(he||{});var ye=(n=>(n.Draft="DRAFT",n.Published="PUBLISHED",n.Throttled="THROTTLED",n.Blocked="BLOCKED",n.Deprecated="DEPRECATED",n))(ye||{}),Oe=(l=>(l.SignUp="SIGN_UP",l.SignIn="SIGN_IN",l.AppointmentBooking="APPOINTMENT_BOOKING",l.LeadGeneration="LEAD_GENERATION",l.ContactUs="CONTACT_US",l.CustomerSupport="CUSTOMER_SUPPORT",l.Survey="SURVEY",l.Other="OTHER",l))(Oe||{}),me=(i=>(i.INIT="INIT",i.BACK="BACK",i.DATA_EXCHANGE="data_exchange",i))(me||{}),Re=(o=>(o.Ping="ping",o.Change="data_exchange",o.Error="error",o.All="*",o))(Re||{});var De=(o=>(o.Approved="APPROVED",o.Active="ACTIVE",o.Inactive="INACTIVE",o.Disabled="DISABLED",o))(De||{}),ve=(i=>(i.Blocked="BLOCKED",i.Limited="LIMITED",i.Available="AVAILABLE",i))(ve||{}),xe=(o=>(o.Approved="APPROVED",o.Active="ACTIVE",o.Inactive="INACTIVE",o.Disabled="DISABLED",o))(xe||{}),Fe=(o=>(o.Verified="verified",o.PendingSubmission="pending_submission",o.Unverified="unverified",o.Rejected="rejected",o))(Fe||{});var ue=(i=>(i.DELIVERED="delivered",i.READ="read",i.SENT="sent",i))(ue||{}),Pe=(f=>(f.MESSAGES="messages",f.STATUSES="statuses",f.MESSAGE_TEMPLATE_STATUS_UPDATE="message_template_status_update",f.PHONE_NUMBER_QUALITY_UPDATE="phone_number_quality_update",f.PHONE_NUMBER_NAME_UPDATE="phone_number_name_update",f.UNKNOWN="unknown",f))(Pe||{});import I from"crypto";import*as be from"crypto";var yt=(r,t)=>be.createHmac("sha256",t).update(r,"utf-8").digest("hex");var b=class{name;debug;constructor(t,s=!1){this.name=t,this.debug=s}log(...t){if(this.debug){let s=`[ ${Date.now()} ]`;this.name&&(s+=` - ${this.name}`),console.log.apply(console,[s,": ",...t])}}error(...t){let s=`[ ${Date.now()} ] - ERROR`;this.name&&(s+=` - ${this.name}`),console.error.apply(console,[s,": ",...t])}warn(...t){let s=`[ ${Date.now()} ] - WARN`;this.name&&(s+=` - ${this.name}`),console.warn.apply(console,[s,": ",...t])}info(...t){let s=`[ ${Date.now()} ] - INFO`;this.name&&(s+=` - ${this.name}`),console.info.apply(console,[s,": ",...t])}};var qe="UTILS",Ue=!1,_e=new b(qe,process.env.DEBUG==="true"||Ue),We=3e3,He=30,Ge=2e4,Le=r=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!r?.accessToken)throw _e.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},k=r=>{Le(r);let t={M4D_APP_ID:r?.appId||process.env.M4D_APP_ID||"",M4D_APP_SECRET:r?.appSecret||process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:r?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),WA_BUSINESS_ACCOUNT_ID:r?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||"",CLOUD_API_VERSION:r?.apiVersion||process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:r?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||"",WEBHOOK_ENDPOINT:r?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||"",WEBHOOK_VERIFICATION_TOKEN:r?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||"",LISTENER_PORT:r?.listenerPort||parseInt(process.env.LISTENER_PORT||"")||We,MAX_RETRIES_AFTER_WAIT:r?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||He,REQUEST_TIMEOUT:r?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||"")||Ge,DEBUG:r?.debug||process.env.DEBUG==="true",FLOW_API_PRIVATE_PEM:r?.privatePem||process.env.FLOW_API_PRIVATE_PEM||"",FLOW_API_PASSPHRASE:r?.passphrase||process.env.FLOW_API_PASSPHRASE||""};return _e.log(`Configuration loaded for App Id ${t.M4D_APP_ID}`),t};function V(r){return r!=null&&typeof r=="object"&&"error"in r&&typeof r.error=="object"&&r.error!=null&&"message"in r.error&&typeof r.error.message=="string"&&"type"in r.error&&typeof r.error.type=="string"&&"code"in r.error&&typeof r.error.code=="number"&&"fbtrace_id"in r.error&&typeof r.error.fbtrace_id=="string"&&(!("error_data"in r.error)||typeof r.error.error_data=="object"&&r.error.error_data!=null&&"messaging_product"in r.error.error_data&&r.error.error_data.messaging_product==="whatsapp"&&"details"in r.error.error_data&&typeof r.error.error_data.details=="string")&&(!("error_subcode"in r.error)||typeof r.error.error_subcode=="number")}var S=r=>{if(!r||Object.keys(r).length===0)return"";let t=new URLSearchParams;for(let[i,o]of Object.entries(r))o!==void 0&&t.append(i,String(o));let s=t.toString();return s?`?${s}`:""};function Ae(r){return"action"in r&&r.action==="ping"}function we(r){return"action"in r&&r.action==="data_exchange"}function Se(r){return"action"in r&&r.action!=="BACK"&&"data"in r&&typeof r.data=="object"&&r.data!==null&&("error_key"in r.data&&r.data.error_key!==void 0||"error_message"in r.data&&r.data.error_message!==void 0)}var ke="BaseAPI",Ke=!1,Je=new b(ke,process.env.DEBUG==="true"||Ke),h=class{config;client;constructor(t,s){this.config=t,this.client=s,Je.log("Initialized with HTTPSClient")}sendJson(t,s,i,o){return this.client.getJson(t,s,i,o)}sendFormData(t,s,i,o){return this.client.sendFormData(t,s,i,o)}sendUrlEncodedForm(t,s,i,o){return this.client.sendUrlEncodedForm(t,s,i,o)}};function K(r){if(!r)return"";let t="";return Array.isArray(r)?t=r.join(","):t=Object.entries(r).filter(([s,i])=>i).map(([s])=>s).join(","),t?`?fields=${t}`:""}var N=class extends h{endpoint="whatsapp_business_profile";constructor(t,s){super(t,s)}async getBusinessProfile(t){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${K(t)}`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessProfile(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async createUploadSession(t,s,i){let o=S({file_length:t,file_type:s,file_name:i});return this.sendJson("POST",`app/uploads/${o}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(t,s){return this.sendJson("POST",`${t}`,this.config.REQUEST_TIMEOUT,s)}async getUploadHandle(t){return this.sendJson("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}};var M=class extends h{endpoint="whatsapp_business_encryption";constructor(t,s){super(t,s)}async getEncryptionPublicKey(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async setEncryptionPublicKey(t){let s=new FormData;return s.append("business_public_key",t),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,s)}};var $e="FlowAPI",Ve=!1,Te=new b($e,process.env.DEBUG==="true"||Ve),B=class extends h{constructor(t,s){super(t,s),Te.log("FlowAPI initialized")}async listFlows(t){return this.sendJson("GET",`/${t}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(t,s){let i={name:s.name,categories:s.categories,...s.endpoint_uri&&{endpoint_uri:s.endpoint_uri},...s.clone_flow_id&&{clone_flow_id:s.clone_flow_id},...s.flow_json&&{flow_json:s.flow_json},...s.publish!==void 0&&{publish:s.publish}};return this.sendJson("POST",`/${t}/flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async getFlow(t,s,i){let o=new URLSearchParams;s&&o.append("fields",s),i&&o.append("date_format",i);let n=o.toString()?`?${o.toString()}`:"";return this.sendJson("GET",`/${t}${n}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(t,s=!1){let i=`preview.invalidate(${s})`;return this.getFlow(t,i)}async updateFlowMetadata(t,s){let i={...s.name&&{name:s.name},...s.categories&&{categories:s.categories},...s.endpoint_uri&&{endpoint_uri:s.endpoint_uri},...s.application_id&&{application_id:s.application_id}};return this.sendJson("POST",`/${t}`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async deleteFlow(t){return this.sendJson("DELETE",`/${t}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(t){return this.sendJson("GET",`/${t}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(t,s){let i=new FormData,o;if(s.file instanceof Buffer)o=new globalThis.Blob([s.file]),i.append("file",o);else if(typeof s.file=="object"&&!(s.file instanceof Blob))try{o=new globalThis.Blob([JSON.stringify(s.file,null,2)],{type:"application/json"}),i.append("file",o)}catch{throw new Error("Failed to stringify JSON object for Flow JSON update.")}else if(s.file instanceof Blob)o=s.file,i.append("file",o);else throw new Error("Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.");return i.append("asset_type","FLOW_JSON"),i.append("name",s.name||"flow.json"),this.sendFormData("POST",`/${t}/assets`,this.config.REQUEST_TIMEOUT,i)}async validateFlowJson(t,s){try{let i=await this.updateFlowJson(t,{file:s}),o=!i.validation_errors||i.validation_errors.length===0;return{...i,valid:o}}catch(i){throw Te.error("Error during Flow JSON validation attempt:",i),i}}async publishFlow(t){return this.sendJson("POST",`/${t}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(t){return this.sendJson("POST",`/${t}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(t,s){let i={source_waba_id:s.source_waba_id,...s.source_flow_names&&{source_flow_names:s.source_flow_names}};return this.sendJson("POST",`/${t}/migrate_flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}};var y=class extends h{endpoint="media";constructor(t,s){super(t,s)}async getMediaById(t){return this.sendJson("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(t,s="whatsapp"){let i=new FormData;return i.append("file",t),i.append("messaging_product",s),i.append("type",t.type),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,i)}async deleteMedia(t){return this.sendJson("DELETE",`${t}`,this.config.REQUEST_TIMEOUT,null)}async downloadMedia(t){return this.sendJson("GET",t,this.config.REQUEST_TIMEOUT,null)}};var O=class extends h{commonMethod="POST";commonEndpoint="messages";constructor(t,s){super(t,s)}bodyBuilder(t,s,i,o){let n={messaging_product:"whatsapp",recipient_type:"individual",to:i,type:t,[t]:s};return o&&(n.context={message_id:o}),n}send(t){return this.sendJson(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/${this.commonEndpoint}`,this.config.REQUEST_TIMEOUT,t)}async audio(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("audio",s,i,o)))}async contacts(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("contacts",s,i,o)))}async document(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("document",s,i,o)))}async image(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("image",s,i,o)))}async interactive(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async location(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("location",s,i,o)))}async sticker(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("sticker",s,i,o)))}async template(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("template",s,i,o)))}async text(t){let{body:s,previewUrl:i,to:o,replyMessageId:n}=t,f;return typeof s=="string"?f={body:s,preview_url:i}:f=s,this.send(JSON.stringify(this.bodyBuilder("text",f,o,n)))}async video(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("video",s,i,o)))}async status(t){let{status:s,messageId:i,typingIndicator:o}=t,n={messaging_product:"whatsapp",status:s,message_id:i,...o&&{typing_indicator:o}};return this.send(JSON.stringify(n))}async markAsRead(t){return this.status({status:"read",messageId:t.messageId})}async showTypingIndicator(t){return this.status({status:"read",messageId:t.messageId,typingIndicator:{type:"text"}})}async interactiveList(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveCtaUrl(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveLocationRequest(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveAddressMessage(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveReplyButtons(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveFlow(t){let{body:s,to:i,replyMessageId:o}=t;return s.action.parameters.flow_message_version===void 0&&(s.action.parameters.flow_message_version="3"),s.action.parameters.mode===void 0&&(s.action.parameters.mode="published"),s.action.parameters.flow_action===void 0&&(s.action.parameters.flow_action="navigate"),s.action.parameters.flow_action==="navigate"?s.action.parameters.flow_action_payload?.screen===void 0&&(s.action.parameters.flow_action_payload={...s.action.parameters.flow_action_payload,screen:"INIT"}):s.action.parameters.flow_action==="data_exchange"&&delete s.action.parameters.flow_action_payload,this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async reaction(t){let{messageId:s,emoji:i,to:o}=t,n={messaging_product:"whatsapp",recipient_type:"individual",to:o,type:"reaction",reaction:{message_id:s,emoji:i}};return this.send(JSON.stringify(n))}};var D=class extends h{endpoint="phone_numbers";constructor(t,s){super(t,s)}async getPhoneNumberById(t){let s=t?S({fields:t}):"";return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}${s}`,this.config.REQUEST_TIMEOUT,null)}async getPhoneNumbers(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async requestVerificationCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async verifyCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};var v=class extends h{endpoint="message_qrdls";constructor(t,s){super(t,s)}async createQrCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getQrCodes(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async getQrCode(t){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${t}`,this.config.REQUEST_TIMEOUT,null)}async updateQrCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteQrCode(t){return this.sendJson("DELETE",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${t}`,this.config.REQUEST_TIMEOUT,null)}};var x=class extends h{constructor(t,s){super(t,s)}async register(t,s){let i={messaging_product:"whatsapp",pin:t,...s&&{data_localization_region:s}};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/register`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async deregister(){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/deregister`,this.config.REQUEST_TIMEOUT,null)}};var F=class extends h{endpoint="message_templates";constructor(t,s){super(t,s)}async getTemplate(t){return this.sendJson("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}async updateTemplate(t,s){return this.sendJson("POST",`${t}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async getTemplates(t){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${S(t)}`,this.config.REQUEST_TIMEOUT,null)}async createTemplate(t){return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteTemplate(t){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${S(t)}`,this.config.REQUEST_TIMEOUT,null)}};var u=class extends h{constructor(t,s){super(t,s)}async setTwoStepVerificationCode(t){let s={pin:t};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}};var q=class extends h{constructor(t,s){super(t,s)}async getWabaAccount(t){let s=K(t)?.replace(/,/g,"%2C");return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}${s}`,this.config.REQUEST_TIMEOUT,null)}async getAllWabaSubscriptions(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async updateWabaSubscription({override_callback_uri:t,verify_token:s}){let i={override_callback_uri:t,verify_token:s};return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async unsubscribeFromWaba(){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}};import{Agent as je}from"https";var Xe="HttpsClient",Ye=!1,Ze=new b(Xe,process.env.DEBUG==="true"||Ye),W=class{agent;constructor(){this.agent=new je({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(t,s,i,o,n,f){let p=`https://${t}/${s}`,l=new AbortController,c=setTimeout(()=>l.abort(),n);try{let g=await fetch(p,{method:i,headers:o,body:f,signal:l.signal});return Ze.log(`${i} : ${p} - ${JSON.stringify(g)}`),clearTimeout(c),new j(g)}catch(g){throw g}}},j=class{res;respStatusCode;respHeaders;constructor(t){this.res=t,this.respStatusCode=t.status,this.respHeaders=Object.fromEntries(t.headers.entries())}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(t){throw new Error("Failed to parse response body to JSON: "+t.message)}}};var Qe="REQUESTER",ze=!1,Ee=new b(Qe,process.env.DEBUG==="true"||ze),H=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(t,s,i,o,n){this.client=new W,this.host="graph.facebook.com",this.apiVersion=t||"22",this.phoneNumberId=s,this.accessToken=i,this.businessAcctId=o,this.userAgent=n}buildHeader(t,s){let i={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return t!=="multipart/form-data"&&(i["Content-Type"]=t),s&&Object.assign(i,s),i}buildCAPIPath(t){return`v${this.apiVersion}.0/${t}`}async sendRequest(t,s,i,o,n="application/json",f){let p=n;o instanceof FormData?p="multipart/form-data":typeof o=="string"&&o.startsWith("<?xml")&&(p="application/xml");let l=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(s)}`;Ee.log(`${t} : ${l} (${p})`);try{let c=await this.client.sendRequest(this.host,this.buildCAPIPath(s),t,this.buildHeader(p,f),i,t==="POST"||t==="PUT"?o:void 0);if(!c.rawResponse().ok){let g=await c.json();throw V(g)?g:{name:"MetaError",message:"Unknown error occurred",error:{message:g.message||"Unknown error occurred",type:"UnknownError",code:c.statusCode(),fbtrace_id:""}}}return c}catch(c){throw V(c)?c:{name:"MetaError",message:c instanceof Error?c.message:"Network error occurred",error:{message:c instanceof Error?c.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}async getJson(t,s,i,o,n){return await(await this.sendRequest(t,s,i,o,"application/json",n)).json()}async sendFormData(t,s,i,o,n){return await(await this.sendRequest(t,s,i,o,"multipart/form-data",n)).json()}async sendUrlEncodedForm(t,s,i,o,n){let f=new URLSearchParams(o).toString();return await(await this.sendRequest(t,s,i,f,"application/x-www-form-urlencoded",n)).json()}};var Ce="WHATSAPP",et=!1,G=new b(Ce,process.env.DEBUG==="true"||et),tt="WA_SDK",T=class{config;requester;messages;templates;phoneNumber;qrCode;encryption;twoStepVerification;registration;media;waba;flow;businessProfile;static Enums=$;constructor(t){this.config=k(t),this.requester=new H(this.config.CLOUD_API_VERSION,this.config.WA_PHONE_NUMBER_ID,this.config.CLOUD_API_ACCESS_TOKEN,this.config.WA_BUSINESS_ACCOUNT_ID,this.userAgent()),this.messages=new O(this.config,this.requester),this.templates=new F(this.config,this.requester),this.phoneNumber=new D(this.config,this.requester),this.qrCode=new v(this.config,this.requester),this.encryption=new M(this.config,this.requester),this.twoStepVerification=new u(this.config,this.requester),this.registration=new x(this.config,this.requester),this.media=new y(this.config,this.requester),this.waba=new q(this.config,this.requester),this.flow=new B(this.config,this.requester),this.businessProfile=new N(this.config,this.requester),G.log("WhatsApp Node.js SDK instantiated!")}userAgent(){return`${tt}/0.0.1 (Node.js ${process.version})`}updateTimeout(t){return this.config.REQUEST_TIMEOUT=t,G.log(`Updated request timeout to ${t}ms`),!0}updatePhoneNumberId(t){return this.config.WA_PHONE_NUMBER_ID=t,G.log(`Updated sender phone number id to ${t}`),!0}updateAccessToken(t){return this.config.CLOUD_API_ACCESS_TOKEN=t,G.log("Updated access token"),!0}updateWabaId(t){return this.config.WA_BUSINESS_ACCOUNT_ID=t,G.log(`Updated business account id to ${t}`),!0}};var st="WEBHOOK",it=!1,_=new b(st,process.env.DEBUG==="true"||it),J=class{config;client;messageHandlers=new Map;eventHandlers=new Map;preProcessHandler=null;postProcessHandler=null;flowHandlers=new Map;constructor(t){let s=k(t);this.config=s,this.client=new T(t),_.log("WebhookHandler instantiated!")}handleVerificationRequest(t,s){let i=t.query["hub.mode"],o=t.query["hub.verify_token"],n=t.query["hub.challenge"];i==="subscribe"&&o===this.config.WEBHOOK_VERIFICATION_TOKEN?(_.log("Webhook verified successfully"),s.status(200).send(n)):(_.log("Webhook verification failed"),s.status(403).end())}async handleWebhookRequest(t,s){let i=t.body;if(i.object!=="whatsapp_business_account"){_.log("Received webhook for non-WhatsApp event"),s.status(404).end();return}for(let o of i.entry)try{let n=o.changes;for(let f of n)f.field==="messages"?await this.processMessages(f.value):await this.processEvent(f.field,f.value)}catch(n){_.log(`Error processing webhook: ${n}`)}s.status(200).end()}handleRequest(t,s){if(t.method==="GET")return this.handleVerificationRequest(t,s);if(t.method==="POST")return this.handleWebhookRequest(t,s);s.status(405).end()}async processMessages(t){let s=t.metadata,i=s.display_phone_number,o=s.phone_number_id,n=t.contacts[0].profile.name,f=t.messages;if(f&&f.length>0)for(let p of f){let l=p.type,c={id:p.id,from:p.from,timestamp:p.timestamp,type:p.type,phoneNumberId:o,displayPhoneNumber:i,profileName:n,originalData:p};switch(p.type){case"text":c.text=p.text;break;case"image":c.image=p.image;break;case"video":c.video=p.video;break;case"audio":c.audio=p.audio;break;case"document":c.document=p.document;break;case"sticker":c.sticker=p.sticker;break;case"location":c.location=p.location;break;case"contacts":c.contacts=p.contacts;break;case"interactive":c.interactive=p.interactive;break;case"button":c.button=p.button;break;case"order":c.order=p.order;break;case"system":c.system=p.system;break;default:break}if(p.context&&(c.context=p.context),p.errors&&(c.errors=p.errors),this.preProcessHandler&&await Promise.resolve(this.preProcessHandler(this.client,c)),this.messageHandlers.has(l)){let g=this.messageHandlers.get(l);g&&await Promise.resolve(g(this.client,c))}if(this.messageHandlers.has("*")){let g=this.messageHandlers.get("*");g&&await Promise.resolve(g(this.client,c))}this.postProcessHandler&&await Promise.resolve(this.postProcessHandler(this.client,c))}t.statuses&&t.statuses.length>0&&await this.processEvent("statuses",t)}async processEvent(t,s){let i={field:t,value:s};if(this.eventHandlers.has(t)){let o=this.eventHandlers.get(t);o&&await Promise.resolve(o(i))}if(this.eventHandlers.has("*")){let o=this.eventHandlers.get("*");o&&await Promise.resolve(o(i))}}onMessage(t,s){this.messageHandlers.set(t,s),_.log(`Registered handler for message type: ${t}`)}onEvent(t,s){this.eventHandlers.set(t,s),_.log(`Registered handler for event field: ${t}`)}onMessagePreProcess(t){this.preProcessHandler=t,_.log("Registered pre-processing handler for all messages")}onMessagePostProcess(t){this.postProcessHandler=t,_.log("Registered post-processing handler for all messages")}async handleFlowRequest(t,s){if(!this.isRequestSignatureValid(t)){s.status(403).end();return}let i;try{i=this.decryptRequest(t.body)}catch(g){if(_.error(g),g instanceof Error){s.status(421).send(g.message);return}s.status(500).send("internal server error, please check with logs");return}let{decryptedBody:o,aesKeyBuffer:n,initialVectorBuffer:f}=i,p;Ae(o)?p="ping":we(o)?p="data_exchange":Se(o)&&(p="error");let l=o;if(p&&this.flowHandlers.has(p)){let g=this.flowHandlers.get(p);if(g){let R=await Promise.resolve(g(this.client,l)),U=this.encryptResponse(R,n,f);s.status(200).send(U);return}}if(this.flowHandlers.has("*")){let g=this.flowHandlers.get("*");if(g){let R=await Promise.resolve(g(this.client,l)),U=this.encryptResponse(R,n,f);s.status(200).send(U);return}}let c=this.encryptResponse({},n,f);s.status(200).send(c)}isRequestSignatureValid(t){let s=this.config.M4D_APP_SECRET;if(!s)return _.warn("App Secret is not set up. Please Add M4D_APP_SECRET or configuration"),!1;let i=t.headers["x-hub-signature-256"];if(!i||typeof i!="string")return _.warn("x-hub-signature-256 header is missing"),!1;let o=Buffer.from(i.replace("sha256=",""),"utf-8"),f=I.createHmac("sha256",s).update(t.rawBody).digest("hex"),p=Buffer.from(f,"utf-8");return I.timingSafeEqual(p,o)?!0:(_.error("Error: Request Signature did not match"),!1)}decryptRequest(t){let{encrypted_aes_key:s,encrypted_flow_data:i,initial_vector:o}=t,n=this.config.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
2
- `),f=this.config.FLOW_API_PASSPHRASE,p=I.createPrivateKey({key:n,passphrase:f}),l=null;try{l=I.privateDecrypt({key:p,padding:I.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(s,"base64"))}catch(Ne){throw _.error(Ne),new Error("Failed to decrypt the request. Please verify your private key.")}let c=Buffer.from(i,"base64"),g=Buffer.from(o,"base64"),R=16,U=c.subarray(0,-R),Ie=c.subarray(-R),P=I.createDecipheriv("aes-128-gcm",l,g);P.setAuthTag(Ie);let d=Buffer.concat([P.update(U),P.final()]).toString("utf-8");return{decryptedBody:JSON.parse(d),aesKeyBuffer:l,initialVectorBuffer:g}}encryptResponse(t,s,i){let o=[];for(let n of Array.from(i.entries()))o.push(~n[1]);try{let n=I.createCipheriv("aes-128-gcm",s,Buffer.from(o));return Buffer.concat([n.update(JSON.stringify(t||{}),"utf-8"),n.final(),n.getAuthTag()]).toString("base64")}catch(n){throw _.error("Response encryption error:",n),new Error("Failed to encrypt response. Internal server error.")}}onFlow(t,s){this.flowHandlers.set(t,s),_.log(`Registered handler for Flow type: ${t}`)}};var Mi=T;export{ae as AudioMediaTypesEnum,he as BusinessVerticalEnum,E as ButtonPositionEnum,z as ButtonTypesEnum,X as CategoryEnum,C as ComponentTypesEnum,ee as ConversationTypesEnum,de as CurrencyCodesEnum,ge as DataLocalizationRegionEnum,re as DocumentMediaTypesEnum,Pe as EventField,me as FlowActionEnum,Oe as FlowCategoryEnum,ye as FlowStatusEnum,Re as FlowTypeEnum,w as HttpMethodsEnum,oe as ImageMediaTypesEnum,Q as InteractiveTypesEnum,fe as LanguagesEnum,ue as MessageStatus,L as MessageTypesEnum,Z as ParametersTypesEnum,le as ReferralSourceTypesEnum,ce as RequestCodeMethodsEnum,te as StatusEnum,ie as StickerMediaTypesEnum,pe as SystemChangeTypesEnum,Y as TemplateStatusEnum,se as VideoMediaTypesEnum,De as WabaAccountReviewStatus,xe as WabaAccountStatus,Fe as WabaBusinessVerificationStatus,A as WabaConfigEnum,ve as WabaHealthStatusCanSendMessage,J as WebhookHandler,ne as WebhookTypesEnum,Mi as default,yt as generateXHub256Sig,k as importConfig,we as isFlowDataExchangeRequest,Se as isFlowErrorRequest,Ae as isFlowPingRequest,V as isMetaError,S as objectToQueryString};
1
+ var Be=Object.defineProperty;var Oe=(r,t)=>{for(var s in t)Be(r,s,{get:t[s],enumerable:!0})};var V={};Oe(V,{AudioMediaTypesEnum:()=>ne,BusinessVerticalEnum:()=>me,ButtonPositionEnum:()=>C,ButtonTypesEnum:()=>E,CategoryEnum:()=>Y,ComponentTypesEnum:()=>ee,ConversationTypesEnum:()=>te,CurrencyCodesEnum:()=>ge,DataLocalizationRegionEnum:()=>he,DocumentMediaTypesEnum:()=>ae,HttpMethodsEnum:()=>S,ImageMediaTypesEnum:()=>re,InteractiveTypesEnum:()=>z,LanguagesEnum:()=>de,MessageTypesEnum:()=>L,ParametersTypesEnum:()=>Q,ReferralSourceTypesEnum:()=>ce,RequestCodeMethodsEnum:()=>fe,StatusEnum:()=>se,StickerMediaTypesEnum:()=>oe,SystemChangeTypesEnum:()=>le,TemplateStatusEnum:()=>Z,VideoMediaTypesEnum:()=>ie,WabaConfigEnum:()=>A,WebhookTypesEnum:()=>pe});var Y=(i=>(i.Authentication="AUTHENTICATION",i.Marketing="MARKETING",i.Utility="UTILITY",i))(Y||{}),Z=(i=>(i.Approved="APPROVED",i.Pending="PENDING",i.Rejected="REJECTED",i))(Z||{}),S=(o=>(o.Get="GET",o.Post="POST",o.Put="PUT",o.Delete="DELETE",o))(S||{}),L=(d=>(d.Audio="audio",d.Contacts="contacts",d.Document="document",d.Image="image",d.Interactive="interactive",d.Location="location",d.Reaction="reaction",d.Sticker="sticker",d.Template="template",d.Text="text",d.Video="video",d.Button="button",d.Order="order",d.System="system",d.Unknown="unknown",d["*"]="*",d))(L||{}),Q=(p=>(p.Currency="currency",p.DateTime="date_time",p.Document="document",p.Image="image",p.Text="text",p.Video="video",p.Payload="payload",p))(Q||{}),z=(l=>(l.Button="button",l.List="list",l.Product="product",l.ProductList="product_list",l.CtaUrl="cta_url",l.LocationRequest="location_request_message",l.AddressMessage="address_message",l.Flow="flow",l))(z||{}),E=(s=>(s.QuickReply="quick_reply",s.URL="url",s))(E||{}),C=(i=>(i[i.First=0]="First",i[i.Second=1]="Second",i[i.Third=2]="Third",i))(C||{}),ee=(o=>(o.Header="HEADER",o.Body="BODY",o.Button="BUTTON",o.Footer="FOOTER",o))(ee||{}),A=(d=>(d.AppId="M4D_APP_ID",d.Port="WA_PORT",d.AppSecret="M4D_APP_SECRET",d.PhoneNumberId="WA_PHONE_NUMBER_ID",d.BusinessAcctId="WA_BUSINESS_ACCOUNT_ID",d.APIVersion="CLOUD_API_VERSION",d.AccessToken="CLOUD_API_ACCESS_TOKEN",d.WebhookEndpoint="WEBHOOK_ENDPOINT",d.WebhookVerificationToken="WEBHOOK_VERIFICATION_TOKEN",d.ListenerPort="LISTENER_PORT",d.MaxRetriesAfterWait="MAX_RETRIES_AFTER_WAIT",d.RequestTimeout="REQUEST_TIMEOUT",d.Debug="DEBUG",d.PrivatePem="FLOW_API_PRIVATE_PEM",d.Passphrase="FLOW_API_PASSPHRASE",d))(A||{}),te=(i=>(i.BusinessInitiated="business_initiated",i.CustomerInitiated="customer_initiated",i.ReferralConversion="referral_conversion",i))(te||{}),se=(i=>(i.Delivered="delivered",i.Read="read",i.Sent="sent",i))(se||{}),ie=(s=>(s.Mp4="video/mp4",s.Threegp="video/3gp",s))(ie||{}),oe=(t=>(t.Webp="image/webp",t))(oe||{}),re=(s=>(s.Jpeg="image/jpeg",s.Png="image/png",s))(re||{}),ae=(l=>(l.Text="text/plain",l.Pdf="application/pdf",l.Ppt="application/vnd.ms-powerpoint",l.Word="application/msword",l.Excel="application/vnd.ms-excel",l.OpenDoc="application/vnd.openxmlformats-officedocument.wordprocessingml.document",l.OpenPres="application/vnd.openxmlformats-officedocument.presentationml.presentation",l.OpenSheet="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",l))(ae||{}),ne=(n=>(n.Aac="audio/aac",n.Mp4="audio/mp4",n.Mpeg="audio/mpeg",n.Amr="audio/amr",n.Ogg="audio/ogg",n))(ne||{}),pe=(R=>(R.Audio="audio",R.Button="button",R.Document="document",R.Text="text",R.Image="image",R.Interactive="interactive",R.Order="order",R.Sticker="sticker",R.System="system",R.Unknown="unknown",R.Video="video",R))(pe||{}),le=(s=>(s.CustomerChangedNumber="customer_changed_number",s.CustomerIdentityChanged="customer_identity_changed",s))(le||{}),ce=(s=>(s.Ad="ad",s.Post="post",s))(ce||{}),fe=(s=>(s.Sms="SMS",s.Voice="VOICE",s))(fe||{}),de=(a=>(a.Afrikaans="af",a.Albanian="sq",a.Arabic="ar",a.Azerbaijani="az",a.Bengali="bn",a.Bulgarian="bg",a.Catalan="ca",a.Chinese_CHN="zh_CN",a.Chinese_HKG="zh_HK",a.Chinese_TAI="zh_TW",a.Croatian="hr",a.Czech="cs",a.Danish="da",a.Dutch="nl",a.English="en",a.English_UK="en_GB",a.English_US="en_US",a.Estonian="et",a.Filipino="fil",a.Finnish="fi",a.French="fr",a.Georgian="ka",a.German="de",a.Greek="el",a.Gujarati="gu",a.Hausa="ha",a.Hebrew="he",a.Hindi="hi",a.Hungarian="hu",a.Indonesian="id",a.Irish="ga",a.Italian="it",a.Japanese="ja",a.Kannada="kn",a.Kazakh="kk",a.Kinyarwanda="rw_RW",a.Korean="ko",a.Kyrgyz_Kyrgyzstan="ky_KG",a.Lao="lo",a.Latvian="lv",a.Lithuanian="lt",a.Macedonian="mk",a.Malay="ms",a.Malayalam="ml",a.Marathi="mr",a.Norwegian="nb",a.Persian="fa",a.Polish="pl",a.Portuguese_BR="pt_BR",a.Portuguese_POR="pt_PT",a.Punjabi="pa",a.Romanian="ro",a.Russian="ru",a.Serbian="sr",a.Slovak="sk",a.Slovenian="sl",a.Spanish="es",a.Spanish_ARG="es_AR",a.Spanish_SPA="es_ES",a.Spanish_MEX="es_MX",a.Swahili="sw",a.Swedish="sv",a.Tamil="ta",a.Telugu="te",a.Thai="th",a.Turkish="tr",a.Ukrainian="uk",a.Urdu="ur",a.Uzbek="uz",a.Vietnamese="vi",a.Zulu="zu",a))(de||{}),ge=(e=>(e.AFN="AFN",e.EUR="EUR",e.ALL="ALL",e.DZD="DZD",e.USD="USD",e.AOA="AOA",e.XCD="XCD",e.ARS="ARS",e.AMD="AMD",e.AWG="AWG",e.AUD="AUD",e.AZN="AZN",e.BSD="BSD",e.BHD="BHD",e.BDT="BDT",e.BBD="BBD",e.BYN="BYN",e.BZD="BZD",e.XOF="XOF",e.BMD="BMD",e.INR="INR",e.BTN="BTN",e.BOB="BOB",e.BOV="BOV",e.BAM="BAM",e.BWP="BWP",e.NOK="NOK",e.BRL="BRL",e.BND="BND",e.BGN="BGN",e.BIF="BIF",e.CVE="CVE",e.KHR="KHR",e.XAF="XAF",e.CAD="CAD",e.KYD="KYD",e.CLP="CLP",e.CLF="CLF",e.CNY="CNY",e.COP="COP",e.COU="COU",e.KMF="KMF",e.CDF="CDF",e.NZD="NZD",e.CRC="CRC",e.HRK="HRK",e.CUP="CUP",e.CUC="CUC",e.ANG="ANG",e.CZK="CZK",e.DKK="DKK",e.DJF="DJF",e.DOP="DOP",e.EGP="EGP",e.SVC="SVC",e.ERN="ERN",e.SZL="SZL",e.ETB="ETB",e.FKP="FKP",e.FJD="FJD",e.XPF="XPF",e.GMD="GMD",e.GEL="GEL",e.GHS="GHS",e.GIP="GIP",e.GTQ="GTQ",e.GBP="GBP",e.GNF="GNF",e.GYD="GYD",e.HTG="HTG",e.HNL="HNL",e.HKD="HKD",e.HUF="HUF",e.ISK="ISK",e.IDR="IDR",e.XDR="XDR",e.IRR="IRR",e.IQD="IQD",e.ILS="ILS",e.JMD="JMD",e.JPY="JPY",e.JOD="JOD",e.KZT="KZT",e.KES="KES",e.KPW="KPW",e.KRW="KRW",e.KWD="KWD",e.KGS="KGS",e.LAK="LAK",e.LBP="LBP",e.LSL="LSL",e.ZAR="ZAR",e.LRD="LRD",e.LYD="LYD",e.CHF="CHF",e.MOP="MOP",e.MKD="MKD",e.MGA="MGA",e.MWK="MWK",e.MYR="MYR",e.MVR="MVR",e.MRU="MRU",e.MUR="MUR",e.XUA="XUA",e.MXN="MXN",e.MXV="MXV",e.MDL="MDL",e.MNT="MNT",e.MAD="MAD",e.MZN="MZN",e.MMK="MMK",e.NAD="NAD",e.NPR="NPR",e.NIO="NIO",e.NGN="NGN",e.OMR="OMR",e.PKR="PKR",e.PAB="PAB",e.PGK="PGK",e.PYG="PYG",e.PEN="PEN",e.PHP="PHP",e.PLN="PLN",e.QAR="QAR",e.RON="RON",e.RUB="RUB",e.RWF="RWF",e.SHP="SHP",e.WST="WST",e.STN="STN",e.SAR="SAR",e.RSD="RSD",e.SCR="SCR",e.SLL="SLL",e.SGD="SGD",e.XSU="XSU",e.SBD="SBD",e.SOS="SOS",e.SSP="SSP",e.LKR="LKR",e.SDG="SDG",e.SRD="SRD",e.SEK="SEK",e.CHE="CHE",e.CHW="CHW",e.SYP="SYP",e.TWD="TWD",e.TJS="TJS",e.TZS="TZS",e.THB="THB",e.TOP="TOP",e.TTD="TTD",e.TND="TND",e.TRY="TRY",e.TMT="TMT",e.UGX="UGX",e.UAH="UAH",e.AED="AED",e.USN="USN",e.UYU="UYU",e.UYI="UYI",e.UYW="UYW",e.UZS="UZS",e.VUV="VUV",e.VES="VES",e.VND="VND",e.YER="YER",e.ZMW="ZMW",e.ZWL="ZWL",e.XBA="XBA",e.XBB="XBB",e.XBC="XBC",e.XBD="XBD",e.XTS="XTS",e.XXX="XXX",e.XAU="XAU",e.XPD="XPD",e.XPT="XPT",e.XAG="XAG",e.AFA="AFA",e.FIM="FIM",e.ALK="ALK",e.ADP="ADP",e.ESP="ESP",e.FRF="FRF",e.AOK="AOK",e.AON="AON",e.AOR="AOR",e.ARA="ARA",e.ARP="ARP",e.ARY="ARY",e.RUR="RUR",e.ATS="ATS",e.AYM="AYM",e.AZM="AZM",e.BYB="BYB",e.BYR="BYR",e.BEC="BEC",e.BEF="BEF",e.BEL="BEL",e.BOP="BOP",e.BAD="BAD",e.BRB="BRB",e.BRC="BRC",e.BRE="BRE",e.BRN="BRN",e.BRR="BRR",e.BGJ="BGJ",e.BGK="BGK",e.BGL="BGL",e.BUK="BUK",e.HRD="HRD",e.CYP="CYP",e.CSJ="CSJ",e.CSK="CSK",e.ECS="ECS",e.ECV="ECV",e.GQE="GQE",e.EEK="EEK",e.XEU="XEU",e.GEK="GEK",e.DDM="DDM",e.DEM="DEM",e.GHC="GHC",e.GHP="GHP",e.GRD="GRD",e.GNE="GNE",e.GNS="GNS",e.GWE="GWE",e.GWP="GWP",e.ITL="ITL",e.ISJ="ISJ",e.IEP="IEP",e.ILP="ILP",e.ILR="ILR",e.LAJ="LAJ",e.LVL="LVL",e.LVR="LVR",e.LSM="LSM",e.ZAL="ZAL",e.LTL="LTL",e.LTT="LTT",e.LUC="LUC",e.LUF="LUF",e.LUL="LUL",e.MGF="MGF",e.MVQ="MVQ",e.MLF="MLF",e.MTL="MTL",e.MTP="MTP",e.MRO="MRO",e.MXP="MXP",e.MZE="MZE",e.MZM="MZM",e.NLG="NLG",e.NIC="NIC",e.PEH="PEH",e.PEI="PEI",e.PES="PES",e.PLZ="PLZ",e.PTE="PTE",e.ROK="ROK",e.ROL="ROL",e.STD="STD",e.CSD="CSD",e.SKK="SKK",e.SIT="SIT",e.RHD="RHD",e.ESA="ESA",e.ESB="ESB",e.SDD="SDD",e.SDP="SDP",e.SRG="SRG",e.CHC="CHC",e.TJR="TJR",e.TPE="TPE",e.TRL="TRL",e.TMM="TMM",e.UGS="UGS",e.UGW="UGW",e.UAK="UAK",e.SUR="SUR",e.USS="USS",e.UYN="UYN",e.UYP="UYP",e.VEB="VEB",e.VEF="VEF",e.VNC="VNC",e.YDD="YDD",e.YUD="YUD",e.YUM="YUM",e.YUN="YUN",e.ZRN="ZRN",e.ZRZ="ZRZ",e.ZMK="ZMK",e.ZWC="ZWC",e.ZWD="ZWD",e.ZWN="ZWN",e.ZWR="ZWR",e.XFO="XFO",e.XRE="XRE",e.XFU="XFU",e))(ge||{}),he=(P=>(P.AU="AU",P.ID="ID",P.IN="IN",P.JP="JP",P.SG="SG",P.KR="KR",P.DE="DE",P.CH="CH",P.GB="GB",P.BR="BR",P.BH="BH",P.ZA="ZA",P.AE="AE",P.CA="CA",P))(he||{}),me=(m=>(m.ALCOHOL="ALCOHOL",m.APPAREL="APPAREL",m.AUTO="AUTO",m.BEAUTY="BEAUTY",m.EDU="EDU",m.ENTERTAIN="ENTERTAIN",m.EVENT_PLAN="EVENT_PLAN",m.FINANCE="FINANCE",m.GOVT="GOVT",m.GROCERY="GROCERY",m.HEALTH="HEALTH",m.HOTEL="HOTEL",m.NONPROFIT="NONPROFIT",m.ONLINE_GAMBLING="ONLINE_GAMBLING",m.OTC_DRUGS="OTC_DRUGS",m.OTHER="OTHER",m.PHYSICAL_GAMBLING="PHYSICAL_GAMBLING",m.PROF_SERVICES="PROF_SERVICES",m.RESTAURANT="RESTAURANT",m.RETAIL="RETAIL",m.TRAVEL="TRAVEL",m))(me||{});var De=(n=>(n.Draft="DRAFT",n.Published="PUBLISHED",n.Throttled="THROTTLED",n.Blocked="BLOCKED",n.Deprecated="DEPRECATED",n))(De||{}),ve=(l=>(l.SignUp="SIGN_UP",l.SignIn="SIGN_IN",l.AppointmentBooking="APPOINTMENT_BOOKING",l.LeadGeneration="LEAD_GENERATION",l.ContactUs="CONTACT_US",l.CustomerSupport="CUSTOMER_SUPPORT",l.Survey="SURVEY",l.Other="OTHER",l))(ve||{}),Re=(i=>(i.INIT="INIT",i.BACK="BACK",i.DATA_EXCHANGE="data_exchange",i))(Re||{}),Pe=(o=>(o.Ping="ping",o.Change="data_exchange",o.Error="error",o.All="*",o))(Pe||{});var xe=(o=>(o.Approved="APPROVED",o.Active="ACTIVE",o.Inactive="INACTIVE",o.Disabled="DISABLED",o))(xe||{}),ue=(i=>(i.Blocked="BLOCKED",i.Limited="LIMITED",i.Available="AVAILABLE",i))(ue||{}),Fe=(o=>(o.Approved="APPROVED",o.Active="ACTIVE",o.Inactive="INACTIVE",o.Disabled="DISABLED",o))(Fe||{}),qe=(o=>(o.Verified="verified",o.PendingSubmission="pending_submission",o.Unverified="unverified",o.Rejected="rejected",o))(qe||{});var Ue=(i=>(i.DELIVERED="delivered",i.READ="read",i.SENT="sent",i))(Ue||{}),be=(c=>(c.MESSAGES="messages",c.STATUSES="statuses",c.MESSAGE_TEMPLATE_STATUS_UPDATE="message_template_status_update",c.PHONE_NUMBER_QUALITY_UPDATE="phone_number_quality_update",c.PHONE_NUMBER_NAME_UPDATE="phone_number_name_update",c.UNKNOWN="unknown",c))(be||{});import I from"crypto";import*as _e from"crypto";var xt=(r,t)=>_e.createHmac("sha256",t).update(r,"utf-8").digest("hex");var b=class{name;debug;constructor(t,s=!1){this.name=t,this.debug=s}log(...t){if(this.debug){let s=`[ ${Date.now()} ]`;this.name&&(s+=` - ${this.name}`),console.log.apply(console,[s,": ",...t])}}error(...t){let s=`[ ${Date.now()} ] - ERROR`;this.name&&(s+=` - ${this.name}`),console.error.apply(console,[s,": ",...t])}warn(...t){let s=`[ ${Date.now()} ] - WARN`;this.name&&(s+=` - ${this.name}`),console.warn.apply(console,[s,": ",...t])}info(...t){let s=`[ ${Date.now()} ] - INFO`;this.name&&(s+=` - ${this.name}`),console.info.apply(console,[s,": ",...t])}};var He="UTILS",We=!1,Ae=new b(He,process.env.DEBUG==="true"||We),Ge=3e3,ke=30,Le=2e4,Je=r=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!r?.accessToken)throw Ae.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},J=r=>{Je(r);let t={M4D_APP_ID:r?.appId||process.env.M4D_APP_ID||"",M4D_APP_SECRET:r?.appSecret||process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:r?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),WA_BUSINESS_ACCOUNT_ID:r?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||"",CLOUD_API_VERSION:r?.apiVersion||process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:r?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||"",WEBHOOK_ENDPOINT:r?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||"",WEBHOOK_VERIFICATION_TOKEN:r?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||"",LISTENER_PORT:r?.listenerPort||parseInt(process.env.LISTENER_PORT||"")||Ge,MAX_RETRIES_AFTER_WAIT:r?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||ke,REQUEST_TIMEOUT:r?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||"")||Le,DEBUG:r?.debug||process.env.DEBUG==="true",FLOW_API_PRIVATE_PEM:r?.privatePem||process.env.FLOW_API_PRIVATE_PEM||"",FLOW_API_PASSPHRASE:r?.passphrase||process.env.FLOW_API_PASSPHRASE||""};return Ae.log(`Configuration loaded for App Id ${t.M4D_APP_ID}`),t};function j(r){return r!=null&&typeof r=="object"&&"error"in r&&typeof r.error=="object"&&r.error!=null&&"message"in r.error&&typeof r.error.message=="string"&&"type"in r.error&&typeof r.error.type=="string"&&"code"in r.error&&typeof r.error.code=="number"&&"fbtrace_id"in r.error&&typeof r.error.fbtrace_id=="string"&&(!("error_data"in r.error)||typeof r.error.error_data=="object"&&r.error.error_data!=null&&"messaging_product"in r.error.error_data&&r.error.error_data.messaging_product==="whatsapp"&&"details"in r.error.error_data&&typeof r.error.error_data.details=="string")&&(!("error_subcode"in r.error)||typeof r.error.error_subcode=="number")}var w=r=>{if(!r||Object.keys(r).length===0)return"";let t=new URLSearchParams;for(let[i,o]of Object.entries(r))o!==void 0&&t.append(i,String(o));let s=t.toString();return s?`?${s}`:""};function Se(r){return typeof r=="object"&&r!==null}function N(r){return typeof r=="string"}var Ke=["data_exchange","INIT","BACK"],$e=["data_exchange","INIT"];function we(r){if(!("flow_token"in r&&N(r.flow_token)&&"action"in r))return!1;let{action:t,version:s,screen:i,data:o}=r,n=s==="3.0",c=Ke.includes(t),p=typeof i>"u"||N(i)&&i!=="SUCCESS",l=t==="data_exchange"||Se(o);return n&&c&&p&&l}function Te(r){if(!("flow_token"in r&&N(r.flow_token)&&"action"in r))return!1;let{action:t,screen:s,data:i}=r,o=$e.includes(t),n=N(s),c=Se(i)&&"error_key"in i&&N(i.error_key)&&"error_message"in i&&N(i.error_message);return o&&n&&c}function Ie(r){return"action"in r&&r.action==="ping"}var Ve="BaseAPI",je=!1,Xe=new b(Ve,process.env.DEBUG==="true"||je),h=class{config;client;constructor(t,s){this.config=t,this.client=s,Xe.log("Initialized with HTTPSClient")}sendJson(t,s,i,o){return this.client.getJson(t,s,i,o)}sendFormData(t,s,i,o){return this.client.sendFormData(t,s,i,o)}sendUrlEncodedForm(t,s,i,o){return this.client.sendUrlEncodedForm(t,s,i,o)}};function K(r){if(!r)return"";let t="";return Array.isArray(r)?t=r.join(","):t=Object.entries(r).filter(([s,i])=>i).map(([s])=>s).join(","),t?`?fields=${t}`:""}var M=class extends h{endpoint="whatsapp_business_profile";constructor(t,s){super(t,s)}async getBusinessProfile(t){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${K(t)}`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessProfile(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async createUploadSession(t,s,i){let o=w({file_length:t,file_type:s,file_name:i});return this.sendJson("POST",`app/uploads/${o}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(t,s){return this.sendJson("POST",`${t}`,this.config.REQUEST_TIMEOUT,s)}async getUploadHandle(t){return this.sendJson("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}};var y=class extends h{endpoint="whatsapp_business_encryption";constructor(t,s){super(t,s)}async getEncryptionPublicKey(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async setEncryptionPublicKey(t){let s=new FormData;return s.append("business_public_key",t),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,s)}};var Ye="FlowAPI",Ze=!1,Ne=new b(Ye,process.env.DEBUG==="true"||Ze),B=class extends h{constructor(t,s){super(t,s),Ne.log("FlowAPI initialized")}async listFlows(t){return this.sendJson("GET",`/${t}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(t,s){let i={name:s.name,categories:s.categories,...s.endpoint_uri&&{endpoint_uri:s.endpoint_uri},...s.clone_flow_id&&{clone_flow_id:s.clone_flow_id},...s.flow_json&&{flow_json:s.flow_json},...s.publish!==void 0&&{publish:s.publish}};return this.sendJson("POST",`/${t}/flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async getFlow(t,s,i){let o=new URLSearchParams;s&&o.append("fields",s),i&&o.append("date_format",i);let n=o.toString()?`?${o.toString()}`:"";return this.sendJson("GET",`/${t}${n}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(t,s=!1){let i=`preview.invalidate(${s})`;return this.getFlow(t,i)}async updateFlowMetadata(t,s){let i={...s.name&&{name:s.name},...s.categories&&{categories:s.categories},...s.endpoint_uri&&{endpoint_uri:s.endpoint_uri},...s.application_id&&{application_id:s.application_id}};return this.sendJson("POST",`/${t}`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async deleteFlow(t){return this.sendJson("DELETE",`/${t}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(t){return this.sendJson("GET",`/${t}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(t,s){let i=new FormData,o;if(s.file instanceof Buffer)o=new globalThis.Blob([s.file]),i.append("file",o);else if(typeof s.file=="object"&&!(s.file instanceof Blob))try{o=new globalThis.Blob([JSON.stringify(s.file,null,2)],{type:"application/json"}),i.append("file",o)}catch{throw new Error("Failed to stringify JSON object for Flow JSON update.")}else if(s.file instanceof Blob)o=s.file,i.append("file",o);else throw new Error("Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.");return i.append("asset_type","FLOW_JSON"),i.append("name",s.name||"flow.json"),this.sendFormData("POST",`/${t}/assets`,this.config.REQUEST_TIMEOUT,i)}async validateFlowJson(t,s){try{let i=await this.updateFlowJson(t,{file:s}),o=!i.validation_errors||i.validation_errors.length===0;return{...i,valid:o}}catch(i){throw Ne.error("Error during Flow JSON validation attempt:",i),i}}async publishFlow(t){return this.sendJson("POST",`/${t}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(t){return this.sendJson("POST",`/${t}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(t,s){let i={source_waba_id:s.source_waba_id,...s.source_flow_names&&{source_flow_names:s.source_flow_names}};return this.sendJson("POST",`/${t}/migrate_flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}};var O=class extends h{endpoint="media";constructor(t,s){super(t,s)}async getMediaById(t){return this.sendJson("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(t,s="whatsapp"){let i=new FormData;return i.append("file",t),i.append("messaging_product",s),i.append("type",t.type),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,i)}async deleteMedia(t){return this.sendJson("DELETE",`${t}`,this.config.REQUEST_TIMEOUT,null)}async downloadMedia(t){return this.sendJson("GET",t,this.config.REQUEST_TIMEOUT,null)}};var D=class extends h{commonMethod="POST";commonEndpoint="messages";constructor(t,s){super(t,s)}bodyBuilder(t,s,i,o){let n={messaging_product:"whatsapp",recipient_type:"individual",to:i,type:t,[t]:s};return o&&(n.context={message_id:o}),n}send(t){return this.sendJson(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/${this.commonEndpoint}`,this.config.REQUEST_TIMEOUT,t)}async audio(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("audio",s,i,o)))}async contacts(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("contacts",s,i,o)))}async document(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("document",s,i,o)))}async image(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("image",s,i,o)))}async interactive(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async location(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("location",s,i,o)))}async sticker(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("sticker",s,i,o)))}async template(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("template",s,i,o)))}async text(t){let{body:s,previewUrl:i,to:o,replyMessageId:n}=t,c;return typeof s=="string"?c={body:s,preview_url:i}:c=s,this.send(JSON.stringify(this.bodyBuilder("text",c,o,n)))}async video(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("video",s,i,o)))}async status(t){let{status:s,messageId:i,typingIndicator:o}=t,n={messaging_product:"whatsapp",status:s,message_id:i,...o&&{typing_indicator:o}};return this.send(JSON.stringify(n))}async markAsRead(t){return this.status({status:"read",messageId:t.messageId})}async showTypingIndicator(t){return this.status({status:"read",messageId:t.messageId,typingIndicator:{type:"text"}})}async interactiveList(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveCtaUrl(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveLocationRequest(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveAddressMessage(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveReplyButtons(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveFlow(t){let{body:s,to:i,replyMessageId:o}=t;return s.action.parameters.flow_message_version===void 0&&(s.action.parameters.flow_message_version="3"),s.action.parameters.mode===void 0&&(s.action.parameters.mode="published"),s.action.parameters.flow_action===void 0&&(s.action.parameters.flow_action="navigate"),s.action.parameters.flow_action==="navigate"?s.action.parameters.flow_action_payload?.screen===void 0&&(s.action.parameters.flow_action_payload={...s.action.parameters.flow_action_payload,screen:"INIT"}):s.action.parameters.flow_action==="data_exchange"&&delete s.action.parameters.flow_action_payload,this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async reaction(t){let{messageId:s,emoji:i,to:o}=t,n={messaging_product:"whatsapp",recipient_type:"individual",to:o,type:"reaction",reaction:{message_id:s,emoji:i}};return this.send(JSON.stringify(n))}};var v=class extends h{endpoint="phone_numbers";constructor(t,s){super(t,s)}async getPhoneNumberById(t){let s=t?w({fields:t}):"";return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}${s}`,this.config.REQUEST_TIMEOUT,null)}async getPhoneNumbers(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async requestVerificationCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async verifyCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};var x=class extends h{endpoint="message_qrdls";constructor(t,s){super(t,s)}async createQrCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getQrCodes(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async getQrCode(t){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${t}`,this.config.REQUEST_TIMEOUT,null)}async updateQrCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteQrCode(t){return this.sendJson("DELETE",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${t}`,this.config.REQUEST_TIMEOUT,null)}};var u=class extends h{constructor(t,s){super(t,s)}async register(t,s){let i={messaging_product:"whatsapp",pin:t,...s&&{data_localization_region:s}};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/register`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async deregister(){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/deregister`,this.config.REQUEST_TIMEOUT,null)}};var F=class extends h{endpoint="message_templates";constructor(t,s){super(t,s)}async getTemplate(t){return this.sendJson("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}async updateTemplate(t,s){return this.sendJson("POST",`${t}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async getTemplates(t){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${w(t)}`,this.config.REQUEST_TIMEOUT,null)}async createTemplate(t){return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteTemplate(t){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${w(t)}`,this.config.REQUEST_TIMEOUT,null)}};var q=class extends h{constructor(t,s){super(t,s)}async setTwoStepVerificationCode(t){let s={pin:t};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}};var U=class extends h{constructor(t,s){super(t,s)}async getWabaAccount(t){let s=K(t)?.replace(/,/g,"%2C");return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}${s}`,this.config.REQUEST_TIMEOUT,null)}async getAllWabaSubscriptions(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async updateWabaSubscription({override_callback_uri:t,verify_token:s}){let i={override_callback_uri:t,verify_token:s};return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async unsubscribeFromWaba(){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}};import{Agent as Qe}from"https";var ze="HttpsClient",Ee=!1,Ce=new b(ze,process.env.DEBUG==="true"||Ee),W=class{agent;constructor(){this.agent=new Qe({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(t,s,i,o,n,c){let p=`https://${t}/${s}`,l=new AbortController,f=setTimeout(()=>l.abort(),n);try{let g=await fetch(p,{method:i,headers:o,body:c,signal:l.signal});return Ce.log(`${i} : ${p} - ${JSON.stringify(g)}`),clearTimeout(f),new X(g)}catch(g){throw g}}},X=class{res;respStatusCode;respHeaders;constructor(t){this.res=t,this.respStatusCode=t.status,this.respHeaders=Object.fromEntries(t.headers.entries())}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(t){throw new Error("Failed to parse response body to JSON: "+t.message)}}};var et="REQUESTER",tt=!1,st=new b(et,process.env.DEBUG==="true"||tt),G=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(t,s,i,o,n){this.client=new W,this.host="graph.facebook.com",this.apiVersion=t||"22",this.phoneNumberId=s,this.accessToken=i,this.businessAcctId=o,this.userAgent=n}buildHeader(t,s){let i={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return t!=="multipart/form-data"&&(i["Content-Type"]=t),s&&Object.assign(i,s),i}buildCAPIPath(t){return`v${this.apiVersion}.0/${t}`}async sendRequest(t,s,i,o,n="application/json",c){let p=n;o instanceof FormData?p="multipart/form-data":typeof o=="string"&&o.startsWith("<?xml")&&(p="application/xml");let l=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(s)}`;st.log(`${t} : ${l} (${p})`);try{let f=await this.client.sendRequest(this.host,this.buildCAPIPath(s),t,this.buildHeader(p,c),i,t==="POST"||t==="PUT"?o:void 0);if(!f.rawResponse().ok){let g=await f.json();throw j(g)?g:{name:"MetaError",message:"Unknown error occurred",error:{message:g.message||"Unknown error occurred",type:"UnknownError",code:f.statusCode(),fbtrace_id:""}}}return f}catch(f){throw j(f)?f:{name:"MetaError",message:f instanceof Error?f.message:"Network error occurred",error:{message:f instanceof Error?f.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}async getJson(t,s,i,o,n){return await(await this.sendRequest(t,s,i,o,"application/json",n)).json()}async sendFormData(t,s,i,o,n){return await(await this.sendRequest(t,s,i,o,"multipart/form-data",n)).json()}async sendUrlEncodedForm(t,s,i,o,n){let c=new URLSearchParams(o).toString();return await(await this.sendRequest(t,s,i,c,"application/x-www-form-urlencoded",n)).json()}};var it="WHATSAPP",ot=!1,k=new b(it,process.env.DEBUG==="true"||ot),rt="WA_SDK",T=class{config;requester;messages;templates;phoneNumber;qrCode;encryption;twoStepVerification;registration;media;waba;flow;businessProfile;static Enums=V;constructor(t){this.config=J(t),this.requester=new G(this.config.CLOUD_API_VERSION,this.config.WA_PHONE_NUMBER_ID,this.config.CLOUD_API_ACCESS_TOKEN,this.config.WA_BUSINESS_ACCOUNT_ID,this.userAgent()),this.messages=new D(this.config,this.requester),this.templates=new F(this.config,this.requester),this.phoneNumber=new v(this.config,this.requester),this.qrCode=new x(this.config,this.requester),this.encryption=new y(this.config,this.requester),this.twoStepVerification=new q(this.config,this.requester),this.registration=new u(this.config,this.requester),this.media=new O(this.config,this.requester),this.waba=new U(this.config,this.requester),this.flow=new B(this.config,this.requester),this.businessProfile=new M(this.config,this.requester),k.log("WhatsApp Node.js SDK instantiated!")}userAgent(){return`${rt}/0.0.1 (Node.js ${process.version})`}updateTimeout(t){return this.config.REQUEST_TIMEOUT=t,k.log(`Updated request timeout to ${t}ms`),!0}updatePhoneNumberId(t){return this.config.WA_PHONE_NUMBER_ID=t,k.log(`Updated sender phone number id to ${t}`),!0}updateAccessToken(t){return this.config.CLOUD_API_ACCESS_TOKEN=t,k.log("Updated access token"),!0}updateWabaId(t){return this.config.WA_BUSINESS_ACCOUNT_ID=t,k.log(`Updated business account id to ${t}`),!0}};var at="WEBHOOK",nt=!1,_=new b(at,process.env.DEBUG==="true"||nt),$=class{config;client;messageHandlers=new Map;eventHandlers=new Map;preProcessHandler=null;postProcessHandler=null;flowHandlers=new Map;constructor(t){let s=J(t);this.config=s,this.client=new T(t),_.log("WebhookHandler instantiated!")}handleVerificationRequest(t,s){let i=t.query["hub.mode"],o=t.query["hub.verify_token"],n=t.query["hub.challenge"];i==="subscribe"&&o===this.config.WEBHOOK_VERIFICATION_TOKEN?(_.log("Webhook verified successfully"),s.status(200).send(n)):(_.log("Webhook verification failed"),s.status(403).end())}async handleWebhookRequest(t,s){let i=t.body;if(i.object!=="whatsapp_business_account"){_.log("Received webhook for non-WhatsApp event"),s.status(404).end();return}for(let o of i.entry)try{let n=o.changes;for(let c of n)c.field==="messages"?await this.processMessages(c.value):await this.processEvent(c.field,c.value)}catch(n){_.log(`Error processing webhook: ${n}`)}s.status(200).end()}handleRequest(t,s){if(t.method==="GET")return this.handleVerificationRequest(t,s);if(t.method==="POST")return this.handleWebhookRequest(t,s);s.status(405).end()}async processMessages(t){let s=t.metadata,i=s.display_phone_number,o=s.phone_number_id,n=t.contacts[0].profile.name,c=t.messages;if(c&&c.length>0)for(let p of c){let l=p.type,f={id:p.id,from:p.from,timestamp:p.timestamp,type:p.type,phoneNumberId:o,displayPhoneNumber:i,profileName:n,originalData:p};switch(p.type){case"text":f.text=p.text;break;case"image":f.image=p.image;break;case"video":f.video=p.video;break;case"audio":f.audio=p.audio;break;case"document":f.document=p.document;break;case"sticker":f.sticker=p.sticker;break;case"location":f.location=p.location;break;case"contacts":f.contacts=p.contacts;break;case"interactive":f.interactive=p.interactive;break;case"button":f.button=p.button;break;case"order":f.order=p.order;break;case"system":f.system=p.system;break;default:break}if(p.context&&(f.context=p.context),p.errors&&(f.errors=p.errors),this.preProcessHandler&&await Promise.resolve(this.preProcessHandler(this.client,f)),this.messageHandlers.has(l)){let g=this.messageHandlers.get(l);g&&await Promise.resolve(g(this.client,f))}if(this.messageHandlers.has("*")){let g=this.messageHandlers.get("*");g&&await Promise.resolve(g(this.client,f))}this.postProcessHandler&&await Promise.resolve(this.postProcessHandler(this.client,f))}t.statuses&&t.statuses.length>0&&await this.processEvent("statuses",t)}async processEvent(t,s){let i={field:t,value:s};if(this.eventHandlers.has(t)){let o=this.eventHandlers.get(t);o&&await Promise.resolve(o(i))}if(this.eventHandlers.has("*")){let o=this.eventHandlers.get("*");o&&await Promise.resolve(o(i))}}onMessage(t,s){this.messageHandlers.set(t,s),_.log(`Registered handler for message type: ${t}`)}onEvent(t,s){this.eventHandlers.set(t,s),_.log(`Registered handler for event field: ${t}`)}onMessagePreProcess(t){this.preProcessHandler=t,_.log("Registered pre-processing handler for all messages")}onMessagePostProcess(t){this.postProcessHandler=t,_.log("Registered post-processing handler for all messages")}async handleFlowRequest(t,s){if(!this.isRequestSignatureValid(t)){s.status(403).end();return}let i;try{i=this.decryptRequest(t.body)}catch(g){if(_.error(g),g instanceof Error){s.status(421).send(g.message);return}s.status(500).send("internal server error, please check with logs");return}let{decryptedBody:o,aesKeyBuffer:n,initialVectorBuffer:c}=i,p;Ie(o)?p="ping":we(o)?p="data_exchange":Te(o)&&(p="error");let l=o;if(p&&this.flowHandlers.has(p)){let g=this.flowHandlers.get(p);if(g){let R=await Promise.resolve(g(this.client,l)),H=this.encryptResponse(R,n,c);s.status(200).send(H);return}}if(this.flowHandlers.has("*")){let g=this.flowHandlers.get("*");if(g){let R=await Promise.resolve(g(this.client,l)),H=this.encryptResponse(R,n,c);s.status(200).send(H);return}}_.log("No handler found, sending an empty response");let f=this.encryptResponse({},n,c);s.status(200).send(f)}isRequestSignatureValid(t){let s=this.config.M4D_APP_SECRET;if(!s)return _.warn("App Secret is not set up. Please Add M4D_APP_SECRET or configuration"),!1;let i=t.headers["x-hub-signature-256"];if(!i||typeof i!="string")return _.warn("x-hub-signature-256 header is missing"),!1;let o=Buffer.from(i.replace("sha256=",""),"utf-8"),c=I.createHmac("sha256",s).update(t.rawBody).digest("hex"),p=Buffer.from(c,"utf-8");return I.timingSafeEqual(p,o)?!0:(_.error("Error: Request Signature did not match"),!1)}decryptRequest(t){let{encrypted_aes_key:s,encrypted_flow_data:i,initial_vector:o}=t,n=this.config.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
2
+ `),c=this.config.FLOW_API_PASSPHRASE,p=I.createPrivateKey({key:n,passphrase:c}),l=null;try{l=I.privateDecrypt({key:p,padding:I.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(s,"base64"))}catch(ye){throw _.error(ye),new Error("Failed to decrypt the request. Please verify your private key.")}let f=Buffer.from(i,"base64"),g=Buffer.from(o,"base64"),R=16,H=f.subarray(0,-R),Me=f.subarray(-R),P=I.createDecipheriv("aes-128-gcm",l,g);P.setAuthTag(Me);let d=Buffer.concat([P.update(H),P.final()]).toString("utf-8");return{decryptedBody:JSON.parse(d),aesKeyBuffer:l,initialVectorBuffer:g}}encryptResponse(t,s,i){let o=[];for(let n of Array.from(i.entries()))o.push(~n[1]);try{let n=I.createCipheriv("aes-128-gcm",s,Buffer.from(o));return Buffer.concat([n.update(JSON.stringify(t||{}),"utf-8"),n.final(),n.getAuthTag()]).toString("base64")}catch(n){throw _.error("Response encryption error:",n),new Error("Failed to encrypt response. Internal server error.")}}onFlow(t,s){this.flowHandlers.set(t,s),_.log(`Registered handler for Flow type: ${t}`)}};var Di=T;export{ne as AudioMediaTypesEnum,me as BusinessVerticalEnum,C as ButtonPositionEnum,E as ButtonTypesEnum,Y as CategoryEnum,ee as ComponentTypesEnum,te as ConversationTypesEnum,ge as CurrencyCodesEnum,he as DataLocalizationRegionEnum,ae as DocumentMediaTypesEnum,be as EventField,Re as FlowActionEnum,ve as FlowCategoryEnum,De as FlowStatusEnum,Pe as FlowTypeEnum,S as HttpMethodsEnum,re as ImageMediaTypesEnum,z as InteractiveTypesEnum,de as LanguagesEnum,Ue as MessageStatus,L as MessageTypesEnum,Q as ParametersTypesEnum,ce as ReferralSourceTypesEnum,fe as RequestCodeMethodsEnum,se as StatusEnum,oe as StickerMediaTypesEnum,le as SystemChangeTypesEnum,Z as TemplateStatusEnum,ie as VideoMediaTypesEnum,xe as WabaAccountReviewStatus,Fe as WabaAccountStatus,qe as WabaBusinessVerificationStatus,A as WabaConfigEnum,ue as WabaHealthStatusCanSendMessage,$ as WebhookHandler,pe as WebhookTypesEnum,Di as default,xt as generateXHub256Sig,J as importConfig,we as isFlowDataExchangeRequest,Te as isFlowErrorRequest,Ie as isFlowPingRequest,j as isMetaError,w as objectToQueryString};
3
3
  //# sourceMappingURL=index.mjs.map