meta-cloud-api 0.1.8 → 0.1.10
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/base.d.mts +3 -1
- package/dist/api/base.d.ts +3 -1
- package/dist/api/base.js +1 -1
- package/dist/api/base.js.map +1 -1
- package/dist/api/base.mjs +1 -1
- package/dist/api/base.mjs.map +1 -1
- package/dist/api/businessProfile.js +1 -1
- package/dist/api/businessProfile.js.map +1 -1
- package/dist/api/businessProfile.mjs +1 -1
- package/dist/api/businessProfile.mjs.map +1 -1
- package/dist/api/encryption.js +1 -1
- package/dist/api/encryption.js.map +1 -1
- package/dist/api/encryption.mjs +1 -1
- package/dist/api/encryption.mjs.map +1 -1
- 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.d.mts +1 -1
- package/dist/api/index.d.ts +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/media.js +1 -1
- package/dist/api/media.js.map +1 -1
- package/dist/api/media.mjs +1 -1
- package/dist/api/media.mjs.map +1 -1
- package/dist/api/messages.js +1 -1
- package/dist/api/messages.js.map +1 -1
- package/dist/api/messages.mjs +1 -1
- package/dist/api/messages.mjs.map +1 -1
- package/dist/api/phoneNumber.js +1 -1
- package/dist/api/phoneNumber.js.map +1 -1
- package/dist/api/phoneNumber.mjs +1 -1
- package/dist/api/phoneNumber.mjs.map +1 -1
- package/dist/api/qrCode.js +1 -1
- package/dist/api/qrCode.js.map +1 -1
- package/dist/api/qrCode.mjs +1 -1
- package/dist/api/qrCode.mjs.map +1 -1
- package/dist/api/registration.js +1 -1
- package/dist/api/registration.js.map +1 -1
- package/dist/api/registration.mjs +1 -1
- package/dist/api/registration.mjs.map +1 -1
- package/dist/api/template.js +1 -1
- package/dist/api/template.js.map +1 -1
- package/dist/api/template.mjs +1 -1
- package/dist/api/template.mjs.map +1 -1
- package/dist/api/twoStepVerification.js +1 -1
- package/dist/api/twoStepVerification.js.map +1 -1
- package/dist/api/twoStepVerification.mjs +1 -1
- package/dist/api/twoStepVerification.mjs.map +1 -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 -0
- package/dist/index.d.ts +2 -0
- 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/request.d.mts +5 -3
- package/dist/request.d.ts +5 -3
- package/dist/request.js +1 -1
- package/dist/request.js.map +1 -1
- package/dist/request.mjs +1 -1
- package/dist/request.mjs.map +1 -1
- package/dist/types/request.d.mts +5 -3
- package/dist/types/request.d.ts +5 -3
- package/dist/types/request.js +1 -1
- package/dist/types/request.js.map +1 -1
- package/dist/types/webhook.d.mts +453 -0
- package/dist/types/webhook.d.ts +453 -0
- package/dist/types/webhook.js +2 -0
- package/dist/types/webhook.js.map +1 -0
- package/dist/types/webhook.mjs +2 -0
- package/dist/types/webhook.mjs.map +1 -0
- package/dist/utils/filters.d.mts +143 -0
- package/dist/utils/filters.d.ts +143 -0
- package/dist/utils/filters.js +2 -0
- package/dist/utils/filters.js.map +1 -0
- package/dist/utils/filters.mjs +2 -0
- package/dist/utils/filters.mjs.map +1 -0
- package/dist/webhook.d.mts +93 -0
- package/dist/webhook.d.ts +93 -0
- package/dist/webhook.js +2 -0
- package/dist/webhook.js.map +1 -0
- package/dist/webhook.mjs +2 -0
- package/dist/webhook.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 +2 -2
package/dist/request.d.mts
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.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
|
|
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
|
package/dist/request.js.map
CHANGED
|
@@ -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.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E,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":["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,G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,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,QACFR,EACAD,EACAE,EACAC,EACAL,EACU,CAEV,OAAQ,MADI,MAAM,KAAK,YAAYG,EAAQD,EAAUE,EAASC,EAAM,mBAAoBL,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
|
|
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
|
package/dist/request.mjs.map
CHANGED
|
@@ -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,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,KAA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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,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N,CAAQ,EAC3BC,EACA,KAAK,YAAYG,EAAsBN,CAAiB,EACxDI,EACAD,IAAW,QAAUA,IAAW,MAAQE,EAAO,MACnD,EAEA,GAAI,CAACG,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,QACFR,EACAD,EACAE,EACAC,EACAL,EACU,CAEV,OAAQ,MADI,MAAM,KAAK,YAAYG,EAAQD,EAAUE,EAASC,EAAM,mBAAoBL,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":["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"]}
|
package/dist/types/request.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { H as HttpMethodsEnum } from '../enums-D7paGoTY.mjs';
|
|
2
2
|
|
|
3
|
-
type GeneralRequestBody = Record<string,
|
|
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?:
|
|
45
|
-
getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?:
|
|
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 };
|
package/dist/types/request.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { H as HttpMethodsEnum } from '../enums-D7paGoTY.js';
|
|
2
2
|
|
|
3
|
-
type GeneralRequestBody = Record<string,
|
|
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?:
|
|
45
|
-
getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?:
|
|
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 };
|
package/dist/types/request.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
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,
|
|
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"]}
|