meta-cloud-api 1.4.1 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -9
- package/dist/index.d.ts +163 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/types/index.d.ts +13 -1
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{__export as e}from"./chunk-CTAAG5j7.js";import{inspect as t}from"util";import*as n from"crypto";import r from"crypto";import{Agent as i}from"https";import{readFileSync as a}from"fs";import{join as o}from"path";var s=e({AudioMediaTypesEnum:()=>S,BusinessVerticalEnum:()=>se,ButtonPositionEnum:()=>m,CategoryEnum:()=>c,ComponentTypesEnum:()=>g,ConversationTypesEnum:()=>ee,CurrencyCodesEnum:()=>ae,DataLocalizationRegionEnum:()=>oe,DocumentMediaTypesEnum:()=>x,HttpMethodsEnum:()=>u,ImageMediaTypesEnum:()=>b,InteractiveTypesEnum:()=>p,LanguagesEnum:()=>ie,MessageTypesEnum:()=>d,ParametersTypesEnum:()=>f,ReferralSourceTypesEnum:()=>ne,RequestCodeMethodsEnum:()=>re,StatusEnum:()=>te,StickerMediaTypesEnum:()=>y,SubTypeEnum:()=>h,SystemChangeTypesEnum:()=>w,TemplateStatusEnum:()=>l,VideoMediaTypesEnum:()=>v,WabaConfigEnum:()=>_,WebhookTypesEnum:()=>C});let c=function(e){return e.Authentication=`AUTHENTICATION`,e.Marketing=`MARKETING`,e.Utility=`UTILITY`,e}({}),l=function(e){return e.Approved=`APPROVED`,e.Pending=`PENDING`,e.Rejected=`REJECTED`,e}({}),u=function(e){return e.Get=`GET`,e.Post=`POST`,e.Put=`PUT`,e.Delete=`DELETE`,e}({}),d=function(e){return e.Audio=`audio`,e.Contacts=`contacts`,e.Document=`document`,e.Image=`image`,e.Interactive=`interactive`,e.Location=`location`,e.Reaction=`reaction`,e.Sticker=`sticker`,e.Template=`template`,e.Text=`text`,e.Video=`video`,e.Button=`button`,e.Order=`order`,e.System=`system`,e.Unsupported=`unsupported`,e.Unknown=`unknown`,e.Statuses=`statuses`,e[`*`]=`*`,e}({}),f=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}({}),p=function(e){return e.Button=`button`,e.List=`list`,e.Product=`product`,e.ProductList=`product_list`,e.CtaUrl=`cta_url`,e.LocationRequest=`location_request_message`,e.AddressMessage=`address_message`,e.Flow=`flow`,e}({}),m=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}({}),h=function(e){return e.Catalog=`CATALOG`,e.CopyCode=`COPY_CODE`,e.Flow=`FLOW`,e.Mpm=`MPM`,e.OrderDetails=`ORDER_DETAILS`,e.QuickReply=`QUICK_REPLY`,e.Reminder=`REMINDER`,e.Url=`URL`,e.VoiceCall=`VOICE_CALL`,e}({}),g=function(e){return e.Header=`HEADER`,e.Body=`BODY`,e.Button=`BUTTON`,e.Footer=`FOOTER`,e}({}),_=function(e){return e.AppId=`M4D_APP_ID`,e.Port=`WA_PORT`,e.AppSecret=`M4D_APP_SECRET`,e.PhoneNumberId=`WA_PHONE_NUMBER_ID`,e.BusinessAcctId=`WA_BUSINESS_ACCOUNT_ID`,e.APIVersion=`CLOUD_API_VERSION`,e.AccessToken=`CLOUD_API_ACCESS_TOKEN`,e.WebhookEndpoint=`WEBHOOK_ENDPOINT`,e.WebhookVerificationToken=`WEBHOOK_VERIFICATION_TOKEN`,e.ListenerPort=`LISTENER_PORT`,e.MaxRetriesAfterWait=`MAX_RETRIES_AFTER_WAIT`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.Debug=`DEBUG`,e.PrivatePem=`FLOW_API_PRIVATE_PEM`,e.Passphrase=`FLOW_API_PASSPHRASE`,e}({}),ee=function(e){return e.BusinessInitiated=`business_initiated`,e.CustomerInitiated=`customer_initiated`,e.ReferralConversion=`referral_conversion`,e}({}),te=function(e){return e.Delivered=`delivered`,e.Read=`read`,e.Sent=`sent`,e}({}),v=function(e){return e.Mp4=`video/mp4`,e.Threegp=`video/3gp`,e}({}),y=function(e){return e.Webp=`image/webp`,e}({}),b=function(e){return e.Jpeg=`image/jpeg`,e.Png=`image/png`,e}({}),x=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}({}),S=function(e){return e.Aac=`audio/aac`,e.Mp4=`audio/mp4`,e.Mpeg=`audio/mpeg`,e.Amr=`audio/amr`,e.Ogg=`audio/ogg`,e}({}),C=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}({}),w=function(e){return e.CustomerChangedNumber=`customer_changed_number`,e.CustomerIdentityChanged=`customer_identity_changed`,e}({}),ne=function(e){return e.Ad=`ad`,e.Post=`post`,e}({}),re=function(e){return e.Sms=`SMS`,e.Voice=`VOICE`,e}({}),ie=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}({}),ae=function(e){return e.AFN=`AFN`,e.EUR=`EUR`,e.ALL=`ALL`,e.DZD=`DZD`,e.USD=`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RESTAURANT`,e.RETAIL=`RETAIL`,e.TRAVEL=`TRAVEL`,e}({});var T=class{name;debug;constructor(e,t=!1){this.name=e,this.debug=t}formatData(e){return e.map(e=>typeof e==`object`?t(e,{depth:null,colors:!0}):e).join(` `)}log(...e){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log(t,`: `,this.formatData(e))}}error(...e){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error(t,`: `,this.formatData(e))}warn(...e){if(this.debug){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn(t,`: `,this.formatData(e))}}info(...e){if(this.debug){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info(t,`: `,this.formatData(e))}}};const ce=new T(`UTILS`,process.env.DEBUG===`true`||!1),le=e=>{if(!process.env[_.AccessToken]&&!e?.accessToken)throw ce.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`),Error(`Missing WhatsApp access token.`)},ue=e=>(le(e),{[_.AppId]:e?.appId||process.env.M4D_APP_ID||``,[_.AppSecret]:e?.appSecret||process.env.M4D_APP_SECRET||``,[_.PhoneNumberId]:e?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),[_.BusinessAcctId]:e?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||``,[_.APIVersion]:e?.apiVersion||process.env.CLOUD_API_VERSION||``,[_.AccessToken]:e?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||``,[_.WebhookEndpoint]:e?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||``,[_.WebhookVerificationToken]:e?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||``,[_.ListenerPort]:e?.listenerPort||parseInt(process.env.LISTENER_PORT||``)||3e3,[_.MaxRetriesAfterWait]:e?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||``)||30,[_.RequestTimeout]:e?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||``)||2e4,[_.Debug]:e?.debug||process.env.DEBUG===`true`,[_.PrivatePem]:e?.privatePem||process.env.FLOW_API_PRIVATE_PEM||``,[_.Passphrase]:e?.passphrase||process.env.FLOW_API_PASSPHRASE||``});function de(e){let t=[[`App ID`,e[_.AppId]||`Not Set`],[`Phone Number ID`,e[_.PhoneNumberId]?.toString()||`Not Set`],[`Business Account ID`,e[_.BusinessAcctId]||`Not Set`],[`API Version`,e[_.APIVersion]||`Not Set`],[`Access Token`,e[_.AccessToken]?`${e[_.AccessToken].substring(0,20)}...`:`Not Set`],[`Webhook Endpoint`,e[_.WebhookEndpoint]||`Not Set`],[`Webhook Verification Token`,e[_.WebhookVerificationToken]?`${e[_.WebhookVerificationToken].substring(0,10)}...`:`Not Set`],[`Listener Port`,e[_.ListenerPort]?.toString()||`Not Set`],[`Debug Mode`,e[_.Debug]?`Enabled`:`Disabled`],[`Max Retries`,e[_.MaxRetriesAfterWait]?.toString()||`Not Set`],[`Request Timeout`,e[_.RequestTimeout]?`${e[_.RequestTimeout]}ms`:`Not Set`],[`Private PEM`,e[_.PrivatePem]?`Configured`:`Not Set`],[`Passphrase`,e[_.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)}┘`,l=`│ ${`Configuration`.padEnd(i)} │ ${`Value`.padEnd(a)} │`,u=t.map(([e,t])=>`│ ${e?.padEnd(i)} │ ${t?.padEnd(a)} │`);return[o,l,s,...u,c].join(`
|
|
2
|
-
`)}const
|
|
3
|
-
`));let s=t.FLOW_API_PASSPHRASE,c=o.includes(`-----BEGIN RSA PRIVATE KEY-----`),l=o.includes(`-----BEGIN PRIVATE KEY-----`)||o.includes(`-----BEGIN ENCRYPTED PRIVATE KEY-----`);
|
|
4
|
-
`)[0]});let u;try{u=s?r.createPrivateKey({key:o,format:`pem`,passphrase:s}):r.createPrivateKey(o)}catch(e){
|
|
1
|
+
import{__export as e}from"./chunk-CTAAG5j7.js";import{inspect as t}from"util";import*as n from"crypto";import r from"crypto";import{Agent as i}from"https";import{readFileSync as a}from"fs";import{join as o}from"path";var s=e({AudioMediaTypesEnum:()=>S,BusinessVerticalEnum:()=>oe,ButtonPositionEnum:()=>m,CategoryEnum:()=>c,ComponentTypesEnum:()=>g,ConversationTypesEnum:()=>ee,CurrencyCodesEnum:()=>ie,DataLocalizationRegionEnum:()=>ae,DocumentMediaTypesEnum:()=>x,HttpMethodsEnum:()=>u,ImageMediaTypesEnum:()=>b,InteractiveTypesEnum:()=>p,LanguagesEnum:()=>re,MessageTypesEnum:()=>d,ParametersTypesEnum:()=>f,ReferralSourceTypesEnum:()=>T,RequestCodeMethodsEnum:()=>ne,StatusEnum:()=>te,StickerMediaTypesEnum:()=>y,SubTypeEnum:()=>h,SystemChangeTypesEnum:()=>w,TemplateStatusEnum:()=>l,VideoMediaTypesEnum:()=>v,WabaConfigEnum:()=>_,WebhookTypesEnum:()=>C});let c=function(e){return e.Authentication=`AUTHENTICATION`,e.Marketing=`MARKETING`,e.Utility=`UTILITY`,e}({}),l=function(e){return e.Approved=`APPROVED`,e.Pending=`PENDING`,e.Rejected=`REJECTED`,e}({}),u=function(e){return e.Get=`GET`,e.Post=`POST`,e.Put=`PUT`,e.Delete=`DELETE`,e}({}),d=function(e){return e.Audio=`audio`,e.Contacts=`contacts`,e.Document=`document`,e.Image=`image`,e.Interactive=`interactive`,e.Location=`location`,e.Reaction=`reaction`,e.Sticker=`sticker`,e.Template=`template`,e.Text=`text`,e.Video=`video`,e.Button=`button`,e.Order=`order`,e.System=`system`,e.Unsupported=`unsupported`,e.Unknown=`unknown`,e.Statuses=`statuses`,e[`*`]=`*`,e}({}),f=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}({}),p=function(e){return e.Button=`button`,e.List=`list`,e.Product=`product`,e.ProductList=`product_list`,e.CtaUrl=`cta_url`,e.LocationRequest=`location_request_message`,e.AddressMessage=`address_message`,e.Flow=`flow`,e}({}),m=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}({}),h=function(e){return e.Catalog=`CATALOG`,e.CopyCode=`COPY_CODE`,e.Flow=`FLOW`,e.Mpm=`MPM`,e.OrderDetails=`ORDER_DETAILS`,e.QuickReply=`QUICK_REPLY`,e.Reminder=`REMINDER`,e.Url=`URL`,e.VoiceCall=`VOICE_CALL`,e}({}),g=function(e){return e.Header=`HEADER`,e.Body=`BODY`,e.Button=`BUTTON`,e.Footer=`FOOTER`,e}({}),_=function(e){return e.AppId=`M4D_APP_ID`,e.Port=`WA_PORT`,e.AppSecret=`M4D_APP_SECRET`,e.PhoneNumberId=`WA_PHONE_NUMBER_ID`,e.BusinessAcctId=`WA_BUSINESS_ACCOUNT_ID`,e.APIVersion=`CLOUD_API_VERSION`,e.AccessToken=`CLOUD_API_ACCESS_TOKEN`,e.WebhookEndpoint=`WEBHOOK_ENDPOINT`,e.WebhookVerificationToken=`WEBHOOK_VERIFICATION_TOKEN`,e.ListenerPort=`LISTENER_PORT`,e.MaxRetriesAfterWait=`MAX_RETRIES_AFTER_WAIT`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.Debug=`DEBUG`,e.PrivatePem=`FLOW_API_PRIVATE_PEM`,e.Passphrase=`FLOW_API_PASSPHRASE`,e}({}),ee=function(e){return e.BusinessInitiated=`business_initiated`,e.CustomerInitiated=`customer_initiated`,e.ReferralConversion=`referral_conversion`,e}({}),te=function(e){return e.Delivered=`delivered`,e.Read=`read`,e.Sent=`sent`,e}({}),v=function(e){return e.Mp4=`video/mp4`,e.Threegp=`video/3gp`,e}({}),y=function(e){return e.Webp=`image/webp`,e}({}),b=function(e){return e.Jpeg=`image/jpeg`,e.Png=`image/png`,e}({}),x=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}({}),S=function(e){return e.Aac=`audio/aac`,e.Mp4=`audio/mp4`,e.Mpeg=`audio/mpeg`,e.Amr=`audio/amr`,e.Ogg=`audio/ogg`,e}({}),C=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}({}),w=function(e){return e.CustomerChangedNumber=`customer_changed_number`,e.CustomerIdentityChanged=`customer_identity_changed`,e}({}),T=function(e){return e.Ad=`ad`,e.Post=`post`,e}({}),ne=function(e){return e.Sms=`SMS`,e.Voice=`VOICE`,e}({}),re=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}({}),ie=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.B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=`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}({}),ae=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}({}),oe=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}({});var E=class{name;debug;constructor(e,t=!1){this.name=e,this.debug=t}formatData(e){return e.map(e=>typeof e==`object`?t(e,{depth:null,colors:!0}):e).join(` `)}log(...e){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log(t,`: `,this.formatData(e))}}error(...e){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error(t,`: `,this.formatData(e))}warn(...e){if(this.debug){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn(t,`: `,this.formatData(e))}}info(...e){if(this.debug){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info(t,`: `,this.formatData(e))}}};const se=new E(`UTILS`,process.env.DEBUG===`true`||!1),ce=e=>{if(!process.env[_.AccessToken]&&!e?.accessToken)throw se.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`),Error(`Missing WhatsApp access token.`)},le=e=>(ce(e),{[_.AppId]:e?.appId||process.env.M4D_APP_ID||``,[_.AppSecret]:e?.appSecret||process.env.M4D_APP_SECRET||``,[_.PhoneNumberId]:e?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),[_.BusinessAcctId]:e?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||``,[_.APIVersion]:e?.apiVersion||process.env.CLOUD_API_VERSION||``,[_.AccessToken]:e?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||``,[_.WebhookEndpoint]:e?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||``,[_.WebhookVerificationToken]:e?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||``,[_.ListenerPort]:e?.listenerPort||parseInt(process.env.LISTENER_PORT||``)||3e3,[_.MaxRetriesAfterWait]:e?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||``)||30,[_.RequestTimeout]:e?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||``)||2e4,[_.Debug]:e?.debug||process.env.DEBUG===`true`,[_.PrivatePem]:e?.privatePem||process.env.FLOW_API_PRIVATE_PEM||``,[_.Passphrase]:e?.passphrase||process.env.FLOW_API_PASSPHRASE||``});function ue(e){let t=[[`App ID`,e[_.AppId]||`Not Set`],[`Phone Number ID`,e[_.PhoneNumberId]?.toString()||`Not Set`],[`Business Account ID`,e[_.BusinessAcctId]||`Not Set`],[`API Version`,e[_.APIVersion]||`Not Set`],[`Access Token`,e[_.AccessToken]?`${e[_.AccessToken].substring(0,20)}...`:`Not Set`],[`Webhook Endpoint`,e[_.WebhookEndpoint]||`Not Set`],[`Webhook Verification Token`,e[_.WebhookVerificationToken]?`${e[_.WebhookVerificationToken].substring(0,10)}...`:`Not Set`],[`Listener Port`,e[_.ListenerPort]?.toString()||`Not Set`],[`Debug Mode`,e[_.Debug]?`Enabled`:`Disabled`],[`Max Retries`,e[_.MaxRetriesAfterWait]?.toString()||`Not Set`],[`Request Timeout`,e[_.RequestTimeout]?`${e[_.RequestTimeout]}ms`:`Not Set`],[`Private PEM`,e[_.PrivatePem]?`Configured`:`Not Set`],[`Passphrase`,e[_.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)}┘`,l=`│ ${`Configuration`.padEnd(i)} │ ${`Value`.padEnd(a)} │`,u=t.map(([e,t])=>`│ ${e?.padEnd(i)} │ ${t?.padEnd(a)} │`);return[o,l,s,...u,c].join(`
|
|
2
|
+
`)}const D=new E(`FLOW_ENCRYPTION_UTILS`,process.env.DEBUG===`true`);function de(){if(!r||typeof r.generateKeyPairSync!=`function`){let e=Error(`This utility requires Node.js environment with crypto module. It cannot be used in browser or edge runtime environments.`);throw D.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 D.error(`Browser environment detected:`,e),e}if(process.versions&&process.versions.node){let e=process.versions.node.split(`.`).map(Number),t=e[0]??0,n=e[1]??0;if(t<10||t===10&&n<12){let e=Error(`Node.js version ${process.versions.node} is not supported. Please upgrade to Node.js 10.12.0 or higher.`);throw D.error(`Node.js version check failed:`,e),e}}D.info(`Environment validation passed`)}function O(e){D.info(`Starting encryption key generation`),de();let t=e||process.env.FLOW_API_PASSPHRASE;if(!t||t.trim().length===0){let e=Error(`Passphrase is empty. Please provide a passphrase as parameter or set FLOW_API_PASSPHRASE environment variable.`);throw D.error(`Passphrase validation failed:`,e),e}t.length<8&&D.warn(`Passphrase is shorter than 8 characters. Consider using a longer passphrase for better security.`);try{D.info(`Generating RSA key pair with 2048-bit modulus`);let e=r.generateKeyPairSync(`rsa`,{modulusLength:2048,publicKeyEncoding:{type:`spki`,format:`pem`},privateKeyEncoding:{type:`pkcs8`,format:`pem`,cipher:`aes-256-cbc`,passphrase:t}});return D.info(`Key pair generated successfully`),{passphrase:t,privateKey:e.privateKey,publicKey:e.publicKey}}catch(e){let t=e instanceof Error?e.message:String(e),n=Error(`Failed to generate key pair: ${t}`);throw D.error(`Key generation failed:`,n),n}}function fe(e,t){D.info(`Decrypting flow request`);let{encrypted_aes_key:n,encrypted_flow_data:i,initial_vector:a}=e;if(!n||!i||!a)throw D.error(`Missing required encryption properties`),Error(`Missing required encryption properties`);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-----`);D.info(`Private key format check:`,{isPKCS1:c,isPKCS8:l,hasBeginMarker:o.includes(`-----BEGIN`),hasEndMarker:o.includes(`-----END`),length:o.length,firstLine:o.split(`
|
|
4
|
+
`)[0]});let u;try{u=s?r.createPrivateKey({key:o,format:`pem`,passphrase:s}):r.createPrivateKey(o)}catch(e){D.error(`Failed to create private key:`,{error:e instanceof Error?e.message:e,pemPreview:o.substring(0,100)+`...`,hasPassphrase:!!s,isPKCS1:c,isPKCS8:l});let t=`Failed to parse private key. Error: ${e instanceof Error?e.message:e}`;throw c?(t+=`
|
|
5
5
|
|
|
6
6
|
Your key is in PKCS#1 format (-----BEGIN RSA PRIVATE KEY-----).`,t+=`
|
|
7
7
|
Please convert it to PKCS#8 format using:`,t+=`
|
|
@@ -9,13 +9,13 @@ Please convert it to PKCS#8 format using:`,t+=`
|
|
|
9
9
|
|
|
10
10
|
Or ensure your key uses a supported encryption algorithm (not DES-EDE3-CBC).`):l||(t+=`
|
|
11
11
|
|
|
12
|
-
Your key format is not recognized. Please ensure it is in PKCS#8 format.`),Error(t)}let d;try{E.info(`Decrypting AES key`),d=r.privateDecrypt({key:u,padding:r.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:`sha256`},Buffer.from(n,`base64`))}catch(e){throw E.error(`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);E.info(`Decrypting flow data`);let g=r.createDecipheriv(`aes-128-gcm`,d,p);g.setAuthTag(h);let _=Buffer.concat([g.update(m),g.final()]).toString(`utf-8`);return E.info(`Flow request decryption complete`),{decryptedBody:JSON.parse(_),aesKeyBuffer:d,initialVectorBuffer:p}}function me(e,t,n){E.info(`Encrypting flow response`);let i=[];for(let e of Array.from(n.entries()))i.push(~e[1]);try{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 E.info(`Flow response encryption complete`),a}catch(e){throw E.error(`Response encryption error:`,e),Error(`Failed to encrypt response. Internal server error.`)}}function O(e){return typeof e==`object`&&!!e&&`error`in e&&typeof e.error==`object`&&e.error!=null&&`message`in e.error&&typeof e.error.message==`string`&&`type`in e.error&&typeof e.error.type==`string`&&`code`in e.error&&typeof e.error.code==`number`&&`fbtrace_id`in e.error&&typeof e.error.fbtrace_id==`string`&&(!(`error_data`in e.error)||typeof e.error.error_data==`object`&&e.error.error_data!=null&&`messaging_product`in e.error.error_data&&e.error.error_data.messaging_product===`whatsapp`&&`details`in e.error.error_data&&typeof e.error.error_data.details==`string`)&&(!(`error_subcode`in e.error)||typeof e.error.error_subcode==`number`)}const k=new T(`HttpsClient`,process.env.DEBUG===`true`);var he=class{agent;constructor(){this.agent=new i({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(e,t,n,r,i,a){let o=`https://${e}/${t}`,s=new AbortController,c=setTimeout(()=>s.abort(),i);try{let e=await fetch(o,{method:n,headers:r,body:a,signal:s.signal});return k.log(`${n} : ${o} - ${JSON.stringify(e)}`),clearTimeout(c),new ge(e)}catch(e){throw k.error(`${n} : ${o} - ${JSON.stringify(e)}`),e}}},ge=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){throw Error(`Failed to parse response body to JSON: `+e.message)}}};const _e=new T(`REQUESTER`,process.env.DEBUG===`true`);var ve=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol=`https:`;constructor(e,t,n,r,i){this.client=new he,this.host=`graph.facebook.com`,this.apiVersion=e||`22`,this.phoneNumberId=t,this.accessToken=n,this.businessAcctId=r,this.userAgent=i}buildHeader(e,t){let n={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return e!==`multipart/form-data`&&(n[`Content-Type`]=e),t&&Object.assign(n,t),n}buildCAPIPath(e){return`v${this.apiVersion}.0/${e}`}async sendRequest(e,t,n,r,i=`application/json`,a){let o=i;r instanceof FormData?o=`multipart/form-data`:typeof r==`string`&&r.startsWith(`<?xml`)&&(o=`application/xml`);let s=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(t)}`;_e.log(`${e} : ${s} (${o})`);try{let i=await this.client.sendRequest(this.host,this.buildCAPIPath(t),e,this.buildHeader(o,a),n,e===`POST`||e===`PUT`?r:void 0);if(!i.rawResponse().ok){let e=await i.json();throw O(e)?e:{name:`MetaError`,message:`Unknown error occurred`,error:{message:e.message||`Unknown error occurred`,type:`UnknownError`,code:i.statusCode(),fbtrace_id:``}}}return i}catch(e){throw O(e)?e:{name:`MetaError`,message:e instanceof Error?e.message:`Network error occurred`,error:{message:e instanceof Error?e.message:`Network error occurred`,type:`NetworkError`,code:500,fbtrace_id:``}}}}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()}async sendUrlEncodedForm(e,t,n,r,i){let a=new URLSearchParams(r).toString();return await(await this.sendRequest(e,t,n,a,`application/x-www-form-urlencoded`,i)).json()}};function A(){try{let e=o(__dirname,`../../package.json`);return JSON.parse(a(e,`utf-8`)).version}catch{return`unknown`}}function ye(){let e=A(),t=process.version;return`WhatsApp-Nodejs-SDK/${e} (Node.js ${t})`}var j=class{config;client;constructor(e,t){this.config=e,this.client=t}sendJson(e,t,n,r){return this.client.getJson(e,t,n,r)}sendFormData(e,t,n,r){return this.client.sendFormData(e,t,n,r)}sendUrlEncodedForm(e,t,n,r){return this.client.sendUrlEncodedForm(e,t,n,r)}};const M=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(`&`)}`:``};var N=class extends j{endpoint=`block_users`;constructor(e,t){super(e,t)}buildBlockUsersBody(e){return{messaging_product:`whatsapp`,block_users:e.map(e=>({user:e}))}}async block(e){if(!e||e.length===0)throw Error(`At least one user must be provided to block`);let t=this.buildBlockUsersBody(e);return await this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(t))}async unblock(e){if(!e||e.length===0)throw Error(`At least one user must be provided to unblock`);let t=this.buildBlockUsersBody(e);return await this.sendJson(u.Delete,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(t))}async listBlockedUsers(e){let t=`${this.config[_.PhoneNumberId]}/${this.endpoint}`;if(e){let n=M(e);n&&(t+=`?${n}`)}return await this.sendJson(u.Get,t,this.config[_.RequestTimeout])}},P=class extends j{endpoint=`whatsapp_business_encryption`;constructor(e,t){super(e,t)}async getEncryptionPublicKey(){return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],null)}async setEncryptionPublicKey(e){let t=new FormData;return t.append(`business_public_key`,e),this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],t)}},F=class extends j{constructor(e,t){super(e,t)}async listFlows(e){return this.sendJson(u.Get,`/${e}/flows`,this.config[_.RequestTimeout],null)}async createFlow(e,t){let n={name:t.name,categories:t.categories,...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.clone_flow_id&&{clone_flow_id:t.clone_flow_id},...t.flow_json&&{flow_json:t.flow_json},...t.publish!==void 0&&{publish:t.publish}};return this.sendJson(u.Post,`/${e}/flows`,this.config[_.RequestTimeout],JSON.stringify(n))}async getFlow(e,t,n){let r=new URLSearchParams;t&&r.append(`fields`,t),n&&r.append(`date_format`,n);let i=r.toString()?`?${r.toString()}`:``;return this.sendJson(u.Get,`/${e}${i}`,this.config[_.RequestTimeout],null)}async getFlowPreview(e,t=!1){let n=`preview.invalidate(${t})`;return this.getFlow(e,n)}async updateFlowMetadata(e,t){let n={...t.name&&{name:t.name},...t.categories&&{categories:t.categories},...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.application_id&&{application_id:t.application_id}};return this.sendJson(u.Post,`/${e}`,this.config[_.RequestTimeout],JSON.stringify(n))}async deleteFlow(e){return this.sendJson(u.Delete,`/${e}`,this.config[_.RequestTimeout],null)}async listAssets(e){return this.sendJson(u.Get,`/${e}/assets`,this.config[_.RequestTimeout],null)}async updateFlowJson(e,t){let n=new FormData,r;if(t.file instanceof Buffer)r=new globalThis.Blob([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(u.Post,`/${e}/assets`,this.config[_.RequestTimeout],n)}async validateFlowJson(e,t){try{let n=await this.updateFlowJson(e,{file:t}),r=!n.validation_errors||n.validation_errors.length===0;return{...n,valid:r}}catch(e){throw e}}async publishFlow(e){return this.sendJson(u.Post,`/${e}/publish`,this.config[_.RequestTimeout],JSON.stringify({}))}async deprecateFlow(e){return this.sendJson(u.Post,`/${e}/deprecate`,this.config[_.RequestTimeout],JSON.stringify({}))}async migrateFlows(e,t){let n={source_waba_id:t.source_waba_id,...t.source_flow_names&&{source_flow_names:t.source_flow_names}};return this.sendJson(u.Post,`/${e}/migrate_flows`,this.config[_.RequestTimeout],JSON.stringify(n))}};let be=function(e){return e.Draft=`DRAFT`,e.Published=`PUBLISHED`,e.Throttled=`THROTTLED`,e.Blocked=`BLOCKED`,e.Deprecated=`DEPRECATED`,e}({}),xe=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}({}),I=function(e){return e.INIT=`INIT`,e.BACK=`BACK`,e.DATA_EXCHANGE=`data_exchange`,e}({}),L=function(e){return e.Ping=`ping`,e.Change=`data_exchange`,e.Error=`error`,e.All=`*`,e}({});var R=class extends j{endpoint=`media`;constructor(e,t){super(e,t)}async getMediaById(e,t){return this.sendJson(u.Get,`${e}`,this.config[_.RequestTimeout],null)}async uploadMedia(e,t=`whatsapp`){let n=new FormData;return n.append(`file`,e),n.append(`messaging_product`,t),n.append(`type`,e.type),this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],n)}async deleteMedia(e,t){return this.sendJson(u.Delete,`${e}`,this.config[_.RequestTimeout],null)}async downloadMedia(e){return this.sendJson(u.Get,e,this.config[_.RequestTimeout],null)}},z=class extends j{commonMethod=u.Post;commonEndpoint=`messages`;constructor(e,t){super(e,t)}bodyBuilder(e,t,n,r){let i={messaging_product:`whatsapp`,recipient_type:`individual`,to:n,type:e,[e]:t};return r&&(i.context={message_id:r}),i}send(e){return this.sendJson(this.commonMethod,`${this.config[_.PhoneNumberId]}/${this.commonEndpoint}`,this.config[_.RequestTimeout],e)}async audio(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Audio,t,n,r)))}async contacts(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Contacts,t,n,r)))}async document(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Document,t,n,r)))}async image(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Image,t,n,r)))}async interactive(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Interactive,t,n,r)))}async location(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Location,t,n,r)))}async sticker(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Sticker,t,n,r)))}async template(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Template,t,n,r)))}async text(e){let{body:t,to:n,replyMessageId:r,previewUrl:i}=e,a=typeof t==`string`?{body:t,preview_url:i??!0}:{...t,preview_url:i??t.preview_url??!0};return this.send(JSON.stringify(this.bodyBuilder(d.Text,a,n,r)))}async video(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Video,t,n,r)))}async status(e){let t={messaging_product:`whatsapp`,status:e.status,message_id:e.messageId,...e.typingIndicator&&{typing_indicator:e.typingIndicator}};return this.send(JSON.stringify(t))}async markAsRead(e){return this.status({status:`read`,messageId:e.messageId})}async showTypingIndicator(e){return this.status({status:`read`,messageId:e.messageId,typingIndicator:{type:`text`}})}async interactiveList(e){return this.interactive(e)}async interactiveCtaUrl(e){return this.interactive(e)}async interactiveLocationRequest(e){return this.interactive(e)}async interactiveAddressMessage(e){return this.interactive(e)}async interactiveReplyButtons(e){return this.interactive(e)}async interactiveFlow(e){return this.interactive(e)}async reaction(e){let t={message_id:e.messageId,emoji:e.emoji};return this.send(JSON.stringify(this.bodyBuilder(d.Reaction,t,e.to)))}},B=class extends j{endpoint=`phone_numbers`;constructor(e,t){super(e,t)}async getPhoneNumberById(e){let t=e?M({fields:e}):``;return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}${t}`,this.config[_.RequestTimeout],null)}async getPhoneNumbers(){return this.sendJson(u.Get,`${this.config[_.BusinessAcctId]}/${this.endpoint}`,this.config[_.RequestTimeout],null)}async requestVerificationCode(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/request_code`,this.config[_.RequestTimeout],JSON.stringify(e))}async verifyCode(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/verify_code`,this.config[_.RequestTimeout],JSON.stringify(e))}async setConversationalAutomation(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/conversational_automation`,this.config[_.RequestTimeout],JSON.stringify(e))}async getConversationalAutomation(){let e=M({fields:`conversational_automation`});return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}${e}`,this.config[_.RequestTimeout],null)}async getThroughput(){let e=M({fields:`throughput`});return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}${e}`,this.config[_.RequestTimeout],null)}};function V(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 H=class extends j{endpoint=`whatsapp_business_profile`;constructor(e,t){super(e,t)}async getBusinessProfile(e){return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}/${this.endpoint}${V(e)}`,this.config[_.RequestTimeout],null)}async updateBusinessProfile(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(e))}async createUploadSession(e,t,n){let r=M({file_length:e,file_type:t,file_name:n});return this.sendJson(u.Post,`app/uploads/${r}`,this.config[_.RequestTimeout],null)}async uploadMedia(e,t){return this.sendJson(u.Post,`${e}`,this.config[_.RequestTimeout],t)}async getUploadHandle(e){return this.sendJson(u.Get,`${e}`,this.config[_.RequestTimeout],null)}},Se=class extends j{endpoint=`message_qrdls`;constructor(e,t){super(e,t)}async createQrCode(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(e))}async getQrCodes(){return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],null)}async getQrCode(e){return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}/${this.endpoint}/${e}`,this.config[_.RequestTimeout],null)}async updateQrCode(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(e))}async deleteQrCode(e){return this.sendJson(u.Delete,`${this.config[_.PhoneNumberId]}/${this.endpoint}/${e}`,this.config[_.RequestTimeout],null)}},Ce=class extends j{constructor(e,t){super(e,t)}async register(e,t){let n={messaging_product:`whatsapp`,pin:e,...t&&{data_localization_region:t}};return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/register`,this.config[_.RequestTimeout],JSON.stringify(n))}async deregister(){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/deregister`,this.config[_.RequestTimeout],null)}},we=class extends j{endpoint=`message_templates`;constructor(e,t){super(e,t)}async getTemplate(e){return this.sendJson(u.Get,`${e}`,this.config[_.RequestTimeout],null)}async updateTemplate(e,t){return this.sendJson(u.Post,`${e}`,this.config[_.RequestTimeout],JSON.stringify(t))}async getTemplates(e){return this.sendJson(u.Get,`${this.config[_.BusinessAcctId]}/${this.endpoint}${M(e??{})}`,this.config[_.RequestTimeout],null)}async createTemplate(e){return this.sendJson(u.Post,`${this.config[_.BusinessAcctId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(e))}async deleteTemplate(e){return this.sendJson(u.Delete,`${this.config[_.BusinessAcctId]}/${this.endpoint}${M(e)}`,this.config[_.RequestTimeout],null)}};function U(e){let t={type:`HEADER`,format:e.format};return e.text&&(t.text=e.text),e.example&&(t.example=e.example),t}function W(e){let t={type:`BODY`,text:e.text};return e.example&&(t.example=e.example),t}function G(e){return{type:`FOOTER`,text:e.text}}function K(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 Te(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 Ee(e){let t=[];if(e.header&&t.push(U(e.header)),e.body&&t.push(W(e.body)),e.footer&&t.push(G(e.footer)),e.buttons&&t.push(...K(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:[Te(e.bodyParameters)]}:void 0}),e.buttons&&n.push(...K(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 De(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:c.Authentication,components:t}}function Oe(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:c.Authentication,components:t}}function ke(e){let t=[];return e.header&&t.push(U({...e.header,format:`TEXT`})),t.push(W(e.body)),e.footer&&t.push(G(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:c.Marketing,components:t}}function Ae(e){let t=[];return e.header&&t.push(U({...e.header,format:`TEXT`})),t.push(W(e.body)),e.footer&&t.push(G(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`COPY_CODE`,example:e.coupon_code}]}),{name:e.name,language:e.language,category:c.Marketing,components:t}}function je(e){let t=[];return t.push({type:`LIMITED_TIME_OFFER`,limited_time_offer:{expiration_time_ms:e.expiration_time_ms}}),e.header&&t.push(U({...e.header,format:`TEXT`})),t.push(W(e.body)),e.footer&&t.push(G(e.footer)),{name:e.name,language:e.language,category:c.Marketing,components:t}}function Me(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(W(e.body)),e.buttons&&r.push(...K(e.buttons)),n.push({card_index:t,components:r})}),t.push({type:`CAROUSEL`,cards:n}),{name:e.name,language:e.language,category:c.Marketing,components:t}}function Ne(e){let t=[];return e.header&&t.push(U({...e.header,format:`TEXT`})),t.push(W(e.body)),e.footer&&t.push(G(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:c.Marketing,components:t}}function Pe(e){let t=[];e.header&&t.push(U({...e.header,format:`TEXT`})),t.push(W(e.body)),e.footer&&t.push(G(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:c.Marketing,components:t}}function Fe(e){let t=[];return e.header&&t.push(U({...e.header,format:`TEXT`})),t.push(W(e.body)),e.footer&&t.push(G(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`SPM`,action:{product_retailer_id:e.product_retailer_id}}]}),{name:e.name,language:e.language,category:c.Marketing,components:t}}var Ie=class extends j{constructor(e,t){super(e,t)}async setTwoStepVerificationCode(e){let t={pin:e};return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}`,this.config[_.RequestTimeout],JSON.stringify(t))}},Le=class extends j{constructor(e,t){super(e,t)}async getWabaAccount(e){let t=V(e)?.replace(/,/g,`%2C`);return this.sendJson(u.Get,`${this.config[_.BusinessAcctId]}${t}`,this.config[_.RequestTimeout],null)}async getAllWabaSubscriptions(){return this.sendJson(u.Get,`${this.config[_.BusinessAcctId]}/subscribed_apps`,this.config[_.RequestTimeout],null)}async updateWabaSubscription({override_callback_uri:e,verify_token:t}){let n={override_callback_uri:e,verify_token:t};return this.sendJson(u.Post,`${this.config[_.BusinessAcctId]}/subscribed_apps`,this.config[_.RequestTimeout],JSON.stringify(n))}async unsubscribeFromWaba(){return this.sendJson(u.Delete,`${this.config[_.BusinessAcctId]}/subscribed_apps`,this.config[_.RequestTimeout],null)}};function Re(){process.env.NODE_ENV===`test`||process.env.VITEST===`true`||typeof global<`u`&&global.__VITEST__||console.log(`\x1B[36m%s\x1B[0m`,`
|
|
12
|
+
Your key format is not recognized. Please ensure it is in PKCS#8 format.`),Error(t)}let d;try{D.info(`Decrypting AES key`),d=r.privateDecrypt({key:u,padding:r.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:`sha256`},Buffer.from(n,`base64`))}catch(e){throw D.error(`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);D.info(`Decrypting flow data`);let g=r.createDecipheriv(`aes-128-gcm`,d,p);g.setAuthTag(h);let _=Buffer.concat([g.update(m),g.final()]).toString(`utf-8`);return D.info(`Flow request decryption complete`),{decryptedBody:JSON.parse(_),aesKeyBuffer:d,initialVectorBuffer:p}}function pe(e,t,n){D.info(`Encrypting flow response`);let i=[];for(let e of Array.from(n.entries()))i.push(~e[1]);try{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 D.info(`Flow response encryption complete`),a}catch(e){throw D.error(`Response encryption error:`,e),Error(`Failed to encrypt response. Internal server error.`)}}function k(e){return typeof e==`object`&&!!e&&`error`in e&&typeof e.error==`object`&&e.error!=null&&`message`in e.error&&typeof e.error.message==`string`&&`type`in e.error&&typeof e.error.type==`string`&&`code`in e.error&&typeof e.error.code==`number`&&`fbtrace_id`in e.error&&typeof e.error.fbtrace_id==`string`&&(!(`error_data`in e.error)||typeof e.error.error_data==`object`&&e.error.error_data!=null&&`messaging_product`in e.error.error_data&&e.error.error_data.messaging_product===`whatsapp`&&`details`in e.error.error_data&&typeof e.error.error_data.details==`string`)&&(!(`error_subcode`in e.error)||typeof e.error.error_subcode==`number`)}const A=new E(`HttpsClient`,process.env.DEBUG===`true`);var me=class{agent;constructor(){this.agent=new i({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(e,t,n,r,i,a){let o=`https://${e}/${t}`,s=new AbortController,c=setTimeout(()=>s.abort(),i);try{let e=await fetch(o,{method:n,headers:r,body:a,signal:s.signal});return A.log(`${n} : ${o} - ${JSON.stringify(e)}`),clearTimeout(c),new he(e)}catch(e){throw A.error(`${n} : ${o} - ${JSON.stringify(e)}`),e}}},he=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){throw Error(`Failed to parse response body to JSON: `+e.message)}}};const ge=new E(`REQUESTER`,process.env.DEBUG===`true`);var _e=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol=`https:`;constructor(e,t,n,r,i){this.client=new me,this.host=`graph.facebook.com`,this.apiVersion=e||`22`,this.phoneNumberId=t,this.accessToken=n,this.businessAcctId=r,this.userAgent=i}buildHeader(e,t){let n={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return e!==`multipart/form-data`&&(n[`Content-Type`]=e),t&&Object.assign(n,t),n}buildCAPIPath(e){return`v${this.apiVersion}.0/${e}`}async sendRequest(e,t,n,r,i=`application/json`,a){let o=i;r instanceof FormData?o=`multipart/form-data`:typeof r==`string`&&r.startsWith(`<?xml`)&&(o=`application/xml`);let s=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(t)}`;ge.log(`${e} : ${s} (${o})`);try{let i=await this.client.sendRequest(this.host,this.buildCAPIPath(t),e,this.buildHeader(o,a),n,e===`POST`||e===`PUT`?r:void 0);if(!i.rawResponse().ok){let e=await i.json();throw k(e)?e:{name:`MetaError`,message:`Unknown error occurred`,error:{message:e.message||`Unknown error occurred`,type:`UnknownError`,code:i.statusCode(),fbtrace_id:``}}}return i}catch(e){throw k(e)?e:{name:`MetaError`,message:e instanceof Error?e.message:`Network error occurred`,error:{message:e instanceof Error?e.message:`Network error occurred`,type:`NetworkError`,code:500,fbtrace_id:``}}}}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()}async sendUrlEncodedForm(e,t,n,r,i){let a=new URLSearchParams(r).toString();return await(await this.sendRequest(e,t,n,a,`application/x-www-form-urlencoded`,i)).json()}};function j(){try{let e=o(__dirname,`../../package.json`);return JSON.parse(a(e,`utf-8`)).version}catch{return`unknown`}}function ve(){let e=j(),t=process.version;return`WhatsApp-Nodejs-SDK/${e} (Node.js ${t})`}var M=class{config;client;constructor(e,t){this.config=e,this.client=t}sendJson(e,t,n,r){return this.client.getJson(e,t,n,r)}sendFormData(e,t,n,r){return this.client.sendFormData(e,t,n,r)}sendUrlEncodedForm(e,t,n,r){return this.client.sendUrlEncodedForm(e,t,n,r)}};const N=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(`&`)}`:``};var P=class extends M{endpoint=`block_users`;constructor(e,t){super(e,t)}buildBlockUsersBody(e){return{messaging_product:`whatsapp`,block_users:e.map(e=>({user:e}))}}async block(e){if(!e||e.length===0)throw Error(`At least one user must be provided to block`);let t=this.buildBlockUsersBody(e);return await this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(t))}async unblock(e){if(!e||e.length===0)throw Error(`At least one user must be provided to unblock`);let t=this.buildBlockUsersBody(e);return await this.sendJson(u.Delete,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(t))}async listBlockedUsers(e){let t=`${this.config[_.PhoneNumberId]}/${this.endpoint}`;if(e){let n=N(e);n&&(t+=`?${n}`)}return await this.sendJson(u.Get,t,this.config[_.RequestTimeout])}},F=class extends M{endpoint=`whatsapp_business_encryption`;constructor(e,t){super(e,t)}async getEncryptionPublicKey(){return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],null)}async setEncryptionPublicKey(e){let t=new FormData;return t.append(`business_public_key`,e),this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],t)}},I=class extends M{constructor(e,t){super(e,t)}async listFlows(e){return this.sendJson(u.Get,`/${e}/flows`,this.config[_.RequestTimeout],null)}async createFlow(e,t){let n={name:t.name,categories:t.categories,...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.clone_flow_id&&{clone_flow_id:t.clone_flow_id},...t.flow_json&&{flow_json:t.flow_json},...t.publish!==void 0&&{publish:t.publish}};return this.sendJson(u.Post,`/${e}/flows`,this.config[_.RequestTimeout],JSON.stringify(n))}async getFlow(e,t,n){let r=new URLSearchParams;t&&r.append(`fields`,t),n&&r.append(`date_format`,n);let i=r.toString()?`?${r.toString()}`:``;return this.sendJson(u.Get,`/${e}${i}`,this.config[_.RequestTimeout],null)}async getFlowPreview(e,t=!1){let n=`preview.invalidate(${t})`;return this.getFlow(e,n)}async updateFlowMetadata(e,t){let n={...t.name&&{name:t.name},...t.categories&&{categories:t.categories},...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.application_id&&{application_id:t.application_id}};return this.sendJson(u.Post,`/${e}`,this.config[_.RequestTimeout],JSON.stringify(n))}async deleteFlow(e){return this.sendJson(u.Delete,`/${e}`,this.config[_.RequestTimeout],null)}async listAssets(e){return this.sendJson(u.Get,`/${e}/assets`,this.config[_.RequestTimeout],null)}async updateFlowJson(e,t){let n=new FormData,r;if(t.file instanceof Buffer)r=new globalThis.Blob([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(u.Post,`/${e}/assets`,this.config[_.RequestTimeout],n)}async validateFlowJson(e,t){try{let n=await this.updateFlowJson(e,{file:t}),r=!n.validation_errors||n.validation_errors.length===0;return{...n,valid:r}}catch(e){throw e}}async publishFlow(e){return this.sendJson(u.Post,`/${e}/publish`,this.config[_.RequestTimeout],JSON.stringify({}))}async deprecateFlow(e){return this.sendJson(u.Post,`/${e}/deprecate`,this.config[_.RequestTimeout],JSON.stringify({}))}async migrateFlows(e,t){let n={source_waba_id:t.source_waba_id,...t.source_flow_names&&{source_flow_names:t.source_flow_names}};return this.sendJson(u.Post,`/${e}/migrate_flows`,this.config[_.RequestTimeout],JSON.stringify(n))}};let ye=function(e){return e.Draft=`DRAFT`,e.Published=`PUBLISHED`,e.Throttled=`THROTTLED`,e.Blocked=`BLOCKED`,e.Deprecated=`DEPRECATED`,e}({}),be=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}({}),L=function(e){return e.INIT=`INIT`,e.BACK=`BACK`,e.DATA_EXCHANGE=`data_exchange`,e}({}),R=function(e){return e.Ping=`ping`,e.Change=`data_exchange`,e.Error=`error`,e.All=`*`,e}({});var z=class extends M{endpoint=`media`;constructor(e,t){super(e,t)}async getMediaById(e,t){return this.sendJson(u.Get,`${e}`,this.config[_.RequestTimeout],null)}async uploadMedia(e,t=`whatsapp`){let n=new FormData;return n.append(`file`,e),n.append(`messaging_product`,t),n.append(`type`,e.type),this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],n)}async deleteMedia(e,t){return this.sendJson(u.Delete,`${e}`,this.config[_.RequestTimeout],null)}async downloadMedia(e){return this.sendJson(u.Get,e,this.config[_.RequestTimeout],null)}},B=class extends M{commonMethod=u.Post;commonEndpoint=`messages`;constructor(e,t){super(e,t)}bodyBuilder(e,t,n,r){let i={messaging_product:`whatsapp`,recipient_type:`individual`,to:n,type:e,[e]:t};return r&&(i.context={message_id:r}),i}send(e){return this.sendJson(this.commonMethod,`${this.config[_.PhoneNumberId]}/${this.commonEndpoint}`,this.config[_.RequestTimeout],e)}async audio(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Audio,t,n,r)))}async contacts(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Contacts,t,n,r)))}async document(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Document,t,n,r)))}async image(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Image,t,n,r)))}async interactive(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Interactive,t,n,r)))}async location(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Location,t,n,r)))}async sticker(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Sticker,t,n,r)))}async template(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Template,t,n,r)))}async text(e){let{body:t,to:n,replyMessageId:r,previewUrl:i}=e,a=typeof t==`string`?{body:t,preview_url:i??!0}:{...t,preview_url:i??t.preview_url??!0};return this.send(JSON.stringify(this.bodyBuilder(d.Text,a,n,r)))}async video(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Video,t,n,r)))}async status(e){let t={messaging_product:`whatsapp`,status:e.status,message_id:e.messageId,...e.typingIndicator&&{typing_indicator:e.typingIndicator}};return this.send(JSON.stringify(t))}async markAsRead(e){return this.status({status:`read`,messageId:e.messageId})}async showTypingIndicator(e){return this.status({status:`read`,messageId:e.messageId,typingIndicator:{type:`text`}})}async interactiveList(e){return this.interactive(e)}async interactiveCtaUrl(e){return this.interactive(e)}async interactiveLocationRequest(e){return this.interactive(e)}async interactiveAddressMessage(e){return this.interactive(e)}async interactiveReplyButtons(e){return this.interactive(e)}async interactiveFlow(e){return this.interactive(e)}async reaction(e){let t={message_id:e.messageId,emoji:e.emoji};return this.send(JSON.stringify(this.bodyBuilder(d.Reaction,t,e.to)))}},V=class extends M{endpoint=`phone_numbers`;constructor(e,t){super(e,t)}async getPhoneNumberById(e){let t=e?N({fields:e}):``;return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}${t}`,this.config[_.RequestTimeout],null)}async getPhoneNumbers(){return this.sendJson(u.Get,`${this.config[_.BusinessAcctId]}/${this.endpoint}`,this.config[_.RequestTimeout],null)}async requestVerificationCode(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/request_code`,this.config[_.RequestTimeout],JSON.stringify(e))}async verifyCode(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/verify_code`,this.config[_.RequestTimeout],JSON.stringify(e))}async setConversationalAutomation(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/conversational_automation`,this.config[_.RequestTimeout],JSON.stringify(e))}async getConversationalAutomation(){let e=N({fields:`conversational_automation`});return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}${e}`,this.config[_.RequestTimeout],null)}async getThroughput(){let e=N({fields:`throughput`});return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}${e}`,this.config[_.RequestTimeout],null)}};function H(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 U=class extends M{endpoint=`whatsapp_business_profile`;constructor(e,t){super(e,t)}async getBusinessProfile(e){return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}/${this.endpoint}${H(e)}`,this.config[_.RequestTimeout],null)}async updateBusinessProfile(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(e))}async createUploadSession(e,t,n){let r=N({file_length:e,file_type:t,file_name:n});return this.sendJson(u.Post,`app/uploads/${r}`,this.config[_.RequestTimeout],null)}async uploadMedia(e,t){return this.sendJson(u.Post,`${e}`,this.config[_.RequestTimeout],t)}async getUploadHandle(e){return this.sendJson(u.Get,`${e}`,this.config[_.RequestTimeout],null)}},xe=class extends M{endpoint=`message_qrdls`;constructor(e,t){super(e,t)}async createQrCode(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(e))}async getQrCodes(){return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],null)}async getQrCode(e){return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}/${this.endpoint}/${e}`,this.config[_.RequestTimeout],null)}async updateQrCode(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(e))}async deleteQrCode(e){return this.sendJson(u.Delete,`${this.config[_.PhoneNumberId]}/${this.endpoint}/${e}`,this.config[_.RequestTimeout],null)}},Se=class extends M{constructor(e,t){super(e,t)}async register(e,t){let n={messaging_product:`whatsapp`,pin:e,...t&&{data_localization_region:t}};return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/register`,this.config[_.RequestTimeout],JSON.stringify(n))}async deregister(){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/deregister`,this.config[_.RequestTimeout],null)}},Ce=class extends M{endpoint=`message_templates`;constructor(e,t){super(e,t)}async getTemplate(e){return this.sendJson(u.Get,`${e}`,this.config[_.RequestTimeout],null)}async updateTemplate(e,t){return this.sendJson(u.Post,`${e}`,this.config[_.RequestTimeout],JSON.stringify(t))}async getTemplates(e){return this.sendJson(u.Get,`${this.config[_.BusinessAcctId]}/${this.endpoint}${N(e??{})}`,this.config[_.RequestTimeout],null)}async createTemplate(e){return this.sendJson(u.Post,`${this.config[_.BusinessAcctId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(e))}async deleteTemplate(e){return this.sendJson(u.Delete,`${this.config[_.BusinessAcctId]}/${this.endpoint}${N(e)}`,this.config[_.RequestTimeout],null)}};function W(e){let t={type:`HEADER`,format:e.format};return e.text&&(t.text=e.text),e.example&&(t.example=e.example),t}function G(e){let t={type:`BODY`,text:e.text};return e.example&&(t.example=e.example),t}function K(e){return{type:`FOOTER`,text:e.text}}function q(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 we(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 Te(e){let t=[];if(e.header&&t.push(W(e.header)),e.body&&t.push(G(e.body)),e.footer&&t.push(K(e.footer)),e.buttons&&t.push(...q(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:[we(e.bodyParameters)]}:void 0}),e.buttons&&n.push(...q(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 Ee(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:c.Authentication,components:t}}function De(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:c.Authentication,components:t}}function Oe(e){let t=[];return e.header&&t.push(W({...e.header,format:`TEXT`})),t.push(G(e.body)),e.footer&&t.push(K(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:c.Marketing,components:t}}function ke(e){let t=[];return e.header&&t.push(W({...e.header,format:`TEXT`})),t.push(G(e.body)),e.footer&&t.push(K(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`COPY_CODE`,example:e.coupon_code}]}),{name:e.name,language:e.language,category:c.Marketing,components:t}}function Ae(e){let t=[];return t.push({type:`LIMITED_TIME_OFFER`,limited_time_offer:{expiration_time_ms:e.expiration_time_ms}}),e.header&&t.push(W({...e.header,format:`TEXT`})),t.push(G(e.body)),e.footer&&t.push(K(e.footer)),{name:e.name,language:e.language,category:c.Marketing,components:t}}function je(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(G(e.body)),e.buttons&&r.push(...q(e.buttons)),n.push({card_index:t,components:r})}),t.push({type:`CAROUSEL`,cards:n}),{name:e.name,language:e.language,category:c.Marketing,components:t}}function Me(e){let t=[];return e.header&&t.push(W({...e.header,format:`TEXT`})),t.push(G(e.body)),e.footer&&t.push(K(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:c.Marketing,components:t}}function Ne(e){let t=[];e.header&&t.push(W({...e.header,format:`TEXT`})),t.push(G(e.body)),e.footer&&t.push(K(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:c.Marketing,components:t}}function Pe(e){let t=[];return e.header&&t.push(W({...e.header,format:`TEXT`})),t.push(G(e.body)),e.footer&&t.push(K(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`SPM`,action:{product_retailer_id:e.product_retailer_id}}]}),{name:e.name,language:e.language,category:c.Marketing,components:t}}var Fe=class extends M{constructor(e,t){super(e,t)}async setTwoStepVerificationCode(e){let t={pin:e};return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}`,this.config[_.RequestTimeout],JSON.stringify(t))}},Ie=class extends M{constructor(e,t){super(e,t)}async getWabaAccount(e){let t=H(e)?.replace(/,/g,`%2C`);return this.sendJson(u.Get,`${this.config[_.BusinessAcctId]}${t}`,this.config[_.RequestTimeout],null)}async getAllWabaSubscriptions(){return this.sendJson(u.Get,`${this.config[_.BusinessAcctId]}/subscribed_apps`,this.config[_.RequestTimeout],null)}async updateWabaSubscription({override_callback_uri:e,verify_token:t}){let n={override_callback_uri:e,verify_token:t};return this.sendJson(u.Post,`${this.config[_.BusinessAcctId]}/subscribed_apps`,this.config[_.RequestTimeout],JSON.stringify(n))}async unsubscribeFromWaba(){return this.sendJson(u.Delete,`${this.config[_.BusinessAcctId]}/subscribed_apps`,this.config[_.RequestTimeout],null)}};function Le(){process.env.NODE_ENV===`test`||process.env.VITEST===`true`||typeof global<`u`&&global.__VITEST__||console.log(`\x1B[36m%s\x1B[0m`,`
|
|
13
13
|
██████╗ ██╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ██████╗ ██╗
|
|
14
14
|
██╔════╝ ██║ ██╔═══██╗ ██║ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║
|
|
15
15
|
██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ███████║ ██████╔╝ ██║
|
|
16
16
|
██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██╔══██║ ██╔═══╝ ██║
|
|
17
17
|
╚██████╗ ███████╗ ╚██████╔╝ ╚██████╔╝ ██████╔╝ ██║ ██║ ██║ ██║
|
|
18
18
|
╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝
|
|
19
|
-
`)}const
|
|
20
|
-
`+de(this.config))}updateTimeout(e){this.config[_.RequestTimeout]=e,`updateTimeout`in this.requester&&this.requester.updateTimeout(e),q.log(`Timeout updated to ${e}ms`)}updateSenderNumberId(e){this.config[_.PhoneNumberId]=e,q.log(`Sender number ID updated to ${e}`)}updateAccessToken(e){this.config[_.AccessToken]=e,`updateAccessToken`in this.requester&&this.requester.updateAccessToken(e),q.log(`Access token updated`)}version(){return A()}static get Enums(){return s}getUserAgent(){return ye()}generateEncryption(e){let t=e||this.config[_.Passphrase];return D(t)}};function Be(e){return typeof e==`object`&&!!e}function J(e){return typeof e==`string`}const Ve=[I.DATA_EXCHANGE,I.INIT,I.BACK],He=[I.DATA_EXCHANGE,I.INIT];function Ue(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=Ve.includes(t),s=r===void 0||J(r)&&r!==`SUCCESS`,c=t===I.DATA_EXCHANGE||Be(i);return a&&o&&s&&c}function We(e){if(!(`flow_token`in e&&J(e.flow_token)&&`action`in e))return!1;let{action:t,screen:n,data:r}=e,i=He.includes(t),a=J(n),o=Be(r)&&`error_key`in r&&J(r.error)&&`error_message`in r&&J(r.error_message);return i&&a&&o}function Ge(e){return`action`in e&&e.action===`ping`}const Y=new T(`WEBHOOK_UTILS`,process.env.DEBUG===`true`);async function Ke(e,t,n){try{let r=await e.json();if(r.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 i=[];for(let e of r.entry)try{let r=e.changes;for(let i of r)i.field===`messages`&&await Ze(e.id,i.value,t,n)}catch(t){let n=`Error processing webhook: ${t}`;Y.error(n,{entry:e,error:t}),i.push(n)}return new Response(i.length>0?JSON.stringify({errors:i}):null,{status:200})}catch(e){return Y.error(`Error processing webhook:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500})}}function qe(){return{version:`3.0`,data:{status:`active`}}}function X(){return{data:{acknowledged:!0}}}async function Je(e,t,n,r){try{let i=await e.text(),a=e.headers.get(`x-hub-signature-256`);if(!Ye(i,a,t.WEBHOOK_VERIFICATION_TOKEN||``))return Y.warn(`Invalid request signature`),new Response(JSON.stringify({error:`Unauthorized`}),{status:401});let o=JSON.parse(i),{decryptedBody:s,aesKeyBuffer:c,initialVectorBuffer:l}=pe(o,t),u=Ge(s),d=We(s),f=Ue(s),p=u?L.Ping:d?L.Error:f?L.Change:L.All,m=r.get(p);if(!m){if(p===L.Ping)m=()=>qe();else if(p===L.Error)m=()=>X();else if(m=r.get(L.All),!m)return Y.warn(`No handler registered for flow type:`,{flowType:p,action:s.action}),new Response(JSON.stringify({error:`Handler not found`}),{status:404})}let h=await m(n,s);if(d){Y.warn(`Flow error notification received`,{error:s.data});let e=h||X();return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":`application/json`}})}if(u||f){let e=me(h,c,l);return new Response(e,{status:200,headers:{"Content-Type":`text/plain`}})}return Y.warn(`Unknown flow request type:`,s),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})}}function Ye(e,t,n){if(!t)return Y.warn(`Missing signature in request`),!1;let i=r.createHmac(`sha256`,n).update(e).digest(`hex`);return r.timingSafeEqual(Buffer.from(t.replace(`sha256=`,``)),Buffer.from(i))}function Xe(e,t){let n=e[`x-forwarded-proto`]||`http`,r=e.host||`localhost`;return`${n}://${r}${t||`/`}`}async function Ze(e,t,n,r){let i=t.metadata,a=e,o=i.display_phone_number,s=i.phone_number_id;if(`statuses`in t&&t.statuses){let e=t;for(let t of e.statuses){let e={wabaId:a,phoneNumberId:s,displayPhoneNumber:o,status:t};await Qe(r.statusHandler,n,e)}return}if(`messages`in t&&t.messages){let e=t,i=e.contacts?.[0]?.profile?.name||``;for(let t of e.messages){let e={wabaId:a,phoneNumberId:s,displayPhoneNumber:o,profileName:i,message:t},c=t.type;await Z(r.preProcessHandler,n,e,`pre-process`),await Z(r.messageHandlers.get(c),n,e,c),await Z(r.postProcessHandler,n,e,`post-process`)}}}async function Z(e,t,n,r){if(e)try{await e(t,n)}catch(e){Y.error(`Error in ${r} handler:`,{error:e,messageId:n.message.id})}}async function Qe(e,t,n){if(e)try{await e(t,n)}catch(e){Y.error(`Error in status handler:`,{error:e,statusId:n.status.id})}}const Q=new T(`WEBHOOK_PROCESSOR`,process.env.DEBUG===`true`);var $=class{config;client;messageHandlers=new Map;statusHandler=void 0;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(e){this.config=ue(e),this.client=new ze(e),Q.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 Ke(e,this.client,{messageHandlers:this.messageHandlers,statusHandler:this.statusHandler,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler}),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 Q.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 Je(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 Q.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),Q.log(`Registered message handler for ${e}`)}onStatus(e){this.statusHandler=e,Q.log(`Registered status handler`)}onMessagePreProcess(e){this.preProcessHandler=e,Q.log(`Registered pre-process handler`)}onMessagePostProcess(e){this.postProcessHandler=e,Q.log(`Registered post-process handler`)}onFlow(e,t){this.flowHandlers.set(e,t),Q.log(`Registered flow handler for ${e}`)}getClient(){return this.client}getConfig(){return this.config}},$e=class{processor;constructor(e){this.processor=new $(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 Xe(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}},et=class extends $e{constructor(e){super(e)}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){throw n(e),e}}async handlePost(e,t,n){try{let n=this.constructFullUrl(e.headers,e.url),r=new globalThis.Request(n,{method:e.method,headers:e.headers,body:JSON.stringify(e.body)}),i=await this.processWebhook(r);return this.applyHeaders(i,t),t.status(i.status).send(i.body),i}catch(e){throw n(e),e}}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){throw n(e),e}}getHandlers(){return{GET:(e,t,n)=>this.handleGet(e,t,n),POST:(e,t,n)=>this.handlePost(e,t,n),webhook:(e,t,n)=>this.autoRoute(e,t,n),flow:(e,t,n)=>this.handleFlow(e,t,n),processor:this.webhookProcessor}}};function tt(e){return new et(e).getHandlers()}var nt=class extends $e{constructor(e){super(e)}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){throw console.error(`Webhook verification error:`,e),t.status(500).json({error:`Internal Server Error`}),e}}async handlePost(e,t){try{await this.parseRequestBody(e)}catch(e){throw console.error(`Webhook processing error:`,e),e instanceof Error&&e.message===`Invalid JSON in request body`?(t.status(400).json({error:`Invalid JSON`}),e):(t.status(500).json({error:`Internal Server Error`}),e)}try{let n=this.constructFullUrl(e.headers,e.url),r=new Request(n,{method:`POST`,headers:e.headers,body:JSON.stringify(e.body)}),i=await this.processWebhook(r);return this.applyHeaders(i,t),t.status(i.status).send(i.body),i}catch(e){throw console.error(`Webhook processing error:`,e),t.status(500).json({error:`Internal Server Error`}),e}}async handleFlow(e,t){try{await this.parseRequestBody(e,!0)}catch(e){throw console.error(`Flow body parsing error:`,e),e instanceof Error&&e.message===`Invalid JSON in request body`?(t.status(400).json({error:`Invalid JSON`}),e):(t.status(500).json({error:`Internal Server Error`}),e)}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){throw console.error(`Flow error:`,e),t.status(500).json({error:`Internal Server Error`}),e}}getHandlers(){return{GET:(e,t)=>this.handleGet(e,t),POST:(e,t)=>this.handlePost(e,t),webhook:(e,t)=>this.autoRoute(e,t),flow:(e,t)=>this.handleFlow(e,t),processor:this.webhookProcessor}}};function rt(e){return new nt(e).getHandlers()}function it(e){let t=new $(e);return{GET:async e=>{try{let{searchParams:n}=new URL(e.url),r=n.get(`hub.mode`),i=n.get(`hub.verify_token`),a=n.get(`hub.challenge`),o=await t.processVerification(r,i,a);return new Response(o.body,{status:o.status,headers:o.headers})}catch(e){return console.error(`Webhook verification error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let n=await t.processWebhook(e);return new Response(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}},webhook:{GET:async e=>{try{let{searchParams:n}=new URL(e.url),r=n.get(`hub.mode`),i=n.get(`hub.verify_token`),a=n.get(`hub.challenge`),o=await t.processVerification(r,i,a);return new Response(o.body,{status:o.status,headers:o.headers})}catch(e){return console.error(`Webhook verification error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let n=await t.processWebhook(e);return new Response(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}}},flow:{GET:async e=>{try{let n=await t.processFlow(e);return new Response(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Flow GET error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}},POST:async e=>{try{let n=await t.processFlow(e);return new Response(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Flow POST error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}}},processor:t}}const at=(e,t)=>n.createHmac(`sha256`,t).update(e,`utf-8`).digest(`hex`);let ot=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),st=function(e){return e.Blocked=`BLOCKED`,e.Limited=`LIMITED`,e.Available=`AVAILABLE`,e}({}),ct=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),lt=function(e){return e.Verified=`verified`,e.PendingSubmission=`pending_submission`,e.Unverified=`unverified`,e.Rejected=`rejected`,e}({});export{S as AudioMediaTypesEnum,N as BlockUsersApi,H as BusinessProfileApi,se as BusinessVerticalEnum,m as ButtonPositionEnum,c as CategoryEnum,g as ComponentTypesEnum,ee as ConversationTypesEnum,ae as CurrencyCodesEnum,oe as DataLocalizationRegionEnum,x as DocumentMediaTypesEnum,P as EncryptionApi,I as FlowActionEnum,F as FlowApi,xe as FlowCategoryEnum,be as FlowStatusEnum,L as FlowTypeEnum,u as HttpMethodsEnum,b as ImageMediaTypesEnum,p as InteractiveTypesEnum,ie as LanguagesEnum,T as Logger,R as MediaApi,z as MessageApi,z as MessagesApi,d as MessageTypesEnum,f as ParametersTypesEnum,B as PhoneNumberApi,Se as QrCodeApi,ne as ReferralSourceTypesEnum,Ce as RegistrationApi,re as RequestCodeMethodsEnum,te as StatusEnum,y as StickerMediaTypesEnum,h as SubTypeEnum,w as SystemChangeTypesEnum,we as TemplateApi,l as TemplateStatusEnum,Ie as TwoStepVerificationApi,v as VideoMediaTypesEnum,ot as WabaAccountReviewStatus,ct as WabaAccountStatus,Le as WabaApi,lt as WabaBusinessVerificationStatus,_ as WabaConfigEnum,st as WabaHealthStatusCanSendMessage,$ as WebhookProcessor,C as WebhookTypesEnum,ze as WhatsApp,V as buildFieldsQueryString,Xe as constructFullUrl,Oe as createAuthenticationTemplate,ke as createCatalogTemplate,Ae as createCouponTemplate,je as createLimitedTimeOfferTemplate,Ne as createMPMTemplate,Me as createMediaCardCarouselTemplate,De as createOTPTemplate,Pe as createProductCardCarouselTemplate,Fe as createSPMTemplate,Ee as createTemplate,tt as expressWebhookHandler,de as formatConfigTable,D as generateEncryption,at as generateXHub256Sig,Ue as isFlowDataExchangeRequest,We as isFlowErrorRequest,Ge as isFlowPingRequest,O as isMetaError,it as nextjsAppWebhookHandler,rt as nextjsPagesWebhookHandler,M as objectToQueryString,Je as processFlowRequest,Ke as processWebhookMessages};
|
|
19
|
+
`)}const J=new E(`WHATSAPP`,process.env.DEBUG===`true`);var Re=class{config;requester;blockUsers;messages;media;phoneNumbers;twoStepVerification;flows;businessProfile;templates;encryption;qrCode;registration;waba;constructor(e){Le(),this.config=le(e),this.requester=new _e(this.config[_.APIVersion],this.config[_.PhoneNumberId],this.config[_.AccessToken],this.config[_.BusinessAcctId],this.getUserAgent()),this.blockUsers=new P(this.config,this.requester),this.messages=new B(this.config,this.requester),this.media=new z(this.config,this.requester),this.phoneNumbers=new V(this.config,this.requester),this.twoStepVerification=new Fe(this.config,this.requester),this.flows=new I(this.config,this.requester),this.businessProfile=new U(this.config,this.requester),this.templates=new Ce(this.config,this.requester),this.encryption=new F(this.config,this.requester),this.qrCode=new xe(this.config,this.requester),this.registration=new Se(this.config,this.requester),this.waba=new Ie(this.config,this.requester),J.log(`
|
|
20
|
+
`+ue(this.config))}updateTimeout(e){this.config[_.RequestTimeout]=e,`updateTimeout`in this.requester&&this.requester.updateTimeout(e),J.log(`Timeout updated to ${e}ms`)}updateSenderNumberId(e){this.config[_.PhoneNumberId]=e,J.log(`Sender number ID updated to ${e}`)}updateAccessToken(e){this.config[_.AccessToken]=e,`updateAccessToken`in this.requester&&this.requester.updateAccessToken(e),J.log(`Access token updated`)}version(){return j()}static get Enums(){return s}getUserAgent(){return ve()}generateEncryption(e){let t=e||this.config[_.Passphrase];return O(t)}};function ze(e){return typeof e==`object`&&!!e}function Y(e){return typeof e==`string`}const Be=[L.DATA_EXCHANGE,L.INIT,L.BACK],Ve=[L.DATA_EXCHANGE,L.INIT];function He(e){if(!(`flow_token`in e&&Y(e.flow_token)&&`action`in e))return!1;let{action:t,version:n,screen:r,data:i}=e,a=n===`3.0`,o=Be.includes(t),s=r===void 0||Y(r)&&r!==`SUCCESS`,c=t===L.DATA_EXCHANGE||ze(i);return a&&o&&s&&c}function Ue(e){if(!(`flow_token`in e&&Y(e.flow_token)&&`action`in e))return!1;let{action:t,screen:n,data:r}=e,i=Ve.includes(t),a=Y(n),o=ze(r)&&`error_key`in r&&Y(r.error)&&`error_message`in r&&Y(r.error_message);return i&&a&&o}function We(e){return`action`in e&&e.action===`ping`}const X=new E(`WEBHOOK_UTILS`,process.env.DEBUG===`true`);async function Ge(e,t,n){try{let r=await e.json();if(r.object!==`whatsapp_business_account`){let e=`Received webhook for non-WhatsApp event`;return X.warn(e),new Response(JSON.stringify({error:e}),{status:404})}let i=[];for(let e of r.entry)try{let r=e.changes;for(let i of r)i.field===`messages`&&await Qe(e.id,i.value,t,n)}catch(t){let n=`Error processing webhook: ${t}`;X.error(n,{entry:e,error:t}),i.push(n)}return new Response(i.length>0?JSON.stringify({errors:i}):null,{status:200})}catch(e){return X.error(`Error processing webhook:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500})}}function Ke(){return{version:`3.0`,data:{status:`active`}}}function qe(){return{data:{acknowledged:!0}}}async function Je(e,t,n,r){try{let i=await e.text(),a=e.headers.get(`x-hub-signature-256`);if(!Ye(i,a,t.WEBHOOK_VERIFICATION_TOKEN||``))return X.warn(`Invalid request signature`),new Response(JSON.stringify({error:`Unauthorized`}),{status:401});let o=JSON.parse(i),{decryptedBody:s,aesKeyBuffer:c,initialVectorBuffer:l}=fe(o,t),u=We(s),d=Ue(s),f=He(s),p=u?R.Ping:d?R.Error:f?R.Change:R.All,m=r.get(p);if(!m){if(p===R.Ping)m=()=>Ke();else if(p===R.Error)m=()=>qe();else if(m=r.get(R.All),!m)return X.warn(`No handler registered for flow type:`,{flowType:p,action:s.action}),new Response(JSON.stringify({error:`Handler not found`}),{status:404})}let h=await m(n,s);if(d){X.warn(`Flow error notification received`,{error:s.data});let e=h||qe();return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":`application/json`}})}if(u||f){let e=pe(h,c,l);return new Response(e,{status:200,headers:{"Content-Type":`text/plain`}})}return X.warn(`Unknown flow request type:`,s),new Response(JSON.stringify({error:`Unknown request type`}),{status:400})}catch(e){return X.error(`Error handling flow request:`,e),new Response(JSON.stringify({error:`Internal server error`}),{status:500})}}function Ye(e,t,n){if(!t)return X.warn(`Missing signature in request`),!1;let i=r.createHmac(`sha256`,n).update(e).digest(`hex`);return r.timingSafeEqual(Buffer.from(t.replace(`sha256=`,``)),Buffer.from(i))}function Xe(e,t){let n=e[`x-forwarded-proto`]||`http`,r=e.host||`localhost`;return`${n}://${r}${t||`/`}`}function Ze(e){if(e.id)return e.id;if(e.type===d.Interactive||e.type===d.Button){let t=e;if(t.context?.id)return t.context.id}return``}async function Qe(e,t,n,r){let i=t.metadata,a=e,o=i.display_phone_number,s=i.phone_number_id;if(`statuses`in t&&t.statuses){let e=t;for(let t of e.statuses){let e={wabaId:a,phoneNumberId:s,displayPhoneNumber:o,status:t};await $e(r.statusHandler,n,e)}return}if(`messages`in t&&t.messages){let e=t,i=e.contacts?.[0]?.profile?.name||``;for(let t of e.messages){let e={wabaId:a,phoneNumberId:s,displayPhoneNumber:o,profileName:i,message:t,messageId:Ze(t)},c=t.type;await Z(r.preProcessHandler,n,e,`pre-process`),await Z(r.messageHandlers.get(c),n,e,c),await Z(r.postProcessHandler,n,e,`post-process`)}}}async function Z(e,t,n,r){if(e)try{await e(t,n)}catch(e){X.error(`Error in ${r} handler:`,{error:e,messageId:n.messageId})}}async function $e(e,t,n){if(e)try{await e(t,n)}catch(e){X.error(`Error in status handler:`,{error:e,statusId:n.status.id})}}const Q=new E(`WEBHOOK_PROCESSOR`,process.env.DEBUG===`true`);var $=class{config;client;messageHandlers=new Map;statusHandler=void 0;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(e){this.config=le(e),this.client=new Re(e),Q.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 Ge(e,this.client,{messageHandlers:this.messageHandlers,statusHandler:this.statusHandler,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler}),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 Q.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 Je(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 Q.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),Q.log(`Registered message handler for ${e}`)}onStatus(e){this.statusHandler=e,Q.log(`Registered status handler`)}onMessagePreProcess(e){this.preProcessHandler=e,Q.log(`Registered pre-process handler`)}onMessagePostProcess(e){this.postProcessHandler=e,Q.log(`Registered post-process handler`)}onFlow(e,t){this.flowHandlers.set(e,t),Q.log(`Registered flow handler for ${e}`)}onText(e){this.messageHandlers.set(d.Text,e),Q.log(`Registered text message handler`)}onImage(e){this.messageHandlers.set(d.Image,e),Q.log(`Registered image message handler`)}onVideo(e){this.messageHandlers.set(d.Video,e),Q.log(`Registered video message handler`)}onAudio(e){this.messageHandlers.set(d.Audio,e),Q.log(`Registered audio message handler`)}onDocument(e){this.messageHandlers.set(d.Document,e),Q.log(`Registered document message handler`)}onSticker(e){this.messageHandlers.set(d.Sticker,e),Q.log(`Registered sticker message handler`)}onInteractive(e){this.messageHandlers.set(d.Interactive,e),Q.log(`Registered interactive message handler`)}onButton(e){this.messageHandlers.set(d.Button,e),Q.log(`Registered button message handler`)}onLocation(e){this.messageHandlers.set(d.Location,e),Q.log(`Registered location message handler`)}onContacts(e){this.messageHandlers.set(d.Contacts,e),Q.log(`Registered contacts message handler`)}onReaction(e){this.messageHandlers.set(d.Reaction,e),Q.log(`Registered reaction message handler`)}onOrder(e){this.messageHandlers.set(d.Order,e),Q.log(`Registered order message handler`)}onSystem(e){this.messageHandlers.set(d.System,e),Q.log(`Registered system message handler`)}getClient(){return this.client}getConfig(){return this.config}},et=class{processor;constructor(e){this.processor=new $(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 Xe(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}},tt=class extends et{constructor(e){super(e)}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){throw n(e),e}}async handlePost(e,t,n){try{let n=this.constructFullUrl(e.headers,e.url),r=new globalThis.Request(n,{method:e.method,headers:e.headers,body:JSON.stringify(e.body)}),i=await this.processWebhook(r);return this.applyHeaders(i,t),t.status(i.status).send(i.body),i}catch(e){throw n(e),e}}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){throw n(e),e}}getHandlers(){return{GET:(e,t,n)=>this.handleGet(e,t,n),POST:(e,t,n)=>this.handlePost(e,t,n),webhook:(e,t,n)=>this.autoRoute(e,t,n),flow:(e,t,n)=>this.handleFlow(e,t,n),processor:this.webhookProcessor}}};function nt(e){return new tt(e).getHandlers()}var rt=class extends et{constructor(e){super(e)}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){throw console.error(`Webhook verification error:`,e),t.status(500).json({error:`Internal Server Error`}),e}}async handlePost(e,t){try{await this.parseRequestBody(e)}catch(e){throw console.error(`Webhook processing error:`,e),e instanceof Error&&e.message===`Invalid JSON in request body`?(t.status(400).json({error:`Invalid JSON`}),e):(t.status(500).json({error:`Internal Server Error`}),e)}try{let n=this.constructFullUrl(e.headers,e.url),r=new Request(n,{method:`POST`,headers:e.headers,body:JSON.stringify(e.body)}),i=await this.processWebhook(r);return this.applyHeaders(i,t),t.status(i.status).send(i.body),i}catch(e){throw console.error(`Webhook processing error:`,e),t.status(500).json({error:`Internal Server Error`}),e}}async handleFlow(e,t){try{await this.parseRequestBody(e,!0)}catch(e){throw console.error(`Flow body parsing error:`,e),e instanceof Error&&e.message===`Invalid JSON in request body`?(t.status(400).json({error:`Invalid JSON`}),e):(t.status(500).json({error:`Internal Server Error`}),e)}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){throw console.error(`Flow error:`,e),t.status(500).json({error:`Internal Server Error`}),e}}getHandlers(){return{GET:(e,t)=>this.handleGet(e,t),POST:(e,t)=>this.handlePost(e,t),webhook:(e,t)=>this.autoRoute(e,t),flow:(e,t)=>this.handleFlow(e,t),processor:this.webhookProcessor}}};function it(e){return new rt(e).getHandlers()}function at(e){let t=new $(e);return{GET:async e=>{try{let{searchParams:n}=new URL(e.url),r=n.get(`hub.mode`),i=n.get(`hub.verify_token`),a=n.get(`hub.challenge`),o=await t.processVerification(r,i,a);return new Response(o.body,{status:o.status,headers:o.headers})}catch(e){return console.error(`Webhook verification error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let n=await t.processWebhook(e);return new Response(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}},webhook:{GET:async e=>{try{let{searchParams:n}=new URL(e.url),r=n.get(`hub.mode`),i=n.get(`hub.verify_token`),a=n.get(`hub.challenge`),o=await t.processVerification(r,i,a);return new Response(o.body,{status:o.status,headers:o.headers})}catch(e){return console.error(`Webhook verification error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let n=await t.processWebhook(e);return new Response(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}}},flow:{GET:async e=>{try{let n=await t.processFlow(e);return new Response(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Flow GET error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}},POST:async e=>{try{let n=await t.processFlow(e);return new Response(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Flow POST error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}}},processor:t}}const ot=(e,t)=>n.createHmac(`sha256`,t).update(e,`utf-8`).digest(`hex`);let st=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),ct=function(e){return e.Blocked=`BLOCKED`,e.Limited=`LIMITED`,e.Available=`AVAILABLE`,e}({}),lt=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),ut=function(e){return e.Verified=`verified`,e.PendingSubmission=`pending_submission`,e.Unverified=`unverified`,e.Rejected=`rejected`,e}({});export{S as AudioMediaTypesEnum,P as BlockUsersApi,U as BusinessProfileApi,oe as BusinessVerticalEnum,m as ButtonPositionEnum,c as CategoryEnum,g as ComponentTypesEnum,ee as ConversationTypesEnum,ie as CurrencyCodesEnum,ae as DataLocalizationRegionEnum,x as DocumentMediaTypesEnum,F as EncryptionApi,L as FlowActionEnum,I as FlowApi,be as FlowCategoryEnum,ye as FlowStatusEnum,R as FlowTypeEnum,u as HttpMethodsEnum,b as ImageMediaTypesEnum,p as InteractiveTypesEnum,re as LanguagesEnum,E as Logger,z as MediaApi,B as MessageApi,B as MessagesApi,d as MessageTypesEnum,f as ParametersTypesEnum,V as PhoneNumberApi,xe as QrCodeApi,T as ReferralSourceTypesEnum,Se as RegistrationApi,ne as RequestCodeMethodsEnum,te as StatusEnum,y as StickerMediaTypesEnum,h as SubTypeEnum,w as SystemChangeTypesEnum,Ce as TemplateApi,l as TemplateStatusEnum,Fe as TwoStepVerificationApi,v as VideoMediaTypesEnum,st as WabaAccountReviewStatus,lt as WabaAccountStatus,Ie as WabaApi,ut as WabaBusinessVerificationStatus,_ as WabaConfigEnum,ct as WabaHealthStatusCanSendMessage,$ as WebhookProcessor,C as WebhookTypesEnum,Re as WhatsApp,H as buildFieldsQueryString,Xe as constructFullUrl,De as createAuthenticationTemplate,Oe as createCatalogTemplate,ke as createCouponTemplate,Ae as createLimitedTimeOfferTemplate,Me as createMPMTemplate,je as createMediaCardCarouselTemplate,Ee as createOTPTemplate,Ne as createProductCardCarouselTemplate,Pe as createSPMTemplate,Te as createTemplate,nt as expressWebhookHandler,ue as formatConfigTable,O as generateEncryption,ot as generateXHub256Sig,He as isFlowDataExchangeRequest,Ue as isFlowErrorRequest,We as isFlowPingRequest,k as isMetaError,at as nextjsAppWebhookHandler,it as nextjsPagesWebhookHandler,N as objectToQueryString,Je as processFlowRequest,Ge as processWebhookMessages};
|
|
21
21
|
//# sourceMappingURL=index.js.map
|