meta-cloud-api 3.11.2 → 3.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- import{t as e}from"./chunk.mjs";import*as t from"node:crypto";const n=`whatsapp`;var r=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)}async sendRaw(e,t,n){return(await this.client.sendRequest(e,t,n)).rawResponse()}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)}},i=e({AudioMediaTypesEnum:()=>ae,BusinessVerticalEnum:()=>pe,ButtonPositionEnum:()=>f,CategoryEnum:()=>a,ComponentTypesEnum:()=>m,ConversationTypesEnum:()=>g,CurrencyCodesEnum:()=>de,DataLocalizationRegionEnum:()=>fe,DocumentMediaTypesEnum:()=>ie,HttpMethodsEnum:()=>c,ImageMediaTypesEnum:()=>re,InteractiveTypesEnum:()=>d,LanguagesEnum:()=>ue,MessageCategoryEnum:()=>o,MessageTypesEnum:()=>l,ParametersTypesEnum:()=>u,ReferralSourceTypesEnum:()=>ce,RequestCodeMethodsEnum:()=>le,StatusEnum:()=>ee,StickerMediaTypesEnum:()=>ne,SubTypeEnum:()=>p,SystemChangeTypesEnum:()=>se,TemplateStatusEnum:()=>s,VideoMediaTypesEnum:()=>te,WabaConfigEnum:()=>h,WebhookTypesEnum:()=>oe});let a=function(e){return e.Authentication=`AUTHENTICATION`,e.Marketing=`MARKETING`,e.Utility=`UTILITY`,e}({}),o=function(e){return e.Authentication=`authentication`,e.Service=`service`,e.Utility=`utility`,e}({}),s=function(e){return e.Approved=`APPROVED`,e.Pending=`PENDING`,e.Rejected=`REJECTED`,e}({}),c=function(e){return e.Get=`GET`,e.Post=`POST`,e.Put=`PUT`,e.Delete=`DELETE`,e}({}),l=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.Edit=`edit`,e.Revoke=`revoke`,e.Unsupported=`unsupported`,e.Unknown=`unknown`,e.Statuses=`statuses`,e[`*`]=`*`,e}({}),u=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}({}),d=function(e){return e.Button=`button`,e.List=`list`,e.Product=`product`,e.ProductList=`product_list`,e.CatalogMessage=`catalog_message`,e.CallPermissionRequest=`call_permission_request`,e.CtaUrl=`cta_url`,e.Carousel=`carousel`,e.LocationRequest=`location_request_message`,e.AddressMessage=`address_message`,e.Flow=`flow`,e.VoiceCall=`voice_call`,e}({}),f=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}({}),p=function(e){return e.Catalog=`CATALOG`,e.CopyCode=`COPY_CODE`,e.Flow=`FLOW`,e.Mpm=`MPM`,e.OrderDetails=`ORDER_DETAILS`,e.PaymentRequest=`PAYMENT_REQUEST`,e.PhoneNumber=`PHONE_NUMBER`,e.QuickReply=`QUICK_REPLY`,e.Reminder=`REMINDER`,e.Url=`URL`,e.VoiceCall=`VOICE_CALL`,e}({}),m=function(e){return e.Header=`HEADER`,e.Body=`BODY`,e.Button=`BUTTON`,e.Footer=`FOOTER`,e}({}),h=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}({}),g=function(e){return e.BusinessInitiated=`business_initiated`,e.CustomerInitiated=`customer_initiated`,e.ReferralConversion=`referral_conversion`,e}({}),ee=function(e){return e.Delivered=`delivered`,e.Read=`read`,e.Sent=`sent`,e}({}),te=function(e){return e.Mp4=`video/mp4`,e.Threegp=`video/3gp`,e}({}),ne=function(e){return e.Webp=`image/webp`,e}({}),re=function(e){return e.Jpeg=`image/jpeg`,e.Png=`image/png`,e}({}),ie=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}({}),ae=function(e){return e.Aac=`audio/aac`,e.Mp4=`audio/mp4`,e.Mpeg=`audio/mpeg`,e.Amr=`audio/amr`,e.Ogg=`audio/ogg`,e}({}),oe=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}({}),se=function(e){return e.CustomerChangedNumber=`customer_changed_number`,e.CustomerIdentityChanged=`customer_identity_changed`,e.UserChangedNumber=`user_changed_number`,e.UserIdentityChanged=`user_identity_changed`,e.UserChangedUserId=`user_changed_user_id`,e}({}),ce=function(e){return e.Ad=`ad`,e.Post=`post`,e}({}),le=function(e){return e.Sms=`SMS`,e.Voice=`VOICE`,e}({}),ue=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}({}),de=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}({}),fe=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}({}),pe=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 _=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(`&`)}`:``},me=[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,131061,131062,131063,131065,131070,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,138038,139e3,139001,139002,139003,139004,139100,139101,139102,139103,147005,200005,200006,200007,1752041,2388001,2388012,2388019,2388040,2388047,2388072,2388073,2388091,2388093,2388103,2388293,2388299,2494100,2494191,2593079,2593085,2593107,2593108],he=new Set(me),ge=[0,3,10,190],_e=[4,80007,130429,131048,131056],ve=[368,130497,131031],ye=[130472,131e3,131005,131008,131009,131016,131021,131026,131030,131042,131044,131045,131047,131050,131051,131052,131053,131056,131057,131048,131061,131062,131063,131065,131070,132e3,132001,132005,132007,132008,132012,132015,132016,132068,132069,135e3,137e3],be=[139e3,139001,139002,139003,139004],xe=[139100,139101,139102,139103],Se=[138e3,138001,138002,138003,138004,138005,138006,138007,138009,138012,138013,138018,138038,613],Ce=[131020,131041,131059,131201,131202,131203,131204,131207,131208,131209,131210,131211,131212,131213,131214,131215],we=new Set(ge),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);function Me(e){return Ne(e)?!0:he.has(e)}function Ne(e){return e>=200&&e<300}function Pe(e){return Ne(e)||we.has(e)}function Fe(e){return Te.has(e)}function Ie(e){return Ee.has(e)}function Le(e){return De.has(e)}function Re(e){return Oe.has(e)}function ze(e){return ke.has(e)}function Be(e){return Ae.has(e)}function Ve(e){return je.has(e)}var v=class extends Error{constructor(e){super(e),this.name=`WhatsAppError`}},y=class extends v{error;statusCode;rateLimit;constructor(e,t,n){super(e),this.name=`WhatsAppApiError`,this.error=t,this.statusCode=n}},b=class extends y{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppAuthorizationError`}},x=class extends y{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppThrottlingError`}},S=class extends y{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppIntegrityError`}},C=class extends y{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppSendMessageError`}},He=class extends y{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppFlowError`}},Ue=class extends y{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppBlockUserError`}},We=class extends y{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppCallingError`}},Ge=class extends y{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppGroupError`}};function w(e,t){let n=e.code;return Pe(n)?new b(e.message,e,t):Fe(n)?new x(e.message,e,t):Ie(n)?new S(e.message,e,t):Le(n)?new C(e.message,e,t):Re(n)?new He(e.message,e,t):ze(n)?new Ue(e.message,e,t):Be(n)?new We(e.message,e,t):Ve(n)?new Ge(e.message,e,t):new y(e.message,e,t)}var Ke=class extends v{cause;constructor(e,t){super(e),this.name=`WhatsAppNetworkError`,this.cause=t}},qe=class extends v{cause;constructor(e,t){super(e),this.name=`WhatsAppUnknownError`,this.cause=t}},T=class extends Error{constructor(e){super(e),this.name=`WhatsAppValidationError`}};function E(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 Je(e){return E(e)&&Me(e.error.code)}function Ye(e){return e instanceof b}function Xe(e){return e instanceof x}function Ze(e){return e instanceof S}function Qe(e){return e instanceof C}function $e(e){return e instanceof He}function et(e){return e instanceof Ue}function tt(e){return e instanceof We}function nt(e){return e instanceof Ge}function rt(e,t){if(E(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 it(e){if(!/^\+?\d{10,15}$/.test(e))throw new T(`Invalid phone number: "${e}". Expected E.164 format (e.g. +14155552671 or 14155552671).`)}function D(e,t){if(!e||e.length===0)throw new T(`"${t}" must contain at least one item.`)}var at=class extends r{endpoint=`block_users`;buildBlockUsersBody(e){return{messaging_product:n,block_users:e.map(e=>({user:e}))}}async block(e){D(e,`users`);let t=this.buildBlockUsersBody(e);return await this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async unblock(e){D(e,`users`);let t=this.buildBlockUsersBody(e);return await this.sendJson(`DELETE`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async listBlockedUsers(e){let t=`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`;if(e){let n=_(e);n&&(t+=n)}return await this.sendJson(`GET`,t,this.config.REQUEST_TIMEOUT)}},ot=class extends r{toQuery(e){return e?_({fields:Array.isArray(e.fields)?e.fields.join(`,`):e.fields,filtering:Array.isArray(e.filtering)?JSON.stringify(e.filtering):e.filtering,sort:e.sort,limit:e.limit,after:e.after,before:e.before}):``}fieldsQuery(e){let t=Array.isArray(e)?e.join(`,`):e;return t?_({fields:t}):``}async getConnectedClientBusinesses(e=this.config.M4D_APP_ID,t){return this.sendJson(`GET`,`${e}/connected_client_businesses${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async addPhoneNumbers(e,t){return this.sendJson(`POST`,`${e}/add_phone_numbers`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getBusinessPortfolio(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getPreVerifiedPhoneNumbers(e,t){return this.sendJson(`GET`,`${e}/preverified_numbers${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getClientWhatsAppBusinessAccounts(e,t){return this.sendJson(`GET`,`${e}/client_whatsapp_business_accounts${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async onboardPartnersToMMLite(e,t){return this.sendJson(`POST`,`${e}/onboard_partners_to_mm_lite`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getOwnedWhatsAppBusinessAccounts(e,t){return this.sendJson(`GET`,`${e}/owned_whatsapp_business_accounts${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async sharePreVerifiedPhoneNumber(e,t){return this.sendJson(`POST`,`${e}/share_preverified_numbers`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getCreditLines(e){return this.sendJson(`GET`,`${e}/extendedcredits`,this.config.REQUEST_TIMEOUT,null)}async getAssignedWhatsAppBusinessAccounts(e,t){return this.sendJson(`GET`,`${e}/assigned_whatsapp_business_accounts${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getWhatsAppAccountNumberDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getPreVerifiedPhoneNumberDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async deletePreVerifiedPhoneNumber(e){return this.sendJson(`DELETE`,e,this.config.REQUEST_TIMEOUT,null)}async getPreVerifiedPhoneNumberPartners(e,t){return this.sendJson(`GET`,`${e}/partners${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async requestPreVerifiedPhoneNumberCode(e,t){return this.sendJson(`POST`,`${e}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async verifyPreVerifiedPhoneNumberCode(e,t){return this.sendJson(`POST`,`${e}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},st=class extends r{endpoint=`calls`;async updateCallingSettings(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/settings`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getCallingSettings(e){let t=Array.isArray(e?.fields)?e?.fields.join(`,`):e?.fields,n=_({...t?{fields:t}:{},...e?.include_sip_credentials===void 0?{}:{include_sip_credentials:e.include_sip_credentials}});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/settings${n}`,this.config.REQUEST_TIMEOUT,null)}async getCallPermissions(e){let t=_({user_wa_id:e.userWaId});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/call_permissions${t}`,this.config.REQUEST_TIMEOUT,null)}async initiateCall(e){let t={messaging_product:n,to:e.to,action:`connect`,session:e.session};return e.biz_opaque_callback_data&&(t.biz_opaque_callback_data=e.biz_opaque_callback_data),e.recording&&(t.recording=e.recording),e.transcription&&(t.transcription=e.transcription),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async preAcceptCall(e){let t={messaging_product:n,call_id:e.call_id,action:`pre_accept`};return e.session&&(t.session=e.session),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async acceptCall(e){let t={messaging_product:n,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),e.recording&&(t.recording=e.recording),e.transcription&&(t.transcription=e.transcription),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async rejectCall(e){let t={messaging_product:n,call_id:e.call_id,action:`reject`};return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async terminateCall(e){let t={messaging_product:n,call_id:e.call_id,action:`terminate`};return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},ct=class extends r{endpoint=`whatsapp_commerce_settings`;async getCommerceSettings(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async updateCommerceSettings(e){let t=_(e);return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${t}`,this.config.REQUEST_TIMEOUT,null)}},lt=class extends r{endpoint=`contact_book`;async deleteEntry(e){if(!e?.bsuid)throw new T(`"bsuid" is required to delete a contact book entry.`);let t=_({messaging_product:n,bsuid:e.bsuid});return await this.sendJson(`DELETE`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${t}`,this.config.REQUEST_TIMEOUT)}},ut=class extends r{endpoint=`whatsapp_business_encryption`;async getEncryptionPublicKey(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async setEncryptionPublicKey(e){let t=new FormData;return t.append(`business_public_key`,e),this.sendFormData(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,t)}},dt=class extends r{appendFormValue(e,t,n){n!==void 0&&e.append(t,Array.isArray(n)?JSON.stringify(n):String(n))}async listFlows(e){return this.sendJson(`GET`,`/${e}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(e,t){let n=new FormData;return this.appendFormValue(n,`name`,t.name),this.appendFormValue(n,`categories`,t.categories),this.appendFormValue(n,`endpoint_uri`,t.endpoint_uri),this.appendFormValue(n,`clone_flow_id`,t.clone_flow_id),this.appendFormValue(n,`flow_json`,t.flow_json),this.appendFormValue(n,`publish`,t.publish),this.sendFormData(`POST`,`/${e}/flows`,this.config.REQUEST_TIMEOUT,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(`GET`,`/${e}${i}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(e,t=!1){let n=`preview.invalidate(${t})`;return this.getFlow(e,n)}async updateFlowMetadata(e,t){let n=new FormData;return this.appendFormValue(n,`name`,t.name),this.appendFormValue(n,`categories`,t.categories),this.appendFormValue(n,`endpoint_uri`,t.endpoint_uri),this.appendFormValue(n,`application_id`,t.application_id),this.sendFormData(`POST`,`/${e}`,this.config.REQUEST_TIMEOUT,n)}async deleteFlow(e){return this.sendJson(`DELETE`,`/${e}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(e){return this.sendJson(`GET`,`/${e}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(e,t){let n=new FormData,r;if(t.file instanceof Uint8Array)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(`POST`,`/${e}/assets`,this.config.REQUEST_TIMEOUT,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(`POST`,`/${e}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(e){return this.sendJson(`POST`,`/${e}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(e,t){let n=new FormData;return this.appendFormValue(n,`source_waba_id`,t.source_waba_id),this.appendFormValue(n,`source_flow_names`,t.source_flow_names),this.sendFormData(`POST`,`/${e}/migrate_flows`,this.config.REQUEST_TIMEOUT,n)}};let ft=function(e){return e.Draft=`DRAFT`,e.Published=`PUBLISHED`,e.Throttled=`THROTTLED`,e.Blocked=`BLOCKED`,e.Deprecated=`DEPRECATED`,e}({}),pt=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}({}),mt=function(e){return e.INIT=`INIT`,e.BACK=`BACK`,e.DATA_EXCHANGE=`data_exchange`,e}({}),ht=function(e){return e.Ping=`ping`,e.Change=`data_exchange`,e.Error=`error`,e.All=`*`,e}({});var gt=class extends r{async createGroup(e){let t={messaging_product:n,subject:e.subject};return e.description&&(t.description=e.description),e.join_approval_mode&&(t.join_approval_mode=e.join_approval_mode),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/groups`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteGroup(e){return this.sendJson(`DELETE`,e,this.config.REQUEST_TIMEOUT,null)}async getGroupInfo(e,t){let n=Array.isArray(t)?t.join(`,`):t,r=n?_({fields:n}):``;return this.sendJson(`GET`,`${e}${r}`,this.config.REQUEST_TIMEOUT,null)}async getActiveGroups(e){let t=e?_(e):``;return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/groups${t}`,this.config.REQUEST_TIMEOUT,null)}async getGroupInviteLink(e){return this.sendJson(`GET`,`${e}/invite_link`,this.config.REQUEST_TIMEOUT,null)}async createGroupInviteLink(e){let t={messaging_product:n};return this.sendJson(`POST`,`${e}/invite_link`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async resetGroupInviteLink(e){let t={messaging_product:n};return this.sendJson(`POST`,`${e}/invite_link`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteGroupInviteLink(e){let t={messaging_product:n};return this.sendJson(`DELETE`,`${e}/invite_link`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getJoinRequests(e){return this.sendJson(`GET`,`${e}/join_requests`,this.config.REQUEST_TIMEOUT,null)}async approveJoinRequests(e,t){let r={messaging_product:n,join_requests:t};return this.sendJson(`POST`,`${e}/join_requests`,this.config.REQUEST_TIMEOUT,JSON.stringify(r))}async rejectJoinRequests(e,t){let r={messaging_product:n,join_requests:t};return this.sendJson(`DELETE`,`${e}/join_requests`,this.config.REQUEST_TIMEOUT,JSON.stringify(r))}async addParticipants(e,t){D(t,`participants`);let r={messaging_product:n,participants:t.map(e=>({user:e}))};return this.sendJson(`POST`,`${e}/participants`,this.config.REQUEST_TIMEOUT,JSON.stringify(r))}async removeParticipants(e,t){D(t,`participants`);let r={messaging_product:n,participants:t.map(e=>({user:e}))};return this.sendJson(`DELETE`,`${e}/participants`,this.config.REQUEST_TIMEOUT,JSON.stringify(r))}async updateGroupSettings(e,t){if(t.profilePictureFile){let r=new FormData;if(r.append(`messaging_product`,n),t.subject&&r.append(`subject`,t.subject),t.description&&r.append(`description`,t.description),t.profilePictureFile instanceof Uint8Array){let e=new globalThis.Blob([new Uint8Array(t.profilePictureFile)],{type:`image/jpeg`});r.append(`file`,e)}else if(t.profilePictureFile instanceof Blob)r.append(`file`,t.profilePictureFile);else throw Error(`Invalid profile picture file type. Use a Buffer or Blob.`);return this.sendFormData(`POST`,e,this.config.REQUEST_TIMEOUT,r)}let r={messaging_product:n};return t.subject&&(r.subject=t.subject),t.description&&(r.description=t.description),this.sendJson(`POST`,e,this.config.REQUEST_TIMEOUT,JSON.stringify(r))}},_t=class extends r{endpoint=`marketing_messages`;async sendTemplateMessage(e){if(!e.to==!e.recipient)throw new T(`Provide exactly one of "to" (phone number) or "recipient" (BSUID).`);let t={messaging_product:n,recipient_type:`individual`,type:`template`,template:e.template};return e.to!==void 0&&(t.to=e.to),e.recipient!==void 0&&(t.recipient=e.recipient),e.message_activity_sharing!==void 0&&(t.message_activity_sharing=e.message_activity_sharing),e.product_policy!==void 0&&(t.product_policy=e.product_policy),e.bid_spec!==void 0&&(t.bid_spec=e.bid_spec),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},vt=class extends r{endpoint=`media`;async getMediaById(e){return this.sendJson(`GET`,`${e}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(e,t){let n=typeof t==`string`?{messagingProduct:t}:t??{},r=n.messagingProduct??`whatsapp`,i=n.type||(e instanceof Blob?e.type:``);if(!i)throw new T(`uploadMedia needs a MIME type: pass options.type (e.g. "image/jpeg") or a Blob/File with a type`);let a=await xt(e,n.type),o=new FormData;return a===e&&!n.type&&!n.filename?o.append(`file`,a):o.append(`file`,a,n.filename??yt(e)??`file`),o.append(`messaging_product`,r),o.append(`type`,i),this.sendFormData(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,o)}async deleteMedia(e){return this.sendJson(`DELETE`,`${e}`,this.config.REQUEST_TIMEOUT,null)}async downloadMedia(e){return(await this.sendRaw(`GET`,e,this.config.REQUEST_TIMEOUT)).blob()}};function yt(e){let t=e?.name;return typeof t==`string`&&t!==``?t:void 0}function bt(e){return typeof ReadableStream<`u`&&(e instanceof ReadableStream||typeof e?.getReader==`function`)}async function xt(e,t){if(e instanceof Blob)return t&&t!==e.type?e.slice(0,e.size,t):e;let n=t?{type:t}:void 0;if(e instanceof ArrayBuffer)return new Blob([e],n);if(e instanceof Uint8Array){let t=e.buffer instanceof ArrayBuffer?e:new Uint8Array(e);return new Blob([t],n)}if(bt(e)){let n=await new Response(e).blob();return t?n.slice(0,n.size,t):n}throw new T(`uploadMedia accepts a File, Blob, Uint8Array, ArrayBuffer or ReadableStream<Uint8Array>`)}var St=class extends r{resolveFields(e){return Array.isArray(e)?e.join(`,`):e}async getMessageHistory(e){let t=e?_({fields:this.resolveFields(e.fields),message_id:e.message_id,start_time:e.start_time,end_time:e.end_time,limit:e.limit,after:e.after,before:e.before}):``;return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/message_history${t}`,this.config.REQUEST_TIMEOUT,null)}async getMessageHistoryEvents(e,t){let n=t?_({fields:this.resolveFields(t.fields),status_filter:t.status_filter,limit:t.limit,after:t.after,before:t.before}):``;return this.sendJson(`GET`,`${e}/events${n}`,this.config.REQUEST_TIMEOUT,null)}},O=class extends r{commonMethod=`POST`;commonEndpoint=`messages`;bodyBuilder(e,t,r,i,a=`individual`,o){a===`individual`&&it(r);let s={messaging_product:n,recipient_type:a,to:r,type:e,[e]:t};return i&&(s.context={message_id:i}),o?.category&&(s.category=o.category),o?.directSendConfig&&(s.direct_send_config=o.directSendConfig),s}send(e){return this.sendJson(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/${this.commonEndpoint}`,this.config.REQUEST_TIMEOUT,e)}sendEncrypted(e){return this.sendJson(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/messages_encrypted`,this.config.REQUEST_TIMEOUT,e)}async audio(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`audio`,t,n,r,i,{category:a,directSendConfig:o})))}async contacts(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`contacts`,t,n,r,i,{category:a,directSendConfig:o})))}async document(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`document`,t,n,r,i,{category:a,directSendConfig:o})))}async image(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`image`,t,n,r,i,{category:a,directSendConfig:o})))}async interactive(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`interactive`,t,n,r,i,{category:a,directSendConfig:o})))}async location(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`location`,t,n,r,i,{category:a,directSendConfig:o})))}async sticker(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`sticker`,t,n,r,i,{category:a,directSendConfig:o})))}async template(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`template`,t,n,r,i,{category:a,directSendConfig:o})))}async text(e){let{body:t,to:n,replyMessageId:r,previewUrl:i,recipientType:a,category:o,directSendConfig:s}=e,c=typeof t==`string`?{body:t,preview_url:i??!0}:{...t,preview_url:i??t.preview_url??!0};return this.send(JSON.stringify(this.bodyBuilder(`text`,c,n,r,a,{category:o,directSendConfig:s})))}async video(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`video`,t,n,r,i,{category:a,directSendConfig:o})))}async status(e){let t={messaging_product:n,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:n,status:`read`,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 interactiveVoiceCall(e){return this.interactive({...e,category:e.category??`utility`})}async interactiveOtp(e){return this.interactive({...e,category:e.category??`authentication`})}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(`reaction`,t,e.to,void 0,e.recipientType)))}async encrypted(e){return this.sendEncrypted(JSON.stringify(e))}},Ct=class extends r{async listPaymentConfigurations(e){return this.sendJson(`GET`,`/${e}/payment_configurations`,this.config.REQUEST_TIMEOUT,null)}async getPaymentConfiguration(e,t){let n=encodeURIComponent(t);return this.sendJson(`GET`,`/${e}/payment_configuration/${n}`,this.config.REQUEST_TIMEOUT,null)}async createPaymentConfiguration(e,t){return this.sendJson(`POST`,`/${e}/payment_configuration`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async updatePaymentConfiguration(e,t,n){let r=encodeURIComponent(t);return this.sendJson(`POST`,`/${e}/payment_configuration/${r}`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async generatePaymentConfigurationOauthLink(e,t){return this.sendJson(`POST`,`/${e}/generate_payment_configuration_oauth_link`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deletePaymentConfiguration(e,t){return this.sendJson(`DELETE`,`/${e}/payment_configuration`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},wt=class extends r{endpoint=`phone_numbers`;async getPhoneNumberById(e){let t=Array.isArray(e)?e.join(`,`):e,n=t?_({fields:t}):``;return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}${n}`,this.config.REQUEST_TIMEOUT,null)}async getPhoneNumbers(e){let t=_({fields:Array.isArray(e?.fields)?e.fields.join(`,`):e?.fields,filtering:Array.isArray(e?.filtering)?JSON.stringify(e.filtering):e?.filtering,sort:e?.sort,limit:e?.limit,after:e?.after,before:e?.before});return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${t}`,this.config.REQUEST_TIMEOUT,null)}async createPhoneNumber(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`POST`,`${t}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async updatePhoneNumberStatus(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async requestVerificationCode(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async verifyCode(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getPhoneNumberSettings(e){let t=Array.isArray(e?.fields)?e.fields.join(`,`):e?.fields,n=_({...t?{fields:t}:{},...e?.include_sip_credentials===void 0?{}:{include_sip_credentials:e.include_sip_credentials}});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/settings${n}`,this.config.REQUEST_TIMEOUT,null)}async updatePhoneNumberSettings(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/settings`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async setConversationalAutomation(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/conversational_automation`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getConversationalAutomation(){let e=_({fields:`conversational_automation`});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}${e}`,this.config.REQUEST_TIMEOUT,null)}async getThroughput(){let e=_({fields:`throughput`});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}${e}`,this.config.REQUEST_TIMEOUT,null)}async getOfficialBusinessAccountStatus(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/official_business_account`,this.config.REQUEST_TIMEOUT,null)}async updateOfficialBusinessAccountStatus(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/official_business_account`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getBusinessComplianceInfo(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/business_compliance_info`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessComplianceInfo(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/business_compliance_info`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getUsername(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/username`,this.config.REQUEST_TIMEOUT,null)}async updateUsername(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/username`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteUsername(){return this.sendJson(`DELETE`,`${this.config.WA_PHONE_NUMBER_ID}/username`,this.config.REQUEST_TIMEOUT,null)}async getUsernameSuggestions(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/username_suggestions`,this.config.REQUEST_TIMEOUT,null)}};function k(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 Tt=class extends r{endpoint=`whatsapp_business_profile`;async getBusinessProfile(e){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${k(e)}`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessProfile(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async createUploadSession(e,t,n){let r=_({file_length:e,file_type:t,file_name:n});return this.sendJson(`POST`,`app/uploads/${r}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(e,t){return this.sendJson(`POST`,`${e}`,this.config.REQUEST_TIMEOUT,t)}async getUploadHandle(e){return this.sendJson(`GET`,`${e}`,this.config.REQUEST_TIMEOUT,null)}},Et=class extends r{endpoint=`message_qrdls`;async createQrCode(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getQrCodes(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async getQrCode(e){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}async updateQrCode(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteQrCode(e){return this.sendJson(`DELETE`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}},Dt=class extends r{async register(e,t){let r={messaging_product:n,pin:e,...t&&{data_localization_region:t}};return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/register`,this.config.REQUEST_TIMEOUT,JSON.stringify(r))}async deregister(){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/deregister`,this.config.REQUEST_TIMEOUT,null)}},Ot=class extends r{toQuery(e){return e?_({fields:Array.isArray(e.fields)?e.fields.join(`,`):e.fields,role:e.role,status:e.status,limit:e.limit,after:e.after,before:e.before}):``}fieldsQuery(e){let t=Array.isArray(e)?e.join(`,`):e;return t?_({fields:t}):``}async createWhatsAppBusinessSolution(e,t){return this.sendJson(`POST`,`${e}/whatsapp_business_solution`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getApplicationWhatsAppBusinessSolutions(e,t){return this.sendJson(`GET`,`${e}/whatsapp_business_solutions${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getSolutionAccessToken(e,t){return this.sendJson(`GET`,`${e}/access_token${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async acceptSolutionDeactivationRequest(e,t={}){return this.sendJson(`POST`,`${e}/accept_deactivation_request`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async acceptSolution(e,t={}){return this.sendJson(`POST`,`${e}/accept`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getSolutionDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async rejectSolutionDeactivationRequest(e,t={}){return this.sendJson(`POST`,`${e}/reject_deactivation_request`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async rejectSolutionRequest(e,t={}){return this.sendJson(`POST`,`${e}/reject`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async sendSolutionDeactivationRequest(e,t={}){return this.sendJson(`POST`,`${e}/send_deactivation_request`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getMigrationIntentDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async listWabaSolutions(e=this.config.WA_BUSINESS_ACCOUNT_ID,t){return this.sendJson(`GET`,`${e}/solutions${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async setSolutionMigrationIntent(e,t){return this.sendJson(`POST`,`${e}/set_solution_migration_intent`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};function A(e){let t={type:`HEADER`,format:e.format};return e.text&&(t.text=e.text),e.example&&(t.example=e.example),t}function j(e){let t={type:`BODY`,text:e.text};return e.example&&(t.example=e.example),t}function M(e){return{type:`FOOTER`,text:e.text}}function N(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 kt(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 At(e){let t=[];if(e.header&&t.push(A(e.header)),e.body&&t.push(j(e.body)),e.footer&&t.push(M(e.footer)),e.buttons&&t.push(...N(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:[kt(e.bodyParameters)]}:void 0}),e.buttons&&n.push(...N(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 jt(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:`AUTHENTICATION`,components:t}}function Mt(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:`AUTHENTICATION`,components:t}}function Nt(e){let t=[];return e.header&&t.push(A({...e.header,format:`TEXT`})),t.push(j(e.body)),e.footer&&t.push(M(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:`MARKETING`,components:t}}function Pt(e){let t=[];return e.header&&t.push(A({...e.header,format:`TEXT`})),t.push(j(e.body)),e.footer&&t.push(M(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`COPY_CODE`,example:e.coupon_code}]}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function Ft(e){let t=[];return t.push({type:`LIMITED_TIME_OFFER`,limited_time_offer:{expiration_time_ms:e.expiration_time_ms}}),e.header&&t.push(A({...e.header,format:`TEXT`})),t.push(j(e.body)),e.footer&&t.push(M(e.footer)),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function It(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(j(e.body)),e.buttons&&r.push(...N(e.buttons)),n.push({card_index:t,components:r})}),t.push({type:`CAROUSEL`,cards:n}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function Lt(e){let t=[];return e.header&&t.push(A({...e.header,format:`TEXT`})),t.push(j(e.body)),e.footer&&t.push(M(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:`MARKETING`,components:t}}function Rt(e){let t=[];e.header&&t.push(A({...e.header,format:`TEXT`})),t.push(j(e.body)),e.footer&&t.push(M(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:`MARKETING`,components:t}}function zt(e){let t=[];return e.header&&t.push(A({...e.header,format:`TEXT`})),t.push(j(e.body)),e.footer&&t.push(M(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`SPM`,action:{product_retailer_id:e.product_retailer_id}}]}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}var Bt=class extends r{endpoint=`message_templates`;async getTemplate(e){return this.sendJson(`GET`,`${e}`,this.config.REQUEST_TIMEOUT,null)}async updateTemplate(e,t){return this.sendJson(`POST`,`${e}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getTemplates(e){return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${_(e??{})}`,this.config.REQUEST_TIMEOUT,null)}async createTemplate(e){return this.sendJson(`POST`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteTemplate(e){return this.sendJson(`DELETE`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${_(e)}`,this.config.REQUEST_TIMEOUT,null)}};const Vt=2e3;var Ht=class extends r{endpoint=`thread_control`;async pass(e){return this.send(`pass`,e)}async release(e){return this.send(`release`,e)}async take(e){return this.send(`take`,e)}async send(e,t){let r=!!t?.to;if(r===!!t?.recipient)throw new T(`Exactly one of "to" or "recipient" is required for thread control.`);if(t.metadata&&t.metadata.length>Vt)throw new T(`"metadata" must be at most ${Vt} characters for thread control.`);if(e!==`pass`&&t.control_pass)throw new T(`"control_pass" is only supported for the pass action.`);let i={messaging_product:n,...r?{to:t.to}:{recipient:t.recipient},action:e,...t.metadata!==void 0&&{metadata:t.metadata},...t.control_pass&&{control_pass:t.control_pass}};return await this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}},Ut=class extends r{async setTwoStepVerificationCode(e){let t={pin:e};return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},Wt=class extends r{toQuery(e){return e?_({fields:Array.isArray(e.fields)?e.fields.join(`,`):e.fields,filtering:Array.isArray(e.filtering)?JSON.stringify(e.filtering):e.filtering,sort:e.sort,limit:e.limit,after:e.after,before:e.before}):``}fieldsQuery(e){let t=Array.isArray(e)?e.join(`,`):e;return t?_({fields:t}):``}async getWabaAccount(e){let t=k(e)?.replace(/,/g,`%2C`);return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}${t}`,this.config.REQUEST_TIMEOUT,null)}async updateWabaAccount(e){return this.sendJson(`POST`,`${this.config.WA_BUSINESS_ACCOUNT_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getWabaActivities(e){return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/activities${this.toQuery(e)}`,this.config.REQUEST_TIMEOUT,null)}async getAllWabaSubscriptions(){return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async updateWabaSubscription({override_callback_uri:e,verify_token:t}){let n={override_callback_uri:e,verify_token:t};return this.sendJson(`POST`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async unsubscribeFromWaba(){return this.sendJson(`DELETE`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async getAssignedUsers(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`GET`,`${t}/assigned_users${this.toQuery(e)}`,this.config.REQUEST_TIMEOUT,null)}async addAssignedUser(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){let n={user:e.user,tasks:e.tasks};return this.sendUrlEncodedForm(`POST`,`${t}/assigned_users`,this.config.REQUEST_TIMEOUT,n)}async removeAssignedUser(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendUrlEncodedForm(`DELETE`,`${t}/assigned_users`,this.config.REQUEST_TIMEOUT,{user:e.user})}async getInProgressOnBehalfRequests(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`GET`,`${t}/in_progress_onbehalf_request${this.toQuery(e)}`,this.config.REQUEST_TIMEOUT,null)}async getOBOMobilityIntent(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async createOBOMobilityIntent(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`POST`,`${t}/obo_mobility_intent`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async setOBOMobilityIntent(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`POST`,`${t}/set_obo_mobility_intent`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getWabaSchedules(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`GET`,`${t}/schedules${this.toQuery(e)}`,this.config.REQUEST_TIMEOUT,null)}async createWabaSchedule(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`POST`,`${t}/schedules`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getWhatsAppBusinessBotDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getWhatsAppBusinessProfileDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async updateWhatsAppBusinessProfile(e,t){return this.sendJson(`POST`,e,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};let Gt=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),Kt=function(e){return e.Blocked=`BLOCKED`,e.Limited=`LIMITED`,e.Available=`AVAILABLE`,e}({}),qt=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),Jt=function(e){return e.Verified=`verified`,e.PendingSubmission=`pending_submission`,e.Unverified=`unverified`,e.Rejected=`rejected`,e}({});var P=class{name;debugEnabled;constructor(e,t=!1){this.name=e,this.debugEnabled=t}formatData(e){return e.map(e=>typeof e==`object`&&e?Yt(e):e).join(` `)}log(...e){if(this.debugEnabled){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.debugEnabled){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn(t,`: `,this.formatData(e))}}info(...e){if(this.debugEnabled){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info(t,`: `,this.formatData(e))}}debug(...e){if(this.debugEnabled){let t=`[ ${Date.now()} ] - DEBUG`;this.name&&(t+=` - ${this.name}`),console.debug(t,`: `,this.formatData(e))}}};function Yt(e){if(e instanceof Error)return e.stack||`${e.name}: ${e.message}`;let t=new WeakSet;try{return JSON.stringify(e,(e,n)=>{if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(typeof n==`bigint`)return n.toString();if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return n},2)}catch{return String(e)}}const Xt=t;function F(){let e=globalThis.process;return typeof e==`object`&&e?e:void 0}function I(e){return F()?.env?.[e]}function L(){return I(`DEBUG`)===`true`}function R(){let e=F()?.getBuiltinModule;if(typeof e!=`function`)return F()?Xt:void 0;try{return e(`node:crypto`)}catch{return}}function z(e){let t=R();if(!t)throw Error(`${e} needs the node:crypto module, which is not available in this runtime. Use the async Web Crypto variant instead, or run on Node.js >= 20.12, Bun or Deno.`);return t}function B(){let e=globalThis.crypto?.subtle;if(!e)throw Error(`Web Crypto (globalThis.crypto.subtle) is not available in this runtime.`);return e}function Zt(){let e=globalThis;if(e.Bun?.version)return`Bun ${e.Bun.version}`;if(e.Deno?.version?.deno)return`Deno ${e.Deno.version.deno}`;if(typeof e.EdgeRuntime==`string`)return`Edge Runtime ${e.EdgeRuntime}`;if(e.navigator?.userAgent===`Cloudflare-Workers`)return`Cloudflare Workers`;let t=F()?.version;return t?`Node.js ${t}`:`unknown runtime`}const Qt=new TextEncoder,$t=new TextDecoder;function en(e){return Qt.encode(e)}function tn(e){return $t.decode(e)}function V(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function nn(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function rn(e){let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return t}function an(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}async function on(e,t){let n=B(),r=await n.importKey(`raw`,en(e),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),i=await n.sign(`HMAC`,r,en(t));return rn(new Uint8Array(i))}const sn=new P(`UTILS`,L()||!1),cn=e=>{if(!I(`CLOUD_API_ACCESS_TOKEN`)&&!e?.accessToken)throw sn.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`),Error(`Missing WhatsApp access token.`)},ln=e=>(cn(e),{M4D_APP_ID:e?.appId||I(`M4D_APP_ID`)||``,M4D_APP_SECRET:e?.appSecret||I(`M4D_APP_SECRET`)||``,WA_PHONE_NUMBER_ID:e?.phoneNumberId||(I(`WA_PHONE_NUMBER_ID`)?Number(I(`WA_PHONE_NUMBER_ID`)):0),WA_BUSINESS_ACCOUNT_ID:e?.businessAcctId||I(`WA_BUSINESS_ACCOUNT_ID`)||``,CLOUD_API_VERSION:e?.apiVersion||I(`CLOUD_API_VERSION`)||`v23.0`,CLOUD_API_ACCESS_TOKEN:e?.accessToken||I(`CLOUD_API_ACCESS_TOKEN`)||``,WEBHOOK_ENDPOINT:e?.webhookEndpoint||I(`WEBHOOK_ENDPOINT`)||``,WEBHOOK_VERIFICATION_TOKEN:e?.webhookVerificationToken||I(`WEBHOOK_VERIFICATION_TOKEN`)||``,LISTENER_PORT:e?.listenerPort||parseInt(I(`LISTENER_PORT`)||``,10)||3e3,MAX_RETRIES_AFTER_WAIT:e?.maxRetriesAfterWait||parseInt(I(`MAX_RETRIES_AFTER_WAIT`)||``,10)||30,REQUEST_TIMEOUT:e?.requestTimeout||parseInt(I(`REQUEST_TIMEOUT`)||``,10)||2e4,DEBUG:e?.debug||L(),FLOW_API_PRIVATE_PEM:e?.privatePem||I(`FLOW_API_PRIVATE_PEM`)||``,FLOW_API_PASSPHRASE:e?.passphrase||I(`FLOW_API_PASSPHRASE`)||``,retry:e?.retry,onRateLimitInfo:e?.onRateLimitInfo});function un(e){let t=[[`App ID`,e.M4D_APP_ID||`Not Set`],[`Phone Number ID`,e.WA_PHONE_NUMBER_ID?.toString()||`Not Set`],[`Business Account ID`,e.WA_BUSINESS_ACCOUNT_ID||`Not Set`],[`API Version`,e.CLOUD_API_VERSION||`Not Set`],[`Access Token`,e.CLOUD_API_ACCESS_TOKEN?`${e.CLOUD_API_ACCESS_TOKEN.substring(0,20)}...`:`Not Set`],[`Webhook Endpoint`,e.WEBHOOK_ENDPOINT||`Not Set`],[`Webhook Verification Token`,e.WEBHOOK_VERIFICATION_TOKEN?`${e.WEBHOOK_VERIFICATION_TOKEN.substring(0,10)}...`:`Not Set`],[`Listener Port`,e.LISTENER_PORT?.toString()||`Not Set`],[`Debug Mode`,e.DEBUG?`Enabled`:`Disabled`],[`Max Retries`,e.MAX_RETRIES_AFTER_WAIT?.toString()||`Not Set`],[`Request Timeout`,e.REQUEST_TIMEOUT?`${e.REQUEST_TIMEOUT}ms`:`Not Set`],[`Private PEM`,e.FLOW_API_PRIVATE_PEM?`Configured`:`Not Set`],[`Passphrase`,e.FLOW_API_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 H=new P(`FLOW_ENCRYPTION_UTILS`,L());function dn(){let e=R();if(!e||typeof e.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 H.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 H.error(`Browser environment detected:`,e),e}let t=globalThis.process?.versions?.node;if(t){let e=t.split(`.`).map(Number),n=e[0]??0,r=e[1]??0;if(n<10||n===10&&r<12){let e=Error(`Node.js version ${t} is not supported. Please upgrade to Node.js 10.12.0 or higher.`);throw H.error(`Node.js version check failed:`,e),e}}return e}function fn(e){H.info(`[generateEncryption] Starting key pair generation`);let t=dn(),n=e||I(`FLOW_API_PASSPHRASE`);if(!n||n.trim().length===0){let e=Error(`Passphrase is empty. Please provide a passphrase as parameter or set FLOW_API_PASSPHRASE environment variable.`);throw H.error(`[generateEncryption] Passphrase validation failed:`,e),e}n.length<8&&H.warn(`[generateEncryption] Passphrase is shorter than 8 characters. Consider using a longer passphrase for better security.`);try{H.info(`[generateEncryption] Generating 2048-bit RSA key pair`);let e=t.generateKeyPairSync(`rsa`,{modulusLength:2048,publicKeyEncoding:{type:`spki`,format:`pem`},privateKeyEncoding:{type:`pkcs8`,format:`pem`,cipher:`aes-256-cbc`,passphrase:n}});return H.info(`[generateEncryption] Key pair generated successfully`),{passphrase:n,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 H.error(`[generateEncryption] Key generation failed:`,n),n}}function pn(e,t){H.info(`[decryptFlowRequest] Starting Flow request decryption`);let n=z(`decryptFlowRequest`);if(!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 H.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 H.error(`[decryptFlowRequest] Configuration error:`,e),e}H.info(`[decryptFlowRequest] Configuration validated`);let{encrypted_aes_key:r,encrypted_flow_data:i,initial_vector:a}=e;if(!r||!i||!a)throw H.error(`[decryptFlowRequest] Missing required encryption properties in request body`),Error(`Missing required encryption properties`);H.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-----`);H.info(`[decryptFlowRequest] Loading private key`,{format:l?`PKCS#8`:c?`PKCS#1`:`Unknown`});let u;try{u=s?n.createPrivateKey({key:o,format:`pem`,passphrase:s}):n.createPrivateKey(o),H.info(`[decryptFlowRequest] Private key loaded successfully`)}catch(e){if(H.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{H.info(`[decryptFlowRequest] Attempting to convert PKCS#1 to PKCS#8 format`);let e=n.createPrivateKey({key:o,format:`pem`,passphrase:s}).export({type:`pkcs8`,format:`pem`,cipher:`aes-256-cbc`,passphrase:s});u=n.createPrivateKey({key:e,format:`pem`,passphrase:s}),H.info(`[decryptFlowRequest] Successfully converted PKCS#1 to PKCS#8 and loaded private key`)}catch(t){H.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+=`
1
+ import{t as e}from"./chunk.mjs";import*as t from"node:crypto";const n=`whatsapp`;var r=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)}async sendRaw(e,t,n){return(await this.client.sendRequest(e,t,n)).rawResponse()}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)}},i=e({AudioMediaTypesEnum:()=>ae,BusinessVerticalEnum:()=>pe,ButtonPositionEnum:()=>f,CategoryEnum:()=>a,ComponentTypesEnum:()=>m,ConversationTypesEnum:()=>g,CurrencyCodesEnum:()=>de,DataLocalizationRegionEnum:()=>fe,DocumentMediaTypesEnum:()=>ie,HttpMethodsEnum:()=>c,ImageMediaTypesEnum:()=>re,InteractiveTypesEnum:()=>d,LanguagesEnum:()=>ue,MessageCategoryEnum:()=>o,MessageTypesEnum:()=>l,ParametersTypesEnum:()=>u,ReferralSourceTypesEnum:()=>ce,RequestCodeMethodsEnum:()=>le,StatusEnum:()=>ee,StickerMediaTypesEnum:()=>ne,SubTypeEnum:()=>p,SystemChangeTypesEnum:()=>se,TemplateStatusEnum:()=>s,VideoMediaTypesEnum:()=>te,WabaConfigEnum:()=>h,WebhookTypesEnum:()=>oe});let a=function(e){return e.Authentication=`AUTHENTICATION`,e.Marketing=`MARKETING`,e.Utility=`UTILITY`,e}({}),o=function(e){return e.Authentication=`authentication`,e.Service=`service`,e.Utility=`utility`,e}({}),s=function(e){return e.Approved=`APPROVED`,e.Pending=`PENDING`,e.Rejected=`REJECTED`,e}({}),c=function(e){return e.Get=`GET`,e.Post=`POST`,e.Put=`PUT`,e.Delete=`DELETE`,e}({}),l=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.Edit=`edit`,e.Revoke=`revoke`,e.Unsupported=`unsupported`,e.Unknown=`unknown`,e.Statuses=`statuses`,e[`*`]=`*`,e}({}),u=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}({}),d=function(e){return e.Button=`button`,e.List=`list`,e.Product=`product`,e.ProductList=`product_list`,e.CatalogMessage=`catalog_message`,e.CallPermissionRequest=`call_permission_request`,e.CtaUrl=`cta_url`,e.Carousel=`carousel`,e.LocationRequest=`location_request_message`,e.AddressMessage=`address_message`,e.Flow=`flow`,e.VoiceCall=`voice_call`,e}({}),f=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}({}),p=function(e){return e.Catalog=`CATALOG`,e.CopyCode=`COPY_CODE`,e.Flow=`FLOW`,e.Mpm=`MPM`,e.OrderDetails=`ORDER_DETAILS`,e.PaymentRequest=`PAYMENT_REQUEST`,e.PhoneNumber=`PHONE_NUMBER`,e.QuickReply=`QUICK_REPLY`,e.Reminder=`REMINDER`,e.Url=`URL`,e.VoiceCall=`VOICE_CALL`,e}({}),m=function(e){return e.Header=`HEADER`,e.Body=`BODY`,e.Button=`BUTTON`,e.Footer=`FOOTER`,e}({}),h=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}({}),g=function(e){return e.BusinessInitiated=`business_initiated`,e.CustomerInitiated=`customer_initiated`,e.ReferralConversion=`referral_conversion`,e}({}),ee=function(e){return e.Delivered=`delivered`,e.Read=`read`,e.Sent=`sent`,e}({}),te=function(e){return e.Mp4=`video/mp4`,e.Threegp=`video/3gp`,e}({}),ne=function(e){return e.Webp=`image/webp`,e}({}),re=function(e){return e.Jpeg=`image/jpeg`,e.Png=`image/png`,e.Webp=`image/webp`,e}({}),ie=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}({}),ae=function(e){return e.Aac=`audio/aac`,e.Mp4=`audio/mp4`,e.Mpeg=`audio/mpeg`,e.Amr=`audio/amr`,e.Ogg=`audio/ogg`,e}({}),oe=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}({}),se=function(e){return e.CustomerChangedNumber=`customer_changed_number`,e.CustomerIdentityChanged=`customer_identity_changed`,e.UserChangedNumber=`user_changed_number`,e.UserIdentityChanged=`user_identity_changed`,e.UserChangedUserId=`user_changed_user_id`,e}({}),ce=function(e){return e.Ad=`ad`,e.Post=`post`,e}({}),le=function(e){return e.Sms=`SMS`,e.Voice=`VOICE`,e}({}),ue=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}({}),de=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}({}),fe=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}({}),pe=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 _=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(`&`)}`:``},me=[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,131061,131062,131063,131065,131070,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,138038,139e3,139001,139002,139003,139004,139100,139101,139102,139103,147005,200005,200006,200007,1752041,2388001,2388012,2388019,2388040,2388047,2388072,2388073,2388091,2388093,2388103,2388293,2388299,2494100,2494191,2593079,2593085,2593107,2593108],he=new Set(me),ge=[0,3,10,190],_e=[4,80007,130429,131048,131056],ve=[368,130497,131031],ye=[130472,131e3,131005,131008,131009,131016,131021,131026,131030,131042,131044,131045,131047,131050,131051,131052,131053,131056,131057,131048,131061,131062,131063,131065,131070,132e3,132001,132005,132007,132008,132012,132015,132016,132068,132069,135e3,137e3],be=[139e3,139001,139002,139003,139004],xe=[139100,139101,139102,139103],Se=[138e3,138001,138002,138003,138004,138005,138006,138007,138009,138012,138013,138018,138038,613],Ce=[131020,131041,131059,131201,131202,131203,131204,131207,131208,131209,131210,131211,131212,131213,131214,131215],we=new Set(ge),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);function Me(e){return Ne(e)?!0:he.has(e)}function Ne(e){return e>=200&&e<300}function Pe(e){return Ne(e)||we.has(e)}function Fe(e){return Te.has(e)}function Ie(e){return Ee.has(e)}function Le(e){return De.has(e)}function Re(e){return Oe.has(e)}function ze(e){return ke.has(e)}function Be(e){return Ae.has(e)}function Ve(e){return je.has(e)}var v=class extends Error{constructor(e){super(e),this.name=`WhatsAppError`}},y=class extends v{error;statusCode;rateLimit;constructor(e,t,n){super(e),this.name=`WhatsAppApiError`,this.error=t,this.statusCode=n}},b=class extends y{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppAuthorizationError`}},x=class extends y{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppThrottlingError`}},S=class extends y{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppIntegrityError`}},C=class extends y{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppSendMessageError`}},He=class extends y{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppFlowError`}},Ue=class extends y{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppBlockUserError`}},We=class extends y{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppCallingError`}},Ge=class extends y{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppGroupError`}};function Ke(e,t){let n=e.code;return Pe(n)?new b(e.message,e,t):Fe(n)?new x(e.message,e,t):Ie(n)?new S(e.message,e,t):Le(n)?new C(e.message,e,t):Re(n)?new He(e.message,e,t):ze(n)?new Ue(e.message,e,t):Be(n)?new We(e.message,e,t):Ve(n)?new Ge(e.message,e,t):new y(e.message,e,t)}var qe=class extends v{cause;constructor(e,t){super(e),this.name=`WhatsAppNetworkError`,this.cause=t}},Je=class extends v{cause;constructor(e,t){super(e),this.name=`WhatsAppUnknownError`,this.cause=t}},w=class extends Error{constructor(e){super(e),this.name=`WhatsAppValidationError`}};function T(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 Ye(e){return T(e)&&Me(e.error.code)}function Xe(e){return e instanceof b}function Ze(e){return e instanceof x}function Qe(e){return e instanceof S}function $e(e){return e instanceof C}function et(e){return e instanceof He}function tt(e){return e instanceof Ue}function nt(e){return e instanceof We}function rt(e){return e instanceof Ge}function it(e,t){if(T(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 at(e){if(!/^\+?\d{10,15}$/.test(e))throw new w(`Invalid phone number: "${e}". Expected E.164 format (e.g. +14155552671 or 14155552671).`)}function E(e,t){if(!e||e.length===0)throw new w(`"${t}" must contain at least one item.`)}var ot=class extends r{endpoint=`block_users`;buildBlockUsersBody(e){return{messaging_product:n,block_users:e.map(e=>({user:e}))}}async block(e){E(e,`users`);let t=this.buildBlockUsersBody(e);return await this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async unblock(e){E(e,`users`);let t=this.buildBlockUsersBody(e);return await this.sendJson(`DELETE`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async listBlockedUsers(e){let t=`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`;if(e){let n=_(e);n&&(t+=n)}return await this.sendJson(`GET`,t,this.config.REQUEST_TIMEOUT)}},st=class extends r{toQuery(e){return e?_({fields:Array.isArray(e.fields)?e.fields.join(`,`):e.fields,filtering:Array.isArray(e.filtering)?JSON.stringify(e.filtering):e.filtering,sort:e.sort,limit:e.limit,after:e.after,before:e.before}):``}fieldsQuery(e){let t=Array.isArray(e)?e.join(`,`):e;return t?_({fields:t}):``}async getConnectedClientBusinesses(e=this.config.M4D_APP_ID,t){return this.sendJson(`GET`,`${e}/connected_client_businesses${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async addPhoneNumbers(e,t){return this.sendJson(`POST`,`${e}/add_phone_numbers`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getBusinessPortfolio(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getPreVerifiedPhoneNumbers(e,t){return this.sendJson(`GET`,`${e}/preverified_numbers${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getClientWhatsAppBusinessAccounts(e,t){return this.sendJson(`GET`,`${e}/client_whatsapp_business_accounts${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async onboardPartnersToMMLite(e,t){return this.sendJson(`POST`,`${e}/onboard_partners_to_mm_lite`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getOwnedWhatsAppBusinessAccounts(e,t){return this.sendJson(`GET`,`${e}/owned_whatsapp_business_accounts${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async sharePreVerifiedPhoneNumber(e,t){return this.sendJson(`POST`,`${e}/share_preverified_numbers`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getCreditLines(e){return this.sendJson(`GET`,`${e}/extendedcredits`,this.config.REQUEST_TIMEOUT,null)}async getAssignedWhatsAppBusinessAccounts(e,t){return this.sendJson(`GET`,`${e}/assigned_whatsapp_business_accounts${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getWhatsAppAccountNumberDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getPreVerifiedPhoneNumberDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async deletePreVerifiedPhoneNumber(e){return this.sendJson(`DELETE`,e,this.config.REQUEST_TIMEOUT,null)}async getPreVerifiedPhoneNumberPartners(e,t){return this.sendJson(`GET`,`${e}/partners${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async requestPreVerifiedPhoneNumberCode(e,t){return this.sendJson(`POST`,`${e}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async verifyPreVerifiedPhoneNumberCode(e,t){return this.sendJson(`POST`,`${e}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},ct=class extends r{endpoint=`calls`;async updateCallingSettings(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/settings`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getCallingSettings(e){let t=Array.isArray(e?.fields)?e?.fields.join(`,`):e?.fields,n=_({...t?{fields:t}:{},...e?.include_sip_credentials===void 0?{}:{include_sip_credentials:e.include_sip_credentials}});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/settings${n}`,this.config.REQUEST_TIMEOUT,null)}async getCallPermissions(e){let t=_({user_wa_id:e.userWaId});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/call_permissions${t}`,this.config.REQUEST_TIMEOUT,null)}async initiateCall(e){let t={messaging_product:n,to:e.to,action:`connect`,session:e.session};return e.messaging_account_id&&(t.messaging_account_id=e.messaging_account_id),e.biz_opaque_callback_data&&(t.biz_opaque_callback_data=e.biz_opaque_callback_data),e.recording&&(t.recording=e.recording),e.transcription&&(t.transcription=e.transcription),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async preAcceptCall(e){let t={messaging_product:n,call_id:e.call_id,action:`pre_accept`};return e.session&&(t.session=e.session),e.messaging_account_id&&(t.messaging_account_id=e.messaging_account_id),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async acceptCall(e){let t={messaging_product:n,call_id:e.call_id,action:`accept`};return e.session&&(t.session=e.session),e.messaging_account_id&&(t.messaging_account_id=e.messaging_account_id),e.biz_opaque_callback_data&&(t.biz_opaque_callback_data=e.biz_opaque_callback_data),e.recording&&(t.recording=e.recording),e.transcription&&(t.transcription=e.transcription),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async rejectCall(e){let t={messaging_product:n,call_id:e.call_id,action:`reject`,...e.messaging_account_id?{messaging_account_id:e.messaging_account_id}:{}};return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async terminateCall(e){let t={messaging_product:n,call_id:e.call_id,action:`terminate`,...e.messaging_account_id?{messaging_account_id:e.messaging_account_id}:{}};return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},lt=class extends r{endpoint=`whatsapp_commerce_settings`;async getCommerceSettings(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async updateCommerceSettings(e){let t=_(e);return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${t}`,this.config.REQUEST_TIMEOUT,null)}},ut=class extends r{endpoint=`contact_book`;async deleteEntry(e){if(!e?.bsuid)throw new w(`"bsuid" is required to delete a contact book entry.`);let t=_({messaging_product:n,bsuid:e.bsuid});return await this.sendJson(`DELETE`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${t}`,this.config.REQUEST_TIMEOUT)}},dt=class extends r{endpoint=`whatsapp_business_encryption`;async getEncryptionPublicKey(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async setEncryptionPublicKey(e){let t=new FormData;return t.append(`business_public_key`,e),this.sendFormData(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,t)}},ft=class extends r{appendFormValue(e,t,n){n!==void 0&&e.append(t,Array.isArray(n)?JSON.stringify(n):String(n))}async listFlows(e){return this.sendJson(`GET`,`/${e}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(e,t){let n=new FormData;return this.appendFormValue(n,`name`,t.name),this.appendFormValue(n,`categories`,t.categories),this.appendFormValue(n,`endpoint_uri`,t.endpoint_uri),this.appendFormValue(n,`clone_flow_id`,t.clone_flow_id),this.appendFormValue(n,`flow_json`,t.flow_json),this.appendFormValue(n,`publish`,t.publish),this.sendFormData(`POST`,`/${e}/flows`,this.config.REQUEST_TIMEOUT,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(`GET`,`/${e}${i}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(e,t=!1){let n=`preview.invalidate(${t})`;return this.getFlow(e,n)}async updateFlowMetadata(e,t){let n=new FormData;return this.appendFormValue(n,`name`,t.name),this.appendFormValue(n,`categories`,t.categories),this.appendFormValue(n,`endpoint_uri`,t.endpoint_uri),this.appendFormValue(n,`application_id`,t.application_id),this.sendFormData(`POST`,`/${e}`,this.config.REQUEST_TIMEOUT,n)}async deleteFlow(e){return this.sendJson(`DELETE`,`/${e}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(e){return this.sendJson(`GET`,`/${e}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(e,t){let n=new FormData,r;if(t.file instanceof Uint8Array)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(`POST`,`/${e}/assets`,this.config.REQUEST_TIMEOUT,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(`POST`,`/${e}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(e){return this.sendJson(`POST`,`/${e}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(e,t){let n=new FormData;return this.appendFormValue(n,`source_waba_id`,t.source_waba_id),this.appendFormValue(n,`source_flow_names`,t.source_flow_names),this.sendFormData(`POST`,`/${e}/migrate_flows`,this.config.REQUEST_TIMEOUT,n)}};let pt=function(e){return e.Draft=`DRAFT`,e.Published=`PUBLISHED`,e.Throttled=`THROTTLED`,e.Blocked=`BLOCKED`,e.Deprecated=`DEPRECATED`,e}({}),mt=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}({}),ht=function(e){return e.INIT=`INIT`,e.BACK=`BACK`,e.DATA_EXCHANGE=`data_exchange`,e}({}),gt=function(e){return e.Ping=`ping`,e.Change=`data_exchange`,e.Error=`error`,e.All=`*`,e}({});var _t=class extends r{async createGroup(e){let t={messaging_product:n,subject:e.subject};return e.description&&(t.description=e.description),e.join_approval_mode&&(t.join_approval_mode=e.join_approval_mode),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/groups`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteGroup(e){return this.sendJson(`DELETE`,e,this.config.REQUEST_TIMEOUT,null)}async getGroupInfo(e,t){let n=Array.isArray(t)?t.join(`,`):t,r=n?_({fields:n}):``;return this.sendJson(`GET`,`${e}${r}`,this.config.REQUEST_TIMEOUT,null)}async getActiveGroups(e){let t=e?_(e):``;return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/groups${t}`,this.config.REQUEST_TIMEOUT,null)}async getGroupInviteLink(e){return this.sendJson(`GET`,`${e}/invite_link`,this.config.REQUEST_TIMEOUT,null)}async createGroupInviteLink(e){let t={messaging_product:n};return this.sendJson(`POST`,`${e}/invite_link`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async resetGroupInviteLink(e){let t={messaging_product:n};return this.sendJson(`POST`,`${e}/invite_link`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteGroupInviteLink(e){let t={messaging_product:n};return this.sendJson(`DELETE`,`${e}/invite_link`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getJoinRequests(e){return this.sendJson(`GET`,`${e}/join_requests`,this.config.REQUEST_TIMEOUT,null)}async approveJoinRequests(e,t){let r={messaging_product:n,join_requests:t};return this.sendJson(`POST`,`${e}/join_requests`,this.config.REQUEST_TIMEOUT,JSON.stringify(r))}async rejectJoinRequests(e,t){let r={messaging_product:n,join_requests:t};return this.sendJson(`DELETE`,`${e}/join_requests`,this.config.REQUEST_TIMEOUT,JSON.stringify(r))}async addParticipants(e,t){E(t,`participants`);let r={messaging_product:n,participants:t.map(e=>({user:e}))};return this.sendJson(`POST`,`${e}/participants`,this.config.REQUEST_TIMEOUT,JSON.stringify(r))}async removeParticipants(e,t){E(t,`participants`);let r={messaging_product:n,participants:t.map(e=>({user:e}))};return this.sendJson(`DELETE`,`${e}/participants`,this.config.REQUEST_TIMEOUT,JSON.stringify(r))}async updateGroupSettings(e,t){if(t.profilePictureFile){let r=new FormData;if(r.append(`messaging_product`,n),t.subject&&r.append(`subject`,t.subject),t.description&&r.append(`description`,t.description),t.profilePictureFile instanceof Uint8Array){let e=new globalThis.Blob([new Uint8Array(t.profilePictureFile)],{type:`image/jpeg`});r.append(`file`,e)}else if(t.profilePictureFile instanceof Blob)r.append(`file`,t.profilePictureFile);else throw Error(`Invalid profile picture file type. Use a Buffer or Blob.`);return this.sendFormData(`POST`,e,this.config.REQUEST_TIMEOUT,r)}let r={messaging_product:n};return t.subject&&(r.subject=t.subject),t.description&&(r.description=t.description),this.sendJson(`POST`,e,this.config.REQUEST_TIMEOUT,JSON.stringify(r))}},vt=class extends r{endpoint=`marketing_messages`;async sendTemplateMessage(e){if(!e.to==!e.recipient)throw new w(`Provide exactly one of "to" (phone number) or "recipient" (BSUID).`);let t={messaging_product:n,recipient_type:`individual`,type:`template`,template:e.template};return e.to!==void 0&&(t.to=e.to),e.recipient!==void 0&&(t.recipient=e.recipient),e.message_activity_sharing!==void 0&&(t.message_activity_sharing=e.message_activity_sharing),e.product_policy!==void 0&&(t.product_policy=e.product_policy),e.bid_spec!==void 0&&(t.bid_spec=e.bid_spec),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},yt=class extends r{endpoint=`media`;async getMediaById(e){return this.sendJson(`GET`,`${e}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(e,t){let n=typeof t==`string`?{messagingProduct:t}:t??{},r=n.messagingProduct??`whatsapp`,i=n.type||(e instanceof Blob?e.type:``);if(!i)throw new w(`uploadMedia needs a MIME type: pass options.type (e.g. "image/jpeg") or a Blob/File with a type`);let a=await St(e,n.type),o=new FormData;return a===e&&!n.type&&!n.filename?o.append(`file`,a):o.append(`file`,a,n.filename??bt(e)??`file`),o.append(`messaging_product`,r),o.append(`type`,i),this.sendFormData(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,o)}async deleteMedia(e){return this.sendJson(`DELETE`,`${e}`,this.config.REQUEST_TIMEOUT,null)}async downloadMedia(e){return(await this.sendRaw(`GET`,e,this.config.REQUEST_TIMEOUT)).blob()}};function bt(e){let t=e?.name;return typeof t==`string`&&t!==``?t:void 0}function xt(e){return typeof ReadableStream<`u`&&(e instanceof ReadableStream||typeof e?.getReader==`function`)}async function St(e,t){if(e instanceof Blob)return t&&t!==e.type?e.slice(0,e.size,t):e;let n=t?{type:t}:void 0;if(e instanceof ArrayBuffer)return new Blob([e],n);if(e instanceof Uint8Array){let t=e.buffer instanceof ArrayBuffer?e:new Uint8Array(e);return new Blob([t],n)}if(xt(e)){let n=await new Response(e).blob();return t?n.slice(0,n.size,t):n}throw new w(`uploadMedia accepts a File, Blob, Uint8Array, ArrayBuffer or ReadableStream<Uint8Array>`)}var Ct=class extends r{resolveFields(e){return Array.isArray(e)?e.join(`,`):e}async getMessageHistory(e){let t=e?_({fields:this.resolveFields(e.fields),message_id:e.message_id,start_time:e.start_time,end_time:e.end_time,limit:e.limit,after:e.after,before:e.before}):``;return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/message_history${t}`,this.config.REQUEST_TIMEOUT,null)}async getMessageHistoryEvents(e,t){let n=t?_({fields:this.resolveFields(t.fields),status_filter:t.status_filter,limit:t.limit,after:t.after,before:t.before}):``;return this.sendJson(`GET`,`${e}/events${n}`,this.config.REQUEST_TIMEOUT,null)}},D=class extends r{commonMethod=`POST`;commonEndpoint=`messages`;bodyBuilder(e,t,r,i,a=`individual`,o){a===`individual`&&at(r);let s={messaging_product:n,recipient_type:a,to:r,type:e,[e]:t};return i&&(s.context={message_id:i}),o?.category&&(s.category=o.category),o?.directSendConfig&&(s.direct_send_config=o.directSendConfig),s}send(e){return this.sendJson(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/${this.commonEndpoint}`,this.config.REQUEST_TIMEOUT,e)}sendEncrypted(e){return this.sendJson(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/messages_encrypted`,this.config.REQUEST_TIMEOUT,e)}async audio(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`audio`,t,n,r,i,{category:a,directSendConfig:o})))}async contacts(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`contacts`,t,n,r,i,{category:a,directSendConfig:o})))}async document(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`document`,t,n,r,i,{category:a,directSendConfig:o})))}async image(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`image`,t,n,r,i,{category:a,directSendConfig:o})))}async interactive(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`interactive`,t,n,r,i,{category:a,directSendConfig:o})))}async location(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`location`,t,n,r,i,{category:a,directSendConfig:o})))}async sticker(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`sticker`,t,n,r,i,{category:a,directSendConfig:o})))}async template(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`template`,t,n,r,i,{category:a,directSendConfig:o})))}async text(e){let{body:t,to:n,replyMessageId:r,previewUrl:i,recipientType:a,category:o,directSendConfig:s}=e,c=typeof t==`string`?{body:t,preview_url:i??!0}:{...t,preview_url:i??t.preview_url??!0};return this.send(JSON.stringify(this.bodyBuilder(`text`,c,n,r,a,{category:o,directSendConfig:s})))}async video(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`video`,t,n,r,i,{category:a,directSendConfig:o})))}async status(e){let t={messaging_product:n,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:n,status:`read`,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 interactiveVoiceCall(e){return this.interactive({...e,category:e.category??`utility`})}async interactiveOtp(e){return this.interactive({...e,category:e.category??`authentication`})}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(`reaction`,t,e.to,void 0,e.recipientType)))}async encrypted(e){return this.sendEncrypted(JSON.stringify(e))}},wt=class extends r{async listPaymentConfigurations(e){return this.sendJson(`GET`,`/${e}/payment_configurations`,this.config.REQUEST_TIMEOUT,null)}async getPaymentConfiguration(e,t){let n=encodeURIComponent(t);return this.sendJson(`GET`,`/${e}/payment_configuration/${n}`,this.config.REQUEST_TIMEOUT,null)}async createPaymentConfiguration(e,t){return this.sendJson(`POST`,`/${e}/payment_configuration`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async updatePaymentConfiguration(e,t,n){let r=encodeURIComponent(t);return this.sendJson(`POST`,`/${e}/payment_configuration/${r}`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async generatePaymentConfigurationOauthLink(e,t){return this.sendJson(`POST`,`/${e}/generate_payment_configuration_oauth_link`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deletePaymentConfiguration(e,t){return this.sendJson(`DELETE`,`/${e}/payment_configuration`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},Tt=class extends r{endpoint=`phone_numbers`;async getPhoneNumberById(e){let t=Array.isArray(e)?e.join(`,`):e,n=t?_({fields:t}):``;return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}${n}`,this.config.REQUEST_TIMEOUT,null)}async getPhoneNumbers(e){let t=_({fields:Array.isArray(e?.fields)?e.fields.join(`,`):e?.fields,filtering:Array.isArray(e?.filtering)?JSON.stringify(e.filtering):e?.filtering,sort:e?.sort,limit:e?.limit,after:e?.after,before:e?.before});return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${t}`,this.config.REQUEST_TIMEOUT,null)}async createPhoneNumber(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`POST`,`${t}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async updatePhoneNumberStatus(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async requestVerificationCode(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async verifyCode(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getPhoneNumberSettings(e){let t=Array.isArray(e?.fields)?e.fields.join(`,`):e?.fields,n=_({...t?{fields:t}:{},...e?.include_sip_credentials===void 0?{}:{include_sip_credentials:e.include_sip_credentials}});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/settings${n}`,this.config.REQUEST_TIMEOUT,null)}async updatePhoneNumberSettings(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/settings`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async setConversationalAutomation(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/conversational_automation`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getConversationalAutomation(){let e=_({fields:`conversational_automation`});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}${e}`,this.config.REQUEST_TIMEOUT,null)}async getThroughput(){let e=_({fields:`throughput`});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}${e}`,this.config.REQUEST_TIMEOUT,null)}async getOfficialBusinessAccountStatus(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/official_business_account`,this.config.REQUEST_TIMEOUT,null)}async updateOfficialBusinessAccountStatus(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/official_business_account`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getBusinessComplianceInfo(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/business_compliance_info`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessComplianceInfo(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/business_compliance_info`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getUsername(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/username`,this.config.REQUEST_TIMEOUT,null)}async updateUsername(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/username`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteUsername(){return this.sendJson(`DELETE`,`${this.config.WA_PHONE_NUMBER_ID}/username`,this.config.REQUEST_TIMEOUT,null)}async getUsernameSuggestions(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/username_suggestions`,this.config.REQUEST_TIMEOUT,null)}};function O(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 Et=class extends r{endpoint=`whatsapp_business_profile`;async getBusinessProfile(e){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${O(e)}`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessProfile(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async createUploadSession(e,t,n){let r=_({file_length:e,file_type:t,file_name:n});return this.sendJson(`POST`,`app/uploads/${r}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(e,t){return this.sendJson(`POST`,`${e}`,this.config.REQUEST_TIMEOUT,t)}async getUploadHandle(e){return this.sendJson(`GET`,`${e}`,this.config.REQUEST_TIMEOUT,null)}},Dt=class extends r{endpoint=`message_qrdls`;async createQrCode(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getQrCodes(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async getQrCode(e){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}async updateQrCode(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteQrCode(e){return this.sendJson(`DELETE`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}},Ot=class extends r{async register(e,t){let r={messaging_product:n,pin:e,...t&&{data_localization_region:t}};return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/register`,this.config.REQUEST_TIMEOUT,JSON.stringify(r))}async deregister(){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/deregister`,this.config.REQUEST_TIMEOUT,null)}},kt=class extends r{toQuery(e){return e?_({fields:Array.isArray(e.fields)?e.fields.join(`,`):e.fields,role:e.role,status:e.status,limit:e.limit,after:e.after,before:e.before}):``}fieldsQuery(e){let t=Array.isArray(e)?e.join(`,`):e;return t?_({fields:t}):``}async createWhatsAppBusinessSolution(e,t){return this.sendJson(`POST`,`${e}/whatsapp_business_solution`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getApplicationWhatsAppBusinessSolutions(e,t){return this.sendJson(`GET`,`${e}/whatsapp_business_solutions${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getSolutionAccessToken(e,t){return this.sendJson(`GET`,`${e}/access_token${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async acceptSolutionDeactivationRequest(e,t={}){return this.sendJson(`POST`,`${e}/accept_deactivation_request`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async acceptSolution(e,t={}){return this.sendJson(`POST`,`${e}/accept`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getSolutionDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async rejectSolutionDeactivationRequest(e,t={}){return this.sendJson(`POST`,`${e}/reject_deactivation_request`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async rejectSolutionRequest(e,t={}){return this.sendJson(`POST`,`${e}/reject`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async sendSolutionDeactivationRequest(e,t={}){return this.sendJson(`POST`,`${e}/send_deactivation_request`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getMigrationIntentDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async listWabaSolutions(e=this.config.WA_BUSINESS_ACCOUNT_ID,t){return this.sendJson(`GET`,`${e}/solutions${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async setSolutionMigrationIntent(e,t){return this.sendJson(`POST`,`${e}/set_solution_migration_intent`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};function k(e){let t={type:`HEADER`,format:e.format};return e.text&&(t.text=e.text),e.example&&(t.example=e.example),t}function A(e){let t={type:`BODY`,text:e.text};return e.example&&(t.example=e.example),t}function j(e){return{type:`FOOTER`,text:e.text}}function M(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 At(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 jt(e){let t=[];if(e.header&&t.push(k(e.header)),e.body&&t.push(A(e.body)),e.footer&&t.push(j(e.footer)),e.buttons&&t.push(...M(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:[At(e.bodyParameters)]}:void 0}),e.buttons&&n.push(...M(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 Mt(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:`AUTHENTICATION`,components:t}}function Nt(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:`AUTHENTICATION`,components:t}}function Pt(e){let t=[];return e.header&&t.push(k({...e.header,format:`TEXT`})),t.push(A(e.body)),e.footer&&t.push(j(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:`MARKETING`,components:t}}function Ft(e){let t=[];return e.header&&t.push(k({...e.header,format:`TEXT`})),t.push(A(e.body)),e.footer&&t.push(j(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`COPY_CODE`,example:e.coupon_code}]}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function It(e){let t=[];return t.push({type:`LIMITED_TIME_OFFER`,limited_time_offer:{expiration_time_ms:e.expiration_time_ms}}),e.header&&t.push(k({...e.header,format:`TEXT`})),t.push(A(e.body)),e.footer&&t.push(j(e.footer)),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function Lt(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(A(e.body)),e.buttons&&r.push(...M(e.buttons)),n.push({card_index:t,components:r})}),t.push({type:`CAROUSEL`,cards:n}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function Rt(e){let t=[];return e.header&&t.push(k({...e.header,format:`TEXT`})),t.push(A(e.body)),e.footer&&t.push(j(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:`MARKETING`,components:t}}function zt(e){let t=[];e.header&&t.push(k({...e.header,format:`TEXT`})),t.push(A(e.body)),e.footer&&t.push(j(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:`MARKETING`,components:t}}function Bt(e){let t=[];return e.header&&t.push(k({...e.header,format:`TEXT`})),t.push(A(e.body)),e.footer&&t.push(j(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`SPM`,action:{product_retailer_id:e.product_retailer_id}}]}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}var Vt=class extends r{endpoint=`message_templates`;async getTemplate(e){return this.sendJson(`GET`,`${e}`,this.config.REQUEST_TIMEOUT,null)}async updateTemplate(e,t){return this.sendJson(`POST`,`${e}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getTemplates(e){return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${_(e??{})}`,this.config.REQUEST_TIMEOUT,null)}async createTemplate(e){return this.sendJson(`POST`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteTemplate(e){return this.sendJson(`DELETE`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${_(e)}`,this.config.REQUEST_TIMEOUT,null)}};const Ht=2e3;var Ut=class extends r{endpoint=`thread_control`;async pass(e){return this.send(`pass`,e)}async release(e){return this.send(`release`,e)}async take(e){return this.send(`take`,e)}async send(e,t){let r=!!t?.to;if(r===!!t?.recipient)throw new w(`Exactly one of "to" or "recipient" is required for thread control.`);if(t.metadata&&t.metadata.length>Ht)throw new w(`"metadata" must be at most ${Ht} characters for thread control.`);if(e!==`pass`&&t.control_pass)throw new w(`"control_pass" is only supported for the pass action.`);let i={messaging_product:n,...r?{to:t.to}:{recipient:t.recipient},action:e,...t.metadata!==void 0&&{metadata:t.metadata},...t.control_pass&&{control_pass:t.control_pass}};return await this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}},Wt=class extends r{async setTwoStepVerificationCode(e){let t={pin:e};return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},Gt=class extends r{toQuery(e){return e?_({fields:Array.isArray(e.fields)?e.fields.join(`,`):e.fields,filtering:Array.isArray(e.filtering)?JSON.stringify(e.filtering):e.filtering,sort:e.sort,limit:e.limit,after:e.after,before:e.before}):``}fieldsQuery(e){let t=Array.isArray(e)?e.join(`,`):e;return t?_({fields:t}):``}async getWabaAccount(e){let t=O(e)?.replace(/,/g,`%2C`);return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}${t}`,this.config.REQUEST_TIMEOUT,null)}async updateWabaAccount(e){return this.sendJson(`POST`,`${this.config.WA_BUSINESS_ACCOUNT_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getWabaActivities(e){return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/activities${this.toQuery(e)}`,this.config.REQUEST_TIMEOUT,null)}async getAllWabaSubscriptions(){return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async updateWabaSubscription({override_callback_uri:e,verify_token:t}){let n={override_callback_uri:e,verify_token:t};return this.sendJson(`POST`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async unsubscribeFromWaba(){return this.sendJson(`DELETE`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async getAssignedUsers(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`GET`,`${t}/assigned_users${this.toQuery(e)}`,this.config.REQUEST_TIMEOUT,null)}async addAssignedUser(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){let n={user:e.user,tasks:e.tasks};return this.sendUrlEncodedForm(`POST`,`${t}/assigned_users`,this.config.REQUEST_TIMEOUT,n)}async removeAssignedUser(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendUrlEncodedForm(`DELETE`,`${t}/assigned_users`,this.config.REQUEST_TIMEOUT,{user:e.user})}async getInProgressOnBehalfRequests(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`GET`,`${t}/in_progress_onbehalf_request${this.toQuery(e)}`,this.config.REQUEST_TIMEOUT,null)}async getOBOMobilityIntent(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async createOBOMobilityIntent(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`POST`,`${t}/obo_mobility_intent`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async setOBOMobilityIntent(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`POST`,`${t}/set_obo_mobility_intent`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getWabaSchedules(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`GET`,`${t}/schedules${this.toQuery(e)}`,this.config.REQUEST_TIMEOUT,null)}async createWabaSchedule(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`POST`,`${t}/schedules`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getWhatsAppBusinessBotDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getWhatsAppBusinessProfileDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async updateWhatsAppBusinessProfile(e,t){return this.sendJson(`POST`,e,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};let Kt=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),qt=function(e){return e.Blocked=`BLOCKED`,e.Limited=`LIMITED`,e.Available=`AVAILABLE`,e}({}),Jt=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),Yt=function(e){return e.Verified=`verified`,e.PendingSubmission=`pending_submission`,e.Unverified=`unverified`,e.Rejected=`rejected`,e}({});var N=class{name;debugEnabled;constructor(e,t=!1){this.name=e,this.debugEnabled=t}formatData(e){return e.map(e=>typeof e==`object`&&e?Xt(e):e).join(` `)}log(...e){if(this.debugEnabled){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.debugEnabled){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn(t,`: `,this.formatData(e))}}info(...e){if(this.debugEnabled){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info(t,`: `,this.formatData(e))}}debug(...e){if(this.debugEnabled){let t=`[ ${Date.now()} ] - DEBUG`;this.name&&(t+=` - ${this.name}`),console.debug(t,`: `,this.formatData(e))}}};function Xt(e){if(e instanceof Error)return e.stack||`${e.name}: ${e.message}`;let t=new WeakSet;try{return JSON.stringify(e,(e,n)=>{if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(typeof n==`bigint`)return n.toString();if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return n},2)}catch{return String(e)}}const Zt=t;function P(){let e=globalThis.process;return typeof e==`object`&&e?e:void 0}function F(e){return P()?.env?.[e]}function I(){return F(`DEBUG`)===`true`}function L(){let e=P()?.getBuiltinModule;if(typeof e!=`function`)return P()?Zt:void 0;try{return e(`node:crypto`)}catch{return}}function R(e){let t=L();if(!t)throw Error(`${e} needs the node:crypto module, which is not available in this runtime. Use the async Web Crypto variant instead, or run on Node.js >= 20.12, Bun or Deno.`);return t}function z(){let e=globalThis.crypto?.subtle;if(!e)throw Error(`Web Crypto (globalThis.crypto.subtle) is not available in this runtime.`);return e}function Qt(){let e=globalThis;if(e.Bun?.version)return`Bun ${e.Bun.version}`;if(e.Deno?.version?.deno)return`Deno ${e.Deno.version.deno}`;if(typeof e.EdgeRuntime==`string`)return`Edge Runtime ${e.EdgeRuntime}`;if(e.navigator?.userAgent===`Cloudflare-Workers`)return`Cloudflare Workers`;let t=P()?.version;return t?`Node.js ${t}`:`unknown runtime`}const $t=new TextEncoder,en=new TextDecoder;function tn(e){return $t.encode(e)}function nn(e){return en.decode(e)}function B(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function rn(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function an(e){let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return t}function on(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}async function sn(e,t){let n=z(),r=await n.importKey(`raw`,tn(e),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),i=await n.sign(`HMAC`,r,tn(t));return an(new Uint8Array(i))}const cn=new N(`UTILS`,I()||!1),ln=e=>{if(!F(`CLOUD_API_ACCESS_TOKEN`)&&!e?.accessToken)throw cn.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`),Error(`Missing WhatsApp access token.`)},un=e=>(ln(e),{M4D_APP_ID:e?.appId||F(`M4D_APP_ID`)||``,M4D_APP_SECRET:e?.appSecret||F(`M4D_APP_SECRET`)||``,WA_PHONE_NUMBER_ID:e?.phoneNumberId||(F(`WA_PHONE_NUMBER_ID`)?Number(F(`WA_PHONE_NUMBER_ID`)):0),WA_BUSINESS_ACCOUNT_ID:e?.businessAcctId||F(`WA_BUSINESS_ACCOUNT_ID`)||``,CLOUD_API_VERSION:e?.apiVersion||F(`CLOUD_API_VERSION`)||`v23.0`,CLOUD_API_ACCESS_TOKEN:e?.accessToken||F(`CLOUD_API_ACCESS_TOKEN`)||``,WEBHOOK_ENDPOINT:e?.webhookEndpoint||F(`WEBHOOK_ENDPOINT`)||``,WEBHOOK_VERIFICATION_TOKEN:e?.webhookVerificationToken||F(`WEBHOOK_VERIFICATION_TOKEN`)||``,LISTENER_PORT:e?.listenerPort||parseInt(F(`LISTENER_PORT`)||``,10)||3e3,MAX_RETRIES_AFTER_WAIT:e?.maxRetriesAfterWait||parseInt(F(`MAX_RETRIES_AFTER_WAIT`)||``,10)||30,REQUEST_TIMEOUT:e?.requestTimeout||parseInt(F(`REQUEST_TIMEOUT`)||``,10)||2e4,DEBUG:e?.debug||I(),FLOW_API_PRIVATE_PEM:e?.privatePem||F(`FLOW_API_PRIVATE_PEM`)||``,FLOW_API_PASSPHRASE:e?.passphrase||F(`FLOW_API_PASSPHRASE`)||``,retry:e?.retry,onRateLimitInfo:e?.onRateLimitInfo,fetch:e?.fetch,onRequest:e?.onRequest,onResponse:e?.onResponse});function dn(e){let t=[[`App ID`,e.M4D_APP_ID||`Not Set`],[`Phone Number ID`,e.WA_PHONE_NUMBER_ID?.toString()||`Not Set`],[`Business Account ID`,e.WA_BUSINESS_ACCOUNT_ID||`Not Set`],[`API Version`,e.CLOUD_API_VERSION||`Not Set`],[`Access Token`,e.CLOUD_API_ACCESS_TOKEN?`${e.CLOUD_API_ACCESS_TOKEN.substring(0,20)}...`:`Not Set`],[`Webhook Endpoint`,e.WEBHOOK_ENDPOINT||`Not Set`],[`Webhook Verification Token`,e.WEBHOOK_VERIFICATION_TOKEN?`${e.WEBHOOK_VERIFICATION_TOKEN.substring(0,10)}...`:`Not Set`],[`Listener Port`,e.LISTENER_PORT?.toString()||`Not Set`],[`Debug Mode`,e.DEBUG?`Enabled`:`Disabled`],[`Max Retries`,e.MAX_RETRIES_AFTER_WAIT?.toString()||`Not Set`],[`Request Timeout`,e.REQUEST_TIMEOUT?`${e.REQUEST_TIMEOUT}ms`:`Not Set`],[`Private PEM`,e.FLOW_API_PRIVATE_PEM?`Configured`:`Not Set`],[`Passphrase`,e.FLOW_API_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 V=new N(`FLOW_ENCRYPTION_UTILS`,I());function fn(){let e=L();if(!e||typeof e.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 V.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 V.error(`Browser environment detected:`,e),e}let t=globalThis.process?.versions?.node;if(t){let e=t.split(`.`).map(Number),n=e[0]??0,r=e[1]??0;if(n<10||n===10&&r<12){let e=Error(`Node.js version ${t} is not supported. Please upgrade to Node.js 10.12.0 or higher.`);throw V.error(`Node.js version check failed:`,e),e}}return e}function pn(e){V.info(`[generateEncryption] Starting key pair generation`);let t=fn(),n=e||F(`FLOW_API_PASSPHRASE`);if(!n||n.trim().length===0){let e=Error(`Passphrase is empty. Please provide a passphrase as parameter or set FLOW_API_PASSPHRASE environment variable.`);throw V.error(`[generateEncryption] Passphrase validation failed:`,e),e}n.length<8&&V.warn(`[generateEncryption] Passphrase is shorter than 8 characters. Consider using a longer passphrase for better security.`);try{V.info(`[generateEncryption] Generating 2048-bit RSA key pair`);let e=t.generateKeyPairSync(`rsa`,{modulusLength:2048,publicKeyEncoding:{type:`spki`,format:`pem`},privateKeyEncoding:{type:`pkcs8`,format:`pem`,cipher:`aes-256-cbc`,passphrase:n}});return V.info(`[generateEncryption] Key pair generated successfully`),{passphrase:n,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 V.error(`[generateEncryption] Key generation failed:`,n),n}}function mn(e,t){V.info(`[decryptFlowRequest] Starting Flow request decryption`);let n=R(`decryptFlowRequest`);if(!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 V.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 V.error(`[decryptFlowRequest] Configuration error:`,e),e}V.info(`[decryptFlowRequest] Configuration validated`);let{encrypted_aes_key:r,encrypted_flow_data:i,initial_vector:a}=e;if(!r||!i||!a)throw V.error(`[decryptFlowRequest] Missing required encryption properties in request body`),Error(`Missing required encryption properties`);V.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-----`);V.info(`[decryptFlowRequest] Loading private key`,{format:l?`PKCS#8`:c?`PKCS#1`:`Unknown`});let u;try{u=s?n.createPrivateKey({key:o,format:`pem`,passphrase:s}):n.createPrivateKey(o),V.info(`[decryptFlowRequest] Private key loaded successfully`)}catch(e){if(V.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{V.info(`[decryptFlowRequest] Attempting to convert PKCS#1 to PKCS#8 format`);let e=n.createPrivateKey({key:o,format:`pem`,passphrase:s}).export({type:`pkcs8`,format:`pem`,cipher:`aes-256-cbc`,passphrase:s});u=n.createPrivateKey({key:e,format:`pem`,passphrase:s}),V.info(`[decryptFlowRequest] Successfully converted PKCS#1 to PKCS#8 and loaded private key`)}catch(t){V.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,14 +10,20 @@ 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{H.info(`[decryptFlowRequest] Decrypting AES key with RSA private key`),d=n.privateDecrypt({key:u,padding:n.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:`sha256`},Buffer.from(r,`base64`)),H.info(`[decryptFlowRequest] AES key decrypted successfully`)}catch(e){throw H.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);H.info(`[decryptFlowRequest] Decrypting flow data with AES-128-GCM`);let g=n.createDecipheriv(`aes-128-gcm`,d,p);g.setAuthTag(h);let ee=Buffer.concat([g.update(m),g.final()]).toString(`utf-8`);return H.info(`[decryptFlowRequest] Flow request decrypted successfully`),{decryptedBody:JSON.parse(ee),aesKeyBuffer:d,initialVectorBuffer:p}}function mn(e,t,n){H.info(`[encryptFlowResponse] Starting Flow response encryption`);let r=z(`encryptFlowResponse`),i=[];for(let e of Array.from(n.entries()))i.push(~e[1]);try{H.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 H.info(`[encryptFlowResponse] Flow response encrypted successfully`),a}catch(e){throw H.error(`[encryptFlowResponse] Response encryption failed:`,e),Error(`Failed to encrypt response. Internal server error.`)}}const hn=/-----BEGIN ([A-Z ]+)-----([\s\S]*?)-----END \1-----/;let U;function gn(e,t){let n=hn.exec(e);if(!n)throw Error(`Failed to parse private key. Expected a PEM encoded PKCS#8 private key.`);let r=n[1];if(r===`PRIVATE KEY`)return V((n[2]??``).replace(/\s+/g,``));let i=R();if(!i)throw Error(`Failed to parse private key. "${r}" keys need node:crypto, which this runtime lacks. Convert the key to an unencrypted PKCS#8 key and keep it in a secret store:
14
- openssl pkcs8 -topk8 -nocrypt -in private.pem -out private-pkcs8.pem`);try{let n=i.createPrivateKey({key:e,format:`pem`,passphrase:t||void 0}).export({type:`pkcs8`,format:`der`});return new Uint8Array(n)}catch(e){throw Error(`Failed to parse private key. Error: ${e instanceof Error?e.message:e}`)}}function _n(e,t){if(U&&U.pem===e&&U.passphrase===t)return U.key;let n=(async()=>B().importKey(`pkcs8`,gn(e,t),{name:`RSA-OAEP`,hash:`SHA-256`},!1,[`decrypt`]))();return U={pem:e,passphrase:t,key:n},n.catch(()=>{U?.key===n&&(U=void 0)}),n}async function vn(e,t){if(!t.FLOW_API_PRIVATE_PEM||t.FLOW_API_PRIVATE_PEM.trim()===``)throw Error(`Missing FLOW_API_PRIVATE_PEM. Please set the FLOW_API_PRIVATE_PEM environment variable or pass privatePem via config.`);let{encrypted_aes_key:n,encrypted_flow_data:r,initial_vector:i}=e??{};if(!n||!r||!i)throw Error(`Missing required encryption properties`);let a=t.FLOW_API_PRIVATE_PEM;a.includes(`\\n`)&&(a=a.replace(/\\n/g,`
15
- `));let o=B(),s=await _n(a,t.FLOW_API_PASSPHRASE||``),c;try{c=new Uint8Array(await o.decrypt({name:`RSA-OAEP`},s,V(n)))}catch(e){throw H.error(`[decryptFlowRequestAsync] Failed to decrypt AES key:`,e),Error(`Failed to decrypt the request. Please verify your private key.`)}let l=V(i),u=await o.importKey(`raw`,c,{name:`AES-GCM`},!1,[`decrypt`]),d=await o.decrypt({name:`AES-GCM`,iv:l,tagLength:128},u,V(r));return{decryptedBody:JSON.parse(tn(new Uint8Array(d))),aesKeyBuffer:c,initialVectorBuffer:l}}async function yn(e,t,n){let r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=~(n[e]??0)&255;try{let n=B(),i=await n.importKey(`raw`,new Uint8Array(t),{name:`AES-GCM`},!1,[`encrypt`]),a=await n.encrypt({name:`AES-GCM`,iv:r,tagLength:128},i,en(JSON.stringify(e||{})));return nn(new Uint8Array(a))}catch(e){throw H.error(`[encryptFlowResponseAsync] Response encryption failed:`,e),Error(`Failed to encrypt response. Internal server error.`)}}function W(e,t){if(typeof e.get==`function`)return e.get(t)??void 0;let n=e,r=Object.keys(n).find(e=>e.toLowerCase()===t);if(r===void 0)return;let i=n[r];return Array.isArray(i)?i[0]:i}function bn(e){if(!(e===void 0||e.trim()===``))try{return JSON.parse(e)}catch{return}}function xn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function G(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``&&Number.isFinite(Number(e)))return Number(e)}function Sn(e){return typeof e==`string`?e:void 0}function Cn(e){let t={},n=G(e.call_count),r=G(e.total_cputime),i=G(e.total_time);return n!==void 0&&(t.callCount=n),r!==void 0&&(t.totalCputime=r),i!==void 0&&(t.totalTime=i),t}function wn(e){if(!xn(e))return[];let t=[];for(let[n,r]of Object.entries(e))if(Array.isArray(r))for(let e of r){if(!xn(e))continue;let r={businessId:n,...Cn(e)},i=Sn(e.type),a=G(e.estimated_time_to_regain_access),o=Sn(e.ads_api_access_tier);i!==void 0&&(r.type=i),a!==void 0&&(r.estimatedTimeToRegainAccessMinutes=a),o!==void 0&&(r.adsApiAccessTier=o),t.push(r)}return t}function Tn(e,t=Date.now()){if(e==null)return;let n=e.trim();if(n===``)return;if(/^\d+(\.\d+)?$/.test(n))return Math.round(Number(n)*1e3);if(!/[a-z]/i.test(n))return;let r=Date.parse(n);if(Number.isFinite(r))return Math.max(0,r-t)}function En(e){if(!e)return;let t=W(e,`x-app-usage`),n=W(e,`x-business-use-case-usage`),r=W(e,`retry-after`);if(t===void 0&&n===void 0&&r===void 0)return;let i={businessUseCaseUsage:[]},a=bn(t);xn(a)&&(i.appUsage=Cn(a)),i.businessUseCaseUsage=wn(bn(n));let o=Tn(r);o!==void 0&&(i.retryAfterMs=o);let s=[...i.appUsage?[i.appUsage]:[],...i.businessUseCaseUsage].flatMap(e=>[e.callCount,e.totalCputime,e.totalTime].filter(e=>e!==void 0));s.length>0&&(i.maxUsagePercent=Math.max(...s));let c=[...o===void 0?[]:[o],...i.businessUseCaseUsage.map(e=>e.estimatedTimeToRegainAccessMinutes).filter(e=>e!==void 0&&e>0).map(e=>e*6e4)];return c.length>0&&(i.retryDelayMs=Math.max(...c)),i}const Dn=new P(`HttpsClient`,L());var On=class{clearSockets(){return!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 Dn.log(`${n} : ${o} - ${JSON.stringify(e)}`),clearTimeout(c),new kn(e)}catch(e){throw Dn.error(`${n} : ${o} - ${JSON.stringify(e)}`),e}}},kn=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 K=new P(`REQUESTER`,L());function An(e){return new Promise(t=>setTimeout(t,e))}var jn=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol=`https:`;retryConfig;onRateLimitInfo;lastRateLimitInfo;constructor(e,t,n,r,i,a,o){this.client=new On,this.host=`graph.facebook.com`,this.apiVersion=this.normalizeApiVersion(e),this.phoneNumberId=t,this.accessToken=n,this.businessAcctId=r,this.userAgent=i,this.retryConfig=a,this.onRateLimitInfo=o}getLastRateLimitInfo(){return this.lastRateLimitInfo}captureRateLimitInfo(e,t,n){if(typeof e.headers!=`function`)return;let r=En(e.headers());if(r){if(this.lastRateLimitInfo=r,this.onRateLimitInfo)try{let i=typeof e.statusCode==`function`?e.statusCode():0;Promise.resolve(this.onRateLimitInfo(r,{method:t,endpoint:n,statusCode:i})).catch(e=>{K.log(`onRateLimitInfo listener threw: ${e instanceof Error?e.message:e}`)})}catch(e){K.log(`onRateLimitInfo listener threw: ${e instanceof Error?e.message:e}`)}return r}}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`${this.apiVersion}/${e}`}normalizeApiVersion(e){if(!e)return`v23.0`;let t=e.trim();return/^v\d+\.\d+$/.test(t)?t:/^\d+\.\d+$/.test(t)?`v${t}`:/^v\d+$/.test(t)?`${t}.0`:/^\d+$/.test(t)?`v${t}.0`:t}buildRequestTarget(e){if(/^https?:\/\//.test(e)){let t=new URL(e),n=`${t.pathname}${t.search}`.replace(/^\//,``);return{host:t.host,path:n,displayUrl:t.toString()}}let t=this.buildCAPIPath(e.replace(/^\//,``));return{host:this.host,path:t,displayUrl:`${this.protocol.toLowerCase()}//${this.host}/${t}`}}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=this.retryConfig?.respectServerDelay??!0,u=this.retryConfig?.maxServerDelayMs??3e4,d=i;r instanceof FormData?d=`multipart/form-data`:typeof r==`string`&&r.startsWith(`<?xml`)&&(d=`application/xml`);let f=this.buildRequestTarget(t);K.log(`${e} : ${f.displayUrl} (${d})`);for(let i=1;i<=o;i++)try{let i=e===`POST`||e===`PUT`||e===`DELETE`,o=await this.client.sendRequest(f.host,f.path,e,this.buildHeader(d,a),n,i?r:void 0),s=this.captureRateLimitInfo(o,e,t);if(!o.rawResponse().ok){let e=null;try{e=await o.json()}catch{e=null}let t=w(rt(e,o.statusCode()).error,o.statusCode());throw s&&(t.rateLimit=s),t}return o}catch(e){if(e instanceof x&&i<o){let t=c===`exponential`?s*2**(i-1):s,n=l?e.rateLimit?.retryDelayMs:void 0,r=n===void 0?t:Math.max(t,Math.min(n,Math.max(0,u)));K.log(`Throttled (attempt ${i}/${o}). Retrying in ${r}ms...`),await An(r);continue}throw e instanceof v?e:E(e)?w(e.error):new Ke(e instanceof Error?e.message:`Network error occurred`,e)}throw new x(`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){K.log(`Timeout updated to ${e}ms`)}updateAccessToken(e){this.accessToken=e,K.log(`Access token updated`)}async sendUrlEncodedForm(e,t,n,r,i){let a=new URLSearchParams;for(let[e,t]of Object.entries(r))if(Array.isArray(t))for(let n of t)a.append(e,n);else a.append(e,t);let o=a.toString();return await(await this.sendRequest(e,t,n,o,`application/x-www-form-urlencoded`,i)).json()}};function Mn(){I(`NODE_ENV`)===`test`||I(`VITEST`)===`true`||typeof global<`u`&&global.__VITEST__||console.log(`\x1B[36m%s\x1B[0m`,`
13
+ Your key format is not recognized. Please ensure it is in PKCS#8 format.`),Error(t)}}let d;try{V.info(`[decryptFlowRequest] Decrypting AES key with RSA private key`),d=n.privateDecrypt({key:u,padding:n.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:`sha256`},Buffer.from(r,`base64`)),V.info(`[decryptFlowRequest] AES key decrypted successfully`)}catch(e){throw V.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);V.info(`[decryptFlowRequest] Decrypting flow data with AES-128-GCM`);let g=n.createDecipheriv(`aes-128-gcm`,d,p);g.setAuthTag(h);let ee=Buffer.concat([g.update(m),g.final()]).toString(`utf-8`);return V.info(`[decryptFlowRequest] Flow request decrypted successfully`),{decryptedBody:JSON.parse(ee),aesKeyBuffer:d,initialVectorBuffer:p}}function hn(e,t,n){V.info(`[encryptFlowResponse] Starting Flow response encryption`);let r=R(`encryptFlowResponse`),i=[];for(let e of Array.from(n.entries()))i.push(~e[1]);try{V.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 V.info(`[encryptFlowResponse] Flow response encrypted successfully`),a}catch(e){throw V.error(`[encryptFlowResponse] Response encryption failed:`,e),Error(`Failed to encrypt response. Internal server error.`)}}const gn=/-----BEGIN ([A-Z ]+)-----([\s\S]*?)-----END \1-----/;let H;function _n(e,t){let n=gn.exec(e);if(!n)throw Error(`Failed to parse private key. Expected a PEM encoded PKCS#8 private key.`);let r=n[1];if(r===`PRIVATE KEY`)return B((n[2]??``).replace(/\s+/g,``));let i=L();if(!i)throw Error(`Failed to parse private key. "${r}" keys need node:crypto, which this runtime lacks. Convert the key to an unencrypted PKCS#8 key and keep it in a secret store:
14
+ openssl pkcs8 -topk8 -nocrypt -in private.pem -out private-pkcs8.pem`);try{let n=i.createPrivateKey({key:e,format:`pem`,passphrase:t||void 0}).export({type:`pkcs8`,format:`der`});return new Uint8Array(n)}catch(e){throw Error(`Failed to parse private key. Error: ${e instanceof Error?e.message:e}`)}}function vn(e,t){if(H&&H.pem===e&&H.passphrase===t)return H.key;let n=(async()=>z().importKey(`pkcs8`,_n(e,t),{name:`RSA-OAEP`,hash:`SHA-256`},!1,[`decrypt`]))();return H={pem:e,passphrase:t,key:n},n.catch(()=>{H?.key===n&&(H=void 0)}),n}async function yn(e,t){if(!t.FLOW_API_PRIVATE_PEM||t.FLOW_API_PRIVATE_PEM.trim()===``)throw Error(`Missing FLOW_API_PRIVATE_PEM. Please set the FLOW_API_PRIVATE_PEM environment variable or pass privatePem via config.`);let{encrypted_aes_key:n,encrypted_flow_data:r,initial_vector:i}=e??{};if(!n||!r||!i)throw Error(`Missing required encryption properties`);let a=t.FLOW_API_PRIVATE_PEM;a.includes(`\\n`)&&(a=a.replace(/\\n/g,`
15
+ `));let o=z(),s=await vn(a,t.FLOW_API_PASSPHRASE||``),c;try{c=new Uint8Array(await o.decrypt({name:`RSA-OAEP`},s,B(n)))}catch(e){throw V.error(`[decryptFlowRequestAsync] Failed to decrypt AES key:`,e),Error(`Failed to decrypt the request. Please verify your private key.`)}let l=B(i),u=await o.importKey(`raw`,c,{name:`AES-GCM`},!1,[`decrypt`]),d=await o.decrypt({name:`AES-GCM`,iv:l,tagLength:128},u,B(r));return{decryptedBody:JSON.parse(nn(new Uint8Array(d))),aesKeyBuffer:c,initialVectorBuffer:l}}async function bn(e,t,n){let r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=~(n[e]??0)&255;try{let n=z(),i=await n.importKey(`raw`,new Uint8Array(t),{name:`AES-GCM`},!1,[`encrypt`]),a=await n.encrypt({name:`AES-GCM`,iv:r,tagLength:128},i,tn(JSON.stringify(e||{})));return rn(new Uint8Array(a))}catch(e){throw V.error(`[encryptFlowResponseAsync] Response encryption failed:`,e),Error(`Failed to encrypt response. Internal server error.`)}}function xn(e,t){if(typeof e.get==`function`)return e.get(t)??void 0;let n=e,r=Object.keys(n).find(e=>e.toLowerCase()===t);if(r===void 0)return;let i=n[r];return Array.isArray(i)?i[0]:i}function Sn(e){if(!(e===void 0||e.trim()===``))try{return JSON.parse(e)}catch{return}}function Cn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function U(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``&&Number.isFinite(Number(e)))return Number(e)}function wn(e){return typeof e==`string`?e:void 0}function Tn(e){let t={},n=U(e.call_count),r=U(e.total_cputime),i=U(e.total_time);return n!==void 0&&(t.callCount=n),r!==void 0&&(t.totalCputime=r),i!==void 0&&(t.totalTime=i),t}function En(e){if(!Cn(e))return[];let t=[];for(let[n,r]of Object.entries(e))if(Array.isArray(r))for(let e of r){if(!Cn(e))continue;let r={businessId:n,...Tn(e)},i=wn(e.type),a=U(e.estimated_time_to_regain_access),o=wn(e.ads_api_access_tier);i!==void 0&&(r.type=i),a!==void 0&&(r.estimatedTimeToRegainAccessMinutes=a),o!==void 0&&(r.adsApiAccessTier=o),t.push(r)}return t}function Dn(e,t=Date.now()){if(e==null)return;let n=e.trim();if(n===``)return;if(/^\d+(\.\d+)?$/.test(n))return Math.round(Number(n)*1e3);if(!/[a-z]/i.test(n))return;let r=Date.parse(n);if(Number.isFinite(r))return Math.max(0,r-t)}function On(e){if(!e)return;let t=xn(e,`x-app-usage`),n=xn(e,`x-business-use-case-usage`),r=xn(e,`retry-after`);if(t===void 0&&n===void 0&&r===void 0)return;let i={businessUseCaseUsage:[]},a=Sn(t);Cn(a)&&(i.appUsage=Tn(a)),i.businessUseCaseUsage=En(Sn(n));let o=Dn(r);o!==void 0&&(i.retryAfterMs=o);let s=[...i.appUsage?[i.appUsage]:[],...i.businessUseCaseUsage].flatMap(e=>[e.callCount,e.totalCputime,e.totalTime].filter(e=>e!==void 0));s.length>0&&(i.maxUsagePercent=Math.max(...s));let c=[...o===void 0?[]:[o],...i.businessUseCaseUsage.map(e=>e.estimatedTimeToRegainAccessMinutes).filter(e=>e!==void 0&&e>0).map(e=>e*6e4)];return c.length>0&&(i.retryDelayMs=Math.max(...c)),i}const kn=new N(`HttpsClient`,I());var An=class{fetchImpl;constructor(e){this.fetchImpl=e}clearSockets(){return!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(this.fetchImpl??globalThis.fetch).call(globalThis,o,{method:n,headers:r,body:a,signal:s.signal});return kn.log(`${n} : ${o} - ${JSON.stringify(e)}`),clearTimeout(c),new jn(e)}catch(e){throw kn.error(`${n} : ${o} - ${JSON.stringify(e)}`),e}}},jn=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 N(`REQUESTER`,I());function Mn(e){return new Promise(t=>setTimeout(t,e))}var Nn=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol=`https:`;retryConfig;onRateLimitInfo;lastRateLimitInfo;hooks;constructor(e,t,n,r,i,a,o,s,c){this.client=new An(s),this.host=`graph.facebook.com`,this.apiVersion=this.normalizeApiVersion(e),this.phoneNumberId=t,this.accessToken=n,this.businessAcctId=r,this.userAgent=i,this.retryConfig=a,this.onRateLimitInfo=o,this.hooks=c}async runHook(e,t){let n=this.hooks?.[e];if(n)try{await n(t)}catch(t){W.log(`${e} hook threw: ${t instanceof Error?t.message:t}`)}}redactHeaders(e){let t={};for(let[n,r]of Object.entries(e))t[n]=n.toLowerCase()===`authorization`?`Bearer ***`:r;return t}getLastRateLimitInfo(){return this.lastRateLimitInfo}captureRateLimitInfo(e,t,n){if(typeof e.headers!=`function`)return;let r=On(e.headers());if(r){if(this.lastRateLimitInfo=r,this.onRateLimitInfo)try{let i=typeof e.statusCode==`function`?e.statusCode():0;Promise.resolve(this.onRateLimitInfo(r,{method:t,endpoint:n,statusCode:i})).catch(e=>{W.log(`onRateLimitInfo listener threw: ${e instanceof Error?e.message:e}`)})}catch(e){W.log(`onRateLimitInfo listener threw: ${e instanceof Error?e.message:e}`)}return r}}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`${this.apiVersion}/${e}`}normalizeApiVersion(e){if(!e)return`v23.0`;let t=e.trim();return/^v\d+\.\d+$/.test(t)?t:/^\d+\.\d+$/.test(t)?`v${t}`:/^v\d+$/.test(t)?`${t}.0`:/^\d+$/.test(t)?`v${t}.0`:t}buildRequestTarget(e){if(/^https?:\/\//.test(e)){let t=new URL(e),n=`${t.pathname}${t.search}`.replace(/^\//,``);return{host:t.host,path:n,displayUrl:t.toString()}}let t=this.buildCAPIPath(e.replace(/^\//,``));return{host:this.host,path:t,displayUrl:`${this.protocol.toLowerCase()}//${this.host}/${t}`}}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=this.retryConfig?.respectServerDelay??!0,u=this.retryConfig?.maxServerDelayMs??3e4,d=i;r instanceof FormData?d=`multipart/form-data`:typeof r==`string`&&r.startsWith(`<?xml`)&&(d=`application/xml`);let f=this.buildRequestTarget(t);W.log(`${e} : ${f.displayUrl} (${d})`);for(let i=1;i<=o;i++)try{let o=e===`POST`||e===`PUT`||e===`DELETE`,s=this.buildHeader(d,a),c=o?r:void 0,l;(this.hooks?.onRequest||this.hooks?.onResponse)&&(l={method:e,url:f.displayUrl,headers:this.redactHeaders(s),body:c,attempt:i},await this.runHook(`onRequest`,l));let u=Date.now(),p=await this.client.sendRequest(f.host,f.path,e,s,n,c);l&&this.hooks?.onResponse&&await this.runHook(`onResponse`,{...l,statusCode:p.statusCode(),responseHeaders:typeof p.headers==`function`?p.headers():{},durationMs:Date.now()-u});let m=this.captureRateLimitInfo(p,e,t);if(!p.rawResponse().ok){let e=null;try{e=await p.json()}catch{e=null}let t=Ke(it(e,p.statusCode()).error,p.statusCode());throw m&&(t.rateLimit=m),t}return p}catch(e){if(e instanceof x&&i<o){let t=c===`exponential`?s*2**(i-1):s,n=l?e.rateLimit?.retryDelayMs:void 0,r=n===void 0?t:Math.max(t,Math.min(n,Math.max(0,u)));W.log(`Throttled (attempt ${i}/${o}). Retrying in ${r}ms...`),await Mn(r);continue}throw e instanceof v?e:T(e)?Ke(e.error):new qe(e instanceof Error?e.message:`Network error occurred`,e)}throw new x(`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;for(let[e,t]of Object.entries(r))if(Array.isArray(t))for(let n of t)a.append(e,n);else a.append(e,t);let o=a.toString();return await(await this.sendRequest(e,t,n,o,`application/x-www-form-urlencoded`,i)).json()}};function Pn(){F(`NODE_ENV`)===`test`||F(`VITEST`)===`true`||typeof global<`u`&&global.__VITEST__||console.log(`\x1B[36m%s\x1B[0m`,`
16
16
  ██████╗ ██╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ██████╗ ██╗
17
17
  ██╔════╝ ██║ ██╔═══██╗ ██║ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║
18
18
  ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ███████║ ██████╔╝ ██║
19
19
  ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██╔══██║ ██╔═══╝ ██║
20
20
  ╚██████╗ ███████╗ ╚██████╔╝ ╚██████╔╝ ██████╔╝ ██║ ██║ ██║ ██║
21
21
  ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝
22
- `)}function Nn(){return`3.11.2`}function Pn(){return`WhatsApp-Nodejs-SDK/${Nn()} (${Zt()})`}const q=new P(`WHATSAPP`,L());var Fn=class{config;requester;blockUsers;business;calling;commerce;contactBook;groups;marketingMessages;messageHistory;messages;media;payments;phoneNumbers;solutions;threadControl;twoStepVerification;flows;businessProfile;templates;encryption;qrCode;registration;waba;constructor(e){Mn(),this.config=ln(e),this.requester=new jn(this.config.CLOUD_API_VERSION,this.config.WA_PHONE_NUMBER_ID,this.config.CLOUD_API_ACCESS_TOKEN,this.config.WA_BUSINESS_ACCOUNT_ID,this.getUserAgent(),this.config.retry,this.config.onRateLimitInfo),this.blockUsers=new at(this.config,this.requester),this.business=new ot(this.config,this.requester),this.calling=new st(this.config,this.requester),this.commerce=new ct(this.config,this.requester),this.contactBook=new lt(this.config,this.requester),this.groups=new gt(this.config,this.requester),this.marketingMessages=new _t(this.config,this.requester),this.messageHistory=new St(this.config,this.requester),this.messages=new O(this.config,this.requester),this.media=new vt(this.config,this.requester),this.payments=new Ct(this.config,this.requester),this.phoneNumbers=new wt(this.config,this.requester),this.solutions=new Ot(this.config,this.requester),this.threadControl=new Ht(this.config,this.requester),this.twoStepVerification=new Ut(this.config,this.requester),this.flows=new dt(this.config,this.requester),this.businessProfile=new Tt(this.config,this.requester),this.templates=new Bt(this.config,this.requester),this.encryption=new ut(this.config,this.requester),this.qrCode=new Et(this.config,this.requester),this.registration=new Dt(this.config,this.requester),this.waba=new Wt(this.config,this.requester),q.log(`\n${un(this.config)}`)}updateTimeout(e){this.config.REQUEST_TIMEOUT=e,this.requester.updateTimeout(e),q.log(`Timeout updated to ${e}ms`)}updateSenderNumberId(e){this.config.WA_PHONE_NUMBER_ID=e,q.log(`Sender number ID updated to ${e}`)}updateAccessToken(e){this.config.CLOUD_API_ACCESS_TOKEN=e,this.requester.updateAccessToken(e),q.log(`Access token updated`)}getLastRateLimitInfo(){return this.requester.getLastRateLimitInfo()}version(){return Nn()}static get Enums(){return i}getUserAgent(){return Pn()}generateEncryption(e){return fn(e||this.config.FLOW_API_PASSPHRASE)}},In=class{maxEntries;entries=new Map;constructor(e={}){let t=e.maxEntries??1e4;if(!Number.isInteger(t)||t<1)throw Error(`MemoryDedupeStore maxEntries must be a positive integer, got ${t}`);this.maxEntries=t}async has(e){return this.lookup(e,Date.now())!==void 0}async setIfAbsent(e,t){let n=Date.now(),r=this.lookup(e,n);return r===void 0?(this.entries.set(e,n+t*1e3),this.evict(n),!0):(this.entries.delete(e),this.entries.set(e,r),!1)}get size(){return this.entries.size}clear(){this.entries.clear()}lookup(e,t){let n=this.entries.get(e);if(n!==void 0){if(n<=t){this.entries.delete(e);return}return n}}evict(e){for(let[t,n]of this.entries)n<=e&&this.entries.delete(t);for(let e of this.entries.keys()){if(this.entries.size<=this.maxEntries)break;this.entries.delete(e)}}};function Ln(e){if(!e)return;let t=e===!0?{}:e,n=t.ttlSeconds??86400;if(!Number.isFinite(n)||n<=0)throw Error(`dedupe.ttlSeconds must be a positive number, got ${n}`);return{store:t.store??new In,ttlSeconds:n}}function Rn(e){return typeof e==`object`&&!!e}function J(e){return typeof e==`string`}const zn=[`data_exchange`,`INIT`,`BACK`],Bn=[`data_exchange`,`INIT`];function Vn(e){if(!(`flow_token`in e&&J(e.flow_token)&&`action`in e))return!1;let{action:t,version:n,screen:r,data:i}=e,a=n===`3.0`,o=zn.includes(t),s=r===void 0||J(r)&&r!==`SUCCESS`,c=t===`data_exchange`||Rn(i);return a&&o&&s&&c}function Hn(e){if(!(`flow_token`in e&&J(e.flow_token)&&`action`in e))return!1;let{action:t,screen:n,data:r}=e,i=Bn.includes(t),a=J(n),o=Rn(r)&&`error_key`in r&&J(r.error)&&`error_message`in r&&J(r.error_message);return i&&a&&o}function Un(e){return`action`in e&&e.action===`ping`}const Y=new P(`WEBHOOK_UTILS`,L()),Wn={account_update:`accountUpdateHandler`,account_review_update:`accountReviewUpdateHandler`,account_alerts:`accountAlertsHandler`,account_settings_update:`accountSettingsUpdateHandler`,automatic_events:`automaticEventsHandler`,business_capability_update:`businessCapabilityUpdateHandler`,business_status_update:`businessStatusUpdateHandler`,business_username_updates:`businessUsernameUpdatesHandler`,calls:`callsHandler`,flows:`flowsHandler`,group_lifecycle_update:`groupLifecycleUpdateHandler`,group_participants_update:`groupParticipantsUpdateHandler`,group_settings_update:`groupSettingsUpdateHandler`,group_status_update:`groupStatusUpdateHandler`,history:`historyHandler`,message_echoes:`messageEchoesHandler`,message_template_components_update:`messageTemplateComponentsUpdateHandler`,message_template_quality_update:`messageTemplateQualityUpdateHandler`,message_template_status_update:`messageTemplateStatusUpdateHandler`,messaging_handovers:`messagingHandoversHandler`,partner_solutions:`partnerSolutionsHandler`,payment_configuration_update:`paymentConfigurationUpdateHandler`,phone_number_name_update:`phoneNumberNameUpdateHandler`,phone_number_quality_update:`phoneNumberQualityUpdateHandler`,security:`securityHandler`,smb_app_state_sync:`smbAppStateSyncHandler`,smb_message_echoes:`smbMessageEchoesHandler`,standby:`standbyHandler`,template_category_update:`templateCategoryUpdateHandler`,template_correct_category_detection:`templateCorrectCategoryDetectionHandler`,tracking_events:`trackingEventsHandler`,user_preferences:`userPreferencesHandler`};function Gn(e){return Object.hasOwn(Wn,e)}const Kn={calls:e=>Jn(`calls`,qn(e?.calls,e=>e?.id?`${e.id}:${e.event}${e.call_status?`:${e.call_status}`:``}`:void 0)),smb_message_echoes:e=>Jn(`smb_message_echoes`,qn(e?.message_echoes,e=>e?.id)),message_echoes:e=>Jn(`message_echoes`,qn(e?.messaging,e=>e?.message?.mid))};function qn(e,t){return Array.isArray(e)?e.map(t):void 0}function Jn(e,t){if(!(!t||t.length===0||t.some(e=>!e)))return`${e}:${t.join(`,`)}`}function Yn(e,t){let n=Kn[e];return n?.(t)}async function Xn(e,t){if(!e||!t)return!1;try{return await e.store.setIfAbsent(t,e.ttlSeconds)?!1:(Y.log(`Skipping duplicate webhook delivery: ${t}`),!0)}catch(e){return Y.error(`Dedupe store failed; processing the webhook anyway:`,{key:t,error:e}),!1}}async function Zn(e,t,n,r={}){try{let i=await e.text();if(r.verifySignature){if(!r.appSecret)return Y.error(`verifyWebhookSignature is on but appSecret is not configured; rejecting webhook`),new Response(JSON.stringify({error:`Webhook signature verification misconfigured`}),{status:500,headers:{"Content-Type":`application/json`}});if(!await tr(i,e.headers.get(`x-hub-signature-256`),r.appSecret))return Y.warn(`Rejected webhook with missing or invalid X-Hub-Signature-256`),new Response(JSON.stringify({error:`Invalid signature`}),{status:401,headers:{"Content-Type":`application/json`}})}let a=JSON.parse(i),o={headers:e.headers,rawBody:i,method:e.method,url:e.url},s=r.dedupe?{store:r.dedupe.store,ttlSeconds:r.dedupe.ttlSeconds??86400}:void 0;if(n.rawHandler){let{rawHandler:e,rawHandlerFields:r}=n,i=a;if(r&&r.length>0){let e={...i,entry:i.entry.map(e=>({...e,changes:e.changes.filter(e=>r.includes(e.field))})).filter(e=>e.changes.length>0)};i=e.entry.length===0?null:e}i&&await e(t,i,o)}if(a.object!==`whatsapp_business_account`){let e=`Received webhook for non-WhatsApp event`;return Y.warn(e),new Response(JSON.stringify({error:e}),{status:404})}let c=[];for(let e of a.entry)try{let r=e.changes;for(let i of r){let r=i.field;if(r===`messages`)await ar(e.id,i.value,t,n,o,s);else if(Gn(r)){let a=n.fieldHandlers?.get(r)??n[Wn[r]];await lr(e.id,{field:r,value:i.value},a,t,o,s)}else Y.warn(`Unhandled webhook field: ${i.field}`)}}catch(t){let n=`Error processing webhook: ${t}`;Y.error(n,{entry:e,error:t}),c.push(n)}return new Response(c.length>0?JSON.stringify({errors:c}):null,{status:200})}catch(e){return Y.error(`Error processing webhook:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500})}}function Qn(){return{version:`3.0`,data:{status:`active`}}}function $n(){return{data:{acknowledged:!0}}}async function er(e,t,n,r){try{let i=await e.text(),a={headers:e.headers,rawBody:i,method:e.method,url:e.url},o=e.headers.get(`x-hub-signature-256`),s=t.M4D_APP_SECRET||t.WEBHOOK_VERIFICATION_TOKEN||``;if(t.M4D_APP_SECRET||Y.warn(`appSecret not configured; verifying Flow signature with the webhook verification token`),!await tr(i,o,s))return Y.warn(`Invalid request signature`),new Response(JSON.stringify({error:`Unauthorized`}),{status:401});let{decryptedBody:c,aesKeyBuffer:l,initialVectorBuffer:u}=await vn(JSON.parse(i),t),d=Un(c),f=Hn(c),p=Vn(c),m;m=d?`ping`:f?`error`:p?`data_exchange`:`*`;let h=r.get(m);if(!h){if(m===`ping`)h=()=>Qn();else if(m===`error`)h=()=>$n();else if(h=r.get(`*`),!h)return Y.warn(`No handler registered for flow type:`,{flowType:m,action:c.action}),new Response(JSON.stringify({error:`Handler not found`}),{status:404})}let g=await h(n,c,a);if(f){Y.warn(`Flow error notification received`,{error:c.data});let e=g||$n();return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":`application/json`}})}if(d||p){let e=await yn(g,l,u);return new Response(e,{status:200,headers:{"Content-Type":`text/plain`}})}return Y.warn(`Unknown flow request type:`,c),new Response(JSON.stringify({error:`Unknown request type`}),{status:400})}catch(e){return Y.error(`Error handling flow request:`,e),new Response(JSON.stringify({error:`Internal server error`}),{status:500})}}async function tr(e,t,n){if(!t||!n)return!1;let r=t.startsWith(`sha256=`)?t.slice(7):t,i=await on(n,e);return an(r.toLowerCase(),i)}function nr(e,t,n){if(!t||!n)return!1;let r=z(`isValidWebhookSignature`),i=t.startsWith(`sha256=`)?t.slice(7):t,a=r.createHmac(`sha256`,n).update(e,`utf8`).digest(`hex`);return an(i.toLowerCase(),a)}function rr(e,t){return`${e[`x-forwarded-proto`]||`http`}://${e.host||`localhost`}${t||`/`}`}function ir(e){return e.id?e.id:(e.type===`interactive`||e.type===`button`)&&`context`in e&&e.context?.id?e.context.id:``}async function ar(e,t,n,r,i,a){let o=t.metadata,s=e,c=o.display_phone_number,l=o.phone_number_id;if(`user_actions`in t&&t.user_actions){let e=t;for(let t of e.user_actions){let e={wabaId:s,phoneNumberId:l,displayPhoneNumber:c,action:t};await cr(r.userActionHandler,n,e,i)}return}if(`statuses`in t&&t.statuses){let e=t;for(let t of e.statuses){if(!r.statusHandler||await Xn(a,t.id?`status:${t.id}:${t.status}`:void 0))continue;let e={wabaId:s,phoneNumberId:l,displayPhoneNumber:c,status:t};await sr(r.statusHandler,n,e,i)}return}if(`messages`in t&&t.messages){let e=t,o=e.contacts?.[0]?.profile?.name||``;for(let t of e.messages){let u={wabaId:s,phoneNumberId:l,displayPhoneNumber:c,profileName:o,message:t,messageId:ir(t),...e.conversation_context&&{conversationContext:e.conversation_context}},d=t.type,f=r.messageHandlers.get(d);!r.preProcessHandler&&!f&&!r.postProcessHandler||await Xn(a,u.messageId?`message:${u.messageId}`:void 0)||(await or(r.preProcessHandler,n,u,i,`pre-process`),await or(f,n,u,i,d),await or(r.postProcessHandler,n,u,i,`post-process`))}}}async function or(e,t,n,r,i){if(e)try{await e(t,n,r)}catch(e){Y.error(`Error in ${i} handler:`,{error:e,messageId:n.messageId})}}async function sr(e,t,n,r){if(e)try{await e(t,n,r)}catch(e){Y.error(`Error in status handler:`,{error:e,statusId:n.status.id})}}async function cr(e,t,n,r){if(e)try{await e(t,n,r)}catch(e){Y.error(`Error in user action handler:`,{error:e,actionType:n.action.action_type})}}async function lr(e,t,n,r,i,a){if(n&&!await Xn(a,Yn(t.field,t.value)))try{await n(r,{wabaId:e,value:t.value},i)}catch(n){Y.error(`Error in ${t.field} handler:`,{error:n,wabaId:e})}}const X=new P(`WEBHOOK_PROCESSOR`,L());function ur(e,t){if(e===`messages`)throw Error(`${t}('messages') is not supported. Use onMessage/onText/... for messages, onStatus for statuses and onUserAction for marketing user actions.`);if(!Gn(e))throw Error(`${t}('${e}'): unknown webhook field`)}var Z=class{config;client;messageHandlers=new Map;statusHandler=void 0;userActionHandler=void 0;preProcessHandler=void 0;postProcessHandler=void 0;rawHandler=void 0;flowHandlers=new Map;fieldHandlers=new Map;verifySignature;dedupe;constructor(e){this.config=ln(e),this.verifySignature=e.verifyWebhookSignature===!0,this.dedupe=Ln(e.dedupe),this.client=new Fn(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 Zn(e,this.client,{messageHandlers:this.messageHandlers,statusHandler:this.statusHandler,userActionHandler:this.userActionHandler,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler,rawHandler:this.rawHandler?.handler,rawHandlerFields:this.rawHandler?.fields,fieldHandlers:this.fieldHandlers},{appSecret:this.config.M4D_APP_SECRET,verifySignature:this.verifySignature,dedupe:this.dedupe}),n=await t.text(),r=t.headers.get(`content-type`)||`application/json`;return{status:t.status,body:n,headers:{"Content-Type":r}}}catch(e){return X.log(`Error processing webhook: ${e}`),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async processFlow(e){try{let t=await er(e,this.config,this.client,this.flowHandlers),n=await t.text(),r=t.headers.get(`content-type`)||`text/plain`;return{status:t.status,body:n,headers:{"Content-Type":r}}}catch(e){return X.log(`Error processing flow: ${e}`),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}onMessage(e,t){if(e===`statuses`)throw Error(`MessageTypesEnum.Statuses is deprecated. Use onStatus(handler) instead of onMessage(MessageTypesEnum.Statuses, handler)`);this.messageHandlers.set(e,t),X.log(`Registered message handler for ${e}`)}onStatus(e){this.statusHandler=e,X.log(`Registered status handler`)}onUserAction(e){this.userActionHandler=e,X.log(`Registered user action handler`)}onMessagePreProcess(e){this.preProcessHandler=e,X.log(`Registered pre-process handler`)}onMessagePostProcess(e){this.postProcessHandler=e,X.log(`Registered post-process handler`)}onRaw(e,t){this.rawHandler={handler:e,fields:t},X.log(`Registered raw webhook handler${t?` for fields: ${t.join(`, `)}`:``}`)}onFlow(e,t){this.flowHandlers.set(e,t),X.log(`Registered flow handler for ${e}`)}on(e,t){ur(e,`on`),this.fieldHandlers.set(e,t),X.log(`Registered ${e} handler`)}off(e){ur(e,`off`),this.fieldHandlers.delete(e),X.log(`Removed ${e} handler`)}onText(e){this.messageHandlers.set(`text`,e),X.log(`Registered text message handler`)}onImage(e){this.messageHandlers.set(`image`,e),X.log(`Registered image message handler`)}onVideo(e){this.messageHandlers.set(`video`,e),X.log(`Registered video message handler`)}onAudio(e){this.messageHandlers.set(`audio`,e),X.log(`Registered audio message handler`)}onDocument(e){this.messageHandlers.set(`document`,e),X.log(`Registered document message handler`)}onSticker(e){this.messageHandlers.set(`sticker`,e),X.log(`Registered sticker message handler`)}onInteractive(e){this.messageHandlers.set(`interactive`,e),X.log(`Registered interactive message handler`)}onButton(e){this.messageHandlers.set(`button`,e),X.log(`Registered button message handler`)}onLocation(e){this.messageHandlers.set(`location`,e),X.log(`Registered location message handler`)}onContacts(e){this.messageHandlers.set(`contacts`,e),X.log(`Registered contacts message handler`)}onReaction(e){this.messageHandlers.set(`reaction`,e),X.log(`Registered reaction message handler`)}onOrder(e){this.messageHandlers.set(`order`,e),X.log(`Registered order message handler`)}onSystem(e){this.messageHandlers.set(`system`,e),X.log(`Registered system message handler`)}onAccountUpdate(e){this.on(`account_update`,e)}onAccountReviewUpdate(e){this.on(`account_review_update`,e)}onAccountAlerts(e){this.on(`account_alerts`,e)}onBusinessCapabilityUpdate(e){this.on(`business_capability_update`,e)}onPhoneNumberNameUpdate(e){this.on(`phone_number_name_update`,e)}onPhoneNumberQualityUpdate(e){this.on(`phone_number_quality_update`,e)}onMessageTemplateStatusUpdate(e){this.on(`message_template_status_update`,e)}onTemplateCategoryUpdate(e){this.on(`template_category_update`,e)}onMessageTemplateQualityUpdate(e){this.on(`message_template_quality_update`,e)}onFlows(e){this.on(`flows`,e)}onSecurity(e){this.on(`security`,e)}onHistory(e){this.on(`history`,e)}onSmbMessageEchoes(e){this.on(`smb_message_echoes`,e)}onSmbAppStateSync(e){this.on(`smb_app_state_sync`,e)}onAccountSettingsUpdate(e){this.on(`account_settings_update`,e)}onAutomaticEvents(e){this.on(`automatic_events`,e)}onBusinessStatusUpdate(e){this.on(`business_status_update`,e)}onBusinessUsernameUpdates(e){this.on(`business_username_updates`,e)}onCalls(e){this.on(`calls`,e)}onGroupLifecycleUpdate(e){this.on(`group_lifecycle_update`,e)}onGroupParticipantsUpdate(e){this.on(`group_participants_update`,e)}onGroupSettingsUpdate(e){this.on(`group_settings_update`,e)}onGroupStatusUpdate(e){this.on(`group_status_update`,e)}onMessageEchoes(e){this.on(`message_echoes`,e)}onMessageTemplateComponentsUpdate(e){this.on(`message_template_components_update`,e)}onMessagingHandovers(e){this.on(`messaging_handovers`,e)}onPartnerSolutions(e){this.on(`partner_solutions`,e)}onPaymentConfigurationUpdate(e){this.on(`payment_configuration_update`,e)}onStandby(e){this.on(`standby`,e)}onTemplateCorrectCategoryDetection(e){this.on(`template_correct_category_detection`,e)}onTrackingEvents(e){this.on(`tracking_events`,e)}onUserPreferences(e){this.on(`user_preferences`,e)}offMessage(e){this.messageHandlers.delete(e),X.log(`Removed message handler for ${e}`)}offMessagePreProcess(){this.preProcessHandler=void 0,X.log(`Removed pre-process handler`)}offMessagePostProcess(){this.postProcessHandler=void 0,X.log(`Removed post-process handler`)}offStatus(){this.statusHandler=void 0,X.log(`Removed status handler`)}offUserAction(){this.userActionHandler=void 0,X.log(`Removed user action handler`)}offRaw(){this.rawHandler=void 0,X.log(`Removed raw webhook handler`)}offFlow(e){this.flowHandlers.delete(e),X.log(`Removed flow handler for ${e}`)}removeAllHandlers(){this.messageHandlers.clear(),this.statusHandler=void 0,this.userActionHandler=void 0,this.preProcessHandler=void 0,this.postProcessHandler=void 0,this.rawHandler=void 0,this.flowHandlers.clear(),this.fieldHandlers.clear(),X.log(`Removed all handlers`)}getClient(){return this.client}getConfig(){return this.config}},dr=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 rr(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}},fr=class extends dr{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 pr=new Map;function mr(e){return`express:${e.phoneNumberId??`default`}`}function hr(e){let t=mr(e),n=pr.get(t);if(n)return n;let r=new fr(e),i={...r.getHandlers(),destroy:()=>{r.webhookProcessor.removeAllHandlers(),pr.delete(t)}};return pr.set(t,i),i}const gr=new Map;function _r(e){return`fastify:${e.phoneNumberId??`default`}`}function vr(e,t){e.code(t.status);for(let[n,r]of Object.entries(t.headers))e.header(n,r);return e.send(t.body)}function yr(e){return e.code(500).header(`Content-Type`,`application/json`).send(JSON.stringify({error:`Internal Server Error`}))}function br(e,t){if(typeof e!=`object`||!e)return null;let n=e[t];return Array.isArray(n)?typeof n[0]==`string`?n[0]:null:typeof n==`string`?n:null}function xr(e){let t=new Headers;for(let[n,r]of Object.entries(e))r!==void 0&&(n===`content-length`||n===`transfer-encoding`||t.set(n,Array.isArray(r)?r.join(`, `):r));return t}function Sr(e){if(e.rawBody!==void 0)return e.rawBody;if(!(e.body===void 0||e.body===null))return typeof e.body==`string`?e.body:JSON.stringify(e.body)}function Cr(e){let t=e.method===`GET`||e.method===`HEAD`?void 0:Sr(e);return new Request(rr(e.headers,e.url),{method:e.method,headers:xr(e.headers),body:t})}function wr(e){let t=_r(e),n=gr.get(t);if(n)return n;let r=Tr(e,t);return gr.set(t,r),r}function Tr(e,t){let n=new Z(e),r=async(e,t)=>{try{return vr(t,await n.processVerification(br(e.query,`hub.mode`),br(e.query,`hub.verify_token`),br(e.query,`hub.challenge`)))}catch(e){return console.error(`Webhook verification error:`,e),yr(t)}},i=async(e,t)=>{try{return vr(t,await n.processWebhook(Cr(e)))}catch(e){return console.error(`Webhook processing error:`,e),yr(t)}};return{GET:r,POST:i,webhook:async(e,t)=>{switch(e.method.toUpperCase()){case`GET`:return r(e,t);case`POST`:return i(e,t);default:return t.code(405).header(`Content-Type`,`application/json`).header(`Allow`,`GET, POST`).send(JSON.stringify({error:`Method Not Allowed`}))}},flow:async(e,t)=>{try{return vr(t,await n.processFlow(Cr(e)))}catch(e){return console.error(`Flow processing error:`,e),yr(t)}},processor:n,destroy:()=>{n.removeAllHandlers(),gr.delete(t)}}}const Er=new Map;function Dr(e){return`hono:${e.phoneNumberId??`default`}`}function Or(e){return new Response(e.body,{status:e.status,headers:e.headers})}function kr(){return new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}async function Ar(e){let t=e.req.raw;return!t.bodyUsed||!e.req.text?t:new Request(t.url,{method:t.method,headers:t.headers,body:await e.req.text()})}function jr(e){let t=Dr(e),n=Er.get(t);if(n)return n;let r=Mr(e,t);return Er.set(t,r),r}function Mr(e,t){let n=new Z(e),r=async e=>{try{let{searchParams:t}=new URL(e.req.raw.url);return Or(await n.processVerification(t.get(`hub.mode`),t.get(`hub.verify_token`),t.get(`hub.challenge`)))}catch(e){return console.error(`Webhook verification error:`,e),kr()}},i=async e=>{try{return Or(await n.processWebhook(await Ar(e)))}catch(e){return console.error(`Webhook processing error:`,e),kr()}};return{GET:r,POST:i,webhook:async e=>{switch(e.req.raw.method.toUpperCase()){case`GET`:return r(e);case`POST`:return i(e);default:return new Response(JSON.stringify({error:`Method Not Allowed`}),{status:405,headers:{"Content-Type":`application/json`,Allow:`GET, POST`}})}},flow:async e=>{try{return Or(await n.processFlow(await Ar(e)))}catch(e){return console.error(`Flow processing error:`,e),kr()}},processor:n,destroy:()=>{n.removeAllHandlers(),Er.delete(t)}}}const Nr=new Map;function Pr(e){return`nextjs-app:${e.phoneNumberId??`default`}`}function Fr(e){let t=Pr(e),n=Nr.get(t);if(n)return n;let r=Ir(e,t);return Nr.set(t,r),r}function Ir(e,t){let n=new Z(e);return{GET:async e=>{try{let{searchParams:t}=new URL(e.url),r=t.get(`hub.mode`),i=t.get(`hub.verify_token`),a=t.get(`hub.challenge`),o=await n.processVerification(r,i,a);return new Response(o.body,{status:o.status,headers:o.headers})}catch(e){return console.error(`Webhook verification error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let t=await n.processWebhook(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}},webhook:{GET:async e=>{try{let{searchParams:t}=new URL(e.url),r=t.get(`hub.mode`),i=t.get(`hub.verify_token`),a=t.get(`hub.challenge`),o=await n.processVerification(r,i,a);return new Response(o.body,{status:o.status,headers:o.headers})}catch(e){return console.error(`Webhook verification error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let t=await n.processWebhook(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}}},flow:{GET:async e=>{try{let t=await n.processFlow(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Flow GET error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}},POST:async e=>{try{let t=await n.processFlow(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Flow POST error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}}},processor:n,destroy:()=>{n.removeAllHandlers(),Nr.delete(t)}}}var Lr=class extends dr{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 Rr=new Map;function zr(e){return`nextjs-page:${e.phoneNumberId??`default`}`}function Br(e){let t=zr(e),n=Rr.get(t);if(n)return n;let r=new Lr(e),i={...r.getHandlers(),destroy:()=>{r.webhookProcessor.removeAllHandlers(),Rr.delete(t)}};return Rr.set(t,i),i}function Vr(e){switch(e.type){case`text`:return e.text.body;case`image`:return e.image.caption||`[Image]`;case`video`:return e.video.caption||`[Video]`;case`audio`:return e.audio.voice?`[Voice Message]`:`[Audio]`;case`document`:return e.document.caption||e.document.filename||`[Document]`;case`sticker`:return e.sticker.animated?`[Animated Sticker]`:`[Sticker]`;case`interactive`:{let t=e.interactive;return t.type===`button_reply`?t.button_reply.title:t.type===`list_reply`?t.list_reply.title:t.type===`nfm_reply`?t.nfm_reply.body||t.nfm_reply.name||`[Form Reply]`:`[Interactive]`}case`button`:return e.button.text;case`location`:return e.location.name||e.location.address||`📍 ${e.location.latitude}, ${e.location.longitude}`;case`contacts`:{let t=e.contacts.map(e=>e.name.formatted_name);return t.length===1?`👤 ${t[0]}`:`👤 ${t.length} contacts`}case`reaction`:return e.reaction.emoji||`[Reaction removed]`;case`order`:{let t=e.order.product_items.length;return`🛒 Order: ${t} item${t>1?`s`:``}`}case`system`:return e.system.body;case`unsupported`:return`[Unsupported message]`;default:return`[${e.type}]`}}const Hr=(e,t)=>z(`generateXHub256Sig`).createHmac(`sha256`,t).update(e,`utf-8`).digest(`hex`),Ur=(e,t)=>on(t,e);function Wr(e){return e.type===`text`}function Gr(e){return e.type===`image`}function Kr(e){return e.type===`video`}function qr(e){return e.type===`audio`}function Jr(e){return e.type===`document`}function Yr(e){return e.type===`sticker`}function Q(e){return e.type===`interactive`}function Xr(e){return e.type===`button`}function Zr(e){return e.type===`location`}function Qr(e){return e.type===`contacts`}function $r(e){return e.type===`reaction`}function ei(e){return e.type===`order`}function ti(e){return e.type===`system`}function ni(e){return Q(e)&&e.interactive.type===`button_reply`}function ri(e){return Q(e)&&e.interactive.type===`list_reply`}function ii(e){return Q(e)&&e.interactive.type===`nfm_reply`}function ai(e){return Gr(e)?{id:e.image.id,mimeType:e.image.mime_type,sha256:e.image.sha256,caption:e.image.caption}:Kr(e)?{id:e.video.id,mimeType:e.video.mime_type,sha256:e.video.sha256,caption:e.video.caption}:qr(e)?{id:e.audio.id,mimeType:e.audio.mime_type,sha256:e.audio.sha256,voice:e.audio.voice}:Jr(e)?{id:e.document.id,mimeType:e.document.mime_type,sha256:e.document.sha256,caption:e.document.caption,filename:e.document.filename}:Yr(e)?{id:e.sticker.id,mimeType:e.sticker.mime_type,sha256:e.sticker.sha256,animated:e.sticker.animated}:null}function oi(e){return Q(e)?e.interactive.type===`button_reply`?{type:`button_reply`,id:e.interactive.button_reply.id,title:e.interactive.button_reply.title}:e.interactive.type===`list_reply`?{type:`list_reply`,id:e.interactive.list_reply.id,title:e.interactive.list_reply.title,description:e.interactive.list_reply.description}:e.interactive.type===`nfm_reply`?{type:`nfm_reply`,id:e.interactive.nfm_reply.name,title:e.interactive.nfm_reply.body,responseJson:e.interactive.nfm_reply.response_json}:null:null}function si(e){return Zr(e)?{latitude:e.location.latitude,longitude:e.location.longitude,name:e.location.name,address:e.location.address,url:e.location.url}:null}function ci(e){return Qr(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 li(e){return $r(e)?{messageId:e.reaction.message_id,emoji:e.reaction.emoji||null}:null}function ui(e){return ei(e)?{catalogId:e.order.catalog_id,text:e.order.text,items:e.order.product_items.map(e=>({productId:e.product_retailer_id,quantity:e.quantity,price:e.item_price,currency:e.currency}))}:null}const di={Authentication:`AUTHENTICATION`,Marketing:`MARKETING`,Utility:`UTILITY`},fi={Authentication:`authentication`,Service:`service`,Utility:`utility`},pi={Approved:`APPROVED`,Pending:`PENDING`,Rejected:`REJECTED`},mi={Get:`GET`,Post:`POST`,Put:`PUT`,Delete:`DELETE`},hi={Audio:`audio`,Contacts:`contacts`,Document:`document`,Image:`image`,Interactive:`interactive`,Location:`location`,Reaction:`reaction`,Sticker:`sticker`,Template:`template`,Text:`text`,Video:`video`,Button:`button`,Order:`order`,System:`system`,Unsupported:`unsupported`,Unknown:`unknown`,Statuses:`statuses`,All:`*`},gi={Action:`ACTION`,CouponCode:`COUPON_CODE`,Currency:`CURRENCY`,DateTime:`DATE_TIME`,Document:`DOCUMENT`,ExpirationTimeMs:`EXPIRATION_TIME_MS`,Image:`IMAGE`,LimitedTimeOffer:`LIMITED_TIME_OFFER`,Location:`LOCATION`,OrderStatus:`ORDER_STATUS`,Payload:`PAYLOAD`,Product:`PRODUCT`,Text:`TEXT`,TtlMinutes:`TTL_MINUTES`,Video:`VIDEO`,WebviewInteraction:`WEBVIEW_INTERACTION`,WebviewPresentation:`WEBVIEW_PRESENTATION`},_i={Button:`button`,List:`list`,Product:`product`,ProductList:`product_list`,CtaUrl:`cta_url`,Carousel:`carousel`,LocationRequest:`location_request_message`,AddressMessage:`address_message`,Flow:`flow`,VoiceCall:`voice_call`},vi={First:1,Second:2,Third:3,Fourth:4,Fifth:5},yi={Catalog:`CATALOG`,CopyCode:`COPY_CODE`,Flow:`FLOW`,Mpm:`MPM`,OrderDetails:`ORDER_DETAILS`,QuickReply:`QUICK_REPLY`,Reminder:`REMINDER`,Url:`URL`,VoiceCall:`VOICE_CALL`},bi={Header:`HEADER`,Body:`BODY`,Button:`BUTTON`,Footer:`FOOTER`},xi={BusinessInitiated:`business_initiated`,CustomerInitiated:`customer_initiated`,ReferralConversion:`referral_conversion`},Si={Delivered:`delivered`,Read:`read`,Sent:`sent`},Ci={Mp4:`video/mp4`,Threegp:`video/3gp`},wi={Webp:`image/webp`},Ti={Jpeg:`image/jpeg`,Png:`image/png`},Ei={Text:`text/plain`,Pdf:`application/pdf`,Ppt:`application/vnd.ms-powerpoint`,Word:`application/msword`,Excel:`application/vnd.ms-excel`,OpenDoc:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,OpenPres:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,OpenSheet:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`},Di={Aac:`audio/aac`,Mp4:`audio/mp4`,Mpeg:`audio/mpeg`,Amr:`audio/amr`,Ogg:`audio/ogg`},Oi={Audio:`audio`,Button:`button`,Document:`document`,Text:`text`,Image:`image`,Interactive:`interactive`,Order:`order`,Sticker:`sticker`,System:`system`,Unknown:`unknown`,Video:`video`},ki={CustomerChangedNumber:`customer_changed_number`,CustomerIdentityChanged:`customer_identity_changed`,UserChangedNumber:`user_changed_number`,UserIdentityChanged:`user_identity_changed`,UserChangedUserId:`user_changed_user_id`},Ai={Ad:`ad`,Post:`post`},ji={Sms:`SMS`,Voice:`VOICE`},Mi={Afrikaans:`af`,Albanian:`sq`,Arabic:`ar`,Azerbaijani:`az`,Bengali:`bn`,Bulgarian:`bg`,Catalan:`ca`,Chinese_CHN:`zh_CN`,Chinese_HKG:`zh_HK`,Chinese_TAI:`zh_TW`,Croatian:`hr`,Czech:`cs`,Danish:`da`,Dutch:`nl`,English:`en`,English_UK:`en_GB`,English_US:`en_US`,Estonian:`et`,Filipino:`fil`,Finnish:`fi`,French:`fr`,Georgian:`ka`,German:`de`,Greek:`el`,Gujarati:`gu`,Hausa:`ha`,Hebrew:`he`,Hindi:`hi`,Hungarian:`hu`,Indonesian:`id`,Irish:`ga`,Italian:`it`,Japanese:`ja`,Kannada:`kn`,Kazakh:`kk`,Kinyarwanda:`rw_RW`,Korean:`ko`,Kyrgyz_Kyrgyzstan:`ky_KG`,Lao:`lo`,Latvian:`lv`,Lithuanian:`lt`,Macedonian:`mk`,Malay:`ms`,Malayalam:`ml`,Marathi:`mr`,Norwegian:`nb`,Persian:`fa`,Polish:`pl`,Portuguese_BR:`pt_BR`,Portuguese_POR:`pt_PT`,Punjabi:`pa`,Romanian:`ro`,Russian:`ru`,Serbian:`sr`,Slovak:`sk`,Slovenian:`sl`,Spanish:`es`,Spanish_ARG:`es_AR`,Spanish_SPA:`es_ES`,Spanish_MEX:`es_MX`,Swahili:`sw`,Swedish:`sv`,Tamil:`ta`,Telugu:`te`,Thai:`th`,Turkish:`tr`,Ukrainian:`uk`,Urdu:`ur`,Uzbek:`uz`,Vietnamese:`vi`,Zulu:`zu`},Ni={AU:`AU`,ID:`ID`,IN:`IN`,JP:`JP`,SG:`SG`,KR:`KR`,DE:`DE`,CH:`CH`,GB:`GB`,BR:`BR`,BH:`BH`,ZA:`ZA`,AE:`AE`,CA:`CA`},Pi=3600*1e3,Fi=24*Pi,Ii=72*Pi,Li=168*Pi,Ri=1e11;function $(e,t){let n;if(e instanceof Date)n=e.getTime();else if(typeof e==`number`)n=Math.abs(e)<Ri?e*1e3:e;else if(typeof e==`string`){let t=e.trim();if(/^\d+(\.\d+)?$/.test(t)){let e=Number(t);n=e<Ri?e*1e3:e}else n=t===``?NaN:Date.parse(t)}else n=NaN;if(!Number.isFinite(n)||!Number.isFinite(new Date(n).getTime()))throw new T(`${t} is not a valid timestamp: ${String(e)}`);return n}function zi(e,t,n){if(e===void 0)return n;if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw new T(`${t} must be a non-negative number of milliseconds`);return e}function Bi(e,t,n,r){if(!Number.isFinite(new Date(t).getTime()))throw new T(`Window expiry is outside the supported timestamp range`);let i=Math.max(0,t-e),a=t-r,o=Math.min(Math.max(0,a-n),i);return{isOpen:o>0,expiresAt:new Date(t),remainingMs:o}}const Vi=Object.freeze({isOpen:!1,expiresAt:null,remainingMs:0});function Hi(e,t={}){let n=zi(t.safetyMarginMs,`safetyMarginMs`,0),r=t.now===void 0?Date.now():$(t.now,`now`);if(e==null)return{...Vi};let i=$(e,`lastInboundAt`);return Bi(i,i+Fi,r,n)}function Ui(e,t={}){return Hi(e,t).isOpen}function Wi(e,t={}){let n=zi(t.safetyMarginMs,`safetyMarginMs`,0),r=zi(t.durationMs,`durationMs`,Ii),i=t.now===void 0?Date.now():$(t.now,`now`);if(e==null)return{...Vi};let a=$(e,`openedAt`);return Bi(a,t.expiresAt===void 0?a+r:$(t.expiresAt,`expiresAt`),i,n)}const Gi={sent:1,failed:2,delivered:3,read:4};function Ki(e){return e&&Object.hasOwn(Gi,e)?Gi[e]:0}function qi(e,t){return Ki(e)-Ki(t)}function Ji(e,t){return e==null||e===``?!0:qi(t,e)>0}function Yi(e,t){return e==null||e===``||qi(t,e)>0?t:e}export{ge as AUTHORIZATION_ERROR_CODES,Di as AudioMediaTypes,ae as AudioMediaTypesEnum,xe as BLOCK_USER_ERROR_CODES,at as BlockUsersApi,ot as BusinessApi,Tt as BusinessProfileApi,pe as BusinessVerticalEnum,vi as ButtonPosition,f as ButtonPositionEnum,Se as CALLING_ERROR_CODES,Fi as CUSTOMER_SERVICE_WINDOW_MS,st as CallingApi,di as Category,a as CategoryEnum,ct as CommerceApi,bi as ComponentType,m as ComponentTypesEnum,lt as ContactBookApi,xi as ConversationTypes,g as ConversationTypesEnum,de as CurrencyCodesEnum,Ni as DataLocalizationRegion,fe as DataLocalizationRegionEnum,Ei as DocumentMediaTypes,ie as DocumentMediaTypesEnum,ut as EncryptionApi,be as FLOW_ERROR_CODES,Ii as FREE_ENTRY_POINT_WINDOW_MS,mt as FlowActionEnum,dt as FlowApi,pt as FlowCategoryEnum,ft as FlowStatusEnum,ht as FlowTypeEnum,Ce as GROUP_ERROR_CODES,gt as GroupsApi,mi as HttpMethods,c as HttpMethodsEnum,ve as INTEGRITY_ERROR_CODES,Ti as ImageMediaTypes,re as ImageMediaTypesEnum,_i as InteractiveTypes,d as InteractiveTypesEnum,Mi as Languages,ue as LanguagesEnum,P as Logger,Li as MAX_FREE_ENTRY_POINT_WINDOW_MS,_t as MarketingMessagesApi,vt as MediaApi,In as MemoryDedupeStore,O as MessageApi,O as MessagesApi,fi as MessageCategory,o as MessageCategoryEnum,St as MessageHistoryApi,hi as MessageTypes,l as MessageTypesEnum,gi as ParametersTypes,u as ParametersTypesEnum,Ct as PaymentsApi,wt as PhoneNumberApi,Et as QrCodeApi,Ai as ReferralSourceTypes,ce as ReferralSourceTypesEnum,Dt as RegistrationApi,ji as RequestCodeMethods,le as RequestCodeMethodsEnum,ye as SEND_MESSAGE_ERROR_CODES,Ot as SolutionsApi,Si as Status,ee as StatusEnum,wi as StickerMediaTypes,ne as StickerMediaTypesEnum,yi as SubType,p as SubTypeEnum,ki as SystemChangeTypes,se as SystemChangeTypesEnum,_e as THROTTLING_ERROR_CODES,Bt as TemplateApi,pi as TemplateStatus,s as TemplateStatusEnum,Ht as ThreadControlApi,Ut as TwoStepVerificationApi,Ci as VideoMediaTypes,te as VideoMediaTypesEnum,me as WHATSAPP_ERROR_CODES,Gt as WabaAccountReviewStatus,qt as WabaAccountStatus,Wt as WabaApi,Jt as WabaBusinessVerificationStatus,h as WabaConfigEnum,Kt as WabaHealthStatusCanSendMessage,Z as WebhookProcessor,Oi as WebhookTypes,oe as WebhookTypesEnum,Fn as WhatsApp,Fn as default,y as WhatsAppApiError,b as WhatsAppAuthorizationError,Ue as WhatsAppBlockUserError,We as WhatsAppCallingError,v as WhatsAppError,He as WhatsAppFlowError,Ge as WhatsAppGroupError,S as WhatsAppIntegrityError,Ke as WhatsAppNetworkError,C as WhatsAppSendMessageError,x as WhatsAppThrottlingError,qe as WhatsAppUnknownError,T as WhatsAppValidationError,k as buildFieldsQueryString,Ui as canSendFreeformMessage,qi as compareMessageStatus,rr as constructFullUrl,Mt as createAuthenticationTemplate,Nt as createCatalogTemplate,Pt as createCouponTemplate,Ft as createLimitedTimeOfferTemplate,Lt as createMPMTemplate,It as createMediaCardCarouselTemplate,jt as createOTPTemplate,Rt as createProductCardCarouselTemplate,zt as createSPMTemplate,At as createTemplate,w as createWhatsAppApiError,pn as decryptFlowRequest,vn as decryptFlowRequestAsync,mn as encryptFlowResponse,yn as encryptFlowResponseAsync,hr as expressWebhookHandler,Vr as extractMessageText,wr as fastifyWebhookHandler,un as formatConfigTable,fn as generateEncryption,Hr as generateXHub256Sig,Ur as generateXHub256SigAsync,ci as getContactsInfo,Hi as getCustomerServiceWindow,Wi as getFreeEntryPointWindow,oi as getInteractiveReply,si as getLocationInfo,ai as getMediaInfo,ui as getOrderInfo,li as getReactionInfo,jr as honoWebhookHandler,Ne as isApiPermissionErrorCode,qr as isAudioMessage,Pe as isAuthorizationErrorCode,ze as isBlockUserErrorCode,Xr as isButtonMessage,ni as isButtonReply,Be as isCallingErrorCode,Qr as isContactsMessage,Jr as isDocumentMessage,Vn as isFlowDataExchangeRequest,Re as isFlowErrorCode,Hn as isFlowErrorRequest,Un as isFlowPingRequest,Ve as isGroupErrorCode,Gr as isImageMessage,Ie as isIntegrityErrorCode,Q as isInteractiveMessage,ri as isListReply,Zr as isLocationMessage,Ji as isMessageStatusAdvance,E as isMetaError,ii as isNfmReply,ei as isOrderMessage,$r as isReactionMessage,Le as isSendMessageErrorCode,Yr as isStickerMessage,ti as isSystemMessage,Wr as isTextMessage,Fe as isThrottlingErrorCode,nr as isValidWebhookSignature,Kr as isVideoMessage,Je as isWhatsAppApiErrorResponse,Ye as isWhatsAppAuthorizationError,et as isWhatsAppBlockUserError,tt as isWhatsAppCallingError,Me as isWhatsAppErrorCode,$e as isWhatsAppFlowError,nt as isWhatsAppGroupError,Ze as isWhatsAppIntegrityError,Qe as isWhatsAppSendMessageError,Xe as isWhatsAppThrottlingError,Fr as nextjsAppWebhookHandler,Br as nextjsPagesWebhookHandler,rt as normalizeMetaError,_ as objectToQueryString,En as parseRateLimitHeaders,Tn as parseRetryAfter,er as processFlowRequest,Zn as processWebhookMessages,Yi as resolveMessageStatus,tr as verifyWebhookSignature};
22
+ `)}function Fn(){return`3.12.1`}function In(){return`WhatsApp-Nodejs-SDK/${Fn()} (${Qt()})`}const G=new N(`WHATSAPP`,I());var Ln=class{config;requester;blockUsers;business;calling;commerce;contactBook;groups;marketingMessages;messageHistory;messages;media;payments;phoneNumbers;solutions;threadControl;twoStepVerification;flows;businessProfile;templates;encryption;qrCode;registration;waba;constructor(e){Pn(),this.config=un(e),this.requester=new Nn(this.config.CLOUD_API_VERSION,this.config.WA_PHONE_NUMBER_ID,this.config.CLOUD_API_ACCESS_TOKEN,this.config.WA_BUSINESS_ACCOUNT_ID,this.getUserAgent(),this.config.retry,this.config.onRateLimitInfo,this.config.fetch,{onRequest:this.config.onRequest,onResponse:this.config.onResponse}),this.blockUsers=new ot(this.config,this.requester),this.business=new st(this.config,this.requester),this.calling=new ct(this.config,this.requester),this.commerce=new lt(this.config,this.requester),this.contactBook=new ut(this.config,this.requester),this.groups=new _t(this.config,this.requester),this.marketingMessages=new vt(this.config,this.requester),this.messageHistory=new Ct(this.config,this.requester),this.messages=new D(this.config,this.requester),this.media=new yt(this.config,this.requester),this.payments=new wt(this.config,this.requester),this.phoneNumbers=new Tt(this.config,this.requester),this.solutions=new kt(this.config,this.requester),this.threadControl=new Ut(this.config,this.requester),this.twoStepVerification=new Wt(this.config,this.requester),this.flows=new ft(this.config,this.requester),this.businessProfile=new Et(this.config,this.requester),this.templates=new Vt(this.config,this.requester),this.encryption=new dt(this.config,this.requester),this.qrCode=new Dt(this.config,this.requester),this.registration=new Ot(this.config,this.requester),this.waba=new Gt(this.config,this.requester),G.log(`\n${dn(this.config)}`)}updateTimeout(e){this.config.REQUEST_TIMEOUT=e,this.requester.updateTimeout(e),G.log(`Timeout updated to ${e}ms`)}updateSenderNumberId(e){this.config.WA_PHONE_NUMBER_ID=e,G.log(`Sender number ID updated to ${e}`)}updateAccessToken(e){this.config.CLOUD_API_ACCESS_TOKEN=e,this.requester.updateAccessToken(e),G.log(`Access token updated`)}getLastRateLimitInfo(){return this.requester.getLastRateLimitInfo()}version(){return Fn()}static get Enums(){return i}getUserAgent(){return In()}generateEncryption(e){return pn(e||this.config.FLOW_API_PASSPHRASE)}},Rn=class{maxEntries;entries=new Map;constructor(e={}){let t=e.maxEntries??1e4;if(!Number.isInteger(t)||t<1)throw Error(`MemoryDedupeStore maxEntries must be a positive integer, got ${t}`);this.maxEntries=t}async has(e){return this.lookup(e,Date.now())!==void 0}async setIfAbsent(e,t){let n=Date.now(),r=this.lookup(e,n);return r===void 0?(this.entries.set(e,n+t*1e3),this.evict(n),!0):(this.entries.delete(e),this.entries.set(e,r),!1)}get size(){return this.entries.size}clear(){this.entries.clear()}lookup(e,t){let n=this.entries.get(e);if(n!==void 0){if(n<=t){this.entries.delete(e);return}return n}}evict(e){for(let[t,n]of this.entries)n<=e&&this.entries.delete(t);for(let e of this.entries.keys()){if(this.entries.size<=this.maxEntries)break;this.entries.delete(e)}}};function zn(e){if(!e)return;let t=e===!0?{}:e,n=t.ttlSeconds??86400;if(!Number.isFinite(n)||n<=0)throw Error(`dedupe.ttlSeconds must be a positive number, got ${n}`);return{store:t.store??new Rn,ttlSeconds:n}}function Bn(e){return typeof e==`object`&&!!e}function K(e){return typeof e==`string`}const Vn=[`data_exchange`,`INIT`,`BACK`],Hn=[`data_exchange`,`INIT`];function Un(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=Vn.includes(t),s=r===void 0||K(r)&&r!==`SUCCESS`,c=t===`data_exchange`||Bn(i);return a&&o&&s&&c}function Wn(e){if(!(`flow_token`in e&&K(e.flow_token)&&`action`in e))return!1;let{action:t,screen:n,data:r}=e,i=Hn.includes(t),a=K(n),o=Bn(r)&&`error_key`in r&&K(r.error)&&`error_message`in r&&K(r.error_message);return i&&a&&o}function Gn(e){return`action`in e&&e.action===`ping`}const q=new N(`WEBHOOK_UTILS`,I()),Kn={account_update:`accountUpdateHandler`,account_review_update:`accountReviewUpdateHandler`,account_alerts:`accountAlertsHandler`,account_settings_update:`accountSettingsUpdateHandler`,automatic_events:`automaticEventsHandler`,business_capability_update:`businessCapabilityUpdateHandler`,business_status_update:`businessStatusUpdateHandler`,business_username_updates:`businessUsernameUpdatesHandler`,calls:`callsHandler`,flows:`flowsHandler`,group_lifecycle_update:`groupLifecycleUpdateHandler`,group_participants_update:`groupParticipantsUpdateHandler`,group_settings_update:`groupSettingsUpdateHandler`,group_status_update:`groupStatusUpdateHandler`,history:`historyHandler`,message_echoes:`messageEchoesHandler`,message_template_components_update:`messageTemplateComponentsUpdateHandler`,message_template_quality_update:`messageTemplateQualityUpdateHandler`,message_template_status_update:`messageTemplateStatusUpdateHandler`,messaging_handovers:`messagingHandoversHandler`,partner_solutions:`partnerSolutionsHandler`,payment_configuration_update:`paymentConfigurationUpdateHandler`,phone_number_name_update:`phoneNumberNameUpdateHandler`,phone_number_quality_update:`phoneNumberQualityUpdateHandler`,security:`securityHandler`,smb_app_state_sync:`smbAppStateSyncHandler`,smb_message_echoes:`smbMessageEchoesHandler`,standby:`standbyHandler`,template_category_update:`templateCategoryUpdateHandler`,template_correct_category_detection:`templateCorrectCategoryDetectionHandler`,tracking_events:`trackingEventsHandler`,user_preferences:`userPreferencesHandler`};function qn(e){return Object.hasOwn(Kn,e)}const Jn={calls:e=>Xn(`calls`,Yn(e?.calls,e=>e?.id?`${e.id}:${e.event}${e.call_status?`:${e.call_status}`:``}`:void 0)),smb_message_echoes:e=>Xn(`smb_message_echoes`,Yn(e?.message_echoes,e=>e?.id)),message_echoes:e=>Xn(`message_echoes`,Yn(e?.messaging,e=>e?.message?.mid))};function Yn(e,t){return Array.isArray(e)?e.map(t):void 0}function Xn(e,t){if(!(!t||t.length===0||t.some(e=>!e)))return`${e}:${t.join(`,`)}`}function Zn(e,t){let n=Jn[e];return n?.(t)}async function Qn(e,t){if(!e||!t)return!1;try{return await e.store.setIfAbsent(t,e.ttlSeconds)?!1:(q.log(`Skipping duplicate webhook delivery: ${t}`),!0)}catch(e){return q.error(`Dedupe store failed; processing the webhook anyway:`,{key:t,error:e}),!1}}async function $n(e,t,n,r={}){try{let i=await e.text();if(r.verifySignature){if(!r.appSecret)return q.error(`verifyWebhookSignature is on but appSecret is not configured; rejecting webhook`),new Response(JSON.stringify({error:`Webhook signature verification misconfigured`}),{status:500,headers:{"Content-Type":`application/json`}});if(!await rr(i,e.headers.get(`x-hub-signature-256`),r.appSecret))return q.warn(`Rejected webhook with missing or invalid X-Hub-Signature-256`),new Response(JSON.stringify({error:`Invalid signature`}),{status:401,headers:{"Content-Type":`application/json`}})}let a=JSON.parse(i),o={headers:e.headers,rawBody:i,method:e.method,url:e.url},s=r.dedupe?{store:r.dedupe.store,ttlSeconds:r.dedupe.ttlSeconds??86400}:void 0;if(n.rawHandler){let{rawHandler:e,rawHandlerFields:r}=n,i=a;if(r&&r.length>0){let e={...i,entry:i.entry.map(e=>({...e,changes:e.changes.filter(e=>r.includes(e.field))})).filter(e=>e.changes.length>0)};i=e.entry.length===0?null:e}i&&await e(t,i,o)}if(a.object!==`whatsapp_business_account`){let e=`Received webhook for non-WhatsApp event`;return q.warn(e),new Response(JSON.stringify({error:e}),{status:404})}let c=[];for(let e of a.entry)try{let r=e.changes;for(let i of r){let r=i.field;if(r===`messages`)await sr(e.id,i.value,t,n,o,s);else if(qn(r)){let a=n.fieldHandlers?.get(r)??n[Kn[r]];await dr(e.id,{field:r,value:i.value},a,t,o,s)}else q.warn(`Unhandled webhook field: ${i.field}`)}}catch(t){let n=`Error processing webhook: ${t}`;q.error(n,{entry:e,error:t}),c.push(n)}return new Response(c.length>0?JSON.stringify({errors:c}):null,{status:200})}catch(e){return q.error(`Error processing webhook:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500})}}function er(){return{version:`3.0`,data:{status:`active`}}}function tr(){return{data:{acknowledged:!0}}}async function nr(e,t,n,r){try{let i=await e.text(),a={headers:e.headers,rawBody:i,method:e.method,url:e.url},o=e.headers.get(`x-hub-signature-256`),s=t.M4D_APP_SECRET||t.WEBHOOK_VERIFICATION_TOKEN||``;if(t.M4D_APP_SECRET||q.warn(`appSecret not configured; verifying Flow signature with the webhook verification token`),!await rr(i,o,s))return q.warn(`Invalid request signature`),new Response(JSON.stringify({error:`Unauthorized`}),{status:401});let{decryptedBody:c,aesKeyBuffer:l,initialVectorBuffer:u}=await yn(JSON.parse(i),t),d=Gn(c),f=Wn(c),p=Un(c),m;m=d?`ping`:f?`error`:p?`data_exchange`:`*`;let h=r.get(m);if(!h){if(m===`ping`)h=()=>er();else if(m===`error`)h=()=>tr();else if(h=r.get(`*`),!h)return q.warn(`No handler registered for flow type:`,{flowType:m,action:c.action}),new Response(JSON.stringify({error:`Handler not found`}),{status:404})}let g=await h(n,c,a);if(f){q.warn(`Flow error notification received`,{error:c.data});let e=g||tr();return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":`application/json`}})}if(d||p){let e=await bn(g,l,u);return new Response(e,{status:200,headers:{"Content-Type":`text/plain`}})}return q.warn(`Unknown flow request type:`,c),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})}}async function rr(e,t,n){if(!t||!n)return!1;let r=t.startsWith(`sha256=`)?t.slice(7):t,i=await sn(n,e);return on(r.toLowerCase(),i)}function ir(e,t,n){if(!t||!n)return!1;let r=R(`isValidWebhookSignature`),i=t.startsWith(`sha256=`)?t.slice(7):t,a=r.createHmac(`sha256`,n).update(e,`utf8`).digest(`hex`);return on(i.toLowerCase(),a)}function ar(e,t){return`${e[`x-forwarded-proto`]||`http`}://${e.host||`localhost`}${t||`/`}`}function or(e){return e.id?e.id:(e.type===`interactive`||e.type===`button`)&&`context`in e&&e.context?.id?e.context.id:``}async function sr(e,t,n,r,i,a){let o=t.metadata,s=e,c=o.display_phone_number,l=o.phone_number_id;if(`user_actions`in t&&t.user_actions){let e=t;for(let t of e.user_actions){let e={wabaId:s,phoneNumberId:l,displayPhoneNumber:c,action:t};await ur(r.userActionHandler,n,e,i)}return}if(`statuses`in t&&t.statuses){let e=t;for(let t of e.statuses){if(!r.statusHandler||await Qn(a,t.id?`status:${t.id}:${t.status}`:void 0))continue;let e={wabaId:s,phoneNumberId:l,displayPhoneNumber:c,status:t};await lr(r.statusHandler,n,e,i)}return}if(`messages`in t&&t.messages){let e=t,o=e.contacts?.[0]?.profile?.name||``;for(let t of e.messages){let u={wabaId:s,phoneNumberId:l,displayPhoneNumber:c,profileName:o,message:t,messageId:or(t),...e.conversation_context&&{conversationContext:e.conversation_context}},d=t.type,f=r.messageHandlers.get(d);!r.preProcessHandler&&!f&&!r.postProcessHandler||await Qn(a,u.messageId?`message:${u.messageId}`:void 0)||(await cr(r.preProcessHandler,n,u,i,`pre-process`),await cr(f,n,u,i,d),await cr(r.postProcessHandler,n,u,i,`post-process`))}}}async function cr(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 lr(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 ur(e,t,n,r){if(e)try{await e(t,n,r)}catch(e){q.error(`Error in user action handler:`,{error:e,actionType:n.action.action_type})}}async function dr(e,t,n,r,i,a){if(n&&!await Qn(a,Zn(t.field,t.value)))try{await n(r,{wabaId:e,value:t.value},i)}catch(n){q.error(`Error in ${t.field} handler:`,{error:n,wabaId:e})}}const J=new N(`WEBHOOK_PROCESSOR`,I());function fr(e,t){if(e===`messages`)throw Error(`${t}('messages') is not supported. Use onMessage/onText/... for messages, onStatus for statuses and onUserAction for marketing user actions.`);if(!qn(e))throw Error(`${t}('${e}'): unknown webhook field`)}var Y=class{config;client;messageHandlers=new Map;statusHandler=void 0;userActionHandler=void 0;preProcessHandler=void 0;postProcessHandler=void 0;rawHandler=void 0;flowHandlers=new Map;fieldHandlers=new Map;verifySignature;dedupe;constructor(e){this.config=un(e),this.verifySignature=e.verifyWebhookSignature===!0,this.dedupe=zn(e.dedupe),this.client=new Ln(e),J.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 $n(e,this.client,{messageHandlers:this.messageHandlers,statusHandler:this.statusHandler,userActionHandler:this.userActionHandler,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler,rawHandler:this.rawHandler?.handler,rawHandlerFields:this.rawHandler?.fields,fieldHandlers:this.fieldHandlers},{appSecret:this.config.M4D_APP_SECRET,verifySignature:this.verifySignature,dedupe:this.dedupe}),n=await t.text(),r=t.headers.get(`content-type`)||`application/json`;return{status:t.status,body:n,headers:{"Content-Type":r}}}catch(e){return J.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 nr(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 J.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),J.log(`Registered message handler for ${e}`)}onStatus(e){this.statusHandler=e,J.log(`Registered status handler`)}onUserAction(e){this.userActionHandler=e,J.log(`Registered user action handler`)}onMessagePreProcess(e){this.preProcessHandler=e,J.log(`Registered pre-process handler`)}onMessagePostProcess(e){this.postProcessHandler=e,J.log(`Registered post-process handler`)}onRaw(e,t){this.rawHandler={handler:e,fields:t},J.log(`Registered raw webhook handler${t?` for fields: ${t.join(`, `)}`:``}`)}onFlow(e,t){this.flowHandlers.set(e,t),J.log(`Registered flow handler for ${e}`)}on(e,t){fr(e,`on`),this.fieldHandlers.set(e,t),J.log(`Registered ${e} handler`)}off(e){fr(e,`off`),this.fieldHandlers.delete(e),J.log(`Removed ${e} handler`)}onText(e){this.messageHandlers.set(`text`,e),J.log(`Registered text message handler`)}onImage(e){this.messageHandlers.set(`image`,e),J.log(`Registered image message handler`)}onVideo(e){this.messageHandlers.set(`video`,e),J.log(`Registered video message handler`)}onAudio(e){this.messageHandlers.set(`audio`,e),J.log(`Registered audio message handler`)}onDocument(e){this.messageHandlers.set(`document`,e),J.log(`Registered document message handler`)}onSticker(e){this.messageHandlers.set(`sticker`,e),J.log(`Registered sticker message handler`)}onInteractive(e){this.messageHandlers.set(`interactive`,e),J.log(`Registered interactive message handler`)}onButton(e){this.messageHandlers.set(`button`,e),J.log(`Registered button message handler`)}onLocation(e){this.messageHandlers.set(`location`,e),J.log(`Registered location message handler`)}onContacts(e){this.messageHandlers.set(`contacts`,e),J.log(`Registered contacts message handler`)}onReaction(e){this.messageHandlers.set(`reaction`,e),J.log(`Registered reaction message handler`)}onOrder(e){this.messageHandlers.set(`order`,e),J.log(`Registered order message handler`)}onSystem(e){this.messageHandlers.set(`system`,e),J.log(`Registered system message handler`)}onAccountUpdate(e){this.on(`account_update`,e)}onAccountReviewUpdate(e){this.on(`account_review_update`,e)}onAccountAlerts(e){this.on(`account_alerts`,e)}onBusinessCapabilityUpdate(e){this.on(`business_capability_update`,e)}onPhoneNumberNameUpdate(e){this.on(`phone_number_name_update`,e)}onPhoneNumberQualityUpdate(e){this.on(`phone_number_quality_update`,e)}onMessageTemplateStatusUpdate(e){this.on(`message_template_status_update`,e)}onTemplateCategoryUpdate(e){this.on(`template_category_update`,e)}onMessageTemplateQualityUpdate(e){this.on(`message_template_quality_update`,e)}onFlows(e){this.on(`flows`,e)}onSecurity(e){this.on(`security`,e)}onHistory(e){this.on(`history`,e)}onSmbMessageEchoes(e){this.on(`smb_message_echoes`,e)}onSmbAppStateSync(e){this.on(`smb_app_state_sync`,e)}onAccountSettingsUpdate(e){this.on(`account_settings_update`,e)}onAutomaticEvents(e){this.on(`automatic_events`,e)}onBusinessStatusUpdate(e){this.on(`business_status_update`,e)}onBusinessUsernameUpdates(e){this.on(`business_username_updates`,e)}onCalls(e){this.on(`calls`,e)}onGroupLifecycleUpdate(e){this.on(`group_lifecycle_update`,e)}onGroupParticipantsUpdate(e){this.on(`group_participants_update`,e)}onGroupSettingsUpdate(e){this.on(`group_settings_update`,e)}onGroupStatusUpdate(e){this.on(`group_status_update`,e)}onMessageEchoes(e){this.on(`message_echoes`,e)}onMessageTemplateComponentsUpdate(e){this.on(`message_template_components_update`,e)}onMessagingHandovers(e){this.on(`messaging_handovers`,e)}onPartnerSolutions(e){this.on(`partner_solutions`,e)}onPaymentConfigurationUpdate(e){this.on(`payment_configuration_update`,e)}onStandby(e){this.on(`standby`,e)}onTemplateCorrectCategoryDetection(e){this.on(`template_correct_category_detection`,e)}onTrackingEvents(e){this.on(`tracking_events`,e)}onUserPreferences(e){this.on(`user_preferences`,e)}offMessage(e){this.messageHandlers.delete(e),J.log(`Removed message handler for ${e}`)}offMessagePreProcess(){this.preProcessHandler=void 0,J.log(`Removed pre-process handler`)}offMessagePostProcess(){this.postProcessHandler=void 0,J.log(`Removed post-process handler`)}offStatus(){this.statusHandler=void 0,J.log(`Removed status handler`)}offUserAction(){this.userActionHandler=void 0,J.log(`Removed user action handler`)}offRaw(){this.rawHandler=void 0,J.log(`Removed raw webhook handler`)}offFlow(e){this.flowHandlers.delete(e),J.log(`Removed flow handler for ${e}`)}removeAllHandlers(){this.messageHandlers.clear(),this.statusHandler=void 0,this.userActionHandler=void 0,this.preProcessHandler=void 0,this.postProcessHandler=void 0,this.rawHandler=void 0,this.flowHandlers.clear(),this.fieldHandlers.clear(),J.log(`Removed all handlers`)}getClient(){return this.client}getConfig(){return this.config}},pr=class{processor;constructor(e){this.processor=new Y(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 ar(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}},mr=class extends pr{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 hr=new Map;function gr(e){return`express:${e.phoneNumberId??`default`}`}function _r(e){let t=gr(e),n=hr.get(t);if(n)return n;let r=new mr(e),i={...r.getHandlers(),destroy:()=>{r.webhookProcessor.removeAllHandlers(),hr.delete(t)}};return hr.set(t,i),i}const vr=new Map;function yr(e){return`fastify:${e.phoneNumberId??`default`}`}function br(e,t){e.code(t.status);for(let[n,r]of Object.entries(t.headers))e.header(n,r);return e.send(t.body)}function X(e){return e.code(500).header(`Content-Type`,`application/json`).send(JSON.stringify({error:`Internal Server Error`}))}function xr(e,t){if(typeof e!=`object`||!e)return null;let n=e[t];return Array.isArray(n)?typeof n[0]==`string`?n[0]:null:typeof n==`string`?n:null}function Sr(e){let t=new Headers;for(let[n,r]of Object.entries(e))r!==void 0&&(n===`content-length`||n===`transfer-encoding`||t.set(n,Array.isArray(r)?r.join(`, `):r));return t}function Cr(e){if(e.rawBody!==void 0)return e.rawBody;if(!(e.body===void 0||e.body===null))return typeof e.body==`string`?e.body:JSON.stringify(e.body)}function wr(e){let t=e.method===`GET`||e.method===`HEAD`?void 0:Cr(e);return new Request(ar(e.headers,e.url),{method:e.method,headers:Sr(e.headers),body:t})}function Tr(e){let t=yr(e),n=vr.get(t);if(n)return n;let r=Er(e,t);return vr.set(t,r),r}function Er(e,t){let n=new Y(e),r=async(e,t)=>{try{return br(t,await n.processVerification(xr(e.query,`hub.mode`),xr(e.query,`hub.verify_token`),xr(e.query,`hub.challenge`)))}catch(e){return console.error(`Webhook verification error:`,e),X(t)}},i=async(e,t)=>{try{return br(t,await n.processWebhook(wr(e)))}catch(e){return console.error(`Webhook processing error:`,e),X(t)}};return{GET:r,POST:i,webhook:async(e,t)=>{switch(e.method.toUpperCase()){case`GET`:return r(e,t);case`POST`:return i(e,t);default:return t.code(405).header(`Content-Type`,`application/json`).header(`Allow`,`GET, POST`).send(JSON.stringify({error:`Method Not Allowed`}))}},flow:async(e,t)=>{try{return br(t,await n.processFlow(wr(e)))}catch(e){return console.error(`Flow processing error:`,e),X(t)}},processor:n,destroy:()=>{n.removeAllHandlers(),vr.delete(t)}}}const Dr=new Map;function Or(e){return`hono:${e.phoneNumberId??`default`}`}function kr(e){return new Response(e.body,{status:e.status,headers:e.headers})}function Ar(){return new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}async function jr(e){let t=e.req.raw;return!t.bodyUsed||!e.req.text?t:new Request(t.url,{method:t.method,headers:t.headers,body:await e.req.text()})}function Mr(e){let t=Or(e),n=Dr.get(t);if(n)return n;let r=Nr(e,t);return Dr.set(t,r),r}function Nr(e,t){let n=new Y(e),r=async e=>{try{let{searchParams:t}=new URL(e.req.raw.url);return kr(await n.processVerification(t.get(`hub.mode`),t.get(`hub.verify_token`),t.get(`hub.challenge`)))}catch(e){return console.error(`Webhook verification error:`,e),Ar()}},i=async e=>{try{return kr(await n.processWebhook(await jr(e)))}catch(e){return console.error(`Webhook processing error:`,e),Ar()}};return{GET:r,POST:i,webhook:async e=>{switch(e.req.raw.method.toUpperCase()){case`GET`:return r(e);case`POST`:return i(e);default:return new Response(JSON.stringify({error:`Method Not Allowed`}),{status:405,headers:{"Content-Type":`application/json`,Allow:`GET, POST`}})}},flow:async e=>{try{return kr(await n.processFlow(await jr(e)))}catch(e){return console.error(`Flow processing error:`,e),Ar()}},processor:n,destroy:()=>{n.removeAllHandlers(),Dr.delete(t)}}}const Pr=new Map;function Fr(e){return`nextjs-app:${e.phoneNumberId??`default`}`}function Ir(e){let t=Fr(e),n=Pr.get(t);if(n)return n;let r=Lr(e,t);return Pr.set(t,r),r}function Lr(e,t){let n=new Y(e);return{GET:async e=>{try{let{searchParams:t}=new URL(e.url),r=t.get(`hub.mode`),i=t.get(`hub.verify_token`),a=t.get(`hub.challenge`),o=await n.processVerification(r,i,a);return new Response(o.body,{status:o.status,headers:o.headers})}catch(e){return console.error(`Webhook verification error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let t=await n.processWebhook(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}},webhook:{GET:async e=>{try{let{searchParams:t}=new URL(e.url),r=t.get(`hub.mode`),i=t.get(`hub.verify_token`),a=t.get(`hub.challenge`),o=await n.processVerification(r,i,a);return new Response(o.body,{status:o.status,headers:o.headers})}catch(e){return console.error(`Webhook verification error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let t=await n.processWebhook(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}}},flow:{GET:async e=>{try{let t=await n.processFlow(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Flow GET error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}},POST:async e=>{try{let t=await n.processFlow(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Flow POST error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}}},processor:n,destroy:()=>{n.removeAllHandlers(),Pr.delete(t)}}}var Rr=class extends pr{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 zr=new Map;function Br(e){return`nextjs-page:${e.phoneNumberId??`default`}`}function Vr(e){let t=Br(e),n=zr.get(t);if(n)return n;let r=new Rr(e),i={...r.getHandlers(),destroy:()=>{r.webhookProcessor.removeAllHandlers(),zr.delete(t)}};return zr.set(t,i),i}function Hr(e){switch(e.type){case`text`:return e.text.body;case`image`:return e.image.caption||`[Image]`;case`video`:return e.video.caption||`[Video]`;case`audio`:return e.audio.voice?`[Voice Message]`:`[Audio]`;case`document`:return e.document.caption||e.document.filename||`[Document]`;case`sticker`:return e.sticker.animated?`[Animated Sticker]`:`[Sticker]`;case`interactive`:{let t=e.interactive;return t.type===`button_reply`?t.button_reply.title:t.type===`list_reply`?t.list_reply.title:t.type===`nfm_reply`?t.nfm_reply.body||t.nfm_reply.name||`[Form Reply]`:`[Interactive]`}case`button`:return e.button.text;case`location`:return e.location.name||e.location.address||`📍 ${e.location.latitude}, ${e.location.longitude}`;case`contacts`:{let t=e.contacts.map(e=>e.name.formatted_name);return t.length===1?`👤 ${t[0]}`:`👤 ${t.length} contacts`}case`reaction`:return e.reaction.emoji||`[Reaction removed]`;case`order`:{let t=e.order.product_items.length;return`🛒 Order: ${t} item${t>1?`s`:``}`}case`system`:return e.system.body;case`unsupported`:return`[Unsupported message]`;default:return`[${e.type}]`}}const Ur=(e,t)=>R(`generateXHub256Sig`).createHmac(`sha256`,t).update(e,`utf-8`).digest(`hex`),Wr=(e,t)=>sn(t,e);function Gr(e){return e.type===`text`}function Kr(e){return e.type===`image`}function qr(e){return e.type===`video`}function Jr(e){return e.type===`audio`}function Yr(e){return e.type===`document`}function Xr(e){return e.type===`sticker`}function Z(e){return e.type===`interactive`}function Zr(e){return e.type===`button`}function Qr(e){return e.type===`location`}function $r(e){return e.type===`contacts`}function ei(e){return e.type===`reaction`}function ti(e){return e.type===`order`}function ni(e){return e.type===`system`}function ri(e){return Z(e)&&e.interactive.type===`button_reply`}function ii(e){return Z(e)&&e.interactive.type===`list_reply`}function ai(e){return Z(e)&&e.interactive.type===`nfm_reply`}function oi(e){return Kr(e)?{id:e.image.id,mimeType:e.image.mime_type,sha256:e.image.sha256,caption:e.image.caption}:qr(e)?{id:e.video.id,mimeType:e.video.mime_type,sha256:e.video.sha256,caption:e.video.caption}:Jr(e)?{id:e.audio.id,mimeType:e.audio.mime_type,sha256:e.audio.sha256,voice:e.audio.voice}:Yr(e)?{id:e.document.id,mimeType:e.document.mime_type,sha256:e.document.sha256,caption:e.document.caption,filename:e.document.filename}:Xr(e)?{id:e.sticker.id,mimeType:e.sticker.mime_type,sha256:e.sticker.sha256,animated:e.sticker.animated}:null}function si(e){return Z(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 ci(e){return Qr(e)?{latitude:e.location.latitude,longitude:e.location.longitude,name:e.location.name,address:e.location.address,url:e.location.url}:null}function li(e){return $r(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 ui(e){return ei(e)?{messageId:e.reaction.message_id,emoji:e.reaction.emoji||null}:null}function di(e){return ti(e)?{catalogId:e.order.catalog_id,text:e.order.text,items:e.order.product_items.map(e=>({productId:e.product_retailer_id,quantity:e.quantity,price:e.item_price,currency:e.currency}))}:null}const fi={Authentication:`AUTHENTICATION`,Marketing:`MARKETING`,Utility:`UTILITY`},pi={Authentication:`authentication`,Service:`service`,Utility:`utility`},mi={Approved:`APPROVED`,Pending:`PENDING`,Rejected:`REJECTED`},hi={Get:`GET`,Post:`POST`,Put:`PUT`,Delete:`DELETE`},gi={Audio:`audio`,Contacts:`contacts`,Document:`document`,Image:`image`,Interactive:`interactive`,Location:`location`,Reaction:`reaction`,Sticker:`sticker`,Template:`template`,Text:`text`,Video:`video`,Button:`button`,Order:`order`,System:`system`,Unsupported:`unsupported`,Unknown:`unknown`,Statuses:`statuses`,All:`*`},_i={Action:`ACTION`,CouponCode:`COUPON_CODE`,Currency:`CURRENCY`,DateTime:`DATE_TIME`,Document:`DOCUMENT`,ExpirationTimeMs:`EXPIRATION_TIME_MS`,Image:`IMAGE`,LimitedTimeOffer:`LIMITED_TIME_OFFER`,Location:`LOCATION`,OrderStatus:`ORDER_STATUS`,Payload:`PAYLOAD`,Product:`PRODUCT`,Text:`TEXT`,TtlMinutes:`TTL_MINUTES`,Video:`VIDEO`,WebviewInteraction:`WEBVIEW_INTERACTION`,WebviewPresentation:`WEBVIEW_PRESENTATION`},vi={Button:`button`,List:`list`,Product:`product`,ProductList:`product_list`,CtaUrl:`cta_url`,Carousel:`carousel`,LocationRequest:`location_request_message`,AddressMessage:`address_message`,Flow:`flow`,VoiceCall:`voice_call`},yi={First:1,Second:2,Third:3,Fourth:4,Fifth:5},bi={Catalog:`CATALOG`,CopyCode:`COPY_CODE`,Flow:`FLOW`,Mpm:`MPM`,OrderDetails:`ORDER_DETAILS`,QuickReply:`QUICK_REPLY`,Reminder:`REMINDER`,Url:`URL`,VoiceCall:`VOICE_CALL`},xi={Header:`HEADER`,Body:`BODY`,Button:`BUTTON`,Footer:`FOOTER`},Si={BusinessInitiated:`business_initiated`,CustomerInitiated:`customer_initiated`,ReferralConversion:`referral_conversion`},Ci={Delivered:`delivered`,Read:`read`,Sent:`sent`},wi={Mp4:`video/mp4`,Threegp:`video/3gp`},Ti={Webp:`image/webp`},Ei={Jpeg:`image/jpeg`,Png:`image/png`,Webp:`image/webp`},Di={Text:`text/plain`,Pdf:`application/pdf`,Ppt:`application/vnd.ms-powerpoint`,Word:`application/msword`,Excel:`application/vnd.ms-excel`,OpenDoc:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,OpenPres:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,OpenSheet:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`},Oi={Aac:`audio/aac`,Mp4:`audio/mp4`,Mpeg:`audio/mpeg`,Amr:`audio/amr`,Ogg:`audio/ogg`},ki={Audio:`audio`,Button:`button`,Document:`document`,Text:`text`,Image:`image`,Interactive:`interactive`,Order:`order`,Sticker:`sticker`,System:`system`,Unknown:`unknown`,Video:`video`},Ai={CustomerChangedNumber:`customer_changed_number`,CustomerIdentityChanged:`customer_identity_changed`,UserChangedNumber:`user_changed_number`,UserIdentityChanged:`user_identity_changed`,UserChangedUserId:`user_changed_user_id`},ji={Ad:`ad`,Post:`post`},Mi={Sms:`SMS`,Voice:`VOICE`},Ni={Afrikaans:`af`,Albanian:`sq`,Arabic:`ar`,Azerbaijani:`az`,Bengali:`bn`,Bulgarian:`bg`,Catalan:`ca`,Chinese_CHN:`zh_CN`,Chinese_HKG:`zh_HK`,Chinese_TAI:`zh_TW`,Croatian:`hr`,Czech:`cs`,Danish:`da`,Dutch:`nl`,English:`en`,English_UK:`en_GB`,English_US:`en_US`,Estonian:`et`,Filipino:`fil`,Finnish:`fi`,French:`fr`,Georgian:`ka`,German:`de`,Greek:`el`,Gujarati:`gu`,Hausa:`ha`,Hebrew:`he`,Hindi:`hi`,Hungarian:`hu`,Indonesian:`id`,Irish:`ga`,Italian:`it`,Japanese:`ja`,Kannada:`kn`,Kazakh:`kk`,Kinyarwanda:`rw_RW`,Korean:`ko`,Kyrgyz_Kyrgyzstan:`ky_KG`,Lao:`lo`,Latvian:`lv`,Lithuanian:`lt`,Macedonian:`mk`,Malay:`ms`,Malayalam:`ml`,Marathi:`mr`,Norwegian:`nb`,Persian:`fa`,Polish:`pl`,Portuguese_BR:`pt_BR`,Portuguese_POR:`pt_PT`,Punjabi:`pa`,Romanian:`ro`,Russian:`ru`,Serbian:`sr`,Slovak:`sk`,Slovenian:`sl`,Spanish:`es`,Spanish_ARG:`es_AR`,Spanish_SPA:`es_ES`,Spanish_MEX:`es_MX`,Swahili:`sw`,Swedish:`sv`,Tamil:`ta`,Telugu:`te`,Thai:`th`,Turkish:`tr`,Ukrainian:`uk`,Urdu:`ur`,Uzbek:`uz`,Vietnamese:`vi`,Zulu:`zu`},Pi={AU:`AU`,ID:`ID`,IN:`IN`,JP:`JP`,SG:`SG`,KR:`KR`,DE:`DE`,CH:`CH`,GB:`GB`,BR:`BR`,BH:`BH`,ZA:`ZA`,AE:`AE`,CA:`CA`},Fi=3600*1e3,Ii=24*Fi,Li=72*Fi,Ri=168*Fi,zi=1e11;function Q(e,t){let n;if(e instanceof Date)n=e.getTime();else if(typeof e==`number`)n=Math.abs(e)<zi?e*1e3:e;else if(typeof e==`string`){let t=e.trim();if(/^\d+(\.\d+)?$/.test(t)){let e=Number(t);n=e<zi?e*1e3:e}else n=t===``?NaN:Date.parse(t)}else n=NaN;if(!Number.isFinite(n)||!Number.isFinite(new Date(n).getTime()))throw new w(`${t} is not a valid timestamp: ${String(e)}`);return n}function Bi(e,t,n){if(e===void 0)return n;if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw new w(`${t} must be a non-negative number of milliseconds`);return e}function Vi(e,t,n,r){if(!Number.isFinite(new Date(t).getTime()))throw new w(`Window expiry is outside the supported timestamp range`);let i=Math.max(0,t-e),a=t-r,o=Math.min(Math.max(0,a-n),i);return{isOpen:o>0,expiresAt:new Date(t),remainingMs:o}}const Hi=Object.freeze({isOpen:!1,expiresAt:null,remainingMs:0});function Ui(e,t={}){let n=Bi(t.safetyMarginMs,`safetyMarginMs`,0),r=t.now===void 0?Date.now():Q(t.now,`now`);if(e==null)return{...Hi};let i=Q(e,`lastInboundAt`);return Vi(i,i+Ii,r,n)}function Wi(e,t={}){return Ui(e,t).isOpen}function Gi(e,t={}){let n=Bi(t.safetyMarginMs,`safetyMarginMs`,0),r=Bi(t.durationMs,`durationMs`,Li),i=t.now===void 0?Date.now():Q(t.now,`now`);if(e==null)return{...Hi};let a=Q(e,`openedAt`);return Vi(a,t.expiresAt===void 0?a+r:Q(t.expiresAt,`expiresAt`),i,n)}const Ki={sent:1,failed:2,delivered:3,read:4};function qi(e){return e&&Object.hasOwn(Ki,e)?Ki[e]:0}function Ji(e,t){return qi(e)-qi(t)}function Yi(e,t){return e==null||e===``?!0:Ji(t,e)>0}function Xi(e,t){return e==null||e===``||Ji(t,e)>0?t:e}function $(e,t){return e.split(`
23
+ `).map(e=>{let n=/^(\s*)(.*?)(\s*)$/s.exec(e);if(!n)return e;let[,r,i,a]=n;return i?`${r}${t}${i}${t}${a}`:e}).join(`
24
+ `)}function Zi(e){return $(e,`*`)}function Qi(e){return $(e,`_`)}function $i(e){return $(e,`~`)}function ea(e){return $(e,"`")}function ta(e){return e.trim()===``?e:`\`\`\`${e}\`\`\``}function na(e){return e.split(`
25
+ `).map(e=>`> ${e}`).join(`
26
+ `)}function ra(e){return e.map(e=>`- ${e}`).join(`
27
+ `)}function ia(e){return e.map((e,t)=>`${t+1}. ${e}`).join(`
28
+ `)}export{ge as AUTHORIZATION_ERROR_CODES,Oi as AudioMediaTypes,ae as AudioMediaTypesEnum,xe as BLOCK_USER_ERROR_CODES,ot as BlockUsersApi,st as BusinessApi,Et as BusinessProfileApi,pe as BusinessVerticalEnum,yi as ButtonPosition,f as ButtonPositionEnum,Se as CALLING_ERROR_CODES,Ii as CUSTOMER_SERVICE_WINDOW_MS,ct as CallingApi,fi as Category,a as CategoryEnum,lt as CommerceApi,xi as ComponentType,m as ComponentTypesEnum,ut as ContactBookApi,Si as ConversationTypes,g as ConversationTypesEnum,de as CurrencyCodesEnum,Pi as DataLocalizationRegion,fe as DataLocalizationRegionEnum,Di as DocumentMediaTypes,ie as DocumentMediaTypesEnum,dt as EncryptionApi,be as FLOW_ERROR_CODES,Li as FREE_ENTRY_POINT_WINDOW_MS,ht as FlowActionEnum,ft as FlowApi,mt as FlowCategoryEnum,pt as FlowStatusEnum,gt as FlowTypeEnum,Ce as GROUP_ERROR_CODES,_t as GroupsApi,hi as HttpMethods,c as HttpMethodsEnum,ve as INTEGRITY_ERROR_CODES,Ei as ImageMediaTypes,re as ImageMediaTypesEnum,vi as InteractiveTypes,d as InteractiveTypesEnum,Ni as Languages,ue as LanguagesEnum,N as Logger,Ri as MAX_FREE_ENTRY_POINT_WINDOW_MS,vt as MarketingMessagesApi,yt as MediaApi,Rn as MemoryDedupeStore,D as MessageApi,D as MessagesApi,pi as MessageCategory,o as MessageCategoryEnum,Ct as MessageHistoryApi,gi as MessageTypes,l as MessageTypesEnum,_i as ParametersTypes,u as ParametersTypesEnum,wt as PaymentsApi,Tt as PhoneNumberApi,Dt as QrCodeApi,ji as ReferralSourceTypes,ce as ReferralSourceTypesEnum,Ot as RegistrationApi,Mi as RequestCodeMethods,le as RequestCodeMethodsEnum,ye as SEND_MESSAGE_ERROR_CODES,kt as SolutionsApi,Ci as Status,ee as StatusEnum,Ti as StickerMediaTypes,ne as StickerMediaTypesEnum,bi as SubType,p as SubTypeEnum,Ai as SystemChangeTypes,se as SystemChangeTypesEnum,_e as THROTTLING_ERROR_CODES,Vt as TemplateApi,mi as TemplateStatus,s as TemplateStatusEnum,Ut as ThreadControlApi,Wt as TwoStepVerificationApi,wi as VideoMediaTypes,te as VideoMediaTypesEnum,me as WHATSAPP_ERROR_CODES,Kt as WabaAccountReviewStatus,Jt as WabaAccountStatus,Gt as WabaApi,Yt as WabaBusinessVerificationStatus,h as WabaConfigEnum,qt as WabaHealthStatusCanSendMessage,Y as WebhookProcessor,ki as WebhookTypes,oe as WebhookTypesEnum,Ln as WhatsApp,Ln as default,y as WhatsAppApiError,b as WhatsAppAuthorizationError,Ue as WhatsAppBlockUserError,We as WhatsAppCallingError,v as WhatsAppError,He as WhatsAppFlowError,Ge as WhatsAppGroupError,S as WhatsAppIntegrityError,qe as WhatsAppNetworkError,C as WhatsAppSendMessageError,x as WhatsAppThrottlingError,Je as WhatsAppUnknownError,w as WhatsAppValidationError,Zi as bold,O as buildFieldsQueryString,ra as bulletList,Wi as canSendFreeformMessage,Ji as compareMessageStatus,ar as constructFullUrl,Nt as createAuthenticationTemplate,Pt as createCatalogTemplate,Ft as createCouponTemplate,It as createLimitedTimeOfferTemplate,Rt as createMPMTemplate,Lt as createMediaCardCarouselTemplate,Mt as createOTPTemplate,zt as createProductCardCarouselTemplate,Bt as createSPMTemplate,jt as createTemplate,Ke as createWhatsAppApiError,mn as decryptFlowRequest,yn as decryptFlowRequestAsync,hn as encryptFlowResponse,bn as encryptFlowResponseAsync,_r as expressWebhookHandler,Hr as extractMessageText,Tr as fastifyWebhookHandler,dn as formatConfigTable,pn as generateEncryption,Ur as generateXHub256Sig,Wr as generateXHub256SigAsync,li as getContactsInfo,Ui as getCustomerServiceWindow,Gi as getFreeEntryPointWindow,si as getInteractiveReply,ci as getLocationInfo,oi as getMediaInfo,di as getOrderInfo,ui as getReactionInfo,Mr as honoWebhookHandler,ea as inlineCode,Ne as isApiPermissionErrorCode,Jr as isAudioMessage,Pe as isAuthorizationErrorCode,ze as isBlockUserErrorCode,Zr as isButtonMessage,ri as isButtonReply,Be as isCallingErrorCode,$r as isContactsMessage,Yr as isDocumentMessage,Un as isFlowDataExchangeRequest,Re as isFlowErrorCode,Wn as isFlowErrorRequest,Gn as isFlowPingRequest,Ve as isGroupErrorCode,Kr as isImageMessage,Ie as isIntegrityErrorCode,Z as isInteractiveMessage,ii as isListReply,Qr as isLocationMessage,Yi as isMessageStatusAdvance,T as isMetaError,ai as isNfmReply,ti as isOrderMessage,ei as isReactionMessage,Le as isSendMessageErrorCode,Xr as isStickerMessage,ni as isSystemMessage,Gr as isTextMessage,Fe as isThrottlingErrorCode,ir as isValidWebhookSignature,qr as isVideoMessage,Ye as isWhatsAppApiErrorResponse,Xe as isWhatsAppAuthorizationError,tt as isWhatsAppBlockUserError,nt as isWhatsAppCallingError,Me as isWhatsAppErrorCode,et as isWhatsAppFlowError,rt as isWhatsAppGroupError,Qe as isWhatsAppIntegrityError,$e as isWhatsAppSendMessageError,Ze as isWhatsAppThrottlingError,Qi as italic,ta as monospace,Ir as nextjsAppWebhookHandler,Vr as nextjsPagesWebhookHandler,it as normalizeMetaError,ia as numberedList,_ as objectToQueryString,On as parseRateLimitHeaders,Dn as parseRetryAfter,nr as processFlowRequest,$n as processWebhookMessages,na as quote,Xi as resolveMessageStatus,$i as strikethrough,rr as verifyWebhookSignature};
23
29
  //# sourceMappingURL=index.mjs.map