@warriorteam/messenger-sdk 1.5.2 → 1.5.4
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 +5 -4
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +24 -6
- package/dist/index.d.ts +24 -6
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -905,6 +905,7 @@ interface BaseWebhookEvent {
|
|
|
905
905
|
*/
|
|
906
906
|
declare enum WebhookEventType {
|
|
907
907
|
MESSAGE = "message",
|
|
908
|
+
MESSAGE_ECHO = "message_echo",
|
|
908
909
|
MESSAGE_EDIT = "message_edit",
|
|
909
910
|
MESSAGE_REACTION = "reaction",
|
|
910
911
|
MESSAGE_READ = "read",
|
|
@@ -986,19 +987,19 @@ interface BaseProcessingContext {
|
|
|
986
987
|
* Get event types from a Page webhook payload (uses 'changes' array)
|
|
987
988
|
*
|
|
988
989
|
* @param payload - The Page webhook payload to extract event types from
|
|
989
|
-
* @returns Array of unique
|
|
990
|
+
* @returns Array of unique WebhookEventType values found in the payload
|
|
990
991
|
*
|
|
991
992
|
* @example
|
|
992
993
|
* ```typescript
|
|
993
994
|
* const eventTypes = getPageWebhookEventTypes(payload);
|
|
994
|
-
* console.log('Page events:', eventTypes); // [
|
|
995
|
+
* console.log('Page events:', eventTypes); // [WebhookEventType.FEED, WebhookEventType.VIDEOS]
|
|
995
996
|
*
|
|
996
|
-
* if (eventTypes.includes(
|
|
997
|
+
* if (eventTypes.includes(WebhookEventType.FEED)) {
|
|
997
998
|
* // Process feed events
|
|
998
999
|
* }
|
|
999
1000
|
* ```
|
|
1000
1001
|
*/
|
|
1001
|
-
declare function getPageWebhookEventTypes(payload: PageWebhookPayload):
|
|
1002
|
+
declare function getPageWebhookEventTypes(payload: PageWebhookPayload): WebhookEventType[];
|
|
1002
1003
|
|
|
1003
1004
|
/**
|
|
1004
1005
|
* Facebook Messenger Platform - Message Edits Webhook Types
|
|
@@ -2889,6 +2890,7 @@ interface ReplyTo {
|
|
|
2889
2890
|
* Message ID of the message being replied to
|
|
2890
2891
|
*/
|
|
2891
2892
|
mid: string;
|
|
2893
|
+
is_self_reply?: boolean;
|
|
2892
2894
|
}
|
|
2893
2895
|
/**
|
|
2894
2896
|
* Base attachment payload interface
|
|
@@ -3005,6 +3007,9 @@ interface Message {
|
|
|
3005
3007
|
* Unique message identifier
|
|
3006
3008
|
*/
|
|
3007
3009
|
mid: string;
|
|
3010
|
+
is_echo?: boolean;
|
|
3011
|
+
app_id?: string | number;
|
|
3012
|
+
metadata?: string;
|
|
3008
3013
|
/**
|
|
3009
3014
|
* Text content of the message.
|
|
3010
3015
|
* Present for text messages and messages with quick replies.
|
|
@@ -3278,6 +3283,18 @@ declare const ATTACHMENT_MIME_TYPES: {
|
|
|
3278
3283
|
readonly file: readonly ["application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "text/plain"];
|
|
3279
3284
|
};
|
|
3280
3285
|
|
|
3286
|
+
interface EchoMessage extends Message {
|
|
3287
|
+
is_echo: true;
|
|
3288
|
+
app_id?: string | number;
|
|
3289
|
+
metadata?: string;
|
|
3290
|
+
}
|
|
3291
|
+
interface MessageEchoWebhookEvent extends BaseWebhookEvent {
|
|
3292
|
+
type: WebhookEventType.MESSAGE_ECHO;
|
|
3293
|
+
message: EchoMessage;
|
|
3294
|
+
}
|
|
3295
|
+
interface MessageEchoWebhookPayload extends WebhookPayload<MessageEchoWebhookEvent> {
|
|
3296
|
+
}
|
|
3297
|
+
|
|
3281
3298
|
/**
|
|
3282
3299
|
* Facebook Messenger Webhook Events - Main Entry Point
|
|
3283
3300
|
*
|
|
@@ -3292,11 +3309,11 @@ declare const ATTACHMENT_MIME_TYPES: {
|
|
|
3292
3309
|
* Discriminated union type of all possible webhook events.
|
|
3293
3310
|
* Each event has a 'type' field that allows TypeScript to narrow the type.
|
|
3294
3311
|
*/
|
|
3295
|
-
type MessengerWebhookEvent = MessageEditWebhookEvent | MessageReactionWebhookEvent | MessageWebhookEvent | MessageReadsWebhookEvent | MessagingFeedbackWebhookEvent | MessagingPostbackWebhookEvent;
|
|
3312
|
+
type MessengerWebhookEvent = MessageEditWebhookEvent | MessageReactionWebhookEvent | MessageWebhookEvent | MessageEchoWebhookEvent | MessageReadsWebhookEvent | MessagingFeedbackWebhookEvent | MessagingPostbackWebhookEvent;
|
|
3296
3313
|
/**
|
|
3297
3314
|
* Union type of all possible webhook payloads
|
|
3298
3315
|
*/
|
|
3299
|
-
type MessengerWebhookPayload = MessageEditWebhookPayload | MessageReactionWebhookPayload | MessageWebhookPayload | MessageReadsWebhookPayload | MessagingFeedbackWebhookPayload | MessagingPostbackWebhookPayload;
|
|
3316
|
+
type MessengerWebhookPayload = MessageEditWebhookPayload | MessageReactionWebhookPayload | MessageWebhookPayload | MessageEchoWebhookPayload | MessageReadsWebhookPayload | MessagingFeedbackWebhookPayload | MessagingPostbackWebhookPayload;
|
|
3300
3317
|
/**
|
|
3301
3318
|
* Type guard to check webhook event type for a SINGLE event.
|
|
3302
3319
|
* This function now properly handles individual events from the messaging array.
|
|
@@ -3374,6 +3391,7 @@ declare function extractWebhookEvents(payload: WebhookPayload): MessengerWebhook
|
|
|
3374
3391
|
*/
|
|
3375
3392
|
interface WebhookEventHandlers {
|
|
3376
3393
|
onMessage?: (event: MessageWebhookEvent) => void | Promise<void>;
|
|
3394
|
+
onMessageEcho?: (event: MessageEchoWebhookEvent) => void | Promise<void>;
|
|
3377
3395
|
onMessageEdit?: (event: MessageEditWebhookEvent) => void | Promise<void>;
|
|
3378
3396
|
onMessageReaction?: (event: MessageReactionWebhookEvent) => void | Promise<void>;
|
|
3379
3397
|
onMessageRead?: (event: MessageReadsWebhookEvent) => void | Promise<void>;
|
package/dist/index.d.ts
CHANGED
|
@@ -905,6 +905,7 @@ interface BaseWebhookEvent {
|
|
|
905
905
|
*/
|
|
906
906
|
declare enum WebhookEventType {
|
|
907
907
|
MESSAGE = "message",
|
|
908
|
+
MESSAGE_ECHO = "message_echo",
|
|
908
909
|
MESSAGE_EDIT = "message_edit",
|
|
909
910
|
MESSAGE_REACTION = "reaction",
|
|
910
911
|
MESSAGE_READ = "read",
|
|
@@ -986,19 +987,19 @@ interface BaseProcessingContext {
|
|
|
986
987
|
* Get event types from a Page webhook payload (uses 'changes' array)
|
|
987
988
|
*
|
|
988
989
|
* @param payload - The Page webhook payload to extract event types from
|
|
989
|
-
* @returns Array of unique
|
|
990
|
+
* @returns Array of unique WebhookEventType values found in the payload
|
|
990
991
|
*
|
|
991
992
|
* @example
|
|
992
993
|
* ```typescript
|
|
993
994
|
* const eventTypes = getPageWebhookEventTypes(payload);
|
|
994
|
-
* console.log('Page events:', eventTypes); // [
|
|
995
|
+
* console.log('Page events:', eventTypes); // [WebhookEventType.FEED, WebhookEventType.VIDEOS]
|
|
995
996
|
*
|
|
996
|
-
* if (eventTypes.includes(
|
|
997
|
+
* if (eventTypes.includes(WebhookEventType.FEED)) {
|
|
997
998
|
* // Process feed events
|
|
998
999
|
* }
|
|
999
1000
|
* ```
|
|
1000
1001
|
*/
|
|
1001
|
-
declare function getPageWebhookEventTypes(payload: PageWebhookPayload):
|
|
1002
|
+
declare function getPageWebhookEventTypes(payload: PageWebhookPayload): WebhookEventType[];
|
|
1002
1003
|
|
|
1003
1004
|
/**
|
|
1004
1005
|
* Facebook Messenger Platform - Message Edits Webhook Types
|
|
@@ -2889,6 +2890,7 @@ interface ReplyTo {
|
|
|
2889
2890
|
* Message ID of the message being replied to
|
|
2890
2891
|
*/
|
|
2891
2892
|
mid: string;
|
|
2893
|
+
is_self_reply?: boolean;
|
|
2892
2894
|
}
|
|
2893
2895
|
/**
|
|
2894
2896
|
* Base attachment payload interface
|
|
@@ -3005,6 +3007,9 @@ interface Message {
|
|
|
3005
3007
|
* Unique message identifier
|
|
3006
3008
|
*/
|
|
3007
3009
|
mid: string;
|
|
3010
|
+
is_echo?: boolean;
|
|
3011
|
+
app_id?: string | number;
|
|
3012
|
+
metadata?: string;
|
|
3008
3013
|
/**
|
|
3009
3014
|
* Text content of the message.
|
|
3010
3015
|
* Present for text messages and messages with quick replies.
|
|
@@ -3278,6 +3283,18 @@ declare const ATTACHMENT_MIME_TYPES: {
|
|
|
3278
3283
|
readonly file: readonly ["application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "text/plain"];
|
|
3279
3284
|
};
|
|
3280
3285
|
|
|
3286
|
+
interface EchoMessage extends Message {
|
|
3287
|
+
is_echo: true;
|
|
3288
|
+
app_id?: string | number;
|
|
3289
|
+
metadata?: string;
|
|
3290
|
+
}
|
|
3291
|
+
interface MessageEchoWebhookEvent extends BaseWebhookEvent {
|
|
3292
|
+
type: WebhookEventType.MESSAGE_ECHO;
|
|
3293
|
+
message: EchoMessage;
|
|
3294
|
+
}
|
|
3295
|
+
interface MessageEchoWebhookPayload extends WebhookPayload<MessageEchoWebhookEvent> {
|
|
3296
|
+
}
|
|
3297
|
+
|
|
3281
3298
|
/**
|
|
3282
3299
|
* Facebook Messenger Webhook Events - Main Entry Point
|
|
3283
3300
|
*
|
|
@@ -3292,11 +3309,11 @@ declare const ATTACHMENT_MIME_TYPES: {
|
|
|
3292
3309
|
* Discriminated union type of all possible webhook events.
|
|
3293
3310
|
* Each event has a 'type' field that allows TypeScript to narrow the type.
|
|
3294
3311
|
*/
|
|
3295
|
-
type MessengerWebhookEvent = MessageEditWebhookEvent | MessageReactionWebhookEvent | MessageWebhookEvent | MessageReadsWebhookEvent | MessagingFeedbackWebhookEvent | MessagingPostbackWebhookEvent;
|
|
3312
|
+
type MessengerWebhookEvent = MessageEditWebhookEvent | MessageReactionWebhookEvent | MessageWebhookEvent | MessageEchoWebhookEvent | MessageReadsWebhookEvent | MessagingFeedbackWebhookEvent | MessagingPostbackWebhookEvent;
|
|
3296
3313
|
/**
|
|
3297
3314
|
* Union type of all possible webhook payloads
|
|
3298
3315
|
*/
|
|
3299
|
-
type MessengerWebhookPayload = MessageEditWebhookPayload | MessageReactionWebhookPayload | MessageWebhookPayload | MessageReadsWebhookPayload | MessagingFeedbackWebhookPayload | MessagingPostbackWebhookPayload;
|
|
3316
|
+
type MessengerWebhookPayload = MessageEditWebhookPayload | MessageReactionWebhookPayload | MessageWebhookPayload | MessageEchoWebhookPayload | MessageReadsWebhookPayload | MessagingFeedbackWebhookPayload | MessagingPostbackWebhookPayload;
|
|
3300
3317
|
/**
|
|
3301
3318
|
* Type guard to check webhook event type for a SINGLE event.
|
|
3302
3319
|
* This function now properly handles individual events from the messaging array.
|
|
@@ -3374,6 +3391,7 @@ declare function extractWebhookEvents(payload: WebhookPayload): MessengerWebhook
|
|
|
3374
3391
|
*/
|
|
3375
3392
|
interface WebhookEventHandlers {
|
|
3376
3393
|
onMessage?: (event: MessageWebhookEvent) => void | Promise<void>;
|
|
3394
|
+
onMessageEcho?: (event: MessageEchoWebhookEvent) => void | Promise<void>;
|
|
3377
3395
|
onMessageEdit?: (event: MessageEditWebhookEvent) => void | Promise<void>;
|
|
3378
3396
|
onMessageReaction?: (event: MessageReactionWebhookEvent) => void | Promise<void>;
|
|
3379
3397
|
onMessageRead?: (event: MessageReadsWebhookEvent) => void | Promise<void>;
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var ae="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 n=0;n<=this.config.maxRetries;n++)try{let a=await this.makeRequest(s,e);return await this.handleResponse(a)}catch(a){if(o=a,a instanceof u&&a.statusCode>=400&&a.statusCode<500||n===this.config.maxRetries)throw a;await this.delay(1e3*(n+1));}throw o||new Error("Unknown error occurred")}buildUrl(e,s,o){let n=new URL(`${this.config.baseUrl}/${this.config.version}${e}`),a=o||this.config.accessToken;if(!a)throw new Error("Access token is required. Provide it in constructor or method options.");return n.searchParams.append("access_token",a),s&&Object.entries(s).forEach(([h,g])=>{n.searchParams.append(h,String(g));}),n.toString()}async makeRequest(e,s){let o=new AbortController,n=setTimeout(()=>o.abort(),this.config.timeout);try{let a={method:s.method,headers:{"Content-Type":"application/json"},signal:o.signal};return s.body&&(a.body=JSON.stringify(s.body)),await fetch(e,a)}catch(a){throw a instanceof Error?a.name==="AbortError"?new y(this.config.timeout):new b(`Network request failed: ${a.message}`,a):a}finally{clearTimeout(n);}}async handleResponse(e){let o=e.headers.get("content-type")?.includes("application/json");if(!e.ok)if(o){let n=await e.json();throw new u(n.error,e.status,n)}else {let n=await e.text();throw new u({message:n||`HTTP ${e.status} ${e.statusText}`,type:"http_error",code:e.status,fbtrace_id:""},e.status,n)}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 P=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 k=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(n=>({id:n})):[{id:e}];return this.moderate({user_ids:o,actions:["block_user"]},s)}async unblockUser(e,s){let o=Array.isArray(e)?e.map(n=>({id:n})):[{id:e}];return this.moderate({user_ids:o,actions:["unblock_user"]},s)}async banUser(e,s){let o=Array.isArray(e)?e.map(n=>({id:n})):[{id:e}];return this.moderate({user_ids:o,actions:["ban_user"]},s)}async unbanUser(e,s){let o=Array.isArray(e)?e.map(n=>({id:n})):[{id:e}];return this.moderate({user_ids:o,actions:["unban_user"]},s)}async moveToSpam(e,s){let o=Array.isArray(e)?e.map(n=>({id:n})):[{id:e}];return this.moderate({user_ids:o,actions:["move_to_spam"]},s)}async blockAndSpam(e,s){let o=Array.isArray(e)?e.map(n=>({id:n})):[{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},n={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:n,accessToken:s?.accessToken})}async button(e,s){de(e.text,e.buttons);let o={template_type:"button",text:e.text,buttons:e.buttons},n={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:n,accessToken:s?.accessToken})}async media(e,s){pe(e.element);let o={template_type:"media",elements:[e.element]},n={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:n,accessToken:s?.accessToken})}async product(e,s){let o={template_type:"product",elements:e.elements},n={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:n,accessToken:s?.accessToken})}};var A=class{constructor(e){this.httpClient=e;}async get(e,s){let{psid:o,fields:n=["first_name","last_name"]}=e,a=new URLSearchParams({fields:n.join(",")});return this.httpClient.request({method:"GET",path:`/${o}?${a.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 n={};return s?.platform&&(n.platform=s.platform),s?.user_id&&(n.user_id=s.user_id),s?.folder&&(n.folder=s.folder),s?.limit&&(n.limit=s.limit.toString()),s?.after&&(n.after=s.after),s?.before&&(n.before=s.before),this.httpClient.request({method:"GET",path:`/${e}/conversations`,query:n,accessToken:o?.accessToken})}async get(e,s,o){if(!e)throw new p("Conversation ID is required");let n={};return s?.fields&&s.fields.length>0&&(n.fields=s.fields.join(",")),s?.limit&&(n.limit=s.limit.toString()),s?.after&&(n.after=s.after),s?.before&&(n.before=s.before),this.httpClient.request({method:"GET",path:`/${e}`,query:n,accessToken:o?.accessToken})}async getMessages(e,s,o){if(!e)throw new p("Conversation ID is required");let n={fields:"messages"};s?.limit&&(n.limit=s.limit.toString()),s?.after&&(n.after=s.after),s?.before&&(n.before=s.before);let a=await this.httpClient.request({method:"GET",path:`/${e}`,query:n,accessToken:o?.accessToken});return {data:a.messages?.data||[],paging:a.messages?.paging}}async getMessage(e,s,o){if(!e)throw new p("Message ID is required");let n={};return s?.fields&&s.fields.length>0?n.fields=s.fields.join(","):n.fields="id,created_time,from,to,message,attachments,reactions,reply_to",this.httpClient.request({method:"GET",path:`/${e}`,query:n,accessToken:o?.accessToken})}async getRecentMessages(e,s){let n=(await this.getMessages(e,{limit:20},s)).data.map(a=>this.getMessage(a.id,void 0,s));return Promise.all(n)}async findByUser(e,s,o,n){let a=await this.list(e,{platform:o,user_id:s},n);return a.data&&a.data.length>0&&a.data[0]?a.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||ae,baseUrl:e.baseUrl,timeout:e.timeout,maxRetries:e.maxRetries};this.httpClient=new C(s),this.send=new P(this.httpClient),this.attachments=new k(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)o&&typeof o=="object"&&"field"in o&&e.add(o.field);}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 nt={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 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,n])=>{e.push({questionId:o,feedbackType:n.type,score:parseInt(n.payload,10),textFeedback:n.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 n=parseInt(o.payload,10),a=e.get(o.type)||[];e.set(o.type,[...a,n]);});}),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 Pe(t){return t.item==="video"}function ke(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:Pe(o),isReaction:ke(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=(a=>(a.MESSENGER_CODE="MESSENGER_CODE",a.DISCOVER_TAB="DISCOVER_TAB",a.ADS="ADS",a.SHORTLINK="SHORTLINK",a.CUSTOMER_CHAT_PLUGIN="CUSTOMER_CHAT_PLUGIN",a))(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 Pt(t){return D(t)?t.attachments.map(e=>e.payload.url):[]}var kt={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 n=N(o);n&&e.add(n);}}return Array.from(e)}function ne(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=ne(t);for(let o of s){let n=St(o);if(!n){e.onUnknown&&await e.onUnknown(o);continue}switch(n.type){case "message":e.onMessage&&await e.onMessage(n);break;case "message_edit":e.onMessageEdit&&await e.onMessageEdit(n);break;case "reaction":e.onMessageReaction&&await e.onMessageReaction(n);break;case "read":e.onMessageRead&&await e.onMessageRead(n);break;case "messaging_feedback":e.onMessagingFeedback&&await e.onMessagingFeedback(n);break;case "postback":e.onMessagingPostback&&await e.onMessagingPostback(n);break;default:let a=n;e.onUnknown&&await e.onUnknown(a);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'),n=e.substring(7),a=o.createHmac("sha256",s).update(t).digest("hex"),h=Buffer.from(n,"hex"),g=Buffer.from(a,"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
|
-
export{
|
|
1
|
+
var re="v23.0",ie="https://graph.facebook.com";var E={MESSAGES:"/me/messages",MESSAGE_ATTACHMENTS:"/me/message_attachments",MODERATE_CONVERSATIONS:"/me/moderate_conversations"},C={TEXT_MESSAGE_MAX_CHARS:2e3},He={IMAGE_MAX_SIZE:8*1024*1024,OTHER_MAX_SIZE:25*1024*1024,VIDEO_TIMEOUT:75,OTHER_TIMEOUT:10},c={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 h=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;}},y=class extends Error{cause;constructor(e,s){super(e),this.name="MessengerNetworkError",this.cause=s;}},T=class extends Error{timeout;constructor(e){super(`Request timed out after ${e}ms`),this.name="MessengerTimeoutError",this.timeout=e;}},d=class extends Error{constructor(e){super(e),this.name="MessengerConfigError";}};var W=class{config;constructor(e){this.config={accessToken:e.accessToken,version:e.version,baseUrl:e.baseUrl||ie,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 h&&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(([b,p])=>{a.searchParams.append(b,String(p));}),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 T(this.config.timeout):new y(`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 h(a.error,e.status,a)}else {let a=await e.text();throw new h({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 M=class extends Error{constructor(e){super(e),this.name="MessageValidationError";}};function ce(t){if(!t||t.trim()==="")throw new M("Text message cannot be empty");if(t.length>C.TEXT_MESSAGE_MAX_CHARS)throw new M(`Text message cannot exceed ${C.TEXT_MESSAGE_MAX_CHARS} characters`)}var k=class{constructor(e){this.httpClient=e;}async message(e,s){return e.message?.text&&ce(e.message.text),this.httpClient.request({method:"POST",path:E.MESSAGES,body:e,accessToken:s?.accessToken})}async action(e,s,o){return this.httpClient.request({method:"POST",path:E.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:E.MESSAGE_ATTACHMENTS,body:o,accessToken:s?.accessToken})}};var S=class{constructor(e){this.httpClient=e;}async moderate(e,s){return this.httpClient.request({method:"POST",path:E.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 de(t){if(t.length===0)throw new i("Generic template must have at least 1 element");if(t.length>c.GENERIC_ELEMENTS_MAX)throw new i(`Generic template cannot have more than ${c.GENERIC_ELEMENTS_MAX} elements`);t.forEach((e,s)=>{$e(e,s);});}function $e(t,e){if(!t.title||t.title.trim()==="")throw new i(`Element ${e}: title is required`);if(t.title.length>c.GENERIC_TITLE_MAX_CHARS)throw new i(`Element ${e}: title cannot exceed ${c.GENERIC_TITLE_MAX_CHARS} characters`);if(t.subtitle&&t.subtitle.length>c.GENERIC_SUBTITLE_MAX_CHARS)throw new i(`Element ${e}: subtitle cannot exceed ${c.GENERIC_SUBTITLE_MAX_CHARS} characters`);if(t.image_url&&!_(t.image_url))throw new i(`Element ${e}: image_url must be HTTPS`);if(t.buttons&&V(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 pe(t,e){if(!t||t.trim()==="")throw new i("Button template text is required");if(t.length>c.BUTTON_TEXT_MAX_CHARS)throw new i(`Button template text cannot exceed ${c.BUTTON_TEXT_MAX_CHARS} characters`);if(e.length===0)throw new i("Button template must have at least 1 button");V(e,"Button template");}function ge(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&&!_(t.url))throw new i("Media template url must be HTTPS");if(t.buttons){if(t.buttons.length>c.MEDIA_BUTTONS_MAX_COUNT)throw new i(`Media template cannot have more than ${c.MEDIA_BUTTONS_MAX_COUNT} buttons`);V(t.buttons,"Media template");}}function V(t,e){if(t.length>c.BUTTONS_MAX_COUNT)throw new i(`${e} cannot have more than ${c.BUTTONS_MAX_COUNT} buttons`);t.forEach((s,o)=>{Ke(s,`${e} button ${o}`);});}function Ke(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>c.BUTTON_TITLE_MAX_CHARS)throw new i(`${e}: title cannot exceed ${c.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(!_(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>c.POSTBACK_PAYLOAD_MAX_CHARS)throw new i(`${e}: payload cannot exceed ${c.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(!_(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&&!_(t.fallback_url))throw new i(`${e}: fallback_url must be HTTPS`)}function _(t){try{return new URL(t).protocol==="https:"}catch{return false}}var A=class{constructor(e){this.httpClient=e;}async generic(e,s){de(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:E.MESSAGES,body:a,accessToken:s?.accessToken})}async button(e,s){pe(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:E.MESSAGES,body:a,accessToken:s?.accessToken})}async media(e,s){ge(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:E.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:E.MESSAGES,body:a,accessToken:s?.accessToken})}};var R=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 v=class{constructor(e){this.httpClient=e;}async list(e,s,o){if(!e)throw new d("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 d("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 d("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 d("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 w=class{send;attachments;moderation;templates;profile;conversations;httpClient;constructor(e={}){this.validateConfig(e);let s={accessToken:e.accessToken,version:e.version||re,baseUrl:e.baseUrl,timeout:e.timeout,maxRetries:e.maxRetries};this.httpClient=new W(s),this.send=new k(this.httpClient),this.attachments=new P(this.httpClient),this.moderation=new S(this.httpClient),this.templates=new A(this.httpClient),this.profile=new R(this.httpClient),this.conversations=new v(this.httpClient);}validateConfig(e){if(e.accessToken!==void 0&&(typeof e.accessToken!="string"||e.accessToken.trim()===""))throw new d("Access token must be a non-empty string");if(e.version&&typeof e.version!="string")throw new d("API version must be a string");if(e.timeout&&(typeof e.timeout!="number"||e.timeout<=0))throw new d("Timeout must be a positive number");if(e.maxRetries&&(typeof e.maxRetries!="number"||e.maxRetries<0))throw new d("Max retries must be a non-negative number")}};var x=(l=>(l.MESSAGE="message",l.MESSAGE_ECHO="message_echo",l.MESSAGE_EDIT="message_edit",l.MESSAGE_REACTION="reaction",l.MESSAGE_READ="read",l.MESSAGING_FEEDBACK="messaging_feedback",l.MESSAGING_POSTBACK="postback",l.FEED="feed",l.VIDEOS="videos",l.LIVE_VIDEOS="live_videos",l))(x||{});function Ye(t){return typeof t.id=="string"&&t.id.length>0}function Ee(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 me(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=Ye(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 le(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 Qe(t){return t&&typeof t=="object"&&"message_edit"in t}function ze(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 U=(m=>(m.LIKE="like",m.DISLIKE="dislike",m.LOVE="love",m.SAD="sad",m.ANGRY="angry",m.WOW="wow",m.SMILE="smile",m.OTHER="other",m))(U||{}),G=(s=>(s.REACT="react",s.UNREACT="unreact",s))(G||{});function Je(t){return t&&typeof t=="object"&&"read"in t}function et(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 ue(t,e){return t<=e}function he(t,e){return t.filter(s=>ue(s.timestamp,e))}function tt(t,e){return he(t,e).length}var st={EVENT_TYPE:"message_reads",READ_PROPERTY:"read"};function ot(t){return t&&typeof t=="object"&&"postback"in t}function fe(t){return t.postback&&"referral"in t.postback&&t.postback.referral!=null}function be(t){return t&&typeof t.id=="string"&&t.id.length>0}function at(t){let e=fe(t),s=be(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 nt={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"},rt={MAX_PAYLOAD_LENGTH:1e3,EVENT_TYPE:"postback",REFERRAL_SOURCES:{SHORTLINK:"SHORTLINK",ADS:"ADS",MESSENGER_CODE:"MESSENGER_CODE"},REFERRAL_TYPES:{OPEN_THREAD:"OPEN_THREAD"}};var F=(o=>(o.CSAT="csat",o.NPS="nps",o.CES="ces",o))(F||{}),B=(o=>(o.ONE_TO_FIVE="one_to_five",o.FIVE_STARS="five_stars",o.FIVE_EMOJIS="five_emojis",o))(B||{}),H=(e=>(e.ZERO_TO_TEN="zero_to_ten",e))(H||{}),q=(e=>(e.ONE_TO_SEVEN="one_to_seven",e))(q||{}),X=(e=>(e.FREE_FORM="free_form",e))(X||{});function it(t){return t&&typeof t=="object"&&"messaging_feedback"in t}function ct(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 dt(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 pt(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 gt(t,e){let s=f.SCORE_RANGES[t];return Number.isInteger(e)&&e>=s.min&&e<=s.max}function Et(t){return t.length<=f.QUESTION_ID.MAX_LENGTH&&f.QUESTION_ID.VALID_PATTERN.test(t)}function mt(t){return t.length<=f.MAX_TEXT_FEEDBACK_LENGTH}var j=(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))(j||{}),$=(g=>(g.ADD="add",g.BLOCK="block",g.EDIT="edit",g.EDITED="edited",g.DELETE="delete",g.FOLLOW="follow",g.HIDE="hide",g.MUTE="mute",g.REMOVE="remove",g.UNBLOCK="unblock",g.UNHIDE="unhide",g.UPDATE="update",g))($||{});function lt(t){return t&&typeof t=="object"&&t.field==="feed"}function ye(t){return t.verb==="add"&&t.item==="post"}function Te(t){return t.item==="comment"}function Me(t){return t.item==="photo"||t.item==="photo-album"}function ke(t){return t.item==="video"}function Pe(t){return t.item==="reaction"}function ut(t){return typeof t.message=="string"&&t.message.length>0}function ht(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:ye(o),isComment:Te(o),isPhoto:Me(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 Se={FIELD_NAME:"feed",MAX_PAGE_LIKES_FOR_NOTIFICATIONS:1e4};var I=(o=>(o.PROCESSING="processing",o.READY="ready",o.ERROR="error",o))(I||{});function _e(t){return t&&typeof t=="object"&&t.field==="videos"}function K(t){return t.status.video_status==="processing"}function Y(t){return t.status.video_status==="ready"}function Q(t){return t.status.video_status==="error"}function Ae(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:K(o),isReady:Y(o),hasError:Q(o)}}function Re(t,e){return t==="processing"&&e==="ready"}function ve(t,e){return t==="processing"&&e==="error"}var xe={FIELD_NAME:"videos",STATUSES:Object.values(I)};var D=(u=>(u.LIVE="LIVE",u.LIVE_STOPPED="LIVE_STOPPED",u.PROCESSING="PROCESSING",u.SCHEDULED_CANCELED="SCHEDULED_CANCELED",u.SCHEDULED_EXPIRED="SCHEDULED_EXPIRED",u.SCHEDULED_LIVE="SCHEDULED_LIVE",u.SCHEDULED_UNPUBLISHED="SCHEDULED_UNPUBLISHED",u.UNPUBLISHED="UNPUBLISHED",u.VOD="VOD",u))(D||{});function Ce(t){return t&&typeof t=="object"&&t.field==="live_videos"}function z(t){return t.status==="LIVE"}function Z(t){return t.status==="SCHEDULED_UNPUBLISHED"||t.status==="SCHEDULED_LIVE"}function J(t){return t.status==="PROCESSING"}function ee(t){return t.status==="LIVE_STOPPED"||t.status==="SCHEDULED_CANCELED"||t.status==="SCHEDULED_EXPIRED"}function te(t){return t.status==="VOD"}function We(t,e,s){let{value:o}=s;return {pageId:t,timestamp:e,eventDate:new Date(e),videoId:o.id,status:o.status,isLive:z(o),isScheduled:Z(o),isProcessing:J(o),hasEnded:ee(o),isVODReady:te(o)}}function Oe(t,e){return t!=="LIVE"&&e==="LIVE"}function Ie(t,e){return t==="LIVE"&&(e==="LIVE_STOPPED"||e==="SCHEDULED_CANCELED"||e==="SCHEDULED_EXPIRED")}var De={FIELD_NAME:"live_videos",STATUSES:Object.values(D)};var se=(p=>(p.AUDIO="audio",p.FILE="file",p.IMAGE="image",p.VIDEO="video",p.FALLBACK="fallback",p.REEL="reel",p.IG_REEL="ig_reel",p))(se||{}),oe=(o=>(o.OPEN_THREAD="OPEN_THREAD",o.PRODUCT="product",o.ADS="ads",o))(oe||{}),ae=(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))(ae||{});function bt(t){return t&&typeof t=="object"&&"message"in t}function yt(t){return typeof t.text=="string"&&t.text.length>0}function N(t){return Array.isArray(t.attachments)&&t.attachments.length>0}function Ne(t){return t.quick_reply!==void 0}function Le(t){return t.reply_to!==void 0}function Ve(t){return t.referral!==void 0}function we(t,e){return t.type===e}function Tt(t){let{message:e}=t;return {...O(t),messageId:e.mid,text:e.text,hasAttachments:N(e),isQuickReply:Ne(e),isReply:Le(e),hasReferral:Ve(e),quickReplyPayload:e.quick_reply?.payload,repliedToMessageId:e.reply_to?.mid}}function Mt(t,e){return N(t)?t.attachments.filter(s=>we(s,e)):[]}function kt(t){return N(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"},St={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 L(t){return !t||typeof t!="object"?null:"type"in t&&Object.values(x).includes(t.type)?t.type:"message"in t&&t.message&&typeof t.message=="object"&&t.message.is_echo===true?"message_echo":"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 Ue(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=L(o);a&&e.add(a);}}return Array.from(e)}function ne(t){return Ee(t)}function _t(t){let e=L(t);return e?"type"in t?t:{...t,type:e}:null}async function Ge(t,e){let s=ne(t);for(let o of s){let a=_t(o);if(!a){e.onUnknown&&await e.onUnknown(o);continue}switch(a.type){case "message":e.onMessage&&await e.onMessage(a);break;case "message_echo":e.onMessageEcho&&await e.onMessageEcho(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 Fe(t,e){return t["hub.mode"]==="subscribe"&&t["hub.verify_token"]===e?t["hub.challenge"]:null}async function Be(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"),b=Buffer.from(a,"hex"),p=Buffer.from(n,"hex");if(b.length!==p.length)return {isValid:!1,error:"Signature length mismatch"};let m=o.timingSafeEqual(b,p);return {isValid:m,error:m?void 0:"Signature verification failed"}}catch(o){return {isValid:false,error:`Signature verification error: ${o instanceof Error?o.message:"Unknown error"}`}}}
|
|
2
|
+
export{He as ATTACHMENT_LIMITS,St as ATTACHMENT_MIME_TYPES,P as AttachmentsAPI,q as CESDisplayOption,nt as COMMON_POSTBACK_PAYLOADS,B as CSATDisplayOption,v as ConversationsAPI,Se as FEED_CONSTANTS,$ as FeedActionVerb,j as FeedItemType,F as FeedbackType,X as FollowUpType,De as LIVE_VIDEO_CONSTANTS,D as LiveVideoStatus,Pt as MESSAGE_CONSTANTS,Ze as MESSAGE_EDIT_CONSTANTS,C as MESSAGE_LIMITS,st as MESSAGE_READS_CONSTANTS,f as MESSAGING_FEEDBACK_CONSTANTS,G as MessageReactionAction,U as MessageReactionType,ae as MessageReferralSource,oe as MessageReferralType,M as MessageValidationError,w as Messenger,h as MessengerAPIError,d as MessengerConfigError,y as MessengerNetworkError,T as MessengerTimeoutError,S as ModerationAPI,H as NPSDisplayOption,rt as POSTBACK_CONSTANTS,R as ProfileAPI,k as SendAPI,c as TEMPLATE_LIMITS,i as TemplateValidationError,A as TemplatesAPI,xe as VIDEO_CONSTANTS,I as VideoStatus,se as WebhookAttachmentType,x as WebhookEventType,ht as extractFeedContext,We as extractLiveVideoContext,Tt as extractMessageContext,ze as extractMessageEditContext,et as extractMessageReadsContext,ct as extractMessagingFeedbackContext,me as extractPageEvents,ft as extractPhotos,at as extractPostbackContext,pt as extractTextFeedback,Ae as extractVideoContext,ne as extractWebhookEvents,kt as getAttachmentUrls,Mt as getAttachmentsByType,dt as getFeedbackScoresByType,le as getPageWebhookEventTypes,tt as getReadMessageCount,he as getReadMessages,L as getWebhookEventType,Ue as getWebhookPayloadEventTypes,N as hasAttachments,ee as hasEnded,ut as hasMessage,Ne as hasQuickReply,Ve as hasReferral,fe as hasReferralData,we as isAttachmentType,Te as isComment,Re as isCompletingEncoding,ve as isEncodingFailed,Ie as isEndingLive,lt as isFeedEvent,ke as isFeedVideo,Oe as isGoingLive,be as isIdentifiedSender,z as isLive,Ce as isLiveVideoEvent,J as isLiveVideoProcessing,Qe as isMessageEditEvent,bt as isMessageEvent,ue as isMessageRead,Je as isMessageReadsEvent,it as isMessagingFeedbackEvent,ot as isMessagingPostbackEvent,Me as isPhoto,ye as isPostCreated,Pe as isReaction,Le as isReplyMessage,Z as isScheduled,yt as isTextMessage,te as isVODReady,gt as isValidFeedbackScore,Et as isValidQuestionId,mt as isValidTextFeedback,_e as isVideoEvent,K as isVideoProcessing,Y as isVideoReady,Ge as processWebhookEvents,Be as verifyWebhookSignature,Fe as verifyWebhookSubscription,Q as videoHasError};//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|