meta-cloud-api 1.0.3 → 1.1.1

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.
Files changed (58) hide show
  1. package/dist/{BusinessProfileApi-WXscSgo-.d.ts → BusinessProfileApi-CW0emncx.d.ts} +1 -1
  2. package/dist/{EncryptionApi-D7pt-OXT.d.ts → EncryptionApi-Dyea0SR3.d.ts} +1 -1
  3. package/dist/{FlowApi-B2ffO-HD.d.ts → FlowApi-DvoT7ivY.d.ts} +1 -1
  4. package/dist/{MessageApi-BgsSpDno.d.ts → MessageApi-D-9SuL4w.d.ts} +1 -1
  5. package/dist/{TemplateApi-xGgIZt89.d.ts → TemplateApi-D4_6LvhN.d.ts} +1 -1
  6. package/dist/{WabaApi-DqQi_68m.d.ts → WabaApi-BvY1JVRH.d.ts} +1 -1
  7. package/dist/{WebhookProcessor-BXYunz4N.d.ts → WebhookProcessor-CE4xBPe0.d.ts} +2 -2
  8. package/dist/{WhatsApp-pTZPQm81.d.ts → WhatsApp-iAly_4pr.d.ts} +6 -6
  9. package/dist/api/encryption/index.d.ts +2 -2
  10. package/dist/api/flow/index.d.ts +3 -2
  11. package/dist/api/flow/index.js +1 -1
  12. package/dist/api/index.d.ts +9 -8
  13. package/dist/api/index.js +1 -1
  14. package/dist/api/messages/builders/index.d.ts +1 -1
  15. package/dist/api/messages/index.d.ts +2 -2
  16. package/dist/api/profile/index.d.ts +2 -2
  17. package/dist/api/template/index.d.ts +6 -200
  18. package/dist/api/waba/index.d.ts +2 -2
  19. package/dist/chunk-5577QQ7V.js +2 -0
  20. package/dist/chunk-5577QQ7V.js.map +1 -0
  21. package/dist/{chunk-WGGN32O2.js → chunk-6DFC5L3X.js} +2 -2
  22. package/dist/chunk-6DFC5L3X.js.map +1 -0
  23. package/dist/chunk-GM63NGNV.js +2 -0
  24. package/dist/chunk-GM63NGNV.js.map +1 -0
  25. package/dist/chunk-J2JPTKU6.js +2 -0
  26. package/dist/chunk-J2JPTKU6.js.map +1 -0
  27. package/dist/{chunk-JPGXONBQ.js → chunk-U5FBZ6UB.js} +3 -3
  28. package/dist/{chunk-JPGXONBQ.js.map → chunk-U5FBZ6UB.js.map} +1 -1
  29. package/dist/chunk-ZMNXRMWK.js +2 -0
  30. package/dist/chunk-ZMNXRMWK.js.map +1 -0
  31. package/dist/{common-BiRA_uz3.d.ts → common-CzzMWFoO.d.ts} +1 -1
  32. package/dist/{common-lV0NsO7t.d.ts → common-nVoO5ROn.d.ts} +28 -1
  33. package/dist/core/webhook/frameworks/express.d.ts +20 -16
  34. package/dist/core/webhook/frameworks/express.js +1 -1
  35. package/dist/core/webhook/frameworks/nextjs-app.d.ts +48 -0
  36. package/dist/core/webhook/frameworks/nextjs-app.js +2 -0
  37. package/dist/core/webhook/frameworks/nextjs-app.js.map +1 -0
  38. package/dist/core/webhook/frameworks/nextjs.d.ts +18 -14
  39. package/dist/core/webhook/frameworks/nextjs.js +1 -1
  40. package/dist/core/webhook/index.d.ts +12 -10
  41. package/dist/core/webhook/index.js +1 -1
  42. package/dist/core/whatsapp/index.d.ts +10 -9
  43. package/dist/core/whatsapp/index.js +1 -1
  44. package/dist/factory-D2eO5etK.d.ts +200 -0
  45. package/dist/handler-DbySwF0E.d.ts +20 -0
  46. package/dist/index.d.ts +20 -17
  47. package/dist/index.js +1 -1
  48. package/dist/{isMetaError-CXWJwW58.d.ts → isMetaError-CLqzdSws.d.ts} +1 -1
  49. package/dist/utils/index.d.ts +3 -2
  50. package/dist/utils/index.js +1 -1
  51. package/package.json +59 -76
  52. package/dist/chunk-NLF2JGYY.js +0 -2
  53. package/dist/chunk-NLF2JGYY.js.map +0 -1
  54. package/dist/chunk-NOJFGTRT.js +0 -2
  55. package/dist/chunk-NOJFGTRT.js.map +0 -1
  56. package/dist/chunk-WGGN32O2.js.map +0 -1
  57. package/dist/chunk-YXZ4L2OK.js +0 -2
  58. package/dist/chunk-YXZ4L2OK.js.map +0 -1
@@ -350,4 +350,4 @@ declare class BusinessProfileApi extends BaseAPI implements BusinessProfileClass
350
350
  getUploadHandle(uploadId: string): Promise<UploadHandle>;
351
351
  }
352
352
 
353
- export { BusinessProfileApi as B, type CreateUploadSessionParams as C, type GetUploadHandleParams as G, type UpdateBusinessProfileRequest as U, BusinessProfileClass as a, type BusinessProfileData as b, type BusinessProfileField as c, type BusinessProfileFieldsParam as d, type BusinessProfileResponse as e, type UploadBusinessProfileResponse as f, type UploadHandle as g, type UploadMediaParams as h, type UploadSession as i, type UploadSessionResponse as j };
353
+ export { BusinessProfileApi as B, type CreateUploadSessionParams as C, type GetUploadHandleParams as G, type UpdateBusinessProfileRequest as U, type BusinessProfileData as a, type BusinessProfileResponse as b, type BusinessProfileField as c, type BusinessProfileFieldsParam as d, BusinessProfileClass as e, type UploadBusinessProfileResponse as f, type UploadHandle as g, type UploadMediaParams as h, type UploadSession as i, type UploadSessionResponse as j };
@@ -19,4 +19,4 @@ declare class EncryptionApi extends BaseAPI implements EncryptionClass {
19
19
  setEncryptionPublicKey(businessPublicKey: string): Promise<ResponseSuccess>;
20
20
  }
21
21
 
22
- export { EncryptionApi as E, type EncryptionClass as a, type EncryptionPublicKeyResponse as b };
22
+ export { EncryptionApi as E, type EncryptionPublicKeyResponse as a, type EncryptionClass as b };
@@ -1,7 +1,7 @@
1
1
  import { B as BaseAPI } from './base-CdGDdVEl.js';
2
2
  import { WabaConfigType } from './types/config.js';
3
3
  import { R as RequesterClass, e as ResponseSuccess } from './request-vYMaEfk5.js';
4
- import { h as FlowClass, k as FlowsListResponse, g as FlowCategoryEnum, C as CreateFlowResponse, c as Flow, j as FlowPreviewResponse, f as FlowAssetsResponse, U as UpdateFlowResponse, V as ValidateFlowJsonResponse, i as FlowMigrationResponse } from './common-lV0NsO7t.js';
4
+ import { g as FlowClass, x as FlowsListResponse, b as FlowCategoryEnum, D as CreateFlowResponse, d as Flow, w as FlowPreviewResponse, f as FlowAssetsResponse, U as UpdateFlowResponse, V as ValidateFlowJsonResponse, u as FlowMigrationResponse } from './common-nVoO5ROn.js';
5
5
 
6
6
  /**
7
7
  * API for managing WhatsApp Flows.
@@ -2,7 +2,7 @@ import { B as BaseAPI } from './base-CdGDdVEl.js';
2
2
  import { WabaConfigType } from './types/config.js';
3
3
  import { M as MessageTypesEnum, C as ComponentTypesEnum, I as InteractiveTypesEnum } from './enums-BZd9T2ul.js';
4
4
  import { R as RequesterClass } from './request-vYMaEfk5.js';
5
- import { f as MessagesClass, A as AudioMediaObject, C as ContactObject, D as DocumentMediaObject, I as ImageMediaObject, a as InteractiveObject, L as LocationObject, c as MessageTemplateObject, d as StickerMediaObject, e as TextObject, V as VideoMediaObject, g as MessageRequestBody, M as MessageRequestParams, b as MessagesResponse, T as TextMessageParams, S as StatusParams, R as ReactionParams } from './common-BiRA_uz3.js';
5
+ import { b as MessagesClass, A as AudioMediaObject, C as ContactObject, D as DocumentMediaObject, I as ImageMediaObject, f as InteractiveObject, L as LocationObject, g as MessageTemplateObject, e as StickerMediaObject, d as TextObject, V as VideoMediaObject, M as MessageRequestBody, a as MessageRequestParams, c as MessagesResponse, T as TextMessageParams, S as StatusParams, R as ReactionParams } from './common-CzzMWFoO.js';
6
6
 
7
7
  /**
8
8
  * Maps each message type to its appropriate payload type
@@ -158,4 +158,4 @@ declare class TemplateApi extends BaseAPI implements TemplateClass {
158
158
  deleteTemplate(params: TemplateDeleteParams): Promise<ResponseSuccess>;
159
159
  }
160
160
 
161
- export { type CatalogButton as C, type FlowButton as F, type MPMButton as M, type OTPButton as O, type PhoneNumberButton as P, type QuickReplyButton as Q, type SPMButton as S, TemplateApi as T, type URLButton as U, TemplateClass as a, type TemplateDeleteParams as b, type TemplateGetParams as c, type TemplateRequestBody as d, type TemplateResponse as e, type TemplateFormat as f, type ComponentTypes as g, type CopyCodeButton as h, type TemplateBody as i, type TemplateButton as j, type TemplateButtons as k, type TemplateCarousel as l, type TemplateFooter as m, type TemplateHeader as n, type TemplateHeaderExample as o, type TemplateLimitedTimeOffer as p, type MediaCarouselCard as q, type ProductCarouselCard as r };
161
+ export { type CatalogButton as C, type FlowButton as F, type MPMButton as M, type OTPButton as O, type PhoneNumberButton as P, type QuickReplyButton as Q, type SPMButton as S, TemplateApi as T, type URLButton as U, type ComponentTypes as a, type CopyCodeButton as b, type TemplateBody as c, type TemplateButton as d, type TemplateButtons as e, type TemplateCarousel as f, TemplateClass as g, type TemplateDeleteParams as h, type TemplateFooter as i, type TemplateFormat as j, type TemplateGetParams as k, type TemplateHeader as l, type TemplateHeaderExample as m, type TemplateLimitedTimeOffer as n, type TemplateRequestBody as o, type TemplateResponse as p, type MediaCarouselCard as q, type ProductCarouselCard as r };
@@ -172,4 +172,4 @@ declare class WabaApi extends BaseAPI implements WABAClass {
172
172
  unsubscribeFromWaba(): Promise<ResponseSuccess>;
173
173
  }
174
174
 
175
- export { type UpdateWabaSubscription as U, WabaApi as W, type WabaAccount as a, type WABAClass as b, type WabaSubscriptions as c };
175
+ export { type UpdateWabaSubscription as U, WabaApi as W, type WabaAccount as a, type WABAClass as b, type WabaSubscription as c, type WabaSubscriptions as d };
@@ -1,7 +1,7 @@
1
- import { a as FlowEndpointRequest, F as FlowTypeEnum } from './common-lV0NsO7t.js';
1
+ import { l as FlowEndpointRequest, F as FlowTypeEnum } from './common-nVoO5ROn.js';
2
2
  import { WabaConfigType, WhatsAppConfig } from './types/config.js';
3
3
  import { M as MessageTypesEnum } from './enums-BZd9T2ul.js';
4
- import { W as WhatsApp } from './WhatsApp-pTZPQm81.js';
4
+ import { W as WhatsApp } from './WhatsApp-iAly_4pr.js';
5
5
 
6
6
  interface WebhookContact {
7
7
  /**
@@ -3,17 +3,17 @@ import { H as HttpMethodsEnum, l as SDKEnums } from './enums-BZd9T2ul.js';
3
3
  import { R as RequesterClass } from './request-vYMaEfk5.js';
4
4
  import { H as HttpsClientClass, a as HttpsClientResponseClass } from './httpsClient-v4gmltzS.js';
5
5
  import { Agent } from 'https';
6
- import { E as EncryptionApi } from './EncryptionApi-D7pt-OXT.js';
7
- import { F as FlowApi } from './FlowApi-B2ffO-HD.js';
6
+ import { E as EncryptionApi } from './EncryptionApi-Dyea0SR3.js';
7
+ import { F as FlowApi } from './FlowApi-DvoT7ivY.js';
8
8
  import { M as MediaApi } from './MediaApi-BrEKpqi_.js';
9
- import { M as MessagesApi } from './MessageApi-BgsSpDno.js';
9
+ import { M as MessagesApi } from './MessageApi-D-9SuL4w.js';
10
10
  import { P as PhoneNumberApi } from './PhoneNumberApi-DKlu9PHl.js';
11
- import { B as BusinessProfileApi } from './BusinessProfileApi-WXscSgo-.js';
11
+ import { B as BusinessProfileApi } from './BusinessProfileApi-CW0emncx.js';
12
12
  import { Q as QrCodeApi } from './QrCodeApi-7vDwIBHR.js';
13
13
  import { R as RegistrationApi } from './RegistrationApi-qO_qoti9.js';
14
- import { T as TemplateApi } from './TemplateApi-xGgIZt89.js';
14
+ import { T as TemplateApi } from './TemplateApi-D4_6LvhN.js';
15
15
  import { T as TwoStepVerificationApi } from './TwoStepVerificationApi-DfNPIz-C.js';
16
- import { W as WabaApi } from './WabaApi-DqQi_68m.js';
16
+ import { W as WabaApi } from './WabaApi-BvY1JVRH.js';
17
17
 
18
18
  declare class HttpsClient implements HttpsClientClass {
19
19
  agent: Agent;
@@ -1,5 +1,5 @@
1
- import { E as EncryptionApi } from '../../EncryptionApi-D7pt-OXT.js';
2
- export { a as EncryptionClass, b as EncryptionPublicKeyResponse } from '../../EncryptionApi-D7pt-OXT.js';
1
+ import { E as EncryptionApi } from '../../EncryptionApi-Dyea0SR3.js';
2
+ export { b as EncryptionClass, a as EncryptionPublicKeyResponse } from '../../EncryptionApi-Dyea0SR3.js';
3
3
  import '../../base-CdGDdVEl.js';
4
4
  import '../../types/config.js';
5
5
  import '../../enums-BZd9T2ul.js';
@@ -1,9 +1,10 @@
1
- import { F as FlowApi } from '../../FlowApi-B2ffO-HD.js';
2
- export { C as CreateFlowResponse, c as Flow, e as FlowActionEnum, f as FlowAssetsResponse, g as FlowCategoryEnum, h as FlowClass, a as FlowEndpointRequest, b as FlowEndpointResponse, i as FlowMigrationResponse, j as FlowPreviewResponse, l as FlowStatusEnum, d as FlowType, F as FlowTypeEnum, m as FlowValidationError, k as FlowsListResponse, U as UpdateFlowResponse, V as ValidateFlowJsonResponse } from '../../common-lV0NsO7t.js';
1
+ import { F as FlowApi } from '../../FlowApi-DvoT7ivY.js';
2
+ export { D as CreateFlowResponse, d as Flow, a as FlowActionEnum, f as FlowAssetsResponse, b as FlowCategoryEnum, g as FlowClass, l as FlowEndpointRequest, m as FlowEndpointResponse, u as FlowMigrationResponse, w as FlowPreviewResponse, c as FlowStatusEnum, z as FlowType, F as FlowTypeEnum, A as FlowValidationError, x as FlowsListResponse, U as UpdateFlowResponse, V as ValidateFlowJsonResponse } from '../../common-nVoO5ROn.js';
3
3
  import '../../base-CdGDdVEl.js';
4
4
  import '../../types/config.js';
5
5
  import '../../enums-BZd9T2ul.js';
6
6
  import '../../request-vYMaEfk5.js';
7
+ import 'http';
7
8
 
8
9
 
9
10
 
@@ -1,2 +1,2 @@
1
- export{a as FlowApi,b as default}from'../../chunk-JC6YMVID.js';export{a as FlowTypeEnum}from'../../chunk-NLF2JGYY.js';import'../../chunk-RIL6QABY.js';import'../../chunk-KMAH6636.js';//# sourceMappingURL=index.js.map
1
+ export{a as FlowApi,b as default}from'../../chunk-JC6YMVID.js';export{d as FlowTypeEnum}from'../../chunk-J2JPTKU6.js';import'../../chunk-RIL6QABY.js';import'../../chunk-KMAH6636.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -1,17 +1,18 @@
1
- export { E as EncryptionApi, a as EncryptionClass, b as EncryptionPublicKeyResponse } from '../EncryptionApi-D7pt-OXT.js';
2
- export { F as FlowApi } from '../FlowApi-B2ffO-HD.js';
3
- export { C as CreateFlowResponse, c as Flow, e as FlowActionEnum, f as FlowAssetsResponse, g as FlowCategoryEnum, h as FlowClass, a as FlowEndpointRequest, b as FlowEndpointResponse, i as FlowMigrationResponse, j as FlowPreviewResponse, l as FlowStatusEnum, d as FlowType, F as FlowTypeEnum, m as FlowValidationError, k as FlowsListResponse, U as UpdateFlowResponse, V as ValidateFlowJsonResponse } from '../common-lV0NsO7t.js';
1
+ export { E as EncryptionApi, b as EncryptionClass, a as EncryptionPublicKeyResponse } from '../EncryptionApi-Dyea0SR3.js';
2
+ export { F as FlowApi } from '../FlowApi-DvoT7ivY.js';
3
+ export { D as CreateFlowResponse, d as Flow, a as FlowActionEnum, f as FlowAssetsResponse, b as FlowCategoryEnum, g as FlowClass, l as FlowEndpointRequest, m as FlowEndpointResponse, u as FlowMigrationResponse, w as FlowPreviewResponse, c as FlowStatusEnum, z as FlowType, F as FlowTypeEnum, A as FlowValidationError, x as FlowsListResponse, U as UpdateFlowResponse, V as ValidateFlowJsonResponse } from '../common-nVoO5ROn.js';
4
4
  export { M as MediaApi, a as MediaClass, b as MediaResponse, c as MediasResponse, U as UploadMediaResponse } from '../MediaApi-BrEKpqi_.js';
5
- export { M as MessagesApi } from '../MessageApi-BgsSpDno.js';
6
- 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';
5
+ export { M as MessagesApi } from '../MessageApi-D-9SuL4w.js';
6
+ export { A as AudioMediaObject, C as ContactObject, D as DocumentMediaObject, I as ImageMediaObject, f as InteractiveObject, L as LocationObject, a as MessageRequestParams, g as MessageTemplateObject, c as MessagesResponse, R as ReactionParams, S as StatusParams, e as StickerMediaObject, T as TextMessageParams, d as TextObject, V as VideoMediaObject } from '../common-CzzMWFoO.js';
7
7
  export { A as AccountMode, C as CodeVerificationStatus, a as Cursors, H as HealthStatus, b as HealthStatusEntity, M as MessagingLimitTier, P as PhoneNumberApi, c as PhoneNumberClass, d as PhoneNumberResponse, e as PhoneNumbersResponse, f as PlatformType, Q as QualityRating, g as QualityScore, R as RequestVerificationCodeRequest, T as Throughput, h as ThroughputLevel, i as TwoStepVerificationParams, V as VerifyCodeRequest } from '../PhoneNumberApi-DKlu9PHl.js';
8
- export { B as BusinessProfileApi, a as BusinessProfileClass, b as BusinessProfileData, c as BusinessProfileField, d as BusinessProfileFieldsParam, e as BusinessProfileResponse, C as CreateUploadSessionParams, G as GetUploadHandleParams, U as UpdateBusinessProfileRequest, f as UploadBusinessProfileResponse, g as UploadHandle, h as UploadMediaParams, i as UploadSession, j as UploadSessionResponse } from '../BusinessProfileApi-WXscSgo-.js';
8
+ export { B as BusinessProfileApi, e as BusinessProfileClass, a as BusinessProfileData, c as BusinessProfileField, d as BusinessProfileFieldsParam, b as BusinessProfileResponse, C as CreateUploadSessionParams, G as GetUploadHandleParams, U as UpdateBusinessProfileRequest, f as UploadBusinessProfileResponse, g as UploadHandle, h as UploadMediaParams, i as UploadSession, j as UploadSessionResponse } from '../BusinessProfileApi-CW0emncx.js';
9
9
  export { C as CreateQrCodeRequest, Q as QrCodeApi, a as QrCodeClass, b as QrCodeResponse, c as QrCodesResponse, U as UpdateQrCodeRequest } from '../QrCodeApi-7vDwIBHR.js';
10
10
  export { R as RegistrationApi, a as RegistrationClass, b as RegistrationRequest } from '../RegistrationApi-qO_qoti9.js';
11
- export { T as TemplateApi, a as TemplateClass, b as TemplateDeleteParams, c as TemplateGetParams, d as TemplateRequestBody, e as TemplateResponse } from '../TemplateApi-xGgIZt89.js';
11
+ export { T as TemplateApi, g as TemplateClass, h as TemplateDeleteParams, k as TemplateGetParams, o as TemplateRequestBody, p as TemplateResponse } from '../TemplateApi-D4_6LvhN.js';
12
12
  export { T as TwoStepVerificationApi, a as TwoStepVerificationClass, b as TwoStepVerificationRequest } from '../TwoStepVerificationApi-DfNPIz-C.js';
13
- export { U as UpdateWabaSubscription, b as WABAClass, a as WabaAccount, W as WabaApi, c as WabaSubscriptions } from '../WabaApi-DqQi_68m.js';
13
+ export { U as UpdateWabaSubscription, b as WABAClass, a as WabaAccount, W as WabaApi, d as WabaSubscriptions } from '../WabaApi-BvY1JVRH.js';
14
14
  import '../base-CdGDdVEl.js';
15
15
  import '../types/config.js';
16
16
  import '../enums-BZd9T2ul.js';
17
17
  import '../request-vYMaEfk5.js';
18
+ import 'http';
package/dist/api/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import'../chunk-AMHQGG6Z.js';export{a as TemplateApi}from'../chunk-VHAODWCN.js';export{b as QrCodeApi}from'../chunk-JPAV644F.js';export{b as RegistrationApi}from'../chunk-PHPQ5HP3.js';export{b as EncryptionApi}from'../chunk-IYSR44P6.js';export{b as TwoStepVerificationApi}from'../chunk-SNNRWNGZ.js';export{b as WabaApi}from'../chunk-L4ESAO2S.js';export{b as MessagesApi}from'../chunk-7QBIZCJ4.js';export{b as MediaApi}from'../chunk-JXCLRKQ7.js';export{b as BusinessProfileApi}from'../chunk-LV3TULSI.js';import'../chunk-CRZ7EUYR.js';export{b as FlowApi}from'../chunk-JC6YMVID.js';import'../chunk-NLF2JGYY.js';export{b as PhoneNumberApi}from'../chunk-FSKBLPGE.js';import'../chunk-MJEG3K4V.js';import'../chunk-RIL6QABY.js';import'../chunk-KMAH6636.js';//# sourceMappingURL=index.js.map
1
+ import'../chunk-AMHQGG6Z.js';export{a as TemplateApi}from'../chunk-VHAODWCN.js';export{b as QrCodeApi}from'../chunk-JPAV644F.js';export{b as RegistrationApi}from'../chunk-PHPQ5HP3.js';export{b as EncryptionApi}from'../chunk-IYSR44P6.js';export{b as TwoStepVerificationApi}from'../chunk-SNNRWNGZ.js';export{b as WabaApi}from'../chunk-L4ESAO2S.js';export{b as MessagesApi}from'../chunk-7QBIZCJ4.js';export{b as MediaApi}from'../chunk-JXCLRKQ7.js';export{b as BusinessProfileApi}from'../chunk-LV3TULSI.js';import'../chunk-CRZ7EUYR.js';export{b as FlowApi}from'../chunk-JC6YMVID.js';import'../chunk-J2JPTKU6.js';export{b as PhoneNumberApi}from'../chunk-FSKBLPGE.js';import'../chunk-MJEG3K4V.js';import'../chunk-RIL6QABY.js';import'../chunk-KMAH6636.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import { N as NameObject, h as AddressesObject, C as ContactObject, a as InteractiveObject, L as LocationObject, A as AudioMediaObject, D as DocumentMediaObject, I as ImageMediaObject, V as VideoMediaObject, d as StickerMediaObject, c as MessageTemplateObject, e as TextObject } from '../../../common-BiRA_uz3.js';
1
+ import { N as NameObject, h as AddressesObject, C as ContactObject, f as InteractiveObject, L as LocationObject, A as AudioMediaObject, D as DocumentMediaObject, I as ImageMediaObject, V as VideoMediaObject, e as StickerMediaObject, g as MessageTemplateObject, d as TextObject } from '../../../common-CzzMWFoO.js';
2
2
  import { I as InteractiveTypesEnum, P as ParametersTypesEnum, i as CurrencyCodesEnum, C as ComponentTypesEnum } from '../../../enums-BZd9T2ul.js';
3
3
  import '../../../base-CdGDdVEl.js';
4
4
  import '../../../types/config.js';
@@ -1,5 +1,5 @@
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';
1
+ import { M as MessagesApi } from '../../MessageApi-D-9SuL4w.js';
2
+ export { A as AudioMediaObject, C as ContactObject, D as DocumentMediaObject, I as ImageMediaObject, f as InteractiveObject, L as LocationObject, a as MessageRequestParams, g as MessageTemplateObject, c as MessagesResponse, R as ReactionParams, S as StatusParams, e as StickerMediaObject, T as TextMessageParams, d as TextObject, V as VideoMediaObject } from '../../common-CzzMWFoO.js';
3
3
  import '../../base-CdGDdVEl.js';
4
4
  import '../../types/config.js';
5
5
  import '../../enums-BZd9T2ul.js';
@@ -1,5 +1,5 @@
1
- import { B as BusinessProfileApi } from '../../BusinessProfileApi-WXscSgo-.js';
2
- export { a as BusinessProfileClass, b as BusinessProfileData, c as BusinessProfileField, d as BusinessProfileFieldsParam, e as BusinessProfileResponse, C as CreateUploadSessionParams, G as GetUploadHandleParams, U as UpdateBusinessProfileRequest, f as UploadBusinessProfileResponse, g as UploadHandle, h as UploadMediaParams, i as UploadSession, j as UploadSessionResponse } from '../../BusinessProfileApi-WXscSgo-.js';
1
+ import { B as BusinessProfileApi } from '../../BusinessProfileApi-CW0emncx.js';
2
+ export { e as BusinessProfileClass, a as BusinessProfileData, c as BusinessProfileField, d as BusinessProfileFieldsParam, b as BusinessProfileResponse, C as CreateUploadSessionParams, G as GetUploadHandleParams, U as UpdateBusinessProfileRequest, f as UploadBusinessProfileResponse, g as UploadHandle, h as UploadMediaParams, i as UploadSession, j as UploadSessionResponse } from '../../BusinessProfileApi-CW0emncx.js';
3
3
  import '../../base-CdGDdVEl.js';
4
4
  import '../../types/config.js';
5
5
  import '../../enums-BZd9T2ul.js';
@@ -1,206 +1,12 @@
1
- import { f as TemplateFormat, d as TemplateRequestBody } from '../../TemplateApi-xGgIZt89.js';
2
- export { C as CatalogButton, g as ComponentTypes, h as CopyCodeButton, F as FlowButton, M as MPMButton, q as MediaCarouselCard, O as OTPButton, P as PhoneNumberButton, r as ProductCarouselCard, Q as QuickReplyButton, S as SPMButton, T as TemplateApi, i as TemplateBody, j as TemplateButton, k as TemplateButtons, l as TemplateCarousel, a as TemplateClass, b as TemplateDeleteParams, m as TemplateFooter, c as TemplateGetParams, n as TemplateHeader, o as TemplateHeaderExample, p as TemplateLimitedTimeOffer, e as TemplateResponse, U as URLButton, T as default } from '../../TemplateApi-xGgIZt89.js';
3
- import { L as LanguagesEnum, i as CurrencyCodesEnum, a as CategoryEnum } from '../../enums-BZd9T2ul.js';
1
+ import { o as TemplateRequestBody } from '../../TemplateApi-D4_6LvhN.js';
2
+ export { C as CatalogButton, a as ComponentTypes, b as CopyCodeButton, F as FlowButton, M as MPMButton, q as MediaCarouselCard, O as OTPButton, P as PhoneNumberButton, r as ProductCarouselCard, Q as QuickReplyButton, S as SPMButton, T as TemplateApi, c as TemplateBody, d as TemplateButton, e as TemplateButtons, f as TemplateCarousel, g as TemplateClass, h as TemplateDeleteParams, i as TemplateFooter, j as TemplateFormat, k as TemplateGetParams, l as TemplateHeader, m as TemplateHeaderExample, n as TemplateLimitedTimeOffer, p as TemplateResponse, U as URLButton, T as default } from '../../TemplateApi-D4_6LvhN.js';
3
+ import { A as AuthenticationTemplateOptions, c as CatalogTemplateOptions, d as CouponTemplateOptions, f as LimitedTimeOfferTemplateOptions, i as MPMTemplateOptions, M as MediaCardCarouselTemplateOptions, O as OTPTemplateOptions, P as ProductCardCarouselTemplateOptions, S as SPMTemplateOptions, T as TemplateOptions } from '../../factory-D2eO5etK.js';
4
+ export { B as BodyOptions, a as ButtonOptions, C as CarouselCard, b as CarouselOptions, e as CurrencyParameter, D as DateTimeParameter, F as FooterOptions, H as HeaderOptions, L as LimitedTimeOfferOptions, g as LocationParameter, h as MediaParameter, j as ProductParameter, k as ProductSection, l as TemplateParameter, m as TextParameter } from '../../factory-D2eO5etK.js';
4
5
  import '../../base-CdGDdVEl.js';
5
6
  import '../../types/config.js';
7
+ import '../../enums-BZd9T2ul.js';
6
8
  import '../../request-vYMaEfk5.js';
7
9
 
8
- interface TextParameter {
9
- type: 'text';
10
- value: string;
11
- }
12
- interface CurrencyParameter {
13
- type: 'currency';
14
- amount_1000: number;
15
- code: CurrencyCodesEnum;
16
- fallback_value: string;
17
- }
18
- interface DateTimeParameter {
19
- type: 'date_time';
20
- fallback_value: string;
21
- }
22
- interface MediaParameter {
23
- type: 'image' | 'video' | 'document';
24
- handle?: string;
25
- link?: string;
26
- }
27
- interface LocationParameter {
28
- type: 'location';
29
- latitude?: number;
30
- longitude?: number;
31
- name?: string;
32
- address?: string;
33
- }
34
- interface ProductParameter {
35
- type: 'product';
36
- product_retailer_id: string;
37
- }
38
- type TemplateParameter = TextParameter | CurrencyParameter | DateTimeParameter | MediaParameter | LocationParameter | ProductParameter;
39
- interface HeaderOptions {
40
- format: TemplateFormat;
41
- text?: string;
42
- parameters?: TemplateParameter[];
43
- example?: {
44
- header_text?: string[];
45
- header_text_named_params?: Array<{
46
- param_name: string;
47
- example: string;
48
- }>;
49
- header_handle?: string[];
50
- };
51
- }
52
- interface BodyOptions {
53
- text: string;
54
- parameters?: TemplateParameter[];
55
- example?: {
56
- body_text?: string[][];
57
- body_text_named_params?: Array<{
58
- param_name: string;
59
- example: string;
60
- }>;
61
- };
62
- }
63
- interface FooterOptions {
64
- text: string;
65
- }
66
- interface ButtonOptions {
67
- phone_number?: {
68
- text: string;
69
- phone_number: string;
70
- };
71
- url?: {
72
- text: string;
73
- url: string;
74
- example?: string;
75
- };
76
- quick_reply?: {
77
- text: string;
78
- }[];
79
- copy_code?: {
80
- example: string;
81
- };
82
- flow?: {
83
- text: string;
84
- flow_id?: string;
85
- flow_name?: string;
86
- flow_json?: string;
87
- flow_action?: 'navigate' | 'data_exchange';
88
- navigate_screen?: string;
89
- };
90
- mpm?: boolean;
91
- otp?: boolean;
92
- spm?: boolean;
93
- }
94
- interface CarouselCard {
95
- image?: string;
96
- video?: string;
97
- product?: string;
98
- body?: string;
99
- bodyParameters?: TemplateParameter[];
100
- buttons?: ButtonOptions;
101
- }
102
- interface CarouselOptions {
103
- cards: CarouselCard[];
104
- }
105
- interface LimitedTimeOfferOptions {
106
- expiration_time_ms: number;
107
- }
108
- interface ProductSection {
109
- title?: string;
110
- product_items: Array<{
111
- product_retailer_id: string;
112
- }>;
113
- }
114
- interface TemplateOptions {
115
- name: string;
116
- language: LanguagesEnum;
117
- category: CategoryEnum;
118
- header?: HeaderOptions;
119
- body?: BodyOptions;
120
- footer?: FooterOptions;
121
- buttons?: ButtonOptions;
122
- carousel?: CarouselOptions;
123
- limitedTimeOffer?: LimitedTimeOfferOptions;
124
- }
125
- interface OTPTemplateOptions {
126
- name: string;
127
- language: LanguagesEnum;
128
- code_expiration_minutes?: number;
129
- add_security_recommendation?: boolean;
130
- }
131
- interface AuthenticationTemplateOptions {
132
- name: string;
133
- language: LanguagesEnum;
134
- code_expiration_minutes?: number;
135
- add_security_recommendation?: boolean;
136
- copy_code_button?: boolean;
137
- }
138
- interface CatalogTemplateOptions {
139
- name: string;
140
- language: LanguagesEnum;
141
- header?: Omit<HeaderOptions, 'format'>;
142
- body: BodyOptions;
143
- footer?: FooterOptions;
144
- thumbnail_product_retailer_id: string;
145
- }
146
- interface CouponTemplateOptions {
147
- name: string;
148
- language: LanguagesEnum;
149
- header?: Omit<HeaderOptions, 'format'>;
150
- body: BodyOptions;
151
- footer?: FooterOptions;
152
- coupon_code: string;
153
- }
154
- interface LimitedTimeOfferTemplateOptions {
155
- name: string;
156
- language: LanguagesEnum;
157
- header?: Omit<HeaderOptions, 'format'>;
158
- body: BodyOptions;
159
- footer?: FooterOptions;
160
- expiration_time_ms: number;
161
- }
162
- interface MediaCardCarouselTemplateOptions {
163
- name: string;
164
- language: LanguagesEnum;
165
- cards: Array<{
166
- header: {
167
- format: 'IMAGE' | 'VIDEO';
168
- example: {
169
- header_handle: string[];
170
- };
171
- };
172
- body: BodyOptions;
173
- buttons?: ButtonOptions;
174
- }>;
175
- }
176
- interface MPMTemplateOptions {
177
- name: string;
178
- language: LanguagesEnum;
179
- header?: Omit<HeaderOptions, 'format'>;
180
- body: BodyOptions;
181
- footer?: FooterOptions;
182
- thumbnail_product_retailer_id: string;
183
- sections: ProductSection[];
184
- }
185
- interface ProductCardCarouselTemplateOptions {
186
- name: string;
187
- language: LanguagesEnum;
188
- header?: Omit<HeaderOptions, 'format'>;
189
- body: BodyOptions;
190
- footer?: FooterOptions;
191
- cards: Array<{
192
- product_retailer_id: string;
193
- }>;
194
- }
195
- interface SPMTemplateOptions {
196
- name: string;
197
- language: LanguagesEnum;
198
- header?: Omit<HeaderOptions, 'format'>;
199
- body: BodyOptions;
200
- footer?: FooterOptions;
201
- product_retailer_id: string;
202
- }
203
-
204
10
  declare function createTemplate(options: TemplateOptions): TemplateRequestBody;
205
11
  declare function createOTPTemplate(options: OTPTemplateOptions): TemplateRequestBody;
206
12
  declare function createAuthenticationTemplate(options: AuthenticationTemplateOptions): TemplateRequestBody;
@@ -212,4 +18,4 @@ declare function createMPMTemplate(options: MPMTemplateOptions): TemplateRequest
212
18
  declare function createProductCardCarouselTemplate(options: ProductCardCarouselTemplateOptions): TemplateRequestBody;
213
19
  declare function createSPMTemplate(options: SPMTemplateOptions): TemplateRequestBody;
214
20
 
215
- export { type AuthenticationTemplateOptions, type BodyOptions, type ButtonOptions, type CarouselCard, type CarouselOptions, type CatalogTemplateOptions, type CouponTemplateOptions, type CurrencyParameter, type DateTimeParameter, type FooterOptions, type HeaderOptions, type LimitedTimeOfferOptions, type LimitedTimeOfferTemplateOptions, type LocationParameter, type MPMTemplateOptions, type MediaCardCarouselTemplateOptions, type MediaParameter, type OTPTemplateOptions, type ProductCardCarouselTemplateOptions, type ProductParameter, type ProductSection, type SPMTemplateOptions, TemplateFormat, type TemplateOptions, type TemplateParameter, TemplateRequestBody, type TextParameter, createAuthenticationTemplate, createCatalogTemplate, createCouponTemplate, createLimitedTimeOfferTemplate, createMPMTemplate, createMediaCardCarouselTemplate, createOTPTemplate, createProductCardCarouselTemplate, createSPMTemplate, createTemplate };
21
+ export { AuthenticationTemplateOptions, CatalogTemplateOptions, CouponTemplateOptions, LimitedTimeOfferTemplateOptions, MPMTemplateOptions, MediaCardCarouselTemplateOptions, OTPTemplateOptions, ProductCardCarouselTemplateOptions, SPMTemplateOptions, TemplateOptions, TemplateRequestBody, createAuthenticationTemplate, createCatalogTemplate, createCouponTemplate, createLimitedTimeOfferTemplate, createMPMTemplate, createMediaCardCarouselTemplate, createOTPTemplate, createProductCardCarouselTemplate, createSPMTemplate, createTemplate };
@@ -1,5 +1,5 @@
1
- import { W as WabaApi } from '../../WabaApi-DqQi_68m.js';
2
- export { U as UpdateWabaSubscription, b as WABAClass, a as WabaAccount, c as WabaSubscriptions } from '../../WabaApi-DqQi_68m.js';
1
+ import { W as WabaApi } from '../../WabaApi-BvY1JVRH.js';
2
+ export { U as UpdateWabaSubscription, b as WABAClass, a as WabaAccount, d as WabaSubscriptions } from '../../WabaApi-BvY1JVRH.js';
3
3
  import '../../base-CdGDdVEl.js';
4
4
  import '../../types/config.js';
5
5
  import '../../enums-BZd9T2ul.js';
@@ -0,0 +1,2 @@
1
+ import {d,c}from'./chunk-U5FBZ6UB.js';var n=class{processor;constructor(e){this.processor=new d(e);}async processVerification(e,s,o){return await this.processor.processVerification(e,s,o)}async processWebhook(e){return await this.processor.processWebhook(e)}async processFlow(e){return await this.processor.processFlow(e)}constructFullUrl(e,s=""){return c(e,s)}applyHeaders(e,s){s.setHeader&&Object.entries(e.headers).forEach(([o,r])=>{s.setHeader(o,r);});}async autoRoute(e,s,...o){switch(e.method?.toUpperCase()){case "GET":return await this.handleGet(e,s,...o);case "POST":return await this.handlePost(e,s,...o);default:if(s.status&&s.json)return s.status(405).json({error:"Method Not Allowed"});throw new Error("Method Not Allowed")}}get webhookProcessor(){return this.processor}};export{n as a};//# sourceMappingURL=chunk-5577QQ7V.js.map
2
+ //# sourceMappingURL=chunk-5577QQ7V.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/webhook/frameworks/handler.ts"],"names":["BaseWebhookHandler","config","WebhookProcessor","mode","token","challenge","request","headers","url","constructFullUrl","result","res","key","value","req","args"],"mappings":"sCAqCO,IAAeA,CAAAA,CAAf,KAAgG,CACzF,SAAA,CAEV,YAAYC,CAAAA,CAA2B,CACnC,IAAA,CAAK,SAAA,CAAY,IAAIC,CAAAA,CAAiBD,CAAM,EAChD,CAuBA,MAAgB,mBAAA,CACZE,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACsB,CACtB,OAAO,MAAM,IAAA,CAAK,SAAA,CAAU,oBAAoBF,CAAAA,CAAMC,CAAAA,CAAOC,CAAS,CAC1E,CAKA,MAAgB,cAAA,CAAeC,CAAAA,CAA0C,CACrE,OAAO,MAAM,IAAA,CAAK,SAAA,CAAU,cAAA,CAAeA,CAAO,CACtD,CAKA,MAAgB,WAAA,CAAYA,EAA0C,CAClE,OAAO,MAAM,IAAA,CAAK,UAAU,WAAA,CAAYA,CAAO,CACnD,CAKU,iBAAiBC,CAAAA,CAAwDC,CAAAA,CAAc,EAAA,CAAY,CACzG,OAAOC,CAAAA,CAAiBF,CAAAA,CAASC,CAAG,CACxC,CAKU,YAAA,CAAaE,CAAAA,CAAuBC,CAAAA,CAAsB,CAC5DA,EAAI,SAAA,EACJ,MAAA,CAAO,OAAA,CAAQD,CAAAA,CAAO,OAAO,CAAA,CAAE,OAAA,CAAQ,CAAC,CAACE,EAAKC,CAAK,CAAA,GAAM,CACrDF,CAAAA,CAAI,UAAWC,CAAAA,CAAKC,CAAK,EAC7B,CAAC,EAET,CAKA,MAAgB,SAAA,CAAUC,CAAAA,CAAeH,KAAmBI,CAAAA,CAA2B,CAGnF,OAFeD,CAAAA,CAAI,QAAQ,WAAA,EAAY,EAGnC,KAAK,MACD,OAAO,MAAM,IAAA,CAAK,SAAA,CAAUA,EAAKH,CAAAA,CAAK,GAAGI,CAAI,CAAA,CACjD,KAAK,MAAA,CACD,OAAO,MAAM,IAAA,CAAK,WAAWD,CAAAA,CAAKH,CAAAA,CAAK,GAAGI,CAAI,EAClD,QACI,GAAIJ,CAAAA,CAAI,MAAA,EAAUA,EAAI,IAAA,CAClB,OAAOA,CAAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK,CAAE,KAAA,CAAO,oBAAqB,CAAC,CAAA,CAE/D,MAAM,IAAI,MAAM,oBAAoB,CAC5C,CACJ,CAKA,IAAI,gBAAA,EAAqC,CACrC,OAAO,IAAA,CAAK,SAChB,CAaJ","file":"chunk-5577QQ7V.js","sourcesContent":["import { WhatsAppConfig } from '../../../types/config';\nimport { WebhookProcessor } from '../WebhookProcessor';\nimport { constructFullUrl } from '../utils/webhookUtils';\n\n// Generic request/response interfaces for framework abstraction\nexport interface BaseRequest {\n method?: string;\n url?: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query?: Record<string, any> | URLSearchParams;\n rawBody?: any;\n}\n\nexport interface BaseResponse<T = any> {\n status(code: number): T;\n json?(data: any): T | void;\n send?(data?: any): T | void;\n setHeader?(name: string, value: string): void;\n}\n\n// Base configuration interface\nexport interface BaseWebhookConfig extends WhatsAppConfig {\n // Framework-specific configs can extend this\n}\n\n// Response result interface for consistent return types\nexport interface WebhookResult {\n status: number;\n headers: Record<string, string>;\n body: any;\n}\n\n/**\n * Abstract base class for framework-agnostic webhook handlers\n * Provides common architecture and functionality across all frameworks\n */\nexport abstract class BaseWebhookHandler<TRequest extends BaseRequest, TResponse extends BaseResponse> {\n protected processor: WebhookProcessor;\n\n constructor(config: BaseWebhookConfig) {\n this.processor = new WebhookProcessor(config);\n }\n\n /**\n * Abstract method for handling GET requests (webhook verification)\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handleGet(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Abstract method for handling POST requests (webhook processing)\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handlePost(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Abstract method for handling flow requests\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handleFlow(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Common webhook verification logic\n */\n protected async processVerification(\n mode: string | null,\n token: string | null,\n challenge: string | null,\n ): Promise<WebhookResult> {\n return await this.processor.processVerification(mode, token, challenge);\n }\n\n /**\n * Common webhook processing logic\n */\n protected async processWebhook(request: Request): Promise<WebhookResult> {\n return await this.processor.processWebhook(request);\n }\n\n /**\n * Common flow processing logic\n */\n protected async processFlow(request: Request): Promise<WebhookResult> {\n return await this.processor.processFlow(request);\n }\n\n /**\n * Helper to construct full URL from headers and path\n */\n protected constructFullUrl(headers: Record<string, string | string[] | undefined>, url: string = ''): string {\n return constructFullUrl(headers, url);\n }\n\n /**\n * Helper to apply result headers to response\n */\n protected applyHeaders(result: WebhookResult, res: TResponse): void {\n if (res.setHeader) {\n Object.entries(result.headers).forEach(([key, value]) => {\n res.setHeader!(key, value);\n });\n }\n }\n\n /**\n * Auto-routing method handler that dispatches based on request method\n */\n protected async autoRoute(req: TRequest, res: TResponse, ...args: any[]): Promise<any> {\n const method = req.method?.toUpperCase();\n\n switch (method) {\n case 'GET':\n return await this.handleGet(req, res, ...args);\n case 'POST':\n return await this.handlePost(req, res, ...args);\n default:\n if (res.status && res.json) {\n return res.status(405).json({ error: 'Method Not Allowed' });\n }\n throw new Error('Method Not Allowed');\n }\n }\n\n /**\n * Get the processor instance for handler registration\n */\n get webhookProcessor(): WebhookProcessor {\n return this.processor;\n }\n\n /**\n * Abstract method to return the clean handler object\n * Each framework implements this to return their specific handler structure\n */\n abstract getHandlers(): {\n GET: (...args: any[]) => Promise<any>;\n POST: (...args: any[]) => Promise<any>;\n webhook: (...args: any[]) => Promise<any>;\n flow: (...args: any[]) => Promise<any>;\n processor: WebhookProcessor;\n };\n}\n"]}
@@ -1,2 +1,2 @@
1
- function c(n){return typeof n=="object"&&n!==null}function o(n){return typeof n=="string"}var f=["data_exchange","INIT","BACK"],E=["data_exchange","INIT"];function w(n){if(!("flow_token"in n&&o(n.flow_token)&&"action"in n))return false;let{action:e,version:i,screen:t,data:s}=n,r=i==="3.0",a=f.includes(e),l=typeof t>"u"||o(t)&&t!=="SUCCESS",u=e==="data_exchange"||c(s);return r&&a&&l&&u}function A(n){if(!("flow_token"in n&&o(n.flow_token)&&"action"in n))return false;let{action:e,screen:i,data:t}=n,s=E.includes(e),r=o(i),a=c(t)&&"error_key"in t&&o(t.error)&&"error_message"in t&&o(t.error_message);return s&&r&&a}function d(n){return "action"in n&&n.action==="ping"}export{w as a,A as b,d as c};//# sourceMappingURL=chunk-WGGN32O2.js.map
2
- //# sourceMappingURL=chunk-WGGN32O2.js.map
1
+ function c(n){return typeof n=="object"&&n!==null}function o(n){return typeof n=="string"}var f=["data_exchange","INIT","BACK"],E=["data_exchange","INIT"];function w(n){if(!("flow_token"in n&&o(n.flow_token)&&"action"in n))return false;let{action:e,version:i,screen:t,data:s}=n,r=i==="3.0",a=f.includes(e),l=typeof t>"u"||o(t)&&t!=="SUCCESS",u=e==="data_exchange"||c(s);return r&&a&&l&&u}function A(n){if(!("flow_token"in n&&o(n.flow_token)&&"action"in n))return false;let{action:e,screen:i,data:t}=n,s=E.includes(e),r=o(i),a=c(t)&&"error_key"in t&&o(t.error)&&"error_message"in t&&o(t.error_message);return s&&r&&a}function d(n){return "action"in n&&n.action==="ping"}export{w as a,A as b,d as c};//# sourceMappingURL=chunk-6DFC5L3X.js.map
2
+ //# sourceMappingURL=chunk-6DFC5L3X.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/flowTypeGuards.ts"],"names":["isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest"],"mappings":"AAaA,SAASA,CAAAA,CAASC,CAAAA,CAAkD,CAChE,OAAO,OAAOA,CAAAA,EAAU,QAAA,EAAYA,CAAAA,GAAU,IAClD,CAOA,SAASC,CAAAA,CAASD,CAAAA,CAAiC,CAC/C,OAAO,OAAOA,CAAAA,EAAU,QAC5B,CAGA,IAAME,CAAAA,CAAwB,CAAA,eAAA,CAAA,MAAA,CAAA,MAAuE,CAAA,CAG/FC,EAAgB,CAAA,eAAA,CAAA,MAAkD,CAAA,CASjE,SAASC,CAAAA,CAA0BC,EAKxC,CAEE,GAAI,EAAE,YAAA,GAAgBA,GAAWJ,CAAAA,CAASI,CAAAA,CAAQ,UAAU,CAAA,EAAK,QAAA,GAAYA,CAAAA,CAAAA,CACzE,OAAO,MAAA,CAGX,GAAM,CAAE,MAAA,CAAAC,CAAAA,CAAQ,OAAA,CAAAC,EAAS,MAAA,CAAAC,CAAAA,CAAQ,IAAA,CAAAC,CAAK,EAAIJ,CAAAA,CAGpCK,CAAAA,CAAkBH,CAAAA,GAAY,KAAA,CAG9BI,CAAAA,CAAiBT,CAAAA,CAAsB,QAAA,CAASI,CAAa,EAG7DM,CAAAA,CAAiB,OAAOJ,CAAAA,CAAW,GAAA,EAAgBP,EAASO,CAAM,CAAA,EAAKA,CAAAA,GAAW,SAAA,CAGlFK,EAAeP,CAAAA,GAAW,eAAA,EAAgCP,CAAAA,CAASU,CAAI,CAAA,CAG7E,OAAOC,CAAAA,EAAmBC,CAAAA,EAAkBC,GAAkBC,CAClE,CASO,SAASC,CAAAA,CAAmBT,EAQjC,CAEE,GAAI,EAAE,YAAA,GAAgBA,GAAWJ,CAAAA,CAASI,CAAAA,CAAQ,UAAU,CAAA,EAAK,QAAA,GAAYA,CAAAA,CAAAA,CACzE,OAAO,MAAA,CAGX,GAAM,CAAE,MAAA,CAAAC,CAAAA,CAAQ,MAAA,CAAAE,EAAQ,IAAA,CAAAC,CAAK,CAAA,CAAIJ,CAAAA,CAG3BM,EAAiBR,CAAAA,CAAc,QAAA,CAASG,CAAa,CAAA,CAGrDM,CAAAA,CAAiBX,CAAAA,CAASO,CAAM,CAAA,CAGhCK,EACFd,CAAAA,CAASU,CAAI,CAAA,EACb,WAAA,GAAeA,GACfR,CAAAA,CAASQ,CAAAA,CAAK,KAAK,CAAA,EACnB,kBAAmBA,CAAAA,EACnBR,CAAAA,CAASQ,CAAAA,CAAK,aAAa,CAAA,CAG/B,OAAOE,CAAAA,EAAkBC,CAAAA,EAAkBC,CAC/C,CASO,SAASE,CAAAA,CAAkBV,CAAAA,CAAiE,CAE/F,OAAO,QAAA,GAAYA,CAAAA,EAAWA,CAAAA,CAAQ,SAAW,MACrD","file":"chunk-6DFC5L3X.js","sourcesContent":["import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '../api/flow/types';\n\n/**\n * Helper function to check if a value is an object\n * @param value The value to check\n * @returns True if the value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Helper function to check if a value is a string\n * @param value The value to check\n * @returns True if the value is a string\n */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n// Array of allowed action types for data exchange requests\nconst DATA_EXCHANGE_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK] as const;\n\n// Array of allowed action types for error notification requests\nconst ERROR_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT] as const;\n\n/**\n * Type guard to check if a request is a Data Exchange request\n * Validates the request structure according to the Flow API specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Data Exchange request, false otherwise\n */\nexport function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {\n action: (typeof DATA_EXCHANGE_ACTIONS)[number];\n screen?: string;\n flow_token: string;\n data?: Record<string, any>;\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, version, screen, data } = request;\n\n // Validate API version\n const hasValidVersion = version === '3.0';\n\n // Check if the action is one of the allowed actions for data exchange\n const hasValidAction = DATA_EXCHANGE_ACTIONS.includes(action as any);\n\n // Screen is optional, but when present must be a string and not 'SUCCESS'\n const hasValidScreen = typeof screen === 'undefined' || (isString(screen) && screen !== 'SUCCESS');\n\n // Data is required except for DATA_EXCHANGE action\n const hasValidData = action === FlowActionEnum.DATA_EXCHANGE || isObject(data);\n\n // All conditions must be met for a valid data exchange request\n return hasValidVersion && hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is an Error Notification request\n * Validates the request structure according to the Flow API error specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Error Notification request, false otherwise\n */\nexport function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {\n action: (typeof ERROR_ACTIONS)[number];\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, screen, data } = request;\n\n // Check if the action is one of the allowed actions for error notifications\n const hasValidAction = ERROR_ACTIONS.includes(action as any);\n\n // Screen is required for error notifications\n const hasValidScreen = isString(screen);\n\n // Validate error data structure\n const hasValidData =\n isObject(data) &&\n 'error_key' in data &&\n isString(data.error) &&\n 'error_message' in data &&\n isString(data.error_message);\n\n // All conditions must be met for a valid error notification request\n return hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is a Ping (health check) request\n * Simple validation for health check endpoints in the Flow API\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a Ping request, false otherwise\n */\nexport function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest {\n // A ping request only requires the 'action' field with value 'ping'\n return 'action' in request && request.action === 'ping';\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import {a as a$1}from'./chunk-5577QQ7V.js';var a=class extends a$1{constructor(e){super(e);}async parseRequestBody(e){if(e.method==="POST"&&!e.body){let s=[];if(typeof e[Symbol.asyncIterator]=="function"){for await(let o of e)s.push(o);let t=Buffer.concat(s).toString();if(t.trim())try{e.body=JSON.parse(t);}catch{throw new Error("Invalid JSON in request body")}else e.body={};}}}async handleGet(e,s){try{let{"hub.mode":t,"hub.verify_token":o,"hub.challenge":r}=e.query,n=await this.processVerification(t||null,o||null,r||null);return this.applyHeaders(n,s),s.status(n.status).send(n.body)}catch(t){return console.error("Webhook verification error:",t),s.status(500).json({error:"Internal Server Error"})}}async handlePost(e,s){try{await this.parseRequestBody(e);}catch(t){return console.error("Webhook processing error:",t),t instanceof Error&&t.message==="Invalid JSON in request body"?s.status(400).json({error:"Invalid JSON"}):s.status(500).json({error:"Internal Server Error"})}try{let t=this.constructFullUrl(e.headers,e.url),o=new Request(t,{method:"POST",headers:e.headers,body:JSON.stringify(e.body)}),r=await this.processWebhook(o);return this.applyHeaders(r,s),s.status(r.status).send(r.body)}catch(t){return console.error("Webhook processing error:",t),s.status(500).json({error:"Internal Server Error"})}}async handleFlow(e,s){try{let t=this.constructFullUrl(e.headers,e.url),o=new Request(t,{method:e.method,headers:e.headers,body:e.method==="POST"?JSON.stringify(e.body):void 0}),r=await this.processFlow(o);return this.applyHeaders(r,s),s.status(r.status).send(r.body)}catch(t){return console.error("Flow error:",t),s.status(500).json({error:"Internal Server Error"})}}getHandlers(){return {GET:(e,s)=>this.handleGet(e,s),POST:(e,s)=>this.handlePost(e,s),webhook:(e,s)=>this.autoRoute(e,s),flow:(e,s)=>this.handleFlow(e,s),processor:this.webhookProcessor}}};function p(i){return new a(i).getHandlers()}export{p as a};//# sourceMappingURL=chunk-GM63NGNV.js.map
2
+ //# sourceMappingURL=chunk-GM63NGNV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/webhook/frameworks/nextjs.ts"],"names":["NextJsWebhookHandler","BaseWebhookHandler","config","req","chunks","chunk","body","res","mode","token","challenge","result","error","fullUrl","webRequest","webhookHandler"],"mappings":"2CA0BA,IAAMA,CAAAA,CAAN,cAGUC,GAAwC,CAC9C,YAAYC,CAAAA,CAA6B,CACrC,MAAMA,CAAM,EAChB,CAGA,MAAc,gBAAA,CAAiBC,EAA8B,CACzD,GAAIA,EAAI,MAAA,GAAW,MAAA,EAAU,CAACA,CAAAA,CAAI,IAAA,CAAM,CACpC,IAAMC,CAAAA,CAAmB,EAAC,CAG1B,GAAI,OAAQD,CAAAA,CAAY,MAAA,CAAO,aAAa,CAAA,EAAM,UAAA,CAAY,CAC1D,UAAA,IAAiBE,CAAAA,IAASF,EACtBC,CAAAA,CAAO,IAAA,CAAKC,CAAK,CAAA,CAGrB,IAAMC,CAAAA,CAAO,MAAA,CAAO,MAAA,CAAOF,CAAM,EAAE,QAAA,EAAS,CAG5C,GAAIE,CAAAA,CAAK,IAAA,GACL,GAAI,CACAH,EAAI,IAAA,CAAO,IAAA,CAAK,MAAMG,CAAI,EAC9B,MAAgB,CACZ,MAAM,IAAI,KAAA,CAAM,8BAA8B,CAClD,CAAA,KAEAH,CAAAA,CAAI,KAAO,GAEnB,CACJ,CACJ,CAEA,MAAgB,SAAA,CAAUA,CAAAA,CAAeI,EAA8B,CACnE,GAAI,CACA,GAAM,CAAE,WAAYC,CAAAA,CAAM,kBAAA,CAAoBC,EAAO,eAAA,CAAiBC,CAAU,CAAA,CAAIP,CAAAA,CAAI,KAAA,CAElFQ,CAAAA,CAAS,MAAM,IAAA,CAAK,mBAAA,CACrBH,GAAmB,IAAA,CACnBC,CAAAA,EAAoB,KACpBC,CAAAA,EAAwB,IAC7B,EAEA,OAAA,IAAA,CAAK,YAAA,CAAaC,EAAQJ,CAAG,CAAA,CACtBA,EAAI,MAAA,CAAOI,CAAAA,CAAO,MAAM,CAAA,CAAE,IAAA,CAAKA,EAAO,IAAI,CACrD,OAASC,CAAAA,CAAO,CACZ,eAAQ,KAAA,CAAM,6BAAA,CAA+BA,CAAK,CAAA,CAC3CL,CAAAA,CAAI,OAAO,GAAG,CAAA,CAAE,KAAK,CAAE,KAAA,CAAO,uBAAwB,CAAC,CAClE,CACJ,CAEA,MAAgB,UAAA,CAAWJ,CAAAA,CAAeI,CAAAA,CAA8B,CACpE,GAAI,CAEA,MAAM,KAAK,gBAAA,CAAiBJ,CAAG,EACnC,CAAA,MAASS,CAAAA,CAAO,CAIZ,OAHA,OAAA,CAAQ,MAAM,2BAAA,CAA6BA,CAAK,EAG5CA,CAAAA,YAAiB,KAAA,EAASA,EAAM,OAAA,GAAY,8BAAA,CACrCL,CAAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,KAAK,CAAE,KAAA,CAAO,cAAe,CAAC,CAAA,CAGlDA,EAAI,MAAA,CAAO,GAAG,EAAE,IAAA,CAAK,CAAE,MAAO,uBAAwB,CAAC,CAClE,CAEA,GAAI,CACA,IAAMM,CAAAA,CAAU,IAAA,CAAK,gBAAA,CAAiBV,CAAAA,CAAI,OAAA,CAASA,EAAI,GAAG,CAAA,CAEpDW,EAAa,IAAI,OAAA,CAAQD,EAAS,CACpC,MAAA,CAAQ,OACR,OAAA,CAASV,CAAAA,CAAI,QACb,IAAA,CAAM,IAAA,CAAK,UAAUA,CAAAA,CAAI,IAAI,CACjC,CAAC,CAAA,CAEKQ,EAAS,MAAM,IAAA,CAAK,eAAeG,CAAU,CAAA,CACnD,YAAK,YAAA,CAAaH,CAAAA,CAAQJ,CAAG,CAAA,CACtBA,CAAAA,CAAI,OAAOI,CAAAA,CAAO,MAAM,EAAE,IAAA,CAAKA,CAAAA,CAAO,IAAI,CACrD,CAAA,MAASC,EAAO,CACZ,OAAA,OAAA,CAAQ,KAAA,CAAM,2BAAA,CAA6BA,CAAK,CAAA,CACzCL,EAAI,MAAA,CAAO,GAAG,EAAE,IAAA,CAAK,CAAE,MAAO,uBAAwB,CAAC,CAClE,CACJ,CAEA,MAAgB,UAAA,CAAWJ,CAAAA,CAAeI,EAA8B,CACpE,GAAI,CACA,IAAMM,CAAAA,CAAU,IAAA,CAAK,gBAAA,CAAiBV,CAAAA,CAAI,OAAA,CAASA,EAAI,GAAG,CAAA,CAEpDW,EAAa,IAAI,OAAA,CAAQD,EAAS,CACpC,MAAA,CAAQV,EAAI,MAAA,CACZ,OAAA,CAASA,EAAI,OAAA,CACb,IAAA,CAAMA,EAAI,MAAA,GAAW,MAAA,CAAS,KAAK,SAAA,CAAUA,CAAAA,CAAI,IAAI,CAAA,CAAI,KAAA,CAC7D,CAAC,EAEKQ,CAAAA,CAAS,MAAM,KAAK,WAAA,CAAYG,CAAU,EAChD,OAAA,IAAA,CAAK,YAAA,CAAaH,EAAQJ,CAAG,CAAA,CACtBA,EAAI,MAAA,CAAOI,CAAAA,CAAO,MAAM,CAAA,CAAE,IAAA,CAAKA,EAAO,IAAI,CACrD,OAASC,CAAAA,CAAO,CACZ,eAAQ,KAAA,CAAM,aAAA,CAAeA,CAAK,CAAA,CAC3BL,CAAAA,CAAI,OAAO,GAAG,CAAA,CAAE,KAAK,CAAE,KAAA,CAAO,uBAAwB,CAAC,CAClE,CACJ,CAEA,WAAA,EAAc,CACV,OAAO,CAEH,GAAA,CAAK,CAACJ,CAAAA,CAAeI,CAAAA,GAAmB,KAAK,SAAA,CAAUJ,CAAAA,CAAKI,CAAG,CAAA,CAC/D,IAAA,CAAM,CAACJ,CAAAA,CAAeI,CAAAA,GAAmB,KAAK,UAAA,CAAWJ,CAAAA,CAAKI,CAAG,CAAA,CAGjE,OAAA,CAAS,CAACJ,CAAAA,CAAeI,CAAAA,GAAmB,KAAK,SAAA,CAAUJ,CAAAA,CAAKI,CAAG,CAAA,CAGnE,IAAA,CAAM,CAACJ,EAAeI,CAAAA,GAAmB,IAAA,CAAK,WAAWJ,CAAAA,CAAKI,CAAG,EAGjE,SAAA,CAAW,IAAA,CAAK,gBACpB,CACJ,CACJ,EAGO,SAASQ,CAAAA,CACZb,EACF,CAEE,OADgB,IAAIF,CAAAA,CAA0CE,CAAM,CAAA,CACrD,WAAA,EACnB","file":"chunk-GM63NGNV.js","sourcesContent":["import { BaseRequest, BaseResponse, BaseWebhookConfig, BaseWebhookHandler } from './handler';\n\n// Next.js specific interfaces\nexport interface BaseApiRequest extends BaseRequest {\n method?: string;\n url?: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query: Partial<Record<string, string | string[]>>;\n rawBody?: any;\n}\n\nexport interface BaseApiResponse extends BaseResponse {\n status(code: number): any;\n json(data: any): void | any;\n send(data?: any): void | any;\n setHeader(name: string, value: string): void;\n}\n\nexport interface NextJsWebhookConfig extends BaseWebhookConfig {\n // Next.js specific config can be added here\n}\n\n/**\n * Next.js Page Router webhook handler extending the base handler\n */\nclass NextJsWebhookHandler<\n TRequest extends BaseApiRequest,\n TResponse extends BaseApiResponse,\n> extends BaseWebhookHandler<TRequest, TResponse> {\n constructor(config: NextJsWebhookConfig) {\n super(config);\n }\n\n // Helper function to parse request body for POST requests\n private async parseRequestBody(req: TRequest): Promise<void> {\n if (req.method === 'POST' && !req.body) {\n const chunks: Buffer[] = [];\n\n // Check if req is a stream (has Symbol.asyncIterator)\n if (typeof (req as any)[Symbol.asyncIterator] === 'function') {\n for await (const chunk of req as any) {\n chunks.push(chunk);\n }\n\n const body = Buffer.concat(chunks).toString();\n\n // Only attempt to parse if there's actual content\n if (body.trim()) {\n try {\n req.body = JSON.parse(body);\n } catch (error) {\n throw new Error('Invalid JSON in request body');\n }\n } else {\n req.body = {};\n }\n }\n }\n }\n\n protected async handleGet(req: TRequest, res: TResponse): Promise<any> {\n try {\n const { 'hub.mode': mode, 'hub.verify_token': token, 'hub.challenge': challenge } = req.query;\n\n const result = await this.processVerification(\n (mode as string) || null,\n (token as string) || null,\n (challenge as string) || null,\n );\n\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n console.error('Webhook verification error:', error);\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n }\n\n protected async handlePost(req: TRequest, res: TResponse): Promise<any> {\n try {\n // Auto-parse body if needed\n await this.parseRequestBody(req);\n } catch (error) {\n console.error('Webhook processing error:', error);\n\n // Handle JSON parsing errors specifically\n if (error instanceof Error && error.message === 'Invalid JSON in request body') {\n return res.status(400).json({ error: 'Invalid JSON' });\n }\n\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n const webRequest = new Request(fullUrl, {\n method: 'POST',\n headers: req.headers as HeadersInit,\n body: JSON.stringify(req.body),\n });\n\n const result = await this.processWebhook(webRequest);\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n console.error('Webhook processing error:', error);\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n }\n\n protected async handleFlow(req: TRequest, res: TResponse): Promise<any> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n const webRequest = new Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: req.method === 'POST' ? JSON.stringify(req.body) : undefined,\n });\n\n const result = await this.processFlow(webRequest);\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n console.error('Flow error:', error);\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n }\n\n getHandlers() {\n return {\n // Method handlers for clean destructuring\n GET: (req: TRequest, res: TResponse) => this.handleGet(req, res),\n POST: (req: TRequest, res: TResponse) => this.handlePost(req, res),\n\n // Auto-routing webhook handler\n webhook: (req: TRequest, res: TResponse) => this.autoRoute(req, res),\n\n // Flow handler\n flow: (req: TRequest, res: TResponse) => this.handleFlow(req, res),\n\n // Expose processor for handler registration\n processor: this.webhookProcessor,\n };\n }\n}\n\n// Generic webhook handler that accepts any compatible request/response types\nexport function webhookHandler<TRequest extends BaseApiRequest, TResponse extends BaseApiResponse>(\n config: NextJsWebhookConfig,\n) {\n const handler = new NextJsWebhookHandler<TRequest, TResponse>(config);\n return handler.getHandlers();\n}\n"]}
@@ -0,0 +1,2 @@
1
+ var s=(o=>(o.Draft="DRAFT",o.Published="PUBLISHED",o.Throttled="THROTTLED",o.Blocked="BLOCKED",o.Deprecated="DEPRECATED",o))(s||{}),n=(e=>(e.SignUp="SIGN_UP",e.SignIn="SIGN_IN",e.AppointmentBooking="APPOINTMENT_BOOKING",e.LeadGeneration="LEAD_GENERATION",e.ContactUs="CONTACT_US",e.CustomerSupport="CUSTOMER_SUPPORT",e.Survey="SURVEY",e.Other="OTHER",e))(n||{}),i=(t=>(t.INIT="INIT",t.BACK="BACK",t.DATA_EXCHANGE="data_exchange",t))(i||{}),a=(r=>(r.Ping="ping",r.Change="data_exchange",r.Error="error",r.All="*",r))(a||{});export{s as a,n as b,i as c,a as d};//# sourceMappingURL=chunk-J2JPTKU6.js.map
2
+ //# sourceMappingURL=chunk-J2JPTKU6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/api/flow/types/common.ts"],"names":["FlowStatusEnum","FlowCategoryEnum","FlowActionEnum","FlowTypeEnum"],"mappings":"AAMO,IAAKA,CAAAA,CAAAA,CAAAA,CAAAA,GACRA,CAAAA,CAAA,KAAA,CAAQ,OAAA,CACRA,EAAA,SAAA,CAAY,WAAA,CACZA,CAAAA,CAAA,SAAA,CAAY,WAAA,CACZA,CAAAA,CAAA,OAAA,CAAU,SAAA,CACVA,EAAA,UAAA,CAAa,YAAA,CALLA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAAA,CAAA,CAWAC,CAAAA,CAAAA,CAAAA,CAAAA,GACRA,CAAAA,CAAA,MAAA,CAAS,SAAA,CACTA,EAAA,MAAA,CAAS,SAAA,CACTA,CAAAA,CAAA,kBAAA,CAAqB,sBACrBA,CAAAA,CAAA,cAAA,CAAiB,iBAAA,CACjBA,CAAAA,CAAA,UAAY,YAAA,CACZA,CAAAA,CAAA,eAAA,CAAkB,kBAAA,CAClBA,CAAAA,CAAA,MAAA,CAAS,QAAA,CACTA,CAAAA,CAAA,MAAQ,OAAA,CARAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAAA,CAAA,CAWAC,CAAAA,CAAAA,CAAAA,CAAAA,GACRA,CAAAA,CAAA,IAAA,CAAO,MAAA,CACPA,CAAAA,CAAA,KAAO,MAAA,CACPA,CAAAA,CAAA,aAAA,CAAgB,eAAA,CAHRA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAAA,CAAA,CAUAC,CAAAA,CAAAA,CAAAA,CAAAA,GAERA,CAAAA,CAAA,KAAO,MAAA,CAEPA,CAAAA,CAAA,MAAA,CAAS,eAAA,CAETA,EAAA,KAAA,CAAQ,OAAA,CAERA,CAAAA,CAAA,GAAA,CAAM,IAREA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAAA","file":"chunk-J2JPTKU6.js","sourcesContent":["import { ResponseSuccess } from '../../../types';\nimport { IncomingHttpHeaders, IncomingMessage } from 'http';\n\n/**\n * Enum for Flow Status\n */\nexport enum FlowStatusEnum {\n Draft = 'DRAFT',\n Published = 'PUBLISHED',\n Throttled = 'THROTTLED',\n Blocked = 'BLOCKED',\n Deprecated = 'DEPRECATED',\n}\n\n/**\n * Enum for Flow Categories\n */\nexport enum FlowCategoryEnum {\n SignUp = 'SIGN_UP',\n SignIn = 'SIGN_IN',\n AppointmentBooking = 'APPOINTMENT_BOOKING',\n LeadGeneration = 'LEAD_GENERATION',\n ContactUs = 'CONTACT_US',\n CustomerSupport = 'CUSTOMER_SUPPORT',\n Survey = 'SURVEY',\n Other = 'OTHER',\n}\n\nexport enum FlowActionEnum {\n INIT = 'INIT',\n BACK = 'BACK',\n DATA_EXCHANGE = 'data_exchange',\n}\n\n/**\n * Enum for Flow Types in webhook handlers\n * Used to register handlers for specific flow events\n */\nexport enum FlowTypeEnum {\n /** Health check/ping requests */\n Ping = 'ping',\n /** Data exchange requests */\n Change = 'data_exchange',\n /** Error notification requests */\n Error = 'error',\n /** Match all flow action types */\n All = '*',\n}\n\nexport type FlowType = (typeof FlowTypeEnum)[keyof typeof FlowTypeEnum];\n\n/**\n * Flow Validation Error Pointer\n */\nexport interface FlowValidationErrorPointer {\n line_start: number;\n line_end: number;\n column_start: number;\n column_end: number;\n path: string;\n}\n\n/**\n * Flow Validation Error\n */\nexport interface FlowValidationError {\n error: string;\n error_type: string;\n message: string;\n line_start: number;\n line_end: number;\n column_start: number;\n column_end: number;\n pointers: FlowValidationErrorPointer[];\n}\n\n/**\n * Flow Item\n */\nexport interface Flow {\n id: string;\n name: string;\n status: FlowStatusEnum;\n categories: FlowCategoryEnum[];\n validation_errors: FlowValidationError[];\n}\n\n/**\n * Pagination Cursors\n */\nexport interface PaginationCursors {\n before: string;\n after: string;\n}\n\n/**\n * Pagination Object\n */\nexport interface Pagination {\n cursors: PaginationCursors;\n}\n\n/**\n * Flows List Response\n */\nexport interface FlowsListResponse {\n data: Flow[];\n paging: Pagination;\n}\n\n/**\n * Flow Asset\n */\nexport interface FlowAsset {\n name: string;\n asset_type: string;\n download_url: string;\n}\n\n/**\n * Flow Assets Response\n */\nexport interface FlowAssetsResponse {\n data: FlowAsset[];\n paging: Pagination;\n}\n\n/**\n * Flow Preview\n */\nexport interface FlowPreview {\n preview_url: string;\n expires_at: string;\n}\n\n/**\n * Flow Preview Response\n */\nexport interface FlowPreviewResponse {\n preview: FlowPreview;\n id: string;\n}\n\n/**\n * Flow Migration Result\n */\nexport interface FlowMigrationResult {\n source_name: string;\n source_id: string;\n migrated_id: string;\n}\n\n/**\n * Flow Migration Failure\n */\nexport interface FlowMigrationFailure {\n source_name: string;\n error_code: string;\n error_message: string;\n}\n\n/**\n * Create Flow Response\n */\nexport interface CreateFlowResponse {\n id: string;\n success: boolean;\n validation_errors?: FlowValidationError[];\n}\n\n/**\n * Update Flow Response\n */\nexport interface UpdateFlowResponse {\n success: boolean;\n validation_errors?: FlowValidationError[];\n}\n\n/**\n * Flow Migration Response\n */\nexport interface FlowMigrationResponse {\n migrated_flows: FlowMigrationResult[];\n failed_flows: FlowMigrationFailure[];\n}\n\n/**\n * Validate Flow JSON Response\n */\nexport interface ValidateFlowJsonResponse {\n valid: boolean;\n success: boolean;\n validation_errors?: FlowValidationError[];\n}\n\n/**\n * WhatsApp Flow Endpoint - Encrypted Request Payload\n * Represents the raw encrypted data received from WhatsApp\n */\nexport interface FlowEncryptedRequestPayload {\n encrypted_aes_key: string;\n encrypted_flow_data: string;\n initial_vector: string;\n}\n\n/**\n * WhatsApp Flow Endpoint - Decrypted Request Response\n * Represents the successfully decrypted data and encryption keys\n */\nexport interface FlowDecryptedRequestResponse {\n decryptedBody: any;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n}\n\n/**\n * WhatsApp Flow Endpoint - HTTP Request with Body\n * Represents an HTTP request with the encrypted payload\n */\nexport interface FlowHttpRequest extends IncomingMessage {\n body: FlowEncryptedRequestPayload;\n headers: IncomingHttpHeaders;\n}\n\n/**\n * WhatsApp Flow Endpoint - Health Check Request\n * Represents the structure of a health check request\n */\nexport interface FlowHealthCheckRequest {\n action: 'ping';\n version: '3.0';\n}\n\n/**\n * WhatsApp Flow Endpoint - Health Check Response\n * The expected response structure for health check requests\n */\nexport interface FlowHealthCheckResponse {\n data: {\n status: 'active';\n };\n}\n\n/**\n * WhatsApp Flow Endpoint - Data Exchange Request\n * Represents the structure of a data exchange request\n */\nexport interface FlowDataExchangeRequest {\n version: '3.0';\n action: FlowActionEnum;\n screen: string;\n flow_token: string;\n data?: Record<string, any> & { error_message?: string };\n}\n\n/**\n * WhatsApp Flow Endpoint - Data Exchange Response\n * The expected response structure for data exchange requests\n */\nexport interface FlowDataExchangeResponse {\n screen?: string;\n data?: Record<string, any | { error_message?: string }>;\n}\n\n/**\n * WhatsApp Flow Endpoint - Success Screen Response\n * The expected response structure for success screen requests\n */\nexport interface FlowSuccessScreenResponse {\n screen: 'SUCCESS';\n data: {\n extension_message_response?: {\n params?: {\n flow_token: string;\n [key: string]: string;\n };\n };\n };\n}\n\n/**\n * WhatsApp Flow Endpoint - Error Notification Request\n * Represents the structure of an error notification request\n */\nexport interface FlowErrorNotificationRequest {\n version: '3.0';\n action: Exclude<FlowActionEnum, FlowActionEnum.BACK>;\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n}\n\n/**\n * WhatsApp Flow Endpoint - Error Notification Response\n * The expected response structure for error notification requests\n */\nexport interface FlowErrorNotificationResponse {\n acknowledged: boolean;\n}\n\n/**\n * WhatsApp Flow Endpoint - Comprehensive Request Object\n * A combined type that includes all possible fields from different request types\n * with all fields being optional for flexibility\n */\nexport interface FlowEndpointRequest {\n // Common fields\n version?: '3.0';\n action?: 'ping' | FlowActionEnum;\n\n screen?: string;\n flow_token?: string;\n\n data?: Record<string, any> & {\n error_key?: string;\n error_message?: string;\n };\n}\n\n/**\n * WhatsApp Flow Endpoint - Response\n * Union type for all possible response types from a Flow endpoint\n */\nexport type FlowEndpointResponse =\n | FlowHealthCheckResponse\n | FlowDataExchangeResponse\n | FlowErrorNotificationResponse\n | FlowSuccessScreenResponse;\n\nexport interface FlowClass {\n /**\n * List Flows\n *\n * @param wabaId - The WABA ID\n * @returns Promise with the list of flows\n */\n listFlows(wabaId: string): Promise<FlowsListResponse>;\n\n /**\n * Create Flow\n *\n * @param wabaId - The WABA ID\n * @param data - The flow data including name, categories, endpoint_uri, and optional clone_flow_id\n * @returns Promise with the created flow ID\n */\n createFlow(\n wabaId: string,\n data: {\n name: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n clone_flow_id?: string;\n flow_json?: string;\n publish?: boolean;\n },\n ): Promise<CreateFlowResponse>;\n\n /**\n * Get Flow\n *\n * @param flowId - The flow ID\n * @param fields - Optional fields to return\n * @param dateFormat - Optional date format\n * @returns Promise with the flow details\n */\n getFlow(flowId: string, fields?: string, dateFormat?: string): Promise<Flow | FlowPreviewResponse>;\n\n /**\n * Update Flow Metadata\n *\n * @param flowId - The flow ID\n * @param data - The flow metadata to update\n * @returns Promise with the success status\n */\n updateFlowMetadata(\n flowId: string,\n data: {\n name?: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n application_id?: string;\n },\n ): Promise<ResponseSuccess>;\n\n /**\n * Delete Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n deleteFlow(flowId: string): Promise<ResponseSuccess>;\n\n /**\n * List Assets (Get Flow JSON URL)\n *\n * @param flowId - The flow ID\n * @returns Promise with the list of assets\n */\n listAssets(flowId: string): Promise<FlowAssetsResponse>;\n\n /**\n * Update Flow JSON\n *\n * @param flowId - The flow ID\n * @param data - The asset data including asset_type, file, and name\n * @returns Promise with the success status and validation errors\n */\n updateFlowJson(\n flowId: string,\n data: {\n file: Blob | Buffer | object;\n name?: string;\n },\n ): Promise<UpdateFlowResponse>;\n\n /**\n * Validate Flow JSON by attempting an update without publishing.\n * This is a convenience method; the API doesn't have a dedicated validation endpoint.\n *\n * @param flowId - The ID of the Flow (must exist, can be in DRAFT status).\n * @param flowJsonData - The Flow JSON content as a Buffer, JSON object, or Blob.\n * @returns Promise indicating if the JSON is valid and includes validation errors if any.\n */\n validateFlowJson(flowId: string, flowJsonData: Blob | Buffer | object): Promise<ValidateFlowJsonResponse>;\n\n /**\n * Publish Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n publishFlow(flowId: string): Promise<ResponseSuccess>;\n\n /**\n * Deprecate Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n deprecateFlow(flowId: string): Promise<ResponseSuccess>;\n\n /**\n * Migrate Flows\n *\n * @param wabaId - The destination WABA ID\n * @param data - The migration data including source_waba_id and optional source_flow_names\n * @returns Promise with migration results\n */\n migrateFlows(\n wabaId: string,\n data: {\n source_waba_id: string;\n source_flow_names?: string[];\n },\n ): Promise<FlowMigrationResponse>;\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-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
+ import {c,b,a as a$1}from'./chunk-6DFC5L3X.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-U5FBZ6UB.js.map
3
+ //# sourceMappingURL=chunk-U5FBZ6UB.js.map