@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/dist/index.d.cts
CHANGED
|
@@ -982,6 +982,23 @@ interface BaseProcessingContext {
|
|
|
982
982
|
/** Human-readable datetime for the event timestamp */
|
|
983
983
|
eventDate: Date;
|
|
984
984
|
}
|
|
985
|
+
/**
|
|
986
|
+
* Get event types from a Page webhook payload (uses 'changes' array)
|
|
987
|
+
*
|
|
988
|
+
* @param payload - The Page webhook payload to extract event types from
|
|
989
|
+
* @returns Array of unique WebhookEventType values found in the payload
|
|
990
|
+
*
|
|
991
|
+
* @example
|
|
992
|
+
* ```typescript
|
|
993
|
+
* const eventTypes = getPageWebhookEventTypes(payload);
|
|
994
|
+
* console.log('Page events:', eventTypes); // [WebhookEventType.FEED, WebhookEventType.VIDEOS]
|
|
995
|
+
*
|
|
996
|
+
* if (eventTypes.includes(WebhookEventType.FEED)) {
|
|
997
|
+
* // Process feed events
|
|
998
|
+
* }
|
|
999
|
+
* ```
|
|
1000
|
+
*/
|
|
1001
|
+
declare function getPageWebhookEventTypes(payload: PageWebhookPayload): WebhookEventType[];
|
|
985
1002
|
|
|
986
1003
|
/**
|
|
987
1004
|
* Facebook Messenger Platform - Message Edits Webhook Types
|
|
@@ -3482,4 +3499,4 @@ declare const TEMPLATE_LIMITS: {
|
|
|
3482
3499
|
readonly MEDIA_BUTTONS_MAX_COUNT: 3;
|
|
3483
3500
|
};
|
|
3484
3501
|
|
|
3485
|
-
export { ATTACHMENT_LIMITS, ATTACHMENT_MIME_TYPES, type AttachmentPayload, type AttachmentType$1 as AttachmentType, type AttachmentUploadRequest, type AttachmentUploadResponse, AttachmentsAPI, type Button, type ButtonTemplatePayload, CESDisplayOption, COMMON_POSTBACK_PAYLOADS, CSATDisplayOption, type Conversation, type ConversationDetail, type ConversationFolder, type Message$1 as ConversationMessage, type MessageAttachment$1 as ConversationMessageAttachment, type MessageReaction as ConversationMessageReaction, type ConversationParticipant, type ConversationPlatform, ConversationsAPI, type DefaultAction, type ErrorResponse, FEED_CONSTANTS, type FallbackAttachmentPayload, FeedActionVerb, type FeedEventData, type FeedEventValue, FeedItemType, type FeedPagePost, type FeedProcessingContext, type FeedSender, type FeedWebhookEvent, type FeedWebhookPayload, type FeedbackFollowUp, type FeedbackQuestion, type FeedbackScreen, FeedbackType, FollowUpType, type GenericTemplate, type GenericTemplateElement, type GenericTemplatePayload, type WebhookPayload as GenericWebhookPayload, type GetConversationParams, type GetMessageParams, type GetProfileRequest, type ImageData, LIVE_VIDEO_CONSTANTS, type ListConversationsParams, type ListConversationsResponse, type ListMessagesResponse, type LiveVideoEventData, type LiveVideoEventValue, type LiveVideoProcessingContext, LiveVideoStatus, type LiveVideoWebhookEvent, type LiveVideoWebhookPayload, MESSAGE_CONSTANTS, MESSAGE_EDIT_CONSTANTS, MESSAGE_LIMITS, MESSAGE_READS_CONSTANTS, MESSAGING_FEEDBACK_CONSTANTS, type MediaAttachmentPayload, type MediaTemplateElement, type MediaTemplatePayload, type Message$2 as Message, type MessageAttachment, type MessageAttachmentType, type MessageBasic, type MessageCommand, type MessageEdit, type MessageEditProcessingContext, type WebhookRecipient as MessageEditRecipient, type WebhookSender as MessageEditSender, type MessageEditWebhookEvent, type MessageEditWebhookPayload, type MessageParticipant, type MessageProcessingContext, MessageReactionAction, type MessageReactionData, type MessageReactionProcessingContext, type WebhookRecipient as MessageReactionRecipient, type WebhookSender as MessageReactionSender, type MessageReactionStats, MessageReactionType, type MessageReactionWebhookConfig, type MessageReactionWebhookEvent, type MessageReactionWebhookPayload, type MessageReadData, type MessageReadsProcessingContext, type MessageReadsWebhookEvent, type MessageReadsWebhookPayload, type WebhookRecipient as MessageRecipient, type MessageReferral, ReferralSource as MessageReferralSource, ReferralType as MessageReferralType, type WebhookSender as MessageSender, type MessageShare, type MessageTag, MessageValidationError, type MessageWebhookEvent, type MessageWebhookPayload, type MessagingFeedbackData, type MessagingFeedbackProcessingContext, type MessagingFeedbackWebhookEvent, type MessagingFeedbackWebhookPayload, type MessagingPostbackWebhookEvent, type MessagingPostbackWebhookPayload, type MessagingType, Messenger, MessengerAPIError, type MessengerConfig, MessengerConfigError, type MessengerError, MessengerNetworkError, MessengerTimeoutError, type MessengerWebhookEvent, type MessengerWebhookPayload, type ModerateConversationsRequest, type ModerateConversationsResponse, ModerationAPI, type ModerationAction, NPSDisplayOption, POSTBACK_CONSTANTS, type PageWebhookEntry, type PageWebhookPayload, type PostbackData, type PostbackEventData, type PostbackPayload, type PostbackProcessingContext, type WebhookRecipient as PostbackRecipient, type PostbackReferral, type WebhookSender as PostbackSender, type ProductTemplateElement, type ProductTemplatePayload, ProfileAPI, type ProfileField, type QuickReply$1 as QuickReply, type Recipient, type ReelAttachmentPayload, type ReferralSource$1 as ReferralSource, type ReferralType$1 as ReferralType, type ReplyInfo, type ReplyTo, SendAPI, type SendMessageRequest, type SendMessageResponse, type SenderAction, type ShareTemplatePayload, type SharedProduct, type StickerAttachmentPayload, type StoryShare, TEMPLATE_LIMITS, TemplateValidationError, TemplatesAPI, type UserId, type UserProfile, VIDEO_CONSTANTS, type VideoData, type VideoEventData, type VideoEventValue, type VideoProcessingContext, VideoStatus, type VideoStatusInfo, type VideoWebhookEvent, type VideoWebhookPayload, type WatermarkTimestamp, AttachmentType as WebhookAttachmentType, type WebhookEntry, type WebhookEventHandlers, WebhookEventType, type Message as WebhookMessage, type QuickReply as WebhookQuickReply, type WebhookSignatureVerificationResult, type WebhookVerificationParams, extractFeedContext, extractLiveVideoContext, extractMessageContext, extractMessageEditContext, extractMessageReadsContext, extractMessagingFeedbackContext, extractPageEvents, extractPhotos, extractPostbackContext, extractTextFeedback, extractVideoContext, extractWebhookEvents, getAttachmentUrls, getAttachmentsByType, getFeedbackScoresByType, getReadMessageCount, getReadMessages, getWebhookEventType, getWebhookPayloadEventTypes, hasAttachments, hasEnded, hasMessage, hasQuickReply, hasReferral, hasReferralData, isAttachmentType, isComment, isCompletingEncoding, isEncodingFailed, isEndingLive, isFeedEvent, isVideo as isFeedVideo, isGoingLive, isIdentifiedSender, isLive, isLiveVideoEvent, isProcessing as isLiveVideoProcessing, isMessageEditEvent, isMessageEvent, isMessageRead, isMessageReadsEvent, isMessagingFeedbackEvent, isMessagingPostbackEvent, isPhoto, isPostCreated, isReaction, isReplyMessage, isScheduled, isTextMessage, isVODReady, isValidFeedbackScore, isValidQuestionId, isValidTextFeedback, isVideoEvent, isProcessing$1 as isVideoProcessing, isReady as isVideoReady, processWebhookEvents, verifyWebhookSignature, verifyWebhookSubscription, hasError as videoHasError };
|
|
3502
|
+
export { ATTACHMENT_LIMITS, ATTACHMENT_MIME_TYPES, type AttachmentPayload, type AttachmentType$1 as AttachmentType, type AttachmentUploadRequest, type AttachmentUploadResponse, AttachmentsAPI, type Button, type ButtonTemplatePayload, CESDisplayOption, COMMON_POSTBACK_PAYLOADS, CSATDisplayOption, type Conversation, type ConversationDetail, type ConversationFolder, type Message$1 as ConversationMessage, type MessageAttachment$1 as ConversationMessageAttachment, type MessageReaction as ConversationMessageReaction, type ConversationParticipant, type ConversationPlatform, ConversationsAPI, type DefaultAction, type ErrorResponse, FEED_CONSTANTS, type FallbackAttachmentPayload, FeedActionVerb, type FeedEventData, type FeedEventValue, FeedItemType, type FeedPagePost, type FeedProcessingContext, type FeedSender, type FeedWebhookEvent, type FeedWebhookPayload, type FeedbackFollowUp, type FeedbackQuestion, type FeedbackScreen, FeedbackType, FollowUpType, type GenericTemplate, type GenericTemplateElement, type GenericTemplatePayload, type WebhookPayload as GenericWebhookPayload, type GetConversationParams, type GetMessageParams, type GetProfileRequest, type ImageData, LIVE_VIDEO_CONSTANTS, type ListConversationsParams, type ListConversationsResponse, type ListMessagesResponse, type LiveVideoEventData, type LiveVideoEventValue, type LiveVideoProcessingContext, LiveVideoStatus, type LiveVideoWebhookEvent, type LiveVideoWebhookPayload, MESSAGE_CONSTANTS, MESSAGE_EDIT_CONSTANTS, MESSAGE_LIMITS, MESSAGE_READS_CONSTANTS, MESSAGING_FEEDBACK_CONSTANTS, type MediaAttachmentPayload, type MediaTemplateElement, type MediaTemplatePayload, type Message$2 as Message, type MessageAttachment, type MessageAttachmentType, type MessageBasic, type MessageCommand, type MessageEdit, type MessageEditProcessingContext, type WebhookRecipient as MessageEditRecipient, type WebhookSender as MessageEditSender, type MessageEditWebhookEvent, type MessageEditWebhookPayload, type MessageParticipant, type MessageProcessingContext, MessageReactionAction, type MessageReactionData, type MessageReactionProcessingContext, type WebhookRecipient as MessageReactionRecipient, type WebhookSender as MessageReactionSender, type MessageReactionStats, MessageReactionType, type MessageReactionWebhookConfig, type MessageReactionWebhookEvent, type MessageReactionWebhookPayload, type MessageReadData, type MessageReadsProcessingContext, type MessageReadsWebhookEvent, type MessageReadsWebhookPayload, type WebhookRecipient as MessageRecipient, type MessageReferral, ReferralSource as MessageReferralSource, ReferralType as MessageReferralType, type WebhookSender as MessageSender, type MessageShare, type MessageTag, MessageValidationError, type MessageWebhookEvent, type MessageWebhookPayload, type MessagingFeedbackData, type MessagingFeedbackProcessingContext, type MessagingFeedbackWebhookEvent, type MessagingFeedbackWebhookPayload, type MessagingPostbackWebhookEvent, type MessagingPostbackWebhookPayload, type MessagingType, Messenger, MessengerAPIError, type MessengerConfig, MessengerConfigError, type MessengerError, MessengerNetworkError, MessengerTimeoutError, type MessengerWebhookEvent, type MessengerWebhookPayload, type ModerateConversationsRequest, type ModerateConversationsResponse, ModerationAPI, type ModerationAction, NPSDisplayOption, POSTBACK_CONSTANTS, type PageWebhookEntry, type PageWebhookPayload, type PostbackData, type PostbackEventData, type PostbackPayload, type PostbackProcessingContext, type WebhookRecipient as PostbackRecipient, type PostbackReferral, type WebhookSender as PostbackSender, type ProductTemplateElement, type ProductTemplatePayload, ProfileAPI, type ProfileField, type QuickReply$1 as QuickReply, type Recipient, type ReelAttachmentPayload, type ReferralSource$1 as ReferralSource, type ReferralType$1 as ReferralType, type ReplyInfo, type ReplyTo, SendAPI, type SendMessageRequest, type SendMessageResponse, type SenderAction, type ShareTemplatePayload, type SharedProduct, type StickerAttachmentPayload, type StoryShare, TEMPLATE_LIMITS, TemplateValidationError, TemplatesAPI, type UserId, type UserProfile, VIDEO_CONSTANTS, type VideoData, type VideoEventData, type VideoEventValue, type VideoProcessingContext, VideoStatus, type VideoStatusInfo, type VideoWebhookEvent, type VideoWebhookPayload, type WatermarkTimestamp, AttachmentType as WebhookAttachmentType, type WebhookEntry, type WebhookEventHandlers, WebhookEventType, type Message as WebhookMessage, type QuickReply as WebhookQuickReply, type WebhookSignatureVerificationResult, type WebhookVerificationParams, extractFeedContext, extractLiveVideoContext, extractMessageContext, extractMessageEditContext, extractMessageReadsContext, extractMessagingFeedbackContext, extractPageEvents, extractPhotos, extractPostbackContext, extractTextFeedback, extractVideoContext, extractWebhookEvents, getAttachmentUrls, getAttachmentsByType, getFeedbackScoresByType, getPageWebhookEventTypes, getReadMessageCount, getReadMessages, getWebhookEventType, getWebhookPayloadEventTypes, hasAttachments, hasEnded, hasMessage, hasQuickReply, hasReferral, hasReferralData, isAttachmentType, isComment, isCompletingEncoding, isEncodingFailed, isEndingLive, isFeedEvent, isVideo as isFeedVideo, isGoingLive, isIdentifiedSender, isLive, isLiveVideoEvent, isProcessing as isLiveVideoProcessing, isMessageEditEvent, isMessageEvent, isMessageRead, isMessageReadsEvent, isMessagingFeedbackEvent, isMessagingPostbackEvent, isPhoto, isPostCreated, isReaction, isReplyMessage, isScheduled, isTextMessage, isVODReady, isValidFeedbackScore, isValidQuestionId, isValidTextFeedback, isVideoEvent, isProcessing$1 as isVideoProcessing, isReady as isVideoReady, processWebhookEvents, verifyWebhookSignature, verifyWebhookSubscription, hasError as videoHasError };
|
package/dist/index.d.ts
CHANGED
|
@@ -982,6 +982,23 @@ interface BaseProcessingContext {
|
|
|
982
982
|
/** Human-readable datetime for the event timestamp */
|
|
983
983
|
eventDate: Date;
|
|
984
984
|
}
|
|
985
|
+
/**
|
|
986
|
+
* Get event types from a Page webhook payload (uses 'changes' array)
|
|
987
|
+
*
|
|
988
|
+
* @param payload - The Page webhook payload to extract event types from
|
|
989
|
+
* @returns Array of unique WebhookEventType values found in the payload
|
|
990
|
+
*
|
|
991
|
+
* @example
|
|
992
|
+
* ```typescript
|
|
993
|
+
* const eventTypes = getPageWebhookEventTypes(payload);
|
|
994
|
+
* console.log('Page events:', eventTypes); // [WebhookEventType.FEED, WebhookEventType.VIDEOS]
|
|
995
|
+
*
|
|
996
|
+
* if (eventTypes.includes(WebhookEventType.FEED)) {
|
|
997
|
+
* // Process feed events
|
|
998
|
+
* }
|
|
999
|
+
* ```
|
|
1000
|
+
*/
|
|
1001
|
+
declare function getPageWebhookEventTypes(payload: PageWebhookPayload): WebhookEventType[];
|
|
985
1002
|
|
|
986
1003
|
/**
|
|
987
1004
|
* Facebook Messenger Platform - Message Edits Webhook Types
|
|
@@ -3482,4 +3499,4 @@ declare const TEMPLATE_LIMITS: {
|
|
|
3482
3499
|
readonly MEDIA_BUTTONS_MAX_COUNT: 3;
|
|
3483
3500
|
};
|
|
3484
3501
|
|
|
3485
|
-
export { ATTACHMENT_LIMITS, ATTACHMENT_MIME_TYPES, type AttachmentPayload, type AttachmentType$1 as AttachmentType, type AttachmentUploadRequest, type AttachmentUploadResponse, AttachmentsAPI, type Button, type ButtonTemplatePayload, CESDisplayOption, COMMON_POSTBACK_PAYLOADS, CSATDisplayOption, type Conversation, type ConversationDetail, type ConversationFolder, type Message$1 as ConversationMessage, type MessageAttachment$1 as ConversationMessageAttachment, type MessageReaction as ConversationMessageReaction, type ConversationParticipant, type ConversationPlatform, ConversationsAPI, type DefaultAction, type ErrorResponse, FEED_CONSTANTS, type FallbackAttachmentPayload, FeedActionVerb, type FeedEventData, type FeedEventValue, FeedItemType, type FeedPagePost, type FeedProcessingContext, type FeedSender, type FeedWebhookEvent, type FeedWebhookPayload, type FeedbackFollowUp, type FeedbackQuestion, type FeedbackScreen, FeedbackType, FollowUpType, type GenericTemplate, type GenericTemplateElement, type GenericTemplatePayload, type WebhookPayload as GenericWebhookPayload, type GetConversationParams, type GetMessageParams, type GetProfileRequest, type ImageData, LIVE_VIDEO_CONSTANTS, type ListConversationsParams, type ListConversationsResponse, type ListMessagesResponse, type LiveVideoEventData, type LiveVideoEventValue, type LiveVideoProcessingContext, LiveVideoStatus, type LiveVideoWebhookEvent, type LiveVideoWebhookPayload, MESSAGE_CONSTANTS, MESSAGE_EDIT_CONSTANTS, MESSAGE_LIMITS, MESSAGE_READS_CONSTANTS, MESSAGING_FEEDBACK_CONSTANTS, type MediaAttachmentPayload, type MediaTemplateElement, type MediaTemplatePayload, type Message$2 as Message, type MessageAttachment, type MessageAttachmentType, type MessageBasic, type MessageCommand, type MessageEdit, type MessageEditProcessingContext, type WebhookRecipient as MessageEditRecipient, type WebhookSender as MessageEditSender, type MessageEditWebhookEvent, type MessageEditWebhookPayload, type MessageParticipant, type MessageProcessingContext, MessageReactionAction, type MessageReactionData, type MessageReactionProcessingContext, type WebhookRecipient as MessageReactionRecipient, type WebhookSender as MessageReactionSender, type MessageReactionStats, MessageReactionType, type MessageReactionWebhookConfig, type MessageReactionWebhookEvent, type MessageReactionWebhookPayload, type MessageReadData, type MessageReadsProcessingContext, type MessageReadsWebhookEvent, type MessageReadsWebhookPayload, type WebhookRecipient as MessageRecipient, type MessageReferral, ReferralSource as MessageReferralSource, ReferralType as MessageReferralType, type WebhookSender as MessageSender, type MessageShare, type MessageTag, MessageValidationError, type MessageWebhookEvent, type MessageWebhookPayload, type MessagingFeedbackData, type MessagingFeedbackProcessingContext, type MessagingFeedbackWebhookEvent, type MessagingFeedbackWebhookPayload, type MessagingPostbackWebhookEvent, type MessagingPostbackWebhookPayload, type MessagingType, Messenger, MessengerAPIError, type MessengerConfig, MessengerConfigError, type MessengerError, MessengerNetworkError, MessengerTimeoutError, type MessengerWebhookEvent, type MessengerWebhookPayload, type ModerateConversationsRequest, type ModerateConversationsResponse, ModerationAPI, type ModerationAction, NPSDisplayOption, POSTBACK_CONSTANTS, type PageWebhookEntry, type PageWebhookPayload, type PostbackData, type PostbackEventData, type PostbackPayload, type PostbackProcessingContext, type WebhookRecipient as PostbackRecipient, type PostbackReferral, type WebhookSender as PostbackSender, type ProductTemplateElement, type ProductTemplatePayload, ProfileAPI, type ProfileField, type QuickReply$1 as QuickReply, type Recipient, type ReelAttachmentPayload, type ReferralSource$1 as ReferralSource, type ReferralType$1 as ReferralType, type ReplyInfo, type ReplyTo, SendAPI, type SendMessageRequest, type SendMessageResponse, type SenderAction, type ShareTemplatePayload, type SharedProduct, type StickerAttachmentPayload, type StoryShare, TEMPLATE_LIMITS, TemplateValidationError, TemplatesAPI, type UserId, type UserProfile, VIDEO_CONSTANTS, type VideoData, type VideoEventData, type VideoEventValue, type VideoProcessingContext, VideoStatus, type VideoStatusInfo, type VideoWebhookEvent, type VideoWebhookPayload, type WatermarkTimestamp, AttachmentType as WebhookAttachmentType, type WebhookEntry, type WebhookEventHandlers, WebhookEventType, type Message as WebhookMessage, type QuickReply as WebhookQuickReply, type WebhookSignatureVerificationResult, type WebhookVerificationParams, extractFeedContext, extractLiveVideoContext, extractMessageContext, extractMessageEditContext, extractMessageReadsContext, extractMessagingFeedbackContext, extractPageEvents, extractPhotos, extractPostbackContext, extractTextFeedback, extractVideoContext, extractWebhookEvents, getAttachmentUrls, getAttachmentsByType, getFeedbackScoresByType, getReadMessageCount, getReadMessages, getWebhookEventType, getWebhookPayloadEventTypes, hasAttachments, hasEnded, hasMessage, hasQuickReply, hasReferral, hasReferralData, isAttachmentType, isComment, isCompletingEncoding, isEncodingFailed, isEndingLive, isFeedEvent, isVideo as isFeedVideo, isGoingLive, isIdentifiedSender, isLive, isLiveVideoEvent, isProcessing as isLiveVideoProcessing, isMessageEditEvent, isMessageEvent, isMessageRead, isMessageReadsEvent, isMessagingFeedbackEvent, isMessagingPostbackEvent, isPhoto, isPostCreated, isReaction, isReplyMessage, isScheduled, isTextMessage, isVODReady, isValidFeedbackScore, isValidQuestionId, isValidTextFeedback, isVideoEvent, isProcessing$1 as isVideoProcessing, isReady as isVideoReady, processWebhookEvents, verifyWebhookSignature, verifyWebhookSubscription, hasError as videoHasError };
|
|
3502
|
+
export { ATTACHMENT_LIMITS, ATTACHMENT_MIME_TYPES, type AttachmentPayload, type AttachmentType$1 as AttachmentType, type AttachmentUploadRequest, type AttachmentUploadResponse, AttachmentsAPI, type Button, type ButtonTemplatePayload, CESDisplayOption, COMMON_POSTBACK_PAYLOADS, CSATDisplayOption, type Conversation, type ConversationDetail, type ConversationFolder, type Message$1 as ConversationMessage, type MessageAttachment$1 as ConversationMessageAttachment, type MessageReaction as ConversationMessageReaction, type ConversationParticipant, type ConversationPlatform, ConversationsAPI, type DefaultAction, type ErrorResponse, FEED_CONSTANTS, type FallbackAttachmentPayload, FeedActionVerb, type FeedEventData, type FeedEventValue, FeedItemType, type FeedPagePost, type FeedProcessingContext, type FeedSender, type FeedWebhookEvent, type FeedWebhookPayload, type FeedbackFollowUp, type FeedbackQuestion, type FeedbackScreen, FeedbackType, FollowUpType, type GenericTemplate, type GenericTemplateElement, type GenericTemplatePayload, type WebhookPayload as GenericWebhookPayload, type GetConversationParams, type GetMessageParams, type GetProfileRequest, type ImageData, LIVE_VIDEO_CONSTANTS, type ListConversationsParams, type ListConversationsResponse, type ListMessagesResponse, type LiveVideoEventData, type LiveVideoEventValue, type LiveVideoProcessingContext, LiveVideoStatus, type LiveVideoWebhookEvent, type LiveVideoWebhookPayload, MESSAGE_CONSTANTS, MESSAGE_EDIT_CONSTANTS, MESSAGE_LIMITS, MESSAGE_READS_CONSTANTS, MESSAGING_FEEDBACK_CONSTANTS, type MediaAttachmentPayload, type MediaTemplateElement, type MediaTemplatePayload, type Message$2 as Message, type MessageAttachment, type MessageAttachmentType, type MessageBasic, type MessageCommand, type MessageEdit, type MessageEditProcessingContext, type WebhookRecipient as MessageEditRecipient, type WebhookSender as MessageEditSender, type MessageEditWebhookEvent, type MessageEditWebhookPayload, type MessageParticipant, type MessageProcessingContext, MessageReactionAction, type MessageReactionData, type MessageReactionProcessingContext, type WebhookRecipient as MessageReactionRecipient, type WebhookSender as MessageReactionSender, type MessageReactionStats, MessageReactionType, type MessageReactionWebhookConfig, type MessageReactionWebhookEvent, type MessageReactionWebhookPayload, type MessageReadData, type MessageReadsProcessingContext, type MessageReadsWebhookEvent, type MessageReadsWebhookPayload, type WebhookRecipient as MessageRecipient, type MessageReferral, ReferralSource as MessageReferralSource, ReferralType as MessageReferralType, type WebhookSender as MessageSender, type MessageShare, type MessageTag, MessageValidationError, type MessageWebhookEvent, type MessageWebhookPayload, type MessagingFeedbackData, type MessagingFeedbackProcessingContext, type MessagingFeedbackWebhookEvent, type MessagingFeedbackWebhookPayload, type MessagingPostbackWebhookEvent, type MessagingPostbackWebhookPayload, type MessagingType, Messenger, MessengerAPIError, type MessengerConfig, MessengerConfigError, type MessengerError, MessengerNetworkError, MessengerTimeoutError, type MessengerWebhookEvent, type MessengerWebhookPayload, type ModerateConversationsRequest, type ModerateConversationsResponse, ModerationAPI, type ModerationAction, NPSDisplayOption, POSTBACK_CONSTANTS, type PageWebhookEntry, type PageWebhookPayload, type PostbackData, type PostbackEventData, type PostbackPayload, type PostbackProcessingContext, type WebhookRecipient as PostbackRecipient, type PostbackReferral, type WebhookSender as PostbackSender, type ProductTemplateElement, type ProductTemplatePayload, ProfileAPI, type ProfileField, type QuickReply$1 as QuickReply, type Recipient, type ReelAttachmentPayload, type ReferralSource$1 as ReferralSource, type ReferralType$1 as ReferralType, type ReplyInfo, type ReplyTo, SendAPI, type SendMessageRequest, type SendMessageResponse, type SenderAction, type ShareTemplatePayload, type SharedProduct, type StickerAttachmentPayload, type StoryShare, TEMPLATE_LIMITS, TemplateValidationError, TemplatesAPI, type UserId, type UserProfile, VIDEO_CONSTANTS, type VideoData, type VideoEventData, type VideoEventValue, type VideoProcessingContext, VideoStatus, type VideoStatusInfo, type VideoWebhookEvent, type VideoWebhookPayload, type WatermarkTimestamp, AttachmentType as WebhookAttachmentType, type WebhookEntry, type WebhookEventHandlers, WebhookEventType, type Message as WebhookMessage, type QuickReply as WebhookQuickReply, type WebhookSignatureVerificationResult, type WebhookVerificationParams, extractFeedContext, extractLiveVideoContext, extractMessageContext, extractMessageEditContext, extractMessageReadsContext, extractMessagingFeedbackContext, extractPageEvents, extractPhotos, extractPostbackContext, extractTextFeedback, extractVideoContext, extractWebhookEvents, getAttachmentUrls, getAttachmentsByType, getFeedbackScoresByType, getPageWebhookEventTypes, getReadMessageCount, getReadMessages, getWebhookEventType, getWebhookPayloadEventTypes, hasAttachments, hasEnded, hasMessage, hasQuickReply, hasReferral, hasReferralData, isAttachmentType, isComment, isCompletingEncoding, isEncodingFailed, isEndingLive, isFeedEvent, isVideo as isFeedVideo, isGoingLive, isIdentifiedSender, isLive, isLiveVideoEvent, isProcessing as isLiveVideoProcessing, isMessageEditEvent, isMessageEvent, isMessageRead, isMessageReadsEvent, isMessagingFeedbackEvent, isMessagingPostbackEvent, isPhoto, isPostCreated, isReaction, isReplyMessage, isScheduled, isTextMessage, isVODReady, isValidFeedbackScore, isValidQuestionId, isValidTextFeedback, isVideoEvent, isProcessing$1 as isVideoProcessing, isReady as isVideoReady, processWebhookEvents, verifyWebhookSignature, verifyWebhookSubscription, hasError as videoHasError };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
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
|
-
export{
|
|
1
|
+
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
|
+
export{Be as ATTACHMENT_LIMITS,Mt as ATTACHMENT_MIME_TYPES,P as AttachmentsAPI,H as CESDisplayOption,at as COMMON_POSTBACK_PAYLOADS,F as CSATDisplayOption,R as ConversationsAPI,Me as FEED_CONSTANTS,j as FeedActionVerb,X as FeedItemType,G as FeedbackType,q as FollowUpType,Ie as LIVE_VIDEO_CONSTANTS,I as LiveVideoStatus,Pt as MESSAGE_CONSTANTS,ze as MESSAGE_EDIT_CONSTANTS,v as MESSAGE_LIMITS,tt as MESSAGE_READS_CONSTANTS,f as MESSAGING_FEEDBACK_CONSTANTS,U as MessageReactionAction,w as MessageReactionType,oe as MessageReferralSource,se as MessageReferralType,T as MessageValidationError,V as Messenger,u as MessengerAPIError,p as MessengerConfigError,b as MessengerNetworkError,y as MessengerTimeoutError,M as ModerationAPI,B as NPSDisplayOption,nt as POSTBACK_CONSTANTS,A as ProfileAPI,k as SendAPI,d as TEMPLATE_LIMITS,i as TemplateValidationError,_ as TemplatesAPI,xe as VIDEO_CONSTANTS,W as VideoStatus,te as WebhookAttachmentType,x as WebhookEventType,ut as extractFeedContext,Ce as extractLiveVideoContext,yt as extractMessageContext,Qe as extractMessageEditContext,Je as extractMessageReadsContext,it as extractMessagingFeedbackContext,Ee as extractPageEvents,ft as extractPhotos,ot as extractPostbackContext,dt as extractTextFeedback,_e as extractVideoContext,ae as extractWebhookEvents,kt as getAttachmentUrls,Tt as getAttachmentsByType,ct as getFeedbackScoresByType,me as getPageWebhookEventTypes,et as getReadMessageCount,ue as getReadMessages,N as getWebhookEventType,we as getWebhookPayloadEventTypes,D as hasAttachments,J as hasEnded,lt as hasMessage,De as hasQuickReply,Le as hasReferral,fe as hasReferralData,Ve as isAttachmentType,ye as isComment,Ae as isCompletingEncoding,Re as isEncodingFailed,We as isEndingLive,mt as isFeedEvent,ke as isFeedVideo,Oe as isGoingLive,he as isIdentifiedSender,Q as isLive,ve as isLiveVideoEvent,Z as isLiveVideoProcessing,Ye as isMessageEditEvent,ht as isMessageEvent,le as isMessageRead,Ze as isMessageReadsEvent,rt as isMessagingFeedbackEvent,st as isMessagingPostbackEvent,Te as isPhoto,be as isPostCreated,Pe as isReaction,Ne as isReplyMessage,z as isScheduled,bt as isTextMessage,ee as isVODReady,pt as isValidFeedbackScore,gt as isValidQuestionId,Et as isValidTextFeedback,Se as isVideoEvent,$ as isVideoProcessing,K as isVideoReady,Ue as processWebhookEvents,Fe as verifyWebhookSignature,Ge as verifyWebhookSubscription,Y as videoHasError};//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|