meta-cloud-api 2.5.0 → 2.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -19
- package/dist/index.d.ts +36 -18
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{t as e}from"./chunk.js";import{inspect as t}from"node:util";import*as n from"node:crypto";import r from"node:crypto";import{Agent as i}from"node:https";import{readFileSync as a}from"node:fs";import{join as o}from"node:path";var s=class{config;client;constructor(e,t){this.config=e,this.client=t}sendJson(e,t,n,r){return this.client.getJson(e,t,n,r)}sendFormData(e,t,n,r){return this.client.sendFormData(e,t,n,r)}sendUrlEncodedForm(e,t,n,r){return this.client.sendUrlEncodedForm(e,t,n,r)}},c=e({AudioMediaTypesEnum:()=>oe,BusinessVerticalEnum:()=>me,ButtonPositionEnum:()=>h,CategoryEnum:()=>l,ComponentTypesEnum:()=>_,ConversationTypesEnum:()=>ee,CurrencyCodesEnum:()=>fe,DataLocalizationRegionEnum:()=>pe,DocumentMediaTypesEnum:()=>ae,HttpMethodsEnum:()=>d,ImageMediaTypesEnum:()=>ie,InteractiveTypesEnum:()=>m,LanguagesEnum:()=>de,MessageTypesEnum:()=>f,ParametersTypesEnum:()=>p,ReferralSourceTypesEnum:()=>le,RequestCodeMethodsEnum:()=>ue,StatusEnum:()=>te,StickerMediaTypesEnum:()=>re,SubTypeEnum:()=>g,SystemChangeTypesEnum:()=>ce,TemplateStatusEnum:()=>u,VideoMediaTypesEnum:()=>ne,WabaConfigEnum:()=>v,WebhookTypesEnum:()=>se});let l=function(e){return e.Authentication=`AUTHENTICATION`,e.Marketing=`MARKETING`,e.Utility=`UTILITY`,e}({}),u=function(e){return e.Approved=`APPROVED`,e.Pending=`PENDING`,e.Rejected=`REJECTED`,e}({}),d=function(e){return e.Get=`GET`,e.Post=`POST`,e.Put=`PUT`,e.Delete=`DELETE`,e}({}),f=function(e){return e.Audio=`audio`,e.Contacts=`contacts`,e.Document=`document`,e.Image=`image`,e.Interactive=`interactive`,e.Location=`location`,e.Reaction=`reaction`,e.Sticker=`sticker`,e.Template=`template`,e.Text=`text`,e.Video=`video`,e.Button=`button`,e.Order=`order`,e.System=`system`,e.Unsupported=`unsupported`,e.Unknown=`unknown`,e.Statuses=`statuses`,e[`*`]=`*`,e}({}),p=function(e){return e.Action=`ACTION`,e.CouponCode=`COUPON_CODE`,e.Currency=`CURRENCY`,e.DateTime=`DATE_TIME`,e.Document=`DOCUMENT`,e.ExpirationTimeMs=`EXPIRATION_TIME_MS`,e.Image=`IMAGE`,e.LimitedTimeOffer=`LIMITED_TIME_OFFER`,e.Location=`LOCATION`,e.OrderStatus=`ORDER_STATUS`,e.Payload=`PAYLOAD`,e.Product=`PRODUCT`,e.Text=`TEXT`,e.TtlMinutes=`TTL_MINUTES`,e.Video=`VIDEO`,e.WebviewInteraction=`WEBVIEW_INTERACTION`,e.WebviewPresentation=`WEBVIEW_PRESENTATION`,e}({}),m=function(e){return e.Button=`button`,e.List=`list`,e.Product=`product`,e.ProductList=`product_list`,e.CtaUrl=`cta_url`,e.Carousel=`carousel`,e.LocationRequest=`location_request_message`,e.AddressMessage=`address_message`,e.Flow=`flow`,e}({}),h=function(e){return e[e.First=1]=`First`,e[e.Second=2]=`Second`,e[e.Third=3]=`Third`,e[e.Fourth=4]=`Fourth`,e[e.Fifth=5]=`Fifth`,e}({}),g=function(e){return e.Catalog=`CATALOG`,e.CopyCode=`COPY_CODE`,e.Flow=`FLOW`,e.Mpm=`MPM`,e.OrderDetails=`ORDER_DETAILS`,e.QuickReply=`QUICK_REPLY`,e.Reminder=`REMINDER`,e.Url=`URL`,e.VoiceCall=`VOICE_CALL`,e}({}),_=function(e){return e.Header=`HEADER`,e.Body=`BODY`,e.Button=`BUTTON`,e.Footer=`FOOTER`,e}({}),v=function(e){return e.AppId=`M4D_APP_ID`,e.Port=`WA_PORT`,e.AppSecret=`M4D_APP_SECRET`,e.PhoneNumberId=`WA_PHONE_NUMBER_ID`,e.BusinessAcctId=`WA_BUSINESS_ACCOUNT_ID`,e.APIVersion=`CLOUD_API_VERSION`,e.AccessToken=`CLOUD_API_ACCESS_TOKEN`,e.WebhookEndpoint=`WEBHOOK_ENDPOINT`,e.WebhookVerificationToken=`WEBHOOK_VERIFICATION_TOKEN`,e.ListenerPort=`LISTENER_PORT`,e.MaxRetriesAfterWait=`MAX_RETRIES_AFTER_WAIT`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.Debug=`DEBUG`,e.PrivatePem=`FLOW_API_PRIVATE_PEM`,e.Passphrase=`FLOW_API_PASSPHRASE`,e}({}),ee=function(e){return e.BusinessInitiated=`business_initiated`,e.CustomerInitiated=`customer_initiated`,e.ReferralConversion=`referral_conversion`,e}({}),te=function(e){return e.Delivered=`delivered`,e.Read=`read`,e.Sent=`sent`,e}({}),ne=function(e){return e.Mp4=`video/mp4`,e.Threegp=`video/3gp`,e}({}),re=function(e){return e.Webp=`image/webp`,e}({}),ie=function(e){return e.Jpeg=`image/jpeg`,e.Png=`image/png`,e}({}),ae=function(e){return e.Text=`text/plain`,e.Pdf=`application/pdf`,e.Ppt=`application/vnd.ms-powerpoint`,e.Word=`application/msword`,e.Excel=`application/vnd.ms-excel`,e.OpenDoc=`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,e.OpenPres=`application/vnd.openxmlformats-officedocument.presentationml.presentation`,e.OpenSheet=`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,e}({}),oe=function(e){return e.Aac=`audio/aac`,e.Mp4=`audio/mp4`,e.Mpeg=`audio/mpeg`,e.Amr=`audio/amr`,e.Ogg=`audio/ogg`,e}({}),se=function(e){return e.Audio=`audio`,e.Button=`button`,e.Document=`document`,e.Text=`text`,e.Image=`image`,e.Interactive=`interactive`,e.Order=`order`,e.Sticker=`sticker`,e.System=`system`,e.Unknown=`unknown`,e.Video=`video`,e}({}),ce=function(e){return e.CustomerChangedNumber=`customer_changed_number`,e.CustomerIdentityChanged=`customer_identity_changed`,e}({}),le=function(e){return e.Ad=`ad`,e.Post=`post`,e}({}),ue=function(e){return e.Sms=`SMS`,e.Voice=`VOICE`,e}({}),de=function(e){return e.Afrikaans=`af`,e.Albanian=`sq`,e.Arabic=`ar`,e.Azerbaijani=`az`,e.Bengali=`bn`,e.Bulgarian=`bg`,e.Catalan=`ca`,e.Chinese_CHN=`zh_CN`,e.Chinese_HKG=`zh_HK`,e.Chinese_TAI=`zh_TW`,e.Croatian=`hr`,e.Czech=`cs`,e.Danish=`da`,e.Dutch=`nl`,e.English=`en`,e.English_UK=`en_GB`,e.English_US=`en_US`,e.Estonian=`et`,e.Filipino=`fil`,e.Finnish=`fi`,e.French=`fr`,e.Georgian=`ka`,e.German=`de`,e.Greek=`el`,e.Gujarati=`gu`,e.Hausa=`ha`,e.Hebrew=`he`,e.Hindi=`hi`,e.Hungarian=`hu`,e.Indonesian=`id`,e.Irish=`ga`,e.Italian=`it`,e.Japanese=`ja`,e.Kannada=`kn`,e.Kazakh=`kk`,e.Kinyarwanda=`rw_RW`,e.Korean=`ko`,e.Kyrgyz_Kyrgyzstan=`ky_KG`,e.Lao=`lo`,e.Latvian=`lv`,e.Lithuanian=`lt`,e.Macedonian=`mk`,e.Malay=`ms`,e.Malayalam=`ml`,e.Marathi=`mr`,e.Norwegian=`nb`,e.Persian=`fa`,e.Polish=`pl`,e.Portuguese_BR=`pt_BR`,e.Portuguese_POR=`pt_PT`,e.Punjabi=`pa`,e.Romanian=`ro`,e.Russian=`ru`,e.Serbian=`sr`,e.Slovak=`sk`,e.Slovenian=`sl`,e.Spanish=`es`,e.Spanish_ARG=`es_AR`,e.Spanish_SPA=`es_ES`,e.Spanish_MEX=`es_MX`,e.Swahili=`sw`,e.Swedish=`sv`,e.Tamil=`ta`,e.Telugu=`te`,e.Thai=`th`,e.Turkish=`tr`,e.Ukrainian=`uk`,e.Urdu=`ur`,e.Uzbek=`uz`,e.Vietnamese=`vi`,e.Zulu=`zu`,e}({}),fe=function(e){return 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}({}),pe=function(e){return e.AU=`AU`,e.ID=`ID`,e.IN=`IN`,e.JP=`JP`,e.SG=`SG`,e.KR=`KR`,e.DE=`DE`,e.CH=`CH`,e.GB=`GB`,e.BR=`BR`,e.BH=`BH`,e.ZA=`ZA`,e.AE=`AE`,e.CA=`CA`,e}({}),me=function(e){return e.ALCOHOL=`ALCOHOL`,e.APPAREL=`APPAREL`,e.AUTO=`AUTO`,e.BEAUTY=`BEAUTY`,e.EDU=`EDU`,e.ENTERTAIN=`ENTERTAIN`,e.EVENT_PLAN=`EVENT_PLAN`,e.FINANCE=`FINANCE`,e.GOVT=`GOVT`,e.GROCERY=`GROCERY`,e.HEALTH=`HEALTH`,e.HOTEL=`HOTEL`,e.NONPROFIT=`NONPROFIT`,e.ONLINE_GAMBLING=`ONLINE_GAMBLING`,e.OTC_DRUGS=`OTC_DRUGS`,e.OTHER=`OTHER`,e.PHYSICAL_GAMBLING=`PHYSICAL_GAMBLING`,e.PROF_SERVICES=`PROF_SERVICES`,e.RESTAURANT=`RESTAURANT`,e.RETAIL=`RETAIL`,e.TRAVEL=`TRAVEL`,e}({});const y=e=>{if(!e||Object.keys(e).length===0)return``;let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0){let e=encodeURIComponent(n),i=encodeURIComponent(String(r));t.push(`${e}=${i}`)}return t.length>0?`?${t.join(`&`)}`:``},he=[0,1,2,3,4,10,33,100,190,200,299,368,613,80007,130429,130472,130497,131e3,131005,131008,131009,131016,131020,131021,131026,131030,131031,131037,131041,131042,131044,131045,131047,131048,131049,131050,131051,131052,131053,131055,131056,131057,131059,131201,131202,131203,131204,131207,131208,131209,131210,131211,131212,131213,131214,131215,132e3,132001,132005,132007,132008,132012,132015,132016,132068,132069,133e3,133004,133005,133006,133008,133009,133010,133015,133016,134011,134100,134101,134102,135e3,137e3,138e3,138001,138002,138003,138004,138005,138006,138007,138009,138012,138013,138018,139e3,139001,139002,139003,139004,139100,139101,139102,139103,200005,200006,200007,1752041,2388001,2388012,2388019,2388040,2388047,2388072,2388073,2388091,2388093,2388103,2388293,2388299,2494100,2593079,2593085,2593107,2593108],ge=new Set(he),_e=[0,3,10,190],ve=[4,80007,130429,131048,131056],ye=[368,130497,131031],be=[130472,131e3,131005,131008,131009,131016,131021,131026,131030,131042,131044,131045,131047,131050,131051,131052,131053,131056,131057,131048,132e3,132001,132005,132007,132008,132012,132015,132016,132068,132069,135e3,137e3],xe=[139e3,139001,139002,139003,139004],Se=[139100,139101,139102,139103],Ce=[138e3,138001,138002,138003,138004,138005,138006,138007,138009,138012,138013,138018,613],we=[131020,131041,131059,131201,131202,131203,131204,131207,131208,131209,131210,131211,131212,131213,131214,131215],Te=new Set(_e),Ee=new Set(ve),De=new Set(ye),Oe=new Set(be),ke=new Set(xe),Ae=new Set(Se),je=new Set(Ce),Me=new Set(we);function Ne(e){return b(e)?!0:ge.has(e)}function b(e){return e>=200&&e<300}function Pe(e){return b(e)||Te.has(e)}function Fe(e){return Ee.has(e)}function Ie(e){return De.has(e)}function Le(e){return Oe.has(e)}function Re(e){return ke.has(e)}function ze(e){return Ae.has(e)}function Be(e){return je.has(e)}function Ve(e){return Me.has(e)}var x=class extends Error{constructor(e){super(e),this.name=`WhatsAppError`}},S=class extends x{error;statusCode;constructor(e,t,n){super(e),this.name=`WhatsAppApiError`,this.error=t,this.statusCode=n}},C=class extends S{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppAuthorizationError`}},w=class extends S{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppThrottlingError`}},T=class extends S{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppIntegrityError`}},E=class extends S{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppSendMessageError`}},D=class extends S{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppFlowError`}},O=class extends S{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppBlockUserError`}},k=class extends S{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppCallingError`}},A=class extends S{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppGroupError`}};function j(e,t){let n=e.code;return Pe(n)?new C(e.message,e,t):Fe(n)?new w(e.message,e,t):Ie(n)?new T(e.message,e,t):Le(n)?new E(e.message,e,t):Re(n)?new D(e.message,e,t):ze(n)?new O(e.message,e,t):Be(n)?new k(e.message,e,t):Ve(n)?new A(e.message,e,t):new S(e.message,e,t)}var He=class extends x{cause;constructor(e,t){super(e),this.name=`WhatsAppNetworkError`,this.cause=t}},Ue=class extends x{cause;constructor(e,t){super(e),this.name=`WhatsAppUnknownError`,this.cause=t}},M=class extends Error{constructor(e){super(e),this.name=`WhatsAppValidationError`}};function N(e){if(typeof e!=`object`||!e||!(`error`in e)||typeof e.error!=`object`||e.error==null)return!1;let t=e.error;if(typeof t.message!=`string`||typeof t.type!=`string`||typeof t.code!=`number`||typeof t.fbtrace_id!=`string`)return!1;if(`error_data`in t&&t.error_data!=null){if(typeof t.error_data!=`object`)return!1;let e=t.error_data;if(`messaging_product`in e&&e.messaging_product!==`whatsapp`||`details`in e&&typeof e.details!=`string`)return!1}return!(`error_subcode`in t&&typeof t.error_subcode!=`number`)}function We(e){return N(e)&&Ne(e.error.code)}function Ge(e){return e instanceof C}function Ke(e){return e instanceof w}function qe(e){return e instanceof T}function Je(e){return e instanceof E}function Ye(e){return e instanceof D}function Xe(e){return e instanceof O}function Ze(e){return e instanceof k}function Qe(e){return e instanceof A}function $e(e,t){if(N(e))return e;let n=`Unknown error occurred`;if(e&&typeof e==`object`&&`message`in e){let t=e.message;typeof t==`string`&&(n=t)}return{name:`MetaError`,message:n,error:{message:n,type:`UnknownError`,code:typeof t==`number`?t:500,fbtrace_id:``}}}function et(e){if(!/^\+?\d{10,15}$/.test(e))throw new M(`Invalid phone number: "${e}". Expected E.164 format (e.g. +14155552671 or 14155552671).`)}function P(e,t){if(!e||e.length===0)throw new M(`"${t}" must contain at least one item.`)}var tt=class extends s{endpoint=`block_users`;buildBlockUsersBody(e){return{messaging_product:`whatsapp`,block_users:e.map(e=>({user:e}))}}async block(e){P(e,`users`);let t=this.buildBlockUsersBody(e);return await this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(t))}async unblock(e){P(e,`users`);let t=this.buildBlockUsersBody(e);return await this.sendJson(d.Delete,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(t))}async listBlockedUsers(e){let t=`${this.config[v.PhoneNumberId]}/${this.endpoint}`;if(e){let n=y(e);n&&(t+=n)}return await this.sendJson(d.Get,t,this.config[v.RequestTimeout])}},nt=class extends s{endpoint=`calls`;async updateCallingSettings(e){return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/settings`,this.config[v.RequestTimeout],JSON.stringify(e))}async getCallingSettings(e){let t=Array.isArray(e?.fields)?e?.fields.join(`,`):e?.fields,n=y({...t?{fields:t}:{},...e?.include_sip_credentials===void 0?{}:{include_sip_credentials:e.include_sip_credentials}});return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}/settings${n}`,this.config[v.RequestTimeout],null)}async getCallPermissions(e){let t=y({user_wa_id:e.userWaId});return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}/call_permissions${t}`,this.config[v.RequestTimeout],null)}async initiateCall(e){let t={messaging_product:`whatsapp`,to:e.to,action:`connect`,session:e.session};return e.biz_opaque_callback_data&&(t.biz_opaque_callback_data=e.biz_opaque_callback_data),this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(t))}async preAcceptCall(e){let t={messaging_product:`whatsapp`,call_id:e.call_id,action:`pre_accept`};return e.session&&(t.session=e.session),this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(t))}async acceptCall(e){let t={messaging_product:`whatsapp`,call_id:e.call_id,action:`accept`};return e.session&&(t.session=e.session),e.biz_opaque_callback_data&&(t.biz_opaque_callback_data=e.biz_opaque_callback_data),this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(t))}async rejectCall(e){let t={messaging_product:`whatsapp`,call_id:e.call_id,action:`reject`};return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(t))}async terminateCall(e){let t={messaging_product:`whatsapp`,call_id:e.call_id,action:`terminate`};return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(t))}},rt=class extends s{endpoint=`whatsapp_commerce_settings`;async getCommerceSettings(){return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],null)}async updateCommerceSettings(e){let t=y(e);return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}${t}`,this.config[v.RequestTimeout],null)}},it=class extends s{endpoint=`whatsapp_business_encryption`;async getEncryptionPublicKey(){return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],null)}async setEncryptionPublicKey(e){let t=new FormData;return t.append(`business_public_key`,e),this.sendFormData(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],t)}},at=class extends s{async listFlows(e){return this.sendJson(d.Get,`/${e}/flows`,this.config[v.RequestTimeout],null)}async createFlow(e,t){let n={name:t.name,categories:t.categories,...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.clone_flow_id&&{clone_flow_id:t.clone_flow_id},...t.flow_json&&{flow_json:t.flow_json},...t.publish!==void 0&&{publish:t.publish}};return this.sendJson(d.Post,`/${e}/flows`,this.config[v.RequestTimeout],JSON.stringify(n))}async getFlow(e,t,n){let r=new URLSearchParams;t&&r.append(`fields`,t),n&&r.append(`date_format`,n);let i=r.toString()?`?${r.toString()}`:``;return this.sendJson(d.Get,`/${e}${i}`,this.config[v.RequestTimeout],null)}async getFlowPreview(e,t=!1){let n=`preview.invalidate(${t})`;return this.getFlow(e,n)}async updateFlowMetadata(e,t){let n={...t.name&&{name:t.name},...t.categories&&{categories:t.categories},...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.application_id&&{application_id:t.application_id}};return this.sendJson(d.Post,`/${e}`,this.config[v.RequestTimeout],JSON.stringify(n))}async deleteFlow(e){return this.sendJson(d.Delete,`/${e}`,this.config[v.RequestTimeout],null)}async listAssets(e){return this.sendJson(d.Get,`/${e}/assets`,this.config[v.RequestTimeout],null)}async updateFlowJson(e,t){let n=new FormData,r;if(t.file instanceof Buffer)r=new globalThis.Blob([new Uint8Array(t.file)]),n.append(`file`,r);else if(typeof t.file==`object`&&!(t.file instanceof Blob))try{r=new globalThis.Blob([JSON.stringify(t.file,null,2)],{type:`application/json`}),n.append(`file`,r)}catch{throw Error(`Failed to stringify JSON object for Flow JSON update.`)}else if(t.file instanceof Blob)r=t.file,n.append(`file`,r);else throw Error(`Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.`);return n.append(`asset_type`,`FLOW_JSON`),n.append(`name`,t.name||`flow.json`),this.sendFormData(d.Post,`/${e}/assets`,this.config[v.RequestTimeout],n)}async validateFlowJson(e,t){let n=await this.updateFlowJson(e,{file:t}),r=!n.validation_errors||n.validation_errors.length===0;return{...n,valid:r}}async publishFlow(e){return this.sendJson(d.Post,`/${e}/publish`,this.config[v.RequestTimeout],JSON.stringify({}))}async deprecateFlow(e){return this.sendJson(d.Post,`/${e}/deprecate`,this.config[v.RequestTimeout],JSON.stringify({}))}async migrateFlows(e,t){let n={source_waba_id:t.source_waba_id,...t.source_flow_names&&{source_flow_names:t.source_flow_names}};return this.sendJson(d.Post,`/${e}/migrate_flows`,this.config[v.RequestTimeout],JSON.stringify(n))}};let ot=function(e){return e.Draft=`DRAFT`,e.Published=`PUBLISHED`,e.Throttled=`THROTTLED`,e.Blocked=`BLOCKED`,e.Deprecated=`DEPRECATED`,e}({}),st=function(e){return e.SignUp=`SIGN_UP`,e.SignIn=`SIGN_IN`,e.AppointmentBooking=`APPOINTMENT_BOOKING`,e.LeadGeneration=`LEAD_GENERATION`,e.ContactUs=`CONTACT_US`,e.CustomerSupport=`CUSTOMER_SUPPORT`,e.Survey=`SURVEY`,e.Other=`OTHER`,e}({}),F=function(e){return e.INIT=`INIT`,e.BACK=`BACK`,e.DATA_EXCHANGE=`data_exchange`,e}({}),I=function(e){return e.Ping=`ping`,e.Change=`data_exchange`,e.Error=`error`,e.All=`*`,e}({});var ct=class extends s{async createGroup(e){let t={messaging_product:`whatsapp`,subject:e.subject};return e.description&&(t.description=e.description),e.join_approval_mode&&(t.join_approval_mode=e.join_approval_mode),this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/groups`,this.config[v.RequestTimeout],JSON.stringify(t))}async deleteGroup(e){return this.sendJson(d.Delete,`/${e}`,this.config[v.RequestTimeout],null)}async getGroupInfo(e,t){let n=Array.isArray(t)?t.join(`,`):t,r=n?y({fields:n}):``;return this.sendJson(d.Get,`/${e}${r}`,this.config[v.RequestTimeout],null)}async getActiveGroups(e){let t=e?y(e):``;return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}/groups${t}`,this.config[v.RequestTimeout],null)}async getGroupInviteLink(e){return this.sendJson(d.Get,`/${e}/invite_link`,this.config[v.RequestTimeout],null)}async resetGroupInviteLink(e){return this.sendJson(d.Post,`/${e}/invite_link`,this.config[v.RequestTimeout],JSON.stringify({messaging_product:`whatsapp`}))}async getJoinRequests(e){return this.sendJson(d.Get,`/${e}/join_requests`,this.config[v.RequestTimeout],null)}async approveJoinRequests(e,t){let n={messaging_product:`whatsapp`,join_requests:t};return this.sendJson(d.Post,`/${e}/join_requests`,this.config[v.RequestTimeout],JSON.stringify(n))}async rejectJoinRequests(e,t){let n={messaging_product:`whatsapp`,join_requests:t};return this.sendJson(d.Delete,`/${e}/join_requests`,this.config[v.RequestTimeout],JSON.stringify(n))}async removeParticipants(e,t){P(t,`participants`);let n={messaging_product:`whatsapp`,participants:t.map(e=>({user:e}))};return this.sendJson(d.Delete,`/${e}/participants`,this.config[v.RequestTimeout],JSON.stringify(n))}async updateGroupSettings(e,t){if(t.profilePictureFile){let n=new FormData;if(n.append(`messaging_product`,`whatsapp`),t.subject&&n.append(`subject`,t.subject),t.description&&n.append(`description`,t.description),t.profilePictureFile instanceof Buffer){let e=new globalThis.Blob([new Uint8Array(t.profilePictureFile)],{type:`image/jpeg`});n.append(`file`,e)}else if(t.profilePictureFile instanceof Blob)n.append(`file`,t.profilePictureFile);else throw Error(`Invalid profile picture file type. Use a Buffer or Blob.`);return this.sendFormData(d.Post,`/${e}`,this.config[v.RequestTimeout],n)}let n={messaging_product:`whatsapp`};return t.subject&&(n.subject=t.subject),t.description&&(n.description=t.description),this.sendJson(d.Post,`/${e}`,this.config[v.RequestTimeout],JSON.stringify(n))}},lt=class extends s{endpoint=`marketing_messages`;async sendTemplateMessage(e){let t={messaging_product:`whatsapp`,recipient_type:`individual`,to:e.to,type:`template`,template:e.template};return e.message_activity_sharing!==void 0&&(t.message_activity_sharing=e.message_activity_sharing),this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(t))}},ut=class extends s{endpoint=`media`;async getMediaById(e){return this.sendJson(d.Get,`${e}`,this.config[v.RequestTimeout],null)}async uploadMedia(e,t=`whatsapp`){let n=new FormData;return n.append(`file`,e),n.append(`messaging_product`,t),n.append(`type`,e.type),this.sendFormData(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],n)}async deleteMedia(e){return this.sendJson(d.Delete,`${e}`,this.config[v.RequestTimeout],null)}async downloadMedia(e){return this.sendJson(d.Get,e,this.config[v.RequestTimeout],null)}},L=class extends s{commonMethod=d.Post;commonEndpoint=`messages`;bodyBuilder(e,t,n,r){et(n);let i={messaging_product:`whatsapp`,recipient_type:`individual`,to:n,type:e,[e]:t};return r&&(i.context={message_id:r}),i}send(e){return this.sendJson(this.commonMethod,`${this.config[v.PhoneNumberId]}/${this.commonEndpoint}`,this.config[v.RequestTimeout],e)}async audio(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Audio,t,n,r)))}async contacts(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Contacts,t,n,r)))}async document(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Document,t,n,r)))}async image(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Image,t,n,r)))}async interactive(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Interactive,t,n,r)))}async location(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Location,t,n,r)))}async sticker(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Sticker,t,n,r)))}async template(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Template,t,n,r)))}async text(e){let{body:t,to:n,replyMessageId:r,previewUrl:i}=e,a=typeof t==`string`?{body:t,preview_url:i??!0}:{...t,preview_url:i??t.preview_url??!0};return this.send(JSON.stringify(this.bodyBuilder(f.Text,a,n,r)))}async video(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Video,t,n,r)))}async status(e){let t={messaging_product:`whatsapp`,status:e.status,message_id:e.messageId,...e.typingIndicator&&{typing_indicator:e.typingIndicator}};return this.send(JSON.stringify(t))}async markAsRead(e){return this.status({status:`read`,messageId:e.messageId})}async showTypingIndicator(e){let t={messaging_product:`whatsapp`,status:`typing`,message_id:e.messageId,typing_indicator:{type:`text`}};return this.send(JSON.stringify(t))}async interactiveList(e){return this.interactive(e)}async interactiveCtaUrl(e){return this.interactive(e)}async interactiveLocationRequest(e){return this.interactive(e)}async interactiveAddressMessage(e){return this.interactive(e)}async interactiveReplyButtons(e){return this.interactive(e)}async interactiveFlow(e){return this.interactive(e)}async interactiveCarousel(e){return this.interactive(e)}async reaction(e){let t={message_id:e.messageId,emoji:e.emoji};return this.send(JSON.stringify(this.bodyBuilder(f.Reaction,t,e.to)))}},dt=class extends s{async listPaymentConfigurations(e){return this.sendJson(d.Get,`/${e}/payment_configurations`,this.config[v.RequestTimeout],null)}async getPaymentConfiguration(e,t){let n=encodeURIComponent(t);return this.sendJson(d.Get,`/${e}/payment_configuration/${n}`,this.config[v.RequestTimeout],null)}async createPaymentConfiguration(e,t){return this.sendJson(d.Post,`/${e}/payment_configuration`,this.config[v.RequestTimeout],JSON.stringify(t))}async updatePaymentConfiguration(e,t,n){let r=encodeURIComponent(t);return this.sendJson(d.Post,`/${e}/payment_configuration/${r}`,this.config[v.RequestTimeout],JSON.stringify(n))}async generatePaymentConfigurationOauthLink(e,t){return this.sendJson(d.Post,`/${e}/generate_payment_configuration_oauth_link`,this.config[v.RequestTimeout],JSON.stringify(t))}async deletePaymentConfiguration(e,t){return this.sendJson(d.Delete,`/${e}/payment_configuration`,this.config[v.RequestTimeout],JSON.stringify(t))}},ft=class extends s{endpoint=`phone_numbers`;async getPhoneNumberById(e){let t=Array.isArray(e)?e.join(`,`):e,n=t?y({fields:t}):``;return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}${n}`,this.config[v.RequestTimeout],null)}async getPhoneNumbers(){return this.sendJson(d.Get,`${this.config[v.BusinessAcctId]}/${this.endpoint}`,this.config[v.RequestTimeout],null)}async requestVerificationCode(e){return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/request_code`,this.config[v.RequestTimeout],JSON.stringify(e))}async verifyCode(e){return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/verify_code`,this.config[v.RequestTimeout],JSON.stringify(e))}async setConversationalAutomation(e){return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/conversational_automation`,this.config[v.RequestTimeout],JSON.stringify(e))}async getConversationalAutomation(){let e=y({fields:`conversational_automation`});return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}${e}`,this.config[v.RequestTimeout],null)}async getThroughput(){let e=y({fields:`throughput`});return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}${e}`,this.config[v.RequestTimeout],null)}};function R(e){if(!e)return``;let t=``;return t=Array.isArray(e)?e.join(`,`):typeof e==`string`?e:Object.entries(e).filter(([e,t])=>t).map(([e])=>e).join(`,`),t?`?fields=${t}`:``}var pt=class extends s{endpoint=`whatsapp_business_profile`;async getBusinessProfile(e){return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}/${this.endpoint}${R(e)}`,this.config[v.RequestTimeout],null)}async updateBusinessProfile(e){return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(e))}async createUploadSession(e,t,n){let r=y({file_length:e,file_type:t,file_name:n});return this.sendJson(d.Post,`app/uploads/${r}`,this.config[v.RequestTimeout],null)}async uploadMedia(e,t){return this.sendJson(d.Post,`${e}`,this.config[v.RequestTimeout],t)}async getUploadHandle(e){return this.sendJson(d.Get,`${e}`,this.config[v.RequestTimeout],null)}},mt=class extends s{endpoint=`message_qrdls`;async createQrCode(e){return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(e))}async getQrCodes(){return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],null)}async getQrCode(e){return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}/${this.endpoint}/${e}`,this.config[v.RequestTimeout],null)}async updateQrCode(e){return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(e))}async deleteQrCode(e){return this.sendJson(d.Delete,`${this.config[v.PhoneNumberId]}/${this.endpoint}/${e}`,this.config[v.RequestTimeout],null)}},ht=class extends s{async register(e,t){let n={messaging_product:`whatsapp`,pin:e,...t&&{data_localization_region:t}};return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/register`,this.config[v.RequestTimeout],JSON.stringify(n))}async deregister(){return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/deregister`,this.config[v.RequestTimeout],null)}};function z(e){let t={type:`HEADER`,format:e.format};return e.text&&(t.text=e.text),e.example&&(t.example=e.example),t}function B(e){let t={type:`BODY`,text:e.text};return e.example&&(t.example=e.example),t}function V(e){return{type:`FOOTER`,text:e.text}}function H(e){let t=[];if(e.phone_number&&t.push({type:`PHONE_NUMBER`,text:e.phone_number.text,phone_number:e.phone_number.phone_number}),e.url){let n={type:`URL`,text:e.url.text,url:e.url.url};e.url.example&&(n.example=[e.url.example]),t.push(n)}if(e.quick_reply&&e.quick_reply.forEach(e=>{t.push({type:`QUICK_REPLY`,text:e.text})}),e.copy_code&&t.push({type:`COPY_CODE`,example:e.copy_code.example}),e.flow){let n={type:`FLOW`,text:e.flow.text};e.flow.flow_id&&(n.flow_id=e.flow.flow_id),e.flow.flow_name&&(n.flow_name=e.flow.flow_name),e.flow.flow_json&&(n.flow_json=e.flow.flow_json),e.flow.flow_action&&(n.flow_action=e.flow.flow_action),e.flow.navigate_screen&&(n.navigate_screen=e.flow.navigate_screen),t.push(n)}return e.mpm&&t.push({type:`MPM`}),e.otp&&t.push({type:`OTP`}),e.spm&&t.push({type:`SPM`}),t.length>0?[{type:`BUTTONS`,buttons:t}]:[]}function gt(e){return e.map(e=>{switch(e.type){case`text`:return e.value;case`currency`:return e.fallback_value;case`date_time`:return e.fallback_value;case`image`:case`video`:case`document`:return e.handle||e.link||``;case`location`:return e.name||``;case`product`:return e.product_retailer_id;default:return``}})}function _t(e){let t=[];if(e.header&&t.push(z(e.header)),e.body&&t.push(B(e.body)),e.footer&&t.push(V(e.footer)),e.buttons&&t.push(...H(e.buttons)),e.carousel){let n=[];e.carousel.cards.forEach((e,t)=>{if(e.image||e.video||e.product){let t=e.image?`IMAGE`:e.video?`VIDEO`:`DOCUMENT`,r=e.image||e.video||e.product||``;n.push({type:`HEADER`,format:t,example:{header_handle:[r]}})}e.body&&n.push({type:`BODY`,text:e.body,example:e.bodyParameters?{body_text:[gt(e.bodyParameters)]}:void 0}),e.buttons&&n.push(...H(e.buttons))}),t.push(...n)}return e.limitedTimeOffer&&t.push({type:`LIMITED_TIME_OFFER`,limited_time_offer:{expiration_time_ms:e.limitedTimeOffer.expiration_time_ms}}),{name:e.name,language:e.language,category:e.category,components:t.length>0?t:void 0}}function vt(e){let t=[],n=`*{{1}}* is your verification code.`;return e.add_security_recommendation&&(n+=` For your security, do not share this code.`),e.code_expiration_minutes&&(n+=` This code expires in ${e.code_expiration_minutes} minutes.`),t.push({type:`BODY`,text:n,example:{body_text:[[`123456`]]}}),t.push({type:`BUTTONS`,buttons:[{type:`OTP`}]}),{name:e.name,language:e.language,category:l.Authentication,components:t}}function yt(e){let t=[],n=`Your security code is *{{1}}*.`;return e.add_security_recommendation&&(n+=` Do not share this code with anyone.`),e.code_expiration_minutes&&(n+=` This code expires in ${e.code_expiration_minutes} minutes.`),t.push({type:`BODY`,text:n,example:{body_text:[[`ABCD1234`]]}}),e.copy_code_button&&t.push({type:`BUTTONS`,buttons:[{type:`COPY_CODE`,example:`ABCD1234`}]}),{name:e.name,language:e.language,category:l.Authentication,components:t}}function bt(e){let t=[];return e.header&&t.push(z({...e.header,format:`TEXT`})),t.push(B(e.body)),e.footer&&t.push(V(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`CATALOG`,action:{thumbnail_product_retailer_id:e.thumbnail_product_retailer_id}}]}),{name:e.name,language:e.language,category:l.Marketing,components:t}}function xt(e){let t=[];return e.header&&t.push(z({...e.header,format:`TEXT`})),t.push(B(e.body)),e.footer&&t.push(V(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`COPY_CODE`,example:e.coupon_code}]}),{name:e.name,language:e.language,category:l.Marketing,components:t}}function St(e){let t=[];return t.push({type:`LIMITED_TIME_OFFER`,limited_time_offer:{expiration_time_ms:e.expiration_time_ms}}),e.header&&t.push(z({...e.header,format:`TEXT`})),t.push(B(e.body)),e.footer&&t.push(V(e.footer)),{name:e.name,language:e.language,category:l.Marketing,components:t}}function Ct(e){let t=[],n=[];return e.cards.forEach((e,t)=>{let r=[];r.push({type:`HEADER`,format:e.header.format,example:e.header.example}),r.push(B(e.body)),e.buttons&&r.push(...H(e.buttons)),n.push({card_index:t,components:r})}),t.push({type:`CAROUSEL`,cards:n}),{name:e.name,language:e.language,category:l.Marketing,components:t}}function wt(e){let t=[];return e.header&&t.push(z({...e.header,format:`TEXT`})),t.push(B(e.body)),e.footer&&t.push(V(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`MPM`,action:{thumbnail_product_retailer_id:e.thumbnail_product_retailer_id,sections:e.sections}}]}),{name:e.name,language:e.language,category:l.Marketing,components:t}}function Tt(e){let t=[];e.header&&t.push(z({...e.header,format:`TEXT`})),t.push(B(e.body)),e.footer&&t.push(V(e.footer));let n=e.cards.map((e,t)=>({card_index:t,components:[{type:`HEADER`,format:`PRODUCT`,example:{header_handle:[e.product_retailer_id]}}]}));return t.push({type:`CAROUSEL`,cards:n}),{name:e.name,language:e.language,category:l.Marketing,components:t}}function Et(e){let t=[];return e.header&&t.push(z({...e.header,format:`TEXT`})),t.push(B(e.body)),e.footer&&t.push(V(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`SPM`,action:{product_retailer_id:e.product_retailer_id}}]}),{name:e.name,language:e.language,category:l.Marketing,components:t}}var Dt=class extends s{endpoint=`message_templates`;async getTemplate(e){return this.sendJson(d.Get,`${e}`,this.config[v.RequestTimeout],null)}async updateTemplate(e,t){return this.sendJson(d.Post,`${e}`,this.config[v.RequestTimeout],JSON.stringify(t))}async getTemplates(e){return this.sendJson(d.Get,`${this.config[v.BusinessAcctId]}/${this.endpoint}${y(e??{})}`,this.config[v.RequestTimeout],null)}async createTemplate(e){return this.sendJson(d.Post,`${this.config[v.BusinessAcctId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(e))}async deleteTemplate(e){return this.sendJson(d.Delete,`${this.config[v.BusinessAcctId]}/${this.endpoint}${y(e)}`,this.config[v.RequestTimeout],null)}},Ot=class extends s{async setTwoStepVerificationCode(e){let t={pin:e};return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}`,this.config[v.RequestTimeout],JSON.stringify(t))}},kt=class extends s{async getWabaAccount(e){let t=R(e)?.replace(/,/g,`%2C`);return this.sendJson(d.Get,`${this.config[v.BusinessAcctId]}${t}`,this.config[v.RequestTimeout],null)}async getAllWabaSubscriptions(){return this.sendJson(d.Get,`${this.config[v.BusinessAcctId]}/subscribed_apps`,this.config[v.RequestTimeout],null)}async updateWabaSubscription({override_callback_uri:e,verify_token:t}){let n={override_callback_uri:e,verify_token:t};return this.sendJson(d.Post,`${this.config[v.BusinessAcctId]}/subscribed_apps`,this.config[v.RequestTimeout],JSON.stringify(n))}async unsubscribeFromWaba(){return this.sendJson(d.Delete,`${this.config[v.BusinessAcctId]}/subscribed_apps`,this.config[v.RequestTimeout],null)}},U=class{name;debug;constructor(e,t=!1){this.name=e,this.debug=t}formatData(e){return e.map(e=>typeof e==`object`?t(e,{depth:null,colors:!0}):e).join(` `)}log(...e){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log(t,`: `,this.formatData(e))}}error(...e){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error(t,`: `,this.formatData(e))}warn(...e){if(this.debug){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn(t,`: `,this.formatData(e))}}info(...e){if(this.debug){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info(t,`: `,this.formatData(e))}}};const At=new U(`UTILS`,process.env.DEBUG===`true`||!1),jt=e=>{if(!process.env[v.AccessToken]&&!e?.accessToken)throw At.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`),Error(`Missing WhatsApp access token.`)},Mt=e=>(jt(e),{[v.AppId]:e?.appId||process.env.M4D_APP_ID||``,[v.AppSecret]:e?.appSecret||process.env.M4D_APP_SECRET||``,[v.PhoneNumberId]:e?.phoneNumberId||(process.env.WA_PHONE_NUMBER_ID?Number(process.env.WA_PHONE_NUMBER_ID):0),[v.BusinessAcctId]:e?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||``,[v.APIVersion]:e?.apiVersion||process.env.CLOUD_API_VERSION||``,[v.AccessToken]:e?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||``,[v.WebhookEndpoint]:e?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||``,[v.WebhookVerificationToken]:e?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||``,[v.ListenerPort]:e?.listenerPort||parseInt(process.env.LISTENER_PORT||``,10)||3e3,[v.MaxRetriesAfterWait]:e?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||``,10)||30,[v.RequestTimeout]:e?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||``,10)||2e4,[v.Debug]:e?.debug||process.env.DEBUG===`true`,[v.PrivatePem]:e?.privatePem||process.env.FLOW_API_PRIVATE_PEM||``,[v.Passphrase]:e?.passphrase||process.env.FLOW_API_PASSPHRASE||``,retry:e?.retry});function Nt(e){let t=[[`App ID`,e[v.AppId]||`Not Set`],[`Phone Number ID`,e[v.PhoneNumberId]?.toString()||`Not Set`],[`Business Account ID`,e[v.BusinessAcctId]||`Not Set`],[`API Version`,e[v.APIVersion]||`Not Set`],[`Access Token`,e[v.AccessToken]?`${e[v.AccessToken].substring(0,20)}...`:`Not Set`],[`Webhook Endpoint`,e[v.WebhookEndpoint]||`Not Set`],[`Webhook Verification Token`,e[v.WebhookVerificationToken]?`${e[v.WebhookVerificationToken].substring(0,10)}...`:`Not Set`],[`Listener Port`,e[v.ListenerPort]?.toString()||`Not Set`],[`Debug Mode`,e[v.Debug]?`Enabled`:`Disabled`],[`Max Retries`,e[v.MaxRetriesAfterWait]?.toString()||`Not Set`],[`Request Timeout`,e[v.RequestTimeout]?`${e[v.RequestTimeout]}ms`:`Not Set`],[`Private PEM`,e[v.PrivatePem]?`Configured`:`Not Set`],[`Passphrase`,e[v.Passphrase]?`Configured`:`Not Set`]],n=Math.max(...t.map(([e])=>e?.length||0)),r=Math.max(...t.map(([,e])=>e?.length||0)),i=Math.max(n,20),a=Math.max(r,30),o=`┌${`─`.repeat(i+2)}┬${`─`.repeat(a+2)}┐`,s=`├${`─`.repeat(i+2)}┼${`─`.repeat(a+2)}┤`,c=`└${`─`.repeat(i+2)}┴${`─`.repeat(a+2)}┘`;return[o,`│ ${`Configuration`.padEnd(i)} │ ${`Value`.padEnd(a)} │`,s,...t.map(([e,t])=>`│ ${e?.padEnd(i)} │ ${t?.padEnd(a)} │`),c].join(`
|
|
2
|
-
`)}const
|
|
3
|
-
`));let s=t.FLOW_API_PASSPHRASE,c=o.includes(`-----BEGIN RSA PRIVATE KEY-----`),l=o.includes(`-----BEGIN PRIVATE KEY-----`)||o.includes(`-----BEGIN ENCRYPTED PRIVATE KEY-----`);
|
|
1
|
+
import{t as e}from"./chunk.js";import{inspect as t}from"node:util";import*as n from"node:crypto";import r from"node:crypto";import{Agent as i}from"node:https";import{readFileSync as a}from"node:fs";import{join as o}from"node:path";var s=class{config;client;constructor(e,t){this.config=e,this.client=t}sendJson(e,t,n,r){return this.client.getJson(e,t,n,r)}sendFormData(e,t,n,r){return this.client.sendFormData(e,t,n,r)}sendUrlEncodedForm(e,t,n,r){return this.client.sendUrlEncodedForm(e,t,n,r)}},c=e({AudioMediaTypesEnum:()=>oe,BusinessVerticalEnum:()=>me,ButtonPositionEnum:()=>h,CategoryEnum:()=>l,ComponentTypesEnum:()=>_,ConversationTypesEnum:()=>ee,CurrencyCodesEnum:()=>fe,DataLocalizationRegionEnum:()=>pe,DocumentMediaTypesEnum:()=>ae,HttpMethodsEnum:()=>d,ImageMediaTypesEnum:()=>ie,InteractiveTypesEnum:()=>m,LanguagesEnum:()=>de,MessageTypesEnum:()=>f,ParametersTypesEnum:()=>p,ReferralSourceTypesEnum:()=>le,RequestCodeMethodsEnum:()=>ue,StatusEnum:()=>te,StickerMediaTypesEnum:()=>re,SubTypeEnum:()=>g,SystemChangeTypesEnum:()=>ce,TemplateStatusEnum:()=>u,VideoMediaTypesEnum:()=>ne,WabaConfigEnum:()=>v,WebhookTypesEnum:()=>se});let l=function(e){return e.Authentication=`AUTHENTICATION`,e.Marketing=`MARKETING`,e.Utility=`UTILITY`,e}({}),u=function(e){return e.Approved=`APPROVED`,e.Pending=`PENDING`,e.Rejected=`REJECTED`,e}({}),d=function(e){return e.Get=`GET`,e.Post=`POST`,e.Put=`PUT`,e.Delete=`DELETE`,e}({}),f=function(e){return e.Audio=`audio`,e.Contacts=`contacts`,e.Document=`document`,e.Image=`image`,e.Interactive=`interactive`,e.Location=`location`,e.Reaction=`reaction`,e.Sticker=`sticker`,e.Template=`template`,e.Text=`text`,e.Video=`video`,e.Button=`button`,e.Order=`order`,e.System=`system`,e.Unsupported=`unsupported`,e.Unknown=`unknown`,e.Statuses=`statuses`,e[`*`]=`*`,e}({}),p=function(e){return e.Action=`ACTION`,e.CouponCode=`COUPON_CODE`,e.Currency=`CURRENCY`,e.DateTime=`DATE_TIME`,e.Document=`DOCUMENT`,e.ExpirationTimeMs=`EXPIRATION_TIME_MS`,e.Image=`IMAGE`,e.LimitedTimeOffer=`LIMITED_TIME_OFFER`,e.Location=`LOCATION`,e.OrderStatus=`ORDER_STATUS`,e.Payload=`PAYLOAD`,e.Product=`PRODUCT`,e.Text=`TEXT`,e.TtlMinutes=`TTL_MINUTES`,e.Video=`VIDEO`,e.WebviewInteraction=`WEBVIEW_INTERACTION`,e.WebviewPresentation=`WEBVIEW_PRESENTATION`,e}({}),m=function(e){return e.Button=`button`,e.List=`list`,e.Product=`product`,e.ProductList=`product_list`,e.CtaUrl=`cta_url`,e.Carousel=`carousel`,e.LocationRequest=`location_request_message`,e.AddressMessage=`address_message`,e.Flow=`flow`,e}({}),h=function(e){return e[e.First=1]=`First`,e[e.Second=2]=`Second`,e[e.Third=3]=`Third`,e[e.Fourth=4]=`Fourth`,e[e.Fifth=5]=`Fifth`,e}({}),g=function(e){return e.Catalog=`CATALOG`,e.CopyCode=`COPY_CODE`,e.Flow=`FLOW`,e.Mpm=`MPM`,e.OrderDetails=`ORDER_DETAILS`,e.QuickReply=`QUICK_REPLY`,e.Reminder=`REMINDER`,e.Url=`URL`,e.VoiceCall=`VOICE_CALL`,e}({}),_=function(e){return e.Header=`HEADER`,e.Body=`BODY`,e.Button=`BUTTON`,e.Footer=`FOOTER`,e}({}),v=function(e){return e.AppId=`M4D_APP_ID`,e.Port=`WA_PORT`,e.AppSecret=`M4D_APP_SECRET`,e.PhoneNumberId=`WA_PHONE_NUMBER_ID`,e.BusinessAcctId=`WA_BUSINESS_ACCOUNT_ID`,e.APIVersion=`CLOUD_API_VERSION`,e.AccessToken=`CLOUD_API_ACCESS_TOKEN`,e.WebhookEndpoint=`WEBHOOK_ENDPOINT`,e.WebhookVerificationToken=`WEBHOOK_VERIFICATION_TOKEN`,e.ListenerPort=`LISTENER_PORT`,e.MaxRetriesAfterWait=`MAX_RETRIES_AFTER_WAIT`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.Debug=`DEBUG`,e.PrivatePem=`FLOW_API_PRIVATE_PEM`,e.Passphrase=`FLOW_API_PASSPHRASE`,e}({}),ee=function(e){return e.BusinessInitiated=`business_initiated`,e.CustomerInitiated=`customer_initiated`,e.ReferralConversion=`referral_conversion`,e}({}),te=function(e){return e.Delivered=`delivered`,e.Read=`read`,e.Sent=`sent`,e}({}),ne=function(e){return e.Mp4=`video/mp4`,e.Threegp=`video/3gp`,e}({}),re=function(e){return e.Webp=`image/webp`,e}({}),ie=function(e){return e.Jpeg=`image/jpeg`,e.Png=`image/png`,e}({}),ae=function(e){return e.Text=`text/plain`,e.Pdf=`application/pdf`,e.Ppt=`application/vnd.ms-powerpoint`,e.Word=`application/msword`,e.Excel=`application/vnd.ms-excel`,e.OpenDoc=`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,e.OpenPres=`application/vnd.openxmlformats-officedocument.presentationml.presentation`,e.OpenSheet=`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,e}({}),oe=function(e){return e.Aac=`audio/aac`,e.Mp4=`audio/mp4`,e.Mpeg=`audio/mpeg`,e.Amr=`audio/amr`,e.Ogg=`audio/ogg`,e}({}),se=function(e){return e.Audio=`audio`,e.Button=`button`,e.Document=`document`,e.Text=`text`,e.Image=`image`,e.Interactive=`interactive`,e.Order=`order`,e.Sticker=`sticker`,e.System=`system`,e.Unknown=`unknown`,e.Video=`video`,e}({}),ce=function(e){return e.CustomerChangedNumber=`customer_changed_number`,e.CustomerIdentityChanged=`customer_identity_changed`,e}({}),le=function(e){return e.Ad=`ad`,e.Post=`post`,e}({}),ue=function(e){return e.Sms=`SMS`,e.Voice=`VOICE`,e}({}),de=function(e){return e.Afrikaans=`af`,e.Albanian=`sq`,e.Arabic=`ar`,e.Azerbaijani=`az`,e.Bengali=`bn`,e.Bulgarian=`bg`,e.Catalan=`ca`,e.Chinese_CHN=`zh_CN`,e.Chinese_HKG=`zh_HK`,e.Chinese_TAI=`zh_TW`,e.Croatian=`hr`,e.Czech=`cs`,e.Danish=`da`,e.Dutch=`nl`,e.English=`en`,e.English_UK=`en_GB`,e.English_US=`en_US`,e.Estonian=`et`,e.Filipino=`fil`,e.Finnish=`fi`,e.French=`fr`,e.Georgian=`ka`,e.German=`de`,e.Greek=`el`,e.Gujarati=`gu`,e.Hausa=`ha`,e.Hebrew=`he`,e.Hindi=`hi`,e.Hungarian=`hu`,e.Indonesian=`id`,e.Irish=`ga`,e.Italian=`it`,e.Japanese=`ja`,e.Kannada=`kn`,e.Kazakh=`kk`,e.Kinyarwanda=`rw_RW`,e.Korean=`ko`,e.Kyrgyz_Kyrgyzstan=`ky_KG`,e.Lao=`lo`,e.Latvian=`lv`,e.Lithuanian=`lt`,e.Macedonian=`mk`,e.Malay=`ms`,e.Malayalam=`ml`,e.Marathi=`mr`,e.Norwegian=`nb`,e.Persian=`fa`,e.Polish=`pl`,e.Portuguese_BR=`pt_BR`,e.Portuguese_POR=`pt_PT`,e.Punjabi=`pa`,e.Romanian=`ro`,e.Russian=`ru`,e.Serbian=`sr`,e.Slovak=`sk`,e.Slovenian=`sl`,e.Spanish=`es`,e.Spanish_ARG=`es_AR`,e.Spanish_SPA=`es_ES`,e.Spanish_MEX=`es_MX`,e.Swahili=`sw`,e.Swedish=`sv`,e.Tamil=`ta`,e.Telugu=`te`,e.Thai=`th`,e.Turkish=`tr`,e.Ukrainian=`uk`,e.Urdu=`ur`,e.Uzbek=`uz`,e.Vietnamese=`vi`,e.Zulu=`zu`,e}({}),fe=function(e){return 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}({}),pe=function(e){return e.AU=`AU`,e.ID=`ID`,e.IN=`IN`,e.JP=`JP`,e.SG=`SG`,e.KR=`KR`,e.DE=`DE`,e.CH=`CH`,e.GB=`GB`,e.BR=`BR`,e.BH=`BH`,e.ZA=`ZA`,e.AE=`AE`,e.CA=`CA`,e}({}),me=function(e){return e.ALCOHOL=`ALCOHOL`,e.APPAREL=`APPAREL`,e.AUTO=`AUTO`,e.BEAUTY=`BEAUTY`,e.EDU=`EDU`,e.ENTERTAIN=`ENTERTAIN`,e.EVENT_PLAN=`EVENT_PLAN`,e.FINANCE=`FINANCE`,e.GOVT=`GOVT`,e.GROCERY=`GROCERY`,e.HEALTH=`HEALTH`,e.HOTEL=`HOTEL`,e.NONPROFIT=`NONPROFIT`,e.ONLINE_GAMBLING=`ONLINE_GAMBLING`,e.OTC_DRUGS=`OTC_DRUGS`,e.OTHER=`OTHER`,e.PHYSICAL_GAMBLING=`PHYSICAL_GAMBLING`,e.PROF_SERVICES=`PROF_SERVICES`,e.RESTAURANT=`RESTAURANT`,e.RETAIL=`RETAIL`,e.TRAVEL=`TRAVEL`,e}({});const y=e=>{if(!e||Object.keys(e).length===0)return``;let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0){let e=encodeURIComponent(n),i=encodeURIComponent(String(r));t.push(`${e}=${i}`)}return t.length>0?`?${t.join(`&`)}`:``},he=[0,1,2,3,4,10,33,100,190,200,299,368,613,80007,130429,130472,130497,131e3,131005,131008,131009,131016,131020,131021,131026,131030,131031,131037,131041,131042,131044,131045,131047,131048,131049,131050,131051,131052,131053,131055,131056,131057,131059,131201,131202,131203,131204,131207,131208,131209,131210,131211,131212,131213,131214,131215,132e3,132001,132005,132007,132008,132012,132015,132016,132068,132069,133e3,133004,133005,133006,133008,133009,133010,133015,133016,134011,134100,134101,134102,135e3,137e3,138e3,138001,138002,138003,138004,138005,138006,138007,138009,138012,138013,138018,139e3,139001,139002,139003,139004,139100,139101,139102,139103,200005,200006,200007,1752041,2388001,2388012,2388019,2388040,2388047,2388072,2388073,2388091,2388093,2388103,2388293,2388299,2494100,2593079,2593085,2593107,2593108],ge=new Set(he),_e=[0,3,10,190],ve=[4,80007,130429,131048,131056],ye=[368,130497,131031],be=[130472,131e3,131005,131008,131009,131016,131021,131026,131030,131042,131044,131045,131047,131050,131051,131052,131053,131056,131057,131048,132e3,132001,132005,132007,132008,132012,132015,132016,132068,132069,135e3,137e3],xe=[139e3,139001,139002,139003,139004],Se=[139100,139101,139102,139103],Ce=[138e3,138001,138002,138003,138004,138005,138006,138007,138009,138012,138013,138018,613],we=[131020,131041,131059,131201,131202,131203,131204,131207,131208,131209,131210,131211,131212,131213,131214,131215],Te=new Set(_e),Ee=new Set(ve),De=new Set(ye),Oe=new Set(be),ke=new Set(xe),Ae=new Set(Se),je=new Set(Ce),Me=new Set(we);function Ne(e){return b(e)?!0:ge.has(e)}function b(e){return e>=200&&e<300}function Pe(e){return b(e)||Te.has(e)}function Fe(e){return Ee.has(e)}function Ie(e){return De.has(e)}function Le(e){return Oe.has(e)}function Re(e){return ke.has(e)}function ze(e){return Ae.has(e)}function Be(e){return je.has(e)}function Ve(e){return Me.has(e)}var x=class extends Error{constructor(e){super(e),this.name=`WhatsAppError`}},S=class extends x{error;statusCode;constructor(e,t,n){super(e),this.name=`WhatsAppApiError`,this.error=t,this.statusCode=n}},C=class extends S{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppAuthorizationError`}},w=class extends S{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppThrottlingError`}},T=class extends S{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppIntegrityError`}},E=class extends S{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppSendMessageError`}},D=class extends S{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppFlowError`}},O=class extends S{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppBlockUserError`}},k=class extends S{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppCallingError`}},A=class extends S{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppGroupError`}};function j(e,t){let n=e.code;return Pe(n)?new C(e.message,e,t):Fe(n)?new w(e.message,e,t):Ie(n)?new T(e.message,e,t):Le(n)?new E(e.message,e,t):Re(n)?new D(e.message,e,t):ze(n)?new O(e.message,e,t):Be(n)?new k(e.message,e,t):Ve(n)?new A(e.message,e,t):new S(e.message,e,t)}var He=class extends x{cause;constructor(e,t){super(e),this.name=`WhatsAppNetworkError`,this.cause=t}},Ue=class extends x{cause;constructor(e,t){super(e),this.name=`WhatsAppUnknownError`,this.cause=t}},M=class extends Error{constructor(e){super(e),this.name=`WhatsAppValidationError`}};function N(e){if(typeof e!=`object`||!e||!(`error`in e)||typeof e.error!=`object`||e.error==null)return!1;let t=e.error;if(typeof t.message!=`string`||typeof t.type!=`string`||typeof t.code!=`number`||typeof t.fbtrace_id!=`string`)return!1;if(`error_data`in t&&t.error_data!=null){if(typeof t.error_data!=`object`)return!1;let e=t.error_data;if(`messaging_product`in e&&e.messaging_product!==`whatsapp`||`details`in e&&typeof e.details!=`string`)return!1}return!(`error_subcode`in t&&typeof t.error_subcode!=`number`)}function We(e){return N(e)&&Ne(e.error.code)}function Ge(e){return e instanceof C}function Ke(e){return e instanceof w}function qe(e){return e instanceof T}function Je(e){return e instanceof E}function Ye(e){return e instanceof D}function Xe(e){return e instanceof O}function Ze(e){return e instanceof k}function Qe(e){return e instanceof A}function $e(e,t){if(N(e))return e;let n=`Unknown error occurred`;if(e&&typeof e==`object`&&`message`in e){let t=e.message;typeof t==`string`&&(n=t)}return{name:`MetaError`,message:n,error:{message:n,type:`UnknownError`,code:typeof t==`number`?t:500,fbtrace_id:``}}}function et(e){if(!/^\+?\d{10,15}$/.test(e))throw new M(`Invalid phone number: "${e}". Expected E.164 format (e.g. +14155552671 or 14155552671).`)}function P(e,t){if(!e||e.length===0)throw new M(`"${t}" must contain at least one item.`)}var tt=class extends s{endpoint=`block_users`;buildBlockUsersBody(e){return{messaging_product:`whatsapp`,block_users:e.map(e=>({user:e}))}}async block(e){P(e,`users`);let t=this.buildBlockUsersBody(e);return await this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(t))}async unblock(e){P(e,`users`);let t=this.buildBlockUsersBody(e);return await this.sendJson(d.Delete,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(t))}async listBlockedUsers(e){let t=`${this.config[v.PhoneNumberId]}/${this.endpoint}`;if(e){let n=y(e);n&&(t+=n)}return await this.sendJson(d.Get,t,this.config[v.RequestTimeout])}},nt=class extends s{endpoint=`calls`;async updateCallingSettings(e){return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/settings`,this.config[v.RequestTimeout],JSON.stringify(e))}async getCallingSettings(e){let t=Array.isArray(e?.fields)?e?.fields.join(`,`):e?.fields,n=y({...t?{fields:t}:{},...e?.include_sip_credentials===void 0?{}:{include_sip_credentials:e.include_sip_credentials}});return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}/settings${n}`,this.config[v.RequestTimeout],null)}async getCallPermissions(e){let t=y({user_wa_id:e.userWaId});return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}/call_permissions${t}`,this.config[v.RequestTimeout],null)}async initiateCall(e){let t={messaging_product:`whatsapp`,to:e.to,action:`connect`,session:e.session};return e.biz_opaque_callback_data&&(t.biz_opaque_callback_data=e.biz_opaque_callback_data),this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(t))}async preAcceptCall(e){let t={messaging_product:`whatsapp`,call_id:e.call_id,action:`pre_accept`};return e.session&&(t.session=e.session),this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(t))}async acceptCall(e){let t={messaging_product:`whatsapp`,call_id:e.call_id,action:`accept`};return e.session&&(t.session=e.session),e.biz_opaque_callback_data&&(t.biz_opaque_callback_data=e.biz_opaque_callback_data),this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(t))}async rejectCall(e){let t={messaging_product:`whatsapp`,call_id:e.call_id,action:`reject`};return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(t))}async terminateCall(e){let t={messaging_product:`whatsapp`,call_id:e.call_id,action:`terminate`};return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(t))}},rt=class extends s{endpoint=`whatsapp_commerce_settings`;async getCommerceSettings(){return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],null)}async updateCommerceSettings(e){let t=y(e);return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}${t}`,this.config[v.RequestTimeout],null)}},it=class extends s{endpoint=`whatsapp_business_encryption`;async getEncryptionPublicKey(){return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],null)}async setEncryptionPublicKey(e){let t=new FormData;return t.append(`business_public_key`,e),this.sendFormData(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],t)}},at=class extends s{async listFlows(e){return this.sendJson(d.Get,`/${e}/flows`,this.config[v.RequestTimeout],null)}async createFlow(e,t){let n={name:t.name,categories:t.categories,...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.clone_flow_id&&{clone_flow_id:t.clone_flow_id},...t.flow_json&&{flow_json:t.flow_json},...t.publish!==void 0&&{publish:t.publish}};return this.sendJson(d.Post,`/${e}/flows`,this.config[v.RequestTimeout],JSON.stringify(n))}async getFlow(e,t,n){let r=new URLSearchParams;t&&r.append(`fields`,t),n&&r.append(`date_format`,n);let i=r.toString()?`?${r.toString()}`:``;return this.sendJson(d.Get,`/${e}${i}`,this.config[v.RequestTimeout],null)}async getFlowPreview(e,t=!1){let n=`preview.invalidate(${t})`;return this.getFlow(e,n)}async updateFlowMetadata(e,t){let n={...t.name&&{name:t.name},...t.categories&&{categories:t.categories},...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.application_id&&{application_id:t.application_id}};return this.sendJson(d.Post,`/${e}`,this.config[v.RequestTimeout],JSON.stringify(n))}async deleteFlow(e){return this.sendJson(d.Delete,`/${e}`,this.config[v.RequestTimeout],null)}async listAssets(e){return this.sendJson(d.Get,`/${e}/assets`,this.config[v.RequestTimeout],null)}async updateFlowJson(e,t){let n=new FormData,r;if(t.file instanceof Buffer)r=new globalThis.Blob([new Uint8Array(t.file)]),n.append(`file`,r);else if(typeof t.file==`object`&&!(t.file instanceof Blob))try{r=new globalThis.Blob([JSON.stringify(t.file,null,2)],{type:`application/json`}),n.append(`file`,r)}catch{throw Error(`Failed to stringify JSON object for Flow JSON update.`)}else if(t.file instanceof Blob)r=t.file,n.append(`file`,r);else throw Error(`Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.`);return n.append(`asset_type`,`FLOW_JSON`),n.append(`name`,t.name||`flow.json`),this.sendFormData(d.Post,`/${e}/assets`,this.config[v.RequestTimeout],n)}async validateFlowJson(e,t){let n=await this.updateFlowJson(e,{file:t}),r=!n.validation_errors||n.validation_errors.length===0;return{...n,valid:r}}async publishFlow(e){return this.sendJson(d.Post,`/${e}/publish`,this.config[v.RequestTimeout],JSON.stringify({}))}async deprecateFlow(e){return this.sendJson(d.Post,`/${e}/deprecate`,this.config[v.RequestTimeout],JSON.stringify({}))}async migrateFlows(e,t){let n={source_waba_id:t.source_waba_id,...t.source_flow_names&&{source_flow_names:t.source_flow_names}};return this.sendJson(d.Post,`/${e}/migrate_flows`,this.config[v.RequestTimeout],JSON.stringify(n))}};let ot=function(e){return e.Draft=`DRAFT`,e.Published=`PUBLISHED`,e.Throttled=`THROTTLED`,e.Blocked=`BLOCKED`,e.Deprecated=`DEPRECATED`,e}({}),st=function(e){return e.SignUp=`SIGN_UP`,e.SignIn=`SIGN_IN`,e.AppointmentBooking=`APPOINTMENT_BOOKING`,e.LeadGeneration=`LEAD_GENERATION`,e.ContactUs=`CONTACT_US`,e.CustomerSupport=`CUSTOMER_SUPPORT`,e.Survey=`SURVEY`,e.Other=`OTHER`,e}({}),F=function(e){return e.INIT=`INIT`,e.BACK=`BACK`,e.DATA_EXCHANGE=`data_exchange`,e}({}),I=function(e){return e.Ping=`ping`,e.Change=`data_exchange`,e.Error=`error`,e.All=`*`,e}({});var ct=class extends s{async createGroup(e){let t={messaging_product:`whatsapp`,subject:e.subject};return e.description&&(t.description=e.description),e.join_approval_mode&&(t.join_approval_mode=e.join_approval_mode),this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/groups`,this.config[v.RequestTimeout],JSON.stringify(t))}async deleteGroup(e){return this.sendJson(d.Delete,`/${e}`,this.config[v.RequestTimeout],null)}async getGroupInfo(e,t){let n=Array.isArray(t)?t.join(`,`):t,r=n?y({fields:n}):``;return this.sendJson(d.Get,`/${e}${r}`,this.config[v.RequestTimeout],null)}async getActiveGroups(e){let t=e?y(e):``;return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}/groups${t}`,this.config[v.RequestTimeout],null)}async getGroupInviteLink(e){return this.sendJson(d.Get,`/${e}/invite_link`,this.config[v.RequestTimeout],null)}async resetGroupInviteLink(e){return this.sendJson(d.Post,`/${e}/invite_link`,this.config[v.RequestTimeout],JSON.stringify({messaging_product:`whatsapp`}))}async getJoinRequests(e){return this.sendJson(d.Get,`/${e}/join_requests`,this.config[v.RequestTimeout],null)}async approveJoinRequests(e,t){let n={messaging_product:`whatsapp`,join_requests:t};return this.sendJson(d.Post,`/${e}/join_requests`,this.config[v.RequestTimeout],JSON.stringify(n))}async rejectJoinRequests(e,t){let n={messaging_product:`whatsapp`,join_requests:t};return this.sendJson(d.Delete,`/${e}/join_requests`,this.config[v.RequestTimeout],JSON.stringify(n))}async removeParticipants(e,t){P(t,`participants`);let n={messaging_product:`whatsapp`,participants:t.map(e=>({user:e}))};return this.sendJson(d.Delete,`/${e}/participants`,this.config[v.RequestTimeout],JSON.stringify(n))}async updateGroupSettings(e,t){if(t.profilePictureFile){let n=new FormData;if(n.append(`messaging_product`,`whatsapp`),t.subject&&n.append(`subject`,t.subject),t.description&&n.append(`description`,t.description),t.profilePictureFile instanceof Buffer){let e=new globalThis.Blob([new Uint8Array(t.profilePictureFile)],{type:`image/jpeg`});n.append(`file`,e)}else if(t.profilePictureFile instanceof Blob)n.append(`file`,t.profilePictureFile);else throw Error(`Invalid profile picture file type. Use a Buffer or Blob.`);return this.sendFormData(d.Post,`/${e}`,this.config[v.RequestTimeout],n)}let n={messaging_product:`whatsapp`};return t.subject&&(n.subject=t.subject),t.description&&(n.description=t.description),this.sendJson(d.Post,`/${e}`,this.config[v.RequestTimeout],JSON.stringify(n))}},lt=class extends s{endpoint=`marketing_messages`;async sendTemplateMessage(e){let t={messaging_product:`whatsapp`,recipient_type:`individual`,to:e.to,type:`template`,template:e.template};return e.message_activity_sharing!==void 0&&(t.message_activity_sharing=e.message_activity_sharing),this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(t))}},ut=class extends s{endpoint=`media`;async getMediaById(e){return this.sendJson(d.Get,`${e}`,this.config[v.RequestTimeout],null)}async uploadMedia(e,t=`whatsapp`){let n=new FormData;return n.append(`file`,e),n.append(`messaging_product`,t),n.append(`type`,e.type),this.sendFormData(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],n)}async deleteMedia(e){return this.sendJson(d.Delete,`${e}`,this.config[v.RequestTimeout],null)}async downloadMedia(e){return this.sendJson(d.Get,e,this.config[v.RequestTimeout],null)}},dt=class extends s{commonMethod=d.Post;commonEndpoint=`messages`;bodyBuilder(e,t,n,r){et(n);let i={messaging_product:`whatsapp`,recipient_type:`individual`,to:n,type:e,[e]:t};return r&&(i.context={message_id:r}),i}send(e){return this.sendJson(this.commonMethod,`${this.config[v.PhoneNumberId]}/${this.commonEndpoint}`,this.config[v.RequestTimeout],e)}async audio(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Audio,t,n,r)))}async contacts(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Contacts,t,n,r)))}async document(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Document,t,n,r)))}async image(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Image,t,n,r)))}async interactive(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Interactive,t,n,r)))}async location(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Location,t,n,r)))}async sticker(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Sticker,t,n,r)))}async template(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Template,t,n,r)))}async text(e){let{body:t,to:n,replyMessageId:r,previewUrl:i}=e,a=typeof t==`string`?{body:t,preview_url:i??!0}:{...t,preview_url:i??t.preview_url??!0};return this.send(JSON.stringify(this.bodyBuilder(f.Text,a,n,r)))}async video(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(f.Video,t,n,r)))}async status(e){let t={messaging_product:`whatsapp`,status:e.status,message_id:e.messageId,...e.typingIndicator&&{typing_indicator:e.typingIndicator}};return this.send(JSON.stringify(t))}async markAsRead(e){return this.status({status:`read`,messageId:e.messageId})}async showTypingIndicator(e){let t={messaging_product:`whatsapp`,status:`typing`,message_id:e.messageId,typing_indicator:{type:`text`}};return this.send(JSON.stringify(t))}async interactiveList(e){return this.interactive(e)}async interactiveCtaUrl(e){return this.interactive(e)}async interactiveLocationRequest(e){return this.interactive(e)}async interactiveAddressMessage(e){return this.interactive(e)}async interactiveReplyButtons(e){return this.interactive(e)}async interactiveFlow(e){return this.interactive(e)}async interactiveCarousel(e){return this.interactive(e)}async reaction(e){let t={message_id:e.messageId,emoji:e.emoji};return this.send(JSON.stringify(this.bodyBuilder(f.Reaction,t,e.to)))}},ft=class extends s{async listPaymentConfigurations(e){return this.sendJson(d.Get,`/${e}/payment_configurations`,this.config[v.RequestTimeout],null)}async getPaymentConfiguration(e,t){let n=encodeURIComponent(t);return this.sendJson(d.Get,`/${e}/payment_configuration/${n}`,this.config[v.RequestTimeout],null)}async createPaymentConfiguration(e,t){return this.sendJson(d.Post,`/${e}/payment_configuration`,this.config[v.RequestTimeout],JSON.stringify(t))}async updatePaymentConfiguration(e,t,n){let r=encodeURIComponent(t);return this.sendJson(d.Post,`/${e}/payment_configuration/${r}`,this.config[v.RequestTimeout],JSON.stringify(n))}async generatePaymentConfigurationOauthLink(e,t){return this.sendJson(d.Post,`/${e}/generate_payment_configuration_oauth_link`,this.config[v.RequestTimeout],JSON.stringify(t))}async deletePaymentConfiguration(e,t){return this.sendJson(d.Delete,`/${e}/payment_configuration`,this.config[v.RequestTimeout],JSON.stringify(t))}},pt=class extends s{endpoint=`phone_numbers`;async getPhoneNumberById(e){let t=Array.isArray(e)?e.join(`,`):e,n=t?y({fields:t}):``;return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}${n}`,this.config[v.RequestTimeout],null)}async getPhoneNumbers(){return this.sendJson(d.Get,`${this.config[v.BusinessAcctId]}/${this.endpoint}`,this.config[v.RequestTimeout],null)}async requestVerificationCode(e){return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/request_code`,this.config[v.RequestTimeout],JSON.stringify(e))}async verifyCode(e){return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/verify_code`,this.config[v.RequestTimeout],JSON.stringify(e))}async setConversationalAutomation(e){return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/conversational_automation`,this.config[v.RequestTimeout],JSON.stringify(e))}async getConversationalAutomation(){let e=y({fields:`conversational_automation`});return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}${e}`,this.config[v.RequestTimeout],null)}async getThroughput(){let e=y({fields:`throughput`});return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}${e}`,this.config[v.RequestTimeout],null)}};function L(e){if(!e)return``;let t=``;return t=Array.isArray(e)?e.join(`,`):typeof e==`string`?e:Object.entries(e).filter(([e,t])=>t).map(([e])=>e).join(`,`),t?`?fields=${t}`:``}var mt=class extends s{endpoint=`whatsapp_business_profile`;async getBusinessProfile(e){return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}/${this.endpoint}${L(e)}`,this.config[v.RequestTimeout],null)}async updateBusinessProfile(e){return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(e))}async createUploadSession(e,t,n){let r=y({file_length:e,file_type:t,file_name:n});return this.sendJson(d.Post,`app/uploads/${r}`,this.config[v.RequestTimeout],null)}async uploadMedia(e,t){return this.sendJson(d.Post,`${e}`,this.config[v.RequestTimeout],t)}async getUploadHandle(e){return this.sendJson(d.Get,`${e}`,this.config[v.RequestTimeout],null)}},ht=class extends s{endpoint=`message_qrdls`;async createQrCode(e){return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(e))}async getQrCodes(){return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],null)}async getQrCode(e){return this.sendJson(d.Get,`${this.config[v.PhoneNumberId]}/${this.endpoint}/${e}`,this.config[v.RequestTimeout],null)}async updateQrCode(e){return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(e))}async deleteQrCode(e){return this.sendJson(d.Delete,`${this.config[v.PhoneNumberId]}/${this.endpoint}/${e}`,this.config[v.RequestTimeout],null)}},gt=class extends s{async register(e,t){let n={messaging_product:`whatsapp`,pin:e,...t&&{data_localization_region:t}};return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/register`,this.config[v.RequestTimeout],JSON.stringify(n))}async deregister(){return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}/deregister`,this.config[v.RequestTimeout],null)}};function R(e){let t={type:`HEADER`,format:e.format};return e.text&&(t.text=e.text),e.example&&(t.example=e.example),t}function z(e){let t={type:`BODY`,text:e.text};return e.example&&(t.example=e.example),t}function B(e){return{type:`FOOTER`,text:e.text}}function V(e){let t=[];if(e.phone_number&&t.push({type:`PHONE_NUMBER`,text:e.phone_number.text,phone_number:e.phone_number.phone_number}),e.url){let n={type:`URL`,text:e.url.text,url:e.url.url};e.url.example&&(n.example=[e.url.example]),t.push(n)}if(e.quick_reply&&e.quick_reply.forEach(e=>{t.push({type:`QUICK_REPLY`,text:e.text})}),e.copy_code&&t.push({type:`COPY_CODE`,example:e.copy_code.example}),e.flow){let n={type:`FLOW`,text:e.flow.text};e.flow.flow_id&&(n.flow_id=e.flow.flow_id),e.flow.flow_name&&(n.flow_name=e.flow.flow_name),e.flow.flow_json&&(n.flow_json=e.flow.flow_json),e.flow.flow_action&&(n.flow_action=e.flow.flow_action),e.flow.navigate_screen&&(n.navigate_screen=e.flow.navigate_screen),t.push(n)}return e.mpm&&t.push({type:`MPM`}),e.otp&&t.push({type:`OTP`}),e.spm&&t.push({type:`SPM`}),t.length>0?[{type:`BUTTONS`,buttons:t}]:[]}function _t(e){return e.map(e=>{switch(e.type){case`text`:return e.value;case`currency`:return e.fallback_value;case`date_time`:return e.fallback_value;case`image`:case`video`:case`document`:return e.handle||e.link||``;case`location`:return e.name||``;case`product`:return e.product_retailer_id;default:return``}})}function vt(e){let t=[];if(e.header&&t.push(R(e.header)),e.body&&t.push(z(e.body)),e.footer&&t.push(B(e.footer)),e.buttons&&t.push(...V(e.buttons)),e.carousel){let n=[];e.carousel.cards.forEach((e,t)=>{if(e.image||e.video||e.product){let t=e.image?`IMAGE`:e.video?`VIDEO`:`DOCUMENT`,r=e.image||e.video||e.product||``;n.push({type:`HEADER`,format:t,example:{header_handle:[r]}})}e.body&&n.push({type:`BODY`,text:e.body,example:e.bodyParameters?{body_text:[_t(e.bodyParameters)]}:void 0}),e.buttons&&n.push(...V(e.buttons))}),t.push(...n)}return e.limitedTimeOffer&&t.push({type:`LIMITED_TIME_OFFER`,limited_time_offer:{expiration_time_ms:e.limitedTimeOffer.expiration_time_ms}}),{name:e.name,language:e.language,category:e.category,components:t.length>0?t:void 0}}function yt(e){let t=[],n=`*{{1}}* is your verification code.`;return e.add_security_recommendation&&(n+=` For your security, do not share this code.`),e.code_expiration_minutes&&(n+=` This code expires in ${e.code_expiration_minutes} minutes.`),t.push({type:`BODY`,text:n,example:{body_text:[[`123456`]]}}),t.push({type:`BUTTONS`,buttons:[{type:`OTP`}]}),{name:e.name,language:e.language,category:l.Authentication,components:t}}function bt(e){let t=[],n=`Your security code is *{{1}}*.`;return e.add_security_recommendation&&(n+=` Do not share this code with anyone.`),e.code_expiration_minutes&&(n+=` This code expires in ${e.code_expiration_minutes} minutes.`),t.push({type:`BODY`,text:n,example:{body_text:[[`ABCD1234`]]}}),e.copy_code_button&&t.push({type:`BUTTONS`,buttons:[{type:`COPY_CODE`,example:`ABCD1234`}]}),{name:e.name,language:e.language,category:l.Authentication,components:t}}function xt(e){let t=[];return e.header&&t.push(R({...e.header,format:`TEXT`})),t.push(z(e.body)),e.footer&&t.push(B(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`CATALOG`,action:{thumbnail_product_retailer_id:e.thumbnail_product_retailer_id}}]}),{name:e.name,language:e.language,category:l.Marketing,components:t}}function St(e){let t=[];return e.header&&t.push(R({...e.header,format:`TEXT`})),t.push(z(e.body)),e.footer&&t.push(B(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`COPY_CODE`,example:e.coupon_code}]}),{name:e.name,language:e.language,category:l.Marketing,components:t}}function Ct(e){let t=[];return t.push({type:`LIMITED_TIME_OFFER`,limited_time_offer:{expiration_time_ms:e.expiration_time_ms}}),e.header&&t.push(R({...e.header,format:`TEXT`})),t.push(z(e.body)),e.footer&&t.push(B(e.footer)),{name:e.name,language:e.language,category:l.Marketing,components:t}}function wt(e){let t=[],n=[];return e.cards.forEach((e,t)=>{let r=[];r.push({type:`HEADER`,format:e.header.format,example:e.header.example}),r.push(z(e.body)),e.buttons&&r.push(...V(e.buttons)),n.push({card_index:t,components:r})}),t.push({type:`CAROUSEL`,cards:n}),{name:e.name,language:e.language,category:l.Marketing,components:t}}function Tt(e){let t=[];return e.header&&t.push(R({...e.header,format:`TEXT`})),t.push(z(e.body)),e.footer&&t.push(B(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`MPM`,action:{thumbnail_product_retailer_id:e.thumbnail_product_retailer_id,sections:e.sections}}]}),{name:e.name,language:e.language,category:l.Marketing,components:t}}function Et(e){let t=[];e.header&&t.push(R({...e.header,format:`TEXT`})),t.push(z(e.body)),e.footer&&t.push(B(e.footer));let n=e.cards.map((e,t)=>({card_index:t,components:[{type:`HEADER`,format:`PRODUCT`,example:{header_handle:[e.product_retailer_id]}}]}));return t.push({type:`CAROUSEL`,cards:n}),{name:e.name,language:e.language,category:l.Marketing,components:t}}function Dt(e){let t=[];return e.header&&t.push(R({...e.header,format:`TEXT`})),t.push(z(e.body)),e.footer&&t.push(B(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`SPM`,action:{product_retailer_id:e.product_retailer_id}}]}),{name:e.name,language:e.language,category:l.Marketing,components:t}}var Ot=class extends s{endpoint=`message_templates`;async getTemplate(e){return this.sendJson(d.Get,`${e}`,this.config[v.RequestTimeout],null)}async updateTemplate(e,t){return this.sendJson(d.Post,`${e}`,this.config[v.RequestTimeout],JSON.stringify(t))}async getTemplates(e){return this.sendJson(d.Get,`${this.config[v.BusinessAcctId]}/${this.endpoint}${y(e??{})}`,this.config[v.RequestTimeout],null)}async createTemplate(e){return this.sendJson(d.Post,`${this.config[v.BusinessAcctId]}/${this.endpoint}`,this.config[v.RequestTimeout],JSON.stringify(e))}async deleteTemplate(e){return this.sendJson(d.Delete,`${this.config[v.BusinessAcctId]}/${this.endpoint}${y(e)}`,this.config[v.RequestTimeout],null)}},kt=class extends s{async setTwoStepVerificationCode(e){let t={pin:e};return this.sendJson(d.Post,`${this.config[v.PhoneNumberId]}`,this.config[v.RequestTimeout],JSON.stringify(t))}},At=class extends s{async getWabaAccount(e){let t=L(e)?.replace(/,/g,`%2C`);return this.sendJson(d.Get,`${this.config[v.BusinessAcctId]}${t}`,this.config[v.RequestTimeout],null)}async getAllWabaSubscriptions(){return this.sendJson(d.Get,`${this.config[v.BusinessAcctId]}/subscribed_apps`,this.config[v.RequestTimeout],null)}async updateWabaSubscription({override_callback_uri:e,verify_token:t}){let n={override_callback_uri:e,verify_token:t};return this.sendJson(d.Post,`${this.config[v.BusinessAcctId]}/subscribed_apps`,this.config[v.RequestTimeout],JSON.stringify(n))}async unsubscribeFromWaba(){return this.sendJson(d.Delete,`${this.config[v.BusinessAcctId]}/subscribed_apps`,this.config[v.RequestTimeout],null)}},H=class{name;debug;constructor(e,t=!1){this.name=e,this.debug=t}formatData(e){return e.map(e=>typeof e==`object`?t(e,{depth:null,colors:!0}):e).join(` `)}log(...e){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log(t,`: `,this.formatData(e))}}error(...e){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error(t,`: `,this.formatData(e))}warn(...e){if(this.debug){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn(t,`: `,this.formatData(e))}}info(...e){if(this.debug){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info(t,`: `,this.formatData(e))}}};const jt=new H(`UTILS`,process.env.DEBUG===`true`||!1),Mt=e=>{if(!process.env[v.AccessToken]&&!e?.accessToken)throw jt.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`),Error(`Missing WhatsApp access token.`)},Nt=e=>(Mt(e),{[v.AppId]:e?.appId||process.env.M4D_APP_ID||``,[v.AppSecret]:e?.appSecret||process.env.M4D_APP_SECRET||``,[v.PhoneNumberId]:e?.phoneNumberId||(process.env.WA_PHONE_NUMBER_ID?Number(process.env.WA_PHONE_NUMBER_ID):0),[v.BusinessAcctId]:e?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||``,[v.APIVersion]:e?.apiVersion||process.env.CLOUD_API_VERSION||``,[v.AccessToken]:e?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||``,[v.WebhookEndpoint]:e?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||``,[v.WebhookVerificationToken]:e?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||``,[v.ListenerPort]:e?.listenerPort||parseInt(process.env.LISTENER_PORT||``,10)||3e3,[v.MaxRetriesAfterWait]:e?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||``,10)||30,[v.RequestTimeout]:e?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||``,10)||2e4,[v.Debug]:e?.debug||process.env.DEBUG===`true`,[v.PrivatePem]:e?.privatePem||process.env.FLOW_API_PRIVATE_PEM||``,[v.Passphrase]:e?.passphrase||process.env.FLOW_API_PASSPHRASE||``,retry:e?.retry});function Pt(e){let t=[[`App ID`,e[v.AppId]||`Not Set`],[`Phone Number ID`,e[v.PhoneNumberId]?.toString()||`Not Set`],[`Business Account ID`,e[v.BusinessAcctId]||`Not Set`],[`API Version`,e[v.APIVersion]||`Not Set`],[`Access Token`,e[v.AccessToken]?`${e[v.AccessToken].substring(0,20)}...`:`Not Set`],[`Webhook Endpoint`,e[v.WebhookEndpoint]||`Not Set`],[`Webhook Verification Token`,e[v.WebhookVerificationToken]?`${e[v.WebhookVerificationToken].substring(0,10)}...`:`Not Set`],[`Listener Port`,e[v.ListenerPort]?.toString()||`Not Set`],[`Debug Mode`,e[v.Debug]?`Enabled`:`Disabled`],[`Max Retries`,e[v.MaxRetriesAfterWait]?.toString()||`Not Set`],[`Request Timeout`,e[v.RequestTimeout]?`${e[v.RequestTimeout]}ms`:`Not Set`],[`Private PEM`,e[v.PrivatePem]?`Configured`:`Not Set`],[`Passphrase`,e[v.Passphrase]?`Configured`:`Not Set`]],n=Math.max(...t.map(([e])=>e?.length||0)),r=Math.max(...t.map(([,e])=>e?.length||0)),i=Math.max(n,20),a=Math.max(r,30),o=`┌${`─`.repeat(i+2)}┬${`─`.repeat(a+2)}┐`,s=`├${`─`.repeat(i+2)}┼${`─`.repeat(a+2)}┤`,c=`└${`─`.repeat(i+2)}┴${`─`.repeat(a+2)}┘`;return[o,`│ ${`Configuration`.padEnd(i)} │ ${`Value`.padEnd(a)} │`,s,...t.map(([e,t])=>`│ ${e?.padEnd(i)} │ ${t?.padEnd(a)} │`),c].join(`
|
|
2
|
+
`)}const U=new H(`FLOW_ENCRYPTION_UTILS`,process.env.DEBUG===`true`);function Ft(){if(!r||typeof r.generateKeyPairSync!=`function`){let e=Error(`This utility requires Node.js environment with crypto module. It cannot be used in browser or edge runtime environments.`);throw U.error(`Environment validation failed:`,e),e}if(typeof window<`u`){let e=Error(`This utility cannot run in a browser environment. Please use it in a Node.js server environment only.`);throw U.error(`Browser environment detected:`,e),e}if(process.versions?.node){let e=process.versions.node.split(`.`).map(Number),t=e[0]??0,n=e[1]??0;if(t<10||t===10&&n<12){let e=Error(`Node.js version ${process.versions.node} is not supported. Please upgrade to Node.js 10.12.0 or higher.`);throw U.error(`Node.js version check failed:`,e),e}}}function It(e){U.info(`[generateEncryption] Starting key pair generation`),Ft();let t=e||process.env.FLOW_API_PASSPHRASE;if(!t||t.trim().length===0){let e=Error(`Passphrase is empty. Please provide a passphrase as parameter or set FLOW_API_PASSPHRASE environment variable.`);throw U.error(`[generateEncryption] Passphrase validation failed:`,e),e}t.length<8&&U.warn(`[generateEncryption] Passphrase is shorter than 8 characters. Consider using a longer passphrase for better security.`);try{U.info(`[generateEncryption] Generating 2048-bit RSA key pair`);let e=r.generateKeyPairSync(`rsa`,{modulusLength:2048,publicKeyEncoding:{type:`spki`,format:`pem`},privateKeyEncoding:{type:`pkcs8`,format:`pem`,cipher:`aes-256-cbc`,passphrase:t}});return U.info(`[generateEncryption] Key pair generated successfully`),{passphrase:t,privateKey:e.privateKey,publicKey:e.publicKey}}catch(e){let t=e instanceof Error?e.message:String(e),n=Error(`Failed to generate key pair: ${t}`);throw U.error(`[generateEncryption] Key generation failed:`,n),n}}function Lt(e,t){if(U.info(`[decryptFlowRequest] Starting Flow request decryption`),!t.FLOW_API_PRIVATE_PEM||t.FLOW_API_PRIVATE_PEM.trim()===``){let e=Error(`Missing FLOW_API_PRIVATE_PEM. Please set the FLOW_API_PRIVATE_PEM environment variable or pass privatePem via config.`);throw U.error(`[decryptFlowRequest] Configuration error:`,e),e}if(!t.FLOW_API_PASSPHRASE||t.FLOW_API_PASSPHRASE.trim()===``){let e=Error(`Missing FLOW_API_PASSPHRASE. Please set the FLOW_API_PASSPHRASE environment variable or pass passphrase via config.`);throw U.error(`[decryptFlowRequest] Configuration error:`,e),e}U.info(`[decryptFlowRequest] Configuration validated`);let{encrypted_aes_key:n,encrypted_flow_data:i,initial_vector:a}=e;if(!n||!i||!a)throw U.error(`[decryptFlowRequest] Missing required encryption properties in request body`),Error(`Missing required encryption properties`);U.info(`[decryptFlowRequest] Request body validated`);let o=t.FLOW_API_PRIVATE_PEM;o.includes(`\\n`)&&(o=o.replace(/\\n/g,`
|
|
3
|
+
`));let s=t.FLOW_API_PASSPHRASE,c=o.includes(`-----BEGIN RSA PRIVATE KEY-----`),l=o.includes(`-----BEGIN PRIVATE KEY-----`)||o.includes(`-----BEGIN ENCRYPTED PRIVATE KEY-----`);U.info(`[decryptFlowRequest] Loading private key`,{format:l?`PKCS#8`:c?`PKCS#1`:`Unknown`});let u;try{u=s?r.createPrivateKey({key:o,format:`pem`,passphrase:s}):r.createPrivateKey(o),U.info(`[decryptFlowRequest] Private key loaded successfully`)}catch(e){if(U.error(`[decryptFlowRequest] Failed to load private key (first attempt):`,{error:e instanceof Error?e.message:e,hasPassphrase:!!s,format:l?`PKCS#8`:c?`PKCS#1`:`Unknown`}),c&&s)try{U.info(`[decryptFlowRequest] Attempting to convert PKCS#1 to PKCS#8 format`);let e=r.createPrivateKey({key:o,format:`pem`,passphrase:s}).export({type:`pkcs8`,format:`pem`,cipher:`aes-256-cbc`,passphrase:s});u=r.createPrivateKey({key:e,format:`pem`,passphrase:s}),U.info(`[decryptFlowRequest] Successfully converted PKCS#1 to PKCS#8 and loaded private key`)}catch(t){U.error(`[decryptFlowRequest] Failed to convert PKCS#1 to PKCS#8:`,{error:t instanceof Error?t.message:t});let n=`Failed to parse private key. Error: ${e instanceof Error?e.message:e}`;throw n+=`
|
|
4
4
|
|
|
5
5
|
Your key is in PKCS#1 format with unsupported encryption (DES-EDE3-CBC).`,n+=`
|
|
6
6
|
Please convert it to PKCS#8 format using:`,n+=`
|
|
@@ -10,12 +10,12 @@ Your key is in PKCS#1 format (-----BEGIN RSA PRIVATE KEY-----).`,t+=`
|
|
|
10
10
|
Please convert it to PKCS#8 format using:`,t+=`
|
|
11
11
|
openssl pkcs8 -topk8 -inform PEM -outform PEM -in old_key.pem -out new_key.pem`):l||(t+=`
|
|
12
12
|
|
|
13
|
-
Your key format is not recognized. Please ensure it is in PKCS#8 format.`),Error(t)}}let d;try{
|
|
13
|
+
Your key format is not recognized. Please ensure it is in PKCS#8 format.`),Error(t)}}let d;try{U.info(`[decryptFlowRequest] Decrypting AES key with RSA private key`),d=r.privateDecrypt({key:u,padding:r.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:`sha256`},Buffer.from(n,`base64`)),U.info(`[decryptFlowRequest] AES key decrypted successfully`)}catch(e){throw U.error(`[decryptFlowRequest] Failed to decrypt AES key:`,e),Error(`Failed to decrypt the request. Please verify your private key.`)}let f=Buffer.from(i,`base64`),p=Buffer.from(a,`base64`),m=f.subarray(0,-16),h=f.subarray(-16);U.info(`[decryptFlowRequest] Decrypting flow data with AES-128-GCM`);let g=r.createDecipheriv(`aes-128-gcm`,d,p);g.setAuthTag(h);let _=Buffer.concat([g.update(m),g.final()]).toString(`utf-8`);return U.info(`[decryptFlowRequest] Flow request decrypted successfully`),{decryptedBody:JSON.parse(_),aesKeyBuffer:d,initialVectorBuffer:p}}function Rt(e,t,n){U.info(`[encryptFlowResponse] Starting Flow response encryption`);let i=[];for(let e of Array.from(n.entries()))i.push(~e[1]);try{U.info(`[encryptFlowResponse] Encrypting response with AES-128-GCM`);let n=r.createCipheriv(`aes-128-gcm`,t,Buffer.from(i)),a=Buffer.concat([n.update(JSON.stringify(e||{}),`utf-8`),n.final(),n.getAuthTag()]).toString(`base64`);return U.info(`[encryptFlowResponse] Flow response encrypted successfully`),a}catch(e){throw U.error(`[encryptFlowResponse] Response encryption failed:`,e),Error(`Failed to encrypt response. Internal server error.`)}}const zt=new H(`HttpsClient`,process.env.DEBUG===`true`);var Bt=class{agent;constructor(){this.agent=new i({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(e,t,n,r,i,a){let o=`https://${e}/${t}`,s=new AbortController,c=setTimeout(()=>s.abort(),i);try{let e=await fetch(o,{method:n,headers:r,body:a,signal:s.signal});return zt.log(`${n} : ${o} - ${JSON.stringify(e)}`),clearTimeout(c),new Vt(e)}catch(e){throw zt.error(`${n} : ${o} - ${JSON.stringify(e)}`),e}}},Vt=class{res;respStatusCode;respHeaders;constructor(e){this.res=e,this.respStatusCode=e.status,this.respHeaders=Object.fromEntries(e.headers.entries())}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(e){let t=Error(`Failed to parse response body to JSON: ${e.message}`);throw t.cause=e,t}}};const W=new H(`REQUESTER`,process.env.DEBUG===`true`);function Ht(e){return new Promise(t=>setTimeout(t,e))}var Ut=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol=`https:`;retryConfig;constructor(e,t,n,r,i,a){this.client=new Bt,this.host=`graph.facebook.com`,this.apiVersion=e||`22`,this.phoneNumberId=t,this.accessToken=n,this.businessAcctId=r,this.userAgent=i,this.retryConfig=a}buildHeader(e,t){let n={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return e!==`multipart/form-data`&&(n[`Content-Type`]=e),t&&Object.assign(n,t),n}buildCAPIPath(e){return`v${this.apiVersion}.0/${e}`}async sendRequest(e,t,n,r,i=`application/json`,a){let o=this.retryConfig?.maxAttempts??3,s=this.retryConfig?.initialDelayMs??1e3,c=this.retryConfig?.backoff??`exponential`,l=i;r instanceof FormData?l=`multipart/form-data`:typeof r==`string`&&r.startsWith(`<?xml`)&&(l=`application/xml`);let u=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(t)}`;W.log(`${e} : ${u} (${l})`);for(let i=1;i<=o;i++)try{let i=e===`POST`||e===`PUT`||e===`DELETE`,o=await this.client.sendRequest(this.host,this.buildCAPIPath(t),e,this.buildHeader(l,a),n,i?r:void 0);if(!o.rawResponse().ok){let e=null;try{e=await o.json()}catch{e=null}throw j($e(e,o.statusCode()).error,o.statusCode())}return o}catch(e){if(e instanceof w&&i<o){let e=c===`exponential`?s*2**(i-1):s;W.log(`Throttled (attempt ${i}/${o}). Retrying in ${e}ms...`),await Ht(e);continue}throw e instanceof x?e:N(e)?j(e.error):new He(e instanceof Error?e.message:`Network error occurred`,e)}throw new w(`Max retry attempts exceeded`,{message:`Max retry attempts exceeded`,type:`ThrottlingError`,code:130429,fbtrace_id:``},429)}async getJson(e,t,n,r,i){return await(await this.sendRequest(e,t,n,r,`application/json`,i)).json()}async sendFormData(e,t,n,r,i){return await(await this.sendRequest(e,t,n,r,`multipart/form-data`,i)).json()}updateTimeout(e){W.log(`Timeout updated to ${e}ms`)}updateAccessToken(e){this.accessToken=e,W.log(`Access token updated`)}async sendUrlEncodedForm(e,t,n,r,i){let a=new URLSearchParams(r).toString();return await(await this.sendRequest(e,t,n,a,`application/x-www-form-urlencoded`,i)).json()}};function Wt(){process.env.NODE_ENV===`test`||process.env.VITEST===`true`||typeof global<`u`&&global.__VITEST__||console.log(`\x1B[36m%s\x1B[0m`,`
|
|
14
14
|
██████╗ ██╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ██████╗ ██╗
|
|
15
15
|
██╔════╝ ██║ ██╔═══██╗ ██║ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║
|
|
16
16
|
██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ███████║ ██████╔╝ ██║
|
|
17
17
|
██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██╔══██║ ██╔═══╝ ██║
|
|
18
18
|
╚██████╗ ███████╗ ╚██████╔╝ ╚██████╔╝ ██████╔╝ ██║ ██║ ██║ ██║
|
|
19
19
|
╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝
|
|
20
|
-
`)}function Wt(){try{let e=o(__dirname,`../../package.json`);return JSON.parse(a(e,`utf-8`)).version}catch{return`unknown`}}function Gt(){return`WhatsApp-Nodejs-SDK/${Wt()} (Node.js ${process.version})`}const K=new U(`WHATSAPP`,process.env.DEBUG===`true`);var Kt=class{config;requester;blockUsers;calling;commerce;groups;marketingMessages;messages;media;payments;phoneNumbers;twoStepVerification;flows;businessProfile;templates;encryption;qrCode;registration;waba;constructor(e){Ut(),this.config=Mt(e),this.requester=new Ht(this.config[v.APIVersion],this.config[v.PhoneNumberId],this.config[v.AccessToken],this.config[v.BusinessAcctId],this.getUserAgent(),this.config.retry),this.blockUsers=new tt(this.config,this.requester),this.calling=new nt(this.config,this.requester),this.commerce=new rt(this.config,this.requester),this.groups=new ct(this.config,this.requester),this.marketingMessages=new lt(this.config,this.requester),this.messages=new L(this.config,this.requester),this.media=new ut(this.config,this.requester),this.payments=new dt(this.config,this.requester),this.phoneNumbers=new ft(this.config,this.requester),this.twoStepVerification=new Ot(this.config,this.requester),this.flows=new at(this.config,this.requester),this.businessProfile=new pt(this.config,this.requester),this.templates=new Dt(this.config,this.requester),this.encryption=new it(this.config,this.requester),this.qrCode=new mt(this.config,this.requester),this.registration=new ht(this.config,this.requester),this.waba=new kt(this.config,this.requester),K.log(`\n${Nt(this.config)}`)}updateTimeout(e){this.config[v.RequestTimeout]=e,this.requester.updateTimeout(e),K.log(`Timeout updated to ${e}ms`)}updateSenderNumberId(e){this.config[v.PhoneNumberId]=e,K.log(`Sender number ID updated to ${e}`)}updateAccessToken(e){this.config[v.AccessToken]=e,this.requester.updateAccessToken(e),K.log(`Access token updated`)}version(){return Wt()}static get Enums(){return c}getUserAgent(){return Gt()}generateEncryption(e){return Ft(e||this.config[v.Passphrase])}};function qt(e){return typeof e==`object`&&!!e}function q(e){return typeof e==`string`}const Jt=[F.DATA_EXCHANGE,F.INIT,F.BACK],Yt=[F.DATA_EXCHANGE,F.INIT];function Xt(e){if(!(`flow_token`in e&&q(e.flow_token)&&`action`in e))return!1;let{action:t,version:n,screen:r,data:i}=e,a=n===`3.0`,o=Jt.includes(t),s=r===void 0||q(r)&&r!==`SUCCESS`,c=t===F.DATA_EXCHANGE||qt(i);return a&&o&&s&&c}function Zt(e){if(!(`flow_token`in e&&q(e.flow_token)&&`action`in e))return!1;let{action:t,screen:n,data:r}=e,i=Yt.includes(t),a=q(n),o=qt(r)&&`error_key`in r&&q(r.error)&&`error_message`in r&&q(r.error_message);return i&&a&&o}function Qt(e){return`action`in e&&e.action===`ping`}const J=new U(`WEBHOOK_UTILS`,process.env.DEBUG===`true`);async function $t(e,t,n){try{let r=await e.text(),i=JSON.parse(r),a={headers:e.headers,rawBody:r,method:e.method,url:e.url};if(n.rawHandler){let{rawHandler:e,rawHandlerFields:r}=n,o=i;if(r&&r.length>0){let e={...o,entry:o.entry.map(e=>({...e,changes:e.changes.filter(e=>r.includes(e.field))})).filter(e=>e.changes.length>0)};o=e.entry.length===0?null:e}o&&await e(t,o,a)}if(i.object!==`whatsapp_business_account`){let e=`Received webhook for non-WhatsApp event`;return J.warn(e),new Response(JSON.stringify({error:e}),{status:404})}let o=[];for(let e of i.entry)try{let r=e.changes;for(let i of r)i.field===`messages`?await sn(e.id,i.value,t,n,a):i.field===`account_update`?await X(e.id,i,n.accountUpdateHandler,t,a):i.field===`account_review_update`?await X(e.id,i,n.accountReviewUpdateHandler,t,a):i.field===`account_alerts`?await X(e.id,i,n.accountAlertsHandler,t,a):i.field===`business_capability_update`?await X(e.id,i,n.businessCapabilityUpdateHandler,t,a):i.field===`phone_number_name_update`?await X(e.id,i,n.phoneNumberNameUpdateHandler,t,a):i.field===`phone_number_quality_update`?await X(e.id,i,n.phoneNumberQualityUpdateHandler,t,a):i.field===`message_template_status_update`?await X(e.id,i,n.messageTemplateStatusUpdateHandler,t,a):i.field===`template_category_update`?await X(e.id,i,n.templateCategoryUpdateHandler,t,a):i.field===`message_template_quality_update`?await X(e.id,i,n.messageTemplateQualityUpdateHandler,t,a):i.field===`flows`?await X(e.id,i,n.flowsHandler,t,a):i.field===`security`?await X(e.id,i,n.securityHandler,t,a):i.field===`history`?await X(e.id,i,n.historyHandler,t,a):i.field===`smb_message_echoes`?await X(e.id,i,n.smbMessageEchoesHandler,t,a):i.field===`smb_app_state_sync`?await X(e.id,i,n.smbAppStateSyncHandler,t,a):i.field===`account_settings_update`?await X(e.id,i,n.accountSettingsUpdateHandler,t,a):i.field===`automatic_events`?await X(e.id,i,n.automaticEventsHandler,t,a):i.field===`business_status_update`?await X(e.id,i,n.businessStatusUpdateHandler,t,a):i.field===`calls`?await X(e.id,i,n.callsHandler,t,a):i.field===`group_lifecycle_update`?await X(e.id,i,n.groupLifecycleUpdateHandler,t,a):i.field===`group_participants_update`?await X(e.id,i,n.groupParticipantsUpdateHandler,t,a):i.field===`group_settings_update`?await X(e.id,i,n.groupSettingsUpdateHandler,t,a):i.field===`group_status_update`?await X(e.id,i,n.groupStatusUpdateHandler,t,a):i.field===`message_echoes`?await X(e.id,i,n.messageEchoesHandler,t,a):i.field===`message_template_components_update`?await X(e.id,i,n.messageTemplateComponentsUpdateHandler,t,a):i.field===`messaging_handovers`?await X(e.id,i,n.messagingHandoversHandler,t,a):i.field===`partner_solutions`?await X(e.id,i,n.partnerSolutionsHandler,t,a):i.field===`payment_configuration_update`?await X(e.id,i,n.paymentConfigurationUpdateHandler,t,a):i.field===`standby`?await X(e.id,i,n.standbyHandler,t,a):i.field===`template_correct_category_detection`?await X(e.id,i,n.templateCorrectCategoryDetectionHandler,t,a):i.field===`tracking_events`?await X(e.id,i,n.trackingEventsHandler,t,a):i.field===`user_preferences`?await X(e.id,i,n.userPreferencesHandler,t,a):J.warn(`Unhandled webhook field: ${i.field}`)}catch(t){let n=`Error processing webhook: ${t}`;J.error(n,{entry:e,error:t}),o.push(n)}return new Response(o.length>0?JSON.stringify({errors:o}):null,{status:200})}catch(e){return J.error(`Error processing webhook:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500})}}function en(){return{version:`3.0`,data:{status:`active`}}}function tn(){return{data:{acknowledged:!0}}}async function nn(e,t,n,r){try{let i=await e.text(),a={headers:e.headers,rawBody:i,method:e.method,url:e.url};if(!rn(i,e.headers.get(`x-hub-signature-256`),t.WEBHOOK_VERIFICATION_TOKEN||``))return J.warn(`Invalid request signature`),new Response(JSON.stringify({error:`Unauthorized`}),{status:401});let{decryptedBody:o,aesKeyBuffer:s,initialVectorBuffer:c}=It(JSON.parse(i),t),l=Qt(o),u=Zt(o),d=Xt(o),f;f=l?I.Ping:u?I.Error:d?I.Change:I.All;let p=r.get(f);if(!p){if(f===I.Ping)p=()=>en();else if(f===I.Error)p=()=>tn();else if(p=r.get(I.All),!p)return J.warn(`No handler registered for flow type:`,{flowType:f,action:o.action}),new Response(JSON.stringify({error:`Handler not found`}),{status:404})}let m=await p(n,o,a);if(u){J.warn(`Flow error notification received`,{error:o.data});let e=m||tn();return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":`application/json`}})}if(l||d){let e=Lt(m,s,c);return new Response(e,{status:200,headers:{"Content-Type":`text/plain`}})}return J.warn(`Unknown flow request type:`,o),new Response(JSON.stringify({error:`Unknown request type`}),{status:400})}catch(e){return J.error(`Error handling flow request:`,e),new Response(JSON.stringify({error:`Internal server error`}),{status:500})}}function rn(e,t,n){if(!t)return J.warn(`Missing signature in request`),!1;let i=r.createHmac(`sha256`,n).update(e).digest(`hex`);return r.timingSafeEqual(Buffer.from(t.replace(`sha256=`,``)),Buffer.from(i))}function an(e,t){return`${e[`x-forwarded-proto`]||`http`}://${e.host||`localhost`}${t||`/`}`}function on(e){return e.id?e.id:(e.type===f.Interactive||e.type===f.Button)&&`context`in e&&e.context?.id?e.context.id:``}async function sn(e,t,n,r,i){let a=t.metadata,o=e,s=a.display_phone_number,c=a.phone_number_id;if(`statuses`in t&&t.statuses){let e=t;for(let t of e.statuses){let e={wabaId:o,phoneNumberId:c,displayPhoneNumber:s,status:t};await cn(r.statusHandler,n,e,i)}return}if(`messages`in t&&t.messages){let e=t,a=e.contacts?.[0]?.profile?.name||``;for(let t of e.messages){let e={wabaId:o,phoneNumberId:c,displayPhoneNumber:s,profileName:a,message:t,messageId:on(t)},l=t.type;await Y(r.preProcessHandler,n,e,i,`pre-process`),await Y(r.messageHandlers.get(l),n,e,i,l),await Y(r.postProcessHandler,n,e,i,`post-process`)}}}async function Y(e,t,n,r,i){if(e)try{await e(t,n,r)}catch(e){J.error(`Error in ${i} handler:`,{error:e,messageId:n.messageId})}}async function cn(e,t,n,r){if(e)try{await e(t,n,r)}catch(e){J.error(`Error in status handler:`,{error:e,statusId:n.status.id})}}async function X(e,t,n,r,i){if(n)try{await n(r,{wabaId:e,value:t.value},i)}catch(n){J.error(`Error in ${t.field} handler:`,{error:n,wabaId:e})}}const Z=new U(`WEBHOOK_PROCESSOR`,process.env.DEBUG===`true`);var Q=class{config;client;messageHandlers=new Map;statusHandler=void 0;preProcessHandler=void 0;postProcessHandler=void 0;rawHandler=void 0;flowHandlers=new Map;accountUpdateHandler=void 0;accountReviewUpdateHandler=void 0;accountAlertsHandler=void 0;businessCapabilityUpdateHandler=void 0;phoneNumberNameUpdateHandler=void 0;phoneNumberQualityUpdateHandler=void 0;messageTemplateStatusUpdateHandler=void 0;templateCategoryUpdateHandler=void 0;messageTemplateQualityUpdateHandler=void 0;flowsHandler=void 0;securityHandler=void 0;historyHandler=void 0;smbMessageEchoesHandler=void 0;smbAppStateSyncHandler=void 0;accountSettingsUpdateHandler=void 0;automaticEventsHandler=void 0;businessStatusUpdateHandler=void 0;callsHandler=void 0;groupLifecycleUpdateHandler=void 0;groupParticipantsUpdateHandler=void 0;groupSettingsUpdateHandler=void 0;groupStatusUpdateHandler=void 0;messageEchoesHandler=void 0;messageTemplateComponentsUpdateHandler=void 0;messagingHandoversHandler=void 0;partnerSolutionsHandler=void 0;paymentConfigurationUpdateHandler=void 0;standbyHandler=void 0;templateCorrectCategoryDetectionHandler=void 0;trackingEventsHandler=void 0;userPreferencesHandler=void 0;constructor(e){this.config=Mt(e),this.client=new Kt(e),Z.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 $t(e,this.client,{messageHandlers:this.messageHandlers,statusHandler:this.statusHandler,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler,rawHandler:this.rawHandler?.handler,rawHandlerFields:this.rawHandler?.fields,accountUpdateHandler:this.accountUpdateHandler,accountReviewUpdateHandler:this.accountReviewUpdateHandler,accountAlertsHandler:this.accountAlertsHandler,businessCapabilityUpdateHandler:this.businessCapabilityUpdateHandler,phoneNumberNameUpdateHandler:this.phoneNumberNameUpdateHandler,phoneNumberQualityUpdateHandler:this.phoneNumberQualityUpdateHandler,messageTemplateStatusUpdateHandler:this.messageTemplateStatusUpdateHandler,templateCategoryUpdateHandler:this.templateCategoryUpdateHandler,messageTemplateQualityUpdateHandler:this.messageTemplateQualityUpdateHandler,flowsHandler:this.flowsHandler,securityHandler:this.securityHandler,historyHandler:this.historyHandler,smbMessageEchoesHandler:this.smbMessageEchoesHandler,smbAppStateSyncHandler:this.smbAppStateSyncHandler,accountSettingsUpdateHandler:this.accountSettingsUpdateHandler,automaticEventsHandler:this.automaticEventsHandler,businessStatusUpdateHandler:this.businessStatusUpdateHandler,callsHandler:this.callsHandler,groupLifecycleUpdateHandler:this.groupLifecycleUpdateHandler,groupParticipantsUpdateHandler:this.groupParticipantsUpdateHandler,groupSettingsUpdateHandler:this.groupSettingsUpdateHandler,groupStatusUpdateHandler:this.groupStatusUpdateHandler,messageEchoesHandler:this.messageEchoesHandler,messageTemplateComponentsUpdateHandler:this.messageTemplateComponentsUpdateHandler,messagingHandoversHandler:this.messagingHandoversHandler,partnerSolutionsHandler:this.partnerSolutionsHandler,paymentConfigurationUpdateHandler:this.paymentConfigurationUpdateHandler,standbyHandler:this.standbyHandler,templateCorrectCategoryDetectionHandler:this.templateCorrectCategoryDetectionHandler,trackingEventsHandler:this.trackingEventsHandler,userPreferencesHandler:this.userPreferencesHandler}),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 Z.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 nn(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 Z.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),Z.log(`Registered message handler for ${e}`)}onStatus(e){this.statusHandler=e,Z.log(`Registered status handler`)}onMessagePreProcess(e){this.preProcessHandler=e,Z.log(`Registered pre-process handler`)}onMessagePostProcess(e){this.postProcessHandler=e,Z.log(`Registered post-process handler`)}onRaw(e,t){this.rawHandler={handler:e,fields:t},Z.log(`Registered raw webhook handler${t?` for fields: ${t.join(`, `)}`:``}`)}onFlow(e,t){this.flowHandlers.set(e,t),Z.log(`Registered flow handler for ${e}`)}onText(e){this.messageHandlers.set(f.Text,e),Z.log(`Registered text message handler`)}onImage(e){this.messageHandlers.set(f.Image,e),Z.log(`Registered image message handler`)}onVideo(e){this.messageHandlers.set(f.Video,e),Z.log(`Registered video message handler`)}onAudio(e){this.messageHandlers.set(f.Audio,e),Z.log(`Registered audio message handler`)}onDocument(e){this.messageHandlers.set(f.Document,e),Z.log(`Registered document message handler`)}onSticker(e){this.messageHandlers.set(f.Sticker,e),Z.log(`Registered sticker message handler`)}onInteractive(e){this.messageHandlers.set(f.Interactive,e),Z.log(`Registered interactive message handler`)}onButton(e){this.messageHandlers.set(f.Button,e),Z.log(`Registered button message handler`)}onLocation(e){this.messageHandlers.set(f.Location,e),Z.log(`Registered location message handler`)}onContacts(e){this.messageHandlers.set(f.Contacts,e),Z.log(`Registered contacts message handler`)}onReaction(e){this.messageHandlers.set(f.Reaction,e),Z.log(`Registered reaction message handler`)}onOrder(e){this.messageHandlers.set(f.Order,e),Z.log(`Registered order message handler`)}onSystem(e){this.messageHandlers.set(f.System,e),Z.log(`Registered system message handler`)}onAccountUpdate(e){this.accountUpdateHandler=e,Z.log(`Registered account_update handler`)}onAccountReviewUpdate(e){this.accountReviewUpdateHandler=e,Z.log(`Registered account_review_update handler`)}onAccountAlerts(e){this.accountAlertsHandler=e,Z.log(`Registered account_alerts handler`)}onBusinessCapabilityUpdate(e){this.businessCapabilityUpdateHandler=e,Z.log(`Registered business_capability_update handler`)}onPhoneNumberNameUpdate(e){this.phoneNumberNameUpdateHandler=e,Z.log(`Registered phone_number_name_update handler`)}onPhoneNumberQualityUpdate(e){this.phoneNumberQualityUpdateHandler=e,Z.log(`Registered phone_number_quality_update handler`)}onMessageTemplateStatusUpdate(e){this.messageTemplateStatusUpdateHandler=e,Z.log(`Registered message_template_status_update handler`)}onTemplateCategoryUpdate(e){this.templateCategoryUpdateHandler=e,Z.log(`Registered template_category_update handler`)}onMessageTemplateQualityUpdate(e){this.messageTemplateQualityUpdateHandler=e,Z.log(`Registered message_template_quality_update handler`)}onFlows(e){this.flowsHandler=e,Z.log(`Registered flows handler`)}onSecurity(e){this.securityHandler=e,Z.log(`Registered security handler`)}onHistory(e){this.historyHandler=e,Z.log(`Registered history handler`)}onSmbMessageEchoes(e){this.smbMessageEchoesHandler=e,Z.log(`Registered smb_message_echoes handler`)}onSmbAppStateSync(e){this.smbAppStateSyncHandler=e,Z.log(`Registered smb_app_state_sync handler`)}onAccountSettingsUpdate(e){this.accountSettingsUpdateHandler=e,Z.log(`Registered account_settings_update handler`)}onAutomaticEvents(e){this.automaticEventsHandler=e,Z.log(`Registered automatic_events handler`)}onBusinessStatusUpdate(e){this.businessStatusUpdateHandler=e,Z.log(`Registered business_status_update handler`)}onCalls(e){this.callsHandler=e,Z.log(`Registered calls handler`)}onGroupLifecycleUpdate(e){this.groupLifecycleUpdateHandler=e,Z.log(`Registered group_lifecycle_update handler`)}onGroupParticipantsUpdate(e){this.groupParticipantsUpdateHandler=e,Z.log(`Registered group_participants_update handler`)}onGroupSettingsUpdate(e){this.groupSettingsUpdateHandler=e,Z.log(`Registered group_settings_update handler`)}onGroupStatusUpdate(e){this.groupStatusUpdateHandler=e,Z.log(`Registered group_status_update handler`)}onMessageEchoes(e){this.messageEchoesHandler=e,Z.log(`Registered message_echoes handler`)}onMessageTemplateComponentsUpdate(e){this.messageTemplateComponentsUpdateHandler=e,Z.log(`Registered message_template_components_update handler`)}onMessagingHandovers(e){this.messagingHandoversHandler=e,Z.log(`Registered messaging_handovers handler`)}onPartnerSolutions(e){this.partnerSolutionsHandler=e,Z.log(`Registered partner_solutions handler`)}onPaymentConfigurationUpdate(e){this.paymentConfigurationUpdateHandler=e,Z.log(`Registered payment_configuration_update handler`)}onStandby(e){this.standbyHandler=e,Z.log(`Registered standby handler`)}onTemplateCorrectCategoryDetection(e){this.templateCorrectCategoryDetectionHandler=e,Z.log(`Registered template_correct_category_detection handler`)}onTrackingEvents(e){this.trackingEventsHandler=e,Z.log(`Registered tracking_events handler`)}onUserPreferences(e){this.userPreferencesHandler=e,Z.log(`Registered user_preferences handler`)}getClient(){return this.client}getConfig(){return this.config}},ln=class{processor;constructor(e){this.processor=new Q(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 an(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}},un=class extends ln{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}}};function dn(e){return new un(e).getHandlers()}function fn(e){let t=new Q(e);return{GET:async e=>{try{let{searchParams:n}=new URL(e.url),r=n.get(`hub.mode`),i=n.get(`hub.verify_token`),a=n.get(`hub.challenge`),o=await t.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 n=await t.processWebhook(e);return new Response(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}},webhook:{GET:async e=>{try{let{searchParams:n}=new URL(e.url),r=n.get(`hub.mode`),i=n.get(`hub.verify_token`),a=n.get(`hub.challenge`),o=await t.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 n=await t.processWebhook(e);return new Response(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}}},flow:{GET:async e=>{try{let n=await t.processFlow(e);return new Response(n.body,{status:n.status,headers:n.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 n=await t.processFlow(e);return new Response(n.body,{status:n.status,headers:n.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:t}}var pn=class extends ln{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}}};function mn(e){return new pn(e).getHandlers()}function hn(e){switch(e.type){case f.Text:return e.text.body;case f.Image:return e.image.caption||`[Image]`;case f.Video:return e.video.caption||`[Video]`;case f.Audio:return e.audio.voice?`[Voice Message]`:`[Audio]`;case f.Document:return e.document.caption||e.document.filename||`[Document]`;case f.Sticker:return e.sticker.animated?`[Animated Sticker]`:`[Sticker]`;case f.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 f.Button:return e.button.text;case f.Location:return e.location.name||e.location.address||`📍 ${e.location.latitude}, ${e.location.longitude}`;case f.Contacts:{let t=e.contacts.map(e=>e.name.formatted_name);return t.length===1?`👤 ${t[0]}`:`👤 ${t.length} contacts`}case f.Reaction:return e.reaction.emoji||`[Reaction removed]`;case f.Order:{let t=e.order.product_items.length;return`🛒 Order: ${t} item${t>1?`s`:``}`}case f.System:return e.system.body;case f.Unsupported:return`[Unsupported message]`;default:return`[${e.type}]`}}const gn=(e,t)=>n.createHmac(`sha256`,t).update(e,`utf-8`).digest(`hex`);function _n(e){return e.type===f.Text}function vn(e){return e.type===f.Image}function yn(e){return e.type===f.Video}function bn(e){return e.type===f.Audio}function xn(e){return e.type===f.Document}function Sn(e){return e.type===f.Sticker}function $(e){return e.type===f.Interactive}function Cn(e){return e.type===f.Button}function wn(e){return e.type===f.Location}function Tn(e){return e.type===f.Contacts}function En(e){return e.type===f.Reaction}function Dn(e){return e.type===f.Order}function On(e){return e.type===f.System}function kn(e){return $(e)&&e.interactive.type===`button_reply`}function An(e){return $(e)&&e.interactive.type===`list_reply`}function jn(e){return $(e)&&e.interactive.type===`nfm_reply`}function Mn(e){return vn(e)?{id:e.image.id,mimeType:e.image.mime_type,sha256:e.image.sha256,caption:e.image.caption}:yn(e)?{id:e.video.id,mimeType:e.video.mime_type,sha256:e.video.sha256,caption:e.video.caption}:bn(e)?{id:e.audio.id,mimeType:e.audio.mime_type,sha256:e.audio.sha256,voice:e.audio.voice}:xn(e)?{id:e.document.id,mimeType:e.document.mime_type,sha256:e.document.sha256,caption:e.document.caption,filename:e.document.filename}:Sn(e)?{id:e.sticker.id,mimeType:e.sticker.mime_type,sha256:e.sticker.sha256,animated:e.sticker.animated}:null}function Nn(e){return $(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 Pn(e){return wn(e)?{latitude:e.location.latitude,longitude:e.location.longitude,name:e.location.name,address:e.location.address,url:e.location.url}:null}function Fn(e){return Tn(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 In(e){return En(e)?{messageId:e.reaction.message_id,emoji:e.reaction.emoji||null}:null}function Ln(e){return Dn(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}let Rn=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),zn=function(e){return e.Blocked=`BLOCKED`,e.Limited=`LIMITED`,e.Available=`AVAILABLE`,e}({}),Bn=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),Vn=function(e){return e.Verified=`verified`,e.PendingSubmission=`pending_submission`,e.Unverified=`unverified`,e.Rejected=`rejected`,e}({});export{_e as AUTHORIZATION_ERROR_CODES,oe as AudioMediaTypesEnum,Se as BLOCK_USER_ERROR_CODES,tt as BlockUsersApi,pt as BusinessProfileApi,me as BusinessVerticalEnum,h as ButtonPositionEnum,Ce as CALLING_ERROR_CODES,nt as CallingApi,l as CategoryEnum,rt as CommerceApi,_ as ComponentTypesEnum,ee as ConversationTypesEnum,fe as CurrencyCodesEnum,pe as DataLocalizationRegionEnum,ae as DocumentMediaTypesEnum,it as EncryptionApi,xe as FLOW_ERROR_CODES,F as FlowActionEnum,at as FlowApi,st as FlowCategoryEnum,ot as FlowStatusEnum,I as FlowTypeEnum,we as GROUP_ERROR_CODES,ct as GroupsApi,d as HttpMethodsEnum,ye as INTEGRITY_ERROR_CODES,ie as ImageMediaTypesEnum,m as InteractiveTypesEnum,de as LanguagesEnum,U as Logger,lt as MarketingMessagesApi,ut as MediaApi,L as MessageApi,L as MessagesApi,f as MessageTypesEnum,p as ParametersTypesEnum,dt as PaymentsApi,ft as PhoneNumberApi,mt as QrCodeApi,le as ReferralSourceTypesEnum,ht as RegistrationApi,ue as RequestCodeMethodsEnum,be as SEND_MESSAGE_ERROR_CODES,te as StatusEnum,re as StickerMediaTypesEnum,g as SubTypeEnum,ce as SystemChangeTypesEnum,ve as THROTTLING_ERROR_CODES,Dt as TemplateApi,u as TemplateStatusEnum,Ot as TwoStepVerificationApi,ne as VideoMediaTypesEnum,he as WHATSAPP_ERROR_CODES,Rn as WabaAccountReviewStatus,Bn as WabaAccountStatus,kt as WabaApi,Vn as WabaBusinessVerificationStatus,v as WabaConfigEnum,zn as WabaHealthStatusCanSendMessage,Q as WebhookProcessor,se as WebhookTypesEnum,Kt as WhatsApp,S as WhatsAppApiError,C as WhatsAppAuthorizationError,O as WhatsAppBlockUserError,k as WhatsAppCallingError,x as WhatsAppError,D as WhatsAppFlowError,A as WhatsAppGroupError,T as WhatsAppIntegrityError,He as WhatsAppNetworkError,E as WhatsAppSendMessageError,w as WhatsAppThrottlingError,Ue as WhatsAppUnknownError,M as WhatsAppValidationError,R as buildFieldsQueryString,an as constructFullUrl,yt as createAuthenticationTemplate,bt as createCatalogTemplate,xt as createCouponTemplate,St as createLimitedTimeOfferTemplate,wt as createMPMTemplate,Ct as createMediaCardCarouselTemplate,vt as createOTPTemplate,Tt as createProductCardCarouselTemplate,Et as createSPMTemplate,_t as createTemplate,j as createWhatsAppApiError,It as decryptFlowRequest,Lt as encryptFlowResponse,dn as expressWebhookHandler,hn as extractMessageText,Nt as formatConfigTable,Ft as generateEncryption,gn as generateXHub256Sig,Fn as getContactsInfo,Nn as getInteractiveReply,Pn as getLocationInfo,Mn as getMediaInfo,Ln as getOrderInfo,In as getReactionInfo,b as isApiPermissionErrorCode,bn as isAudioMessage,Pe as isAuthorizationErrorCode,ze as isBlockUserErrorCode,Cn as isButtonMessage,kn as isButtonReply,Be as isCallingErrorCode,Tn as isContactsMessage,xn as isDocumentMessage,Xt as isFlowDataExchangeRequest,Re as isFlowErrorCode,Zt as isFlowErrorRequest,Qt as isFlowPingRequest,Ve as isGroupErrorCode,vn as isImageMessage,Ie as isIntegrityErrorCode,$ as isInteractiveMessage,An as isListReply,wn as isLocationMessage,N as isMetaError,jn as isNfmReply,Dn as isOrderMessage,En as isReactionMessage,Le as isSendMessageErrorCode,Sn as isStickerMessage,On as isSystemMessage,_n as isTextMessage,Fe as isThrottlingErrorCode,yn as isVideoMessage,We as isWhatsAppApiErrorResponse,Ge as isWhatsAppAuthorizationError,Xe as isWhatsAppBlockUserError,Ze as isWhatsAppCallingError,Ne as isWhatsAppErrorCode,Ye as isWhatsAppFlowError,Qe as isWhatsAppGroupError,qe as isWhatsAppIntegrityError,Je as isWhatsAppSendMessageError,Ke as isWhatsAppThrottlingError,fn as nextjsAppWebhookHandler,mn as nextjsPagesWebhookHandler,$e as normalizeMetaError,y as objectToQueryString,nn as processFlowRequest,$t as processWebhookMessages};
|
|
20
|
+
`)}function Gt(){try{let e=o(__dirname,`../../package.json`);return JSON.parse(a(e,`utf-8`)).version}catch{return`unknown`}}function Kt(){return`WhatsApp-Nodejs-SDK/${Gt()} (Node.js ${process.version})`}const G=new H(`WHATSAPP`,process.env.DEBUG===`true`);var qt=class{config;requester;blockUsers;calling;commerce;groups;marketingMessages;messages;media;payments;phoneNumbers;twoStepVerification;flows;businessProfile;templates;encryption;qrCode;registration;waba;constructor(e){Wt(),this.config=Nt(e),this.requester=new Ut(this.config[v.APIVersion],this.config[v.PhoneNumberId],this.config[v.AccessToken],this.config[v.BusinessAcctId],this.getUserAgent(),this.config.retry),this.blockUsers=new tt(this.config,this.requester),this.calling=new nt(this.config,this.requester),this.commerce=new rt(this.config,this.requester),this.groups=new ct(this.config,this.requester),this.marketingMessages=new lt(this.config,this.requester),this.messages=new dt(this.config,this.requester),this.media=new ut(this.config,this.requester),this.payments=new ft(this.config,this.requester),this.phoneNumbers=new pt(this.config,this.requester),this.twoStepVerification=new kt(this.config,this.requester),this.flows=new at(this.config,this.requester),this.businessProfile=new mt(this.config,this.requester),this.templates=new Ot(this.config,this.requester),this.encryption=new it(this.config,this.requester),this.qrCode=new ht(this.config,this.requester),this.registration=new gt(this.config,this.requester),this.waba=new At(this.config,this.requester),G.log(`\n${Pt(this.config)}`)}updateTimeout(e){this.config[v.RequestTimeout]=e,this.requester.updateTimeout(e),G.log(`Timeout updated to ${e}ms`)}updateSenderNumberId(e){this.config[v.PhoneNumberId]=e,G.log(`Sender number ID updated to ${e}`)}updateAccessToken(e){this.config[v.AccessToken]=e,this.requester.updateAccessToken(e),G.log(`Access token updated`)}version(){return Gt()}static get Enums(){return c}getUserAgent(){return Kt()}generateEncryption(e){return It(e||this.config[v.Passphrase])}};function Jt(e){return typeof e==`object`&&!!e}function K(e){return typeof e==`string`}const Yt=[F.DATA_EXCHANGE,F.INIT,F.BACK],Xt=[F.DATA_EXCHANGE,F.INIT];function Zt(e){if(!(`flow_token`in e&&K(e.flow_token)&&`action`in e))return!1;let{action:t,version:n,screen:r,data:i}=e,a=n===`3.0`,o=Yt.includes(t),s=r===void 0||K(r)&&r!==`SUCCESS`,c=t===F.DATA_EXCHANGE||Jt(i);return a&&o&&s&&c}function Qt(e){if(!(`flow_token`in e&&K(e.flow_token)&&`action`in e))return!1;let{action:t,screen:n,data:r}=e,i=Xt.includes(t),a=K(n),o=Jt(r)&&`error_key`in r&&K(r.error)&&`error_message`in r&&K(r.error_message);return i&&a&&o}function $t(e){return`action`in e&&e.action===`ping`}const q=new H(`WEBHOOK_UTILS`,process.env.DEBUG===`true`);async function en(e,t,n){try{let r=await e.text(),i=JSON.parse(r),a={headers:e.headers,rawBody:r,method:e.method,url:e.url};if(n.rawHandler){let{rawHandler:e,rawHandlerFields:r}=n,o=i;if(r&&r.length>0){let e={...o,entry:o.entry.map(e=>({...e,changes:e.changes.filter(e=>r.includes(e.field))})).filter(e=>e.changes.length>0)};o=e.entry.length===0?null:e}o&&await e(t,o,a)}if(i.object!==`whatsapp_business_account`){let e=`Received webhook for non-WhatsApp event`;return q.warn(e),new Response(JSON.stringify({error:e}),{status:404})}let o=[];for(let e of i.entry)try{let r=e.changes;for(let i of r)i.field===`messages`?await cn(e.id,i.value,t,n,a):i.field===`account_update`?await Y(e.id,i,n.accountUpdateHandler,t,a):i.field===`account_review_update`?await Y(e.id,i,n.accountReviewUpdateHandler,t,a):i.field===`account_alerts`?await Y(e.id,i,n.accountAlertsHandler,t,a):i.field===`business_capability_update`?await Y(e.id,i,n.businessCapabilityUpdateHandler,t,a):i.field===`phone_number_name_update`?await Y(e.id,i,n.phoneNumberNameUpdateHandler,t,a):i.field===`phone_number_quality_update`?await Y(e.id,i,n.phoneNumberQualityUpdateHandler,t,a):i.field===`message_template_status_update`?await Y(e.id,i,n.messageTemplateStatusUpdateHandler,t,a):i.field===`template_category_update`?await Y(e.id,i,n.templateCategoryUpdateHandler,t,a):i.field===`message_template_quality_update`?await Y(e.id,i,n.messageTemplateQualityUpdateHandler,t,a):i.field===`flows`?await Y(e.id,i,n.flowsHandler,t,a):i.field===`security`?await Y(e.id,i,n.securityHandler,t,a):i.field===`history`?await Y(e.id,i,n.historyHandler,t,a):i.field===`smb_message_echoes`?await Y(e.id,i,n.smbMessageEchoesHandler,t,a):i.field===`smb_app_state_sync`?await Y(e.id,i,n.smbAppStateSyncHandler,t,a):i.field===`account_settings_update`?await Y(e.id,i,n.accountSettingsUpdateHandler,t,a):i.field===`automatic_events`?await Y(e.id,i,n.automaticEventsHandler,t,a):i.field===`business_status_update`?await Y(e.id,i,n.businessStatusUpdateHandler,t,a):i.field===`calls`?await Y(e.id,i,n.callsHandler,t,a):i.field===`group_lifecycle_update`?await Y(e.id,i,n.groupLifecycleUpdateHandler,t,a):i.field===`group_participants_update`?await Y(e.id,i,n.groupParticipantsUpdateHandler,t,a):i.field===`group_settings_update`?await Y(e.id,i,n.groupSettingsUpdateHandler,t,a):i.field===`group_status_update`?await Y(e.id,i,n.groupStatusUpdateHandler,t,a):i.field===`message_echoes`?await Y(e.id,i,n.messageEchoesHandler,t,a):i.field===`message_template_components_update`?await Y(e.id,i,n.messageTemplateComponentsUpdateHandler,t,a):i.field===`messaging_handovers`?await Y(e.id,i,n.messagingHandoversHandler,t,a):i.field===`partner_solutions`?await Y(e.id,i,n.partnerSolutionsHandler,t,a):i.field===`payment_configuration_update`?await Y(e.id,i,n.paymentConfigurationUpdateHandler,t,a):i.field===`standby`?await Y(e.id,i,n.standbyHandler,t,a):i.field===`template_correct_category_detection`?await Y(e.id,i,n.templateCorrectCategoryDetectionHandler,t,a):i.field===`tracking_events`?await Y(e.id,i,n.trackingEventsHandler,t,a):i.field===`user_preferences`?await Y(e.id,i,n.userPreferencesHandler,t,a):q.warn(`Unhandled webhook field: ${i.field}`)}catch(t){let n=`Error processing webhook: ${t}`;q.error(n,{entry:e,error:t}),o.push(n)}return new Response(o.length>0?JSON.stringify({errors:o}):null,{status:200})}catch(e){return q.error(`Error processing webhook:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500})}}function tn(){return{version:`3.0`,data:{status:`active`}}}function nn(){return{data:{acknowledged:!0}}}async function rn(e,t,n,r){try{let i=await e.text(),a={headers:e.headers,rawBody:i,method:e.method,url:e.url};if(!an(i,e.headers.get(`x-hub-signature-256`),t.WEBHOOK_VERIFICATION_TOKEN||``))return q.warn(`Invalid request signature`),new Response(JSON.stringify({error:`Unauthorized`}),{status:401});let{decryptedBody:o,aesKeyBuffer:s,initialVectorBuffer:c}=Lt(JSON.parse(i),t),l=$t(o),u=Qt(o),d=Zt(o),f;f=l?I.Ping:u?I.Error:d?I.Change:I.All;let p=r.get(f);if(!p){if(f===I.Ping)p=()=>tn();else if(f===I.Error)p=()=>nn();else if(p=r.get(I.All),!p)return q.warn(`No handler registered for flow type:`,{flowType:f,action:o.action}),new Response(JSON.stringify({error:`Handler not found`}),{status:404})}let m=await p(n,o,a);if(u){q.warn(`Flow error notification received`,{error:o.data});let e=m||nn();return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":`application/json`}})}if(l||d){let e=Rt(m,s,c);return new Response(e,{status:200,headers:{"Content-Type":`text/plain`}})}return q.warn(`Unknown flow request type:`,o),new Response(JSON.stringify({error:`Unknown request type`}),{status:400})}catch(e){return q.error(`Error handling flow request:`,e),new Response(JSON.stringify({error:`Internal server error`}),{status:500})}}function an(e,t,n){if(!t)return q.warn(`Missing signature in request`),!1;let i=r.createHmac(`sha256`,n).update(e).digest(`hex`);return r.timingSafeEqual(Buffer.from(t.replace(`sha256=`,``)),Buffer.from(i))}function on(e,t){return`${e[`x-forwarded-proto`]||`http`}://${e.host||`localhost`}${t||`/`}`}function sn(e){return e.id?e.id:(e.type===f.Interactive||e.type===f.Button)&&`context`in e&&e.context?.id?e.context.id:``}async function cn(e,t,n,r,i){let a=t.metadata,o=e,s=a.display_phone_number,c=a.phone_number_id;if(`statuses`in t&&t.statuses){let e=t;for(let t of e.statuses){let e={wabaId:o,phoneNumberId:c,displayPhoneNumber:s,status:t};await ln(r.statusHandler,n,e,i)}return}if(`messages`in t&&t.messages){let e=t,a=e.contacts?.[0]?.profile?.name||``;for(let t of e.messages){let e={wabaId:o,phoneNumberId:c,displayPhoneNumber:s,profileName:a,message:t,messageId:sn(t)},l=t.type;await J(r.preProcessHandler,n,e,i,`pre-process`),await J(r.messageHandlers.get(l),n,e,i,l),await J(r.postProcessHandler,n,e,i,`post-process`)}}}async function J(e,t,n,r,i){if(e)try{await e(t,n,r)}catch(e){q.error(`Error in ${i} handler:`,{error:e,messageId:n.messageId})}}async function ln(e,t,n,r){if(e)try{await e(t,n,r)}catch(e){q.error(`Error in status handler:`,{error:e,statusId:n.status.id})}}async function Y(e,t,n,r,i){if(n)try{await n(r,{wabaId:e,value:t.value},i)}catch(n){q.error(`Error in ${t.field} handler:`,{error:n,wabaId:e})}}const X=new H(`WEBHOOK_PROCESSOR`,process.env.DEBUG===`true`);var Z=class{config;client;messageHandlers=new Map;statusHandler=void 0;preProcessHandler=void 0;postProcessHandler=void 0;rawHandler=void 0;flowHandlers=new Map;accountUpdateHandler=void 0;accountReviewUpdateHandler=void 0;accountAlertsHandler=void 0;businessCapabilityUpdateHandler=void 0;phoneNumberNameUpdateHandler=void 0;phoneNumberQualityUpdateHandler=void 0;messageTemplateStatusUpdateHandler=void 0;templateCategoryUpdateHandler=void 0;messageTemplateQualityUpdateHandler=void 0;flowsHandler=void 0;securityHandler=void 0;historyHandler=void 0;smbMessageEchoesHandler=void 0;smbAppStateSyncHandler=void 0;accountSettingsUpdateHandler=void 0;automaticEventsHandler=void 0;businessStatusUpdateHandler=void 0;callsHandler=void 0;groupLifecycleUpdateHandler=void 0;groupParticipantsUpdateHandler=void 0;groupSettingsUpdateHandler=void 0;groupStatusUpdateHandler=void 0;messageEchoesHandler=void 0;messageTemplateComponentsUpdateHandler=void 0;messagingHandoversHandler=void 0;partnerSolutionsHandler=void 0;paymentConfigurationUpdateHandler=void 0;standbyHandler=void 0;templateCorrectCategoryDetectionHandler=void 0;trackingEventsHandler=void 0;userPreferencesHandler=void 0;constructor(e){this.config=Nt(e),this.client=new qt(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 en(e,this.client,{messageHandlers:this.messageHandlers,statusHandler:this.statusHandler,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler,rawHandler:this.rawHandler?.handler,rawHandlerFields:this.rawHandler?.fields,accountUpdateHandler:this.accountUpdateHandler,accountReviewUpdateHandler:this.accountReviewUpdateHandler,accountAlertsHandler:this.accountAlertsHandler,businessCapabilityUpdateHandler:this.businessCapabilityUpdateHandler,phoneNumberNameUpdateHandler:this.phoneNumberNameUpdateHandler,phoneNumberQualityUpdateHandler:this.phoneNumberQualityUpdateHandler,messageTemplateStatusUpdateHandler:this.messageTemplateStatusUpdateHandler,templateCategoryUpdateHandler:this.templateCategoryUpdateHandler,messageTemplateQualityUpdateHandler:this.messageTemplateQualityUpdateHandler,flowsHandler:this.flowsHandler,securityHandler:this.securityHandler,historyHandler:this.historyHandler,smbMessageEchoesHandler:this.smbMessageEchoesHandler,smbAppStateSyncHandler:this.smbAppStateSyncHandler,accountSettingsUpdateHandler:this.accountSettingsUpdateHandler,automaticEventsHandler:this.automaticEventsHandler,businessStatusUpdateHandler:this.businessStatusUpdateHandler,callsHandler:this.callsHandler,groupLifecycleUpdateHandler:this.groupLifecycleUpdateHandler,groupParticipantsUpdateHandler:this.groupParticipantsUpdateHandler,groupSettingsUpdateHandler:this.groupSettingsUpdateHandler,groupStatusUpdateHandler:this.groupStatusUpdateHandler,messageEchoesHandler:this.messageEchoesHandler,messageTemplateComponentsUpdateHandler:this.messageTemplateComponentsUpdateHandler,messagingHandoversHandler:this.messagingHandoversHandler,partnerSolutionsHandler:this.partnerSolutionsHandler,paymentConfigurationUpdateHandler:this.paymentConfigurationUpdateHandler,standbyHandler:this.standbyHandler,templateCorrectCategoryDetectionHandler:this.templateCorrectCategoryDetectionHandler,trackingEventsHandler:this.trackingEventsHandler,userPreferencesHandler:this.userPreferencesHandler}),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 rn(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`)}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}`)}onText(e){this.messageHandlers.set(f.Text,e),X.log(`Registered text message handler`)}onImage(e){this.messageHandlers.set(f.Image,e),X.log(`Registered image message handler`)}onVideo(e){this.messageHandlers.set(f.Video,e),X.log(`Registered video message handler`)}onAudio(e){this.messageHandlers.set(f.Audio,e),X.log(`Registered audio message handler`)}onDocument(e){this.messageHandlers.set(f.Document,e),X.log(`Registered document message handler`)}onSticker(e){this.messageHandlers.set(f.Sticker,e),X.log(`Registered sticker message handler`)}onInteractive(e){this.messageHandlers.set(f.Interactive,e),X.log(`Registered interactive message handler`)}onButton(e){this.messageHandlers.set(f.Button,e),X.log(`Registered button message handler`)}onLocation(e){this.messageHandlers.set(f.Location,e),X.log(`Registered location message handler`)}onContacts(e){this.messageHandlers.set(f.Contacts,e),X.log(`Registered contacts message handler`)}onReaction(e){this.messageHandlers.set(f.Reaction,e),X.log(`Registered reaction message handler`)}onOrder(e){this.messageHandlers.set(f.Order,e),X.log(`Registered order message handler`)}onSystem(e){this.messageHandlers.set(f.System,e),X.log(`Registered system message handler`)}onAccountUpdate(e){this.accountUpdateHandler=e,X.log(`Registered account_update handler`)}onAccountReviewUpdate(e){this.accountReviewUpdateHandler=e,X.log(`Registered account_review_update handler`)}onAccountAlerts(e){this.accountAlertsHandler=e,X.log(`Registered account_alerts handler`)}onBusinessCapabilityUpdate(e){this.businessCapabilityUpdateHandler=e,X.log(`Registered business_capability_update handler`)}onPhoneNumberNameUpdate(e){this.phoneNumberNameUpdateHandler=e,X.log(`Registered phone_number_name_update handler`)}onPhoneNumberQualityUpdate(e){this.phoneNumberQualityUpdateHandler=e,X.log(`Registered phone_number_quality_update handler`)}onMessageTemplateStatusUpdate(e){this.messageTemplateStatusUpdateHandler=e,X.log(`Registered message_template_status_update handler`)}onTemplateCategoryUpdate(e){this.templateCategoryUpdateHandler=e,X.log(`Registered template_category_update handler`)}onMessageTemplateQualityUpdate(e){this.messageTemplateQualityUpdateHandler=e,X.log(`Registered message_template_quality_update handler`)}onFlows(e){this.flowsHandler=e,X.log(`Registered flows handler`)}onSecurity(e){this.securityHandler=e,X.log(`Registered security handler`)}onHistory(e){this.historyHandler=e,X.log(`Registered history handler`)}onSmbMessageEchoes(e){this.smbMessageEchoesHandler=e,X.log(`Registered smb_message_echoes handler`)}onSmbAppStateSync(e){this.smbAppStateSyncHandler=e,X.log(`Registered smb_app_state_sync handler`)}onAccountSettingsUpdate(e){this.accountSettingsUpdateHandler=e,X.log(`Registered account_settings_update handler`)}onAutomaticEvents(e){this.automaticEventsHandler=e,X.log(`Registered automatic_events handler`)}onBusinessStatusUpdate(e){this.businessStatusUpdateHandler=e,X.log(`Registered business_status_update handler`)}onCalls(e){this.callsHandler=e,X.log(`Registered calls handler`)}onGroupLifecycleUpdate(e){this.groupLifecycleUpdateHandler=e,X.log(`Registered group_lifecycle_update handler`)}onGroupParticipantsUpdate(e){this.groupParticipantsUpdateHandler=e,X.log(`Registered group_participants_update handler`)}onGroupSettingsUpdate(e){this.groupSettingsUpdateHandler=e,X.log(`Registered group_settings_update handler`)}onGroupStatusUpdate(e){this.groupStatusUpdateHandler=e,X.log(`Registered group_status_update handler`)}onMessageEchoes(e){this.messageEchoesHandler=e,X.log(`Registered message_echoes handler`)}onMessageTemplateComponentsUpdate(e){this.messageTemplateComponentsUpdateHandler=e,X.log(`Registered message_template_components_update handler`)}onMessagingHandovers(e){this.messagingHandoversHandler=e,X.log(`Registered messaging_handovers handler`)}onPartnerSolutions(e){this.partnerSolutionsHandler=e,X.log(`Registered partner_solutions handler`)}onPaymentConfigurationUpdate(e){this.paymentConfigurationUpdateHandler=e,X.log(`Registered payment_configuration_update handler`)}onStandby(e){this.standbyHandler=e,X.log(`Registered standby handler`)}onTemplateCorrectCategoryDetection(e){this.templateCorrectCategoryDetectionHandler=e,X.log(`Registered template_correct_category_detection handler`)}onTrackingEvents(e){this.trackingEventsHandler=e,X.log(`Registered tracking_events handler`)}onUserPreferences(e){this.userPreferencesHandler=e,X.log(`Registered user_preferences handler`)}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`)}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.preProcessHandler=void 0,this.postProcessHandler=void 0,this.rawHandler=void 0,this.flowHandlers.clear(),this.accountUpdateHandler=void 0,this.accountReviewUpdateHandler=void 0,this.accountAlertsHandler=void 0,this.businessCapabilityUpdateHandler=void 0,this.phoneNumberNameUpdateHandler=void 0,this.phoneNumberQualityUpdateHandler=void 0,this.messageTemplateStatusUpdateHandler=void 0,this.templateCategoryUpdateHandler=void 0,this.messageTemplateQualityUpdateHandler=void 0,this.flowsHandler=void 0,this.securityHandler=void 0,this.historyHandler=void 0,this.smbMessageEchoesHandler=void 0,this.smbAppStateSyncHandler=void 0,this.accountSettingsUpdateHandler=void 0,this.automaticEventsHandler=void 0,this.businessStatusUpdateHandler=void 0,this.callsHandler=void 0,this.groupLifecycleUpdateHandler=void 0,this.groupParticipantsUpdateHandler=void 0,this.groupSettingsUpdateHandler=void 0,this.groupStatusUpdateHandler=void 0,this.messageEchoesHandler=void 0,this.messageTemplateComponentsUpdateHandler=void 0,this.messagingHandoversHandler=void 0,this.partnerSolutionsHandler=void 0,this.paymentConfigurationUpdateHandler=void 0,this.standbyHandler=void 0,this.templateCorrectCategoryDetectionHandler=void 0,this.trackingEventsHandler=void 0,this.userPreferencesHandler=void 0,X.log(`Removed all handlers`)}getClient(){return this.client}getConfig(){return this.config}},un=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 on(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}},dn=class extends un{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 Q=new Map;function fn(e){return`express:${e.phoneNumberId??`default`}`}function pn(e){let t=fn(e),n=Q.get(t);if(n)return n;let r=new dn(e),i={...r.getHandlers(),destroy:()=>{r.webhookProcessor.removeAllHandlers(),Q.delete(t)}};return Q.set(t,i),i}const mn=new Map;function hn(e){return`nextjs-app:${e.phoneNumberId??`default`}`}function gn(e){let t=hn(e),n=mn.get(t);if(n)return n;let r=new Z(e),i={GET:async e=>{try{let{searchParams:t}=new URL(e.url),n=t.get(`hub.mode`),i=t.get(`hub.verify_token`),a=t.get(`hub.challenge`),o=await r.processVerification(n,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 r.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),n=t.get(`hub.mode`),i=t.get(`hub.verify_token`),a=t.get(`hub.challenge`),o=await r.processVerification(n,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 r.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 r.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 r.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:r,destroy:()=>{r.removeAllHandlers(),mn.delete(t)}};return mn.set(t,i),i}var _n=class extends un{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 vn=new Map;function yn(e){return`nextjs-page:${e.phoneNumberId??`default`}`}function bn(e){let t=yn(e),n=vn.get(t);if(n)return n;let r=new _n(e),i={...r.getHandlers(),destroy:()=>{r.webhookProcessor.removeAllHandlers(),vn.delete(t)}};return vn.set(t,i),i}function xn(e){switch(e.type){case f.Text:return e.text.body;case f.Image:return e.image.caption||`[Image]`;case f.Video:return e.video.caption||`[Video]`;case f.Audio:return e.audio.voice?`[Voice Message]`:`[Audio]`;case f.Document:return e.document.caption||e.document.filename||`[Document]`;case f.Sticker:return e.sticker.animated?`[Animated Sticker]`:`[Sticker]`;case f.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 f.Button:return e.button.text;case f.Location:return e.location.name||e.location.address||`📍 ${e.location.latitude}, ${e.location.longitude}`;case f.Contacts:{let t=e.contacts.map(e=>e.name.formatted_name);return t.length===1?`👤 ${t[0]}`:`👤 ${t.length} contacts`}case f.Reaction:return e.reaction.emoji||`[Reaction removed]`;case f.Order:{let t=e.order.product_items.length;return`🛒 Order: ${t} item${t>1?`s`:``}`}case f.System:return e.system.body;case f.Unsupported:return`[Unsupported message]`;default:return`[${e.type}]`}}const Sn=(e,t)=>n.createHmac(`sha256`,t).update(e,`utf-8`).digest(`hex`);function Cn(e){return e.type===f.Text}function wn(e){return e.type===f.Image}function Tn(e){return e.type===f.Video}function En(e){return e.type===f.Audio}function Dn(e){return e.type===f.Document}function On(e){return e.type===f.Sticker}function $(e){return e.type===f.Interactive}function kn(e){return e.type===f.Button}function An(e){return e.type===f.Location}function jn(e){return e.type===f.Contacts}function Mn(e){return e.type===f.Reaction}function Nn(e){return e.type===f.Order}function Pn(e){return e.type===f.System}function Fn(e){return $(e)&&e.interactive.type===`button_reply`}function In(e){return $(e)&&e.interactive.type===`list_reply`}function Ln(e){return $(e)&&e.interactive.type===`nfm_reply`}function Rn(e){return wn(e)?{id:e.image.id,mimeType:e.image.mime_type,sha256:e.image.sha256,caption:e.image.caption}:Tn(e)?{id:e.video.id,mimeType:e.video.mime_type,sha256:e.video.sha256,caption:e.video.caption}:En(e)?{id:e.audio.id,mimeType:e.audio.mime_type,sha256:e.audio.sha256,voice:e.audio.voice}:Dn(e)?{id:e.document.id,mimeType:e.document.mime_type,sha256:e.document.sha256,caption:e.document.caption,filename:e.document.filename}:On(e)?{id:e.sticker.id,mimeType:e.sticker.mime_type,sha256:e.sticker.sha256,animated:e.sticker.animated}:null}function zn(e){return $(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 Bn(e){return An(e)?{latitude:e.location.latitude,longitude:e.location.longitude,name:e.location.name,address:e.location.address,url:e.location.url}:null}function Vn(e){return jn(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 Hn(e){return Mn(e)?{messageId:e.reaction.message_id,emoji:e.reaction.emoji||null}:null}function Un(e){return Nn(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}let Wn=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),Gn=function(e){return e.Blocked=`BLOCKED`,e.Limited=`LIMITED`,e.Available=`AVAILABLE`,e}({}),Kn=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),qn=function(e){return e.Verified=`verified`,e.PendingSubmission=`pending_submission`,e.Unverified=`unverified`,e.Rejected=`rejected`,e}({});export{_e as AUTHORIZATION_ERROR_CODES,oe as AudioMediaTypesEnum,Se as BLOCK_USER_ERROR_CODES,tt as BlockUsersApi,mt as BusinessProfileApi,me as BusinessVerticalEnum,h as ButtonPositionEnum,Ce as CALLING_ERROR_CODES,nt as CallingApi,l as CategoryEnum,rt as CommerceApi,_ as ComponentTypesEnum,ee as ConversationTypesEnum,fe as CurrencyCodesEnum,pe as DataLocalizationRegionEnum,ae as DocumentMediaTypesEnum,it as EncryptionApi,xe as FLOW_ERROR_CODES,F as FlowActionEnum,at as FlowApi,st as FlowCategoryEnum,ot as FlowStatusEnum,I as FlowTypeEnum,we as GROUP_ERROR_CODES,ct as GroupsApi,d as HttpMethodsEnum,ye as INTEGRITY_ERROR_CODES,ie as ImageMediaTypesEnum,m as InteractiveTypesEnum,de as LanguagesEnum,H as Logger,lt as MarketingMessagesApi,ut as MediaApi,dt as MessageApi,dt as MessagesApi,f as MessageTypesEnum,p as ParametersTypesEnum,ft as PaymentsApi,pt as PhoneNumberApi,ht as QrCodeApi,le as ReferralSourceTypesEnum,gt as RegistrationApi,ue as RequestCodeMethodsEnum,be as SEND_MESSAGE_ERROR_CODES,te as StatusEnum,re as StickerMediaTypesEnum,g as SubTypeEnum,ce as SystemChangeTypesEnum,ve as THROTTLING_ERROR_CODES,Ot as TemplateApi,u as TemplateStatusEnum,kt as TwoStepVerificationApi,ne as VideoMediaTypesEnum,he as WHATSAPP_ERROR_CODES,Wn as WabaAccountReviewStatus,Kn as WabaAccountStatus,At as WabaApi,qn as WabaBusinessVerificationStatus,v as WabaConfigEnum,Gn as WabaHealthStatusCanSendMessage,Z as WebhookProcessor,se as WebhookTypesEnum,qt as WhatsApp,S as WhatsAppApiError,C as WhatsAppAuthorizationError,O as WhatsAppBlockUserError,k as WhatsAppCallingError,x as WhatsAppError,D as WhatsAppFlowError,A as WhatsAppGroupError,T as WhatsAppIntegrityError,He as WhatsAppNetworkError,E as WhatsAppSendMessageError,w as WhatsAppThrottlingError,Ue as WhatsAppUnknownError,M as WhatsAppValidationError,L as buildFieldsQueryString,on as constructFullUrl,bt as createAuthenticationTemplate,xt as createCatalogTemplate,St as createCouponTemplate,Ct as createLimitedTimeOfferTemplate,Tt as createMPMTemplate,wt as createMediaCardCarouselTemplate,yt as createOTPTemplate,Et as createProductCardCarouselTemplate,Dt as createSPMTemplate,vt as createTemplate,j as createWhatsAppApiError,Lt as decryptFlowRequest,Rt as encryptFlowResponse,pn as expressWebhookHandler,xn as extractMessageText,Pt as formatConfigTable,It as generateEncryption,Sn as generateXHub256Sig,Vn as getContactsInfo,zn as getInteractiveReply,Bn as getLocationInfo,Rn as getMediaInfo,Un as getOrderInfo,Hn as getReactionInfo,b as isApiPermissionErrorCode,En as isAudioMessage,Pe as isAuthorizationErrorCode,ze as isBlockUserErrorCode,kn as isButtonMessage,Fn as isButtonReply,Be as isCallingErrorCode,jn as isContactsMessage,Dn as isDocumentMessage,Zt as isFlowDataExchangeRequest,Re as isFlowErrorCode,Qt as isFlowErrorRequest,$t as isFlowPingRequest,Ve as isGroupErrorCode,wn as isImageMessage,Ie as isIntegrityErrorCode,$ as isInteractiveMessage,In as isListReply,An as isLocationMessage,N as isMetaError,Ln as isNfmReply,Nn as isOrderMessage,Mn as isReactionMessage,Le as isSendMessageErrorCode,On as isStickerMessage,Pn as isSystemMessage,Cn as isTextMessage,Fe as isThrottlingErrorCode,Tn as isVideoMessage,We as isWhatsAppApiErrorResponse,Ge as isWhatsAppAuthorizationError,Xe as isWhatsAppBlockUserError,Ze as isWhatsAppCallingError,Ne as isWhatsAppErrorCode,Ye as isWhatsAppFlowError,Qe as isWhatsAppGroupError,qe as isWhatsAppIntegrityError,Je as isWhatsAppSendMessageError,Ke as isWhatsAppThrottlingError,gn as nextjsAppWebhookHandler,bn as nextjsPagesWebhookHandler,$e as normalizeMetaError,y as objectToQueryString,rn as processFlowRequest,en as processWebhookMessages};
|
|
21
21
|
//# sourceMappingURL=index.js.map
|