@warriorteam/messenger-sdk 1.5.1 → 1.5.3
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 +29 -8
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +18 -1
- package/dist/index.d.ts +18 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -411,13 +411,15 @@ The SDK provides comprehensive webhook support with full TypeScript safety throu
|
|
|
411
411
|
### Webhook Types and Processing
|
|
412
412
|
|
|
413
413
|
```typescript
|
|
414
|
-
import {
|
|
414
|
+
import {
|
|
415
415
|
processWebhookEvents,
|
|
416
416
|
extractWebhookEvents,
|
|
417
417
|
getWebhookEventType,
|
|
418
418
|
getWebhookPayloadEventTypes,
|
|
419
|
+
getPageWebhookEventTypes,
|
|
419
420
|
WebhookEventType,
|
|
420
|
-
GenericWebhookPayload
|
|
421
|
+
GenericWebhookPayload,
|
|
422
|
+
PageWebhookPayload
|
|
421
423
|
} from '@warriorteam/messenger-sdk';
|
|
422
424
|
|
|
423
425
|
// Process webhook with type-safe handlers
|
|
@@ -466,9 +468,14 @@ for (const event of events) {
|
|
|
466
468
|
}
|
|
467
469
|
}
|
|
468
470
|
|
|
469
|
-
// Check what event types are in the payload
|
|
471
|
+
// Check what event types are in the payload (Messenger events)
|
|
470
472
|
const eventTypes = getWebhookPayloadEventTypes(payload);
|
|
471
|
-
console.log('Received event types:', eventTypes);
|
|
473
|
+
console.log('Received Messenger event types:', eventTypes); // e.g., ['message', 'postback']
|
|
474
|
+
|
|
475
|
+
// For Page webhooks, use getPageWebhookEventTypes instead:
|
|
476
|
+
// const pagePayload: PageWebhookPayload = req.body;
|
|
477
|
+
// const pageEventTypes = getPageWebhookEventTypes(pagePayload);
|
|
478
|
+
// console.log('Received Page event types:', pageEventTypes); // e.g., [WebhookEventType.FEED, WebhookEventType.VIDEOS]
|
|
472
479
|
```
|
|
473
480
|
|
|
474
481
|
### Webhook Verification
|
|
@@ -570,14 +577,20 @@ import {
|
|
|
570
577
|
isLive,
|
|
571
578
|
extractVideoContext,
|
|
572
579
|
extractLiveVideoContext,
|
|
580
|
+
getPageWebhookEventTypes,
|
|
573
581
|
FeedActionVerb,
|
|
574
582
|
VideoStatus,
|
|
575
|
-
LiveVideoStatus
|
|
583
|
+
LiveVideoStatus,
|
|
584
|
+
PageWebhookPayload
|
|
576
585
|
} from '@warriorteam/messenger-sdk';
|
|
577
586
|
|
|
578
587
|
// Handle Page webhooks
|
|
579
588
|
app.post('/webhook/page', express.json(), async (req, res) => {
|
|
580
|
-
const payload = req.body;
|
|
589
|
+
const payload: PageWebhookPayload = req.body;
|
|
590
|
+
|
|
591
|
+
// Check what types of Page events are in this payload
|
|
592
|
+
const eventTypes = getPageWebhookEventTypes(payload);
|
|
593
|
+
console.log('Received Page event types:', eventTypes); // e.g., [WebhookEventType.FEED, WebhookEventType.VIDEOS]
|
|
581
594
|
|
|
582
595
|
for (const entry of payload.entry) {
|
|
583
596
|
for (const change of entry.changes || []) {
|
|
@@ -795,10 +808,18 @@ npm run format
|
|
|
795
808
|
|
|
796
809
|
## Changelog
|
|
797
810
|
|
|
798
|
-
### v1.5.
|
|
811
|
+
### v1.5.2 (Latest)
|
|
812
|
+
- **Added**: `getPageWebhookEventTypes()` utility function for extracting event types from Page webhooks
|
|
813
|
+
- Returns `WebhookEventType[]` array with proper enum values (e.g., `[WebhookEventType.FEED, WebhookEventType.VIDEOS]`)
|
|
814
|
+
- Maps Page webhook `field` values to `WebhookEventType` enum for type safety
|
|
815
|
+
- Similar to `getWebhookPayloadEventTypes()` but for `PageWebhookPayload` structure
|
|
816
|
+
- Properly exported from main package
|
|
817
|
+
- **Improved**: Documentation with usage examples for Page webhook event type extraction
|
|
818
|
+
|
|
819
|
+
### v1.5.1
|
|
799
820
|
- **Added**: Complete NestJS/Express webhook controller example in README
|
|
800
821
|
- **Updated**: WebhookEventType enum to include FEED, VIDEOS, LIVE_VIDEOS
|
|
801
|
-
- **Improved**: Documentation with clear type usage for webhook handlers
|
|
822
|
+
- **Improved**: Documentation with clear type usage for webhook handlers and Page webhook utilities
|
|
802
823
|
|
|
803
824
|
### v1.5.0
|
|
804
825
|
- **Added**: Conversations API for retrieving conversation history and messages
|
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var ne="v23.0",re="https://graph.facebook.com";var m={MESSAGES:"/me/messages",MESSAGE_ATTACHMENTS:"/me/message_attachments",MODERATE_CONVERSATIONS:"/me/moderate_conversations"},v={TEXT_MESSAGE_MAX_CHARS:2e3},Fe={IMAGE_MAX_SIZE:8*1024*1024,OTHER_MAX_SIZE:25*1024*1024,VIDEO_TIMEOUT:75,OTHER_TIMEOUT:10},d={GENERIC_ELEMENTS_MAX:10,GENERIC_TITLE_MAX_CHARS:80,GENERIC_SUBTITLE_MAX_CHARS:80,BUTTON_TEXT_MAX_CHARS:640,BUTTONS_MAX_COUNT:3,BUTTON_TITLE_MAX_CHARS:20,POSTBACK_PAYLOAD_MAX_CHARS:1e3,MEDIA_ELEMENTS_COUNT:1,MEDIA_BUTTONS_MAX_COUNT:3};var u=class extends Error{code;type;subcode;fbtrace_id;statusCode;response;constructor(e,s,o){super(e.message),this.name="MessengerAPIError",this.code=e.code,this.type=e.type,this.subcode=e.error_subcode,this.fbtrace_id=e.fbtrace_id,this.statusCode=s,this.response=o;}},b=class extends Error{cause;constructor(e,s){super(e),this.name="MessengerNetworkError",this.cause=s;}},y=class extends Error{timeout;constructor(e){super(`Request timed out after ${e}ms`),this.name="MessengerTimeoutError",this.timeout=e;}},p=class extends Error{constructor(e){super(e),this.name="MessengerConfigError";}};var C=class{config;constructor(e){this.config={accessToken:e.accessToken,version:e.version,baseUrl:e.baseUrl||re,timeout:e.timeout||3e4,maxRetries:e.maxRetries||3};}async request(e){let s=this.buildUrl(e.path,e.query,e.accessToken),o;for(let a=0;a<=this.config.maxRetries;a++)try{let n=await this.makeRequest(s,e);return await this.handleResponse(n)}catch(n){if(o=n,n instanceof u&&n.statusCode>=400&&n.statusCode<500||a===this.config.maxRetries)throw n;await this.delay(1e3*(a+1));}throw o||new Error("Unknown error occurred")}buildUrl(e,s,o){let a=new URL(`${this.config.baseUrl}/${this.config.version}${e}`),n=o||this.config.accessToken;if(!n)throw new Error("Access token is required. Provide it in constructor or method options.");return a.searchParams.append("access_token",n),s&&Object.entries(s).forEach(([h,g])=>{a.searchParams.append(h,String(g));}),a.toString()}async makeRequest(e,s){let o=new AbortController,a=setTimeout(()=>o.abort(),this.config.timeout);try{let n={method:s.method,headers:{"Content-Type":"application/json"},signal:o.signal};return s.body&&(n.body=JSON.stringify(s.body)),await fetch(e,n)}catch(n){throw n instanceof Error?n.name==="AbortError"?new y(this.config.timeout):new b(`Network request failed: ${n.message}`,n):n}finally{clearTimeout(a);}}async handleResponse(e){let o=e.headers.get("content-type")?.includes("application/json");if(!e.ok)if(o){let a=await e.json();throw new u(a.error,e.status,a)}else {let a=await e.text();throw new u({message:a||`HTTP ${e.status} ${e.statusText}`,type:"http_error",code:e.status,fbtrace_id:""},e.status,a)}return o?await e.json():await e.text()}delay(e){return new Promise(s=>setTimeout(s,e))}};var T=class extends Error{constructor(e){super(e),this.name="MessageValidationError";}};function ie(t){if(!t||t.trim()==="")throw new T("Text message cannot be empty");if(t.length>v.TEXT_MESSAGE_MAX_CHARS)throw new T(`Text message cannot exceed ${v.TEXT_MESSAGE_MAX_CHARS} characters`)}var M=class{constructor(e){this.httpClient=e;}async message(e,s){return e.message?.text&&ie(e.message.text),this.httpClient.request({method:"POST",path:m.MESSAGES,body:e,accessToken:s?.accessToken})}async action(e,s,o){return this.httpClient.request({method:"POST",path:m.MESSAGES,body:{recipient:{id:e},messaging_type:"RESPONSE",sender_action:s},accessToken:o?.accessToken})}async typingOn(e,s){return this.action(e,"typing_on",s)}async typingOff(e,s){return this.action(e,"typing_off",s)}async markSeen(e,s){return this.action(e,"mark_seen",s)}async attachment(e,s){return this.message({recipient:e.recipient,messaging_type:e.messaging_type??"RESPONSE",message:{attachment:{type:e.type,payload:{attachment_id:e.attachment_id}}}},s)}async attachmentFromUrl(e,s){return this.message({recipient:e.recipient,messaging_type:e.messaging_type??"RESPONSE",message:{attachment:{type:e.type,payload:{url:e.url}}}},s)}};var P=class{constructor(e){this.httpClient=e;}async upload(e,s){let o={message:{attachment:{type:e.type,payload:{url:e.url,is_reusable:e.is_reusable??true}}}};return this.httpClient.request({method:"POST",path:m.MESSAGE_ATTACHMENTS,body:o,accessToken:s?.accessToken})}};var k=class{constructor(e){this.httpClient=e;}async moderate(e,s){return this.httpClient.request({method:"POST",path:m.MODERATE_CONVERSATIONS,body:e,accessToken:s?.accessToken})}async blockUser(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["block_user"]},s)}async unblockUser(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["unblock_user"]},s)}async banUser(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["ban_user"]},s)}async unbanUser(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["unban_user"]},s)}async moveToSpam(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["move_to_spam"]},s)}async blockAndSpam(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["block_user","move_to_spam"]},s)}};var i=class extends Error{constructor(e){super(e),this.name="TemplateValidationError";}};function ce(t){if(t.length===0)throw new i("Generic template must have at least 1 element");if(t.length>d.GENERIC_ELEMENTS_MAX)throw new i(`Generic template cannot have more than ${d.GENERIC_ELEMENTS_MAX} elements`);t.forEach((e,s)=>{Xe(e,s);});}function Xe(t,e){if(!t.title||t.title.trim()==="")throw new i(`Element ${e}: title is required`);if(t.title.length>d.GENERIC_TITLE_MAX_CHARS)throw new i(`Element ${e}: title cannot exceed ${d.GENERIC_TITLE_MAX_CHARS} characters`);if(t.subtitle&&t.subtitle.length>d.GENERIC_SUBTITLE_MAX_CHARS)throw new i(`Element ${e}: subtitle cannot exceed ${d.GENERIC_SUBTITLE_MAX_CHARS} characters`);if(t.image_url&&!S(t.image_url))throw new i(`Element ${e}: image_url must be HTTPS`);if(t.buttons&&L(t.buttons,`Element ${e}`),!!!(t.subtitle||t.image_url||t.default_action||t.buttons&&t.buttons.length>0))throw new i(`Element ${e}: must have at least one additional property beyond title`)}function de(t,e){if(!t||t.trim()==="")throw new i("Button template text is required");if(t.length>d.BUTTON_TEXT_MAX_CHARS)throw new i(`Button template text cannot exceed ${d.BUTTON_TEXT_MAX_CHARS} characters`);if(e.length===0)throw new i("Button template must have at least 1 button");L(e,"Button template");}function pe(t){if(!t.media_type)throw new i("Media template element must have media_type");if(!t.url&&!t.attachment_id)throw new i("Media template element must have either url or attachment_id");if(t.url&&t.attachment_id)throw new i("Media template element cannot have both url and attachment_id");if(t.url&&!S(t.url))throw new i("Media template url must be HTTPS");if(t.buttons){if(t.buttons.length>d.MEDIA_BUTTONS_MAX_COUNT)throw new i(`Media template cannot have more than ${d.MEDIA_BUTTONS_MAX_COUNT} buttons`);L(t.buttons,"Media template");}}function L(t,e){if(t.length>d.BUTTONS_MAX_COUNT)throw new i(`${e} cannot have more than ${d.BUTTONS_MAX_COUNT} buttons`);t.forEach((s,o)=>{je(s,`${e} button ${o}`);});}function je(t,e){if(!t.type)throw new i(`${e}: type is required`);if(t.type!=="account_unlink"&&(!t.title||t.title.trim()===""))throw new i(`${e}: title is required for ${t.type} buttons`);if(t.title&&t.title.length>d.BUTTON_TITLE_MAX_CHARS)throw new i(`${e}: title cannot exceed ${d.BUTTON_TITLE_MAX_CHARS} characters`);switch(t.type){case "web_url":if(!t.url)throw new i(`${e}: url is required for web_url buttons`);if(!S(t.url))throw new i(`${e}: url must be HTTPS for web_url buttons`);break;case "postback":if(!t.payload)throw new i(`${e}: payload is required for postback buttons`);if(t.payload.length>d.POSTBACK_PAYLOAD_MAX_CHARS)throw new i(`${e}: payload cannot exceed ${d.POSTBACK_PAYLOAD_MAX_CHARS} characters`);break;case "phone_number":if(!t.payload)throw new i(`${e}: payload is required for phone_number buttons`);if(!t.payload.startsWith("+"))throw new i(`${e}: phone_number payload must start with + (e.g., +1234567890)`);break;case "game_play":break;case "account_link":if(!t.url)throw new i(`${e}: url is required for account_link buttons`);if(!S(t.url))throw new i(`${e}: url must be HTTPS for account_link buttons`);break;}if(t.type==="web_url"&&t.messenger_extensions&&t.fallback_url&&!S(t.fallback_url))throw new i(`${e}: fallback_url must be HTTPS`)}function S(t){try{return new URL(t).protocol==="https:"}catch{return false}}var _=class{constructor(e){this.httpClient=e;}async generic(e,s){ce(e.elements);let o={template_type:"generic",elements:e.elements,image_aspect_ratio:e.image_aspect_ratio},a={recipient:e.recipient,messaging_type:e.messaging_type||"UPDATE",message:{attachment:{type:"template",payload:o}},notification_type:e.notification_type,tag:e.tag};return this.httpClient.request({method:"POST",path:m.MESSAGES,body:a,accessToken:s?.accessToken})}async button(e,s){de(e.text,e.buttons);let o={template_type:"button",text:e.text,buttons:e.buttons},a={recipient:e.recipient,messaging_type:e.messaging_type||"UPDATE",message:{attachment:{type:"template",payload:o}},notification_type:e.notification_type,tag:e.tag};return this.httpClient.request({method:"POST",path:m.MESSAGES,body:a,accessToken:s?.accessToken})}async media(e,s){pe(e.element);let o={template_type:"media",elements:[e.element]},a={recipient:e.recipient,messaging_type:e.messaging_type||"UPDATE",message:{attachment:{type:"template",payload:o}},notification_type:e.notification_type,tag:e.tag};return this.httpClient.request({method:"POST",path:m.MESSAGES,body:a,accessToken:s?.accessToken})}async product(e,s){let o={template_type:"product",elements:e.elements},a={recipient:e.recipient,messaging_type:e.messaging_type||"UPDATE",message:{attachment:{type:"template",payload:o}},notification_type:e.notification_type,tag:e.tag};return this.httpClient.request({method:"POST",path:m.MESSAGES,body:a,accessToken:s?.accessToken})}};var A=class{constructor(e){this.httpClient=e;}async get(e,s){let{psid:o,fields:a=["first_name","last_name"]}=e,n=new URLSearchParams({fields:a.join(",")});return this.httpClient.request({method:"GET",path:`/${o}?${n.toString()}`,body:void 0,accessToken:s?.accessToken})}async getBasic(e,s){return this.get({psid:e,fields:["first_name","last_name","profile_pic"]},s)}async getFull(e,s){return this.get({psid:e,fields:["id","name","first_name","last_name","profile_pic","locale","timezone","gender"]},s)}async getName(e,s){return this.get({psid:e,fields:["first_name","last_name"]},s)}async getProfilePicture(e,s){return this.get({psid:e,fields:["profile_pic"]},s)}};var R=class{constructor(e){this.httpClient=e;}async list(e,s,o){if(!e)throw new p("Page ID is required");let a={};return s?.platform&&(a.platform=s.platform),s?.user_id&&(a.user_id=s.user_id),s?.folder&&(a.folder=s.folder),s?.limit&&(a.limit=s.limit.toString()),s?.after&&(a.after=s.after),s?.before&&(a.before=s.before),this.httpClient.request({method:"GET",path:`/${e}/conversations`,query:a,accessToken:o?.accessToken})}async get(e,s,o){if(!e)throw new p("Conversation ID is required");let a={};return s?.fields&&s.fields.length>0&&(a.fields=s.fields.join(",")),s?.limit&&(a.limit=s.limit.toString()),s?.after&&(a.after=s.after),s?.before&&(a.before=s.before),this.httpClient.request({method:"GET",path:`/${e}`,query:a,accessToken:o?.accessToken})}async getMessages(e,s,o){if(!e)throw new p("Conversation ID is required");let a={fields:"messages"};s?.limit&&(a.limit=s.limit.toString()),s?.after&&(a.after=s.after),s?.before&&(a.before=s.before);let n=await this.httpClient.request({method:"GET",path:`/${e}`,query:a,accessToken:o?.accessToken});return {data:n.messages?.data||[],paging:n.messages?.paging}}async getMessage(e,s,o){if(!e)throw new p("Message ID is required");let a={};return s?.fields&&s.fields.length>0?a.fields=s.fields.join(","):a.fields="id,created_time,from,to,message,attachments,reactions,reply_to",this.httpClient.request({method:"GET",path:`/${e}`,query:a,accessToken:o?.accessToken})}async getRecentMessages(e,s){let a=(await this.getMessages(e,{limit:20},s)).data.map(n=>this.getMessage(n.id,void 0,s));return Promise.all(a)}async findByUser(e,s,o,a){let n=await this.list(e,{platform:o,user_id:s},a);return n.data&&n.data.length>0&&n.data[0]?n.data[0].id:null}};var V=class{send;attachments;moderation;templates;profile;conversations;httpClient;constructor(e={}){this.validateConfig(e);let s={accessToken:e.accessToken,version:e.version||ne,baseUrl:e.baseUrl,timeout:e.timeout,maxRetries:e.maxRetries};this.httpClient=new C(s),this.send=new M(this.httpClient),this.attachments=new P(this.httpClient),this.moderation=new k(this.httpClient),this.templates=new _(this.httpClient),this.profile=new A(this.httpClient),this.conversations=new R(this.httpClient);}validateConfig(e){if(e.accessToken!==void 0&&(typeof e.accessToken!="string"||e.accessToken.trim()===""))throw new p("Access token must be a non-empty string");if(e.version&&typeof e.version!="string")throw new p("API version must be a string");if(e.timeout&&(typeof e.timeout!="number"||e.timeout<=0))throw new p("Timeout must be a positive number");if(e.maxRetries&&(typeof e.maxRetries!="number"||e.maxRetries<0))throw new p("Max retries must be a non-negative number")}};var x=(c=>(c.MESSAGE="message",c.MESSAGE_EDIT="message_edit",c.MESSAGE_REACTION="reaction",c.MESSAGE_READ="read",c.MESSAGING_FEEDBACK="messaging_feedback",c.MESSAGING_POSTBACK="postback",c.FEED="feed",c.VIDEOS="videos",c.LIVE_VIDEOS="live_videos",c))(x||{});function $e(t){return typeof t.id=="string"&&t.id.length>0}function ge(t){let e=[];if(t.object==="page"&&Array.isArray(t.entry))for(let s of t.entry)Array.isArray(s.messaging)&&e.push(...s.messaging);return e}function Ee(t){let e=[];if(t.object==="page"&&Array.isArray(t.entry))for(let s of t.entry)Array.isArray(s.changes)&&e.push(...s.changes);return e}function O(t){let e=$e(t.sender);return {senderId:t.sender.id,userRef:t.sender.user_ref,recipientId:t.recipient.id,timestamp:t.timestamp,isIdentifiedUser:e,eventDate:new Date(t.timestamp)}}function Ke(t){return t&&typeof t=="object"&&"message_edit"in t}function Ye(t){return {...O(t),messageId:t.message_edit.mid,updatedText:t.message_edit.text,editCount:t.message_edit.num_edit}}var Qe={MAX_EDITS:5,EVENT_TYPE:"message_edit"};var w=(l=>(l.LIKE="like",l.DISLIKE="dislike",l.LOVE="love",l.SAD="sad",l.ANGRY="angry",l.WOW="wow",l.SMILE="smile",l.OTHER="other",l))(w||{}),U=(s=>(s.REACT="react",s.UNREACT="unreact",s))(U||{});function ze(t){return t&&typeof t=="object"&&"read"in t}function Ze(t){return {senderId:t.sender.id,recipientId:t.recipient.id,watermarkTimestamp:t.read.watermark,readTimestamp:t.timestamp,watermarkDate:new Date(t.read.watermark),readDate:new Date(t.timestamp)}}function me(t,e){return t<=e}function le(t,e){return t.filter(s=>me(s.timestamp,e))}function Je(t,e){return le(t,e).length}var et={EVENT_TYPE:"message_reads",READ_PROPERTY:"read"};function tt(t){return t&&typeof t=="object"&&"postback"in t}function ue(t){return t.postback&&"referral"in t.postback&&t.postback.referral!=null}function fe(t){return t&&typeof t.id=="string"&&t.id.length>0}function st(t){let e=ue(t),s=fe(t.sender);return {payload:t.postback.payload,senderId:t.sender.id,userRef:t.sender.user_ref,recipientId:t.recipient.id,buttonTitle:t.postback.title,messageId:t.postback.mid,timestamp:t.timestamp,referralContext:e?{ref:t.postback.referral.ref,source:t.postback.referral.source,type:t.postback.referral.type}:void 0,isReferred:e,isIdentifiedUser:s}}var ot={GET_STARTED:"GET_STARTED",MAIN_MENU:"MAIN_MENU",HELP:"HELP",SUPPORT:"SUPPORT",CONTACT:"CONTACT",CONTACT_SALES:"CONTACT_SALES",CONTACT_SUPPORT:"CONTACT_SUPPORT",BACK:"BACK",NEXT:"NEXT",CANCEL:"CANCEL",SETTINGS:"SETTINGS",PREFERENCES:"PREFERENCES"},at={MAX_PAYLOAD_LENGTH:1e3,EVENT_TYPE:"postback",REFERRAL_SOURCES:{SHORTLINK:"SHORTLINK",ADS:"ADS",MESSENGER_CODE:"MESSENGER_CODE"},REFERRAL_TYPES:{OPEN_THREAD:"OPEN_THREAD"}};var G=(o=>(o.CSAT="csat",o.NPS="nps",o.CES="ces",o))(G||{}),F=(o=>(o.ONE_TO_FIVE="one_to_five",o.FIVE_STARS="five_stars",o.FIVE_EMOJIS="five_emojis",o))(F||{}),B=(e=>(e.ZERO_TO_TEN="zero_to_ten",e))(B||{}),H=(e=>(e.ONE_TO_SEVEN="one_to_seven",e))(H||{}),q=(e=>(e.FREE_FORM="free_form",e))(q||{});function nt(t){return t&&typeof t=="object"&&"messaging_feedback"in t}function rt(t){let e=[];return t.messaging_feedback.feedback_screens.forEach(s=>{Object.entries(s.questions).forEach(([o,a])=>{e.push({questionId:o,feedbackType:a.type,score:parseInt(a.payload,10),textFeedback:a.follow_up?.payload,screenId:s.screen_id});});}),{senderId:t.sender.id,recipientId:t.recipient.id,submissionTimestamp:t.timestamp,screenCount:t.messaging_feedback.feedback_screens.length,allResponses:e}}function it(t){let e=new Map;return t.messaging_feedback.feedback_screens.forEach(s=>{Object.values(s.questions).forEach(o=>{let a=parseInt(o.payload,10),n=e.get(o.type)||[];e.set(o.type,[...n,a]);});}),e}function ct(t){let e=[];return t.messaging_feedback.feedback_screens.forEach(s=>{Object.values(s.questions).forEach(o=>{o.follow_up?.payload&&e.push(o.follow_up.payload);});}),e}var f={MAX_TEXT_FEEDBACK_LENGTH:400,SCORE_RANGES:{csat:{min:1,max:5},nps:{min:0,max:10},ces:{min:1,max:7}},TEMPLATE_EXPIRY:{MIN_DAYS:1,MAX_DAYS:7,DEFAULT_DAYS:1},QUESTION_ID:{MAX_LENGTH:80,VALID_PATTERN:/^[a-zA-Z0-9_]+$/},TEMPLATE_LIMITS:{MAX_TITLES:1,MAX_SCORING_COMPONENTS:1},EVENT_TYPE:"messaging_feedback"};function dt(t,e){let s=f.SCORE_RANGES[t];return Number.isInteger(e)&&e>=s.min&&e<=s.max}function pt(t){return t.length<=f.QUESTION_ID.MAX_LENGTH&&f.QUESTION_ID.VALID_PATTERN.test(t)}function gt(t){return t.length<=f.MAX_TEXT_FEEDBACK_LENGTH}var X=(r=>(r.ALBUM="album",r.ADDRESS="address",r.COMMENT="comment",r.CONNECTION="connection",r.COUPON="coupon",r.EVENT="event",r.EXPERIENCE="experience",r.GROUP="group",r.GROUP_MESSAGE="group_message",r.INTEREST="interest",r.LINK="link",r.MENTION="mention",r.MILESTONE="milestone",r.NOTE="note",r.PAGE="page",r.PICTURE="picture",r.PLATFORM_STORY="platform-story",r.PHOTO="photo",r.PHOTO_ALBUM="photo-album",r.POST="post",r.PROFILE="profile",r.QUESTION="question",r.RATING="rating",r.REACTION="reaction",r.RELATIONSHIP_STATUS="relationship-status",r.SHARE="share",r.STATUS="status",r.STORY="story",r.TIMELINE_COVER="timeline cover",r.TAG="tag",r.VIDEO="video",r))(X||{}),j=(E=>(E.ADD="add",E.BLOCK="block",E.EDIT="edit",E.EDITED="edited",E.DELETE="delete",E.FOLLOW="follow",E.HIDE="hide",E.MUTE="mute",E.REMOVE="remove",E.UNBLOCK="unblock",E.UNHIDE="unhide",E.UPDATE="update",E))(j||{});function Et(t){return t&&typeof t=="object"&&t.field==="feed"}function he(t){return t.verb==="add"&&t.item==="post"}function be(t){return t.item==="comment"}function ye(t){return t.item==="photo"||t.item==="photo-album"}function Te(t){return t.item==="video"}function Me(t){return t.item==="reaction"}function mt(t){return typeof t.message=="string"&&t.message.length>0}function lt(t,e,s){let{value:o}=s;return {pageId:t,timestamp:e,eventDate:new Date(e),sender:o.from,postId:o.post_id,commentId:o.comment_id,verb:o.verb,item:o.item,message:o.message,isPostCreated:he(o),isComment:be(o),isPhoto:ye(o),isVideo:Te(o),isReaction:Me(o)}}function ut(t){let e=[];return t.photo&&e.push({url:t.photo,id:t.photo_id}),t.photos&&Array.isArray(t.photos)&&e.push(...t.photos.map((s,o)=>({url:s,id:t.photo_ids?.[o]}))),e}var Pe={FIELD_NAME:"feed",MAX_PAGE_LIKES_FOR_NOTIFICATIONS:1e4};var W=(o=>(o.PROCESSING="processing",o.READY="ready",o.ERROR="error",o))(W||{});function ke(t){return t&&typeof t=="object"&&t.field==="videos"}function $(t){return t.status.video_status==="processing"}function K(t){return t.status.video_status==="ready"}function Y(t){return t.status.video_status==="error"}function Se(t,e,s){let{value:o}=s;return {pageId:t,timestamp:e,eventDate:new Date(e),videoId:o.id,status:o.status.video_status,isProcessing:$(o),isReady:K(o),hasError:Y(o)}}function _e(t,e){return t==="processing"&&e==="ready"}function Ae(t,e){return t==="processing"&&e==="error"}var Re={FIELD_NAME:"videos",STATUSES:Object.values(W)};var I=(c=>(c.LIVE="LIVE",c.LIVE_STOPPED="LIVE_STOPPED",c.PROCESSING="PROCESSING",c.SCHEDULED_CANCELED="SCHEDULED_CANCELED",c.SCHEDULED_EXPIRED="SCHEDULED_EXPIRED",c.SCHEDULED_LIVE="SCHEDULED_LIVE",c.SCHEDULED_UNPUBLISHED="SCHEDULED_UNPUBLISHED",c.UNPUBLISHED="UNPUBLISHED",c.VOD="VOD",c))(I||{});function xe(t){return t&&typeof t=="object"&&t.field==="live_videos"}function Q(t){return t.status==="LIVE"}function z(t){return t.status==="SCHEDULED_UNPUBLISHED"||t.status==="SCHEDULED_LIVE"}function Z(t){return t.status==="PROCESSING"}function J(t){return t.status==="LIVE_STOPPED"||t.status==="SCHEDULED_CANCELED"||t.status==="SCHEDULED_EXPIRED"}function ee(t){return t.status==="VOD"}function ve(t,e,s){let{value:o}=s;return {pageId:t,timestamp:e,eventDate:new Date(e),videoId:o.id,status:o.status,isLive:Q(o),isScheduled:z(o),isProcessing:Z(o),hasEnded:J(o),isVODReady:ee(o)}}function Ce(t,e){return t!=="LIVE"&&e==="LIVE"}function Oe(t,e){return t==="LIVE"&&(e==="LIVE_STOPPED"||e==="SCHEDULED_CANCELED"||e==="SCHEDULED_EXPIRED")}var We={FIELD_NAME:"live_videos",STATUSES:Object.values(I)};var te=(g=>(g.AUDIO="audio",g.FILE="file",g.IMAGE="image",g.VIDEO="video",g.FALLBACK="fallback",g.REEL="reel",g.IG_REEL="ig_reel",g))(te||{}),se=(o=>(o.OPEN_THREAD="OPEN_THREAD",o.PRODUCT="product",o.ADS="ads",o))(se||{}),oe=(n=>(n.MESSENGER_CODE="MESSENGER_CODE",n.DISCOVER_TAB="DISCOVER_TAB",n.ADS="ADS",n.SHORTLINK="SHORTLINK",n.CUSTOMER_CHAT_PLUGIN="CUSTOMER_CHAT_PLUGIN",n))(oe||{});function ft(t){return t&&typeof t=="object"&&"message"in t}function ht(t){return typeof t.text=="string"&&t.text.length>0}function D(t){return Array.isArray(t.attachments)&&t.attachments.length>0}function Ie(t){return t.quick_reply!==void 0}function De(t){return t.reply_to!==void 0}function Ne(t){return t.referral!==void 0}function Le(t,e){return t.type===e}function bt(t){let{message:e}=t;return {...O(t),messageId:e.mid,text:e.text,hasAttachments:D(e),isQuickReply:Ie(e),isReply:De(e),hasReferral:Ne(e),quickReplyPayload:e.quick_reply?.payload,repliedToMessageId:e.reply_to?.mid}}function yt(t,e){return D(t)?t.attachments.filter(s=>Le(s,e)):[]}function Tt(t){return D(t)?t.attachments.map(e=>e.payload.url):[]}var Mt={MAX_TEXT_LENGTH:2e3,MAX_QUICK_REPLY_PAYLOAD_LENGTH:1e3,MAX_REFERRAL_REF_LENGTH:250,EVENT_TYPE:"message"},Pt={image:["image/jpeg","image/png","image/gif","image/webp"],video:["video/mp4","video/avi","video/quicktime","video/webm"],audio:["audio/mpeg","audio/mp4","audio/wav","audio/ogg"],file:["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain"]};function N(t){return !t||typeof t!="object"?null:"type"in t&&Object.values(x).includes(t.type)?t.type:"message"in t?"message":"message_edit"in t?"message_edit":"reaction"in t?"reaction":"read"in t?"read":"messaging_feedback"in t?"messaging_feedback":"postback"in t?"postback":null}function Ve(t){let e=new Set;if(t.object==="page"&&Array.isArray(t.entry)){for(let s of t.entry)if(Array.isArray(s.messaging))for(let o of s.messaging){let a=N(o);a&&e.add(a);}}return Array.from(e)}function ae(t){return ge(t)}function kt(t){let e=N(t);return e?"type"in t?t:{...t,type:e}:null}async function we(t,e){let s=ae(t);for(let o of s){let a=kt(o);if(!a){e.onUnknown&&await e.onUnknown(o);continue}switch(a.type){case "message":e.onMessage&&await e.onMessage(a);break;case "message_edit":e.onMessageEdit&&await e.onMessageEdit(a);break;case "reaction":e.onMessageReaction&&await e.onMessageReaction(a);break;case "read":e.onMessageRead&&await e.onMessageRead(a);break;case "messaging_feedback":e.onMessagingFeedback&&await e.onMessagingFeedback(a);break;case "postback":e.onMessagingPostback&&await e.onMessagingPostback(a);break;default:let n=a;e.onUnknown&&await e.onUnknown(n);break}}}function Ue(t,e){return t["hub.mode"]==="subscribe"&&t["hub.verify_token"]===e?t["hub.challenge"]:null}async function Ge(t,e,s){if(!e)return {isValid:false,error:"Missing X-Hub-Signature-256 header"};if(!e.startsWith("sha256="))return {isValid:false,error:"Invalid signature format. Expected sha256= prefix"};if(!s)return {isValid:false,error:"App secret is required for signature verification"};try{if(typeof Buffer>"u")return {isValid:!1,error:"Signature verification is only supported in Node.js environments"};let o=await import('crypto'),a=e.substring(7),n=o.createHmac("sha256",s).update(t).digest("hex"),h=Buffer.from(a,"hex"),g=Buffer.from(n,"hex");if(h.length!==g.length)return {isValid:!1,error:"Signature length mismatch"};let l=o.timingSafeEqual(h,g);return {isValid:l,error:l?void 0:"Signature verification failed"}}catch(o){return {isValid:false,error:`Signature verification error: ${o instanceof Error?o.message:"Unknown error"}`}}}
|
|
2
|
-
exports.ATTACHMENT_LIMITS=
|
|
1
|
+
'use strict';var ne="v23.0",re="https://graph.facebook.com";var m={MESSAGES:"/me/messages",MESSAGE_ATTACHMENTS:"/me/message_attachments",MODERATE_CONVERSATIONS:"/me/moderate_conversations"},v={TEXT_MESSAGE_MAX_CHARS:2e3},Be={IMAGE_MAX_SIZE:8*1024*1024,OTHER_MAX_SIZE:25*1024*1024,VIDEO_TIMEOUT:75,OTHER_TIMEOUT:10},d={GENERIC_ELEMENTS_MAX:10,GENERIC_TITLE_MAX_CHARS:80,GENERIC_SUBTITLE_MAX_CHARS:80,BUTTON_TEXT_MAX_CHARS:640,BUTTONS_MAX_COUNT:3,BUTTON_TITLE_MAX_CHARS:20,POSTBACK_PAYLOAD_MAX_CHARS:1e3,MEDIA_ELEMENTS_COUNT:1,MEDIA_BUTTONS_MAX_COUNT:3};var u=class extends Error{code;type;subcode;fbtrace_id;statusCode;response;constructor(e,s,o){super(e.message),this.name="MessengerAPIError",this.code=e.code,this.type=e.type,this.subcode=e.error_subcode,this.fbtrace_id=e.fbtrace_id,this.statusCode=s,this.response=o;}},b=class extends Error{cause;constructor(e,s){super(e),this.name="MessengerNetworkError",this.cause=s;}},y=class extends Error{timeout;constructor(e){super(`Request timed out after ${e}ms`),this.name="MessengerTimeoutError",this.timeout=e;}},p=class extends Error{constructor(e){super(e),this.name="MessengerConfigError";}};var C=class{config;constructor(e){this.config={accessToken:e.accessToken,version:e.version,baseUrl:e.baseUrl||re,timeout:e.timeout||3e4,maxRetries:e.maxRetries||3};}async request(e){let s=this.buildUrl(e.path,e.query,e.accessToken),o;for(let a=0;a<=this.config.maxRetries;a++)try{let n=await this.makeRequest(s,e);return await this.handleResponse(n)}catch(n){if(o=n,n instanceof u&&n.statusCode>=400&&n.statusCode<500||a===this.config.maxRetries)throw n;await this.delay(1e3*(a+1));}throw o||new Error("Unknown error occurred")}buildUrl(e,s,o){let a=new URL(`${this.config.baseUrl}/${this.config.version}${e}`),n=o||this.config.accessToken;if(!n)throw new Error("Access token is required. Provide it in constructor or method options.");return a.searchParams.append("access_token",n),s&&Object.entries(s).forEach(([h,g])=>{a.searchParams.append(h,String(g));}),a.toString()}async makeRequest(e,s){let o=new AbortController,a=setTimeout(()=>o.abort(),this.config.timeout);try{let n={method:s.method,headers:{"Content-Type":"application/json"},signal:o.signal};return s.body&&(n.body=JSON.stringify(s.body)),await fetch(e,n)}catch(n){throw n instanceof Error?n.name==="AbortError"?new y(this.config.timeout):new b(`Network request failed: ${n.message}`,n):n}finally{clearTimeout(a);}}async handleResponse(e){let o=e.headers.get("content-type")?.includes("application/json");if(!e.ok)if(o){let a=await e.json();throw new u(a.error,e.status,a)}else {let a=await e.text();throw new u({message:a||`HTTP ${e.status} ${e.statusText}`,type:"http_error",code:e.status,fbtrace_id:""},e.status,a)}return o?await e.json():await e.text()}delay(e){return new Promise(s=>setTimeout(s,e))}};var T=class extends Error{constructor(e){super(e),this.name="MessageValidationError";}};function ie(t){if(!t||t.trim()==="")throw new T("Text message cannot be empty");if(t.length>v.TEXT_MESSAGE_MAX_CHARS)throw new T(`Text message cannot exceed ${v.TEXT_MESSAGE_MAX_CHARS} characters`)}var k=class{constructor(e){this.httpClient=e;}async message(e,s){return e.message?.text&&ie(e.message.text),this.httpClient.request({method:"POST",path:m.MESSAGES,body:e,accessToken:s?.accessToken})}async action(e,s,o){return this.httpClient.request({method:"POST",path:m.MESSAGES,body:{recipient:{id:e},messaging_type:"RESPONSE",sender_action:s},accessToken:o?.accessToken})}async typingOn(e,s){return this.action(e,"typing_on",s)}async typingOff(e,s){return this.action(e,"typing_off",s)}async markSeen(e,s){return this.action(e,"mark_seen",s)}async attachment(e,s){return this.message({recipient:e.recipient,messaging_type:e.messaging_type??"RESPONSE",message:{attachment:{type:e.type,payload:{attachment_id:e.attachment_id}}}},s)}async attachmentFromUrl(e,s){return this.message({recipient:e.recipient,messaging_type:e.messaging_type??"RESPONSE",message:{attachment:{type:e.type,payload:{url:e.url}}}},s)}};var P=class{constructor(e){this.httpClient=e;}async upload(e,s){let o={message:{attachment:{type:e.type,payload:{url:e.url,is_reusable:e.is_reusable??true}}}};return this.httpClient.request({method:"POST",path:m.MESSAGE_ATTACHMENTS,body:o,accessToken:s?.accessToken})}};var M=class{constructor(e){this.httpClient=e;}async moderate(e,s){return this.httpClient.request({method:"POST",path:m.MODERATE_CONVERSATIONS,body:e,accessToken:s?.accessToken})}async blockUser(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["block_user"]},s)}async unblockUser(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["unblock_user"]},s)}async banUser(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["ban_user"]},s)}async unbanUser(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["unban_user"]},s)}async moveToSpam(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["move_to_spam"]},s)}async blockAndSpam(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["block_user","move_to_spam"]},s)}};var i=class extends Error{constructor(e){super(e),this.name="TemplateValidationError";}};function ce(t){if(t.length===0)throw new i("Generic template must have at least 1 element");if(t.length>d.GENERIC_ELEMENTS_MAX)throw new i(`Generic template cannot have more than ${d.GENERIC_ELEMENTS_MAX} elements`);t.forEach((e,s)=>{je(e,s);});}function je(t,e){if(!t.title||t.title.trim()==="")throw new i(`Element ${e}: title is required`);if(t.title.length>d.GENERIC_TITLE_MAX_CHARS)throw new i(`Element ${e}: title cannot exceed ${d.GENERIC_TITLE_MAX_CHARS} characters`);if(t.subtitle&&t.subtitle.length>d.GENERIC_SUBTITLE_MAX_CHARS)throw new i(`Element ${e}: subtitle cannot exceed ${d.GENERIC_SUBTITLE_MAX_CHARS} characters`);if(t.image_url&&!S(t.image_url))throw new i(`Element ${e}: image_url must be HTTPS`);if(t.buttons&&L(t.buttons,`Element ${e}`),!!!(t.subtitle||t.image_url||t.default_action||t.buttons&&t.buttons.length>0))throw new i(`Element ${e}: must have at least one additional property beyond title`)}function de(t,e){if(!t||t.trim()==="")throw new i("Button template text is required");if(t.length>d.BUTTON_TEXT_MAX_CHARS)throw new i(`Button template text cannot exceed ${d.BUTTON_TEXT_MAX_CHARS} characters`);if(e.length===0)throw new i("Button template must have at least 1 button");L(e,"Button template");}function pe(t){if(!t.media_type)throw new i("Media template element must have media_type");if(!t.url&&!t.attachment_id)throw new i("Media template element must have either url or attachment_id");if(t.url&&t.attachment_id)throw new i("Media template element cannot have both url and attachment_id");if(t.url&&!S(t.url))throw new i("Media template url must be HTTPS");if(t.buttons){if(t.buttons.length>d.MEDIA_BUTTONS_MAX_COUNT)throw new i(`Media template cannot have more than ${d.MEDIA_BUTTONS_MAX_COUNT} buttons`);L(t.buttons,"Media template");}}function L(t,e){if(t.length>d.BUTTONS_MAX_COUNT)throw new i(`${e} cannot have more than ${d.BUTTONS_MAX_COUNT} buttons`);t.forEach((s,o)=>{$e(s,`${e} button ${o}`);});}function $e(t,e){if(!t.type)throw new i(`${e}: type is required`);if(t.type!=="account_unlink"&&(!t.title||t.title.trim()===""))throw new i(`${e}: title is required for ${t.type} buttons`);if(t.title&&t.title.length>d.BUTTON_TITLE_MAX_CHARS)throw new i(`${e}: title cannot exceed ${d.BUTTON_TITLE_MAX_CHARS} characters`);switch(t.type){case "web_url":if(!t.url)throw new i(`${e}: url is required for web_url buttons`);if(!S(t.url))throw new i(`${e}: url must be HTTPS for web_url buttons`);break;case "postback":if(!t.payload)throw new i(`${e}: payload is required for postback buttons`);if(t.payload.length>d.POSTBACK_PAYLOAD_MAX_CHARS)throw new i(`${e}: payload cannot exceed ${d.POSTBACK_PAYLOAD_MAX_CHARS} characters`);break;case "phone_number":if(!t.payload)throw new i(`${e}: payload is required for phone_number buttons`);if(!t.payload.startsWith("+"))throw new i(`${e}: phone_number payload must start with + (e.g., +1234567890)`);break;case "game_play":break;case "account_link":if(!t.url)throw new i(`${e}: url is required for account_link buttons`);if(!S(t.url))throw new i(`${e}: url must be HTTPS for account_link buttons`);break;}if(t.type==="web_url"&&t.messenger_extensions&&t.fallback_url&&!S(t.fallback_url))throw new i(`${e}: fallback_url must be HTTPS`)}function S(t){try{return new URL(t).protocol==="https:"}catch{return false}}var _=class{constructor(e){this.httpClient=e;}async generic(e,s){ce(e.elements);let o={template_type:"generic",elements:e.elements,image_aspect_ratio:e.image_aspect_ratio},a={recipient:e.recipient,messaging_type:e.messaging_type||"UPDATE",message:{attachment:{type:"template",payload:o}},notification_type:e.notification_type,tag:e.tag};return this.httpClient.request({method:"POST",path:m.MESSAGES,body:a,accessToken:s?.accessToken})}async button(e,s){de(e.text,e.buttons);let o={template_type:"button",text:e.text,buttons:e.buttons},a={recipient:e.recipient,messaging_type:e.messaging_type||"UPDATE",message:{attachment:{type:"template",payload:o}},notification_type:e.notification_type,tag:e.tag};return this.httpClient.request({method:"POST",path:m.MESSAGES,body:a,accessToken:s?.accessToken})}async media(e,s){pe(e.element);let o={template_type:"media",elements:[e.element]},a={recipient:e.recipient,messaging_type:e.messaging_type||"UPDATE",message:{attachment:{type:"template",payload:o}},notification_type:e.notification_type,tag:e.tag};return this.httpClient.request({method:"POST",path:m.MESSAGES,body:a,accessToken:s?.accessToken})}async product(e,s){let o={template_type:"product",elements:e.elements},a={recipient:e.recipient,messaging_type:e.messaging_type||"UPDATE",message:{attachment:{type:"template",payload:o}},notification_type:e.notification_type,tag:e.tag};return this.httpClient.request({method:"POST",path:m.MESSAGES,body:a,accessToken:s?.accessToken})}};var A=class{constructor(e){this.httpClient=e;}async get(e,s){let{psid:o,fields:a=["first_name","last_name"]}=e,n=new URLSearchParams({fields:a.join(",")});return this.httpClient.request({method:"GET",path:`/${o}?${n.toString()}`,body:void 0,accessToken:s?.accessToken})}async getBasic(e,s){return this.get({psid:e,fields:["first_name","last_name","profile_pic"]},s)}async getFull(e,s){return this.get({psid:e,fields:["id","name","first_name","last_name","profile_pic","locale","timezone","gender"]},s)}async getName(e,s){return this.get({psid:e,fields:["first_name","last_name"]},s)}async getProfilePicture(e,s){return this.get({psid:e,fields:["profile_pic"]},s)}};var R=class{constructor(e){this.httpClient=e;}async list(e,s,o){if(!e)throw new p("Page ID is required");let a={};return s?.platform&&(a.platform=s.platform),s?.user_id&&(a.user_id=s.user_id),s?.folder&&(a.folder=s.folder),s?.limit&&(a.limit=s.limit.toString()),s?.after&&(a.after=s.after),s?.before&&(a.before=s.before),this.httpClient.request({method:"GET",path:`/${e}/conversations`,query:a,accessToken:o?.accessToken})}async get(e,s,o){if(!e)throw new p("Conversation ID is required");let a={};return s?.fields&&s.fields.length>0&&(a.fields=s.fields.join(",")),s?.limit&&(a.limit=s.limit.toString()),s?.after&&(a.after=s.after),s?.before&&(a.before=s.before),this.httpClient.request({method:"GET",path:`/${e}`,query:a,accessToken:o?.accessToken})}async getMessages(e,s,o){if(!e)throw new p("Conversation ID is required");let a={fields:"messages"};s?.limit&&(a.limit=s.limit.toString()),s?.after&&(a.after=s.after),s?.before&&(a.before=s.before);let n=await this.httpClient.request({method:"GET",path:`/${e}`,query:a,accessToken:o?.accessToken});return {data:n.messages?.data||[],paging:n.messages?.paging}}async getMessage(e,s,o){if(!e)throw new p("Message ID is required");let a={};return s?.fields&&s.fields.length>0?a.fields=s.fields.join(","):a.fields="id,created_time,from,to,message,attachments,reactions,reply_to",this.httpClient.request({method:"GET",path:`/${e}`,query:a,accessToken:o?.accessToken})}async getRecentMessages(e,s){let a=(await this.getMessages(e,{limit:20},s)).data.map(n=>this.getMessage(n.id,void 0,s));return Promise.all(a)}async findByUser(e,s,o,a){let n=await this.list(e,{platform:o,user_id:s},a);return n.data&&n.data.length>0&&n.data[0]?n.data[0].id:null}};var V=class{send;attachments;moderation;templates;profile;conversations;httpClient;constructor(e={}){this.validateConfig(e);let s={accessToken:e.accessToken,version:e.version||ne,baseUrl:e.baseUrl,timeout:e.timeout,maxRetries:e.maxRetries};this.httpClient=new C(s),this.send=new k(this.httpClient),this.attachments=new P(this.httpClient),this.moderation=new M(this.httpClient),this.templates=new _(this.httpClient),this.profile=new A(this.httpClient),this.conversations=new R(this.httpClient);}validateConfig(e){if(e.accessToken!==void 0&&(typeof e.accessToken!="string"||e.accessToken.trim()===""))throw new p("Access token must be a non-empty string");if(e.version&&typeof e.version!="string")throw new p("API version must be a string");if(e.timeout&&(typeof e.timeout!="number"||e.timeout<=0))throw new p("Timeout must be a positive number");if(e.maxRetries&&(typeof e.maxRetries!="number"||e.maxRetries<0))throw new p("Max retries must be a non-negative number")}};var x=(c=>(c.MESSAGE="message",c.MESSAGE_EDIT="message_edit",c.MESSAGE_REACTION="reaction",c.MESSAGE_READ="read",c.MESSAGING_FEEDBACK="messaging_feedback",c.MESSAGING_POSTBACK="postback",c.FEED="feed",c.VIDEOS="videos",c.LIVE_VIDEOS="live_videos",c))(x||{});function Ke(t){return typeof t.id=="string"&&t.id.length>0}function ge(t){let e=[];if(t.object==="page"&&Array.isArray(t.entry))for(let s of t.entry)Array.isArray(s.messaging)&&e.push(...s.messaging);return e}function Ee(t){let e=[];if(t.object==="page"&&Array.isArray(t.entry))for(let s of t.entry)Array.isArray(s.changes)&&e.push(...s.changes);return e}function O(t){let e=Ke(t.sender);return {senderId:t.sender.id,userRef:t.sender.user_ref,recipientId:t.recipient.id,timestamp:t.timestamp,isIdentifiedUser:e,eventDate:new Date(t.timestamp)}}function me(t){let e=new Set;if(t.object==="page"&&Array.isArray(t.entry)){for(let s of t.entry)if(Array.isArray(s.changes)){for(let o of s.changes)if(o&&typeof o=="object"&&"field"in o)switch(o.field){case "feed":e.add("feed");break;case "videos":e.add("videos");break;case "live_videos":e.add("live_videos");break}}}return Array.from(e)}function Ye(t){return t&&typeof t=="object"&&"message_edit"in t}function Qe(t){return {...O(t),messageId:t.message_edit.mid,updatedText:t.message_edit.text,editCount:t.message_edit.num_edit}}var ze={MAX_EDITS:5,EVENT_TYPE:"message_edit"};var w=(l=>(l.LIKE="like",l.DISLIKE="dislike",l.LOVE="love",l.SAD="sad",l.ANGRY="angry",l.WOW="wow",l.SMILE="smile",l.OTHER="other",l))(w||{}),U=(s=>(s.REACT="react",s.UNREACT="unreact",s))(U||{});function Ze(t){return t&&typeof t=="object"&&"read"in t}function Je(t){return {senderId:t.sender.id,recipientId:t.recipient.id,watermarkTimestamp:t.read.watermark,readTimestamp:t.timestamp,watermarkDate:new Date(t.read.watermark),readDate:new Date(t.timestamp)}}function le(t,e){return t<=e}function ue(t,e){return t.filter(s=>le(s.timestamp,e))}function et(t,e){return ue(t,e).length}var tt={EVENT_TYPE:"message_reads",READ_PROPERTY:"read"};function st(t){return t&&typeof t=="object"&&"postback"in t}function fe(t){return t.postback&&"referral"in t.postback&&t.postback.referral!=null}function he(t){return t&&typeof t.id=="string"&&t.id.length>0}function ot(t){let e=fe(t),s=he(t.sender);return {payload:t.postback.payload,senderId:t.sender.id,userRef:t.sender.user_ref,recipientId:t.recipient.id,buttonTitle:t.postback.title,messageId:t.postback.mid,timestamp:t.timestamp,referralContext:e?{ref:t.postback.referral.ref,source:t.postback.referral.source,type:t.postback.referral.type}:void 0,isReferred:e,isIdentifiedUser:s}}var at={GET_STARTED:"GET_STARTED",MAIN_MENU:"MAIN_MENU",HELP:"HELP",SUPPORT:"SUPPORT",CONTACT:"CONTACT",CONTACT_SALES:"CONTACT_SALES",CONTACT_SUPPORT:"CONTACT_SUPPORT",BACK:"BACK",NEXT:"NEXT",CANCEL:"CANCEL",SETTINGS:"SETTINGS",PREFERENCES:"PREFERENCES"},nt={MAX_PAYLOAD_LENGTH:1e3,EVENT_TYPE:"postback",REFERRAL_SOURCES:{SHORTLINK:"SHORTLINK",ADS:"ADS",MESSENGER_CODE:"MESSENGER_CODE"},REFERRAL_TYPES:{OPEN_THREAD:"OPEN_THREAD"}};var G=(o=>(o.CSAT="csat",o.NPS="nps",o.CES="ces",o))(G||{}),F=(o=>(o.ONE_TO_FIVE="one_to_five",o.FIVE_STARS="five_stars",o.FIVE_EMOJIS="five_emojis",o))(F||{}),B=(e=>(e.ZERO_TO_TEN="zero_to_ten",e))(B||{}),H=(e=>(e.ONE_TO_SEVEN="one_to_seven",e))(H||{}),q=(e=>(e.FREE_FORM="free_form",e))(q||{});function rt(t){return t&&typeof t=="object"&&"messaging_feedback"in t}function it(t){let e=[];return t.messaging_feedback.feedback_screens.forEach(s=>{Object.entries(s.questions).forEach(([o,a])=>{e.push({questionId:o,feedbackType:a.type,score:parseInt(a.payload,10),textFeedback:a.follow_up?.payload,screenId:s.screen_id});});}),{senderId:t.sender.id,recipientId:t.recipient.id,submissionTimestamp:t.timestamp,screenCount:t.messaging_feedback.feedback_screens.length,allResponses:e}}function ct(t){let e=new Map;return t.messaging_feedback.feedback_screens.forEach(s=>{Object.values(s.questions).forEach(o=>{let a=parseInt(o.payload,10),n=e.get(o.type)||[];e.set(o.type,[...n,a]);});}),e}function dt(t){let e=[];return t.messaging_feedback.feedback_screens.forEach(s=>{Object.values(s.questions).forEach(o=>{o.follow_up?.payload&&e.push(o.follow_up.payload);});}),e}var f={MAX_TEXT_FEEDBACK_LENGTH:400,SCORE_RANGES:{csat:{min:1,max:5},nps:{min:0,max:10},ces:{min:1,max:7}},TEMPLATE_EXPIRY:{MIN_DAYS:1,MAX_DAYS:7,DEFAULT_DAYS:1},QUESTION_ID:{MAX_LENGTH:80,VALID_PATTERN:/^[a-zA-Z0-9_]+$/},TEMPLATE_LIMITS:{MAX_TITLES:1,MAX_SCORING_COMPONENTS:1},EVENT_TYPE:"messaging_feedback"};function pt(t,e){let s=f.SCORE_RANGES[t];return Number.isInteger(e)&&e>=s.min&&e<=s.max}function gt(t){return t.length<=f.QUESTION_ID.MAX_LENGTH&&f.QUESTION_ID.VALID_PATTERN.test(t)}function Et(t){return t.length<=f.MAX_TEXT_FEEDBACK_LENGTH}var X=(r=>(r.ALBUM="album",r.ADDRESS="address",r.COMMENT="comment",r.CONNECTION="connection",r.COUPON="coupon",r.EVENT="event",r.EXPERIENCE="experience",r.GROUP="group",r.GROUP_MESSAGE="group_message",r.INTEREST="interest",r.LINK="link",r.MENTION="mention",r.MILESTONE="milestone",r.NOTE="note",r.PAGE="page",r.PICTURE="picture",r.PLATFORM_STORY="platform-story",r.PHOTO="photo",r.PHOTO_ALBUM="photo-album",r.POST="post",r.PROFILE="profile",r.QUESTION="question",r.RATING="rating",r.REACTION="reaction",r.RELATIONSHIP_STATUS="relationship-status",r.SHARE="share",r.STATUS="status",r.STORY="story",r.TIMELINE_COVER="timeline cover",r.TAG="tag",r.VIDEO="video",r))(X||{}),j=(E=>(E.ADD="add",E.BLOCK="block",E.EDIT="edit",E.EDITED="edited",E.DELETE="delete",E.FOLLOW="follow",E.HIDE="hide",E.MUTE="mute",E.REMOVE="remove",E.UNBLOCK="unblock",E.UNHIDE="unhide",E.UPDATE="update",E))(j||{});function mt(t){return t&&typeof t=="object"&&t.field==="feed"}function be(t){return t.verb==="add"&&t.item==="post"}function ye(t){return t.item==="comment"}function Te(t){return t.item==="photo"||t.item==="photo-album"}function ke(t){return t.item==="video"}function Pe(t){return t.item==="reaction"}function lt(t){return typeof t.message=="string"&&t.message.length>0}function ut(t,e,s){let{value:o}=s;return {pageId:t,timestamp:e,eventDate:new Date(e),sender:o.from,postId:o.post_id,commentId:o.comment_id,verb:o.verb,item:o.item,message:o.message,isPostCreated:be(o),isComment:ye(o),isPhoto:Te(o),isVideo:ke(o),isReaction:Pe(o)}}function ft(t){let e=[];return t.photo&&e.push({url:t.photo,id:t.photo_id}),t.photos&&Array.isArray(t.photos)&&e.push(...t.photos.map((s,o)=>({url:s,id:t.photo_ids?.[o]}))),e}var Me={FIELD_NAME:"feed",MAX_PAGE_LIKES_FOR_NOTIFICATIONS:1e4};var W=(o=>(o.PROCESSING="processing",o.READY="ready",o.ERROR="error",o))(W||{});function Se(t){return t&&typeof t=="object"&&t.field==="videos"}function $(t){return t.status.video_status==="processing"}function K(t){return t.status.video_status==="ready"}function Y(t){return t.status.video_status==="error"}function _e(t,e,s){let{value:o}=s;return {pageId:t,timestamp:e,eventDate:new Date(e),videoId:o.id,status:o.status.video_status,isProcessing:$(o),isReady:K(o),hasError:Y(o)}}function Ae(t,e){return t==="processing"&&e==="ready"}function Re(t,e){return t==="processing"&&e==="error"}var xe={FIELD_NAME:"videos",STATUSES:Object.values(W)};var I=(c=>(c.LIVE="LIVE",c.LIVE_STOPPED="LIVE_STOPPED",c.PROCESSING="PROCESSING",c.SCHEDULED_CANCELED="SCHEDULED_CANCELED",c.SCHEDULED_EXPIRED="SCHEDULED_EXPIRED",c.SCHEDULED_LIVE="SCHEDULED_LIVE",c.SCHEDULED_UNPUBLISHED="SCHEDULED_UNPUBLISHED",c.UNPUBLISHED="UNPUBLISHED",c.VOD="VOD",c))(I||{});function ve(t){return t&&typeof t=="object"&&t.field==="live_videos"}function Q(t){return t.status==="LIVE"}function z(t){return t.status==="SCHEDULED_UNPUBLISHED"||t.status==="SCHEDULED_LIVE"}function Z(t){return t.status==="PROCESSING"}function J(t){return t.status==="LIVE_STOPPED"||t.status==="SCHEDULED_CANCELED"||t.status==="SCHEDULED_EXPIRED"}function ee(t){return t.status==="VOD"}function Ce(t,e,s){let{value:o}=s;return {pageId:t,timestamp:e,eventDate:new Date(e),videoId:o.id,status:o.status,isLive:Q(o),isScheduled:z(o),isProcessing:Z(o),hasEnded:J(o),isVODReady:ee(o)}}function Oe(t,e){return t!=="LIVE"&&e==="LIVE"}function We(t,e){return t==="LIVE"&&(e==="LIVE_STOPPED"||e==="SCHEDULED_CANCELED"||e==="SCHEDULED_EXPIRED")}var Ie={FIELD_NAME:"live_videos",STATUSES:Object.values(I)};var te=(g=>(g.AUDIO="audio",g.FILE="file",g.IMAGE="image",g.VIDEO="video",g.FALLBACK="fallback",g.REEL="reel",g.IG_REEL="ig_reel",g))(te||{}),se=(o=>(o.OPEN_THREAD="OPEN_THREAD",o.PRODUCT="product",o.ADS="ads",o))(se||{}),oe=(n=>(n.MESSENGER_CODE="MESSENGER_CODE",n.DISCOVER_TAB="DISCOVER_TAB",n.ADS="ADS",n.SHORTLINK="SHORTLINK",n.CUSTOMER_CHAT_PLUGIN="CUSTOMER_CHAT_PLUGIN",n))(oe||{});function ht(t){return t&&typeof t=="object"&&"message"in t}function bt(t){return typeof t.text=="string"&&t.text.length>0}function D(t){return Array.isArray(t.attachments)&&t.attachments.length>0}function De(t){return t.quick_reply!==void 0}function Ne(t){return t.reply_to!==void 0}function Le(t){return t.referral!==void 0}function Ve(t,e){return t.type===e}function yt(t){let{message:e}=t;return {...O(t),messageId:e.mid,text:e.text,hasAttachments:D(e),isQuickReply:De(e),isReply:Ne(e),hasReferral:Le(e),quickReplyPayload:e.quick_reply?.payload,repliedToMessageId:e.reply_to?.mid}}function Tt(t,e){return D(t)?t.attachments.filter(s=>Ve(s,e)):[]}function kt(t){return D(t)?t.attachments.map(e=>e.payload.url):[]}var Pt={MAX_TEXT_LENGTH:2e3,MAX_QUICK_REPLY_PAYLOAD_LENGTH:1e3,MAX_REFERRAL_REF_LENGTH:250,EVENT_TYPE:"message"},Mt={image:["image/jpeg","image/png","image/gif","image/webp"],video:["video/mp4","video/avi","video/quicktime","video/webm"],audio:["audio/mpeg","audio/mp4","audio/wav","audio/ogg"],file:["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain"]};function N(t){return !t||typeof t!="object"?null:"type"in t&&Object.values(x).includes(t.type)?t.type:"message"in t?"message":"message_edit"in t?"message_edit":"reaction"in t?"reaction":"read"in t?"read":"messaging_feedback"in t?"messaging_feedback":"postback"in t?"postback":null}function we(t){let e=new Set;if(t.object==="page"&&Array.isArray(t.entry)){for(let s of t.entry)if(Array.isArray(s.messaging))for(let o of s.messaging){let a=N(o);a&&e.add(a);}}return Array.from(e)}function ae(t){return ge(t)}function St(t){let e=N(t);return e?"type"in t?t:{...t,type:e}:null}async function Ue(t,e){let s=ae(t);for(let o of s){let a=St(o);if(!a){e.onUnknown&&await e.onUnknown(o);continue}switch(a.type){case "message":e.onMessage&&await e.onMessage(a);break;case "message_edit":e.onMessageEdit&&await e.onMessageEdit(a);break;case "reaction":e.onMessageReaction&&await e.onMessageReaction(a);break;case "read":e.onMessageRead&&await e.onMessageRead(a);break;case "messaging_feedback":e.onMessagingFeedback&&await e.onMessagingFeedback(a);break;case "postback":e.onMessagingPostback&&await e.onMessagingPostback(a);break;default:let n=a;e.onUnknown&&await e.onUnknown(n);break}}}function Ge(t,e){return t["hub.mode"]==="subscribe"&&t["hub.verify_token"]===e?t["hub.challenge"]:null}async function Fe(t,e,s){if(!e)return {isValid:false,error:"Missing X-Hub-Signature-256 header"};if(!e.startsWith("sha256="))return {isValid:false,error:"Invalid signature format. Expected sha256= prefix"};if(!s)return {isValid:false,error:"App secret is required for signature verification"};try{if(typeof Buffer>"u")return {isValid:!1,error:"Signature verification is only supported in Node.js environments"};let o=await import('crypto'),a=e.substring(7),n=o.createHmac("sha256",s).update(t).digest("hex"),h=Buffer.from(a,"hex"),g=Buffer.from(n,"hex");if(h.length!==g.length)return {isValid:!1,error:"Signature length mismatch"};let l=o.timingSafeEqual(h,g);return {isValid:l,error:l?void 0:"Signature verification failed"}}catch(o){return {isValid:false,error:`Signature verification error: ${o instanceof Error?o.message:"Unknown error"}`}}}
|
|
2
|
+
exports.ATTACHMENT_LIMITS=Be;exports.ATTACHMENT_MIME_TYPES=Mt;exports.AttachmentsAPI=P;exports.CESDisplayOption=H;exports.COMMON_POSTBACK_PAYLOADS=at;exports.CSATDisplayOption=F;exports.ConversationsAPI=R;exports.FEED_CONSTANTS=Me;exports.FeedActionVerb=j;exports.FeedItemType=X;exports.FeedbackType=G;exports.FollowUpType=q;exports.LIVE_VIDEO_CONSTANTS=Ie;exports.LiveVideoStatus=I;exports.MESSAGE_CONSTANTS=Pt;exports.MESSAGE_EDIT_CONSTANTS=ze;exports.MESSAGE_LIMITS=v;exports.MESSAGE_READS_CONSTANTS=tt;exports.MESSAGING_FEEDBACK_CONSTANTS=f;exports.MessageReactionAction=U;exports.MessageReactionType=w;exports.MessageReferralSource=oe;exports.MessageReferralType=se;exports.MessageValidationError=T;exports.Messenger=V;exports.MessengerAPIError=u;exports.MessengerConfigError=p;exports.MessengerNetworkError=b;exports.MessengerTimeoutError=y;exports.ModerationAPI=M;exports.NPSDisplayOption=B;exports.POSTBACK_CONSTANTS=nt;exports.ProfileAPI=A;exports.SendAPI=k;exports.TEMPLATE_LIMITS=d;exports.TemplateValidationError=i;exports.TemplatesAPI=_;exports.VIDEO_CONSTANTS=xe;exports.VideoStatus=W;exports.WebhookAttachmentType=te;exports.WebhookEventType=x;exports.extractFeedContext=ut;exports.extractLiveVideoContext=Ce;exports.extractMessageContext=yt;exports.extractMessageEditContext=Qe;exports.extractMessageReadsContext=Je;exports.extractMessagingFeedbackContext=it;exports.extractPageEvents=Ee;exports.extractPhotos=ft;exports.extractPostbackContext=ot;exports.extractTextFeedback=dt;exports.extractVideoContext=_e;exports.extractWebhookEvents=ae;exports.getAttachmentUrls=kt;exports.getAttachmentsByType=Tt;exports.getFeedbackScoresByType=ct;exports.getPageWebhookEventTypes=me;exports.getReadMessageCount=et;exports.getReadMessages=ue;exports.getWebhookEventType=N;exports.getWebhookPayloadEventTypes=we;exports.hasAttachments=D;exports.hasEnded=J;exports.hasMessage=lt;exports.hasQuickReply=De;exports.hasReferral=Le;exports.hasReferralData=fe;exports.isAttachmentType=Ve;exports.isComment=ye;exports.isCompletingEncoding=Ae;exports.isEncodingFailed=Re;exports.isEndingLive=We;exports.isFeedEvent=mt;exports.isFeedVideo=ke;exports.isGoingLive=Oe;exports.isIdentifiedSender=he;exports.isLive=Q;exports.isLiveVideoEvent=ve;exports.isLiveVideoProcessing=Z;exports.isMessageEditEvent=Ye;exports.isMessageEvent=ht;exports.isMessageRead=le;exports.isMessageReadsEvent=Ze;exports.isMessagingFeedbackEvent=rt;exports.isMessagingPostbackEvent=st;exports.isPhoto=Te;exports.isPostCreated=be;exports.isReaction=Pe;exports.isReplyMessage=Ne;exports.isScheduled=z;exports.isTextMessage=bt;exports.isVODReady=ee;exports.isValidFeedbackScore=pt;exports.isValidQuestionId=gt;exports.isValidTextFeedback=Et;exports.isVideoEvent=Se;exports.isVideoProcessing=$;exports.isVideoReady=K;exports.processWebhookEvents=Ue;exports.verifyWebhookSignature=Fe;exports.verifyWebhookSubscription=Ge;exports.videoHasError=Y;//# sourceMappingURL=index.cjs.map
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|