meta-cloud-api 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/dist/api/base.d.mts +3 -1
  2. package/dist/api/base.d.ts +3 -1
  3. package/dist/api/base.js +1 -1
  4. package/dist/api/base.js.map +1 -1
  5. package/dist/api/base.mjs +1 -1
  6. package/dist/api/base.mjs.map +1 -1
  7. package/dist/api/businessProfile.d.mts +5 -2
  8. package/dist/api/businessProfile.d.ts +5 -2
  9. package/dist/api/businessProfile.js +1 -1
  10. package/dist/api/businessProfile.js.map +1 -1
  11. package/dist/api/businessProfile.mjs +1 -1
  12. package/dist/api/businessProfile.mjs.map +1 -1
  13. package/dist/api/encryption.js +1 -1
  14. package/dist/api/encryption.js.map +1 -1
  15. package/dist/api/encryption.mjs +1 -1
  16. package/dist/api/encryption.mjs.map +1 -1
  17. package/dist/api/flow.js +1 -1
  18. package/dist/api/flow.js.map +1 -1
  19. package/dist/api/flow.mjs +1 -1
  20. package/dist/api/flow.mjs.map +1 -1
  21. package/dist/api/index.d.mts +1 -1
  22. package/dist/api/index.d.ts +1 -1
  23. package/dist/api/index.js +1 -1
  24. package/dist/api/index.js.map +1 -1
  25. package/dist/api/index.mjs +1 -1
  26. package/dist/api/index.mjs.map +1 -1
  27. package/dist/api/media.js +1 -1
  28. package/dist/api/media.js.map +1 -1
  29. package/dist/api/media.mjs +1 -1
  30. package/dist/api/media.mjs.map +1 -1
  31. package/dist/api/messages.js +1 -1
  32. package/dist/api/messages.js.map +1 -1
  33. package/dist/api/messages.mjs +1 -1
  34. package/dist/api/messages.mjs.map +1 -1
  35. package/dist/api/phoneNumber.js +1 -1
  36. package/dist/api/phoneNumber.js.map +1 -1
  37. package/dist/api/phoneNumber.mjs +1 -1
  38. package/dist/api/phoneNumber.mjs.map +1 -1
  39. package/dist/api/qrCode.js +1 -1
  40. package/dist/api/qrCode.js.map +1 -1
  41. package/dist/api/qrCode.mjs +1 -1
  42. package/dist/api/qrCode.mjs.map +1 -1
  43. package/dist/api/registration.js +1 -1
  44. package/dist/api/registration.js.map +1 -1
  45. package/dist/api/registration.mjs +1 -1
  46. package/dist/api/registration.mjs.map +1 -1
  47. package/dist/api/template.js +1 -1
  48. package/dist/api/template.js.map +1 -1
  49. package/dist/api/template.mjs +1 -1
  50. package/dist/api/template.mjs.map +1 -1
  51. package/dist/api/twoStepVerification.js +1 -1
  52. package/dist/api/twoStepVerification.js.map +1 -1
  53. package/dist/api/twoStepVerification.mjs +1 -1
  54. package/dist/api/twoStepVerification.mjs.map +1 -1
  55. package/dist/api/waba.js +1 -1
  56. package/dist/api/waba.js.map +1 -1
  57. package/dist/api/waba.mjs +1 -1
  58. package/dist/api/waba.mjs.map +1 -1
  59. package/dist/index.d.mts +1 -1
  60. package/dist/index.d.ts +1 -1
  61. package/dist/index.js +1 -1
  62. package/dist/index.js.map +1 -1
  63. package/dist/index.mjs +1 -1
  64. package/dist/index.mjs.map +1 -1
  65. package/dist/request.d.mts +5 -3
  66. package/dist/request.d.ts +5 -3
  67. package/dist/request.js +1 -1
  68. package/dist/request.js.map +1 -1
  69. package/dist/request.mjs +1 -1
  70. package/dist/request.mjs.map +1 -1
  71. package/dist/types/businessProfile.d.mts +8 -4
  72. package/dist/types/businessProfile.d.ts +8 -4
  73. package/dist/types/businessProfile.js +1 -1
  74. package/dist/types/businessProfile.js.map +1 -1
  75. package/dist/types/index.d.mts +1 -1
  76. package/dist/types/index.d.ts +1 -1
  77. package/dist/types/request.d.mts +5 -3
  78. package/dist/types/request.d.ts +5 -3
  79. package/dist/types/request.js +1 -1
  80. package/dist/types/request.js.map +1 -1
  81. package/dist/whatsapp.js +1 -1
  82. package/dist/whatsapp.js.map +1 -1
  83. package/dist/whatsapp.mjs +1 -1
  84. package/dist/whatsapp.mjs.map +1 -1
  85. package/package.json +2 -2
@@ -14,10 +14,12 @@ declare class Requester implements RequesterClass {
14
14
  host: Readonly<string>;
15
15
  protocol: Readonly<string>;
16
16
  constructor(host: string, apiVersion: string, phoneNumberId: number, accessToken: string, businessAcctId: string, userAgent: string);
17
- buildHeader(contentType: string): HeadersInit;
17
+ buildHeader(contentType: string, additionalHeaders?: Record<string, string>): HeadersInit;
18
18
  buildCAPIPath(endpoint: string): string;
19
- sendRequest(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<HttpsClientResponseClass>;
20
- getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T>;
19
+ sendRequest(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any, contentType?: string, additionalHeaders?: Record<string, string>): Promise<HttpsClientResponseClass>;
20
+ getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any, additionalHeaders?: Record<string, string>): Promise<T>;
21
+ sendFormData<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: FormData, additionalHeaders?: Record<string, string>): Promise<T>;
22
+ sendUrlEncodedForm<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: Record<string, string>, additionalHeaders?: Record<string, string>): Promise<T>;
21
23
  }
22
24
 
23
25
  export { Requester as default };
package/dist/request.d.ts CHANGED
@@ -14,10 +14,12 @@ declare class Requester implements RequesterClass {
14
14
  host: Readonly<string>;
15
15
  protocol: Readonly<string>;
16
16
  constructor(host: string, apiVersion: string, phoneNumberId: number, accessToken: string, businessAcctId: string, userAgent: string);
17
- buildHeader(contentType: string): HeadersInit;
17
+ buildHeader(contentType: string, additionalHeaders?: Record<string, string>): HeadersInit;
18
18
  buildCAPIPath(endpoint: string): string;
19
- sendRequest(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<HttpsClientResponseClass>;
20
- getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T>;
19
+ sendRequest(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any, contentType?: string, additionalHeaders?: Record<string, string>): Promise<HttpsClientResponseClass>;
20
+ getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any, additionalHeaders?: Record<string, string>): Promise<T>;
21
+ sendFormData<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: FormData, additionalHeaders?: Record<string, string>): Promise<T>;
22
+ sendUrlEncodedForm<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: Record<string, string>, additionalHeaders?: Record<string, string>): Promise<T>;
21
23
  }
22
24
 
23
25
  export { Requester as default };
package/dist/request.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var m=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var R=Object.prototype.hasOwnProperty;var E=(r,e)=>{for(var t in e)m(r,t,{get:e[t],enumerable:!0})},C=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of w(e))!R.call(r,o)&&o!==t&&m(r,o,{get:()=>e[o],enumerable:!(n=b(e,o))||n.enumerable});return r};var _=r=>C(m({},"__esModule",{value:!0}),r);var L={};E(L,{default:()=>u});module.exports=_(L);var f=require("https");var a=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 H="HttpsClient",$=!1,A=new a(H,process.env.DEBUG==="true"||$),l=class{agent;constructor(){this.agent=new f.Agent({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(e,t,n,o,i,c){let s=`https://${e}/${t}`,p=new AbortController,y=setTimeout(()=>p.abort(),i);try{let d=await fetch(s,{method:n,headers:o,body:c,signal:p.signal});return A.log(`${n} : ${s} - ${JSON.stringify(d)}`),clearTimeout(y),new g(d)}catch(d){throw d}}},g=class{res;respStatusCode;respHeaders;constructor(e){this.res=e,this.respStatusCode=e.status,this.respHeaders=Object.fromEntries(e.headers.entries())}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(e){throw new Error("Failed to parse response body to JSON: "+e.message)}}};function h(r){return r!=null&&typeof r=="object"&&"error"in r&&typeof r.error=="object"&&r.error!=null&&"message"in r.error&&typeof r.error.message=="string"&&"type"in r.error&&typeof r.error.type=="string"&&"code"in r.error&&typeof r.error.code=="number"&&"fbtrace_id"in r.error&&typeof r.error.fbtrace_id=="string"&&(!("error_data"in r.error)||typeof r.error.error_data=="object"&&r.error.error_data!=null&&"messaging_product"in r.error.error_data&&r.error.error_data.messaging_product==="whatsapp"&&"details"in r.error.error_data&&typeof r.error.error_data.details=="string")&&(!("error_subcode"in r.error)||typeof r.error.error_subcode=="number")}var I="REQUESTER",M=!1,O=new a(I,process.env.DEBUG==="true"||M),u=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(e,t,n,o,i,c){this.client=new l,this.host=e||"graph.facebook.com",this.apiVersion=t||"22",this.phoneNumberId=n,this.accessToken=o,this.businessAcctId=i,this.userAgent=c}buildHeader(e){return{"Content-Type":e,Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent}}buildCAPIPath(e){return`v${this.apiVersion}.0/${e}`}async sendRequest(e,t,n,o){let i="application/json",c=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(t)}`;O.log(`${e} : ${c}`);try{let s=await this.client.sendRequest(this.host,this.buildCAPIPath(t),e,this.buildHeader(i),n,e==="POST"||e==="PUT"?o:void 0);if(!s.rawResponse().ok){let p=await s.json();throw h(p)?p:{name:"MetaError",message:"Unknown error occurred",error:{message:p.message||"Unknown error occurred",type:"UnknownError",code:s.statusCode(),fbtrace_id:""}}}return s}catch(s){throw h(s)?s:{name:"MetaError",message:s instanceof Error?s.message:"Network error occurred",error:{message:s instanceof Error?s.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}async getJson(e,t,n,o){return await(await this.sendRequest(e,t,n,o)).json()}};
1
+ "use strict";var g=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var b=Object.prototype.hasOwnProperty;var E=(t,e)=>{for(var r in e)g(t,r,{get:e[r],enumerable:!0})},C=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of R(e))!b.call(t,s)&&s!==r&&g(t,s,{get:()=>e[s],enumerable:!(n=w(e,s))||n.enumerable});return t};var H=t=>C(g({},"__esModule",{value:!0}),t);var O={};E(O,{default:()=>m});module.exports=H(O);var y=require("https");var d=class{name;debug;constructor(e,r=!1){this.name=e,this.debug=r}log(...e){if(this.debug){let r=`[ ${Date.now()} ]`;this.name&&(r+=` - ${this.name}`),console.log.apply(console,[r,": ",...e])}}error(...e){let r=`[ ${Date.now()} ] - ERROR`;this.name&&(r+=` - ${this.name}`),console.error.apply(console,[r,": ",...e])}warn(...e){let r=`[ ${Date.now()} ] - WARN`;this.name&&(r+=` - ${this.name}`),console.warn.apply(console,[r,": ",...e])}info(...e){let r=`[ ${Date.now()} ] - INFO`;this.name&&(r+=` - ${this.name}`),console.info.apply(console,[r,": ",...e])}};var _="HttpsClient",$=!1,A=new d(_,process.env.DEBUG==="true"||$),l=class{agent;constructor(){this.agent=new y.Agent({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(e,r,n,s,a,i){let c=`https://${e}/${r}`,u=new AbortController,o=setTimeout(()=>u.abort(),a);try{let p=await fetch(c,{method:n,headers:s,body:i,signal:u.signal});return A.log(`${n} : ${c} - ${JSON.stringify(p)}`),clearTimeout(o),new h(p)}catch(p){throw p}}},h=class{res;respStatusCode;respHeaders;constructor(e){this.res=e,this.respStatusCode=e.status,this.respHeaders=Object.fromEntries(e.headers.entries())}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(e){throw new Error("Failed to parse response body to JSON: "+e.message)}}};function f(t){return t!=null&&typeof t=="object"&&"error"in t&&typeof t.error=="object"&&t.error!=null&&"message"in t.error&&typeof t.error.message=="string"&&"type"in t.error&&typeof t.error.type=="string"&&"code"in t.error&&typeof t.error.code=="number"&&"fbtrace_id"in t.error&&typeof t.error.fbtrace_id=="string"&&(!("error_data"in t.error)||typeof t.error.error_data=="object"&&t.error.error_data!=null&&"messaging_product"in t.error.error_data&&t.error.error_data.messaging_product==="whatsapp"&&"details"in t.error.error_data&&typeof t.error.error_data.details=="string")&&(!("error_subcode"in t.error)||typeof t.error.error_subcode=="number")}var M="REQUESTER",T=!1,I=new d(M,process.env.DEBUG==="true"||T),m=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(e,r,n,s,a,i){this.client=new l,this.host=e||"graph.facebook.com",this.apiVersion=r||"22",this.phoneNumberId=n,this.accessToken=s,this.businessAcctId=a,this.userAgent=i}buildHeader(e,r){let n={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return e!=="multipart/form-data"&&(n["Content-Type"]=e),r&&Object.assign(n,r),n}buildCAPIPath(e){return`v${this.apiVersion}.0/${e}`}async sendRequest(e,r,n,s,a="application/json",i){let c=a;s instanceof FormData?c="multipart/form-data":typeof s=="string"&&s.startsWith("<?xml")&&(c="application/xml");let u=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(r)}`;I.log(`${e} : ${u} (${c})`);try{let o=await this.client.sendRequest(this.host,this.buildCAPIPath(r),e,this.buildHeader(c,i),n,e==="POST"||e==="PUT"?s:void 0);if(!o.rawResponse().ok){let p=await o.json();throw f(p)?p:{name:"MetaError",message:"Unknown error occurred",error:{message:p.message||"Unknown error occurred",type:"UnknownError",code:o.statusCode(),fbtrace_id:""}}}return o}catch(o){throw f(o)?o:{name:"MetaError",message:o instanceof Error?o.message:"Network error occurred",error:{message:o instanceof Error?o.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}async getJson(e,r,n,s,a){return await(await this.sendRequest(e,r,n,s,"application/json",a)).json()}async sendFormData(e,r,n,s,a){return await(await this.sendRequest(e,r,n,s,"multipart/form-data",a)).json()}async sendUrlEncodedForm(e,r,n,s,a){let i=new URLSearchParams(s).toString();return await(await this.sendRequest(e,r,n,i,"application/x-www-form-urlencoded",a)).json()}};
2
2
  //# sourceMappingURL=request.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/request.ts","../src/httpsClient.ts","../src/utils/logger.ts","../src/utils/isMetaError.ts"],"sourcesContent":["import HttpsClient from './httpsClient';\nimport type { HttpMethodsEnum } from './types/enums';\nimport type { RequesterClass } from './types/request';\nimport { isMetaError, MetaError } from './utils/isMetaError';\nimport Logger from './utils/logger';\n\nconst LIB_NAME = 'REQUESTER';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class Requester implements RequesterClass {\n client: Readonly<HttpsClient>;\n accessToken: Readonly<string>;\n phoneNumberId: Readonly<number>;\n businessAcctId: Readonly<string>;\n apiVersion: Readonly<string>;\n userAgent: Readonly<string>;\n host: Readonly<string>;\n protocol: Readonly<string> = 'https:';\n\n constructor(\n host: string,\n apiVersion: string,\n phoneNumberId: number,\n accessToken: string,\n businessAcctId: string,\n userAgent: string,\n ) {\n this.client = new HttpsClient();\n this.host = host || 'graph.facebook.com';\n this.apiVersion = apiVersion || '22';\n this.phoneNumberId = phoneNumberId;\n this.accessToken = accessToken;\n this.businessAcctId = businessAcctId;\n this.userAgent = userAgent;\n }\n\n buildHeader(contentType: string): HeadersInit {\n const headers: HeadersInit = {\n 'Content-Type': contentType,\n Authorization: `Bearer ${this.accessToken}`,\n 'User-Agent': this.userAgent,\n };\n return headers;\n }\n\n buildCAPIPath(endpoint: string): string {\n return `v${this.apiVersion}.0/${endpoint}`;\n }\n\n async sendRequest(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any) {\n const contentType = 'application/json';\n const path = `${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(endpoint)}`;\n\n LOGGER.log(`${method} : ${path}`);\n\n try {\n const response = await this.client.sendRequest(\n this.host,\n this.buildCAPIPath(endpoint),\n method,\n this.buildHeader(contentType),\n timeout,\n method === 'POST' || method === 'PUT' ? body : undefined,\n );\n\n if (!response.rawResponse().ok) {\n const errorData = await response.json();\n if (isMetaError(errorData)) {\n throw errorData;\n }\n // If the error doesn't match Meta's format, create a generic MetaError\n throw {\n name: 'MetaError',\n message: 'Unknown error occurred',\n error: {\n message: errorData.message || 'Unknown error occurred',\n type: 'UnknownError',\n code: response.statusCode(),\n fbtrace_id: '',\n },\n } as MetaError;\n }\n\n return response;\n } catch (error) {\n if (isMetaError(error)) {\n throw error;\n }\n // Handle network errors or other unexpected errors\n throw {\n name: 'MetaError',\n message: error instanceof Error ? error.message : 'Network error occurred',\n error: {\n message: error instanceof Error ? error.message : 'Network error occurred',\n type: 'NetworkError',\n code: 500,\n fbtrace_id: '',\n },\n } as MetaError;\n }\n }\n\n async getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n const res = await this.sendRequest(method, endpoint, timeout, body);\n return (await res.json()) as T;\n }\n}\n","import { Agent } from 'https';\n\nimport Logger from './utils/logger';\nimport { HttpMethodsEnum } from './types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from './types/httpsClient';\n\nconst LIB_NAME = 'HttpsClient';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class HttpsClient implements HttpsClientClass {\n agent: Agent;\n\n constructor() {\n this.agent = new Agent({ keepAlive: true });\n }\n\n clearSockets(): boolean {\n this.agent.destroy();\n return true;\n }\n\n async sendRequest(\n hostname: string,\n path: string,\n method: HttpMethodsEnum,\n headers: HeadersInit,\n timeout: number,\n body?: BodyInit | null,\n ): Promise<HttpsClientResponseClass> {\n const url = `https://${hostname}/${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n LOGGER.log(`${method} : ${url} - ${JSON.stringify(response)}`);\n\n clearTimeout(timeoutId);\n return new HttpsClientResponse(response);\n } catch (error) {\n throw error;\n }\n }\n}\n\nexport class HttpsClientResponse implements HttpsClientResponseClass {\n res: Response;\n respStatusCode: number;\n respHeaders: ResponseHeaders;\n\n constructor(resp: Response) {\n this.res = resp;\n this.respStatusCode = resp.status;\n this.respHeaders = Object.fromEntries(resp.headers.entries());\n }\n\n statusCode(): number {\n return this.respStatusCode;\n }\n\n headers(): ResponseHeaders {\n return this.respHeaders;\n }\n\n rawResponse(): Response {\n return this.res;\n }\n\n async json(): Promise<ResponseJSONBody> {\n try {\n return (await this.res.json()) as ResponseJSONBody;\n } catch (err) {\n // TODO Error Handling\n throw new Error('Failed to parse response body to JSON: ' + (err as Error).message);\n }\n }\n}\n","// @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","export interface MetaError extends Error {\n error: {\n message: string;\n type: string;\n code: number;\n error_data?: {\n messaging_product: 'whatsapp';\n details: string;\n };\n error_subcode?: number;\n fbtrace_id: string;\n };\n}\n\n/**\n * Determines if the error is a Meta API error response\n * @param error Any error object to check\n * @returns Type guard indicating if error is a Meta API error\n */\nexport function isMetaError(error: any): error is MetaError {\n return (\n error != null &&\n typeof error === 'object' &&\n 'error' in error &&\n typeof error.error === 'object' &&\n error.error != null &&\n 'message' in error.error &&\n typeof error.error.message === 'string' &&\n 'type' in error.error &&\n typeof error.error.type === 'string' &&\n 'code' in error.error &&\n typeof error.error.code === 'number' &&\n 'fbtrace_id' in error.error &&\n typeof error.error.fbtrace_id === 'string' &&\n (!('error_data' in error.error) ||\n (typeof error.error.error_data === 'object' &&\n error.error.error_data != null &&\n 'messaging_product' in error.error.error_data &&\n error.error.error_data.messaging_product === 'whatsapp' &&\n 'details' in error.error.error_data &&\n typeof error.error.error_data.details === 'string')) &&\n (!('error_subcode' in error.error) || typeof error.error.error_subcode === 'number')\n );\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GCAA,IAAAI,EAAsB,iBCGtB,IAAqBC,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,CACtD,CACJ,CAEA,SAASA,EAAa,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J,CACJ,CACJ,CAEA,MAAM,QAAWP,EAAyBD,EAAkBE,EAAiBC,EAAwB,CAEjG,OAAQ,MADI,MAAM,KAAK,YAAYF,EAAQD,EAAUE,EAASC,CAAI,GAChD,KAAK,CAC3B,CACJ","names":["request_exports","__export","Requester","__toCommonJS","import_https","Logger","name","debug","data","prefix","LIB_NAME","LOG_LOCAL","LOGGER","Logger","HttpsClient","hostname","path","method","headers","timeout","body","url","controller","timeoutId","response","HttpsClientResponse","error","resp","err","isMetaError","error","LIB_NAME","LOG_LOCAL","LOGGER","Logger","Requester","host","apiVersion","phoneNumberId","accessToken","businessAcctId","userAgent","HttpsClient","contentType","endpoint","method","timeout","body","path","response","errorData","isMetaError","error"]}
1
+ {"version":3,"sources":["../src/request.ts","../src/httpsClient.ts","../src/utils/logger.ts","../src/utils/isMetaError.ts"],"sourcesContent":["import HttpsClient from './httpsClient';\nimport type { HttpMethodsEnum } from './types/enums';\nimport type { RequesterClass } from './types/request';\nimport { isMetaError, MetaError } from './utils/isMetaError';\nimport Logger from './utils/logger';\n\nconst LIB_NAME = 'REQUESTER';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class Requester implements RequesterClass {\n client: Readonly<HttpsClient>;\n accessToken: Readonly<string>;\n phoneNumberId: Readonly<number>;\n businessAcctId: Readonly<string>;\n apiVersion: Readonly<string>;\n userAgent: Readonly<string>;\n host: Readonly<string>;\n protocol: Readonly<string> = 'https:';\n\n constructor(\n host: string,\n apiVersion: string,\n phoneNumberId: number,\n accessToken: string,\n businessAcctId: string,\n userAgent: string,\n ) {\n this.client = new HttpsClient();\n this.host = host || 'graph.facebook.com';\n this.apiVersion = apiVersion || '22';\n this.phoneNumberId = phoneNumberId;\n this.accessToken = accessToken;\n this.businessAcctId = businessAcctId;\n this.userAgent = userAgent;\n }\n\n buildHeader(contentType: string, additionalHeaders?: Record<string, string>): HeadersInit {\n const headers: HeadersInit = {\n Authorization: `Bearer ${this.accessToken}`,\n 'User-Agent': this.userAgent,\n };\n\n if (contentType !== 'multipart/form-data') {\n headers['Content-Type'] = contentType;\n }\n\n if (additionalHeaders) {\n Object.assign(headers, additionalHeaders);\n }\n\n return headers;\n }\n\n buildCAPIPath(endpoint: string): string {\n return `v${this.apiVersion}.0/${endpoint}`;\n }\n\n async sendRequest(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n contentType: string = 'application/json',\n additionalHeaders?: Record<string, string>,\n ) {\n let effectiveContentType = contentType;\n\n if (body instanceof FormData) {\n effectiveContentType = 'multipart/form-data';\n } else if (typeof body === 'string' && body.startsWith('<?xml')) {\n effectiveContentType = 'application/xml';\n }\n\n const path = `${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(endpoint)}`;\n\n LOGGER.log(`${method} : ${path} (${effectiveContentType})`);\n\n try {\n const response = await this.client.sendRequest(\n this.host,\n this.buildCAPIPath(endpoint),\n method,\n this.buildHeader(effectiveContentType, additionalHeaders),\n timeout,\n method === 'POST' || method === 'PUT' ? body : undefined,\n );\n\n if (!response.rawResponse().ok) {\n const errorData = await response.json();\n if (isMetaError(errorData)) {\n throw errorData;\n }\n // If the error doesn't match Meta's format, create a generic MetaError\n throw {\n name: 'MetaError',\n message: 'Unknown error occurred',\n error: {\n message: errorData.message || 'Unknown error occurred',\n type: 'UnknownError',\n code: response.statusCode(),\n fbtrace_id: '',\n },\n } as MetaError;\n }\n\n return response;\n } catch (error) {\n if (isMetaError(error)) {\n throw error;\n }\n // Handle network errors or other unexpected errors\n throw {\n name: 'MetaError',\n message: error instanceof Error ? error.message : 'Network error occurred',\n error: {\n message: error instanceof Error ? error.message : 'Network error occurred',\n type: 'NetworkError',\n code: 500,\n fbtrace_id: '',\n },\n } as MetaError;\n }\n }\n\n async getJson<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(method, endpoint, timeout, body, 'application/json', additionalHeaders);\n return (await res.json()) as T;\n }\n\n async sendFormData<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: FormData,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n formData,\n 'multipart/form-data',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n\n async sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: Record<string, string>,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const urlEncodedBody = new URLSearchParams(formData).toString();\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n urlEncodedBody,\n 'application/x-www-form-urlencoded',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n}\n","import { Agent } from 'https';\n\nimport Logger from './utils/logger';\nimport { HttpMethodsEnum } from './types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from './types/httpsClient';\n\nconst LIB_NAME = 'HttpsClient';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class HttpsClient implements HttpsClientClass {\n agent: Agent;\n\n constructor() {\n this.agent = new Agent({ keepAlive: true });\n }\n\n clearSockets(): boolean {\n this.agent.destroy();\n return true;\n }\n\n async sendRequest(\n hostname: string,\n path: string,\n method: HttpMethodsEnum,\n headers: HeadersInit,\n timeout: number,\n body?: BodyInit | null,\n ): Promise<HttpsClientResponseClass> {\n const url = `https://${hostname}/${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n LOGGER.log(`${method} : ${url} - ${JSON.stringify(response)}`);\n\n clearTimeout(timeoutId);\n return new HttpsClientResponse(response);\n } catch (error) {\n throw error;\n }\n }\n}\n\nexport class HttpsClientResponse implements HttpsClientResponseClass {\n res: Response;\n respStatusCode: number;\n respHeaders: ResponseHeaders;\n\n constructor(resp: Response) {\n this.res = resp;\n this.respStatusCode = resp.status;\n this.respHeaders = Object.fromEntries(resp.headers.entries());\n }\n\n statusCode(): number {\n return this.respStatusCode;\n }\n\n headers(): ResponseHeaders {\n return this.respHeaders;\n }\n\n rawResponse(): Response {\n return this.res;\n }\n\n async json(): Promise<ResponseJSONBody> {\n try {\n return (await this.res.json()) as ResponseJSONBody;\n } catch (err) {\n // TODO Error Handling\n throw new Error('Failed to parse response body to JSON: ' + (err as Error).message);\n }\n }\n}\n","// @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","export interface MetaError extends Error {\n error: {\n message: string;\n type: string;\n code: number;\n error_data?: {\n messaging_product: 'whatsapp';\n details: string;\n };\n error_subcode?: number;\n fbtrace_id: string;\n };\n}\n\n/**\n * Determines if the error is a Meta API error response\n * @param error Any error object to check\n * @returns Type guard indicating if error is a Meta API error\n */\nexport function isMetaError(error: any): error is MetaError {\n return (\n error != null &&\n typeof error === 'object' &&\n 'error' in error &&\n typeof error.error === 'object' &&\n error.error != null &&\n 'message' in error.error &&\n typeof error.error.message === 'string' &&\n 'type' in error.error &&\n typeof error.error.type === 'string' &&\n 'code' in error.error &&\n typeof error.error.code === 'number' &&\n 'fbtrace_id' in error.error &&\n typeof error.error.fbtrace_id === 'string' &&\n (!('error_data' in error.error) ||\n (typeof error.error.error_data === 'object' &&\n error.error.error_data != null &&\n 'messaging_product' in error.error.error_data &&\n error.error.error_data.messaging_product === 'whatsapp' &&\n 'details' in error.error.error_data &&\n typeof error.error.error_data.details === 'string')) &&\n (!('error_subcode' in error.error) || typeof error.error.error_subcode === 'number')\n );\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GCAA,IAAAI,EAAsB,iBCGtB,IAAqBC,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,CACtD,CACJ,CAEA,SAASA,EAAa,CAClB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,aACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,MAAM,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACxD,CAEA,QAAQA,EAAa,CACjB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,YACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,KAAK,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACvD,CAEA,QAAQA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AAoBL,CAAiB,GACvF,KAAK,CAC3B,CAEA,MAAM,aACFG,EACAD,EACAE,EACAQ,EACAZ,EACU,CASV,OAAQ,MARI,MAAM,KAAK,YACnBG,EACAD,EACAE,EACAQ,EACA,sBACAZ,CACJ,GACkB,KAAK,CAC3B,CAEA,MAAM,mBACFG,EACAD,EACAE,EACAQ,EACAZ,EACU,CACV,IAAMa,EAAiB,IAAI,gBAAgBD,CAAQ,EAAE,SAAS,EAS9D,OAAQ,MARI,MAAM,KAAK,YACnBT,EACAD,EACAE,EACAS,EACA,oCACAb,CACJ,GACkB,KAAK,CAC3B,CACJ","names":["request_exports","__export","Requester","__toCommonJS","import_https","Logger","name","debug","data","prefix","LIB_NAME","LOG_LOCAL","LOGGER","Logger","HttpsClient","hostname","path","method","headers","timeout","body","url","controller","timeoutId","response","HttpsClientResponse","error","resp","err","isMetaError","error","LIB_NAME","LOG_LOCAL","LOGGER","Logger","Requester","host","apiVersion","phoneNumberId","accessToken","businessAcctId","userAgent","HttpsClient","contentType","additionalHeaders","headers","endpoint","method","timeout","body","effectiveContentType","path","response","errorData","isMetaError","error","formData","urlEncodedBody"]}
package/dist/request.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{Agent as f}from"https";var a=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 y="HttpsClient",b=!1,w=new a(y,process.env.DEBUG==="true"||b),l=class{agent;constructor(){this.agent=new f({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(e,t,o,n,i,c){let s=`https://${e}/${t}`,p=new AbortController,h=setTimeout(()=>p.abort(),i);try{let d=await fetch(s,{method:o,headers:n,body:c,signal:p.signal});return w.log(`${o} : ${s} - ${JSON.stringify(d)}`),clearTimeout(h),new u(d)}catch(d){throw d}}},u=class{res;respStatusCode;respHeaders;constructor(e){this.res=e,this.respStatusCode=e.status,this.respHeaders=Object.fromEntries(e.headers.entries())}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(e){throw new Error("Failed to parse response body to JSON: "+e.message)}}};function m(r){return r!=null&&typeof r=="object"&&"error"in r&&typeof r.error=="object"&&r.error!=null&&"message"in r.error&&typeof r.error.message=="string"&&"type"in r.error&&typeof r.error.type=="string"&&"code"in r.error&&typeof r.error.code=="number"&&"fbtrace_id"in r.error&&typeof r.error.fbtrace_id=="string"&&(!("error_data"in r.error)||typeof r.error.error_data=="object"&&r.error.error_data!=null&&"messaging_product"in r.error.error_data&&r.error.error_data.messaging_product==="whatsapp"&&"details"in r.error.error_data&&typeof r.error.error_data.details=="string")&&(!("error_subcode"in r.error)||typeof r.error.error_subcode=="number")}var R="REQUESTER",E=!1,C=new a(R,process.env.DEBUG==="true"||E),g=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(e,t,o,n,i,c){this.client=new l,this.host=e||"graph.facebook.com",this.apiVersion=t||"22",this.phoneNumberId=o,this.accessToken=n,this.businessAcctId=i,this.userAgent=c}buildHeader(e){return{"Content-Type":e,Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent}}buildCAPIPath(e){return`v${this.apiVersion}.0/${e}`}async sendRequest(e,t,o,n){let i="application/json",c=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(t)}`;C.log(`${e} : ${c}`);try{let s=await this.client.sendRequest(this.host,this.buildCAPIPath(t),e,this.buildHeader(i),o,e==="POST"||e==="PUT"?n:void 0);if(!s.rawResponse().ok){let p=await s.json();throw m(p)?p:{name:"MetaError",message:"Unknown error occurred",error:{message:p.message||"Unknown error occurred",type:"UnknownError",code:s.statusCode(),fbtrace_id:""}}}return s}catch(s){throw m(s)?s:{name:"MetaError",message:s instanceof Error?s.message:"Network error occurred",error:{message:s instanceof Error?s.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}async getJson(e,t,o,n){return await(await this.sendRequest(e,t,o,n)).json()}};export{g as default};
1
+ import{Agent as f}from"https";var d=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 y="HttpsClient",w=!1,R=new d(y,process.env.DEBUG==="true"||w),l=class{agent;constructor(){this.agent=new f({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(e,t,s,n,a,i){let c=`https://${e}/${t}`,u=new AbortController,o=setTimeout(()=>u.abort(),a);try{let p=await fetch(c,{method:s,headers:n,body:i,signal:u.signal});return R.log(`${s} : ${c} - ${JSON.stringify(p)}`),clearTimeout(o),new m(p)}catch(p){throw p}}},m=class{res;respStatusCode;respHeaders;constructor(e){this.res=e,this.respStatusCode=e.status,this.respHeaders=Object.fromEntries(e.headers.entries())}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(e){throw new Error("Failed to parse response body to JSON: "+e.message)}}};function g(r){return r!=null&&typeof r=="object"&&"error"in r&&typeof r.error=="object"&&r.error!=null&&"message"in r.error&&typeof r.error.message=="string"&&"type"in r.error&&typeof r.error.type=="string"&&"code"in r.error&&typeof r.error.code=="number"&&"fbtrace_id"in r.error&&typeof r.error.fbtrace_id=="string"&&(!("error_data"in r.error)||typeof r.error.error_data=="object"&&r.error.error_data!=null&&"messaging_product"in r.error.error_data&&r.error.error_data.messaging_product==="whatsapp"&&"details"in r.error.error_data&&typeof r.error.error_data.details=="string")&&(!("error_subcode"in r.error)||typeof r.error.error_subcode=="number")}var b="REQUESTER",E=!1,C=new d(b,process.env.DEBUG==="true"||E),h=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(e,t,s,n,a,i){this.client=new l,this.host=e||"graph.facebook.com",this.apiVersion=t||"22",this.phoneNumberId=s,this.accessToken=n,this.businessAcctId=a,this.userAgent=i}buildHeader(e,t){let s={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return e!=="multipart/form-data"&&(s["Content-Type"]=e),t&&Object.assign(s,t),s}buildCAPIPath(e){return`v${this.apiVersion}.0/${e}`}async sendRequest(e,t,s,n,a="application/json",i){let c=a;n instanceof FormData?c="multipart/form-data":typeof n=="string"&&n.startsWith("<?xml")&&(c="application/xml");let u=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(t)}`;C.log(`${e} : ${u} (${c})`);try{let o=await this.client.sendRequest(this.host,this.buildCAPIPath(t),e,this.buildHeader(c,i),s,e==="POST"||e==="PUT"?n:void 0);if(!o.rawResponse().ok){let p=await o.json();throw g(p)?p:{name:"MetaError",message:"Unknown error occurred",error:{message:p.message||"Unknown error occurred",type:"UnknownError",code:o.statusCode(),fbtrace_id:""}}}return o}catch(o){throw g(o)?o:{name:"MetaError",message:o instanceof Error?o.message:"Network error occurred",error:{message:o instanceof Error?o.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}async getJson(e,t,s,n,a){return await(await this.sendRequest(e,t,s,n,"application/json",a)).json()}async sendFormData(e,t,s,n,a){return await(await this.sendRequest(e,t,s,n,"multipart/form-data",a)).json()}async sendUrlEncodedForm(e,t,s,n,a){let i=new URLSearchParams(n).toString();return await(await this.sendRequest(e,t,s,i,"application/x-www-form-urlencoded",a)).json()}};export{h as default};
2
2
  //# sourceMappingURL=request.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/httpsClient.ts","../src/utils/logger.ts","../src/utils/isMetaError.ts","../src/request.ts"],"sourcesContent":["import { Agent } from 'https';\n\nimport Logger from './utils/logger';\nimport { HttpMethodsEnum } from './types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from './types/httpsClient';\n\nconst LIB_NAME = 'HttpsClient';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class HttpsClient implements HttpsClientClass {\n agent: Agent;\n\n constructor() {\n this.agent = new Agent({ keepAlive: true });\n }\n\n clearSockets(): boolean {\n this.agent.destroy();\n return true;\n }\n\n async sendRequest(\n hostname: string,\n path: string,\n method: HttpMethodsEnum,\n headers: HeadersInit,\n timeout: number,\n body?: BodyInit | null,\n ): Promise<HttpsClientResponseClass> {\n const url = `https://${hostname}/${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n LOGGER.log(`${method} : ${url} - ${JSON.stringify(response)}`);\n\n clearTimeout(timeoutId);\n return new HttpsClientResponse(response);\n } catch (error) {\n throw error;\n }\n }\n}\n\nexport class HttpsClientResponse implements HttpsClientResponseClass {\n res: Response;\n respStatusCode: number;\n respHeaders: ResponseHeaders;\n\n constructor(resp: Response) {\n this.res = resp;\n this.respStatusCode = resp.status;\n this.respHeaders = Object.fromEntries(resp.headers.entries());\n }\n\n statusCode(): number {\n return this.respStatusCode;\n }\n\n headers(): ResponseHeaders {\n return this.respHeaders;\n }\n\n rawResponse(): Response {\n return this.res;\n }\n\n async json(): Promise<ResponseJSONBody> {\n try {\n return (await this.res.json()) as ResponseJSONBody;\n } catch (err) {\n // TODO Error Handling\n throw new Error('Failed to parse response body to JSON: ' + (err as Error).message);\n }\n }\n}\n","// @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","export interface MetaError extends Error {\n error: {\n message: string;\n type: string;\n code: number;\n error_data?: {\n messaging_product: 'whatsapp';\n details: string;\n };\n error_subcode?: number;\n fbtrace_id: string;\n };\n}\n\n/**\n * Determines if the error is a Meta API error response\n * @param error Any error object to check\n * @returns Type guard indicating if error is a Meta API error\n */\nexport function isMetaError(error: any): error is MetaError {\n return (\n error != null &&\n typeof error === 'object' &&\n 'error' in error &&\n typeof error.error === 'object' &&\n error.error != null &&\n 'message' in error.error &&\n typeof error.error.message === 'string' &&\n 'type' in error.error &&\n typeof error.error.type === 'string' &&\n 'code' in error.error &&\n typeof error.error.code === 'number' &&\n 'fbtrace_id' in error.error &&\n typeof error.error.fbtrace_id === 'string' &&\n (!('error_data' in error.error) ||\n (typeof error.error.error_data === 'object' &&\n error.error.error_data != null &&\n 'messaging_product' in error.error.error_data &&\n error.error.error_data.messaging_product === 'whatsapp' &&\n 'details' in error.error.error_data &&\n typeof error.error.error_data.details === 'string')) &&\n (!('error_subcode' in error.error) || typeof error.error.error_subcode === 'number')\n );\n}\n","import HttpsClient from './httpsClient';\nimport type { HttpMethodsEnum } from './types/enums';\nimport type { RequesterClass } from './types/request';\nimport { isMetaError, MetaError } from './utils/isMetaError';\nimport Logger from './utils/logger';\n\nconst LIB_NAME = 'REQUESTER';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class Requester implements RequesterClass {\n client: Readonly<HttpsClient>;\n accessToken: Readonly<string>;\n phoneNumberId: Readonly<number>;\n businessAcctId: Readonly<string>;\n apiVersion: Readonly<string>;\n userAgent: Readonly<string>;\n host: Readonly<string>;\n protocol: Readonly<string> = 'https:';\n\n constructor(\n host: string,\n apiVersion: string,\n phoneNumberId: number,\n accessToken: string,\n businessAcctId: string,\n userAgent: string,\n ) {\n this.client = new HttpsClient();\n this.host = host || 'graph.facebook.com';\n this.apiVersion = apiVersion || '22';\n this.phoneNumberId = phoneNumberId;\n this.accessToken = accessToken;\n this.businessAcctId = businessAcctId;\n this.userAgent = userAgent;\n }\n\n buildHeader(contentType: string): HeadersInit {\n const headers: HeadersInit = {\n 'Content-Type': contentType,\n Authorization: `Bearer ${this.accessToken}`,\n 'User-Agent': this.userAgent,\n };\n return headers;\n }\n\n buildCAPIPath(endpoint: string): string {\n return `v${this.apiVersion}.0/${endpoint}`;\n }\n\n async sendRequest(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any) {\n const contentType = 'application/json';\n const path = `${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(endpoint)}`;\n\n LOGGER.log(`${method} : ${path}`);\n\n try {\n const response = await this.client.sendRequest(\n this.host,\n this.buildCAPIPath(endpoint),\n method,\n this.buildHeader(contentType),\n timeout,\n method === 'POST' || method === 'PUT' ? body : undefined,\n );\n\n if (!response.rawResponse().ok) {\n const errorData = await response.json();\n if (isMetaError(errorData)) {\n throw errorData;\n }\n // If the error doesn't match Meta's format, create a generic MetaError\n throw {\n name: 'MetaError',\n message: 'Unknown error occurred',\n error: {\n message: errorData.message || 'Unknown error occurred',\n type: 'UnknownError',\n code: response.statusCode(),\n fbtrace_id: '',\n },\n } as MetaError;\n }\n\n return response;\n } catch (error) {\n if (isMetaError(error)) {\n throw error;\n }\n // Handle network errors or other unexpected errors\n throw {\n name: 'MetaError',\n message: error instanceof Error ? error.message : 'Network error occurred',\n error: {\n message: error instanceof Error ? error.message : 'Network error occurred',\n type: 'NetworkError',\n code: 500,\n fbtrace_id: '',\n },\n } as MetaError;\n }\n }\n\n async getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n const res = await this.sendRequest(method, endpoint, timeout, body);\n return (await res.json()) as T;\n }\n}\n"],"mappings":"AAAA,OAAS,SAAAA,MAAa,QCGtB,IAAqBC,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,CACtD,CACJ,CAEA,SAASA,EAAa,CAClB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,aACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,MAAM,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACxD,CAEA,QAAQA,EAAa,CACjB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,YACxB,KAAK,OACLA,GAAU,MAAM,KAAK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,UAAU,KAAK,WAAW,GACzC,aAAc,KAAK,SACvB,CAEJ,CAEA,cAAcC,EAA0B,CACpC,MAAO,IAAI,KAAK,UAAU,MAAMA,CAAQ,EAC5C,CAEA,MAAM,YAAYC,EAAyBD,EAAkBE,EAAiBC,EAAY,CACtF,IAAMJ,EAAc,mBACdK,EAAO,GAAG,KAAK,SAAS,YAAY,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,cAAcJ,CAAQ,CAAC,GAEzFX,EAAO,IAAI,GAAGY,CAAM,MAAMG,CAAI,EAAE,EAEhC,GAAI,CACA,IAAMC,EAAW,MAAM,KAAK,OAAO,YAC/B,KAAK,KACL,KAAK,cAAcL,CAAQ,EAC3BC,EACA,KAAK,YAAYF,CAAW,EAC5BG,EACAD,IAAW,QAAUA,IAAW,MAAQE,EAAO,MACnD,EAEA,GAAI,CAACE,EAAS,YAAY,EAAE,GAAI,CAC5B,IAAMC,EAAY,MAAMD,EAAS,KAAK,EACtC,MAAIE,EAAYD,CAAS,EACfA,EAGJ,CACF,KAAM,YACN,QAAS,yBACT,MAAO,CACH,QAASA,EAAU,SAAW,yBAC9B,KAAM,eACN,KAAMD,EAAS,WAAW,EAC1B,WAAY,EAChB,CACJ,CACJ,CAEA,OAAOA,CACX,OAASG,EAAO,CACZ,MAAID,EAAYC,CAAK,EACXA,EAGJ,CACF,KAAM,YACN,QAASA,aAAiB,MAAQA,EAAM,QAAU,yBAClD,MAAO,CACH,QAASA,aAAiB,MAAQA,EAAM,QAAU,yBAClD,KAAM,eACN,KAAM,IACN,WAAY,EAChB,CACJ,CACJ,CACJ,CAEA,MAAM,QAAWP,EAAyBD,EAAkBE,EAAiBC,EAAwB,CAEjG,OAAQ,MADI,MAAM,KAAK,YAAYF,EAAQD,EAAUE,EAASC,CAAI,GAChD,KAAK,CAC3B,CACJ","names":["Agent","Logger","name","debug","data","prefix","LIB_NAME","LOG_LOCAL","LOGGER","Logger","HttpsClient","Agent","hostname","path","method","headers","timeout","body","url","controller","timeoutId","response","HttpsClientResponse","error","resp","err","isMetaError","error","LIB_NAME","LOG_LOCAL","LOGGER","Logger","Requester","host","apiVersion","phoneNumberId","accessToken","businessAcctId","userAgent","HttpsClient","contentType","endpoint","method","timeout","body","path","response","errorData","isMetaError","error"]}
1
+ {"version":3,"sources":["../src/httpsClient.ts","../src/utils/logger.ts","../src/utils/isMetaError.ts","../src/request.ts"],"sourcesContent":["import { Agent } from 'https';\n\nimport Logger from './utils/logger';\nimport { HttpMethodsEnum } from './types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from './types/httpsClient';\n\nconst LIB_NAME = 'HttpsClient';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class HttpsClient implements HttpsClientClass {\n agent: Agent;\n\n constructor() {\n this.agent = new Agent({ keepAlive: true });\n }\n\n clearSockets(): boolean {\n this.agent.destroy();\n return true;\n }\n\n async sendRequest(\n hostname: string,\n path: string,\n method: HttpMethodsEnum,\n headers: HeadersInit,\n timeout: number,\n body?: BodyInit | null,\n ): Promise<HttpsClientResponseClass> {\n const url = `https://${hostname}/${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n LOGGER.log(`${method} : ${url} - ${JSON.stringify(response)}`);\n\n clearTimeout(timeoutId);\n return new HttpsClientResponse(response);\n } catch (error) {\n throw error;\n }\n }\n}\n\nexport class HttpsClientResponse implements HttpsClientResponseClass {\n res: Response;\n respStatusCode: number;\n respHeaders: ResponseHeaders;\n\n constructor(resp: Response) {\n this.res = resp;\n this.respStatusCode = resp.status;\n this.respHeaders = Object.fromEntries(resp.headers.entries());\n }\n\n statusCode(): number {\n return this.respStatusCode;\n }\n\n headers(): ResponseHeaders {\n return this.respHeaders;\n }\n\n rawResponse(): Response {\n return this.res;\n }\n\n async json(): Promise<ResponseJSONBody> {\n try {\n return (await this.res.json()) as ResponseJSONBody;\n } catch (err) {\n // TODO Error Handling\n throw new Error('Failed to parse response body to JSON: ' + (err as Error).message);\n }\n }\n}\n","// @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","export interface MetaError extends Error {\n error: {\n message: string;\n type: string;\n code: number;\n error_data?: {\n messaging_product: 'whatsapp';\n details: string;\n };\n error_subcode?: number;\n fbtrace_id: string;\n };\n}\n\n/**\n * Determines if the error is a Meta API error response\n * @param error Any error object to check\n * @returns Type guard indicating if error is a Meta API error\n */\nexport function isMetaError(error: any): error is MetaError {\n return (\n error != null &&\n typeof error === 'object' &&\n 'error' in error &&\n typeof error.error === 'object' &&\n error.error != null &&\n 'message' in error.error &&\n typeof error.error.message === 'string' &&\n 'type' in error.error &&\n typeof error.error.type === 'string' &&\n 'code' in error.error &&\n typeof error.error.code === 'number' &&\n 'fbtrace_id' in error.error &&\n typeof error.error.fbtrace_id === 'string' &&\n (!('error_data' in error.error) ||\n (typeof error.error.error_data === 'object' &&\n error.error.error_data != null &&\n 'messaging_product' in error.error.error_data &&\n error.error.error_data.messaging_product === 'whatsapp' &&\n 'details' in error.error.error_data &&\n typeof error.error.error_data.details === 'string')) &&\n (!('error_subcode' in error.error) || typeof error.error.error_subcode === 'number')\n );\n}\n","import HttpsClient from './httpsClient';\nimport type { HttpMethodsEnum } from './types/enums';\nimport type { RequesterClass } from './types/request';\nimport { isMetaError, MetaError } from './utils/isMetaError';\nimport Logger from './utils/logger';\n\nconst LIB_NAME = 'REQUESTER';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class Requester implements RequesterClass {\n client: Readonly<HttpsClient>;\n accessToken: Readonly<string>;\n phoneNumberId: Readonly<number>;\n businessAcctId: Readonly<string>;\n apiVersion: Readonly<string>;\n userAgent: Readonly<string>;\n host: Readonly<string>;\n protocol: Readonly<string> = 'https:';\n\n constructor(\n host: string,\n apiVersion: string,\n phoneNumberId: number,\n accessToken: string,\n businessAcctId: string,\n userAgent: string,\n ) {\n this.client = new HttpsClient();\n this.host = host || 'graph.facebook.com';\n this.apiVersion = apiVersion || '22';\n this.phoneNumberId = phoneNumberId;\n this.accessToken = accessToken;\n this.businessAcctId = businessAcctId;\n this.userAgent = userAgent;\n }\n\n buildHeader(contentType: string, additionalHeaders?: Record<string, string>): HeadersInit {\n const headers: HeadersInit = {\n Authorization: `Bearer ${this.accessToken}`,\n 'User-Agent': this.userAgent,\n };\n\n if (contentType !== 'multipart/form-data') {\n headers['Content-Type'] = contentType;\n }\n\n if (additionalHeaders) {\n Object.assign(headers, additionalHeaders);\n }\n\n return headers;\n }\n\n buildCAPIPath(endpoint: string): string {\n return `v${this.apiVersion}.0/${endpoint}`;\n }\n\n async sendRequest(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n contentType: string = 'application/json',\n additionalHeaders?: Record<string, string>,\n ) {\n let effectiveContentType = contentType;\n\n if (body instanceof FormData) {\n effectiveContentType = 'multipart/form-data';\n } else if (typeof body === 'string' && body.startsWith('<?xml')) {\n effectiveContentType = 'application/xml';\n }\n\n const path = `${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(endpoint)}`;\n\n LOGGER.log(`${method} : ${path} (${effectiveContentType})`);\n\n try {\n const response = await this.client.sendRequest(\n this.host,\n this.buildCAPIPath(endpoint),\n method,\n this.buildHeader(effectiveContentType, additionalHeaders),\n timeout,\n method === 'POST' || method === 'PUT' ? body : undefined,\n );\n\n if (!response.rawResponse().ok) {\n const errorData = await response.json();\n if (isMetaError(errorData)) {\n throw errorData;\n }\n // If the error doesn't match Meta's format, create a generic MetaError\n throw {\n name: 'MetaError',\n message: 'Unknown error occurred',\n error: {\n message: errorData.message || 'Unknown error occurred',\n type: 'UnknownError',\n code: response.statusCode(),\n fbtrace_id: '',\n },\n } as MetaError;\n }\n\n return response;\n } catch (error) {\n if (isMetaError(error)) {\n throw error;\n }\n // Handle network errors or other unexpected errors\n throw {\n name: 'MetaError',\n message: error instanceof Error ? error.message : 'Network error occurred',\n error: {\n message: error instanceof Error ? error.message : 'Network error occurred',\n type: 'NetworkError',\n code: 500,\n fbtrace_id: '',\n },\n } as MetaError;\n }\n }\n\n async getJson<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(method, endpoint, timeout, body, 'application/json', additionalHeaders);\n return (await res.json()) as T;\n }\n\n async sendFormData<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: FormData,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n formData,\n 'multipart/form-data',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n\n async sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: Record<string, string>,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const urlEncodedBody = new URLSearchParams(formData).toString();\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n urlEncodedBody,\n 'application/x-www-form-urlencoded',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n}\n"],"mappings":"AAAA,OAAS,SAAAA,MAAa,QCGtB,IAAqBC,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,CACtD,CACJ,CAEA,SAASA,EAAa,CAClB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,aACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,MAAM,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACxD,CAEA,QAAQA,EAAa,CACjB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,YACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,KAAK,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACvD,CAEA,QAAQA,EAAa,CACjB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,YACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,KAAK,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACvD,CACJ,EDvCA,IAAME,EAAW,cACXC,EAAY,GACZC,EAAS,IAAIC,EAAOH,EAAU,QAAQ,IAAI,QAAU,QAAUC,CAAS,EAExDG,EAArB,KAA6D,CACzD,MAEA,aAAc,CACV,KAAK,MAAQ,IAAIC,EAAM,C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,oCACAb,CACJ,GACkB,KAAK,CAC3B,CACJ","names":["Agent","Logger","name","debug","data","prefix","LIB_NAME","LOG_LOCAL","LOGGER","Logger","HttpsClient","Agent","hostname","path","method","headers","timeout","body","url","controller","timeoutId","response","HttpsClientResponse","error","resp","err","isMetaError","error","LIB_NAME","LOG_LOCAL","LOGGER","Logger","Requester","host","apiVersion","phoneNumberId","accessToken","businessAcctId","userAgent","HttpsClient","contentType","additionalHeaders","headers","endpoint","method","timeout","body","effectiveContentType","path","response","errorData","isMetaError","error","formData","urlEncodedBody"]}
@@ -1,6 +1,11 @@
1
1
  import { k as BusinessVerticalEnum } from '../enums-D7paGoTY.mjs';
2
2
  import { ResponseSuccess } from './request.mjs';
3
3
 
4
+ /**
5
+ * Available fields that can be requested when retrieving a business profile.
6
+ */
7
+ type BusinessProfileField = 'about' | 'address' | 'description' | 'email' | 'profile_picture_url' | 'websites' | 'vertical';
8
+ type BusinessProfileFieldsParam = BusinessProfileField[];
4
9
  interface BusinessProfileData {
5
10
  /**
6
11
  * The business's About text. This text appears in the business's profile, beneath its profile image,
@@ -117,10 +122,9 @@ interface UploadHandle {
117
122
  interface BusinessProfileClass {
118
123
  /**
119
124
  * Get your business profile.
120
- * @param fields Fields to be returned in the response. If not specified, all fields will be returned.
121
- * Possible values: about, address, description, email, profile_picture_url, websites, vertical
125
+ * @param fields Specific fields to be returned in the response. If not specified, all fields will be returned.
122
126
  */
123
- getBusinessProfile(fields?: string): Promise<BusinessProfileResponse>;
127
+ getBusinessProfile(fields?: BusinessProfileFieldsParam | string): Promise<BusinessProfileResponse>;
124
128
  /**
125
129
  * Update your business profile.
126
130
  * @param updateRequest The request object containing the fields to update.
@@ -146,4 +150,4 @@ interface BusinessProfileClass {
146
150
  getUploadHandle(uploadId: string): Promise<UploadHandle>;
147
151
  }
148
152
 
149
- export type { BusinessProfileClass, BusinessProfileData, BusinessProfileResponse, UpdateBusinessProfileRequest, UploadBusinessProfileResponse, UploadHandle, UploadSession, UploadSessionResponse };
153
+ export type { BusinessProfileClass, BusinessProfileData, BusinessProfileField, BusinessProfileFieldsParam, BusinessProfileResponse, UpdateBusinessProfileRequest, UploadBusinessProfileResponse, UploadHandle, UploadSession, UploadSessionResponse };
@@ -1,6 +1,11 @@
1
1
  import { k as BusinessVerticalEnum } from '../enums-D7paGoTY.js';
2
2
  import { ResponseSuccess } from './request.js';
3
3
 
4
+ /**
5
+ * Available fields that can be requested when retrieving a business profile.
6
+ */
7
+ type BusinessProfileField = 'about' | 'address' | 'description' | 'email' | 'profile_picture_url' | 'websites' | 'vertical';
8
+ type BusinessProfileFieldsParam = BusinessProfileField[];
4
9
  interface BusinessProfileData {
5
10
  /**
6
11
  * The business's About text. This text appears in the business's profile, beneath its profile image,
@@ -117,10 +122,9 @@ interface UploadHandle {
117
122
  interface BusinessProfileClass {
118
123
  /**
119
124
  * Get your business profile.
120
- * @param fields Fields to be returned in the response. If not specified, all fields will be returned.
121
- * Possible values: about, address, description, email, profile_picture_url, websites, vertical
125
+ * @param fields Specific fields to be returned in the response. If not specified, all fields will be returned.
122
126
  */
123
- getBusinessProfile(fields?: string): Promise<BusinessProfileResponse>;
127
+ getBusinessProfile(fields?: BusinessProfileFieldsParam | string): Promise<BusinessProfileResponse>;
124
128
  /**
125
129
  * Update your business profile.
126
130
  * @param updateRequest The request object containing the fields to update.
@@ -146,4 +150,4 @@ interface BusinessProfileClass {
146
150
  getUploadHandle(uploadId: string): Promise<UploadHandle>;
147
151
  }
148
152
 
149
- export type { BusinessProfileClass, BusinessProfileData, BusinessProfileResponse, UpdateBusinessProfileRequest, UploadBusinessProfileResponse, UploadHandle, UploadSession, UploadSessionResponse };
153
+ export type { BusinessProfileClass, BusinessProfileData, BusinessProfileField, BusinessProfileFieldsParam, BusinessProfileResponse, UpdateBusinessProfileRequest, UploadBusinessProfileResponse, UploadHandle, UploadSession, UploadSessionResponse };
@@ -1,2 +1,2 @@
1
- "use strict";var n=Object.defineProperty;var o=Object.getOwnPropertyDescriptor;var a=Object.getOwnPropertyNames;var l=Object.prototype.hasOwnProperty;var p=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of a(e))!l.call(s,i)&&i!==t&&n(s,i,{get:()=>e[i],enumerable:!(r=o(e,i))||r.enumerable});return s};var d=s=>p(n({},"__esModule",{value:!0}),s);var u={};module.exports=d(u);
1
+ "use strict";var t=Object.defineProperty;var o=Object.getOwnPropertyDescriptor;var a=Object.getOwnPropertyNames;var l=Object.prototype.hasOwnProperty;var p=(s,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of a(e))!l.call(s,i)&&i!==n&&t(s,i,{get:()=>e[i],enumerable:!(r=o(e,i))||r.enumerable});return s};var d=s=>p(t({},"__esModule",{value:!0}),s);var u={};module.exports=d(u);
2
2
  //# sourceMappingURL=businessProfile.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/types/businessProfile.ts"],"sourcesContent":["import { BusinessVerticalEnum } from './enums';\nimport { ResponseSuccess } from './request';\n\nexport interface BusinessProfileData {\n /**\n * The business's About text. This text appears in the business's profile, beneath its profile image,\n * phone number, and contact buttons.\n * - String cannot be empty\n * - Strings must be between 1 and 139 characters\n * - Rendered emojis are supported however their unicode values are not.\n * Emoji unicode values must be Java- or JavaScript-escape encoded\n * - Hyperlinks can be included but will not render as clickable links\n * - Markdown is not supported\n */\n about?: string;\n /**\n * Address of the business. Character limit 256.\n */\n address?: string;\n /**\n * Description of the business. Character limit 512.\n */\n description?: string;\n /**\n * The contact email address (in valid email format) of the business. Character limit 128.\n */\n email?: string;\n /**\n * The messaging service used for the request. Always set it to \"whatsapp\" if you are using\n * the WhatsApp Business API.\n */\n messaging_product: string;\n /**\n * Profile picture URL.\n */\n profile_picture_url?: string;\n /**\n * The URLs associated with the business. For instance, a website, Facebook Page, or Instagram.\n * - You must include the http:// or https:// portion of the URL\n * - There is a maximum of 2 websites with a maximum of 256 characters each\n */\n websites?: string[];\n /**\n * Business category. This can be either an empty string or one of the predefined business categories.\n * @see BusinessVerticalEnum for all available options\n */\n vertical?: BusinessVerticalEnum | string;\n}\n\nexport interface BusinessProfileResponse {\n data: BusinessProfileData[];\n}\n\nexport interface UpdateBusinessProfileRequest {\n /**\n * The messaging service used for the request. Always set it to \"whatsapp\" if you are using\n * the WhatsApp Business API.\n * @required\n */\n messaging_product: string;\n /**\n * The business's About text. This text appears in the business's profile, beneath its profile image,\n * phone number, and contact buttons.\n * - String cannot be empty\n * - Strings must be between 1 and 139 characters\n * - Rendered emojis are supported however their unicode values are not.\n * Emoji unicode values must be Java- or JavaScript-escape encoded\n * - Hyperlinks can be included but will not render as clickable links\n * - Markdown is not supported\n */\n about?: string;\n /**\n * Address of the business. Character limit 256.\n */\n address?: string;\n /**\n * Description of the business. Character limit 512.\n */\n description?: string;\n /**\n * Business category. This can be either an empty string or one of the predefined business categories.\n * @see BusinessVerticalEnum for all available options\n */\n vertical?: BusinessVerticalEnum | string;\n /**\n * The contact email address (in valid email format) of the business. Character limit 128.\n */\n email?: string;\n /**\n * The URLs associated with the business. For instance, a website, Facebook Page, or Instagram.\n * - You must include the http:// or https:// portion of the URL\n * - There is a maximum of 2 websites with a maximum of 256 characters each\n */\n websites?: string[];\n /**\n * Handle of the profile picture. This handle is generated when you upload the binary file\n * for the profile picture to Meta using the Resumable Upload API.\n */\n profile_picture_handle?: string;\n}\n\nexport interface UploadSession {\n id: string;\n video?: boolean;\n}\n\nexport interface UploadSessionResponse {\n id: string;\n}\n\nexport interface UploadBusinessProfileResponse {\n h: string;\n}\n\nexport interface UploadHandle {\n handle: string;\n file_size: number;\n upload_result: {\n handle_type: string;\n name: string;\n };\n}\n\nexport interface BusinessProfileClass {\n /**\n * Get your business profile.\n * @param fields Fields to be returned in the response. If not specified, all fields will be returned.\n * Possible values: about, address, description, email, profile_picture_url, websites, vertical\n */\n getBusinessProfile(fields?: string): Promise<BusinessProfileResponse>;\n\n /**\n * Update your business profile.\n * @param updateRequest The request object containing the fields to update.\n */\n updateBusinessProfile(updateRequest: UpdateBusinessProfileRequest): Promise<ResponseSuccess>;\n\n /**\n * Create an upload session for profile picture.\n * @param fileLength Length of the file to be uploaded in bytes.\n * @param fileType MIME type of the file (e.g., 'image/jpeg').\n * @param fileName Name of the file.\n */\n createUploadSession(fileLength: number, fileType: string, fileName: string): Promise<UploadSessionResponse>;\n\n /**\n * Upload media file to the upload session.\n * @param uploadId The ID of the upload session.\n * @param file The binary data of the file.\n */\n uploadMedia(uploadId: string, file: Buffer): Promise<UploadBusinessProfileResponse>;\n\n /**\n * Get the upload handle information.\n * @param uploadId The ID of the upload session.\n */\n getUploadHandle(uploadId: string): Promise<UploadHandle>;\n}\n"],"mappings":"+WAAA,IAAAA,EAAA,kBAAAC,EAAAD","names":["businessProfile_exports","__toCommonJS"]}
1
+ {"version":3,"sources":["../../src/types/businessProfile.ts"],"sourcesContent":["import { BusinessVerticalEnum } from './enums';\nimport { ResponseSuccess } from './request';\n\n/**\n * Available fields that can be requested when retrieving a business profile.\n */\nexport type BusinessProfileField =\n | 'about'\n | 'address'\n | 'description'\n | 'email'\n | 'profile_picture_url'\n | 'websites'\n | 'vertical';\n\nexport type BusinessProfileFieldsParam = BusinessProfileField[];\n\nexport interface BusinessProfileData {\n /**\n * The business's About text. This text appears in the business's profile, beneath its profile image,\n * phone number, and contact buttons.\n * - String cannot be empty\n * - Strings must be between 1 and 139 characters\n * - Rendered emojis are supported however their unicode values are not.\n * Emoji unicode values must be Java- or JavaScript-escape encoded\n * - Hyperlinks can be included but will not render as clickable links\n * - Markdown is not supported\n */\n about?: string;\n /**\n * Address of the business. Character limit 256.\n */\n address?: string;\n /**\n * Description of the business. Character limit 512.\n */\n description?: string;\n /**\n * The contact email address (in valid email format) of the business. Character limit 128.\n */\n email?: string;\n /**\n * The messaging service used for the request. Always set it to \"whatsapp\" if you are using\n * the WhatsApp Business API.\n */\n messaging_product: string;\n /**\n * Profile picture URL.\n */\n profile_picture_url?: string;\n /**\n * The URLs associated with the business. For instance, a website, Facebook Page, or Instagram.\n * - You must include the http:// or https:// portion of the URL\n * - There is a maximum of 2 websites with a maximum of 256 characters each\n */\n websites?: string[];\n /**\n * Business category. This can be either an empty string or one of the predefined business categories.\n * @see BusinessVerticalEnum for all available options\n */\n vertical?: BusinessVerticalEnum | string;\n}\n\nexport interface BusinessProfileResponse {\n data: BusinessProfileData[];\n}\n\nexport interface UpdateBusinessProfileRequest {\n /**\n * The messaging service used for the request. Always set it to \"whatsapp\" if you are using\n * the WhatsApp Business API.\n * @required\n */\n messaging_product: string;\n /**\n * The business's About text. This text appears in the business's profile, beneath its profile image,\n * phone number, and contact buttons.\n * - String cannot be empty\n * - Strings must be between 1 and 139 characters\n * - Rendered emojis are supported however their unicode values are not.\n * Emoji unicode values must be Java- or JavaScript-escape encoded\n * - Hyperlinks can be included but will not render as clickable links\n * - Markdown is not supported\n */\n about?: string;\n /**\n * Address of the business. Character limit 256.\n */\n address?: string;\n /**\n * Description of the business. Character limit 512.\n */\n description?: string;\n /**\n * Business category. This can be either an empty string or one of the predefined business categories.\n * @see BusinessVerticalEnum for all available options\n */\n vertical?: BusinessVerticalEnum | string;\n /**\n * The contact email address (in valid email format) of the business. Character limit 128.\n */\n email?: string;\n /**\n * The URLs associated with the business. For instance, a website, Facebook Page, or Instagram.\n * - You must include the http:// or https:// portion of the URL\n * - There is a maximum of 2 websites with a maximum of 256 characters each\n */\n websites?: string[];\n /**\n * Handle of the profile picture. This handle is generated when you upload the binary file\n * for the profile picture to Meta using the Resumable Upload API.\n */\n profile_picture_handle?: string;\n}\n\nexport interface UploadSession {\n id: string;\n video?: boolean;\n}\n\nexport interface UploadSessionResponse {\n id: string;\n}\n\nexport interface UploadBusinessProfileResponse {\n h: string;\n}\n\nexport interface UploadHandle {\n handle: string;\n file_size: number;\n upload_result: {\n handle_type: string;\n name: string;\n };\n}\n\nexport interface BusinessProfileClass {\n /**\n * Get your business profile.\n * @param fields Specific fields to be returned in the response. If not specified, all fields will be returned.\n */\n getBusinessProfile(fields?: BusinessProfileFieldsParam | string): Promise<BusinessProfileResponse>;\n\n /**\n * Update your business profile.\n * @param updateRequest The request object containing the fields to update.\n */\n updateBusinessProfile(updateRequest: UpdateBusinessProfileRequest): Promise<ResponseSuccess>;\n\n /**\n * Create an upload session for profile picture.\n * @param fileLength Length of the file to be uploaded in bytes.\n * @param fileType MIME type of the file (e.g., 'image/jpeg').\n * @param fileName Name of the file.\n */\n createUploadSession(fileLength: number, fileType: string, fileName: string): Promise<UploadSessionResponse>;\n\n /**\n * Upload media file to the upload session.\n * @param uploadId The ID of the upload session.\n * @param file The binary data of the file.\n */\n uploadMedia(uploadId: string, file: Buffer): Promise<UploadBusinessProfileResponse>;\n\n /**\n * Get the upload handle information.\n * @param uploadId The ID of the upload session.\n */\n getUploadHandle(uploadId: string): Promise<UploadHandle>;\n}\n"],"mappings":"+WAAA,IAAAA,EAAA,kBAAAC,EAAAD","names":["businessProfile_exports","__toCommonJS"]}
@@ -15,4 +15,4 @@ export { EncryptionClass, EncryptionPublicKeyResponse } from './encryption.mjs';
15
15
  export { UpdateWabaSubscription, WABAClass, WabaAccount, WabaAccountFields, WabaAccountFieldsParam, WabaAccountReviewStatus, WabaAccountStatus, WabaBusinessVerificationStatus, WabaHealthStatus, WabaHealthStatusCanSendMessage, WabaHealthStatusEntity, WabaHealthStatusError, WabaSubscription, WabaSubscriptions } from './waba.mjs';
16
16
  export { MediaClass, MediaResponse, MediasResponse, UploadMediaResponse } from './media.mjs';
17
17
  export { CreateFlowResponse, Flow, FlowAsset, FlowAssetsResponse, FlowCategoryEnum, FlowClass, FlowMigrationFailure, FlowMigrationResponse, FlowMigrationResult, FlowPreview, FlowPreviewResponse, FlowStatusEnum, FlowValidationError, FlowValidationErrorPointer, FlowsListResponse, Pagination, PaginationCursors, UpdateFlowResponse, ValidateFlowJsonResponse } from './flow.mjs';
18
- export { BusinessProfileClass, BusinessProfileData, BusinessProfileResponse, UpdateBusinessProfileRequest, UploadBusinessProfileResponse, UploadHandle, UploadSession, UploadSessionResponse } from './businessProfile.mjs';
18
+ export { BusinessProfileClass, BusinessProfileData, BusinessProfileField, BusinessProfileFieldsParam, BusinessProfileResponse, UpdateBusinessProfileRequest, UploadBusinessProfileResponse, UploadHandle, UploadSession, UploadSessionResponse } from './businessProfile.mjs';
@@ -15,4 +15,4 @@ export { EncryptionClass, EncryptionPublicKeyResponse } from './encryption.js';
15
15
  export { UpdateWabaSubscription, WABAClass, WabaAccount, WabaAccountFields, WabaAccountFieldsParam, WabaAccountReviewStatus, WabaAccountStatus, WabaBusinessVerificationStatus, WabaHealthStatus, WabaHealthStatusCanSendMessage, WabaHealthStatusEntity, WabaHealthStatusError, WabaSubscription, WabaSubscriptions } from './waba.js';
16
16
  export { MediaClass, MediaResponse, MediasResponse, UploadMediaResponse } from './media.js';
17
17
  export { CreateFlowResponse, Flow, FlowAsset, FlowAssetsResponse, FlowCategoryEnum, FlowClass, FlowMigrationFailure, FlowMigrationResponse, FlowMigrationResult, FlowPreview, FlowPreviewResponse, FlowStatusEnum, FlowValidationError, FlowValidationErrorPointer, FlowsListResponse, Pagination, PaginationCursors, UpdateFlowResponse, ValidateFlowJsonResponse } from './flow.js';
18
- export { BusinessProfileClass, BusinessProfileData, BusinessProfileResponse, UpdateBusinessProfileRequest, UploadBusinessProfileResponse, UploadHandle, UploadSession, UploadSessionResponse } from './businessProfile.js';
18
+ export { BusinessProfileClass, BusinessProfileData, BusinessProfileField, BusinessProfileFieldsParam, BusinessProfileResponse, UpdateBusinessProfileRequest, UploadBusinessProfileResponse, UploadHandle, UploadSession, UploadSessionResponse } from './businessProfile.js';
@@ -1,6 +1,6 @@
1
1
  import { H as HttpMethodsEnum } from '../enums-D7paGoTY.mjs';
2
2
 
3
- type GeneralRequestBody = Record<string, any>;
3
+ type GeneralRequestBody = Record<string, unknown>;
4
4
  interface GeneralHeaderInterface {
5
5
  /**
6
6
  * Authorization token. This is required for all HTTP requests made to the graph API.
@@ -41,8 +41,10 @@ interface Paging {
41
41
  }
42
42
  declare class RequesterClass {
43
43
  constructor(host: string, apiVersion: string, phoneNumberId: number, accessToken: string, businessAcctId: string, userAgent: string);
44
- sendRequest: (method: HttpMethodsEnum, path: string, timeout: number, body?: any) => Promise<RequesterResponseInterface<any>>;
45
- getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T>;
44
+ sendRequest: (method: HttpMethodsEnum, path: string, timeout: number, body?: GeneralRequestBody, contentType?: string, additionalHeaders?: Record<string, string>) => Promise<RequesterResponseInterface<unknown>>;
45
+ getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: GeneralRequestBody, additionalHeaders?: Record<string, string>): Promise<T>;
46
+ sendFormData<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: FormData, additionalHeaders?: Record<string, string>): Promise<T>;
47
+ sendUrlEncodedForm<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: Record<string, string>, additionalHeaders?: Record<string, string>): Promise<T>;
46
48
  }
47
49
 
48
50
  export { type GeneralHeaderInterface, type GeneralRequestBody, type Paging, RequesterClass, type RequesterResponseInterface, type ResponseData, type ResponsePagination, type ResponseSuccess };
@@ -1,6 +1,6 @@
1
1
  import { H as HttpMethodsEnum } from '../enums-D7paGoTY.js';
2
2
 
3
- type GeneralRequestBody = Record<string, any>;
3
+ type GeneralRequestBody = Record<string, unknown>;
4
4
  interface GeneralHeaderInterface {
5
5
  /**
6
6
  * Authorization token. This is required for all HTTP requests made to the graph API.
@@ -41,8 +41,10 @@ interface Paging {
41
41
  }
42
42
  declare class RequesterClass {
43
43
  constructor(host: string, apiVersion: string, phoneNumberId: number, accessToken: string, businessAcctId: string, userAgent: string);
44
- sendRequest: (method: HttpMethodsEnum, path: string, timeout: number, body?: any) => Promise<RequesterResponseInterface<any>>;
45
- getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T>;
44
+ sendRequest: (method: HttpMethodsEnum, path: string, timeout: number, body?: GeneralRequestBody, contentType?: string, additionalHeaders?: Record<string, string>) => Promise<RequesterResponseInterface<unknown>>;
45
+ getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: GeneralRequestBody, additionalHeaders?: Record<string, string>): Promise<T>;
46
+ sendFormData<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: FormData, additionalHeaders?: Record<string, string>): Promise<T>;
47
+ sendUrlEncodedForm<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: Record<string, string>, additionalHeaders?: Record<string, string>): Promise<T>;
46
48
  }
47
49
 
48
50
  export { type GeneralHeaderInterface, type GeneralRequestBody, type Paging, RequesterClass, type RequesterResponseInterface, type ResponseData, type ResponsePagination, type ResponseSuccess };
@@ -1,2 +1,2 @@
1
- "use strict";var r=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var a=Object.getOwnPropertyNames;var g=Object.prototype.hasOwnProperty;var p=(t,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of a(e))!g.call(t,n)&&n!==o&&r(t,n,{get:()=>e[n],enumerable:!(s=i(e,n))||s.enumerable});return t};var c=t=>p(r({},"__esModule",{value:!0}),t);var u={};module.exports=c(u);
1
+ "use strict";var s=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var a=Object.getOwnPropertyNames;var d=Object.prototype.hasOwnProperty;var g=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of a(e))!d.call(t,n)&&n!==o&&s(t,n,{get:()=>e[n],enumerable:!(r=i(e,n))||r.enumerable});return t};var m=t=>g(s({},"__esModule",{value:!0}),t);var u={};module.exports=m(u);
2
2
  //# sourceMappingURL=request.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/types/request.ts"],"sourcesContent":["import { HttpMethodsEnum } from './enums';\n\nexport type GeneralRequestBody = Record<string, any>;\n\nexport interface GeneralHeaderInterface {\n /**\n * Authorization token. This is required for all HTTP requests made to the graph API.\n * @default 'Bearer '\n */\n Authorization: string;\n\n /**\n * Content type of the message being sent. This is required for all HTTP requests made to the graph API.\n * @default 'application/json'\n */\n 'Content-Type': string;\n\n /**\n * User agent field sent in all requests. This is used to gather SDK usage metrics and help\n * better triage support requests.\n * @default `WA_SDK/${ SDK_version } (Node.js ${ process.version })`\n */\n 'User-Agent': string;\n}\n\nexport interface RequesterResponseInterface<T> {\n json: () => Promise<T>;\n}\n\nexport interface ResponseSuccess {\n success: boolean;\n}\n\nexport interface ResponseData<T> {\n data: T;\n}\n\nexport interface ResponsePagination<T> {\n data: T[];\n paging: Paging;\n}\n\nexport interface Paging {\n cursors: {\n before: string;\n after: string;\n };\n next: string;\n}\n\nexport declare class RequesterClass {\n constructor(\n host: string,\n apiVersion: string,\n phoneNumberId: number,\n accessToken: string,\n businessAcctId: string,\n userAgent: string,\n );\n sendRequest: (\n method: HttpMethodsEnum,\n path: string,\n timeout: number,\n body?: any,\n ) => Promise<RequesterResponseInterface<any>>;\n\n getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T>;\n}\n"],"mappings":"+WAAA,IAAAA,EAAA,kBAAAC,EAAAD","names":["request_exports","__toCommonJS"]}
1
+ {"version":3,"sources":["../../src/types/request.ts"],"sourcesContent":["import { HttpMethodsEnum } from './enums';\n\nexport type GeneralRequestBody = Record<string, unknown>;\n\nexport interface GeneralHeaderInterface {\n /**\n * Authorization token. This is required for all HTTP requests made to the graph API.\n * @default 'Bearer '\n */\n Authorization: string;\n\n /**\n * Content type of the message being sent. This is required for all HTTP requests made to the graph API.\n * @default 'application/json'\n */\n 'Content-Type': string;\n\n /**\n * User agent field sent in all requests. This is used to gather SDK usage metrics and help\n * better triage support requests.\n * @default `WA_SDK/${ SDK_version } (Node.js ${ process.version })`\n */\n 'User-Agent': string;\n}\n\nexport interface RequesterResponseInterface<T> {\n json: () => Promise<T>;\n}\n\nexport interface ResponseSuccess {\n success: boolean;\n}\n\nexport interface ResponseData<T> {\n data: T;\n}\n\nexport interface ResponsePagination<T> {\n data: T[];\n paging: Paging;\n}\n\nexport interface Paging {\n cursors: {\n before: string;\n after: string;\n };\n next: string;\n}\n\nexport declare class RequesterClass {\n constructor(\n host: string,\n apiVersion: string,\n phoneNumberId: number,\n accessToken: string,\n businessAcctId: string,\n userAgent: string,\n );\n\n sendRequest: (\n method: HttpMethodsEnum,\n path: string,\n timeout: number,\n body?: GeneralRequestBody,\n contentType?: string,\n additionalHeaders?: Record<string, string>,\n ) => Promise<RequesterResponseInterface<unknown>>;\n\n getJson<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: GeneralRequestBody,\n additionalHeaders?: Record<string, string>,\n ): Promise<T>;\n\n sendFormData<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: FormData,\n additionalHeaders?: Record<string, string>,\n ): Promise<T>;\n\n sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: Record<string, string>,\n additionalHeaders?: Record<string, string>,\n ): Promise<T>;\n}\n"],"mappings":"+WAAA,IAAAA,EAAA,kBAAAC,EAAAD","names":["request_exports","__toCommonJS"]}