meta-cloud-api 0.1.1 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/flow.d.mts +39 -17
- package/dist/api/flow.d.ts +39 -17
- package/dist/api/flow.js +1 -1
- package/dist/api/flow.js.map +1 -1
- package/dist/api/flow.mjs +1 -1
- package/dist/api/flow.mjs.map +1 -1
- package/dist/api/index.js +1 -1
- package/dist/api/index.js.map +1 -1
- package/dist/api/index.mjs +1 -1
- package/dist/api/index.mjs.map +1 -1
- package/dist/api/waba.d.mts +2 -1
- package/dist/api/waba.d.ts +2 -1
- package/dist/api/waba.js +1 -1
- package/dist/api/waba.js.map +1 -1
- package/dist/api/waba.mjs +1 -1
- package/dist/api/waba.mjs.map +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/types/flow.d.mts +35 -10
- package/dist/types/flow.d.ts +35 -10
- package/dist/types/flow.js +1 -1
- package/dist/types/flow.js.map +1 -1
- package/dist/types/flow.mjs +1 -1
- package/dist/types/flow.mjs.map +1 -1
- package/dist/types/index.d.mts +2 -2
- package/dist/types/index.d.ts +2 -2
- package/dist/types/index.js +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/types/index.mjs +1 -1
- package/dist/types/index.mjs.map +1 -1
- package/dist/types/waba.d.mts +61 -7
- package/dist/types/waba.d.ts +61 -7
- package/dist/types/waba.js +1 -1
- package/dist/types/waba.js.map +1 -1
- package/dist/types/waba.mjs +1 -0
- package/dist/types/waba.mjs.map +1 -1
- package/dist/utils/buildFieldsQueryString.d.mts +3 -0
- package/dist/utils/buildFieldsQueryString.d.ts +3 -0
- package/dist/utils/buildFieldsQueryString.js +2 -0
- package/dist/utils/buildFieldsQueryString.js.map +1 -0
- package/dist/utils/buildFieldsQueryString.mjs +2 -0
- package/dist/utils/buildFieldsQueryString.mjs.map +1 -0
- package/dist/whatsapp.js +1 -1
- package/dist/whatsapp.js.map +1 -1
- package/dist/whatsapp.mjs +1 -1
- package/dist/whatsapp.mjs.map +1 -1
- package/package.json +1 -1
package/dist/api/flow.d.mts
CHANGED
|
@@ -19,7 +19,7 @@ declare class FlowAPI extends BaseAPI implements FlowClass {
|
|
|
19
19
|
*
|
|
20
20
|
* @param wabaId - The WABA ID
|
|
21
21
|
* @param data - The flow data including name, categories, endpoint_uri, and optional clone_flow_id
|
|
22
|
-
* @returns Promise with the created flow ID
|
|
22
|
+
* @returns Promise with the created flow ID and validation errors if any
|
|
23
23
|
*/
|
|
24
24
|
createFlow(wabaId: string, data: {
|
|
25
25
|
name: string;
|
|
@@ -34,19 +34,27 @@ declare class FlowAPI extends BaseAPI implements FlowClass {
|
|
|
34
34
|
validation_errors?: FlowValidationError[];
|
|
35
35
|
}>>;
|
|
36
36
|
/**
|
|
37
|
-
* Get Flow
|
|
37
|
+
* Get Flow details
|
|
38
38
|
*
|
|
39
39
|
* @param flowId - The flow ID
|
|
40
|
-
* @param fields - Optional fields to return
|
|
40
|
+
* @param fields - Optional fields to return (e.g., 'name,status,preview.invalidate(false)')
|
|
41
41
|
* @param dateFormat - Optional date format
|
|
42
|
-
* @returns Promise with the flow details
|
|
42
|
+
* @returns Promise with the flow details or preview response
|
|
43
43
|
*/
|
|
44
44
|
getFlow(flowId: string, fields?: string, dateFormat?: string): Promise<RequesterResponseInterface<Flow | FlowPreviewResponse>>;
|
|
45
|
+
/**
|
|
46
|
+
* Get Flow Preview URL
|
|
47
|
+
*
|
|
48
|
+
* @param flowId - The flow ID
|
|
49
|
+
* @param invalidate - Optional. If true, invalidates existing preview and generates a new one. Defaults to false.
|
|
50
|
+
* @returns Promise with the flow preview details
|
|
51
|
+
*/
|
|
52
|
+
getFlowPreview(flowId: string, invalidate?: boolean): Promise<RequesterResponseInterface<FlowPreviewResponse>>;
|
|
45
53
|
/**
|
|
46
54
|
* Update Flow Metadata
|
|
47
55
|
*
|
|
48
56
|
* @param flowId - The flow ID
|
|
49
|
-
* @param data - The flow metadata to update
|
|
57
|
+
* @param data - The flow metadata to update (name, categories, endpoint_uri, application_id)
|
|
50
58
|
* @returns Promise with the success status
|
|
51
59
|
*/
|
|
52
60
|
updateFlowMetadata(flowId: string, data: {
|
|
@@ -56,34 +64,48 @@ declare class FlowAPI extends BaseAPI implements FlowClass {
|
|
|
56
64
|
application_id?: string;
|
|
57
65
|
}): Promise<RequesterResponseInterface<ResponseSuccess>>;
|
|
58
66
|
/**
|
|
59
|
-
* Delete Flow
|
|
67
|
+
* Delete Flow (only works if the Flow is in DRAFT status)
|
|
60
68
|
*
|
|
61
69
|
* @param flowId - The flow ID
|
|
62
70
|
* @returns Promise with the success status
|
|
63
71
|
*/
|
|
64
72
|
deleteFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>>;
|
|
65
73
|
/**
|
|
66
|
-
* List Assets (
|
|
74
|
+
* List Assets (e.g., get Flow JSON download URL)
|
|
67
75
|
*
|
|
68
76
|
* @param flowId - The flow ID
|
|
69
77
|
* @returns Promise with the list of assets
|
|
70
78
|
*/
|
|
71
79
|
listAssets(flowId: string): Promise<RequesterResponseInterface<FlowAssetsResponse>>;
|
|
72
80
|
/**
|
|
73
|
-
* Update Flow JSON
|
|
81
|
+
* Update Flow JSON by uploading a file, buffer, JSON object, or Blob.
|
|
74
82
|
*
|
|
75
83
|
* @param flowId - The flow ID
|
|
76
|
-
* @param data -
|
|
77
|
-
* @
|
|
84
|
+
* @param data - Object containing the file data and optional name.
|
|
85
|
+
* @param data.file - The Flow JSON content as a Buffer, JSON object, or Blob.
|
|
86
|
+
* @param data.name - Optional name for the asset, defaults to 'flow.json'.
|
|
87
|
+
* @returns Promise with the success status and validation errors, if any.
|
|
78
88
|
*/
|
|
79
89
|
updateFlowJson(flowId: string, data: {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
name: string;
|
|
90
|
+
file: Blob | Buffer | object;
|
|
91
|
+
name?: string;
|
|
83
92
|
}): Promise<RequesterResponseInterface<{
|
|
84
93
|
success: boolean;
|
|
85
94
|
validation_errors?: FlowValidationError[];
|
|
86
95
|
}>>;
|
|
96
|
+
/**
|
|
97
|
+
* Validate Flow JSON by attempting an update without publishing.
|
|
98
|
+
* This is a convenience method; the API doesn't have a dedicated validation endpoint.
|
|
99
|
+
*
|
|
100
|
+
* @param flowId - The ID of the Flow (must exist, can be in DRAFT status).
|
|
101
|
+
* @param flowJsonData - The Flow JSON content as a file path (string), Buffer, JSON object, or Blob.
|
|
102
|
+
* @returns Promise indicating if the JSON is valid and includes validation errors if any.
|
|
103
|
+
*/
|
|
104
|
+
validateFlowJson(flowId: string, flowJsonData: Blob | Buffer | object): Promise<RequesterResponseInterface<{
|
|
105
|
+
valid: boolean;
|
|
106
|
+
success: boolean;
|
|
107
|
+
validation_errors?: FlowValidationError[];
|
|
108
|
+
}>>;
|
|
87
109
|
/**
|
|
88
110
|
* Publish Flow
|
|
89
111
|
*
|
|
@@ -99,13 +121,13 @@ declare class FlowAPI extends BaseAPI implements FlowClass {
|
|
|
99
121
|
*/
|
|
100
122
|
deprecateFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>>;
|
|
101
123
|
/**
|
|
102
|
-
* Migrate Flows
|
|
124
|
+
* Migrate Flows between WABAs
|
|
103
125
|
*
|
|
104
|
-
* @param
|
|
126
|
+
* @param destinationWabaId - The destination WABA ID
|
|
105
127
|
* @param data - The migration data including source_waba_id and optional source_flow_names
|
|
106
|
-
* @returns Promise with migration results
|
|
128
|
+
* @returns Promise with migration results (successes and failures)
|
|
107
129
|
*/
|
|
108
|
-
migrateFlows(
|
|
130
|
+
migrateFlows(destinationWabaId: string, data: {
|
|
109
131
|
source_waba_id: string;
|
|
110
132
|
source_flow_names?: string[];
|
|
111
133
|
}): Promise<RequesterResponseInterface<FlowMigrationResponse>>;
|
package/dist/api/flow.d.ts
CHANGED
|
@@ -19,7 +19,7 @@ declare class FlowAPI extends BaseAPI implements FlowClass {
|
|
|
19
19
|
*
|
|
20
20
|
* @param wabaId - The WABA ID
|
|
21
21
|
* @param data - The flow data including name, categories, endpoint_uri, and optional clone_flow_id
|
|
22
|
-
* @returns Promise with the created flow ID
|
|
22
|
+
* @returns Promise with the created flow ID and validation errors if any
|
|
23
23
|
*/
|
|
24
24
|
createFlow(wabaId: string, data: {
|
|
25
25
|
name: string;
|
|
@@ -34,19 +34,27 @@ declare class FlowAPI extends BaseAPI implements FlowClass {
|
|
|
34
34
|
validation_errors?: FlowValidationError[];
|
|
35
35
|
}>>;
|
|
36
36
|
/**
|
|
37
|
-
* Get Flow
|
|
37
|
+
* Get Flow details
|
|
38
38
|
*
|
|
39
39
|
* @param flowId - The flow ID
|
|
40
|
-
* @param fields - Optional fields to return
|
|
40
|
+
* @param fields - Optional fields to return (e.g., 'name,status,preview.invalidate(false)')
|
|
41
41
|
* @param dateFormat - Optional date format
|
|
42
|
-
* @returns Promise with the flow details
|
|
42
|
+
* @returns Promise with the flow details or preview response
|
|
43
43
|
*/
|
|
44
44
|
getFlow(flowId: string, fields?: string, dateFormat?: string): Promise<RequesterResponseInterface<Flow | FlowPreviewResponse>>;
|
|
45
|
+
/**
|
|
46
|
+
* Get Flow Preview URL
|
|
47
|
+
*
|
|
48
|
+
* @param flowId - The flow ID
|
|
49
|
+
* @param invalidate - Optional. If true, invalidates existing preview and generates a new one. Defaults to false.
|
|
50
|
+
* @returns Promise with the flow preview details
|
|
51
|
+
*/
|
|
52
|
+
getFlowPreview(flowId: string, invalidate?: boolean): Promise<RequesterResponseInterface<FlowPreviewResponse>>;
|
|
45
53
|
/**
|
|
46
54
|
* Update Flow Metadata
|
|
47
55
|
*
|
|
48
56
|
* @param flowId - The flow ID
|
|
49
|
-
* @param data - The flow metadata to update
|
|
57
|
+
* @param data - The flow metadata to update (name, categories, endpoint_uri, application_id)
|
|
50
58
|
* @returns Promise with the success status
|
|
51
59
|
*/
|
|
52
60
|
updateFlowMetadata(flowId: string, data: {
|
|
@@ -56,34 +64,48 @@ declare class FlowAPI extends BaseAPI implements FlowClass {
|
|
|
56
64
|
application_id?: string;
|
|
57
65
|
}): Promise<RequesterResponseInterface<ResponseSuccess>>;
|
|
58
66
|
/**
|
|
59
|
-
* Delete Flow
|
|
67
|
+
* Delete Flow (only works if the Flow is in DRAFT status)
|
|
60
68
|
*
|
|
61
69
|
* @param flowId - The flow ID
|
|
62
70
|
* @returns Promise with the success status
|
|
63
71
|
*/
|
|
64
72
|
deleteFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>>;
|
|
65
73
|
/**
|
|
66
|
-
* List Assets (
|
|
74
|
+
* List Assets (e.g., get Flow JSON download URL)
|
|
67
75
|
*
|
|
68
76
|
* @param flowId - The flow ID
|
|
69
77
|
* @returns Promise with the list of assets
|
|
70
78
|
*/
|
|
71
79
|
listAssets(flowId: string): Promise<RequesterResponseInterface<FlowAssetsResponse>>;
|
|
72
80
|
/**
|
|
73
|
-
* Update Flow JSON
|
|
81
|
+
* Update Flow JSON by uploading a file, buffer, JSON object, or Blob.
|
|
74
82
|
*
|
|
75
83
|
* @param flowId - The flow ID
|
|
76
|
-
* @param data -
|
|
77
|
-
* @
|
|
84
|
+
* @param data - Object containing the file data and optional name.
|
|
85
|
+
* @param data.file - The Flow JSON content as a Buffer, JSON object, or Blob.
|
|
86
|
+
* @param data.name - Optional name for the asset, defaults to 'flow.json'.
|
|
87
|
+
* @returns Promise with the success status and validation errors, if any.
|
|
78
88
|
*/
|
|
79
89
|
updateFlowJson(flowId: string, data: {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
name: string;
|
|
90
|
+
file: Blob | Buffer | object;
|
|
91
|
+
name?: string;
|
|
83
92
|
}): Promise<RequesterResponseInterface<{
|
|
84
93
|
success: boolean;
|
|
85
94
|
validation_errors?: FlowValidationError[];
|
|
86
95
|
}>>;
|
|
96
|
+
/**
|
|
97
|
+
* Validate Flow JSON by attempting an update without publishing.
|
|
98
|
+
* This is a convenience method; the API doesn't have a dedicated validation endpoint.
|
|
99
|
+
*
|
|
100
|
+
* @param flowId - The ID of the Flow (must exist, can be in DRAFT status).
|
|
101
|
+
* @param flowJsonData - The Flow JSON content as a file path (string), Buffer, JSON object, or Blob.
|
|
102
|
+
* @returns Promise indicating if the JSON is valid and includes validation errors if any.
|
|
103
|
+
*/
|
|
104
|
+
validateFlowJson(flowId: string, flowJsonData: Blob | Buffer | object): Promise<RequesterResponseInterface<{
|
|
105
|
+
valid: boolean;
|
|
106
|
+
success: boolean;
|
|
107
|
+
validation_errors?: FlowValidationError[];
|
|
108
|
+
}>>;
|
|
87
109
|
/**
|
|
88
110
|
* Publish Flow
|
|
89
111
|
*
|
|
@@ -99,13 +121,13 @@ declare class FlowAPI extends BaseAPI implements FlowClass {
|
|
|
99
121
|
*/
|
|
100
122
|
deprecateFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>>;
|
|
101
123
|
/**
|
|
102
|
-
* Migrate Flows
|
|
124
|
+
* Migrate Flows between WABAs
|
|
103
125
|
*
|
|
104
|
-
* @param
|
|
126
|
+
* @param destinationWabaId - The destination WABA ID
|
|
105
127
|
* @param data - The migration data including source_waba_id and optional source_flow_names
|
|
106
|
-
* @returns Promise with migration results
|
|
128
|
+
* @returns Promise with migration results (successes and failures)
|
|
107
129
|
*/
|
|
108
|
-
migrateFlows(
|
|
130
|
+
migrateFlows(destinationWabaId: string, data: {
|
|
109
131
|
source_waba_id: string;
|
|
110
132
|
source_flow_names?: string[];
|
|
111
133
|
}): Promise<RequesterResponseInterface<FlowMigrationResponse>>;
|
package/dist/api/flow.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var N=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var U=(A,i)=>{for(var t in i)N(A,t,{get:i[t],enumerable:!0})},I=(A,i,t,R)=>{if(i&&typeof i=="object"||typeof i=="function")for(let l of O(i))!G.call(A,l)&&l!==t&&N(A,l,{get:()=>i[l],enumerable:!(R=_(i,l))||R.enumerable});return A};var F=A=>I(N({},"__esModule",{value:!0}),A);var o={};U(o,{default:()=>D});module.exports=F(o);var S=class{name;debug;constructor(i,t=!1){this.name=i,this.debug=t}log(...i){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log.apply(console,[t,": ",...i])}}error(...i){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error.apply(console,[t,": ",...i])}warn(...i){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn.apply(console,[t,": ",...i])}info(...i){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info.apply(console,[t,": ",...i])}};var w="BaseAPI",T=!1,K=new S(w,process.env.DEBUG==="true"||T),P=class{config;client;constructor(i,t){this.config=i,this.client=t,K.log("Initialized with HTTPSClient")}sendJson(i,t,R,l){return this.client.getJson(i,t,R,l)}};var M="FlowAPI",h=!1,f=new S(M,process.env.DEBUG==="true"||h),D=class extends P{constructor(i,t){super(i,t),f.log("FlowAPI initialized")}async listFlows(i){return this.sendJson("GET",`/${i}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(i,t){let R={name:t.name,categories:t.categories,...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.clone_flow_id&&{clone_flow_id:t.clone_flow_id},...t.flow_json&&{flow_json:t.flow_json},...t.publish!==void 0&&{publish:t.publish}};return this.sendJson("POST",`/${i}/flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}async getFlow(i,t,R){let l=new URLSearchParams;t&&l.append("fields",t),R&&l.append("date_format",R);let p=l.toString()?`?${l.toString()}`:"";return this.sendJson("GET",`/${i}${p}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(i,t=!1){let R=`preview.invalidate(${t})`;return this.getFlow(i,R)}async updateFlowMetadata(i,t){let R={...t.name&&{name:t.name},...t.categories&&{categories:t.categories},...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.application_id&&{application_id:t.application_id}};return this.sendJson("POST",`/${i}`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}async deleteFlow(i){return this.sendJson("DELETE",`/${i}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(i){return this.sendJson("GET",`/${i}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(i,t){let R=new FormData,l;if(t.file instanceof Buffer)l=new globalThis.Blob([t.file]),R.append("file",l);else if(typeof t.file=="object"&&!(t.file instanceof Blob))try{l=new globalThis.Blob([JSON.stringify(t.file,null,2)],{type:"application/json"}),R.append("file",l)}catch{throw new Error("Failed to stringify JSON object for Flow JSON update.")}else if(t.file instanceof Blob)l=t.file,R.append("file",l);else throw new Error("Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.");return R.append("asset_type","FLOW_JSON"),R.append("name",t.name||"flow.json"),this.sendJson("POST",`/${i}/assets`,this.config.REQUEST_TIMEOUT,R)}async validateFlowJson(i,t){try{let l=await(await this.updateFlowJson(i,{file:t})).json(),p=!l.validation_errors||l.validation_errors.length===0,B={...l,valid:p};return{json:async()=>B}}catch(R){throw f.error("Error during Flow JSON validation attempt:",R),R}}async publishFlow(i){return this.sendJson("POST",`/${i}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(i){return this.sendJson("POST",`/${i}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(i,t){let R={source_waba_id:t.source_waba_id,...t.source_flow_names&&{source_flow_names:t.source_flow_names}};return this.sendJson("POST",`/${i}/migrate_flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}};
|
|
2
2
|
//# sourceMappingURL=flow.js.map
|
package/dist/api/flow.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/api/flow.ts","../../src/utils/logger.ts","../../src/api/base.ts"],"sourcesContent":["import { WabaConfigType } from '../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport {\n Flow,\n FlowAssetsResponse,\n FlowCategoryEnum,\n FlowClass,\n FlowMigrationResponse,\n FlowPreviewResponse,\n FlowsListResponse,\n FlowValidationError,\n} from '../types/flow';\nimport { RequesterClass, RequesterResponseInterface, ResponseSuccess } from '../types/request';\nimport Logger from '../utils/logger';\nimport BaseAPI from './base';\n\nconst LIB_NAME = 'FlowAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class FlowAPI extends BaseAPI implements FlowClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n LOGGER.log('FlowAPI initialized');\n }\n\n /**\n * List Flows\n *\n * @param wabaId - The WABA ID\n * @returns Promise with the list of flows\n */\n async listFlows(wabaId: string): Promise<RequesterResponseInterface<FlowsListResponse>> {\n return this.sendJson(HttpMethodsEnum.Get, `/${wabaId}/flows`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\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 async 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<\n RequesterResponseInterface<{ id: string; success: boolean; validation_errors?: FlowValidationError[] }>\n > {\n const formData = new FormData();\n\n if (data.name) formData.append('name', data.name);\n if (data.categories) formData.append('categories', JSON.stringify(data.categories));\n if (data.endpoint_uri) formData.append('endpoint_uri', data.endpoint_uri);\n if (data.clone_flow_id) formData.append('clone_flow_id', data.clone_flow_id);\n if (data.flow_json) formData.append('flow_json', data.flow_json);\n if (data.publish !== undefined) formData.append('publish', String(data.publish));\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\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 async getFlow(\n flowId: string,\n fields?: string,\n dateFormat?: string,\n ): Promise<RequesterResponseInterface<Flow | FlowPreviewResponse>> {\n const params = new URLSearchParams();\n if (fields) params.append('fields', fields);\n if (dateFormat) params.append('date_format', dateFormat);\n\n const queryString = params.toString() ? `?${params.toString()}` : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}${queryString}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\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 async updateFlowMetadata(\n flowId: string,\n data: {\n name?: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n application_id?: string;\n },\n ): Promise<RequesterResponseInterface<ResponseSuccess>> {\n const formData = new FormData();\n\n if (data.name) formData.append('name', data.name);\n if (data.categories) formData.append('categories', JSON.stringify(data.categories));\n if (data.endpoint_uri) formData.append('endpoint_uri', data.endpoint_uri);\n if (data.application_id) formData.append('application_id', data.application_id);\n\n return this.sendJson(HttpMethodsEnum.Post, `/${flowId}`, this.config[WabaConfigEnum.RequestTimeout], formData);\n }\n\n /**\n * Delete Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deleteFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n return this.sendJson(HttpMethodsEnum.Delete, `/${flowId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\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 async listAssets(flowId: string): Promise<RequesterResponseInterface<FlowAssetsResponse>> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\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 async updateFlowJson(\n flowId: string,\n data: {\n asset_type: 'FLOW_JSON';\n file: Blob;\n name: string;\n },\n ): Promise<RequesterResponseInterface<{ success: boolean; validation_errors?: FlowValidationError[] }>> {\n const formData = new FormData();\n\n formData.append('asset_type', data.asset_type);\n formData.append('file', data.file);\n formData.append('name', data.name);\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n /**\n * Publish Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async publishFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/publish`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}),\n );\n }\n\n /**\n * Deprecate Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deprecateFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/deprecate`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}),\n );\n }\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 async migrateFlows(\n wabaId: string,\n data: {\n source_waba_id: string;\n source_flow_names?: string[];\n },\n ): Promise<RequesterResponseInterface<FlowMigrationResponse>> {\n const formData = new FormData();\n\n formData.append('source_waba_id', data.source_waba_id);\n if (data.source_flow_names) {\n formData.append('source_flow_names', JSON.stringify(data.source_flow_names));\n }\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/migrate_flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n}\n","// @ts-nocheck\nimport type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debug: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debug = debug;\n }\n\n log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log.apply(console, [prefix, ': ', ...data]);\n }\n }\n\n error(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - ERROR`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.error.apply(console, [prefix, ': ', ...data]);\n }\n\n warn(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn.apply(console, [prefix, ': ', ...data]);\n }\n\n info(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info.apply(console, [prefix, ': ', ...data]);\n }\n}\n","import Logger from '../utils/logger';\nimport type { BaseClass } from '../types/base';\nimport type { WabaConfigType } from '../types/config';\nimport type { RequesterClass } from '../types/request';\nimport { HttpMethodsEnum } from 'src/types/enums';\n\nconst LIB_NAME = 'BaseAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class BaseAPI implements BaseClass {\n protected config: WabaConfigType;\n protected client: RequesterClass;\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n this.config = config;\n this.client = client;\n LOGGER.log('Initialized with HTTPSClient');\n }\n\n protected sendJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n return this.client.getJson<T>(method, endpoint, timeout, body);\n }\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GCGA,IAAqBI,EAArB,KAAuD,CAC3C,KACA,M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C9EA,EAAK,cAAcC,EAAS,OAAO,eAAgBD,EAAK,YAAY,EACpEA,EAAK,gBAAgBC,EAAS,OAAO,iBAAkBD,EAAK,cAAc,EAEvE,KAAK,gBAA+B,IAAIE,CAAM,GAAI,KAAK,OAAO,gBAAgCD,CAAQ,CACjH,CAQA,MAAM,WAAWC,EAAsE,CACnF,OAAO,KAAK,kBAAiC,IAAIA,CAAM,GAAI,KAAK,OAAO,gBAAgC,IAAI,CAC/G,CAQA,MAAM,WAAWA,EAAyE,CACtF,OAAO,KAAK,eAER,IAAIA,CAAM,UACV,KAAK,OAAO,gBACZ,IACJ,CACJ,CASA,MAAM,eACFA,EACAF,EAKoG,CACpG,IAAMC,EAAW,IAAI,SAErB,OAAAA,EAAS,OAAO,aAAcD,EAAK,UAAU,EAC7CC,EAAS,OAAO,OAAQD,EAAK,IAAI,EACjCC,EAAS,OAAO,OAAQD,EAAK,IAAI,EAE1B,KAAK,gBAER,IAAIE,CAAM,UACV,KAAK,OAAO,gBACZD,CACJ,CACJ,CAQA,MAAM,YAAYC,EAAsE,CACpF,OAAO,KAAK,gBAER,IAAIA,CAAM,WACV,KAAK,OAAO,gBACZ,KAAK,UAAU,CAAC,CAAC,CACrB,CACJ,CAQA,MAAM,cAAcA,EAAsE,CACtF,OAAO,KAAK,gBAER,IAAIA,CAAM,aACV,KAAK,OAAO,gBACZ,KAAK,UAAU,CAAC,CAAC,CACrB,CACJ,CASA,MAAM,aACFH,EACAC,EAI0D,CAC1D,IAAMC,EAAW,IAAI,SAErB,OAAAA,EAAS,OAAO,iBAAkBD,EAAK,cAAc,EACjDA,EAAK,mBACLC,EAAS,OAAO,oBAAqB,KAAK,UAAUD,EAAK,iBAAiB,CAAC,EAGxE,KAAK,gBAER,IAAID,CAAM,iBACV,KAAK,OAAO,gBACZE,CACJ,CACJ,CACJ","names":["flow_exports","__export","FlowAPI","__toCommonJS","Logger","name","debug","data","prefix","LIB_NAME","LOG_LOCAL","LOGGER","Logger","BaseAPI","config","client","method","endpoint","timeout","body","LIB_NAME","LOG_LOCAL","LOGGER","Logger","FlowAPI","BaseAPI","config","client","wabaId","data","formData","flowId","fields","dateFormat","params","queryString"]}
|
|
1
|
+
{"version":3,"sources":["../../src/api/flow.ts","../../src/utils/logger.ts","../../src/api/base.ts"],"sourcesContent":["import { WabaConfigType } from '../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport {\n Flow,\n FlowAssetsResponse,\n FlowCategoryEnum,\n FlowClass,\n FlowMigrationResponse,\n FlowPreviewResponse,\n FlowsListResponse,\n FlowValidationError,\n} from '../types/flow';\nimport { RequesterClass, RequesterResponseInterface, ResponseSuccess } from '../types/request';\nimport Logger from '../utils/logger';\nimport BaseAPI from './base';\n\nconst LIB_NAME = 'FlowAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class FlowAPI extends BaseAPI implements FlowClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n LOGGER.log('FlowAPI initialized');\n }\n\n /**\n * List Flows\n *\n * @param wabaId - The WABA ID\n * @returns Promise with the list of flows\n */\n async listFlows(wabaId: string): Promise<RequesterResponseInterface<FlowsListResponse>> {\n return this.sendJson(HttpMethodsEnum.Get, `/${wabaId}/flows`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\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 and validation errors if any\n */\n async 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; // Flow JSON as a string\n publish?: boolean;\n },\n ): Promise<\n RequesterResponseInterface<{ id: string; success: boolean; validation_errors?: FlowValidationError[] }>\n > {\n // The API expects application/json for this endpoint based on documentation examples\n // Let's ensure we send JSON, not FormData, unless specifically required by an endpoint variation.\n const payload = {\n name: data.name,\n categories: data.categories,\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.clone_flow_id && { clone_flow_id: data.clone_flow_id }),\n ...(data.flow_json && { flow_json: data.flow_json }),\n ...(data.publish !== undefined && { publish: data.publish }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Get Flow details\n *\n * @param flowId - The flow ID\n * @param fields - Optional fields to return (e.g., 'name,status,preview.invalidate(false)')\n * @param dateFormat - Optional date format\n * @returns Promise with the flow details or preview response\n */\n async getFlow(\n flowId: string,\n fields?: string,\n dateFormat?: string,\n ): Promise<RequesterResponseInterface<Flow | FlowPreviewResponse>> {\n const params = new URLSearchParams();\n if (fields) params.append('fields', fields);\n if (dateFormat) params.append('date_format', dateFormat);\n\n const queryString = params.toString() ? `?${params.toString()}` : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}${queryString}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get Flow Preview URL\n *\n * @param flowId - The flow ID\n * @param invalidate - Optional. If true, invalidates existing preview and generates a new one. Defaults to false.\n * @returns Promise with the flow preview details\n */\n async getFlowPreview(\n flowId: string,\n invalidate: boolean = false,\n ): Promise<RequesterResponseInterface<FlowPreviewResponse>> {\n const fields = `preview.invalidate(${invalidate})`;\n // Type assertion needed as getFlow can return Flow or FlowPreviewResponse\n return this.getFlow(flowId, fields) as Promise<RequesterResponseInterface<FlowPreviewResponse>>;\n }\n\n /**\n * Update Flow Metadata\n *\n * @param flowId - The flow ID\n * @param data - The flow metadata to update (name, categories, endpoint_uri, application_id)\n * @returns Promise with the success status\n */\n async updateFlowMetadata(\n flowId: string,\n data: {\n name?: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n application_id?: string;\n },\n ): Promise<RequesterResponseInterface<ResponseSuccess>> {\n // The API expects application/json for this endpoint based on documentation examples\n const payload = {\n ...(data.name && { name: data.name }),\n ...(data.categories && { categories: data.categories }),\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.application_id && { application_id: data.application_id }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Delete Flow (only works if the Flow is in DRAFT status)\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deleteFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n return this.sendJson(HttpMethodsEnum.Delete, `/${flowId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * List Assets (e.g., get Flow JSON download URL)\n *\n * @param flowId - The flow ID\n * @returns Promise with the list of assets\n */\n async listAssets(flowId: string): Promise<RequesterResponseInterface<FlowAssetsResponse>> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update Flow JSON by uploading a file, buffer, JSON object, or Blob.\n *\n * @param flowId - The flow ID\n * @param data - Object containing the file data and optional name.\n * @param data.file - The Flow JSON content as a Buffer, JSON object, or Blob.\n * @param data.name - Optional name for the asset, defaults to 'flow.json'.\n * @returns Promise with the success status and validation errors, if any.\n */\n async updateFlowJson(\n flowId: string,\n data: {\n file: Blob | Buffer | object; // JSON object, Buffer, or Blob\n name?: string; // Default to \"flow.json\"\n },\n ): Promise<RequesterResponseInterface<{ success: boolean; validation_errors?: FlowValidationError[] }>> {\n const formData = new FormData();\n let fileContent: Blob;\n\n // Handle different input types for the file\n if (data.file instanceof Buffer) {\n // Buffer\n // Create a Blob from the Buffer and cast it to the global Blob type\n fileContent = new globalThis.Blob([data.file]);\n formData.append('file', fileContent as unknown as Blob);\n } else if (typeof data.file === 'object' && !(data.file instanceof Blob)) {\n // JSON object - stringify and create Blob\n try {\n // Create a Blob from the JSON string and cast it to the global Blob type\n fileContent = new globalThis.Blob([JSON.stringify(data.file, null, 2)], { type: 'application/json' });\n formData.append('file', fileContent as unknown as Blob);\n } catch (e) {\n throw new Error('Failed to stringify JSON object for Flow JSON update.');\n }\n } else if (data.file instanceof Blob) {\n // Blob (already in correct format)\n fileContent = data.file;\n formData.append('file', fileContent as unknown as Blob);\n } else {\n throw new Error('Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.');\n }\n\n formData.append('asset_type', 'FLOW_JSON'); // Required by API\n formData.append('name', data.name || 'flow.json'); // Required by API\n\n // The underlying.sendJson needs to correctly handle FormData\n // It might need specific headers like `Content-Type: multipart/form-data; boundary=...`\n // which FormData library usually helps generate.\n // Assuming.sendJson handles FormData correctly:\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData, // Pass FormData directly\n // Headers might be set automatically by the client when FormData is detected,\n // or might need to be explicitly set depending on the client implementation.\n // e.g., { 'Content-Type': `multipart/form-data; boundary=${formData.getBoundary()}` }\n );\n }\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 file path (string), Buffer, JSON object, or Blob.\n * @returns Promise indicating if the JSON is valid and includes validation errors if any.\n */\n async validateFlowJson(\n flowId: string,\n flowJsonData: Blob | Buffer | object,\n ): Promise<\n RequesterResponseInterface<{ valid: boolean; success: boolean; validation_errors?: FlowValidationError[] }>\n > {\n try {\n // Attempt to update the Flow JSON. The API response includes validation errors.\n const result = await this.updateFlowJson(flowId, {\n file: flowJsonData,\n });\n\n // Get the response data\n const responseData = await result.json();\n\n const isValid = !responseData.validation_errors || responseData.validation_errors.length === 0;\n\n // Create a new response with the 'valid' flag\n const enhancedResponse = {\n ...responseData,\n valid: isValid,\n };\n\n // Return a new RequesterResponseInterface with the enhanced data\n return {\n json: async () => enhancedResponse,\n };\n } catch (error) {\n // If the update itself fails (e.g., network error, auth error), rethrow.\n // Specific API validation errors are handled within the 'result' above.\n LOGGER.error('Error during Flow JSON validation attempt:', error);\n throw error;\n }\n }\n\n /**\n * Publish Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async publishFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/publish`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Deprecate Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deprecateFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/deprecate`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Migrate Flows between WABAs\n *\n * @param destinationWabaId - 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 (successes and failures)\n */\n async migrateFlows(\n destinationWabaId: string,\n data: {\n source_waba_id: string;\n source_flow_names?: string[];\n },\n ): Promise<RequesterResponseInterface<FlowMigrationResponse>> {\n // API documentation suggests this endpoint might expect application/json\n // Let's double-check or assume JSON based on typical Graph API patterns unless FormData is confirmed.\n // Assuming JSON for now:\n const payload = {\n source_waba_id: data.source_waba_id,\n ...(data.source_flow_names && { source_flow_names: data.source_flow_names }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${destinationWabaId}/migrate_flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload),\n );\n }\n}\n","// @ts-nocheck\nimport type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debug: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debug = debug;\n }\n\n log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log.apply(console, [prefix, ': ', ...data]);\n }\n }\n\n error(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - ERROR`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.error.apply(console, [prefix, ': ', ...data]);\n }\n\n warn(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn.apply(console, [prefix, ': ', ...data]);\n }\n\n info(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info.apply(console, [prefix, ': ', ...data]);\n }\n}\n","import Logger from '../utils/logger';\nimport type { BaseClass } from '../types/base';\nimport type { WabaConfigType } from '../types/config';\nimport type { RequesterClass } from '../types/request';\nimport { HttpMethodsEnum } from 'src/types/enums';\n\nconst LIB_NAME = 'BaseAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class BaseAPI implements BaseClass {\n protected config: WabaConfigType;\n protected client: RequesterClass;\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n this.config = config;\n this.client = client;\n LOGGER.log('Initialized with HTTPSClient');\n }\n\n protected sendJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n return this.client.getJson<T>(method, endpoint, timeout, body);\n }\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GCGA,IAAqBI,EAArB,KAAuD,CAC3C,KACA,MAER,YAAYC,EAAcC,EAAiB,GAAO,CAC9C,KAAK,KAAOD,EACZ,KAAK,MAAQC,CACjB,CAEA,OAA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SAAW,EAGvFE,EAAmB,CACrB,GAAGF,EACH,MAAOC,CACX,EAGA,MAAO,CACH,KAAM,SAAYC,CACtB,CACJ,OAASC,EAAO,CAGZ,MAAArB,EAAO,MAAM,6CAA8CqB,CAAK,EAC1DA,CACV,CACJ,CAQA,MAAM,YAAYZ,EAAsE,CAEpF,OAAO,KAAK,gBAER,IAAIA,CAAM,WACV,KAAK,OAAO,gBACZ,KAAK,UAAU,CAAC,CAAC,CACrB,CACJ,CAQA,MAAM,cAAcA,EAAsE,CAEtF,OAAO,KAAK,gBAER,IAAIA,CAAM,aACV,KAAK,OAAO,gBACZ,KAAK,UAAU,CAAC,CAAC,CACrB,CACJ,CASA,MAAM,aACFa,EACAf,EAI0D,CAI1D,IAAMC,EAAU,CACZ,eAAgBD,EAAK,eACrB,GAAIA,EAAK,mBAAqB,CAAE,kBAAmBA,EAAK,iBAAkB,CAC9E,EAEA,OAAO,KAAK,gBAER,IAAIe,CAAiB,iBACrB,KAAK,OAAO,gBACZ,KAAK,UAAUd,CAAO,CAC1B,CACJ,CACJ","names":["flow_exports","__export","FlowAPI","__toCommonJS","Logger","name","debug","data","prefix","LIB_NAME","LOG_LOCAL","LOGGER","Logger","BaseAPI","config","client","method","endpoint","timeout","body","LIB_NAME","LOG_LOCAL","LOGGER","Logger","FlowAPI","BaseAPI","config","client","wabaId","data","payload","flowId","fields","dateFormat","params","queryString","invalidate","formData","fileContent","flowJsonData","responseData","isValid","enhancedResponse","error","destinationWabaId"]}
|
package/dist/api/flow.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var A=class{name;debug;constructor(i,t=!1){this.name=i,this.debug=t}log(...i){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log.apply(console,[t,": ",...i])}}error(...i){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error.apply(console,[t,": ",...i])}warn(...i){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn.apply(console,[t,": ",...i])}info(...i){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info.apply(console,[t,": ",...i])}};var
|
|
1
|
+
var A=class{name;debug;constructor(i,t=!1){this.name=i,this.debug=t}log(...i){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log.apply(console,[t,": ",...i])}}error(...i){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error.apply(console,[t,": ",...i])}warn(...i){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn.apply(console,[t,": ",...i])}info(...i){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info.apply(console,[t,": ",...i])}};var B="BaseAPI",_=!1,O=new A(B,process.env.DEBUG==="true"||_),S=class{config;client;constructor(i,t){this.config=i,this.client=t,O.log("Initialized with HTTPSClient")}sendJson(i,t,R,l){return this.client.getJson(i,t,R,l)}};var G="FlowAPI",U=!1,N=new A(G,process.env.DEBUG==="true"||U),p=class extends S{constructor(i,t){super(i,t),N.log("FlowAPI initialized")}async listFlows(i){return this.sendJson("GET",`/${i}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(i,t){let R={name:t.name,categories:t.categories,...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.clone_flow_id&&{clone_flow_id:t.clone_flow_id},...t.flow_json&&{flow_json:t.flow_json},...t.publish!==void 0&&{publish:t.publish}};return this.sendJson("POST",`/${i}/flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}async getFlow(i,t,R){let l=new URLSearchParams;t&&l.append("fields",t),R&&l.append("date_format",R);let P=l.toString()?`?${l.toString()}`:"";return this.sendJson("GET",`/${i}${P}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(i,t=!1){let R=`preview.invalidate(${t})`;return this.getFlow(i,R)}async updateFlowMetadata(i,t){let R={...t.name&&{name:t.name},...t.categories&&{categories:t.categories},...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.application_id&&{application_id:t.application_id}};return this.sendJson("POST",`/${i}`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}async deleteFlow(i){return this.sendJson("DELETE",`/${i}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(i){return this.sendJson("GET",`/${i}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(i,t){let R=new FormData,l;if(t.file instanceof Buffer)l=new globalThis.Blob([t.file]),R.append("file",l);else if(typeof t.file=="object"&&!(t.file instanceof Blob))try{l=new globalThis.Blob([JSON.stringify(t.file,null,2)],{type:"application/json"}),R.append("file",l)}catch{throw new Error("Failed to stringify JSON object for Flow JSON update.")}else if(t.file instanceof Blob)l=t.file,R.append("file",l);else throw new Error("Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.");return R.append("asset_type","FLOW_JSON"),R.append("name",t.name||"flow.json"),this.sendJson("POST",`/${i}/assets`,this.config.REQUEST_TIMEOUT,R)}async validateFlowJson(i,t){try{let l=await(await this.updateFlowJson(i,{file:t})).json(),P=!l.validation_errors||l.validation_errors.length===0,f={...l,valid:P};return{json:async()=>f}}catch(R){throw N.error("Error during Flow JSON validation attempt:",R),R}}async publishFlow(i){return this.sendJson("POST",`/${i}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(i){return this.sendJson("POST",`/${i}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(i,t){let R={source_waba_id:t.source_waba_id,...t.source_flow_names&&{source_flow_names:t.source_flow_names}};return this.sendJson("POST",`/${i}/migrate_flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}};export{p as default};
|
|
2
2
|
//# sourceMappingURL=flow.mjs.map
|
package/dist/api/flow.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/logger.ts","../../src/api/base.ts","../../src/api/flow.ts"],"sourcesContent":["// @ts-nocheck\nimport type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debug: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debug = debug;\n }\n\n log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log.apply(console, [prefix, ': ', ...data]);\n }\n }\n\n error(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - ERROR`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.error.apply(console, [prefix, ': ', ...data]);\n }\n\n warn(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn.apply(console, [prefix, ': ', ...data]);\n }\n\n info(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info.apply(console, [prefix, ': ', ...data]);\n }\n}\n","import Logger from '../utils/logger';\nimport type { BaseClass } from '../types/base';\nimport type { WabaConfigType } from '../types/config';\nimport type { RequesterClass } from '../types/request';\nimport { HttpMethodsEnum } from 'src/types/enums';\n\nconst LIB_NAME = 'BaseAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class BaseAPI implements BaseClass {\n protected config: WabaConfigType;\n protected client: RequesterClass;\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n this.config = config;\n this.client = client;\n LOGGER.log('Initialized with HTTPSClient');\n }\n\n protected sendJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n return this.client.getJson<T>(method, endpoint, timeout, body);\n }\n}\n","import { WabaConfigType } from '../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport {\n Flow,\n FlowAssetsResponse,\n FlowCategoryEnum,\n FlowClass,\n FlowMigrationResponse,\n FlowPreviewResponse,\n FlowsListResponse,\n FlowValidationError,\n} from '../types/flow';\nimport { RequesterClass, RequesterResponseInterface, ResponseSuccess } from '../types/request';\nimport Logger from '../utils/logger';\nimport BaseAPI from './base';\n\nconst LIB_NAME = 'FlowAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class FlowAPI extends BaseAPI implements FlowClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n LOGGER.log('FlowAPI initialized');\n }\n\n /**\n * List Flows\n *\n * @param wabaId - The WABA ID\n * @returns Promise with the list of flows\n */\n async listFlows(wabaId: string): Promise<RequesterResponseInterface<FlowsListResponse>> {\n return this.sendJson(HttpMethodsEnum.Get, `/${wabaId}/flows`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\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 async 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<\n RequesterResponseInterface<{ id: string; success: boolean; validation_errors?: FlowValidationError[] }>\n > {\n const formData = new FormData();\n\n if (data.name) formData.append('name', data.name);\n if (data.categories) formData.append('categories', JSON.stringify(data.categories));\n if (data.endpoint_uri) formData.append('endpoint_uri', data.endpoint_uri);\n if (data.clone_flow_id) formData.append('clone_flow_id', data.clone_flow_id);\n if (data.flow_json) formData.append('flow_json', data.flow_json);\n if (data.publish !== undefined) formData.append('publish', String(data.publish));\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\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 async getFlow(\n flowId: string,\n fields?: string,\n dateFormat?: string,\n ): Promise<RequesterResponseInterface<Flow | FlowPreviewResponse>> {\n const params = new URLSearchParams();\n if (fields) params.append('fields', fields);\n if (dateFormat) params.append('date_format', dateFormat);\n\n const queryString = params.toString() ? `?${params.toString()}` : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}${queryString}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\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 async updateFlowMetadata(\n flowId: string,\n data: {\n name?: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n application_id?: string;\n },\n ): Promise<RequesterResponseInterface<ResponseSuccess>> {\n const formData = new FormData();\n\n if (data.name) formData.append('name', data.name);\n if (data.categories) formData.append('categories', JSON.stringify(data.categories));\n if (data.endpoint_uri) formData.append('endpoint_uri', data.endpoint_uri);\n if (data.application_id) formData.append('application_id', data.application_id);\n\n return this.sendJson(HttpMethodsEnum.Post, `/${flowId}`, this.config[WabaConfigEnum.RequestTimeout], formData);\n }\n\n /**\n * Delete Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deleteFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n return this.sendJson(HttpMethodsEnum.Delete, `/${flowId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\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 async listAssets(flowId: string): Promise<RequesterResponseInterface<FlowAssetsResponse>> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\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 async updateFlowJson(\n flowId: string,\n data: {\n asset_type: 'FLOW_JSON';\n file: Blob;\n name: string;\n },\n ): Promise<RequesterResponseInterface<{ success: boolean; validation_errors?: FlowValidationError[] }>> {\n const formData = new FormData();\n\n formData.append('asset_type', data.asset_type);\n formData.append('file', data.file);\n formData.append('name', data.name);\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n /**\n * Publish Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async publishFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/publish`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}),\n );\n }\n\n /**\n * Deprecate Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deprecateFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/deprecate`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}),\n );\n }\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 async migrateFlows(\n wabaId: string,\n data: {\n source_waba_id: string;\n source_flow_names?: string[];\n },\n ): Promise<RequesterResponseInterface<FlowMigrationResponse>> {\n const formData = new FormData();\n\n formData.append('source_waba_id', data.source_waba_id);\n if (data.source_flow_names) {\n formData.append('source_flow_names', JSON.stringify(data.source_flow_names));\n }\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/migrate_flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n}\n"],"mappings":"AAGA,IAAqBA,EAArB,KAAuD,CAC3C,KACA,MAER,YAAYC,EAAcC,EAAiB,GAAO,CAC9C,KAAK,KAAOD,EACZ,KAAK,MAAQC,CACjB,CAEA,OAAOC,EAA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D,EAAK,cAAc,EAEvE,KAAK,gBAA+B,IAAIE,CAAM,GAAI,KAAK,OAAO,gBAAgCD,CAAQ,CACjH,CAQA,MAAM,WAAWC,EAAsE,CACnF,OAAO,KAAK,kBAAiC,IAAIA,CAAM,GAAI,KAAK,OAAO,gBAAgC,IAAI,CAC/G,CAQA,MAAM,WAAWA,EAAyE,CACtF,OAAO,KAAK,eAER,IAAIA,CAAM,UACV,KAAK,OAAO,gBACZ,IACJ,CACJ,CASA,MAAM,eACFA,EACAF,EAKoG,CACpG,IAAMC,EAAW,IAAI,SAErB,OAAAA,EAAS,OAAO,aAAcD,EAAK,UAAU,EAC7CC,EAAS,OAAO,OAAQD,EAAK,IAAI,EACjCC,EAAS,OAAO,OAAQD,EAAK,IAAI,EAE1B,KAAK,gBAER,IAAIE,CAAM,UACV,KAAK,OAAO,gBACZD,CACJ,CACJ,CAQA,MAAM,YAAYC,EAAsE,CACpF,OAAO,KAAK,gBAER,IAAIA,CAAM,WACV,KAAK,OAAO,gBACZ,KAAK,UAAU,CAAC,CAAC,CACrB,CACJ,CAQA,MAAM,cAAcA,EAAsE,CACtF,OAAO,KAAK,gBAER,IAAIA,CAAM,aACV,KAAK,OAAO,gBACZ,KAAK,UAAU,CAAC,CAAC,CACrB,CACJ,CASA,MAAM,aACFH,EACAC,EAI0D,CAC1D,IAAMC,EAAW,IAAI,SAErB,OAAAA,EAAS,OAAO,iBAAkBD,EAAK,cAAc,EACjDA,EAAK,mBACLC,EAAS,OAAO,oBAAqB,KAAK,UAAUD,EAAK,iBAAiB,CAAC,EAGxE,KAAK,gBAER,IAAID,CAAM,iBACV,KAAK,OAAO,gBACZE,CACJ,CACJ,CACJ","names":["Logger","name","debug","data","prefix","LIB_NAME","LOG_LOCAL","LOGGER","Logger","BaseAPI","config","client","method","endpoint","timeout","body","LIB_NAME","LOG_LOCAL","LOGGER","Logger","FlowAPI","BaseAPI","config","client","wabaId","data","formData","flowId","fields","dateFormat","params","queryString"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/logger.ts","../../src/api/base.ts","../../src/api/flow.ts"],"sourcesContent":["// @ts-nocheck\nimport type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debug: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debug = debug;\n }\n\n log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log.apply(console, [prefix, ': ', ...data]);\n }\n }\n\n error(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - ERROR`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.error.apply(console, [prefix, ': ', ...data]);\n }\n\n warn(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn.apply(console, [prefix, ': ', ...data]);\n }\n\n info(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info.apply(console, [prefix, ': ', ...data]);\n }\n}\n","import Logger from '../utils/logger';\nimport type { BaseClass } from '../types/base';\nimport type { WabaConfigType } from '../types/config';\nimport type { RequesterClass } from '../types/request';\nimport { HttpMethodsEnum } from 'src/types/enums';\n\nconst LIB_NAME = 'BaseAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class BaseAPI implements BaseClass {\n protected config: WabaConfigType;\n protected client: RequesterClass;\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n this.config = config;\n this.client = client;\n LOGGER.log('Initialized with HTTPSClient');\n }\n\n protected sendJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n return this.client.getJson<T>(method, endpoint, timeout, body);\n }\n}\n","import { WabaConfigType } from '../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport {\n Flow,\n FlowAssetsResponse,\n FlowCategoryEnum,\n FlowClass,\n FlowMigrationResponse,\n FlowPreviewResponse,\n FlowsListResponse,\n FlowValidationError,\n} from '../types/flow';\nimport { RequesterClass, RequesterResponseInterface, ResponseSuccess } from '../types/request';\nimport Logger from '../utils/logger';\nimport BaseAPI from './base';\n\nconst LIB_NAME = 'FlowAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class FlowAPI extends BaseAPI implements FlowClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n LOGGER.log('FlowAPI initialized');\n }\n\n /**\n * List Flows\n *\n * @param wabaId - The WABA ID\n * @returns Promise with the list of flows\n */\n async listFlows(wabaId: string): Promise<RequesterResponseInterface<FlowsListResponse>> {\n return this.sendJson(HttpMethodsEnum.Get, `/${wabaId}/flows`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\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 and validation errors if any\n */\n async 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; // Flow JSON as a string\n publish?: boolean;\n },\n ): Promise<\n RequesterResponseInterface<{ id: string; success: boolean; validation_errors?: FlowValidationError[] }>\n > {\n // The API expects application/json for this endpoint based on documentation examples\n // Let's ensure we send JSON, not FormData, unless specifically required by an endpoint variation.\n const payload = {\n name: data.name,\n categories: data.categories,\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.clone_flow_id && { clone_flow_id: data.clone_flow_id }),\n ...(data.flow_json && { flow_json: data.flow_json }),\n ...(data.publish !== undefined && { publish: data.publish }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Get Flow details\n *\n * @param flowId - The flow ID\n * @param fields - Optional fields to return (e.g., 'name,status,preview.invalidate(false)')\n * @param dateFormat - Optional date format\n * @returns Promise with the flow details or preview response\n */\n async getFlow(\n flowId: string,\n fields?: string,\n dateFormat?: string,\n ): Promise<RequesterResponseInterface<Flow | FlowPreviewResponse>> {\n const params = new URLSearchParams();\n if (fields) params.append('fields', fields);\n if (dateFormat) params.append('date_format', dateFormat);\n\n const queryString = params.toString() ? `?${params.toString()}` : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}${queryString}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get Flow Preview URL\n *\n * @param flowId - The flow ID\n * @param invalidate - Optional. If true, invalidates existing preview and generates a new one. Defaults to false.\n * @returns Promise with the flow preview details\n */\n async getFlowPreview(\n flowId: string,\n invalidate: boolean = false,\n ): Promise<RequesterResponseInterface<FlowPreviewResponse>> {\n const fields = `preview.invalidate(${invalidate})`;\n // Type assertion needed as getFlow can return Flow or FlowPreviewResponse\n return this.getFlow(flowId, fields) as Promise<RequesterResponseInterface<FlowPreviewResponse>>;\n }\n\n /**\n * Update Flow Metadata\n *\n * @param flowId - The flow ID\n * @param data - The flow metadata to update (name, categories, endpoint_uri, application_id)\n * @returns Promise with the success status\n */\n async updateFlowMetadata(\n flowId: string,\n data: {\n name?: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n application_id?: string;\n },\n ): Promise<RequesterResponseInterface<ResponseSuccess>> {\n // The API expects application/json for this endpoint based on documentation examples\n const payload = {\n ...(data.name && { name: data.name }),\n ...(data.categories && { categories: data.categories }),\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.application_id && { application_id: data.application_id }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Delete Flow (only works if the Flow is in DRAFT status)\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deleteFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n return this.sendJson(HttpMethodsEnum.Delete, `/${flowId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * List Assets (e.g., get Flow JSON download URL)\n *\n * @param flowId - The flow ID\n * @returns Promise with the list of assets\n */\n async listAssets(flowId: string): Promise<RequesterResponseInterface<FlowAssetsResponse>> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update Flow JSON by uploading a file, buffer, JSON object, or Blob.\n *\n * @param flowId - The flow ID\n * @param data - Object containing the file data and optional name.\n * @param data.file - The Flow JSON content as a Buffer, JSON object, or Blob.\n * @param data.name - Optional name for the asset, defaults to 'flow.json'.\n * @returns Promise with the success status and validation errors, if any.\n */\n async updateFlowJson(\n flowId: string,\n data: {\n file: Blob | Buffer | object; // JSON object, Buffer, or Blob\n name?: string; // Default to \"flow.json\"\n },\n ): Promise<RequesterResponseInterface<{ success: boolean; validation_errors?: FlowValidationError[] }>> {\n const formData = new FormData();\n let fileContent: Blob;\n\n // Handle different input types for the file\n if (data.file instanceof Buffer) {\n // Buffer\n // Create a Blob from the Buffer and cast it to the global Blob type\n fileContent = new globalThis.Blob([data.file]);\n formData.append('file', fileContent as unknown as Blob);\n } else if (typeof data.file === 'object' && !(data.file instanceof Blob)) {\n // JSON object - stringify and create Blob\n try {\n // Create a Blob from the JSON string and cast it to the global Blob type\n fileContent = new globalThis.Blob([JSON.stringify(data.file, null, 2)], { type: 'application/json' });\n formData.append('file', fileContent as unknown as Blob);\n } catch (e) {\n throw new Error('Failed to stringify JSON object for Flow JSON update.');\n }\n } else if (data.file instanceof Blob) {\n // Blob (already in correct format)\n fileContent = data.file;\n formData.append('file', fileContent as unknown as Blob);\n } else {\n throw new Error('Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.');\n }\n\n formData.append('asset_type', 'FLOW_JSON'); // Required by API\n formData.append('name', data.name || 'flow.json'); // Required by API\n\n // The underlying.sendJson needs to correctly handle FormData\n // It might need specific headers like `Content-Type: multipart/form-data; boundary=...`\n // which FormData library usually helps generate.\n // Assuming.sendJson handles FormData correctly:\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData, // Pass FormData directly\n // Headers might be set automatically by the client when FormData is detected,\n // or might need to be explicitly set depending on the client implementation.\n // e.g., { 'Content-Type': `multipart/form-data; boundary=${formData.getBoundary()}` }\n );\n }\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 file path (string), Buffer, JSON object, or Blob.\n * @returns Promise indicating if the JSON is valid and includes validation errors if any.\n */\n async validateFlowJson(\n flowId: string,\n flowJsonData: Blob | Buffer | object,\n ): Promise<\n RequesterResponseInterface<{ valid: boolean; success: boolean; validation_errors?: FlowValidationError[] }>\n > {\n try {\n // Attempt to update the Flow JSON. The API response includes validation errors.\n const result = await this.updateFlowJson(flowId, {\n file: flowJsonData,\n });\n\n // Get the response data\n const responseData = await result.json();\n\n const isValid = !responseData.validation_errors || responseData.validation_errors.length === 0;\n\n // Create a new response with the 'valid' flag\n const enhancedResponse = {\n ...responseData,\n valid: isValid,\n };\n\n // Return a new RequesterResponseInterface with the enhanced data\n return {\n json: async () => enhancedResponse,\n };\n } catch (error) {\n // If the update itself fails (e.g., network error, auth error), rethrow.\n // Specific API validation errors are handled within the 'result' above.\n LOGGER.error('Error during Flow JSON validation attempt:', error);\n throw error;\n }\n }\n\n /**\n * Publish Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async publishFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/publish`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Deprecate Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deprecateFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/deprecate`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Migrate Flows between WABAs\n *\n * @param destinationWabaId - 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 (successes and failures)\n */\n async migrateFlows(\n destinationWabaId: string,\n data: {\n source_waba_id: string;\n source_flow_names?: string[];\n },\n ): Promise<RequesterResponseInterface<FlowMigrationResponse>> {\n // API documentation suggests this endpoint might expect application/json\n // Let's double-check or assume JSON based on typical Graph API patterns unless FormData is confirmed.\n // Assuming JSON for now:\n const payload = {\n source_waba_id: data.source_waba_id,\n ...(data.source_flow_names && { source_flow_names: data.source_flow_names }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${destinationWabaId}/migrate_flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload),\n );\n }\n}\n"],"mappings":"AAGA,IAAqBA,EAArB,KAAuD,CAC3C,KACA,MAER,YAAYC,EAAcC,EAAiB,GAAO,CAC9C,KAAK,KAAOD,EACZ,KAAK,MAAQC,CACjB,CAEA,OAAOC,EAAa,CAChB,GAAI,KAAK,MAAO,CACZ,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,KACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,IAAI,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,C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AsE,CAEpF,OAAO,KAAK,gBAER,IAAIA,CAAM,WACV,KAAK,OAAO,gBACZ,KAAK,UAAU,CAAC,CAAC,CACrB,CACJ,CAQA,MAAM,cAAcA,EAAsE,CAEtF,OAAO,KAAK,gBAER,IAAIA,CAAM,aACV,KAAK,OAAO,gBACZ,KAAK,UAAU,CAAC,CAAC,CACrB,CACJ,CASA,MAAM,aACFa,EACAf,EAI0D,CAI1D,IAAMC,EAAU,CACZ,eAAgBD,EAAK,eACrB,GAAIA,EAAK,mBAAqB,CAAE,kBAAmBA,EAAK,iBAAkB,CAC9E,EAEA,OAAO,KAAK,gBAER,IAAIe,CAAiB,iBACrB,KAAK,OAAO,gBACZ,KAAK,UAAUd,CAAO,CAC1B,CACJ,CACJ","names":["Logger","name","debug","data","prefix","LIB_NAME","LOG_LOCAL","LOGGER","Logger","BaseAPI","config","client","method","endpoint","timeout","body","LIB_NAME","LOG_LOCAL","LOGGER","Logger","FlowAPI","BaseAPI","config","client","wabaId","data","payload","flowId","fields","dateFormat","params","queryString","invalidate","formData","fileContent","flowJsonData","responseData","isValid","enhancedResponse","error","destinationWabaId"]}
|
package/dist/api/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var N=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var D=Object.prototype.hasOwnProperty;var _=(a,e)=>{for(var t in e)N(a,t,{get:e[t],enumerable:!0})},B=(a,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of O(e))!D.call(a,i)&&i!==t&&N(a,i,{get:()=>e[i],enumerable:!(s=b(e,i))||s.enumerable});return a};var m=a=>B(N({},"__esModule",{value:!0}),a);var K={};_(K,{BaseAPI:()=>o,BusinessProfileAPI:()=>l,EncryptionAPI:()=>P,FlowAPI:()=>c,MediaAPI:()=>I,MessagesAPI:()=>h,PhoneNumberAPI:()=>g,QrCodeAPI:()=>S,RegistrationAPI:()=>T,TemplateAPI:()=>A,TwoStepVerificationAPI:()=>q,WabaAPI:()=>M});module.exports=m(K);var f=class{name;debug;constructor(e,t=!1){this.name=e,this.debug=t}log(...e){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log.apply(console,[t,": ",...e])}}error(...e){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error.apply(console,[t,": ",...e])}warn(...e){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn.apply(console,[t,": ",...e])}info(...e){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info.apply(console,[t,": ",...e])}};var U="BaseAPI",G=!1,w=new f(U,process.env.DEBUG==="true"||G),o=class{config;client;constructor(e,t){this.config=e,this.client=t,w.log("Initialized with HTTPSClient")}sendJson(e,t,s,i){return this.client.getJson(e,t,s,i)}};var n=a=>{if(!a||Object.keys(a).length===0)return"";let e=new URLSearchParams;for(let[s,i]of Object.entries(a))i!==void 0&&e.append(s,String(i));let t=e.toString();return t?`?${t}`:""};var l=class extends o{endpoint="whatsapp_business_profile";constructor(e,t){super(e,t)}async getBusinessProfile(e){let t=e?n({fields:e}):"";return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${t}`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessProfile(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async createUploadSession(e,t,s){let i=n({file_length:e,file_type:t,file_name:s});return this.sendJson("POST",`app/uploads/${i}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(e,t){return this.sendJson("POST",`${e}`,this.config.REQUEST_TIMEOUT,t)}async getUploadHandle(e){return this.sendJson("GET",`${e}`,this.config.REQUEST_TIMEOUT,null)}};var P=class extends o{endpoint="whatsapp_business_encryption";constructor(e,t){super(e,t)}async getEncryptionPublicKey(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async setEncryptionPublicKey(e){let t=new FormData;return t.append("business_public_key",e),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,t)}};var F="FlowAPI",J=!1,x=new f(F,process.env.DEBUG==="true"||J),c=class extends o{constructor(e,t){super(e,t),x.log("FlowAPI initialized")}async listFlows(e){return this.sendJson("GET",`/${e}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(e,t){let s=new FormData;return t.name&&s.append("name",t.name),t.categories&&s.append("categories",JSON.stringify(t.categories)),t.endpoint_uri&&s.append("endpoint_uri",t.endpoint_uri),t.clone_flow_id&&s.append("clone_flow_id",t.clone_flow_id),t.flow_json&&s.append("flow_json",t.flow_json),t.publish!==void 0&&s.append("publish",String(t.publish)),this.sendJson("POST",`/${e}/flows`,this.config.REQUEST_TIMEOUT,s)}async getFlow(e,t,s){let i=new URLSearchParams;t&&i.append("fields",t),s&&i.append("date_format",s);let p=i.toString()?`?${i.toString()}`:"";return this.sendJson("GET",`/${e}${p}`,this.config.REQUEST_TIMEOUT,null)}async updateFlowMetadata(e,t){let s=new FormData;return t.name&&s.append("name",t.name),t.categories&&s.append("categories",JSON.stringify(t.categories)),t.endpoint_uri&&s.append("endpoint_uri",t.endpoint_uri),t.application_id&&s.append("application_id",t.application_id),this.sendJson("POST",`/${e}`,this.config.REQUEST_TIMEOUT,s)}async deleteFlow(e){return this.sendJson("DELETE",`/${e}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(e){return this.sendJson("GET",`/${e}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(e,t){let s=new FormData;return s.append("asset_type",t.asset_type),s.append("file",t.file),s.append("name",t.name),this.sendJson("POST",`/${e}/assets`,this.config.REQUEST_TIMEOUT,s)}async publishFlow(e){return this.sendJson("POST",`/${e}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(e){return this.sendJson("POST",`/${e}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(e,t){let s=new FormData;return s.append("source_waba_id",t.source_waba_id),t.source_flow_names&&s.append("source_flow_names",JSON.stringify(t.source_flow_names)),this.sendJson("POST",`/${e}/migrate_flows`,this.config.REQUEST_TIMEOUT,s)}};var I=class extends o{endpoint="media";constructor(e,t){super(e,t)}async getMediaById(e){return this.sendJson("GET",`${e}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(e,t="whatsapp"){let s=new FormData;return s.append("file",e),s.append("messaging_product",t),s.append("type",e.type),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,s)}async deleteMedia(e){return this.sendJson("DELETE",`${e}`,this.config.REQUEST_TIMEOUT,null)}async downloadMedia(e){return this.sendJson("GET",e,this.config.REQUEST_TIMEOUT,null)}};var h=class extends o{commonMethod="POST";commonEndpoint="messages";constructor(e,t){super(e,t)}bodyBuilder(e,t,s,i){let p={messaging_product:"whatsapp",recipient_type:"individual",to:s,type:e,[e]:t};return i&&(p.context={message_id:i}),p}send(e){return this.sendJson(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/${this.commonEndpoint}`,this.config.REQUEST_TIMEOUT,e)}async audio(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("audio",t,s,i)))}async contacts(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("contacts",t,s,i)))}async document(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("document",t,s,i)))}async image(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("image",t,s,i)))}async interactive(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async location(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("location",t,s,i)))}async sticker(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("sticker",t,s,i)))}async template(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("template",t,s,i)))}async text(e){let{body:t,previewUrl:s,to:i,replyMessageId:p}=e,d;return typeof t=="string"?d={body:t,preview_url:s}:d=t,this.send(JSON.stringify(this.bodyBuilder("text",d,i,p)))}async video(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("video",t,s,i)))}async status(e){let{status:t,messageId:s,typingIndicator:i}=e,p={messaging_product:"whatsapp",status:t,message_id:s,...i&&{typing_indicator:i}};return this.send(JSON.stringify(p))}async markAsRead(e){return this.status({status:"read",messageId:e.messageId})}async showTypingIndicator(e){return this.status({status:"read",messageId:e.messageId,typingIndicator:{type:"text"}})}async interactiveList(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async interactiveCtaUrl(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async interactiveLocationRequest(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async interactiveAddressMessage(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async interactiveReplyButtons(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async interactiveFlow(e){let{body:t,to:s,replyMessageId:i}=e;return t.action.parameters.flow_message_version===void 0&&(t.action.parameters.flow_message_version="3"),t.action.parameters.mode===void 0&&(t.action.parameters.mode="published"),t.action.parameters.flow_action===void 0&&(t.action.parameters.flow_action="navigate"),t.action.parameters.flow_action==="navigate"?t.action.parameters.flow_action_payload?.screen===void 0&&(t.action.parameters.flow_action_payload={...t.action.parameters.flow_action_payload,screen:"INIT"}):t.action.parameters.flow_action==="data_exchange"&&delete t.action.parameters.flow_action_payload,this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async reaction(e){let{messageId:t,emoji:s,to:i}=e,p={messaging_product:"whatsapp",recipient_type:"individual",to:i,type:"reaction",reaction:{message_id:t,emoji:s}};return this.send(JSON.stringify(p))}};var g=class extends o{endpoint="phone_numbers";constructor(e,t){super(e,t)}async getPhoneNumberById(e){let t=e?n({fields:e}):"";return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}${t}`,this.config.REQUEST_TIMEOUT,null)}async getPhoneNumbers(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async requestVerificationCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async verifyCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}};var S=class extends o{endpoint="message_qrdls";constructor(e,t){super(e,t)}async createQrCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getQrCodes(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async getQrCode(e){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}async updateQrCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteQrCode(e){return this.sendJson("DELETE",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}};var T=class extends o{constructor(e,t){super(e,t)}async register(e,t){let s={messaging_product:"whatsapp",pin:e,...t&&{data_localization_region:t}};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/register`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async deregister(){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/deregister`,this.config.REQUEST_TIMEOUT,null)}};var A=class extends o{endpoint="message_templates";constructor(e,t){super(e,t)}async getTemplate(e){return this.sendJson("GET",`${e}`,this.config.REQUEST_TIMEOUT,null)}async updateTemplate(e,t){return this.sendJson("POST",`${e}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getTemplates(e){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${n(e)}`,this.config.REQUEST_TIMEOUT,null)}async createTemplate(e){return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteTemplate(e){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${n(e)}`,this.config.REQUEST_TIMEOUT,null)}};var q=class extends o{constructor(e,t){super(e,t)}async setTwoStepVerificationCode(e){let t={pin:e};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};var M=class extends o{constructor(e,t){super(e,t)}async getAllWabaSubscriptions(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async updateWabaSubscription({override_callback_uri:e,verify_token:t}){let s={override_callback_uri:e,verify_token:t};return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async unsubscribeFromWaba(){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}};0&&(module.exports={BaseAPI,BusinessProfileAPI,EncryptionAPI,FlowAPI,MediaAPI,MessagesAPI,PhoneNumberAPI,QrCodeAPI,RegistrationAPI,TemplateAPI,TwoStepVerificationAPI,WabaAPI});
|
|
1
|
+
"use strict";var N=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var D=Object.prototype.hasOwnProperty;var m=(o,e)=>{for(var t in e)N(o,t,{get:e[t],enumerable:!0})},U=(o,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of _(e))!D.call(o,i)&&i!==t&&N(o,i,{get:()=>e[i],enumerable:!(s=O(e,i))||s.enumerable});return o};var G=o=>U(N({},"__esModule",{value:!0}),o);var v={};m(v,{BaseAPI:()=>a,BusinessProfileAPI:()=>c,EncryptionAPI:()=>P,FlowAPI:()=>h,MediaAPI:()=>I,MessagesAPI:()=>g,PhoneNumberAPI:()=>S,QrCodeAPI:()=>T,RegistrationAPI:()=>A,TemplateAPI:()=>b,TwoStepVerificationAPI:()=>d,WabaAPI:()=>q});module.exports=G(v);var l=class{name;debug;constructor(e,t=!1){this.name=e,this.debug=t}log(...e){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log.apply(console,[t,": ",...e])}}error(...e){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error.apply(console,[t,": ",...e])}warn(...e){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn.apply(console,[t,": ",...e])}info(...e){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info.apply(console,[t,": ",...e])}};var w="BaseAPI",F=!1,J=new l(w,process.env.DEBUG==="true"||F),a=class{config;client;constructor(e,t){this.config=e,this.client=t,J.log("Initialized with HTTPSClient")}sendJson(e,t,s,i){return this.client.getJson(e,t,s,i)}};var R=o=>{if(!o||Object.keys(o).length===0)return"";let e=new URLSearchParams;for(let[s,i]of Object.entries(o))i!==void 0&&e.append(s,String(i));let t=e.toString();return t?`?${t}`:""};var c=class extends a{endpoint="whatsapp_business_profile";constructor(e,t){super(e,t)}async getBusinessProfile(e){let t=e?R({fields:e}):"";return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${t}`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessProfile(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async createUploadSession(e,t,s){let i=R({file_length:e,file_type:t,file_name:s});return this.sendJson("POST",`app/uploads/${i}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(e,t){return this.sendJson("POST",`${e}`,this.config.REQUEST_TIMEOUT,t)}async getUploadHandle(e){return this.sendJson("GET",`${e}`,this.config.REQUEST_TIMEOUT,null)}};var P=class extends a{endpoint="whatsapp_business_encryption";constructor(e,t){super(e,t)}async getEncryptionPublicKey(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async setEncryptionPublicKey(e){let t=new FormData;return t.append("business_public_key",e),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,t)}};var x="FlowAPI",K=!1,M=new l(x,process.env.DEBUG==="true"||K),h=class extends a{constructor(e,t){super(e,t),M.log("FlowAPI initialized")}async listFlows(e){return this.sendJson("GET",`/${e}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(e,t){let s={name:t.name,categories:t.categories,...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.clone_flow_id&&{clone_flow_id:t.clone_flow_id},...t.flow_json&&{flow_json:t.flow_json},...t.publish!==void 0&&{publish:t.publish}};return this.sendJson("POST",`/${e}/flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async getFlow(e,t,s){let i=new URLSearchParams;t&&i.append("fields",t),s&&i.append("date_format",s);let p=i.toString()?`?${i.toString()}`:"";return this.sendJson("GET",`/${e}${p}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(e,t=!1){let s=`preview.invalidate(${t})`;return this.getFlow(e,s)}async updateFlowMetadata(e,t){let s={...t.name&&{name:t.name},...t.categories&&{categories:t.categories},...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.application_id&&{application_id:t.application_id}};return this.sendJson("POST",`/${e}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async deleteFlow(e){return this.sendJson("DELETE",`/${e}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(e){return this.sendJson("GET",`/${e}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(e,t){let s=new FormData,i;if(t.file instanceof Buffer)i=new globalThis.Blob([t.file]),s.append("file",i);else if(typeof t.file=="object"&&!(t.file instanceof Blob))try{i=new globalThis.Blob([JSON.stringify(t.file,null,2)],{type:"application/json"}),s.append("file",i)}catch{throw new Error("Failed to stringify JSON object for Flow JSON update.")}else if(t.file instanceof Blob)i=t.file,s.append("file",i);else throw new Error("Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.");return s.append("asset_type","FLOW_JSON"),s.append("name",t.name||"flow.json"),this.sendJson("POST",`/${e}/assets`,this.config.REQUEST_TIMEOUT,s)}async validateFlowJson(e,t){try{let i=await(await this.updateFlowJson(e,{file:t})).json(),p=!i.validation_errors||i.validation_errors.length===0,f={...i,valid:p};return{json:async()=>f}}catch(s){throw M.error("Error during Flow JSON validation attempt:",s),s}}async publishFlow(e){return this.sendJson("POST",`/${e}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(e){return this.sendJson("POST",`/${e}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(e,t){let s={source_waba_id:t.source_waba_id,...t.source_flow_names&&{source_flow_names:t.source_flow_names}};return this.sendJson("POST",`/${e}/migrate_flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}};var I=class extends a{endpoint="media";constructor(e,t){super(e,t)}async getMediaById(e){return this.sendJson("GET",`${e}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(e,t="whatsapp"){let s=new FormData;return s.append("file",e),s.append("messaging_product",t),s.append("type",e.type),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,s)}async deleteMedia(e){return this.sendJson("DELETE",`${e}`,this.config.REQUEST_TIMEOUT,null)}async downloadMedia(e){return this.sendJson("GET",e,this.config.REQUEST_TIMEOUT,null)}};var g=class extends a{commonMethod="POST";commonEndpoint="messages";constructor(e,t){super(e,t)}bodyBuilder(e,t,s,i){let p={messaging_product:"whatsapp",recipient_type:"individual",to:s,type:e,[e]:t};return i&&(p.context={message_id:i}),p}send(e){return this.sendJson(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/${this.commonEndpoint}`,this.config.REQUEST_TIMEOUT,e)}async audio(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("audio",t,s,i)))}async contacts(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("contacts",t,s,i)))}async document(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("document",t,s,i)))}async image(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("image",t,s,i)))}async interactive(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async location(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("location",t,s,i)))}async sticker(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("sticker",t,s,i)))}async template(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("template",t,s,i)))}async text(e){let{body:t,previewUrl:s,to:i,replyMessageId:p}=e,f;return typeof t=="string"?f={body:t,preview_url:s}:f=t,this.send(JSON.stringify(this.bodyBuilder("text",f,i,p)))}async video(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("video",t,s,i)))}async status(e){let{status:t,messageId:s,typingIndicator:i}=e,p={messaging_product:"whatsapp",status:t,message_id:s,...i&&{typing_indicator:i}};return this.send(JSON.stringify(p))}async markAsRead(e){return this.status({status:"read",messageId:e.messageId})}async showTypingIndicator(e){return this.status({status:"read",messageId:e.messageId,typingIndicator:{type:"text"}})}async interactiveList(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async interactiveCtaUrl(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async interactiveLocationRequest(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async interactiveAddressMessage(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async interactiveReplyButtons(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async interactiveFlow(e){let{body:t,to:s,replyMessageId:i}=e;return t.action.parameters.flow_message_version===void 0&&(t.action.parameters.flow_message_version="3"),t.action.parameters.mode===void 0&&(t.action.parameters.mode="published"),t.action.parameters.flow_action===void 0&&(t.action.parameters.flow_action="navigate"),t.action.parameters.flow_action==="navigate"?t.action.parameters.flow_action_payload?.screen===void 0&&(t.action.parameters.flow_action_payload={...t.action.parameters.flow_action_payload,screen:"INIT"}):t.action.parameters.flow_action==="data_exchange"&&delete t.action.parameters.flow_action_payload,this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async reaction(e){let{messageId:t,emoji:s,to:i}=e,p={messaging_product:"whatsapp",recipient_type:"individual",to:i,type:"reaction",reaction:{message_id:t,emoji:s}};return this.send(JSON.stringify(p))}};var S=class extends a{endpoint="phone_numbers";constructor(e,t){super(e,t)}async getPhoneNumberById(e){let t=e?R({fields:e}):"";return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}${t}`,this.config.REQUEST_TIMEOUT,null)}async getPhoneNumbers(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async requestVerificationCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async verifyCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}};var T=class extends a{endpoint="message_qrdls";constructor(e,t){super(e,t)}async createQrCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getQrCodes(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async getQrCode(e){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}async updateQrCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteQrCode(e){return this.sendJson("DELETE",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}};var A=class extends a{constructor(e,t){super(e,t)}async register(e,t){let s={messaging_product:"whatsapp",pin:e,...t&&{data_localization_region:t}};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/register`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async deregister(){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/deregister`,this.config.REQUEST_TIMEOUT,null)}};var b=class extends a{endpoint="message_templates";constructor(e,t){super(e,t)}async getTemplate(e){return this.sendJson("GET",`${e}`,this.config.REQUEST_TIMEOUT,null)}async updateTemplate(e,t){return this.sendJson("POST",`${e}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getTemplates(e){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${R(e)}`,this.config.REQUEST_TIMEOUT,null)}async createTemplate(e){return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteTemplate(e){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${R(e)}`,this.config.REQUEST_TIMEOUT,null)}};var d=class extends a{constructor(e,t){super(e,t)}async setTwoStepVerificationCode(e){let t={pin:e};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};function B(o){if(!o)return"";let e="";return Array.isArray(o)?e=o.join(","):e=Object.entries(o).filter(([t,s])=>s).map(([t])=>t).join(","),e?`?fields=${e}`:""}var q=class extends a{constructor(e,t){super(e,t)}async getWabaAccount(e){let t=B(e);return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}${t}`,this.config.REQUEST_TIMEOUT,null)}async getAllWabaSubscriptions(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async updateWabaSubscription({override_callback_uri:e,verify_token:t}){let s={override_callback_uri:e,verify_token:t};return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async unsubscribeFromWaba(){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}};0&&(module.exports={BaseAPI,BusinessProfileAPI,EncryptionAPI,FlowAPI,MediaAPI,MessagesAPI,PhoneNumberAPI,QrCodeAPI,RegistrationAPI,TemplateAPI,TwoStepVerificationAPI,WabaAPI});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|