meta-cloud-api 1.0.1 → 1.0.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/dist/{FlowApi-UAvzhJfV.d.ts → FlowApi-B2ffO-HD.d.ts} +1 -1
- package/dist/MessageApi-BgsSpDno.d.ts +171 -0
- package/dist/{WebhookProcessor-ByAe7Kf_.d.ts → WebhookProcessor-BXYunz4N.d.ts} +2 -2
- package/dist/{WhatsApp-BIBtT-y9.d.ts → WhatsApp-pTZPQm81.d.ts} +2 -2
- package/dist/api/flow/index.d.ts +2 -2
- package/dist/api/index.d.ts +4 -3
- package/dist/api/index.js +1 -1
- package/dist/api/messages/builders/index.d.ts +536 -0
- package/dist/api/messages/builders/index.js +4 -0
- package/dist/api/messages/builders/index.js.map +1 -0
- package/dist/api/messages/index.d.ts +2 -2
- package/dist/{chunk-B7DCL6I7.js → chunk-BAOZ4U74.js} +3 -3
- package/dist/{chunk-B7DCL6I7.js.map → chunk-BAOZ4U74.js.map} +1 -1
- package/dist/{chunk-HJGN3PO4.js → chunk-JPGXONBQ.js} +3 -3
- package/dist/{chunk-HJGN3PO4.js.map → chunk-JPGXONBQ.js.map} +1 -1
- package/dist/{chunk-OA2SW4AF.js → chunk-NOJFGTRT.js} +2 -2
- package/dist/{chunk-OA2SW4AF.js.map → chunk-NOJFGTRT.js.map} +1 -1
- package/dist/{chunk-UCBYECNQ.js → chunk-YXZ4L2OK.js} +2 -2
- package/dist/{chunk-UCBYECNQ.js.map → chunk-YXZ4L2OK.js.map} +1 -1
- package/dist/{MessageApi-Circorzz.d.ts → common-BiRA_uz3.d.ts} +8 -170
- package/dist/{common-DDXsNyLF.d.ts → common-lV0NsO7t.d.ts} +1 -1
- package/dist/core/webhook/frameworks/express.d.ts +6 -5
- package/dist/core/webhook/frameworks/express.js +1 -1
- package/dist/core/webhook/frameworks/nextjs.d.ts +6 -5
- package/dist/core/webhook/frameworks/nextjs.js +1 -1
- package/dist/core/webhook/index.d.ts +6 -5
- package/dist/core/webhook/index.js +1 -1
- package/dist/core/whatsapp/index.d.ts +5 -4
- package/dist/core/whatsapp/index.js +1 -1
- package/dist/index.d.ts +7 -5
- package/dist/index.js +1 -1
- package/dist/isMetaError-CXWJwW58.d.ts +63 -0
- package/dist/utils/index.d.ts +3 -62
- package/package.json +24 -17
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/api/messages/builders/ContactMessageBuilder.ts","../../../../src/api/messages/builders/InteractiveMessageBuilder.ts","../../../../src/api/messages/builders/LocationMessageBuilder.ts","../../../../src/api/messages/builders/MediaMessageBuilder.ts","../../../../src/api/messages/builders/ReactionMessageBuilder.ts","../../../../src/api/messages/builders/TemplateMessageBuilder.ts","../../../../src/api/messages/builders/TextMessageBuilder.ts"],"names":["ContactMessageBuilder","name","firstName","lastName","middleName","suffix","prefix","phone","type","waId","phoneObj","email","emailObj","address","street","city","country","company","department","title","org","url","urlObj","year","month","day","monthStr","dayStr","ContactMessageFactory","mobilePhone","birthday","builder","isBaseActionObject","action","InteractiveMessageBuilder","text","imageUrl","buttons","btn","sections","section","buttonText","displayText","InteractiveMessageFactory","bodyText","options","message","LocationMessageBuilder","latitude","longitude","LocationMessageFactory","businessName","fullAddress","BaseMediaBuilder","id","caption","ImageMessageBuilder","VideoMessageBuilder","AudioMessageBuilder","DocumentMessageBuilder","filename","StickerMessageBuilder","MediaMessageFactory","linkOrId","isId","ReactionMessageBuilder","messageId","emoji","ReactionMessageFactory","isValidLanguageCode","code","LanguagesEnum","isValidButtonPosition","index","ButtonPositionEnum","TemplateMessageBuilder","parameters","headerComponent","param","bodyComponent","footerComponent","button","subType","buttonComponent","fallbackValue","currencyCode","amount","timestamp","TemplateMessageFactory","language","bodyParameters","customerName","orderNumber","TextMessageBuilder","enable","TextMessageFactory","body"],"mappings":"oDAaO,IAAMA,CAAAA,CAAN,KAA4B,CACvB,OAAA,CAAkC,EAAC,CAK3C,OAAA,CAAQC,CAAA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B,CAAE,OAAA,CAAQG,CAAI,CAAA,CAAE,OAClD,CAKA,OAAO,qBAAA,CAAsBA,EAA0B,CACnD,OAAO,IAAIH,CAAAA,GAAqB,OAAA,CAAQG,CAAI,CAAA,CAAE,aAAA,CAAc,IAAI,CAAA,CAAE,KAAA,EACtE,CAKA,OAAO,kBAAA,CAAmB7E,CAAAA,CAAe2B,CAAAA,CAA6B,CAClE,OAAO,IAAI+C,CAAAA,EAAmB,CAAE,OAAA,CAAQ,IAAI1E,CAAK,CAAA;;AAAA,EAAQ2B,CAAO,CAAA,CAAE,CAAA,CAAE,KAAA,EACxE,CACJ","file":"index.js","sourcesContent":["import type {\n AddressesObject,\n ContactObject,\n EmailObject,\n NameObject,\n OrgObject,\n PhoneObject,\n URLObject,\n} from '../types/contact';\n\n/**\n * Builder class for creating contact messages with a fluent API\n */\nexport class ContactMessageBuilder {\n private contact: Partial<ContactObject> = {};\n\n /**\n * Set the contact name (required)\n */\n setName(name: NameObject): this {\n if (!name || typeof name !== 'object') {\n throw new Error('Name must be an object');\n }\n this.contact.name = name;\n return this;\n }\n\n /**\n * Set simple name with first name only\n */\n setSimpleName(firstName: string, lastName?: string): this {\n if (!firstName || typeof firstName !== 'string') {\n throw new Error('First name must be a non-empty string');\n }\n const name: NameObject = {\n formatted_name: lastName ? `${firstName} ${lastName}` : firstName,\n first_name: firstName,\n };\n if (lastName) {\n name.last_name = lastName;\n }\n return this.setName(name);\n }\n\n /**\n * Set full name details\n */\n setFullName(firstName: string, lastName?: string, middleName?: string, suffix?: string, prefix?: string): this {\n if (!firstName || typeof firstName !== 'string') {\n throw new Error('First name must be a non-empty string');\n }\n\n const nameParts = [prefix, firstName, middleName, lastName, suffix].filter(Boolean);\n const name: NameObject = {\n formatted_name: nameParts.join(' '),\n first_name: firstName,\n };\n\n if (lastName) name.last_name = lastName;\n if (middleName) name.middle_name = middleName;\n if (suffix) name.suffix = suffix;\n if (prefix) name.prefix = prefix;\n\n return this.setName(name);\n }\n\n /**\n * Add phone numbers\n */\n addPhone(phone: string, type?: string, waId?: string): this {\n if (!phone || typeof phone !== 'string') {\n throw new Error('Phone number must be a non-empty string');\n }\n\n const phoneObj: PhoneObject = { phone: 'PHONE_NUMBER' };\n if (type) phoneObj.type = type;\n if (waId) phoneObj.wa_id = waId;\n\n if (!this.contact.phones) {\n this.contact.phones = [];\n }\n this.contact.phones.push(phoneObj);\n return this;\n }\n\n /**\n * Add email addresses\n */\n addEmail(email: string, type?: string): this {\n if (!email || typeof email !== 'string') {\n throw new Error('Email must be a non-empty string');\n }\n if (!email.match(/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/)) {\n throw new Error('Invalid email format');\n }\n\n const emailObj: EmailObject = { email };\n if (type) emailObj.type = type;\n\n if (!this.contact.emails) {\n this.contact.emails = [];\n }\n this.contact.emails.push(emailObj);\n return this;\n }\n\n /**\n * Add address\n */\n addAddress(address: AddressesObject): this {\n if (!address || typeof address !== 'object') {\n throw new Error('Address must be an object');\n }\n\n if (!this.contact.addresses) {\n this.contact.addresses = [];\n }\n this.contact.addresses.push(address);\n return this;\n }\n\n /**\n * Add simple address\n */\n addSimpleAddress(street: string, city: string, country: string, type?: string): this {\n const address: AddressesObject = {\n street,\n city,\n country,\n };\n if (type) address.type = type;\n return this.addAddress(address);\n }\n\n /**\n * Set organization details\n */\n setOrganization(company: string, department?: string, title?: string): this {\n const org: OrgObject = {};\n if (company) org.company = company;\n if (department) org.department = department;\n if (title) org.title = title;\n\n this.contact.org = org;\n return this;\n }\n\n /**\n * Add URL\n */\n addUrl(url: string, type?: string): this {\n if (!url || typeof url !== 'string') {\n throw new Error('URL must be a non-empty string');\n }\n\n const urlObj: URLObject = { url };\n if (type) urlObj.type = type;\n\n if (!this.contact.urls) {\n this.contact.urls = [];\n }\n this.contact.urls.push(urlObj);\n return this;\n }\n\n /**\n * Set birthday (format: YYYY-MM-DD)\n */\n setBirthday(year: number, month: number, day: number): this {\n const monthStr = month.toString().padStart(2, '0');\n const dayStr = day.toString().padStart(2, '0');\n this.contact.birthday = `${year}-${monthStr}-${dayStr}` as ContactObject['birthday'];\n return this;\n }\n\n /**\n * Build the final contact object\n */\n build(): ContactObject {\n if (!this.contact.name) {\n throw new Error('Contact name is required');\n }\n\n return this.contact as ContactObject;\n }\n\n /**\n * Reset the builder for reuse\n */\n reset(): this {\n this.contact = {};\n return this;\n }\n}\n\n/**\n * Factory class for common contact patterns\n */\nexport class ContactMessageFactory {\n /**\n * Create a simple contact with name and phone\n */\n static createSimpleContact(firstName: string, phone: string): ContactObject {\n return new ContactMessageBuilder().setSimpleName(firstName).addPhone(phone).build();\n }\n\n /**\n * Create a business contact\n */\n static createBusinessContact(\n firstName: string,\n lastName: string,\n company: string,\n title: string,\n phone: string,\n email: string,\n ): ContactObject {\n return new ContactMessageBuilder()\n .setSimpleName(firstName, lastName)\n .setOrganization(company, undefined, title)\n .addPhone(phone, 'WORK')\n .addEmail(email, 'WORK')\n .build();\n }\n\n /**\n * Create a personal contact with full details\n */\n static createPersonalContact(\n firstName: string,\n lastName: string,\n mobilePhone: string,\n email?: string,\n birthday?: { year: number; month: number; day: number },\n ): ContactObject {\n const builder = new ContactMessageBuilder().setSimpleName(firstName, lastName).addPhone(mobilePhone, 'MOBILE');\n\n if (email) {\n builder.addEmail(email, 'HOME');\n }\n\n if (birthday) {\n builder.setBirthday(birthday.year, birthday.month, birthday.day);\n }\n\n return builder.build();\n }\n}\n","import { InteractiveTypesEnum } from '../../../types/enums';\nimport type { InteractiveObject } from '../types/interactive';\n\n/**\n * Type guards for different action object types\n */\ntype RowObject = {\n id: string;\n title: string;\n description?: string;\n};\n\ntype SectionObject = {\n title?: string;\n rows: RowObject[];\n};\n\ntype BaseActionObject = {\n buttons?: Array<{ type: 'reply'; reply: { id: string; title: string } }>;\n sections?: SectionObject[];\n button?: string;\n catalog_id?: string;\n product_retailer_id?: string;\n};\n\ntype CtaUrlActionObject = {\n name: 'cta_url';\n parameters: {\n display_text: string;\n url: string;\n };\n};\n\ntype ActionObjectUnion = BaseActionObject | CtaUrlActionObject;\n\nfunction isBaseActionObject(action: ActionObjectUnion): action is BaseActionObject {\n return !('name' in action);\n}\n\nfunction isCtaUrlActionObject(action: ActionObjectUnion): action is CtaUrlActionObject {\n return 'name' in action && action.name === 'cta_url';\n}\n\n/**\n * Builder class for creating interactive messages with a fluent API\n */\nexport class InteractiveMessageBuilder {\n private message: Partial<InteractiveObject> = {};\n\n /**\n * Set the interactive message type\n */\n setType(type: InteractiveTypesEnum): this {\n this.message.type = type;\n return this;\n }\n\n /**\n * Set the body text of the message\n */\n setBody(text: string): this {\n this.message.body = { text };\n return this;\n }\n\n /**\n * Set the footer text of the message\n */\n setFooter(text: string): this {\n this.message.footer = { text };\n return this;\n }\n\n /**\n * Set a text header\n */\n setTextHeader(text: string): this {\n this.message.header = { type: 'text', text };\n return this;\n }\n\n /**\n * Set an image header\n */\n setImageHeader(imageUrl: string): this {\n this.message.header = {\n type: 'image',\n image: { link: imageUrl },\n };\n return this;\n }\n\n /**\n * Add reply buttons (for button type messages)\n */\n addReplyButtons(buttons: Array<{ id: string; title: string }>): this {\n if (!this.message.action) {\n this.message.action = {} as ActionObjectUnion;\n }\n\n const action = this.message.action as ActionObjectUnion;\n if (isBaseActionObject(action)) {\n action.buttons = buttons.map((btn) => ({\n type: 'reply',\n reply: {\n id: btn.id,\n title: btn.title,\n },\n }));\n }\n\n return this;\n }\n\n /**\n * Add list sections (for list type messages)\n * Note: This creates a single section with multiple rows\n */\n addListSections(\n sections: Array<{\n title?: string;\n rows: Array<{ id: string; title: string; description?: string }>;\n }>,\n ): this {\n if (!this.message.action) {\n this.message.action = {} as ActionObjectUnion;\n }\n\n const action = this.message.action as ActionObjectUnion;\n if (isBaseActionObject(action)) {\n // Convert sections to the proper format expected by WhatsApp API\n action.sections = sections.map((section) => ({\n title: section.title,\n rows: section.rows,\n }));\n }\n\n return this;\n }\n\n /**\n * Set the button text for list messages\n */\n setListButtonText(buttonText: string): this {\n if (!this.message.action) {\n this.message.action = {} as ActionObjectUnion;\n }\n\n const action = this.message.action as ActionObjectUnion;\n if (isBaseActionObject(action)) {\n action.button = buttonText;\n }\n\n return this;\n }\n\n /**\n * Set CTA URL action\n */\n setCTAUrl(displayText: string, url: string): this {\n this.message.action = {\n name: 'cta_url',\n parameters: {\n display_text: displayText,\n url: url,\n },\n } as CtaUrlActionObject;\n\n return this;\n }\n\n /**\n * Build the final interactive object\n */\n build(): InteractiveObject {\n if (!this.message.type) {\n throw new Error('Interactive message type is required');\n }\n if (!this.message.body) {\n throw new Error('Interactive message body is required');\n }\n if (!this.message.action) {\n throw new Error('Interactive message action is required');\n }\n\n return this.message as InteractiveObject;\n }\n\n /**\n * Reset the builder for reuse\n */\n reset(): this {\n this.message = {};\n return this;\n }\n}\n\n/**\n * Convenience factory functions for common interactive message types\n */\nexport class InteractiveMessageFactory {\n /**\n * Create a button message with reply buttons\n */\n static createButtonMessage(\n bodyText: string,\n buttons: Array<{ id: string; title: string }>,\n options?: { headerText?: string; footerText?: string },\n ): InteractiveObject {\n const builder = new InteractiveMessageBuilder()\n .setType(InteractiveTypesEnum.Button)\n .setBody(bodyText)\n .addReplyButtons(buttons);\n\n if (options?.headerText) {\n builder.setTextHeader(options.headerText);\n }\n if (options?.footerText) {\n builder.setFooter(options.footerText);\n }\n\n return builder.build();\n }\n\n /**\n * Create a list message with sections\n */\n static createListMessage(\n bodyText: string,\n buttonText: string,\n sections: Array<{\n title?: string;\n rows: Array<{ id: string; title: string; description?: string }>;\n }>,\n options?: { headerText?: string; footerText?: string },\n ): InteractiveObject {\n const builder = new InteractiveMessageBuilder()\n .setType(InteractiveTypesEnum.List)\n .setBody(bodyText)\n .addListSections(sections);\n\n if (options?.headerText) {\n builder.setTextHeader(options.headerText);\n }\n if (options?.footerText) {\n builder.setFooter(options.footerText);\n }\n\n const message = builder.build();\n\n // Add button text for list messages\n const action = message.action as ActionObjectUnion;\n if (isBaseActionObject(action)) {\n action.button = buttonText;\n }\n\n return message;\n }\n\n /**\n * Create a CTA URL message\n */\n static createCTAUrlMessage(\n bodyText: string,\n displayText: string,\n url: string,\n options?: { headerText?: string; footerText?: string },\n ): InteractiveObject {\n const builder = new InteractiveMessageBuilder()\n .setType(InteractiveTypesEnum.CtaUrl)\n .setBody(bodyText)\n .setCTAUrl(displayText, url);\n\n if (options?.headerText) {\n builder.setTextHeader(options.headerText);\n }\n if (options?.footerText) {\n builder.setFooter(options.footerText);\n }\n\n return builder.build();\n }\n}\n","import type { LocationObject } from '../types/location';\n\n/**\n * Builder class for creating location messages with a fluent API\n */\nexport class LocationMessageBuilder {\n private location: Partial<LocationObject> = {};\n\n /**\n * Set the latitude coordinate\n */\n setLatitude(latitude: number): this {\n if (typeof latitude !== 'number' || latitude < -90 || latitude > 90) {\n throw new Error('Latitude must be a number between -90 and 90');\n }\n this.location.latitude = latitude;\n return this;\n }\n\n /**\n * Set the longitude coordinate\n */\n setLongitude(longitude: number): this {\n if (typeof longitude !== 'number' || longitude < -180 || longitude > 180) {\n throw new Error('Longitude must be a number between -180 and 180');\n }\n this.location.longitude = longitude;\n return this;\n }\n\n /**\n * Set coordinates using latitude and longitude\n */\n setCoordinates(latitude: number, longitude: number): this {\n return this.setLatitude(latitude).setLongitude(longitude);\n }\n\n /**\n * Set the location name\n */\n setName(name: string): this {\n if (name && typeof name !== 'string') {\n throw new Error('Location name must be a string');\n }\n this.location.name = name;\n return this;\n }\n\n /**\n * Set the location address\n */\n setAddress(address: string): this {\n if (address && typeof address !== 'string') {\n throw new Error('Location address must be a string');\n }\n this.location.address = address;\n return this;\n }\n\n /**\n * Build the final location object\n */\n build(): LocationObject {\n if (this.location.latitude === undefined) {\n throw new Error('Latitude is required');\n }\n if (this.location.longitude === undefined) {\n throw new Error('Longitude is required');\n }\n\n return this.location as LocationObject;\n }\n\n /**\n * Reset the builder for reuse\n */\n reset(): this {\n this.location = {};\n return this;\n }\n}\n\n/**\n * Factory class for common location patterns\n */\nexport class LocationMessageFactory {\n /**\n * Create a simple location with just coordinates\n */\n static createSimpleLocation(latitude: number, longitude: number): LocationObject {\n return new LocationMessageBuilder().setCoordinates(latitude, longitude).build();\n }\n\n /**\n * Create a location with name and address\n */\n static createNamedLocation(latitude: number, longitude: number, name: string, address: string): LocationObject {\n return new LocationMessageBuilder()\n .setCoordinates(latitude, longitude)\n .setName(name)\n .setAddress(address)\n .build();\n }\n\n /**\n * Create a business location\n */\n static createBusinessLocation(\n latitude: number,\n longitude: number,\n businessName: string,\n fullAddress: string,\n ): LocationObject {\n return new LocationMessageBuilder()\n .setCoordinates(latitude, longitude)\n .setName(businessName)\n .setAddress(fullAddress)\n .build();\n }\n}\n","import type {\n AudioMediaObject,\n DocumentMediaObject,\n ImageMediaObject,\n StickerMediaObject,\n VideoMediaObject,\n} from '../types/media';\n\n/**\n * Base builder for media messages\n */\nabstract class BaseMediaBuilder<T> {\n protected media: Partial<T> = {};\n\n /**\n * Set media ID (for uploaded media)\n */\n setId(id: string): this {\n if (!id || typeof id !== 'string') {\n throw new Error('Media ID must be a non-empty string');\n }\n (this.media as any).id = id;\n return this;\n }\n\n /**\n * Set media URL\n */\n setLink(url: string): this {\n if (!url || typeof url !== 'string') {\n throw new Error('Media URL must be a non-empty string');\n }\n if (!url.match(/^https?:\\/\\//)) {\n throw new Error('Media URL must be a valid HTTP/HTTPS URL');\n }\n (this.media as any).link = url;\n return this;\n }\n\n /**\n * Set media caption\n */\n setCaption(caption: string): this {\n if (caption && typeof caption !== 'string') {\n throw new Error('Caption must be a string');\n }\n (this.media as any).caption = caption;\n return this;\n }\n\n /**\n * Build the media object\n */\n build(): T {\n if (!(this.media as any).id && !(this.media as any).link) {\n throw new Error('Either media ID or link is required');\n }\n return this.media as T;\n }\n\n /**\n * Reset the builder\n */\n reset(): this {\n this.media = {};\n return this;\n }\n}\n\n/**\n * Builder for image messages\n */\nexport class ImageMessageBuilder extends BaseMediaBuilder<ImageMediaObject> {\n // Image inherits all methods from BaseMediaBuilder\n}\n\n/**\n * Builder for video messages\n */\nexport class VideoMessageBuilder extends BaseMediaBuilder<VideoMediaObject> {\n // Video inherits all methods from BaseMediaBuilder\n}\n\n/**\n * Builder for audio messages\n */\nexport class AudioMessageBuilder extends BaseMediaBuilder<AudioMediaObject> {\n // Audio doesn't support caption\n setCaption(caption: string): this {\n throw new Error('Audio messages do not support captions');\n }\n}\n\n/**\n * Builder for document messages\n */\nexport class DocumentMessageBuilder extends BaseMediaBuilder<DocumentMediaObject> {\n /**\n * Set document filename\n */\n setFilename(filename: string): this {\n if (!filename || typeof filename !== 'string') {\n throw new Error('Filename must be a non-empty string');\n }\n this.media.filename = filename;\n return this;\n }\n}\n\n/**\n * Builder for sticker messages\n */\nexport class StickerMessageBuilder extends BaseMediaBuilder<StickerMediaObject> {\n // Sticker doesn't support caption\n setCaption(caption: string): this {\n throw new Error('Sticker messages do not support captions');\n }\n}\n\n/**\n * Factory class for common media patterns\n */\nexport class MediaMessageFactory {\n /**\n * Create an image with caption\n */\n static createImageWithCaption(linkOrId: string, caption: string, isId: boolean = false): ImageMediaObject {\n const builder = new ImageMessageBuilder();\n if (isId) {\n builder.setId(linkOrId);\n } else {\n builder.setLink(linkOrId);\n }\n return builder.setCaption(caption).build();\n }\n\n /**\n * Create a video with caption\n */\n static createVideoWithCaption(linkOrId: string, caption: string, isId: boolean = false): VideoMediaObject {\n const builder = new VideoMessageBuilder();\n if (isId) {\n builder.setId(linkOrId);\n } else {\n builder.setLink(linkOrId);\n }\n return builder.setCaption(caption).build();\n }\n\n /**\n * Create a document with filename\n */\n static createDocument(\n linkOrId: string,\n filename: string,\n caption?: string,\n isId: boolean = false,\n ): DocumentMediaObject {\n const builder = new DocumentMessageBuilder();\n if (isId) {\n builder.setId(linkOrId);\n } else {\n builder.setLink(linkOrId);\n }\n builder.setFilename(filename);\n if (caption) {\n builder.setCaption(caption);\n }\n return builder.build();\n }\n\n /**\n * Create an audio message\n */\n static createAudio(linkOrId: string, isId: boolean = false): AudioMediaObject {\n const builder = new AudioMessageBuilder();\n if (isId) {\n builder.setId(linkOrId);\n } else {\n builder.setLink(linkOrId);\n }\n return builder.build();\n }\n\n /**\n * Create a sticker message\n */\n static createSticker(linkOrId: string, isId: boolean = false): StickerMediaObject {\n const builder = new StickerMessageBuilder();\n if (isId) {\n builder.setId(linkOrId);\n } else {\n builder.setLink(linkOrId);\n }\n return builder.build();\n }\n}\n","/**\n * Builder class for creating reaction messages with a fluent API\n */\nexport class ReactionMessageBuilder {\n private reaction: { message_id?: string; emoji?: string } = {};\n\n /**\n * Set the message ID to react to\n */\n setMessageId(messageId: string): this {\n if (!messageId || typeof messageId !== 'string') {\n throw new Error('Message ID must be a non-empty string');\n }\n this.reaction.message_id = messageId;\n return this;\n }\n\n /**\n * Set the emoji for the reaction\n */\n setEmoji(emoji: string): this {\n if (!emoji || typeof emoji !== 'string') {\n throw new Error('Emoji must be a non-empty string');\n }\n // Validate that it's a single emoji (basic check)\n if (emoji.length > 4) {\n throw new Error('Please provide a single emoji character');\n }\n this.reaction.emoji = emoji;\n return this;\n }\n\n /**\n * Remove a reaction (by sending empty emoji)\n */\n removeReaction(): this {\n this.reaction.emoji = '';\n return this;\n }\n\n /**\n * Build the final reaction object\n */\n build(): { message_id: string; emoji: string } {\n if (!this.reaction.message_id) {\n throw new Error('Message ID is required');\n }\n if (this.reaction.emoji === undefined) {\n throw new Error('Emoji is required (use empty string to remove reaction)');\n }\n\n return this.reaction as { message_id: string; emoji: string };\n }\n\n /**\n * Reset the builder for reuse\n */\n reset(): this {\n this.reaction = {};\n return this;\n }\n}\n\n/**\n * Factory class for common reaction patterns\n */\nexport class ReactionMessageFactory {\n /**\n * Create a like reaction\n */\n static createLike(messageId: string): { message_id: string; emoji: string } {\n return new ReactionMessageBuilder().setMessageId(messageId).setEmoji('👍').build();\n }\n\n /**\n * Create a heart reaction\n */\n static createHeart(messageId: string): { message_id: string; emoji: string } {\n return new ReactionMessageBuilder().setMessageId(messageId).setEmoji('❤️').build();\n }\n\n /**\n * Create a laughing reaction\n */\n static createLaugh(messageId: string): { message_id: string; emoji: string } {\n return new ReactionMessageBuilder().setMessageId(messageId).setEmoji('😂').build();\n }\n\n /**\n * Create a wow reaction\n */\n static createWow(messageId: string): { message_id: string; emoji: string } {\n return new ReactionMessageBuilder().setMessageId(messageId).setEmoji('😮').build();\n }\n\n /**\n * Create a sad reaction\n */\n static createSad(messageId: string): { message_id: string; emoji: string } {\n return new ReactionMessageBuilder().setMessageId(messageId).setEmoji('😢').build();\n }\n\n /**\n * Create an angry reaction\n */\n static createAngry(messageId: string): { message_id: string; emoji: string } {\n return new ReactionMessageBuilder().setMessageId(messageId).setEmoji('😠').build();\n }\n\n /**\n * Remove a reaction\n */\n static removeReaction(messageId: string): { message_id: string; emoji: string } {\n return new ReactionMessageBuilder().setMessageId(messageId).removeReaction().build();\n }\n}\n","import {\n ButtonPositionEnum,\n ComponentTypesEnum,\n CurrencyCodesEnum,\n LanguagesEnum,\n ParametersTypesEnum,\n SubTypeEnum,\n} from '../../../types/enums';\nimport type { MessageTemplateObject } from '../types/template';\n\n// Helper type for currency parameter\nexport type CurrencyParameterHelper = {\n type: ParametersTypesEnum.Currency;\n currency: {\n fallback_value: string;\n code: CurrencyCodesEnum;\n amount_1000: number;\n };\n};\n\n// Helper type for date time parameter\nexport type DateTimeParameterHelper = {\n type: ParametersTypesEnum.DateTime;\n date_time: {\n fallback_value: string;\n timestamp: number;\n };\n};\n\n// Union type for all parameter helpers\nexport type ParameterObject = CurrencyParameterHelper | DateTimeParameterHelper;\n\n// Type guards for validation\nfunction isValidLanguageCode(code: string): code is LanguagesEnum {\n return Object.values(LanguagesEnum).includes(code as LanguagesEnum);\n}\n\nfunction isValidButtonPosition(index: number): index is ButtonPositionEnum {\n return Object.values(ButtonPositionEnum).includes(index as ButtonPositionEnum);\n}\n\n/**\n * Builder class for creating template messages with a fluent API\n */\nexport class TemplateMessageBuilder {\n private template: Partial<MessageTemplateObject<ComponentTypesEnum>> = {\n components: [],\n };\n\n /**\n * Set the template name\n */\n setName(name: string): this {\n if (!name || name.trim().length === 0) {\n throw new Error('Template name cannot be empty');\n }\n this.template.name = name;\n return this;\n }\n\n /**\n * Set the template language\n */\n setLanguage(code: string): this {\n if (!isValidLanguageCode(code)) {\n throw new Error(`Invalid language code: ${code}. Must be a valid LanguagesEnum value.`);\n }\n this.template.language = { policy: 'deterministic', code };\n return this;\n }\n\n /**\n * Add a header component with text parameters\n */\n addTextHeader(parameters: string[]): this {\n if (!Array.isArray(parameters)) {\n throw new Error('Parameters must be an array');\n }\n\n const headerComponent = {\n type: ComponentTypesEnum.Header,\n parameters: parameters.map((param) => {\n if (typeof param !== 'string') {\n throw new Error('All parameters must be strings');\n }\n return { type: ParametersTypesEnum.Text, text: param };\n }),\n };\n\n if (!this.template.components) {\n this.template.components = [];\n }\n this.template.components.push(headerComponent as any);\n return this;\n }\n\n /**\n * Add a header component with image\n */\n addImageHeader(imageUrl: string): this {\n if (!imageUrl || typeof imageUrl !== 'string') {\n throw new Error('Image URL must be a non-empty string');\n }\n\n const headerComponent = {\n type: ComponentTypesEnum.Header,\n parameters: [\n {\n type: ParametersTypesEnum.Image,\n image: { link: imageUrl },\n },\n ],\n };\n\n if (!this.template.components) {\n this.template.components = [];\n }\n this.template.components.push(headerComponent as any);\n return this;\n }\n\n /**\n * Add a body component with text parameters\n */\n addBody(parameters: string[]): this {\n if (!Array.isArray(parameters)) {\n throw new Error('Parameters must be an array');\n }\n\n const bodyComponent = {\n type: ComponentTypesEnum.Body,\n parameters: parameters.map((param) => {\n if (typeof param !== 'string') {\n throw new Error('All parameters must be strings');\n }\n return { type: ParametersTypesEnum.Text, text: param };\n }),\n };\n\n if (!this.template.components) {\n this.template.components = [];\n }\n this.template.components.push(bodyComponent as any);\n return this;\n }\n\n /**\n * Add a footer component (usually no parameters needed)\n */\n addFooter(): this {\n const footerComponent = {\n type: ComponentTypesEnum.Footer,\n };\n\n if (!this.template.components) {\n this.template.components = [];\n }\n this.template.components.push(footerComponent as any);\n return this;\n }\n\n /**\n * Add button components (for quick replies, URLs, etc.)\n */\n addButtons(\n buttons: Array<{\n index: number;\n type: 'quick_reply' | 'url';\n parameters?: string[];\n }>,\n ): this {\n if (!Array.isArray(buttons)) {\n throw new Error('Buttons must be an array');\n }\n\n buttons.forEach((button) => {\n if (typeof button.index !== 'number' || !isValidButtonPosition(button.index)) {\n throw new Error(`Button index must be a valid ButtonPositionEnum value: ${button.index}`);\n }\n\n // Map string types to SubTypeEnum values\n const subType = button.type === 'quick_reply' ? SubTypeEnum.QuickReply : SubTypeEnum.Url;\n\n const buttonComponent = {\n type: ComponentTypesEnum.Button,\n sub_type: subType,\n index: button.index,\n } as any;\n\n if (button.parameters && button.parameters.length > 0) {\n if (!Array.isArray(button.parameters)) {\n throw new Error('Button parameters must be an array');\n }\n\n // Handle different parameter types based on button type\n if (button.type === 'quick_reply') {\n // Quick reply buttons use payload parameters\n buttonComponent.parameters = button.parameters.map((param) => {\n if (typeof param !== 'string') {\n throw new Error('All button parameters must be strings');\n }\n return { type: ParametersTypesEnum.Payload, payload: param };\n });\n } else if (button.type === 'url') {\n // URL buttons use text parameters\n buttonComponent.parameters = button.parameters.map((param) => {\n if (typeof param !== 'string') {\n throw new Error('All button parameters must be strings');\n }\n return { type: ParametersTypesEnum.Text, text: param };\n });\n }\n }\n\n if (!this.template.components) {\n this.template.components = [];\n }\n this.template.components.push(buttonComponent);\n });\n\n return this;\n }\n\n /**\n * Add a currency parameter for header/body\n */\n addCurrencyParameter(fallbackValue: string, currencyCode: string, amount: number): CurrencyParameterHelper {\n if (!fallbackValue || typeof fallbackValue !== 'string') {\n throw new Error('Fallback value must be a non-empty string');\n }\n if (!currencyCode || typeof currencyCode !== 'string') {\n throw new Error('Currency code must be a non-empty string');\n }\n if (typeof amount !== 'number' || amount < 0) {\n throw new Error('Amount must be a non-negative number');\n }\n\n return {\n type: ParametersTypesEnum.Currency,\n currency: {\n fallback_value: fallbackValue,\n code: currencyCode as CurrencyCodesEnum,\n amount_1000: amount * 1000, // WhatsApp expects amount in smallest unit\n },\n };\n }\n\n /**\n * Add a date time parameter\n */\n addDateTimeParameter(fallbackValue: string, timestamp: number): DateTimeParameterHelper {\n if (!fallbackValue || typeof fallbackValue !== 'string') {\n throw new Error('Fallback value must be a non-empty string');\n }\n if (typeof timestamp !== 'number' || timestamp <= 0) {\n throw new Error('Timestamp must be a positive number');\n }\n\n return {\n type: ParametersTypesEnum.DateTime,\n date_time: {\n fallback_value: fallbackValue,\n timestamp: timestamp,\n },\n };\n }\n\n /**\n * Build the final template object\n */\n build(): MessageTemplateObject<ComponentTypesEnum> {\n if (!this.template.name) {\n throw new Error('Template name is required');\n }\n if (!this.template.language) {\n throw new Error('Template language is required');\n }\n\n return this.template as MessageTemplateObject<ComponentTypesEnum>;\n }\n\n /**\n * Reset the builder for reuse\n */\n reset(): this {\n this.template = { components: [] };\n return this;\n }\n}\n\n/**\n * Factory class for common template patterns\n */\nexport class TemplateMessageFactory {\n /**\n * Create a simple text-only template\n */\n static createSimpleTextTemplate(\n name: string,\n language: string,\n bodyParameters: string[],\n ): MessageTemplateObject<ComponentTypesEnum> {\n if (!name || !language || !Array.isArray(bodyParameters)) {\n throw new Error('Invalid parameters for simple text template');\n }\n\n return new TemplateMessageBuilder().setName(name).setLanguage(language).addBody(bodyParameters).build();\n }\n\n /**\n * Create a template with header, body and buttons\n */\n static createCompleteTemplate(\n name: string,\n language: string,\n options: {\n headerParameters?: string[];\n headerImage?: string;\n bodyParameters: string[];\n buttons?: Array<{\n index: number;\n type: 'quick_reply' | 'url';\n parameters?: string[];\n }>;\n },\n ): MessageTemplateObject<ComponentTypesEnum> {\n if (!name || !language || !options.bodyParameters) {\n throw new Error('Invalid parameters for complete template');\n }\n\n const builder = new TemplateMessageBuilder()\n .setName(name)\n .setLanguage(language)\n .addBody(options.bodyParameters);\n\n if (options.headerParameters) {\n builder.addTextHeader(options.headerParameters);\n } else if (options.headerImage) {\n builder.addImageHeader(options.headerImage);\n }\n\n if (options.buttons) {\n builder.addButtons(options.buttons);\n }\n\n return builder.build();\n }\n\n /**\n * Create an order confirmation template\n */\n static createOrderConfirmationTemplate(\n language: string,\n customerName: string,\n orderNumber: string,\n amount: number,\n currencyCode: string,\n ): MessageTemplateObject<ComponentTypesEnum> {\n if (!language || !customerName || !orderNumber || typeof amount !== 'number' || !currencyCode) {\n throw new Error('Invalid parameters for order confirmation template');\n }\n\n return new TemplateMessageBuilder()\n .setName('order_confirmation')\n .setLanguage(language)\n .addBody([customerName, orderNumber, amount.toString(), currencyCode])\n .addButtons([\n { index: 0, type: 'quick_reply' },\n { index: 1, type: 'url', parameters: [orderNumber] },\n ])\n .build();\n }\n}\n","import type { TextObject } from '../types/text';\n\n/**\n * Builder class for creating text messages with a fluent API\n */\nexport class TextMessageBuilder {\n private textMessage: Partial<TextObject> = {};\n\n /**\n * Set the message body text\n */\n setBody(text: string): this {\n if (!text || typeof text !== 'string') {\n throw new Error('Message body must be a non-empty string');\n }\n this.textMessage.body = text;\n return this;\n }\n\n /**\n * Enable or disable URL preview\n */\n setPreviewUrl(enable: boolean = true): this {\n this.textMessage.preview_url = enable;\n return this;\n }\n\n /**\n * Build the final text object\n */\n build(): TextObject {\n if (!this.textMessage.body) {\n throw new Error('Message body is required');\n }\n\n return this.textMessage as TextObject;\n }\n\n /**\n * Reset the builder for reuse\n */\n reset(): this {\n this.textMessage = {};\n return this;\n }\n}\n\n/**\n * Factory class for common text message patterns\n */\nexport class TextMessageFactory {\n /**\n * Create a simple text message\n */\n static createSimpleText(body: string): TextObject {\n return new TextMessageBuilder().setBody(body).build();\n }\n\n /**\n * Create a text message with URL preview\n */\n static createTextWithPreview(body: string): TextObject {\n return new TextMessageBuilder().setBody(body).setPreviewUrl(true).build();\n }\n\n /**\n * Create a notification message\n */\n static createNotification(title: string, message: string): TextObject {\n return new TextMessageBuilder().setBody(`*${title}*\\n\\n${message}`).build();\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { M as MessagesApi } from '../../MessageApi-
|
|
2
|
-
export { A as AudioMediaObject, C as ContactObject, D as DocumentMediaObject, I as ImageMediaObject, a as InteractiveObject, L as LocationObject,
|
|
1
|
+
import { M as MessagesApi } from '../../MessageApi-BgsSpDno.js';
|
|
2
|
+
export { A as AudioMediaObject, C as ContactObject, D as DocumentMediaObject, I as ImageMediaObject, a as InteractiveObject, L as LocationObject, M as MessageRequestParams, c as MessageTemplateObject, b as MessagesResponse, R as ReactionParams, S as StatusParams, d as StickerMediaObject, T as TextMessageParams, e as TextObject, V as VideoMediaObject } from '../../common-BiRA_uz3.js';
|
|
3
3
|
import '../../base-CdGDdVEl.js';
|
|
4
4
|
import '../../types/config.js';
|
|
5
5
|
import '../../enums-BZd9T2ul.js';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a,b as b$a,d as d$1,e,c}from'./chunk-FKXSL2JK.js';import {b as b$7}from'./chunk-JPAV644F.js';import {b as b$8}from'./chunk-PHPQ5HP3.js';import {b as b$6}from'./chunk-IYSR44P6.js';import {b as b$3}from'./chunk-SNNRWNGZ.js';import {b as b$9}from'./chunk-L4ESAO2S.js';import {b}from'./chunk-7QBIZCJ4.js';import {b as b$1}from'./chunk-JXCLRKQ7.js';import {b as b$5}from'./chunk-LV3TULSI.js';import {b as b$4}from'./chunk-JC6YMVID.js';import {b as b$2}from'./chunk-FSKBLPGE.js';import {
|
|
1
|
+
import {a,b as b$a,d as d$1,e,c}from'./chunk-FKXSL2JK.js';import {a as a$1}from'./chunk-VHAODWCN.js';import {b as b$7}from'./chunk-JPAV644F.js';import {b as b$8}from'./chunk-PHPQ5HP3.js';import {b as b$6}from'./chunk-IYSR44P6.js';import {b as b$3}from'./chunk-SNNRWNGZ.js';import {b as b$9}from'./chunk-L4ESAO2S.js';import {b}from'./chunk-7QBIZCJ4.js';import {b as b$1}from'./chunk-JXCLRKQ7.js';import {b as b$5}from'./chunk-LV3TULSI.js';import {b as b$4}from'./chunk-JC6YMVID.js';import {b as b$2}from'./chunk-FSKBLPGE.js';import {z}from'./chunk-KMAH6636.js';import {Agent}from'https';var k="UTILS",M=false,U=new a(k,process.env.DEBUG==="true"||M),H=3e3,B=30,V=2e4,$=s=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!s?.accessToken)throw U.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},q=s=>($(s),{M4D_APP_ID:s?.appId||process.env.M4D_APP_ID||"",M4D_APP_SECRET:s?.appSecret||process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:s?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),WA_BUSINESS_ACCOUNT_ID:s?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||"",CLOUD_API_VERSION:s?.apiVersion||process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:s?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||"",WEBHOOK_ENDPOINT:s?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||"",WEBHOOK_VERIFICATION_TOKEN:s?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||"",LISTENER_PORT:s?.listenerPort||parseInt(process.env.LISTENER_PORT||"")||H,MAX_RETRIES_AFTER_WAIT:s?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||B,REQUEST_TIMEOUT:s?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||"")||V,DEBUG:s?.debug||process.env.DEBUG==="true",FLOW_API_PRIVATE_PEM:s?.privatePem||process.env.FLOW_API_PRIVATE_PEM||"",FLOW_API_PASSPHRASE:s?.passphrase||process.env.FLOW_API_PASSPHRASE||""});var x="HttpsClient",F=false,v=new a(x,process.env.DEBUG==="true"||F),m=class{agent;constructor(){this.agent=new Agent({keepAlive:true});}clearSockets(){return this.agent.destroy(),true}async sendRequest(e,r,t,o,i,u){let a=`https://${e}/${r}`,h=new AbortController,n=setTimeout(()=>h.abort(),i);try{let c=await fetch(a,{method:t,headers:o,body:u,signal:h.signal});return v.log(`${t} : ${a} - ${JSON.stringify(c)}`),clearTimeout(n),new E(c)}catch(c){throw v.error(`${t} : ${a} - ${JSON.stringify(c)}`),c}}},E=class{res;respStatusCode;respHeaders;constructor(e){this.res=e,this.respStatusCode=e.status,this.respHeaders=Object.fromEntries(e.headers.entries());}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(e){throw new Error("Failed to parse response body to JSON: "+e.message)}}};var K="REQUESTER",j=false,J=new a(K,process.env.DEBUG==="true"||j),g=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(e,r,t,o,i){this.client=new m,this.host="graph.facebook.com",this.apiVersion=e||"22",this.phoneNumberId=r,this.accessToken=t,this.businessAcctId=o,this.userAgent=i;}buildHeader(e,r){let t={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return e!=="multipart/form-data"&&(t["Content-Type"]=e),r&&Object.assign(t,r),t}buildCAPIPath(e){return `v${this.apiVersion}.0/${e}`}async sendRequest(e,r,t,o,i="application/json",u){let a=i;o instanceof FormData?a="multipart/form-data":typeof o=="string"&&o.startsWith("<?xml")&&(a="application/xml");let h=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(r)}`;J.log(`${e} : ${h} (${a})`);try{let n=await this.client.sendRequest(this.host,this.buildCAPIPath(r),e,this.buildHeader(a,u),t,e==="POST"||e==="PUT"?o:void 0);if(!n.rawResponse().ok){let c$1=await n.json();throw c(c$1)?c$1:{name:"MetaError",message:"Unknown error occurred",error:{message:c$1.message||"Unknown error occurred",type:"UnknownError",code:n.statusCode(),fbtrace_id:""}}}return n}catch(n){throw c(n)?n:{name:"MetaError",message:n instanceof Error?n.message:"Network error occurred",error:{message:n instanceof Error?n.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}async getJson(e,r,t,o,i){return await(await this.sendRequest(e,r,t,o,"application/json",i)).json()}async sendFormData(e,r,t,o,i){return await(await this.sendRequest(e,r,t,o,"multipart/form-data",i)).json()}async sendUrlEncodedForm(e,r,t,o,i){let u=new URLSearchParams(o).toString();return await(await this.sendRequest(e,r,t,u,"application/x-www-form-urlencoded",i)).json()}};function D(){process.env.NODE_ENV==="test"||process.env.VITEST==="true"||typeof global<"u"&&global.__VITEST__||console.log("\x1B[36m%s\x1B[0m",`
|
|
2
2
|
\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557
|
|
3
3
|
\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2551
|
|
4
4
|
\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551
|
|
@@ -6,5 +6,5 @@ import {a,b as b$a,d as d$1,e,c}from'./chunk-FKXSL2JK.js';import {b as b$7}from'
|
|
|
6
6
|
\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551
|
|
7
7
|
\u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D
|
|
8
8
|
`);}var Q="WHATSAPP",d=new a(Q,process.env.DEBUG==="true"),f=class{config;requester;messages;media;phoneNumbers;twoStepVerification;flows;businessProfile;templates;encryption;qrCode;registration;waba;constructor(e){D(),this.config=q(e),this.requester=new g(this.config.CLOUD_API_VERSION,this.config.WA_PHONE_NUMBER_ID,this.config.CLOUD_API_ACCESS_TOKEN,this.config.WA_BUSINESS_ACCOUNT_ID,this.getUserAgent()),this.messages=new b(this.config,this.requester),this.media=new b$1(this.config,this.requester),this.phoneNumbers=new b$2(this.config,this.requester),this.twoStepVerification=new b$3(this.config,this.requester),this.flows=new b$4(this.config,this.requester),this.businessProfile=new b$5(this.config,this.requester),this.templates=new a$1(this.config,this.requester),this.encryption=new b$6(this.config,this.requester),this.qrCode=new b$7(this.config,this.requester),this.registration=new b$8(this.config,this.requester),this.waba=new b$9(this.config,this.requester),d.log(`
|
|
9
|
-
`+b$a(this.config));}updateTimeout(e){this.config.REQUEST_TIMEOUT=e,"updateTimeout"in this.requester&&this.requester.updateTimeout(e),d.log(`Timeout updated to ${e}ms`);}updateSenderNumberId(e){this.config.WA_PHONE_NUMBER_ID=e,d.log(`Sender number ID updated to ${e}`);}updateAccessToken(e){this.config.CLOUD_API_ACCESS_TOKEN=e,"updateAccessToken"in this.requester&&this.requester.updateAccessToken(e),d.log("Access token updated");}version(){return d$1()}static get Enums(){return z}getUserAgent(){return e()}};export{q as a,f as b};//# sourceMappingURL=chunk-
|
|
10
|
-
//# sourceMappingURL=chunk-
|
|
9
|
+
`+b$a(this.config));}updateTimeout(e){this.config.REQUEST_TIMEOUT=e,"updateTimeout"in this.requester&&this.requester.updateTimeout(e),d.log(`Timeout updated to ${e}ms`);}updateSenderNumberId(e){this.config.WA_PHONE_NUMBER_ID=e,d.log(`Sender number ID updated to ${e}`);}updateAccessToken(e){this.config.CLOUD_API_ACCESS_TOKEN=e,"updateAccessToken"in this.requester&&this.requester.updateAccessToken(e),d.log("Access token updated");}version(){return d$1()}static get Enums(){return z}getUserAgent(){return e()}};export{q as a,f as b};//# sourceMappingURL=chunk-BAOZ4U74.js.map
|
|
10
|
+
//# sourceMappingURL=chunk-BAOZ4U74.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config/importConfig.ts","../src/utils/http/httpsClient.ts","../src/utils/http/request.ts","../src/utils/logoConsole.ts","../src/core/whatsapp/WhatsApp.ts"],"names":["LIB_NAME","LOG_LOCAL","LOGGER","Logger","DEFAULT_LISTENER_PORT","DEFAULT_MAX_RETRIES_AFTER_WAIT","DEFAULT_REQUEST_TIMEOUT","emptyConfigChecker","config","importConfig","inputConfig","HttpsClient","Agent","hostname","path","method","headers","timeout","body","url","controller","timeoutId","response","HttpsClientResponse","error","resp","err","Requester","apiVersion","phoneNumberId","accessToken","businessAcctId","userAgent","contentType","additionalHeaders","endpoint","effectiveContentType","errorData","isMetaError","formData","urlEncodedBody","printLogo","WhatsApp","messages_default","media_default","phone_default","twoStepVerification_default","flow_default","profile_default","TemplateApi","encryption_default","qrCode_default","registration_default","waba_default","formatConfigTable","getVersion","enums_exports","getUserAgent"],"mappings":"0kBAIA,IAAMA,EAAW,OAAA,CACXC,CAAAA,CAAY,MACZC,CAAAA,CAAS,IAAIC,EAAOH,CAAAA,CAAU,OAAA,CAAQ,GAAA,CAAI,KAAA,GAAU,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A,CAClD,eAAA,GAAmB,IAAA,CAAK,WACvB,IAAA,CAAK,SAAA,CAAkB,aAAA,CAAcA,CAAO,EAEjDf,CAAAA,CAAO,GAAA,CAAI,CAAA,mBAAA,EAAsBe,CAAO,IAAI,EAChD,CAEA,oBAAA,CAAqBY,CAAAA,CAA6B,CAC9C,IAAA,CAAK,MAAA,CAAO,mBAAyCA,CAAAA,CACrD3B,CAAAA,CAAO,IAAI,CAAA,4BAAA,EAA+B2B,CAAa,CAAA,CAAE,EAC7D,CAEA,iBAAA,CAAkBC,CAAAA,CAA2B,CACzC,IAAA,CAAK,OAAO,sBAAA,CAAuCA,CAAAA,CAC/C,mBAAA,GAAuB,IAAA,CAAK,WAC3B,IAAA,CAAK,SAAA,CAAkB,kBAAkBA,CAAW,CAAA,CAEzD5B,EAAO,GAAA,CAAI,sBAAsB,EACrC,CAKA,SAAkB,CACd,OAAOqD,GAAAA,EACX,CAKA,WAAW,KAAA,EAAQ,CACf,OAAOC,CACX,CAKA,YAAA,EAAuB,CACnB,OAAOC,CAAAA,EACX,CACJ","file":"chunk-B7DCL6I7.js","sourcesContent":["import type { WabaConfigType, WhatsAppConfig } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\nimport Logger from '../utils/logger';\n\nconst LIB_NAME = 'UTILS';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\nconst DEFAULT_LISTENER_PORT = 3000;\nconst DEFAULT_MAX_RETRIES_AFTER_WAIT = 30;\nconst DEFAULT_REQUEST_TIMEOUT = 20000;\n\nconst emptyConfigChecker = (config: WhatsAppConfig | undefined) => {\n if (!process.env[WabaConfigEnum.AccessToken] && !config?.accessToken) {\n LOGGER.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`);\n throw new Error('Missing WhatsApp access token.');\n }\n};\n\nexport const importConfig = (inputConfig?: WhatsAppConfig) => {\n emptyConfigChecker(inputConfig);\n\n const wabaConfig: WabaConfigType = {\n [WabaConfigEnum.AppId]: inputConfig?.appId || process.env.M4D_APP_ID || '',\n [WabaConfigEnum.AppSecret]: inputConfig?.appSecret || process.env.M4D_APP_SECRET || '',\n [WabaConfigEnum.PhoneNumberId]: inputConfig?.phoneNumberId || Number(process.env.WA_PHONE_NUMBER_ID),\n [WabaConfigEnum.BusinessAcctId]: inputConfig?.businessAcctId || process.env.WA_BUSINESS_ACCOUNT_ID || '',\n [WabaConfigEnum.APIVersion]: inputConfig?.apiVersion || process.env.CLOUD_API_VERSION || '',\n [WabaConfigEnum.AccessToken]: inputConfig?.accessToken || process.env.CLOUD_API_ACCESS_TOKEN || '',\n [WabaConfigEnum.WebhookEndpoint]: inputConfig?.webhookEndpoint || process.env.WEBHOOK_ENDPOINT || '',\n [WabaConfigEnum.WebhookVerificationToken]:\n inputConfig?.webhookVerificationToken || process.env.WEBHOOK_VERIFICATION_TOKEN || '',\n [WabaConfigEnum.ListenerPort]:\n inputConfig?.listenerPort || parseInt(process.env.LISTENER_PORT || '') || DEFAULT_LISTENER_PORT,\n [WabaConfigEnum.MaxRetriesAfterWait]:\n inputConfig?.maxRetriesAfterWait ||\n parseInt(process.env.MAX_RETRIES_AFTER_WAIT || '') ||\n DEFAULT_MAX_RETRIES_AFTER_WAIT,\n [WabaConfigEnum.RequestTimeout]:\n inputConfig?.requestTimeout || parseInt(process.env.REQUEST_TIMEOUT || '') || DEFAULT_REQUEST_TIMEOUT,\n [WabaConfigEnum.Debug]: inputConfig?.debug || process.env.DEBUG === 'true',\n [WabaConfigEnum.PrivatePem]: inputConfig?.privatePem || process.env.FLOW_API_PRIVATE_PEM || '',\n [WabaConfigEnum.Passphrase]: inputConfig?.passphrase || process.env.FLOW_API_PASSPHRASE || '',\n };\n\n return wabaConfig;\n};\n","import { Agent } from 'https';\n\nimport { HttpMethodsEnum } from '../../types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from '../../types/httpsClient';\nimport Logger from '../logger';\n\nconst LIB_NAME = 'HttpsClient';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class HttpsClient implements HttpsClientClass {\n agent: Agent;\n\n constructor() {\n this.agent = new Agent({ keepAlive: true });\n }\n\n clearSockets(): boolean {\n this.agent.destroy();\n return true;\n }\n\n async sendRequest(\n hostname: string,\n path: string,\n method: HttpMethodsEnum,\n headers: HeadersInit,\n timeout: number,\n body?: BodyInit | null,\n ): Promise<HttpsClientResponseClass> {\n const url = `https://${hostname}/${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n LOGGER.log(`${method} : ${url} - ${JSON.stringify(response)}`);\n\n clearTimeout(timeoutId);\n return new HttpsClientResponse(response);\n } catch (error) {\n LOGGER.error(`${method} : ${url} - ${JSON.stringify(error)}`);\n throw error;\n }\n }\n}\n\nexport class HttpsClientResponse implements HttpsClientResponseClass {\n res: Response;\n respStatusCode: number;\n respHeaders: ResponseHeaders;\n\n constructor(resp: Response) {\n this.res = resp;\n this.respStatusCode = resp.status;\n this.respHeaders = Object.fromEntries(resp.headers.entries());\n }\n\n statusCode(): number {\n return this.respStatusCode;\n }\n\n headers(): ResponseHeaders {\n return this.respHeaders;\n }\n\n rawResponse(): Response {\n return this.res;\n }\n\n async json(): Promise<ResponseJSONBody> {\n try {\n return (await this.res.json()) as ResponseJSONBody;\n } catch (err) {\n // TODO Error Handling\n throw new Error('Failed to parse response body to JSON: ' + (err as Error).message);\n }\n }\n}\n","import type { HttpMethodsEnum } from '../../types/enums';\nimport type { RequesterClass } from '../../types/request';\nimport { isMetaError, MetaError } from '../isMetaError';\nimport Logger from '../logger';\nimport HttpsClient from './httpsClient';\n\nconst LIB_NAME = 'REQUESTER';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class Requester implements RequesterClass {\n client: Readonly<HttpsClient>;\n accessToken: Readonly<string>;\n phoneNumberId: Readonly<number>;\n businessAcctId: Readonly<string>;\n apiVersion: Readonly<string>;\n userAgent: Readonly<string>;\n host: Readonly<string>;\n protocol: Readonly<string> = 'https:';\n\n constructor(\n apiVersion: string,\n phoneNumberId: number,\n accessToken: string,\n businessAcctId: string,\n userAgent: string,\n ) {\n this.client = new HttpsClient();\n this.host = 'graph.facebook.com';\n this.apiVersion = apiVersion || '22';\n this.phoneNumberId = phoneNumberId;\n this.accessToken = accessToken;\n this.businessAcctId = businessAcctId;\n this.userAgent = userAgent;\n }\n\n buildHeader(contentType: string, additionalHeaders?: Record<string, string>): HeadersInit {\n const headers: HeadersInit = {\n Authorization: `Bearer ${this.accessToken}`,\n 'User-Agent': this.userAgent,\n };\n\n if (contentType !== 'multipart/form-data') {\n headers['Content-Type'] = contentType;\n }\n\n if (additionalHeaders) {\n Object.assign(headers, additionalHeaders);\n }\n\n return headers;\n }\n\n buildCAPIPath(endpoint: string): string {\n return `v${this.apiVersion}.0/${endpoint}`;\n }\n\n async sendRequest(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n contentType: string = 'application/json',\n additionalHeaders?: Record<string, string>,\n ) {\n let effectiveContentType = contentType;\n\n if (body instanceof FormData) {\n effectiveContentType = 'multipart/form-data';\n } else if (typeof body === 'string' && body.startsWith('<?xml')) {\n effectiveContentType = 'application/xml';\n }\n\n const path = `${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(endpoint)}`;\n\n LOGGER.log(`${method} : ${path} (${effectiveContentType})`);\n\n try {\n const response = await this.client.sendRequest(\n this.host,\n this.buildCAPIPath(endpoint),\n method,\n this.buildHeader(effectiveContentType, additionalHeaders),\n timeout,\n method === 'POST' || method === 'PUT' ? body : undefined,\n );\n\n if (!response.rawResponse().ok) {\n const errorData = await response.json();\n if (isMetaError(errorData)) {\n throw errorData;\n }\n // If the error doesn't match Meta's format, create a generic MetaError\n throw {\n name: 'MetaError',\n message: 'Unknown error occurred',\n error: {\n message: errorData.message || 'Unknown error occurred',\n type: 'UnknownError',\n code: response.statusCode(),\n fbtrace_id: '',\n },\n } as MetaError;\n }\n\n return response;\n } catch (error) {\n if (isMetaError(error)) {\n throw error;\n }\n // Handle network errors or other unexpected errors\n throw {\n name: 'MetaError',\n message: error instanceof Error ? error.message : 'Network error occurred',\n error: {\n message: error instanceof Error ? error.message : 'Network error occurred',\n type: 'NetworkError',\n code: 500,\n fbtrace_id: '',\n },\n } as MetaError;\n }\n }\n\n async getJson<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(method, endpoint, timeout, body, 'application/json', additionalHeaders);\n return (await res.json()) as T;\n }\n\n async sendFormData<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: FormData,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n formData,\n 'multipart/form-data',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n\n async sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: Record<string, string>,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const urlEncodedBody = new URLSearchParams(formData).toString();\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n urlEncodedBody,\n 'application/x-www-form-urlencoded',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n}\n","export function printLogo() {\n // 테스트 환경에서는 로고를 출력하지 않음\n if (\n process.env.NODE_ENV === 'test' ||\n process.env.VITEST === 'true' ||\n (typeof global !== 'undefined' && (global as any).__VITEST__)\n ) {\n return;\n }\n\n console.log(\n '\\x1b[36m%s\\x1b[0m',\n `\n██████╗ ██╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ██████╗ ██╗\n██╔════╝ ██║ ██╔═══██╗ ██║ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║\n██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ███████║ ██████╔╝ ██║\n██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██╔══██║ ██╔═══╝ ██║\n╚██████╗ ███████╗ ╚██████╔╝ ╚██████╔╝ ██████╔╝ ██║ ██║ ██║ ██║\n ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝\n`,\n );\n}\n","import { importConfig } from '../../config/importConfig';\nimport { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport * as SDKEnums from '../../types/enums';\nimport { formatConfigTable } from '../../utils/configTable';\nimport Requester from '../../utils/http/request';\nimport Logger from '../../utils/logger';\nimport { getUserAgent, getVersion } from '../../utils/version';\n\nimport {\n BusinessProfileApi,\n EncryptionApi,\n FlowApi,\n MediaApi,\n MessagesApi,\n PhoneNumberApi,\n QrCodeApi,\n RegistrationApi,\n TemplateApi,\n TwoStepVerificationApi,\n WabaApi,\n} from '../../api';\nimport { printLogo } from '../../utils/logoConsole';\n\nconst LIB_NAME = 'WHATSAPP';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * WhatsApp SDK Main Class following official patterns\n * Provides unified access to WhatsApp Cloud API and Flows API\n */\nexport default class WhatsApp {\n config: WabaConfigType;\n requester: Readonly<Requester>;\n messages: MessagesApi;\n media: MediaApi;\n phoneNumbers: PhoneNumberApi;\n twoStepVerification: TwoStepVerificationApi;\n flows: FlowApi;\n businessProfile: BusinessProfileApi;\n templates: TemplateApi;\n encryption: EncryptionApi;\n qrCode: QrCodeApi;\n registration: RegistrationApi;\n waba: WabaApi;\n\n constructor(config?: WhatsAppConfig) {\n printLogo();\n this.config = importConfig(config);\n\n this.requester = new Requester(\n this.config[SDKEnums.WabaConfigEnum.APIVersion],\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId],\n this.config[SDKEnums.WabaConfigEnum.AccessToken],\n this.config[SDKEnums.WabaConfigEnum.BusinessAcctId],\n this.getUserAgent(),\n );\n\n this.messages = new MessagesApi(this.config, this.requester);\n this.media = new MediaApi(this.config, this.requester);\n this.phoneNumbers = new PhoneNumberApi(this.config, this.requester);\n this.twoStepVerification = new TwoStepVerificationApi(this.config, this.requester);\n this.flows = new FlowApi(this.config, this.requester);\n this.businessProfile = new BusinessProfileApi(this.config, this.requester);\n this.templates = new TemplateApi(this.config, this.requester);\n this.encryption = new EncryptionApi(this.config, this.requester);\n this.qrCode = new QrCodeApi(this.config, this.requester);\n this.registration = new RegistrationApi(this.config, this.requester);\n this.waba = new WabaApi(this.config, this.requester);\n\n LOGGER.log('\\n' + formatConfigTable(this.config));\n }\n\n /**\n * Runtime configuration updates following official patterns\n */\n updateTimeout(timeout: number): void {\n this.config[SDKEnums.WabaConfigEnum.RequestTimeout] = timeout;\n if ('updateTimeout' in this.requester) {\n (this.requester as any).updateTimeout(timeout);\n }\n LOGGER.log(`Timeout updated to ${timeout}ms`);\n }\n\n updateSenderNumberId(phoneNumberId: number): void {\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId] = phoneNumberId;\n LOGGER.log(`Sender number ID updated to ${phoneNumberId}`);\n }\n\n updateAccessToken(accessToken: string): void {\n this.config[SDKEnums.WabaConfigEnum.AccessToken] = accessToken;\n if ('updateAccessToken' in this.requester) {\n (this.requester as any).updateAccessToken(accessToken);\n }\n LOGGER.log('Access token updated');\n }\n\n /**\n * Get SDK version\n */\n version(): string {\n return getVersion();\n }\n\n /**\n * Static enums access\n */\n static get Enums() {\n return SDKEnums;\n }\n\n /**\n * Get User-Agent string\n */\n getUserAgent(): string {\n return getUserAgent();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/config/importConfig.ts","../src/utils/http/httpsClient.ts","../src/utils/http/request.ts","../src/utils/logoConsole.ts","../src/core/whatsapp/WhatsApp.ts"],"names":["LIB_NAME","LOG_LOCAL","LOGGER","Logger","DEFAULT_LISTENER_PORT","DEFAULT_MAX_RETRIES_AFTER_WAIT","DEFAULT_REQUEST_TIMEOUT","emptyConfigChecker","config","importConfig","inputConfig","HttpsClient","Agent","hostname","path","method","headers","timeout","body","url","controller","timeoutId","response","HttpsClientResponse","error","resp","err","Requester","apiVersion","phoneNumberId","accessToken","businessAcctId","userAgent","contentType","additionalHeaders","endpoint","effectiveContentType","errorData","isMetaError","formData","urlEncodedBody","printLogo","WhatsApp","messages_default","media_default","phone_default","twoStepVerification_default","flow_default","profile_default","TemplateApi","encryption_default","qrCode_default","registration_default","waba_default","formatConfigTable","getVersion","enums_exports","getUserAgent"],"mappings":"0kBAIA,IAAMA,EAAW,OAAA,CACXC,CAAAA,CAAY,MACZC,CAAAA,CAAS,IAAIC,EAAOH,CAAAA,CAAU,OAAA,CAAQ,GAAA,CAAI,KAAA,GAAU,QAAUC,CAAS,CAAA,CACvEG,EAAwB,GAAA,CACxBC,CAAAA,CAAiC,GACjCC,CAAAA,CAA0B,GAAA,CAE1BC,CAAAA,CAAsBC,CAAAA,EAAuC,CAC/D,GAAI,CAAC,QAAQ,GAAA,CAAI,sBAAA,EAA+B,CAACA,CAAAA,EAAQ,WAAA,CACrD,MAAAN,CAAAA,CAAO,IAAI,2FAA2F,CAAA,CAChG,IAAI,KAAA,CAAM,gCAAgC,CAExD,CAAA,CAEaO,CAAAA,CAAgBC,CAAAA,GACzBH,CAAAA,CAAmBG,CAAW,CAAA,CAEK,CAC9B,WAAuBA,CAAAA,EAAa,KAAA,EAAS,QAAQ,GAAA,CAAI,UAAA,EAAc,EAAA,CACvE,cAAA,CAA2BA,GAAa,SAAA,EAAa,OAAA,CAAQ,IAAI,cAAA,EAAkB,EAAA,CACnF,mBAA+BA,CAAAA,EAAa,aAAA,EAAiB,MAAA,CAAO,OAAA,CAAQ,IAAI,kBAAkB,CAAA,CAClG,uBAAgCA,CAAAA,EAAa,cAAA,EAAkB,QAA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J","file":"chunk-BAOZ4U74.js","sourcesContent":["import type { WabaConfigType, WhatsAppConfig } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\nimport Logger from '../utils/logger';\n\nconst LIB_NAME = 'UTILS';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\nconst DEFAULT_LISTENER_PORT = 3000;\nconst DEFAULT_MAX_RETRIES_AFTER_WAIT = 30;\nconst DEFAULT_REQUEST_TIMEOUT = 20000;\n\nconst emptyConfigChecker = (config: WhatsAppConfig | undefined) => {\n if (!process.env[WabaConfigEnum.AccessToken] && !config?.accessToken) {\n LOGGER.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`);\n throw new Error('Missing WhatsApp access token.');\n }\n};\n\nexport const importConfig = (inputConfig?: WhatsAppConfig) => {\n emptyConfigChecker(inputConfig);\n\n const wabaConfig: WabaConfigType = {\n [WabaConfigEnum.AppId]: inputConfig?.appId || process.env.M4D_APP_ID || '',\n [WabaConfigEnum.AppSecret]: inputConfig?.appSecret || process.env.M4D_APP_SECRET || '',\n [WabaConfigEnum.PhoneNumberId]: inputConfig?.phoneNumberId || Number(process.env.WA_PHONE_NUMBER_ID),\n [WabaConfigEnum.BusinessAcctId]: inputConfig?.businessAcctId || process.env.WA_BUSINESS_ACCOUNT_ID || '',\n [WabaConfigEnum.APIVersion]: inputConfig?.apiVersion || process.env.CLOUD_API_VERSION || '',\n [WabaConfigEnum.AccessToken]: inputConfig?.accessToken || process.env.CLOUD_API_ACCESS_TOKEN || '',\n [WabaConfigEnum.WebhookEndpoint]: inputConfig?.webhookEndpoint || process.env.WEBHOOK_ENDPOINT || '',\n [WabaConfigEnum.WebhookVerificationToken]:\n inputConfig?.webhookVerificationToken || process.env.WEBHOOK_VERIFICATION_TOKEN || '',\n [WabaConfigEnum.ListenerPort]:\n inputConfig?.listenerPort || parseInt(process.env.LISTENER_PORT || '') || DEFAULT_LISTENER_PORT,\n [WabaConfigEnum.MaxRetriesAfterWait]:\n inputConfig?.maxRetriesAfterWait ||\n parseInt(process.env.MAX_RETRIES_AFTER_WAIT || '') ||\n DEFAULT_MAX_RETRIES_AFTER_WAIT,\n [WabaConfigEnum.RequestTimeout]:\n inputConfig?.requestTimeout || parseInt(process.env.REQUEST_TIMEOUT || '') || DEFAULT_REQUEST_TIMEOUT,\n [WabaConfigEnum.Debug]: inputConfig?.debug || process.env.DEBUG === 'true',\n [WabaConfigEnum.PrivatePem]: inputConfig?.privatePem || process.env.FLOW_API_PRIVATE_PEM || '',\n [WabaConfigEnum.Passphrase]: inputConfig?.passphrase || process.env.FLOW_API_PASSPHRASE || '',\n };\n\n return wabaConfig;\n};\n","import { Agent } from 'https';\n\nimport { HttpMethodsEnum } from '../../types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from '../../types/httpsClient';\nimport Logger from '../logger';\n\nconst LIB_NAME = 'HttpsClient';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class HttpsClient implements HttpsClientClass {\n agent: Agent;\n\n constructor() {\n this.agent = new Agent({ keepAlive: true });\n }\n\n clearSockets(): boolean {\n this.agent.destroy();\n return true;\n }\n\n async sendRequest(\n hostname: string,\n path: string,\n method: HttpMethodsEnum,\n headers: HeadersInit,\n timeout: number,\n body?: BodyInit | null,\n ): Promise<HttpsClientResponseClass> {\n const url = `https://${hostname}/${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n LOGGER.log(`${method} : ${url} - ${JSON.stringify(response)}`);\n\n clearTimeout(timeoutId);\n return new HttpsClientResponse(response);\n } catch (error) {\n LOGGER.error(`${method} : ${url} - ${JSON.stringify(error)}`);\n throw error;\n }\n }\n}\n\nexport class HttpsClientResponse implements HttpsClientResponseClass {\n res: Response;\n respStatusCode: number;\n respHeaders: ResponseHeaders;\n\n constructor(resp: Response) {\n this.res = resp;\n this.respStatusCode = resp.status;\n this.respHeaders = Object.fromEntries(resp.headers.entries());\n }\n\n statusCode(): number {\n return this.respStatusCode;\n }\n\n headers(): ResponseHeaders {\n return this.respHeaders;\n }\n\n rawResponse(): Response {\n return this.res;\n }\n\n async json(): Promise<ResponseJSONBody> {\n try {\n return (await this.res.json()) as ResponseJSONBody;\n } catch (err) {\n // TODO Error Handling\n throw new Error('Failed to parse response body to JSON: ' + (err as Error).message);\n }\n }\n}\n","import type { HttpMethodsEnum } from '../../types/enums';\nimport type { RequesterClass } from '../../types/request';\nimport { isMetaError, MetaError } from '../isMetaError';\nimport Logger from '../logger';\nimport HttpsClient from './httpsClient';\n\nconst LIB_NAME = 'REQUESTER';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class Requester implements RequesterClass {\n client: Readonly<HttpsClient>;\n accessToken: Readonly<string>;\n phoneNumberId: Readonly<number>;\n businessAcctId: Readonly<string>;\n apiVersion: Readonly<string>;\n userAgent: Readonly<string>;\n host: Readonly<string>;\n protocol: Readonly<string> = 'https:';\n\n constructor(\n apiVersion: string,\n phoneNumberId: number,\n accessToken: string,\n businessAcctId: string,\n userAgent: string,\n ) {\n this.client = new HttpsClient();\n this.host = 'graph.facebook.com';\n this.apiVersion = apiVersion || '22';\n this.phoneNumberId = phoneNumberId;\n this.accessToken = accessToken;\n this.businessAcctId = businessAcctId;\n this.userAgent = userAgent;\n }\n\n buildHeader(contentType: string, additionalHeaders?: Record<string, string>): HeadersInit {\n const headers: HeadersInit = {\n Authorization: `Bearer ${this.accessToken}`,\n 'User-Agent': this.userAgent,\n };\n\n if (contentType !== 'multipart/form-data') {\n headers['Content-Type'] = contentType;\n }\n\n if (additionalHeaders) {\n Object.assign(headers, additionalHeaders);\n }\n\n return headers;\n }\n\n buildCAPIPath(endpoint: string): string {\n return `v${this.apiVersion}.0/${endpoint}`;\n }\n\n async sendRequest(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n contentType: string = 'application/json',\n additionalHeaders?: Record<string, string>,\n ) {\n let effectiveContentType = contentType;\n\n if (body instanceof FormData) {\n effectiveContentType = 'multipart/form-data';\n } else if (typeof body === 'string' && body.startsWith('<?xml')) {\n effectiveContentType = 'application/xml';\n }\n\n const path = `${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(endpoint)}`;\n\n LOGGER.log(`${method} : ${path} (${effectiveContentType})`);\n\n try {\n const response = await this.client.sendRequest(\n this.host,\n this.buildCAPIPath(endpoint),\n method,\n this.buildHeader(effectiveContentType, additionalHeaders),\n timeout,\n method === 'POST' || method === 'PUT' ? body : undefined,\n );\n\n if (!response.rawResponse().ok) {\n const errorData = await response.json();\n if (isMetaError(errorData)) {\n throw errorData;\n }\n // If the error doesn't match Meta's format, create a generic MetaError\n throw {\n name: 'MetaError',\n message: 'Unknown error occurred',\n error: {\n message: errorData.message || 'Unknown error occurred',\n type: 'UnknownError',\n code: response.statusCode(),\n fbtrace_id: '',\n },\n } as MetaError;\n }\n\n return response;\n } catch (error) {\n if (isMetaError(error)) {\n throw error;\n }\n // Handle network errors or other unexpected errors\n throw {\n name: 'MetaError',\n message: error instanceof Error ? error.message : 'Network error occurred',\n error: {\n message: error instanceof Error ? error.message : 'Network error occurred',\n type: 'NetworkError',\n code: 500,\n fbtrace_id: '',\n },\n } as MetaError;\n }\n }\n\n async getJson<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(method, endpoint, timeout, body, 'application/json', additionalHeaders);\n return (await res.json()) as T;\n }\n\n async sendFormData<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: FormData,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n formData,\n 'multipart/form-data',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n\n async sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: Record<string, string>,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const urlEncodedBody = new URLSearchParams(formData).toString();\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n urlEncodedBody,\n 'application/x-www-form-urlencoded',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n}\n","export function printLogo() {\n // 테스트 환경에서는 로고를 출력하지 않음\n if (\n process.env.NODE_ENV === 'test' ||\n process.env.VITEST === 'true' ||\n (typeof global !== 'undefined' && (global as any).__VITEST__)\n ) {\n return;\n }\n\n console.log(\n '\\x1b[36m%s\\x1b[0m',\n `\n██████╗ ██╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ██████╗ ██╗\n██╔════╝ ██║ ██╔═══██╗ ██║ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║\n██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ███████║ ██████╔╝ ██║\n██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██╔══██║ ██╔═══╝ ██║\n╚██████╗ ███████╗ ╚██████╔╝ ╚██████╔╝ ██████╔╝ ██║ ██║ ██║ ██║\n ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝\n`,\n );\n}\n","import { importConfig } from '../../config/importConfig';\nimport { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport * as SDKEnums from '../../types/enums';\nimport { formatConfigTable } from '../../utils/configTable';\nimport Requester from '../../utils/http/request';\nimport Logger from '../../utils/logger';\nimport { getUserAgent, getVersion } from '../../utils/version';\n\nimport {\n BusinessProfileApi,\n EncryptionApi,\n FlowApi,\n MediaApi,\n MessagesApi,\n PhoneNumberApi,\n QrCodeApi,\n RegistrationApi,\n TemplateApi,\n TwoStepVerificationApi,\n WabaApi,\n} from '../../api';\nimport { printLogo } from '../../utils/logoConsole';\n\nconst LIB_NAME = 'WHATSAPP';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * WhatsApp SDK Main Class following official patterns\n * Provides unified access to WhatsApp Cloud API and Flows API\n */\nexport default class WhatsApp {\n config: WabaConfigType;\n requester: Readonly<Requester>;\n messages: MessagesApi;\n media: MediaApi;\n phoneNumbers: PhoneNumberApi;\n twoStepVerification: TwoStepVerificationApi;\n flows: FlowApi;\n businessProfile: BusinessProfileApi;\n templates: TemplateApi;\n encryption: EncryptionApi;\n qrCode: QrCodeApi;\n registration: RegistrationApi;\n waba: WabaApi;\n\n constructor(config?: WhatsAppConfig) {\n printLogo();\n this.config = importConfig(config);\n\n this.requester = new Requester(\n this.config[SDKEnums.WabaConfigEnum.APIVersion],\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId],\n this.config[SDKEnums.WabaConfigEnum.AccessToken],\n this.config[SDKEnums.WabaConfigEnum.BusinessAcctId],\n this.getUserAgent(),\n );\n\n this.messages = new MessagesApi(this.config, this.requester);\n this.media = new MediaApi(this.config, this.requester);\n this.phoneNumbers = new PhoneNumberApi(this.config, this.requester);\n this.twoStepVerification = new TwoStepVerificationApi(this.config, this.requester);\n this.flows = new FlowApi(this.config, this.requester);\n this.businessProfile = new BusinessProfileApi(this.config, this.requester);\n this.templates = new TemplateApi(this.config, this.requester);\n this.encryption = new EncryptionApi(this.config, this.requester);\n this.qrCode = new QrCodeApi(this.config, this.requester);\n this.registration = new RegistrationApi(this.config, this.requester);\n this.waba = new WabaApi(this.config, this.requester);\n\n LOGGER.log('\\n' + formatConfigTable(this.config));\n }\n\n /**\n * Runtime configuration updates following official patterns\n */\n updateTimeout(timeout: number): void {\n this.config[SDKEnums.WabaConfigEnum.RequestTimeout] = timeout;\n if ('updateTimeout' in this.requester) {\n (this.requester as any).updateTimeout(timeout);\n }\n LOGGER.log(`Timeout updated to ${timeout}ms`);\n }\n\n updateSenderNumberId(phoneNumberId: number): void {\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId] = phoneNumberId;\n LOGGER.log(`Sender number ID updated to ${phoneNumberId}`);\n }\n\n updateAccessToken(accessToken: string): void {\n this.config[SDKEnums.WabaConfigEnum.AccessToken] = accessToken;\n if ('updateAccessToken' in this.requester) {\n (this.requester as any).updateAccessToken(accessToken);\n }\n LOGGER.log('Access token updated');\n }\n\n /**\n * Get SDK version\n */\n version(): string {\n return getVersion();\n }\n\n /**\n * Static enums access\n */\n static get Enums() {\n return SDKEnums;\n }\n\n /**\n * Get User-Agent string\n */\n getUserAgent(): string {\n return getUserAgent();\n }\n}\n"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {c,b,a as a$1}from'./chunk-WGGN32O2.js';import {a as a$2,b as b$1}from'./chunk-
|
|
2
|
-
`),d=e.FLOW_API_PASSPHRASE,i=y.createPrivateKey({key:p,passphrase:d}),g;try{s.info("Decrypting AES key"),g=y.privateDecrypt({key:i,padding:y.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(r,"base64"));}catch(F){throw s.error("Failed to decrypt AES key:",F),new Error("Failed to decrypt the request. Please verify your private key.")}let u=Buffer.from(t,"base64"),l=Buffer.from(o,"base64"),f=u.subarray(0,-16),c=u.subarray(-16);s.info("Decrypting flow data");let b=y.createDecipheriv("aes-128-gcm",g,l);b.setAuthTag(c);let v=Buffer.concat([b.update(f),b.final()]).toString("utf-8");return s.info("Flow request decryption complete"),{decryptedBody:JSON.parse(v),aesKeyBuffer:g,initialVectorBuffer:l}}function A(a,e,r){s.info("Encrypting flow response");let t=[];for(let o of Array.from(r.entries()))t.push(~o[1]);try{let o=y.createCipheriv("aes-128-gcm",e,Buffer.from(t)),p=Buffer.concat([o.update(JSON.stringify(a||{}),"utf-8"),o.final(),o.getAuthTag()]).toString("base64");return s.info("Flow response encryption complete"),p}catch(o){throw s.error("Response encryption error:",o),new Error("Failed to encrypt response. Internal server error.")}}var m=new a("WEBHOOK_PROCESSOR",process.env.DEBUG==="true"),W=class{config;client;messageHandlers=new Map;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(e){this.config=a$2(e),this.client=new b$1(e),m.log("WebhookProcessor instantiated");}async processVerification(e,r,t){return e==="subscribe"&&r===this.config.WEBHOOK_VERIFICATION_TOKEN?{status:200,body:t||"",headers:{"Content-Type":"text/plain"}}:{status:403,body:JSON.stringify({error:"Forbidden"}),headers:{"Content-Type":"application/json"}}}async processWebhook(e){try{let r=await M(e,this.client,{messageHandlers:this.messageHandlers,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler}),t=await r.text(),o=r.headers.get("content-type")||"application/json";return {status:r.status,body:t,headers:{"Content-Type":o}}}catch(r){return m.log(`Error processing webhook: ${r}`),{status:500,body:JSON.stringify({error:"Internal Server Error"}),headers:{"Content-Type":"application/json"}}}}async processFlow(e){try{let r=await S(e,this.config,this.client,this.flowHandlers),t=await r.text(),o=r.headers.get("content-type")||"application/json";return {status:r.status,body:t,headers:{"Content-Type":o}}}catch(r){return m.log(`Error processing flow: ${r}`),{status:500,body:JSON.stringify({error:"Internal Server Error"}),headers:{"Content-Type":"application/json"}}}}onMessage(e,r){this.messageHandlers.set(e,r),m.log(`Registered message handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,m.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,m.log("Registered post-process handler");}onFlow(e,r){this.flowHandlers.set(e,r),m.log(`Registered flow handler for ${e}`);}getClient(){return this.client}getConfig(){return this.config}};export{M as a,S as b,C as c,W as d};//# sourceMappingURL=chunk-
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {c,b,a as a$1}from'./chunk-WGGN32O2.js';import {a as a$2,b as b$1}from'./chunk-BAOZ4U74.js';import {a}from'./chunk-FKXSL2JK.js';import y from'crypto';var O="WEBHOOK_UTILS",s=new a(O,process.env.DEBUG==="true");async function M(a,e,r){try{s.info("Processing webhook messages request");let t=await a.json();if(s.info("Webhook request body:",t),t.object!=="whatsapp_business_account"){let p="Received webhook for non-WhatsApp event";return s.warn(p,{body:t}),new Response(JSON.stringify({error:p}),{status:404})}let o=[];for(let p of t.entry)try{s.info("Processing webhook entry:",{entryId:p.id});let d=p.changes;for(let i of d)i.field==="messages"&&(s.info("Processing messages change:",{change:i}),await T(p.id,i.value,e,r));}catch(d){let i=`Error processing webhook: ${d}`;s.error(i,{entry:p,error:d}),o.push(i);}return s.info("Webhook processing complete",{errorCount:o.length}),new Response(o.length>0?JSON.stringify({errors:o}):null,{status:200})}catch(t){return s.error("Error processing webhook:",t),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500})}}async function S(a,e,r,t){try{s.info("Processing flow request");let o=await a.text(),p=a.headers.get("x-hub-signature-256");if(s.info("Flow request signature:",{signature:p}),!_(o,p,e.WEBHOOK_VERIFICATION_TOKEN||""))return s.warn("Invalid request signature",{signature:p}),new Response(JSON.stringify({error:"Unauthorized"}),{status:401});let d=JSON.parse(o);s.info("Flow request data:",d);let{decryptedBody:i}=q(d,e);s.info("Decrypted flow request:",i);let g=t.get("*");if(!g)return s.warn("No handler registered for flow action:",{action:i.action}),new Response(JSON.stringify({error:"Handler not found"}),{status:404});if(c(i))return s.info("Handling flow ping request"),new Response(JSON.stringify({version:"3.0",data:{status:"active"}}),{status:200});if(b(i))return s.warn("Flow error request received:",i),new Response(null,{status:200});if(a$1(i)){s.info("Processing flow data exchange request");let u=await g(r,i);s.info("Flow handler result:",u);let l=A(u,Buffer.from(d.aes_key,"base64"),Buffer.from(d.initial_vector,"base64"));return s.info("Encrypted flow response generated"),new Response(JSON.stringify(l),{status:200})}return s.warn("Unknown flow request type:",i),new Response(JSON.stringify({error:"Unknown request type"}),{status:400})}catch(o){return s.error("Error handling flow request:",o),new Response(JSON.stringify({error:"Internal server error"}),{status:500})}}function _(a,e,r){if(!e)return s.warn("Missing signature in request"),false;s.info("Signature verification details:",{bodyLength:a.length,verificationTokenLength:r.length,rawSignature:e,cleanedSignature:e.replace("sha256=","")});let t=y.createHmac("sha256",r).update(a).digest("hex");return s.info("Signature verification:",{received:e.replace("sha256=",""),expected:t}),y.timingSafeEqual(Buffer.from(e.replace("sha256=","")),Buffer.from(t))}function C(a,e){let r=a["x-forwarded-proto"]||"http",t=a.host||"localhost";return `${r}://${t}${e||"/"}`}async function T(a,e,r,t){s.info("Processing messages:",{waba_id:a,value:e});let o=e.metadata,p=e.contacts,d=a,i=o?.display_phone_number||"",g=o?.phone_number_id||"",u=p?.[0]?.profile?.name||"";if(e.statuses&&e.statuses.length>0){s.info("Processing statuses:",{statusCount:e.statuses.length});let l=e.statuses;for(let n of l){let f={wabaId:d,id:n.id,from:n.recipient_id,timestamp:n.timestamp,type:"statuses",phoneNumberId:g,displayPhoneNumber:i,profileName:u,statuses:e.statuses[0],originalData:n};s.info("Processing status:",f),await w(t.messageHandlers.get("statuses"),r,f,"statuses");}return}if(e.messages&&e.messages.length>0){s.info("Processing messages:",{messageCount:e.messages.length});let l=e.messages;for(let n of l){let f=n.type;s.info("Processing message:",{messageType:f,messageId:n.id});let c={wabaId:d,id:n.id,from:n.from,timestamp:n.timestamp,type:n.type,phoneNumberId:g,displayPhoneNumber:i,profileName:u,originalData:n};switch(f){case "text":c.text=n.text;break;case "image":c.image=n.image;break;case "video":c.video=n.video;break;case "audio":c.audio=n.audio;break;case "document":c.document=n.document;break;case "sticker":c.sticker=n.sticker;break;case "location":c.location=n.location;break;case "contacts":c.contacts=n.contacts;break;case "interactive":c.interactive=n.interactive;break;case "button":c.button=n.button;break;case "order":c.order=n.order;break;case "system":c.system=n.system;break;case "reaction":c.reaction=n.reaction;break;default:s.warn("Unknown message type:",{messageType:f});break}s.info("Executing message handlers"),await w(t.preProcessHandler,r,c,"pre-process"),await w(t.messageHandlers.get(f),r,c,f),await w(t.postProcessHandler,r,c,"post-process");}}}async function w(a,e,r,t){if(a)try{s.info("Executing handler:",{handlerType:t,messageId:r.id}),await a(e,r),s.info("Handler execution complete:",{handlerType:t,messageId:r.id});}catch(o){s.error(`Error in ${t} handler:`,{error:o,messageId:r.id});}else s.info("No handler registered:",{handlerType:t});}function q(a,e){s.info("Decrypting flow request");let{encrypted_aes_key:r,encrypted_flow_data:t,initial_vector:o}=a;if(!r||!t||!o)throw s.error("Missing required encryption properties"),new Error("Missing required encryption properties");let p=e.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
|
|
2
|
+
`),d=e.FLOW_API_PASSPHRASE,i=y.createPrivateKey({key:p,passphrase:d}),g;try{s.info("Decrypting AES key"),g=y.privateDecrypt({key:i,padding:y.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(r,"base64"));}catch(F){throw s.error("Failed to decrypt AES key:",F),new Error("Failed to decrypt the request. Please verify your private key.")}let u=Buffer.from(t,"base64"),l=Buffer.from(o,"base64"),f=u.subarray(0,-16),c=u.subarray(-16);s.info("Decrypting flow data");let b=y.createDecipheriv("aes-128-gcm",g,l);b.setAuthTag(c);let v=Buffer.concat([b.update(f),b.final()]).toString("utf-8");return s.info("Flow request decryption complete"),{decryptedBody:JSON.parse(v),aesKeyBuffer:g,initialVectorBuffer:l}}function A(a,e,r){s.info("Encrypting flow response");let t=[];for(let o of Array.from(r.entries()))t.push(~o[1]);try{let o=y.createCipheriv("aes-128-gcm",e,Buffer.from(t)),p=Buffer.concat([o.update(JSON.stringify(a||{}),"utf-8"),o.final(),o.getAuthTag()]).toString("base64");return s.info("Flow response encryption complete"),p}catch(o){throw s.error("Response encryption error:",o),new Error("Failed to encrypt response. Internal server error.")}}var m=new a("WEBHOOK_PROCESSOR",process.env.DEBUG==="true"),W=class{config;client;messageHandlers=new Map;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(e){this.config=a$2(e),this.client=new b$1(e),m.log("WebhookProcessor instantiated");}async processVerification(e,r,t){return e==="subscribe"&&r===this.config.WEBHOOK_VERIFICATION_TOKEN?{status:200,body:t||"",headers:{"Content-Type":"text/plain"}}:{status:403,body:JSON.stringify({error:"Forbidden"}),headers:{"Content-Type":"application/json"}}}async processWebhook(e){try{let r=await M(e,this.client,{messageHandlers:this.messageHandlers,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler}),t=await r.text(),o=r.headers.get("content-type")||"application/json";return {status:r.status,body:t,headers:{"Content-Type":o}}}catch(r){return m.log(`Error processing webhook: ${r}`),{status:500,body:JSON.stringify({error:"Internal Server Error"}),headers:{"Content-Type":"application/json"}}}}async processFlow(e){try{let r=await S(e,this.config,this.client,this.flowHandlers),t=await r.text(),o=r.headers.get("content-type")||"application/json";return {status:r.status,body:t,headers:{"Content-Type":o}}}catch(r){return m.log(`Error processing flow: ${r}`),{status:500,body:JSON.stringify({error:"Internal Server Error"}),headers:{"Content-Type":"application/json"}}}}onMessage(e,r){this.messageHandlers.set(e,r),m.log(`Registered message handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,m.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,m.log("Registered post-process handler");}onFlow(e,r){this.flowHandlers.set(e,r),m.log(`Registered flow handler for ${e}`);}getClient(){return this.client}getConfig(){return this.config}};export{M as a,S as b,C as c,W as d};//# sourceMappingURL=chunk-JPGXONBQ.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-JPGXONBQ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookProcessor.ts"],"names":["LIB_NAME","LOGGER","Logger","processWebhookMessages","request","whatsapp","handlers","body","errorMsg","errors","entry","changes","change","processMessages","error","processFlowRequest","config","flowHandlers","signature","verifySignature","data","decryptedBody","decryptFlowRequest","handler","isFlowPingRequest","isFlowErrorRequest","isFlowDataExchangeRequest","result","encryptedResponse","encryptFlowResponse","verificationToken","expectedSignature","crypto","constructFullUrl","headers","url","protocol","host","waba_id","value","metadata","contacts","wabaId","displayPhoneNumber","phoneNumberId","profileName","statuses","status","processedStatus","executeHandler","messages","message","messageType","processedMessage","handlerType","encrypted_aes_key","encrypted_flow_data","initial_vector","privatePem","passphrase","privateKey","decryptedAesKey","flowDataBuffer","initialVectorBuffer","encrypted_flow_data_body","encrypted_flow_data_tag","decipher","decryptedJSONString","response","aesKeyBuffer","flipped_iv","pair","cipher","WebhookProcessor","importConfig","WhatsApp","mode","token","challenge","webResponse","contentType","type"],"mappings":"6JAUA,IAAMA,CAAAA,CAAW,eAAA,CACXC,CAAAA,CAAS,IAAIC,CAAAA,CAAOF,CAAAA,CAAU,OAAA,CAAQ,GAAA,CAAI,KAAA,GAAU,MAAM,EAQhE,eAAsBG,CAAAA,CAClBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAKiB,CACjB,GAAI,CACAL,CAAAA,CAAO,IAAA,CAAK,qCAAqC,CAAA,CACjD,IAAMM,CAAAA,CAAO,MAAMH,CAAAA,CAAQ,IAAA,EAAK,CAIhC,GAHAH,CAAAA,CAAO,IAAA,CAAK,uBAAA,CAAyBM,CAAI,CAAA,CAGrCA,CAAAA,CAAK,MAAA,GAAW,2BAAA,CAA6B,CAC7C,IAAMC,CAAAA,CAAW,yCAAA,CACjB,OAAAP,CAAAA,CAAO,IAAA,CAAKO,CAAAA,CAAU,CAAE,IAAA,CAAAD,CAAK,CAAC,CAAA,CACvB,IAAI,QAAA,CAAS,IAAA,CAAK,SAAA,CAAU,CAAE,MAAOC,CAAS,CAAC,CAAA,CAAG,CAAE,MAAA,CAAQ,GAAI,CAAC,CAC5E,CAEA,IAAMC,CAAAA,CAAmB,EAAC,CAG1B,IAAA,IAAWC,KAASH,CAAAA,CAAK,KAAA,CACrB,GAAI,CACAN,CAAAA,CAAO,IAAA,CAAK,2BAAA,CAA6B,CAAE,OAAA,CAASS,CAAAA,CAAM,EAAG,CAAC,CAAA,CAC9D,IAAMC,EAAUD,CAAAA,CAAM,OAAA,CACtB,IAAA,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AA,CAAI,gCAAgC,EAC/C,CAEA,oBAAA,CAAqBsB,CAAAA,CAA+B,CAChD,IAAA,CAAK,mBAAqBA,CAAAA,CAC1BtB,CAAAA,CAAO,GAAA,CAAI,iCAAiC,EAChD,CAEA,MAAA,CAAOgF,CAAAA,CAAoB1D,CAAAA,CAA4B,CACnD,IAAA,CAAK,YAAA,CAAa,GAAA,CAAI0D,CAAAA,CAAM1D,CAAO,CAAA,CACnCtB,EAAO,GAAA,CAAI,CAAA,4BAAA,EAA+BgF,CAAI,CAAA,CAAE,EACpD,CAEA,SAAA,EAAsB,CAClB,OAAO,IAAA,CAAK,MAChB,CAEA,SAAA,EAA4B,CACxB,OAAO,IAAA,CAAK,MAChB,CACJ","file":"chunk-HJGN3PO4.js","sourcesContent":["import crypto from 'crypto';\nimport { FlowEndpointRequest } from '../../../api/flow';\nimport { FlowTypeEnum } from '../../../api/flow/types';\nimport { WabaConfigType } from '../../../types/config';\nimport { MessageTypesEnum } from '../../../types/enums';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '../../../utils/flowTypeGuards';\nimport Logger from '../../../utils/logger';\nimport { WhatsApp } from '../../whatsapp';\nimport { WebhookMessage, WebhookMessageValue } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\nexport type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n/**\n * Process webhook messages\n */\nexport async function processWebhookMessages(\n request: Request,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<Response> {\n try {\n LOGGER.info('Processing webhook messages request');\n const body = await request.json();\n LOGGER.info('Webhook request body:', body);\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n const errorMsg = 'Received webhook for non-WhatsApp event';\n LOGGER.warn(errorMsg, { body });\n return new Response(JSON.stringify({ error: errorMsg }), { status: 404 });\n }\n\n const errors: string[] = [];\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n LOGGER.info('Processing webhook entry:', { entryId: entry.id });\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === 'messages') {\n LOGGER.info('Processing messages change:', { change });\n await processMessages(entry.id, change.value, whatsapp, handlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.error(errorMsg, { entry, error });\n errors.push(errorMsg);\n }\n }\n\n LOGGER.info('Webhook processing complete', { errorCount: errors.length });\n return new Response(errors.length > 0 ? JSON.stringify({ errors }) : null, { status: 200 });\n } catch (error) {\n LOGGER.error('Error processing webhook:', error);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });\n }\n}\n\n/**\n * Handle flow requests\n */\nexport async function processFlowRequest(\n request: Request,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<Response> {\n try {\n LOGGER.info('Processing flow request');\n const body = await request.text();\n const signature = request.headers.get('x-hub-signature-256');\n LOGGER.info('Flow request signature:', { signature });\n\n // Validate request signature\n if (!verifySignature(body, signature, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.warn('Invalid request signature', { signature });\n return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });\n }\n\n const data = JSON.parse(body);\n LOGGER.info('Flow request data:', data);\n\n // Decrypt the request\n const { decryptedBody } = decryptFlowRequest(data, config);\n LOGGER.info('Decrypted flow request:', decryptedBody);\n\n // Get the flow handler\n const handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.warn('No handler registered for flow action:', { action: decryptedBody.action });\n return new Response(JSON.stringify({ error: 'Handler not found' }), { status: 404 });\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n LOGGER.info('Handling flow ping request');\n return new Response(\n JSON.stringify({\n version: '3.0',\n data: { status: 'active' },\n }),\n { status: 200 },\n );\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.warn('Flow error request received:', decryptedBody);\n return new Response(null, { status: 200 });\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n LOGGER.info('Processing flow data exchange request');\n const result = await handler(whatsapp, decryptedBody);\n LOGGER.info('Flow handler result:', result);\n\n const encryptedResponse = encryptFlowResponse(\n result,\n Buffer.from(data.aes_key, 'base64'),\n Buffer.from(data.initial_vector, 'base64'),\n );\n LOGGER.info('Encrypted flow response generated');\n\n return new Response(JSON.stringify(encryptedResponse), { status: 200 });\n }\n\n LOGGER.warn('Unknown flow request type:', decryptedBody);\n return new Response(JSON.stringify({ error: 'Unknown request type' }), { status: 400 });\n } catch (error) {\n LOGGER.error('Error handling flow request:', error);\n return new Response(JSON.stringify({ error: 'Internal server error' }), { status: 500 });\n }\n}\n\n/**\n * Verify webhook signature\n */\nfunction verifySignature(body: string, signature: string | null, verificationToken: string): boolean {\n if (!signature) {\n LOGGER.warn('Missing signature in request');\n return false;\n }\n\n LOGGER.info('Signature verification details:', {\n bodyLength: body.length,\n verificationTokenLength: verificationToken.length,\n rawSignature: signature,\n cleanedSignature: signature.replace('sha256=', ''),\n });\n\n const expectedSignature = crypto.createHmac('sha256', verificationToken).update(body).digest('hex');\n LOGGER.info('Signature verification:', {\n received: signature.replace('sha256=', ''),\n expected: expectedSignature,\n });\n\n return crypto.timingSafeEqual(Buffer.from(signature.replace('sha256=', '')), Buffer.from(expectedSignature));\n}\n\n/**\n * Constructs a full URL from framework-specific request headers and URL\n * @param headers - Request headers containing host and protocol information\n * @param url - Relative URL path\n * @returns Full URL string\n */\nexport function constructFullUrl(headers: Record<string, string | string[] | undefined>, url?: string): string {\n const protocol = headers['x-forwarded-proto'] || 'http';\n const host = headers.host || 'localhost';\n const path = url || '/';\n return `${protocol}://${host}${path}`;\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookMessageValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n LOGGER.info('Processing messages:', { waba_id, value });\n\n const metadata = value.metadata;\n const contacts = value.contacts;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata?.display_phone_number || '';\n const phoneNumberId = metadata?.phone_number_id || '';\n const profileName = contacts?.[0]?.profile?.name || '';\n\n if (value.statuses && value.statuses.length > 0) {\n LOGGER.info('Processing statuses:', { statusCount: value.statuses.length });\n const statuses = value.statuses;\n for (const status of statuses) {\n const processedStatus: WebhookMessage = {\n wabaId,\n id: status.id,\n from: status.recipient_id,\n timestamp: status.timestamp,\n type: MessageTypesEnum.Statuses,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n statuses: value.statuses[0],\n originalData: status,\n };\n\n LOGGER.info('Processing status:', processedStatus);\n await executeHandler(\n handlers.messageHandlers.get(MessageTypesEnum.Statuses),\n whatsapp,\n processedStatus,\n MessageTypesEnum.Statuses,\n );\n }\n return;\n }\n\n if (value.messages && value.messages.length > 0) {\n LOGGER.info('Processing messages:', { messageCount: value.messages.length });\n const messages = value.messages;\n\n for (const message of messages) {\n const messageType = message.type;\n LOGGER.info('Processing message:', { messageType, messageId: message.id });\n\n const processedMessage: WebhookMessage = {\n wabaId,\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n switch (messageType) {\n case MessageTypesEnum.Text:\n processedMessage.text = message.text;\n break;\n case MessageTypesEnum.Image:\n processedMessage.image = message.image;\n break;\n case MessageTypesEnum.Video:\n processedMessage.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n processedMessage.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n processedMessage.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n processedMessage.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n processedMessage.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n processedMessage.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n processedMessage.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n processedMessage.button = message.button;\n break;\n case MessageTypesEnum.Order:\n processedMessage.order = message.order;\n break;\n case MessageTypesEnum.System:\n processedMessage.system = message.system;\n break;\n case MessageTypesEnum.Reaction:\n processedMessage.reaction = message.reaction;\n break;\n default:\n LOGGER.warn('Unknown message type:', { messageType });\n break;\n }\n\n // Execute handlers in sequence\n LOGGER.info('Executing message handlers');\n await executeHandler(handlers.preProcessHandler, whatsapp, processedMessage, 'pre-process');\n await executeHandler(handlers.messageHandlers.get(messageType), whatsapp, processedMessage, messageType);\n await executeHandler(handlers.postProcessHandler, whatsapp, processedMessage, 'post-process');\n }\n }\n}\n\nasync function executeHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n message: WebhookMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n LOGGER.info('Executing handler:', { handlerType, messageId: message.id });\n await handler(whatsapp, message);\n LOGGER.info('Handler execution complete:', { handlerType, messageId: message.id });\n } catch (error) {\n LOGGER.error(`Error in ${handlerType} handler:`, { error, messageId: message.id });\n }\n } else {\n LOGGER.info('No handler registered:', { handlerType });\n }\n}\n\nfunction decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n LOGGER.info('Decrypting flow request');\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n LOGGER.error('Missing required encryption properties');\n throw new Error('Missing required encryption properties');\n }\n\n const privatePem = config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey: Buffer;\n\n try {\n LOGGER.info('Decrypting AES key');\n decryptedAesKey = crypto.privateDecrypt(\n {\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,\n oaepHash: 'sha256',\n },\n Buffer.from(encrypted_aes_key, 'base64'),\n );\n } catch (error) {\n LOGGER.error('Failed to decrypt AES key:', error);\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n LOGGER.info('Decrypting flow data');\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n LOGGER.info('Flow request decryption complete');\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\nfunction encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n LOGGER.info('Encrypting flow response');\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n const encryptedResponse = Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n\n LOGGER.info('Flow response encryption complete');\n return encryptedResponse;\n } catch (error) {\n LOGGER.error('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","import { FlowTypeEnum } from '../../api/flow/types';\nimport { importConfig } from '../../config/importConfig';\nimport { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport { MessageTypesEnum } from '../../types/enums';\nimport Logger from '../../utils/logger';\nimport { WhatsApp } from '../whatsapp';\nimport { FlowHandler, MessageHandler, processFlowRequest, processWebhookMessages } from './utils/webhookUtils';\n\nconst LOGGER = new Logger('WEBHOOK_PROCESSOR', process.env.DEBUG === 'true');\n\nexport interface WebhookResponse {\n status: number;\n body: string;\n headers: Record<string, string>;\n}\n\nexport class WebhookProcessor {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<MessageTypesEnum, MessageHandler> = new Map();\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookProcessor instantiated');\n }\n\n async processVerification(\n mode: string | null,\n token: string | null,\n challenge: string | null,\n ): Promise<WebhookResponse> {\n if (mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN) {\n return {\n status: 200,\n body: challenge || '',\n headers: { 'Content-Type': 'text/plain' },\n };\n }\n\n return {\n status: 403,\n body: JSON.stringify({ error: 'Forbidden' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n\n async processWebhook(request: Request): Promise<WebhookResponse> {\n try {\n const webResponse = await processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n\n const body = await webResponse.text();\n const contentType = webResponse.headers.get('content-type') || 'application/json';\n\n return {\n status: webResponse.status,\n body,\n headers: { 'Content-Type': contentType },\n };\n } catch (error) {\n LOGGER.log(`Error processing webhook: ${error}`);\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n }\n\n async processFlow(request: Request): Promise<WebhookResponse> {\n try {\n const webResponse = await processFlowRequest(request, this.config, this.client, this.flowHandlers);\n const body = await webResponse.text();\n const contentType = webResponse.headers.get('content-type') || 'application/json';\n\n return {\n status: webResponse.status,\n body,\n headers: { 'Content-Type': contentType },\n };\n } catch (error) {\n LOGGER.log(`Error processing flow: ${error}`);\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n }\n\n onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${type}`);\n }\n\n getClient(): WhatsApp {\n return this.client;\n }\n\n getConfig(): WabaConfigType {\n return this.config;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookProcessor.ts"],"names":["LIB_NAME","LOGGER","Logger","processWebhookMessages","request","whatsapp","handlers","body","errorMsg","errors","entry","changes","change","processMessages","error","processFlowRequest","config","flowHandlers","signature","verifySignature","data","decryptedBody","decryptFlowRequest","handler","isFlowPingRequest","isFlowErrorRequest","isFlowDataExchangeRequest","result","encryptedResponse","encryptFlowResponse","verificationToken","expectedSignature","crypto","constructFullUrl","headers","url","protocol","host","waba_id","value","metadata","contacts","wabaId","displayPhoneNumber","phoneNumberId","profileName","statuses","status","processedStatus","executeHandler","messages","message","messageType","processedMessage","handlerType","encrypted_aes_key","encrypted_flow_data","initial_vector","privatePem","passphrase","privateKey","decryptedAesKey","flowDataBuffer","initialVectorBuffer","encrypted_flow_data_body","encrypted_flow_data_tag","decipher","decryptedJSONString","response","aesKeyBuffer","flipped_iv","pair","cipher","WebhookProcessor","importConfig","WhatsApp","mode","token","challenge","webResponse","contentType","type"],"mappings":"6JAUA,IAAMA,CAAAA,CAAW,eAAA,CACXC,CAAAA,CAAS,IAAIC,CAAAA,CAAOF,CAAAA,CAAU,OAAA,CAAQ,GAAA,CAAI,KAAA,GAAU,MAAM,EAQhE,eAAsBG,CAAAA,CAClBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAKiB,CACjB,GAAI,CACAL,CAAAA,CAAO,IAAA,CAAK,qCAAqC,CAAA,CACjD,IAAMM,CAAAA,CAAO,MAAMH,CAAAA,CAAQ,IAAA,EAAK,CAIhC,GAHAH,CAAAA,CAAO,IAAA,CAAK,uBAAA,CAAyBM,CAAI,CAAA,CAGrCA,CAAAA,CAAK,MAAA,GAAW,2BAAA,CAA6B,CAC7C,IAAMC,CAAAA,CAAW,yCAAA,CACjB,OAAAP,CAAAA,CAAO,IAAA,CAAKO,CAAAA,CAAU,CAAE,IAAA,CAAAD,CAAK,CAAC,CAAA,CACvB,IAAI,QAAA,CAAS,IAAA,CAAK,SAAA,CAAU,CAAE,MAAOC,CAAS,CAAC,CAAA,CAAG,CAAE,MAAA,CAAQ,GAAI,CAAC,CAC5E,CAEA,IAAMC,CAAAA,CAAmB,EAAC,CAG1B,IAAA,IAAWC,KAASH,CAAAA,CAAK,KAAA,CACrB,GAAI,CACAN,CAAAA,CAAO,IAAA,CAAK,2BAAA,CAA6B,CAAE,OAAA,CAASS,CAAAA,CAAM,EAAG,CAAC,CAAA,CAC9D,IAAMC,EAAUD,CAAAA,CAAM,OAAA,CACtB,IAAA,IAAWE,CAAAA,IAAUD,CAAAA,CACbC,CAAAA,CAAO,KAAA,GAAU,UAAA,GACjBX,CAAAA,CAAO,IAAA,CAAK,6BAAA,CAA+B,CAAE,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,GAAA,CAAI,iCAAiC,EAChD,CAEA,MAAA,CAAOgF,CAAAA,CAAoB1D,CAAAA,CAA4B,CACnD,IAAA,CAAK,YAAA,CAAa,GAAA,CAAI0D,CAAAA,CAAM1D,CAAO,CAAA,CACnCtB,EAAO,GAAA,CAAI,CAAA,4BAAA,EAA+BgF,CAAI,CAAA,CAAE,EACpD,CAEA,SAAA,EAAsB,CAClB,OAAO,IAAA,CAAK,MAChB,CAEA,SAAA,EAA4B,CACxB,OAAO,IAAA,CAAK,MAChB,CACJ","file":"chunk-JPGXONBQ.js","sourcesContent":["import crypto from 'crypto';\nimport { FlowEndpointRequest } from '../../../api/flow';\nimport { FlowTypeEnum } from '../../../api/flow/types';\nimport { WabaConfigType } from '../../../types/config';\nimport { MessageTypesEnum } from '../../../types/enums';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '../../../utils/flowTypeGuards';\nimport Logger from '../../../utils/logger';\nimport { WhatsApp } from '../../whatsapp';\nimport { WebhookMessage, WebhookMessageValue } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\nexport type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n/**\n * Process webhook messages\n */\nexport async function processWebhookMessages(\n request: Request,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<Response> {\n try {\n LOGGER.info('Processing webhook messages request');\n const body = await request.json();\n LOGGER.info('Webhook request body:', body);\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n const errorMsg = 'Received webhook for non-WhatsApp event';\n LOGGER.warn(errorMsg, { body });\n return new Response(JSON.stringify({ error: errorMsg }), { status: 404 });\n }\n\n const errors: string[] = [];\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n LOGGER.info('Processing webhook entry:', { entryId: entry.id });\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === 'messages') {\n LOGGER.info('Processing messages change:', { change });\n await processMessages(entry.id, change.value, whatsapp, handlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.error(errorMsg, { entry, error });\n errors.push(errorMsg);\n }\n }\n\n LOGGER.info('Webhook processing complete', { errorCount: errors.length });\n return new Response(errors.length > 0 ? JSON.stringify({ errors }) : null, { status: 200 });\n } catch (error) {\n LOGGER.error('Error processing webhook:', error);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });\n }\n}\n\n/**\n * Handle flow requests\n */\nexport async function processFlowRequest(\n request: Request,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<Response> {\n try {\n LOGGER.info('Processing flow request');\n const body = await request.text();\n const signature = request.headers.get('x-hub-signature-256');\n LOGGER.info('Flow request signature:', { signature });\n\n // Validate request signature\n if (!verifySignature(body, signature, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.warn('Invalid request signature', { signature });\n return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });\n }\n\n const data = JSON.parse(body);\n LOGGER.info('Flow request data:', data);\n\n // Decrypt the request\n const { decryptedBody } = decryptFlowRequest(data, config);\n LOGGER.info('Decrypted flow request:', decryptedBody);\n\n // Get the flow handler\n const handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.warn('No handler registered for flow action:', { action: decryptedBody.action });\n return new Response(JSON.stringify({ error: 'Handler not found' }), { status: 404 });\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n LOGGER.info('Handling flow ping request');\n return new Response(\n JSON.stringify({\n version: '3.0',\n data: { status: 'active' },\n }),\n { status: 200 },\n );\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.warn('Flow error request received:', decryptedBody);\n return new Response(null, { status: 200 });\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n LOGGER.info('Processing flow data exchange request');\n const result = await handler(whatsapp, decryptedBody);\n LOGGER.info('Flow handler result:', result);\n\n const encryptedResponse = encryptFlowResponse(\n result,\n Buffer.from(data.aes_key, 'base64'),\n Buffer.from(data.initial_vector, 'base64'),\n );\n LOGGER.info('Encrypted flow response generated');\n\n return new Response(JSON.stringify(encryptedResponse), { status: 200 });\n }\n\n LOGGER.warn('Unknown flow request type:', decryptedBody);\n return new Response(JSON.stringify({ error: 'Unknown request type' }), { status: 400 });\n } catch (error) {\n LOGGER.error('Error handling flow request:', error);\n return new Response(JSON.stringify({ error: 'Internal server error' }), { status: 500 });\n }\n}\n\n/**\n * Verify webhook signature\n */\nfunction verifySignature(body: string, signature: string | null, verificationToken: string): boolean {\n if (!signature) {\n LOGGER.warn('Missing signature in request');\n return false;\n }\n\n LOGGER.info('Signature verification details:', {\n bodyLength: body.length,\n verificationTokenLength: verificationToken.length,\n rawSignature: signature,\n cleanedSignature: signature.replace('sha256=', ''),\n });\n\n const expectedSignature = crypto.createHmac('sha256', verificationToken).update(body).digest('hex');\n LOGGER.info('Signature verification:', {\n received: signature.replace('sha256=', ''),\n expected: expectedSignature,\n });\n\n return crypto.timingSafeEqual(Buffer.from(signature.replace('sha256=', '')), Buffer.from(expectedSignature));\n}\n\n/**\n * Constructs a full URL from framework-specific request headers and URL\n * @param headers - Request headers containing host and protocol information\n * @param url - Relative URL path\n * @returns Full URL string\n */\nexport function constructFullUrl(headers: Record<string, string | string[] | undefined>, url?: string): string {\n const protocol = headers['x-forwarded-proto'] || 'http';\n const host = headers.host || 'localhost';\n const path = url || '/';\n return `${protocol}://${host}${path}`;\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookMessageValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n LOGGER.info('Processing messages:', { waba_id, value });\n\n const metadata = value.metadata;\n const contacts = value.contacts;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata?.display_phone_number || '';\n const phoneNumberId = metadata?.phone_number_id || '';\n const profileName = contacts?.[0]?.profile?.name || '';\n\n if (value.statuses && value.statuses.length > 0) {\n LOGGER.info('Processing statuses:', { statusCount: value.statuses.length });\n const statuses = value.statuses;\n for (const status of statuses) {\n const processedStatus: WebhookMessage = {\n wabaId,\n id: status.id,\n from: status.recipient_id,\n timestamp: status.timestamp,\n type: MessageTypesEnum.Statuses,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n statuses: value.statuses[0],\n originalData: status,\n };\n\n LOGGER.info('Processing status:', processedStatus);\n await executeHandler(\n handlers.messageHandlers.get(MessageTypesEnum.Statuses),\n whatsapp,\n processedStatus,\n MessageTypesEnum.Statuses,\n );\n }\n return;\n }\n\n if (value.messages && value.messages.length > 0) {\n LOGGER.info('Processing messages:', { messageCount: value.messages.length });\n const messages = value.messages;\n\n for (const message of messages) {\n const messageType = message.type;\n LOGGER.info('Processing message:', { messageType, messageId: message.id });\n\n const processedMessage: WebhookMessage = {\n wabaId,\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n switch (messageType) {\n case MessageTypesEnum.Text:\n processedMessage.text = message.text;\n break;\n case MessageTypesEnum.Image:\n processedMessage.image = message.image;\n break;\n case MessageTypesEnum.Video:\n processedMessage.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n processedMessage.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n processedMessage.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n processedMessage.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n processedMessage.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n processedMessage.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n processedMessage.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n processedMessage.button = message.button;\n break;\n case MessageTypesEnum.Order:\n processedMessage.order = message.order;\n break;\n case MessageTypesEnum.System:\n processedMessage.system = message.system;\n break;\n case MessageTypesEnum.Reaction:\n processedMessage.reaction = message.reaction;\n break;\n default:\n LOGGER.warn('Unknown message type:', { messageType });\n break;\n }\n\n // Execute handlers in sequence\n LOGGER.info('Executing message handlers');\n await executeHandler(handlers.preProcessHandler, whatsapp, processedMessage, 'pre-process');\n await executeHandler(handlers.messageHandlers.get(messageType), whatsapp, processedMessage, messageType);\n await executeHandler(handlers.postProcessHandler, whatsapp, processedMessage, 'post-process');\n }\n }\n}\n\nasync function executeHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n message: WebhookMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n LOGGER.info('Executing handler:', { handlerType, messageId: message.id });\n await handler(whatsapp, message);\n LOGGER.info('Handler execution complete:', { handlerType, messageId: message.id });\n } catch (error) {\n LOGGER.error(`Error in ${handlerType} handler:`, { error, messageId: message.id });\n }\n } else {\n LOGGER.info('No handler registered:', { handlerType });\n }\n}\n\nfunction decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n LOGGER.info('Decrypting flow request');\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n LOGGER.error('Missing required encryption properties');\n throw new Error('Missing required encryption properties');\n }\n\n const privatePem = config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey: Buffer;\n\n try {\n LOGGER.info('Decrypting AES key');\n decryptedAesKey = crypto.privateDecrypt(\n {\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,\n oaepHash: 'sha256',\n },\n Buffer.from(encrypted_aes_key, 'base64'),\n );\n } catch (error) {\n LOGGER.error('Failed to decrypt AES key:', error);\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n LOGGER.info('Decrypting flow data');\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n LOGGER.info('Flow request decryption complete');\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\nfunction encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n LOGGER.info('Encrypting flow response');\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n const encryptedResponse = Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n\n LOGGER.info('Flow response encryption complete');\n return encryptedResponse;\n } catch (error) {\n LOGGER.error('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","import { FlowTypeEnum } from '../../api/flow/types';\nimport { importConfig } from '../../config/importConfig';\nimport { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport { MessageTypesEnum } from '../../types/enums';\nimport Logger from '../../utils/logger';\nimport { WhatsApp } from '../whatsapp';\nimport { FlowHandler, MessageHandler, processFlowRequest, processWebhookMessages } from './utils/webhookUtils';\n\nconst LOGGER = new Logger('WEBHOOK_PROCESSOR', process.env.DEBUG === 'true');\n\nexport interface WebhookResponse {\n status: number;\n body: string;\n headers: Record<string, string>;\n}\n\nexport class WebhookProcessor {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<MessageTypesEnum, MessageHandler> = new Map();\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookProcessor instantiated');\n }\n\n async processVerification(\n mode: string | null,\n token: string | null,\n challenge: string | null,\n ): Promise<WebhookResponse> {\n if (mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN) {\n return {\n status: 200,\n body: challenge || '',\n headers: { 'Content-Type': 'text/plain' },\n };\n }\n\n return {\n status: 403,\n body: JSON.stringify({ error: 'Forbidden' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n\n async processWebhook(request: Request): Promise<WebhookResponse> {\n try {\n const webResponse = await processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n\n const body = await webResponse.text();\n const contentType = webResponse.headers.get('content-type') || 'application/json';\n\n return {\n status: webResponse.status,\n body,\n headers: { 'Content-Type': contentType },\n };\n } catch (error) {\n LOGGER.log(`Error processing webhook: ${error}`);\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n }\n\n async processFlow(request: Request): Promise<WebhookResponse> {\n try {\n const webResponse = await processFlowRequest(request, this.config, this.client, this.flowHandlers);\n const body = await webResponse.text();\n const contentType = webResponse.headers.get('content-type') || 'application/json';\n\n return {\n status: webResponse.status,\n body,\n headers: { 'Content-Type': contentType },\n };\n } catch (error) {\n LOGGER.log(`Error processing flow: ${error}`);\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n }\n\n onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${type}`);\n }\n\n getClient(): WhatsApp {\n return this.client;\n }\n\n getConfig(): WabaConfigType {\n return this.config;\n }\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {d,c}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {d,c}from'./chunk-JPGXONBQ.js';function b(h){let d$1=new d(h);return {webhook:async(e,r,i)=>{try{if(e.method==="GET"){let{"hub.mode":s,"hub.verify_token":n,"hub.challenge":t}=e.query,o=await d$1.processVerification(s||null,n||null,t||null);return Object.entries(o.headers).forEach(([a,l])=>{r.setHeader(a,l);}),r.status(o.status).send(o.body)}if(e.method==="POST"){let s=c(e.headers,e.url),n=new globalThis.Request(s,{method:e.method,headers:e.headers,body:JSON.stringify(e.body)}),t=await d$1.processWebhook(n);return Object.entries(t.headers).forEach(([o,a])=>{r.setHeader(o,a);}),r.status(t.status).send(t.body)}return r.status(405).json({error:"Method Not Allowed"})}catch(s){i(s);return}},flow:async(e,r,i)=>{try{let s=c(e.headers,e.url),n=new globalThis.Request(s,{method:e.method,headers:e.headers,body:e.method==="POST"?JSON.stringify(e.body):void 0}),t=await d$1.processFlow(n);return Object.entries(t.headers).forEach(([o,a])=>{r.setHeader(o,a);}),r.status(t.status).send(t.body)}catch(s){i(s);return}},processor:d$1}}export{b as a};//# sourceMappingURL=chunk-NOJFGTRT.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-NOJFGTRT.js.map
|