@ecodrix/erix-api 1.2.2 → 1.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +22 -6
- package/dist/ts/browser/index.global.js +5 -5
- package/dist/ts/browser/index.global.js.map +1 -1
- package/dist/ts/cjs/index.cjs +1 -1
- package/dist/ts/cjs/index.cjs.map +1 -1
- package/dist/ts/cjs/index.d.cts +22 -6
- package/dist/ts/esm/index.d.ts +22 -6
- package/dist/ts/esm/index.js +1 -1
- package/dist/ts/esm/index.js.map +1 -1
- package/package.json +1 -1
- package/src/core.ts +24 -0
- package/src/resources/media.ts +16 -6
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import ie from"repl";import{Command as oe}from"commander";import ce from"dotenv";import o from"picocolors";import ae from"axios";import X from"axios-retry";import{io as ne}from"socket.io-client";var H=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends H{status;code;constructor(e,t,a){super(e),this.name="APIError",this.status=t,this.code=a}},T=class extends u{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}};var i=class{constructor(e){this.client=e}async post(e,t,a){try{let s=this.buildConfig(a);return(await this.client.post(e,t,s)).data}catch(s){this.handleError(s)}}async get(e,t){try{let a=this.buildConfig(t);return(await this.client.get(e,a)).data}catch(a){this.handleError(a)}}async patch(e,t,a){try{let s=this.buildConfig(a);return(await this.client.patch(e,t,s)).data}catch(s){this.handleError(s)}}async put(e,t,a){try{let s=this.buildConfig(a);return(await this.client.put(e,t,s)).data}catch(s){this.handleError(s)}}async deleteRequest(e,t){try{let a=this.buildConfig(t);return(await this.client.delete(e,a)).data}catch(a){this.handleError(a)}}buildConfig(e){if(!e)return;let t={...e};return e.idempotencyKey&&(t.headers={...t.headers,"Idempotency-Key":e.idempotencyKey}),t}handleError(e){throw e.response?new u(e.response.data?.message||e.response.data?.error||"API Request Failed",e.response.status,e.response.data?.code):new u(e.message||"Network Error")}};var j=class extends i{async list(e){return this.get(`/api/crm/leads/${e}/notes`)}async create(e,t){return this.post(`/api/crm/leads/${e}/notes`,t)}async update(e,t){return this.patch(`/api/crm/notes/${e}`,{content:t})}async pin(e,t=!0){return this.patch(`/api/crm/notes/${e}/pin`,{isPinned:t})}async delete(e){return this.deleteRequest(`/api/crm/notes/${e}`)}},f=class extends i{notes;constructor(e){super(e),this.notes=new j(e)}async timeline(e,t){return this.get(`/api/crm/leads/${e}/timeline`,{params:t})}async list(e,t){return this.get(`/api/crm/leads/${e}/activities`,{params:{...t}})}async log(e){return this.post(`/api/crm/leads/${e.leadId}/activities`,e)}async logCall(e,t){return this.post(`/api/crm/leads/${e}/calls`,t)}};var b=class extends i{async overview(e){return this.get("/api/crm/analytics/overview",{params:e})}async funnel(e){return this.get("/api/crm/analytics/funnel",{params:{pipelineId:e}})}async forecast(e){return this.get("/api/crm/analytics/forecast",{params:{pipelineId:e}})}async sources(e){return this.get("/api/crm/analytics/sources",{params:e})}async team(e){return this.get("/api/crm/analytics/team",{params:e})}async heatmap(e){return this.get("/api/crm/analytics/heatmap",{params:e})}async scores(){return this.get("/api/crm/analytics/scores")}async stageTime(e){return this.get("/api/crm/analytics/stage-time",{params:{pipelineId:e}})}async tiered(e){return this.get("/api/crm/analytics/tiered",{params:e})}async summary(e){return this.get("/api/crm/analytics/summary",{params:e})}async whatsapp(e){return this.get("/api/crm/analytics/whatsapp",{params:e})}};var v=class extends i{async stats(){return this.get("/api/crm/automation/stats")}async logs(e){return this.get("/api/crm/automation/logs",{params:e})}async retryFailedEvent(e){return this.post(`/api/crm/automation/logs/${e}/retry`,{})}};var x=class extends i{async list(){return this.get("/api/crm/automations")}async create(e){return this.post("/api/crm/automations",e)}async update(e,t){return this.patch(`/api/crm/automations/${e}`,t)}async toggle(e){return this.patch(`/api/crm/automations/${e}/toggle`)}async delete(e){return this.deleteRequest(`/api/crm/automations/${e}`)}async bulkDelete(e){return this.post("/api/crm/automations/bulk-delete",{ids:e})}async test(e,t){return this.post(`/api/crm/automations/${e}/test`,{leadId:t})}async getAvailableEvents(){return this.post("/api/crm/automations/events",{})}async enrollments(e,t){return this.get(`/api/crm/automations/${e}/enrollments`,{params:t})}async getEnrollment(e){return this.get(`/api/crm/automations/enrollments/${e}`)}async pauseEnrollment(e,t){return this.post(`/api/crm/automations/${e}/enrollments/${t}/pause`,{})}async resumeEnrollment(e,t){return this.post(`/api/crm/automations/${e}/enrollments/${t}/resume`,{})}async runs(e){return this.get(`/api/crm/automations/${e}/runs`)}async getRun(e){return this.get(`/api/crm/automations/runs/${e}`)}async resumeRun(e){return this.post(`/api/crm/automations/runs/${e}/resume`,{})}async abortRun(e){return this.post(`/api/crm/automations/runs/${e}/abort`,{})}async webhookEvent(e,t,a){return this.post("/api/crm/webhook-event",{ruleId:e,eventName:t,payload:a})}};var P=class extends i{async create(e){return this.post("/api/crm/leads",e)}async describe(){let e=await this.fields(),t=Array.isArray(e.data)?e.data:[],a=[{key:"firstName",label:"First Name",type:"string",required:!0,group:"Basic Info"},{key:"lastName",label:"Last Name",type:"string",required:!1,group:"Basic Info"},{key:"phone",label:"Phone Number",type:"phone",required:!0,group:"Contact"},{key:"email",label:"Email Address",type:"email",required:!1,group:"Contact"},{key:"status",label:"Status",type:"select",required:!0,options:[{label:"New",value:"new"},{label:"Contacted",value:"contacted"},{label:"Qualified",value:"qualified"},{label:"Won",value:"won"},{label:"Lost",value:"lost"}]},{key:"value",label:"Lead Value",type:"currency",required:!1},{key:"source",label:"Source",type:"string",required:!1}],s=t.map(r=>({key:`metadata.extra.${r.name}`,label:r.label||r.name,type:r.type||"string",required:!!r.required,options:r.options,group:"Custom Fields"}));return{name:"Lead",fields:[...a,...s],uiHints:{icon:"User",primaryColor:"#3b82f6",defaultSort:{field:"createdAt",direction:"desc"},summaryFields:["firstName","lastName","phone","status"]}}}async upsert(e){return this.post("/api/crm/leads/upsert",e)}async createMany(e,t=50){let a=[];for(let s=0;s<e.length;s+=t){let l=e.slice(s,s+t).map(m=>this.create(m)),g=await Promise.allSettled(l);for(let m of g)if(m.status==="fulfilled")a.push(m.value);else throw m.reason}return a}async import(e){return this.post("/api/crm/leads/import",{leads:e})}async list(e){let t={...e};return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/api/crm/leads",{params:t})}async*listAutoPaging(e){let t=e?.page||1,a=!0;for(;a;){let s=await this.list({...e,page:t}),r=Array.isArray(s.data)?s.data:s||[];if(r.length===0){a=!1;break}for(let l of r)yield l;s.pagination&&t<s.pagination.pages||!s.pagination&&r.length>0?t++:a=!1}}async retrieve(e){return this.get(`/api/crm/leads/${e}`)}async retrieveByPhone(e){return this.get(`/api/crm/leads/phone/${encodeURIComponent(e)}`)}async retrieveByRef(e,t){return this.get(`/api/crm/leads/ref/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async update(e,t){return this.patch(`/api/crm/leads/${e}`,t)}async move(e,t){return this.patch(`/api/crm/leads/${e}/move`,{stageId:t})}async convert(e,t,a){return this.post(`/api/crm/leads/${e}/convert`,{outcome:t,reason:a})}async tags(e,t){return this.patch(`/api/crm/leads/${e}/tags`,t)}async recalculateScore(e){return this.post(`/api/crm/leads/${e}/score`,{})}async updateMetadata(e,t){return this.patch(`/api/crm/leads/${e}/metadata`,t)}async fields(){return this.get("/api/crm/leads/fields")}async notes(e){return this.get(`/api/crm/leads/${e}/notes`)}async activities(e,t){return this.get(`/api/crm/leads/${e}/timeline`,{params:t})}async createNote(e,t){return this.post(`/api/crm/leads/${e}/notes`,t)}async updateNote(e,t,a){return this.patch(`/api/crm/notes/${t}`,a)}async deleteNote(e,t){return this.deleteRequest(`/api/crm/notes/${t}`)}async delete(e){return this.deleteRequest(`/api/crm/leads/${e}`)}async bulkDelete(e){return this.deleteRequest("/api/crm/leads",{data:{ids:e}})}};var w=class extends i{async capture(e){return this.post("/api/crm/payments/capture",e)}};var $=class extends i{async list(){return this.get("/api/crm/pipelines")}async getStageManifest(e){let t=await this.retrieve(e),a=Array.isArray(t.data?.stages)?t.data.stages:[];return{name:`Pipeline: ${t.data?.name||e}`,fields:a.map(s=>({key:s._id,label:s.name,type:"string",required:!0,options:[{label:s.name,value:s._id}],group:"Stages",uiHints:{color:s.color||"#cbd5e1",probability:s.probability}})),uiHints:{icon:"Columns",primaryColor:"#6366f1"}}}async create(e){return this.post("/api/crm/pipelines",e)}async retrieve(e){return this.get(`/api/crm/pipelines/${e}`)}async update(e,t){return this.patch(`/api/crm/pipelines/${e}`,t)}async setDefault(e){return this.patch(`/api/crm/pipelines/${e}/default`,{})}async duplicate(e,t){return this.post(`/api/crm/pipelines/${e}/duplicate`,{newName:t})}async archive(e){return this.patch(`/api/crm/pipelines/${e}/archive`,{})}async delete(e){return this.deleteRequest(`/api/crm/pipelines/${e}`)}async board(e){return this.get(`/api/crm/pipelines/${e}/board`)}async forecast(e){return this.get(`/api/crm/pipelines/${e}/forecast`)}async addStage(e,t){return this.post(`/api/crm/pipelines/${e}/stages`,t)}async reorderStages(e,t){return this.patch(`/api/crm/pipelines/${e}/stages/reorder`,{order:t})}async updateStage(e,t){return this.patch(`/api/crm/stages/${e}`,t)}async deleteStage(e,t){return this.deleteRequest(`/api/crm/stages/${e}`,{data:t?{moveLeadsToStageId:t}:void 0})}};var R=class extends i{async getConfig(){return this.get("/api/crm/scoring")}async updateConfig(e){return this.patch("/api/crm/scoring",e)}async recalculate(e){return this.post(`/api/crm/scoring/${e}/recalculate`,{})}};var C=class extends i{async enroll(e){return this.post("/api/crm/sequences/enroll",e)}async unenroll(e){return this.deleteRequest(`/api/crm/sequences/unenroll/${e}`)}async listForLead(e){return this.get(`/api/crm/sequences/lead/${e}`)}};var A=class{leads;pipelines;activities;analytics;automations;sequences;scoring;payments;automationDashboard;constructor(e){this.leads=new P(e),this.pipelines=new $(e),this.activities=new f(e),this.analytics=new b(e),this.automations=new x(e),this.sequences=new C(e),this.scoring=new R(e),this.payments=new w(e),this.automationDashboard=new v(e)}};var I=class extends i{async sendCampaign(e){return this.post("/api/saas/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/emails/test",{to:e})}async listTemplates(e){return this.get("/api/saas/mail/templates",{params:e})}async getTemplate(e){return this.get(`/api/saas/mail/templates/${e}`)}async createTemplate(e){return this.post("/api/saas/mail/templates",e)}async updateTemplate(e,t){return this.put(`/api/saas/mail/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/api/saas/mail/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/api/saas/mail/templates/${e}/preview`,t)}};var k=class extends i{async list(){return this.get("/api/saas/events")}async assign(e){return this.post("/api/saas/events/assign",e)}async unassign(e){return this.post("/api/saas/events/unassign",{name:e})}async unassignBulk(e){return this.post("/api/saas/events/unassign/bulk",{names:e})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}async listCustomEvents(){return this.get("/api/saas/crm/custom-events")}async createCustomEvent(e){return this.post("/api/saas/crm/custom-events",e)}async deleteCustomEvent(e){return this.deleteRequest(`/api/saas/crm/custom-events/${e}`)}async emit(e){return this.post("/api/saas/crm/events/emit",e)}};var E=class extends i{async system(){return(await this.get("/api/saas/health")).data}async clientHealth(){return(await this.get("/api/saas/health/client")).data}async getDiagnosticReport(){return this.clientHealth()}async jobStatus(e){return(await this.get(`/api/saas/jobs/status/${e}`)).data}};var S=class extends i{async listEventLogs(e){return this.get("/api/saas/events/logs",{params:e})}async getEventLog(e){return this.get(`/api/saas/events/logs/${e}`)}async listCallbackLogs(e){return this.get("/api/saas/callbacks/logs",{params:e})}async getStats(){return this.get("/api/saas/events/stats")}};var J=class extends i{async sendCampaign(e){return this.post("/api/saas/marketing/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/marketing/emails/test",{to:e})}},Y=class extends i{async list(e){return this.get("/api/saas/marketing/campaigns",{params:e})}async create(e){return this.post("/api/saas/marketing/campaigns",e)}async retrieve(e){return this.get(`/api/saas/marketing/campaigns/${e}`)}async update(e,t){return this.patch(`/api/saas/marketing/campaigns/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/marketing/campaigns/${e}`)}async send(e,t){return this.post(`/api/saas/marketing/campaigns/${e}/send`,t||{})}async stats(e){return this.get(`/api/saas/marketing/campaigns/${e}/stats`)}},G=class extends i{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},L=class extends i{emails;campaigns;whatsapp;constructor(e){super(e),this.emails=new J(e),this.campaigns=new Y(e),this.whatsapp=new G(e)}};import se from"axios";var D=class extends i{async getUsage(){return this.get("/api/saas/storage/usage")}async createFolder(e){return this.post("/api/saas/storage/folders",{name:e})}async list(e,t){return this.get(`/api/saas/storage/files/${e}`,{params:t})}async delete(e){return this.deleteRequest("/api/saas/storage/files",{params:{key:e}})}async getDownloadUrl(e){return this.post("/api/saas/storage/download-url",{key:e})}async upload(e,t){let a=await this.post("/api/saas/storage/upload-url",t),{uploadUrl:s,key:r}=a.data;await se.put(s,e,{headers:{"Content-Type":t.contentType}});let l=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:r,sizeBytes:l})}};var q=class extends i{async create(e){return this.post("/api/saas/meet",e)}async list(e){return this.get("/api/saas/meet",{params:e})}async retrieve(e){return this.get(`/api/saas/meet/${e}`)}async update(e,t){return this.patch(`/api/saas/meet/${e}`,t)}async reschedule(e,t){return this.patch(`/api/saas/meet/${e}`,t)}async delete(e){return this.update(e,{status:"cancelled"})}};var O=class extends i{async listLogs(e){return this.get("/api/saas/events/logs",{params:e})}async retrieveLog(e){return this.get(`/api/saas/events/logs/${e}`)}async getStats(e){return this.get("/api/saas/events/stats",{params:e})}async listCallbacks(e){return this.get("/api/saas/callbacks/logs",{params:e})}async listAlerts(e){return this.get("/api/crm/notifications",{params:e})}async dismissAlert(e){return this.patch(`/api/crm/notifications/${e}/dismiss`)}async clearAllAlerts(){return this.deleteRequest("/api/crm/notifications/clear-all")}async retryAction(e){return this.post(`/api/crm/notifications/${e}/retry`,{})}};var M=class extends i{async listFailed(){return this.get("/api/saas/admin/queue/failed")}async getStats(){return this.get("/api/saas/admin/queue/stats")}async retryJob(e){return this.post(`/api/saas/admin/queue/${e}/retry`,{})}async deleteJob(e){return this.deleteRequest(`/api/saas/admin/queue/${e}`)}};var Q=class extends i{async create(e){return this.post("/api/saas/storage/folders",{name:e})}async delete(e){return this.deleteRequest(`/api/saas/storage/folders/${encodeURIComponent(e)}`)}},z=class extends i{async list(e,t){return this.get(`/api/saas/storage/files/${e}`,{params:t})}async getUploadUrl(e){return this.post("/api/saas/storage/upload-url",e)}async confirmUpload(e){return this.post("/api/saas/storage/confirm-upload",e)}async getDownloadUrl(e){return this.post("/api/saas/storage/download-url",{key:e})}async delete(e){return this.deleteRequest("/api/saas/storage/files",{params:{key:e}})}},N=class extends i{folders;files;constructor(e){super(e),this.folders=new Q(e),this.files=new z(e)}async usage(){return this.get("/api/saas/storage/usage")}};var h=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},U=class{async constructEvent(e,t,a){if(!t)throw new h("No webhook signature provided");let s=Array.isArray(t)?t[0]:t;s.startsWith("sha256=")&&(s=s.slice(7));try{let r=await import("crypto"),g=r.createHmac("sha256",a).update(e).digest("hex");if(!r.timingSafeEqual(Buffer.from(g),Buffer.from(s)))throw new h("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(r){throw r instanceof h?r:new h(`Webhook payload parsing failed: ${r.message}`)}}};var _=class extends i{async list(e){return this.get("/api/saas/chat/broadcasts",{params:e})}async retrieve(e){return this.get(`/api/saas/chat/broadcasts/${e}`)}async create(e){return this.post("/api/saas/chat/broadcast",e)}async update(e,t){return this.patch(`/api/saas/chat/broadcasts/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/chat/broadcasts/${e}`)}};var F=class extends i{async list(e){return this.get("/api/saas/chat/conversations",{params:e})}async create(e){return this.post("/api/saas/chat/conversations",e)}async retrieve(e){return this.get(`/api/saas/chat/conversations/${e}`)}async messages(e,t){return this.get(`/api/saas/chat/conversations/${e}/messages`,{params:t})}async linkLead(e,t,a){return this.post(`/api/saas/chat/conversations/${e}/link-lead`,{leadId:t,leadData:a})}async markRead(e){return this.post(`/api/saas/chat/conversations/${e}/read`,{})}async delete(e){return this.deleteRequest(`/api/saas/chat/conversations/${e}`)}async bulkDelete(e){return this.post("/api/saas/chat/conversations/bulk-delete",{ids:e})}};var B=class extends i{async send(e){return this.post("/api/saas/chat/send",e)}async sendTemplate(e){return this.post("/api/saas/chat/send",{...e,templateLanguage:e.language||e.templateLanguage||"en_US"})}async star(e,t){return this.post(`/api/saas/chat/messages/${e}/star`,{isStarred:t})}async react(e,t){return this.post(`/api/saas/chat/messages/${e}/react`,{reaction:t})}async markRead(e){return this.post(`/api/saas/chat/conversations/${e}/read`)}async upload(e){let t=new FormData;return t.append("file",e),this.post("/api/saas/chat/upload",t,{headers:{"Content-Type":"multipart/form-data"}})}};var K=class extends i{async list(e){return this.get("/api/saas/chat/templates",{params:e})}async sync(){return this.post("/api/saas/chat/templates/sync",{})}async retrieve(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}`)}async create(e){return this.post("/api/saas/chat/templates",e)}async update(e,t){return this.put(`/api/saas/chat/templates/${e}`,t)}async deleteTemplate(e,t){return this.deleteRequest(`/api/saas/chat/templates/${encodeURIComponent(e)}${t?"?force=true":""}`)}async mappingConfig(){return this.get("/api/saas/chat/templates/mapping/config")}async collections(){return this.get("/api/saas/chat/templates/collections")}async collectionFields(e){return this.get(`/api/saas/chat/templates/collections/${encodeURIComponent(e)}/fields`)}async updateMapping(e,t){return this.put(`/api/saas/chat/templates/${encodeURIComponent(e)}/mapping`,t)}async validate(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/validate`)}async preview(e,t){return this.post(`/api/saas/chat/templates/${encodeURIComponent(e)}/preview`,{context:t})}async getVariableManifest(e){let t=await this.retrieve(e),a=Array.isArray(t.data?.components)?t.data.components:[],s=[];for(let r of a)if(r.text){let l=r.text.match(/{{(\d+)}}/g);if(l)for(let g of l){let m=g.replace(/{{|}}/g,"");s.push({key:`var_${m}`,label:`${r.type} Var {{${m}}}`,type:"string",required:!0,group:r.type,description:`Variable placeholder in template ${r.type}`})}}return{name:`Template variables: ${t.data?.name||e}`,fields:s,uiHints:{icon:"Variables",primaryColor:"#059669"}}}async checkUsage(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/usage`)}};var V=class extends i{messages;conversations;broadcasts;templates;constructor(e){super(e),this.messages=new B(e),this.conversations=new F(e),this.broadcasts=new _(e),this.templates=new K(e)}async upload(e,t){let a=new FormData;return a.append("file",e,t),this.post("/api/saas/chat/upload",a,{headers:typeof a.getHeaders=="function"?a.getHeaders():void 0})}async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}};var re="https://api.ecodrix.com",W=class{client;socket;whatsapp;crm;media;meet;notifications;email;logs;events;webhooks;storage;marketing;health;queue;constructor(e){if(!e.apiKey)throw new T("API Key is required");let t=e.baseUrl??re,a=e.socketUrl||t,s=typeof window<"u"&&typeof window.document<"u",r=s?"browser":typeof process<"u"?`node ${process.version}`:"unknown",l=s?globalThis.navigator?.userAgent||"browser":typeof process<"u"?process.platform:"unknown";this.client=ae.create({baseURL:t,headers:{"x-api-key":e.apiKey,"x-client-code":e.clientCode?.toUpperCase(),"Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:"1.0.0",runtime:r,os:l})}}),X(this.client,{retries:3,retryDelay:X.exponentialDelay,retryCondition:g=>X.isNetworkOrIdempotentRequestError(g)||g.response?.status===429,onRetry:(g,m,Z)=>{typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${g}/3): ${Z.method?.toUpperCase()} ${Z.url}. Reason: ${m.message}`)}}),this.whatsapp=new V(this.client),this.crm=new A(this.client),this.media=new D(this.client),this.meet=new q(this.client),this.notifications=new O(this.client),this.email=new I(this.client),this.logs=new S(this.client),this.events=new k(this.client),this.webhooks=new U,this.storage=new N(this.client),this.marketing=new L(this.client),this.health=new E(this.client),this.queue=new M(this.client),this.socket=ne(a,{extraHeaders:{"x-api-key":e.apiKey,"x-client-code":e.clientCode?.toUpperCase()||""}}),this.setupSocket(e.clientCode)}joinRoom(e){this.socket.emit("join-room",e)}leaveRoom(e){this.socket.emit("leave-room",e)}setupSocket(e){this.socket.on("connect",()=>{e&&this.socket.emit("join-room",e.toUpperCase())})}on(e,t){return this.socket.on(e,t),this}disconnect(){this.socket.disconnect()}off(e,t){return this.socket.off(e,t),this}async request(e,t,a,s){try{return(await this.client.request({method:e,url:t,data:a,params:s})).data}catch(r){throw r.response?new u(r.response.data?.message||r.response.data?.error||"Raw Execution Failed",r.response.status,r.response.data?.code):new u(r.message||"Network Error")}}};ce.config();var ee="1.2.2";var pe="Official Isomorphic SDK for the ECODrIx platform. Native support for WhatsApp, CRM, Storage, and Meetings across TS, JS, Python, and Java.",d=new oe;d.name("erix").description(pe).version(ee);function y(n){let e=n.key||process.env.ECOD_API_KEY,t=n.client||process.env.ECOD_CLIENT_CODE;return e||(console.error(o.red("Error: API Key is missing.")),console.log(o.yellow("Set ECOD_API_KEY environment variable or use --key <key>")),process.exit(1)),new W({apiKey:e,clientCode:t,baseUrl:n.baseUrl||process.env.ECOD_BASE_URL})}d.option("-k, --key <key>","ECODrIx API Key").option("-c, --client <code...","Tenant Client Code").option("--base-url <url>","API Base URL override");d.command("whoami").description("Verify current authentication and tenant status").action(async(n,e)=>{let t=e.parent.opts(),a=y(t);console.log(o.cyan("Checking connection to ECODrIx Platform..."));try{let s=await a.request("GET","/api/saas/me/profile");console.log(o.green("\u2714 Authenticated successfully!")),console.log(`${o.bold("User ID:")} ${s.id}`),console.log(`${o.bold("Organisation:")} ${s.organisation?.name||"N/A"}`),t.client&&console.log(`${o.bold("Tenant Code:")} ${o.magenta(t.client)}`)}catch(s){console.error(o.red("\u2716 Authentication failed")),console.error(o.dim(s.message)),process.exit(1)}});var le=d.command("whatsapp").description("WhatsApp Business API operations");le.command("send-template").description("Send a WhatsApp template message").argument("<phone>","Recipient phone number").argument("<template>","Template name").option("-v, --vars <json>","Template variables as JSON string","[]").action(async(n,e,t,a)=>{let s=a.parent.parent.opts(),r=y(s);try{let l=JSON.parse(t.vars);console.log(o.cyan(`Sending template '${e}' to ${n}...`));let g=await r.whatsapp.messages.sendTemplate({to:n,templateName:e,language:"en_US",variables:l});console.log(o.green("\u2714 Message sent successfully!")),console.log(o.dim(`ID: ${g?.id||"N/A"}`))}catch(l){console.error(o.red("\u2716 Failed to send message")),console.error(o.dim(l.message))}});var te=d.command("crm").description("CRM and Lead management");te.command("leads").description("List recent leads").option("-l, --limit <number>","Number of leads to fetch","10").option("-s, --status <status>","Filter by lead status").option("-p, --pipeline <id>","Filter by pipeline ID").option("-q, --search <query>","Search by name or email").action(async(n,e)=>{let t=e.parent.parent.opts(),a=y(t);try{let s=Number.parseInt(n.limit);console.log(o.cyan(`Fetching last ${s} leads...`));let r={limit:s};n.status&&(r.status=n.status),n.pipeline&&(r.pipelineId=n.pipeline),n.search&&(r.search=n.search);let l=await a.crm.leads.list(r),g=Array.isArray(l.data)?l.data:Array.isArray(l)?l:[];if(g.length===0){console.log(o.yellow("No leads found."));return}console.table(g.map(m=>({ID:m.id||m._id,Name:`${m.firstName} ${m.lastName||""}`.trim(),Phone:m.phone,Status:m.status,Score:m.score||0,Created:new Date(m.createdAt).toLocaleDateString()})))}catch(s){console.error(o.red("\u2716 Failed to fetch leads")),console.error(o.dim(s.message))}});te.command("pipelines").description("List all CRM pipelines").action(async(n,e)=>{let t=e.parent.parent.opts(),a=y(t);try{console.log(o.cyan("Fetching pipelines..."));let s=await a.crm.pipelines.list(),r=s.data||s||[];if(r.length===0){console.log(o.yellow("No pipelines found."));return}console.table(r.map(l=>({ID:l.id||l._id,Name:l.name,Default:l.isDefault?"Yes":"No",Stages:l.stages?.length||0})))}catch(s){console.error(o.red("\u2716 Failed to fetch pipelines")),console.error(o.dim(s.message))}});var me=d.command("analytics").description("Business Intelligence Analytics");me.command("overview").description("Get high-level CRM KPIs").option("-r, --range <range>","Date range (e.g., 24h, 7d, 30d, 365d)","30d").action(async(n,e)=>{let t=e.parent.parent.opts(),a=y(t);try{console.log(o.cyan(`Fetching overview metrics for last ${n.range}...`));let s=await a.crm.analytics.overview({range:n.range}),r=s.data||s;console.log(`
|
|
2
|
+
import ie from"repl";import{Command as oe}from"commander";import ce from"dotenv";import o from"picocolors";import ae from"axios";import X from"axios-retry";import{io as ne}from"socket.io-client";var H=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends H{status;code;constructor(e,t,a){super(e),this.name="APIError",this.status=t,this.code=a}},T=class extends u{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}};var i=class{constructor(e){this.client=e}async post(e,t,a){try{let s=this.buildConfig(a);return(await this.client.post(e,t,s)).data}catch(s){this.handleError(s)}}async get(e,t){try{let a=this.buildConfig(t);return(await this.client.get(e,a)).data}catch(a){this.handleError(a)}}async patch(e,t,a){try{let s=this.buildConfig(a);return(await this.client.patch(e,t,s)).data}catch(s){this.handleError(s)}}async put(e,t,a){try{let s=this.buildConfig(a);return(await this.client.put(e,t,s)).data}catch(s){this.handleError(s)}}async deleteRequest(e,t){try{let a=this.buildConfig(t);return(await this.client.delete(e,a)).data}catch(a){this.handleError(a)}}buildConfig(e){if(!e)return;let t={...e};return e.idempotencyKey&&(t.headers={...t.headers,"Idempotency-Key":e.idempotencyKey}),t}handleError(e){throw e.response?new u(e.response.data?.message||e.response.data?.error||"API Request Failed",e.response.status,e.response.data?.code):new u(e.message||"Network Error")}};var j=class extends i{async list(e){return this.get(`/api/crm/leads/${e}/notes`)}async create(e,t){return this.post(`/api/crm/leads/${e}/notes`,t)}async update(e,t){return this.patch(`/api/crm/notes/${e}`,{content:t})}async pin(e,t=!0){return this.patch(`/api/crm/notes/${e}/pin`,{isPinned:t})}async delete(e){return this.deleteRequest(`/api/crm/notes/${e}`)}},f=class extends i{notes;constructor(e){super(e),this.notes=new j(e)}async timeline(e,t){return this.get(`/api/crm/leads/${e}/timeline`,{params:t})}async list(e,t){return this.get(`/api/crm/leads/${e}/activities`,{params:{...t}})}async log(e){return this.post(`/api/crm/leads/${e.leadId}/activities`,e)}async logCall(e,t){return this.post(`/api/crm/leads/${e}/calls`,t)}};var b=class extends i{async overview(e){return this.get("/api/crm/analytics/overview",{params:e})}async funnel(e){return this.get("/api/crm/analytics/funnel",{params:{pipelineId:e}})}async forecast(e){return this.get("/api/crm/analytics/forecast",{params:{pipelineId:e}})}async sources(e){return this.get("/api/crm/analytics/sources",{params:e})}async team(e){return this.get("/api/crm/analytics/team",{params:e})}async heatmap(e){return this.get("/api/crm/analytics/heatmap",{params:e})}async scores(){return this.get("/api/crm/analytics/scores")}async stageTime(e){return this.get("/api/crm/analytics/stage-time",{params:{pipelineId:e}})}async tiered(e){return this.get("/api/crm/analytics/tiered",{params:e})}async summary(e){return this.get("/api/crm/analytics/summary",{params:e})}async whatsapp(e){return this.get("/api/crm/analytics/whatsapp",{params:e})}};var v=class extends i{async stats(){return this.get("/api/crm/automation/stats")}async logs(e){return this.get("/api/crm/automation/logs",{params:e})}async retryFailedEvent(e){return this.post(`/api/crm/automation/logs/${e}/retry`,{})}};var x=class extends i{async list(){return this.get("/api/crm/automations")}async create(e){return this.post("/api/crm/automations",e)}async update(e,t){return this.patch(`/api/crm/automations/${e}`,t)}async toggle(e){return this.patch(`/api/crm/automations/${e}/toggle`)}async delete(e){return this.deleteRequest(`/api/crm/automations/${e}`)}async bulkDelete(e){return this.post("/api/crm/automations/bulk-delete",{ids:e})}async test(e,t){return this.post(`/api/crm/automations/${e}/test`,{leadId:t})}async getAvailableEvents(){return this.post("/api/crm/automations/events",{})}async enrollments(e,t){return this.get(`/api/crm/automations/${e}/enrollments`,{params:t})}async getEnrollment(e){return this.get(`/api/crm/automations/enrollments/${e}`)}async pauseEnrollment(e,t){return this.post(`/api/crm/automations/${e}/enrollments/${t}/pause`,{})}async resumeEnrollment(e,t){return this.post(`/api/crm/automations/${e}/enrollments/${t}/resume`,{})}async runs(e){return this.get(`/api/crm/automations/${e}/runs`)}async getRun(e){return this.get(`/api/crm/automations/runs/${e}`)}async resumeRun(e){return this.post(`/api/crm/automations/runs/${e}/resume`,{})}async abortRun(e){return this.post(`/api/crm/automations/runs/${e}/abort`,{})}async webhookEvent(e,t,a){return this.post("/api/crm/webhook-event",{ruleId:e,eventName:t,payload:a})}};var P=class extends i{async create(e){return this.post("/api/crm/leads",e)}async describe(){let e=await this.fields(),t=Array.isArray(e.data)?e.data:[],a=[{key:"firstName",label:"First Name",type:"string",required:!0,group:"Basic Info"},{key:"lastName",label:"Last Name",type:"string",required:!1,group:"Basic Info"},{key:"phone",label:"Phone Number",type:"phone",required:!0,group:"Contact"},{key:"email",label:"Email Address",type:"email",required:!1,group:"Contact"},{key:"status",label:"Status",type:"select",required:!0,options:[{label:"New",value:"new"},{label:"Contacted",value:"contacted"},{label:"Qualified",value:"qualified"},{label:"Won",value:"won"},{label:"Lost",value:"lost"}]},{key:"value",label:"Lead Value",type:"currency",required:!1},{key:"source",label:"Source",type:"string",required:!1}],s=t.map(r=>({key:`metadata.extra.${r.name}`,label:r.label||r.name,type:r.type||"string",required:!!r.required,options:r.options,group:"Custom Fields"}));return{name:"Lead",fields:[...a,...s],uiHints:{icon:"User",primaryColor:"#3b82f6",defaultSort:{field:"createdAt",direction:"desc"},summaryFields:["firstName","lastName","phone","status"]}}}async upsert(e){return this.post("/api/crm/leads/upsert",e)}async createMany(e,t=50){let a=[];for(let s=0;s<e.length;s+=t){let l=e.slice(s,s+t).map(m=>this.create(m)),g=await Promise.allSettled(l);for(let m of g)if(m.status==="fulfilled")a.push(m.value);else throw m.reason}return a}async import(e){return this.post("/api/crm/leads/import",{leads:e})}async list(e){let t={...e};return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/api/crm/leads",{params:t})}async*listAutoPaging(e){let t=e?.page||1,a=!0;for(;a;){let s=await this.list({...e,page:t}),r=Array.isArray(s.data)?s.data:s||[];if(r.length===0){a=!1;break}for(let l of r)yield l;s.pagination&&t<s.pagination.pages||!s.pagination&&r.length>0?t++:a=!1}}async retrieve(e){return this.get(`/api/crm/leads/${e}`)}async retrieveByPhone(e){return this.get(`/api/crm/leads/phone/${encodeURIComponent(e)}`)}async retrieveByRef(e,t){return this.get(`/api/crm/leads/ref/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async update(e,t){return this.patch(`/api/crm/leads/${e}`,t)}async move(e,t){return this.patch(`/api/crm/leads/${e}/move`,{stageId:t})}async convert(e,t,a){return this.post(`/api/crm/leads/${e}/convert`,{outcome:t,reason:a})}async tags(e,t){return this.patch(`/api/crm/leads/${e}/tags`,t)}async recalculateScore(e){return this.post(`/api/crm/leads/${e}/score`,{})}async updateMetadata(e,t){return this.patch(`/api/crm/leads/${e}/metadata`,t)}async fields(){return this.get("/api/crm/leads/fields")}async notes(e){return this.get(`/api/crm/leads/${e}/notes`)}async activities(e,t){return this.get(`/api/crm/leads/${e}/timeline`,{params:t})}async createNote(e,t){return this.post(`/api/crm/leads/${e}/notes`,t)}async updateNote(e,t,a){return this.patch(`/api/crm/notes/${t}`,a)}async deleteNote(e,t){return this.deleteRequest(`/api/crm/notes/${t}`)}async delete(e){return this.deleteRequest(`/api/crm/leads/${e}`)}async bulkDelete(e){return this.deleteRequest("/api/crm/leads",{data:{ids:e}})}};var w=class extends i{async capture(e){return this.post("/api/crm/payments/capture",e)}};var $=class extends i{async list(){return this.get("/api/crm/pipelines")}async getStageManifest(e){let t=await this.retrieve(e),a=Array.isArray(t.data?.stages)?t.data.stages:[];return{name:`Pipeline: ${t.data?.name||e}`,fields:a.map(s=>({key:s._id,label:s.name,type:"string",required:!0,options:[{label:s.name,value:s._id}],group:"Stages",uiHints:{color:s.color||"#cbd5e1",probability:s.probability}})),uiHints:{icon:"Columns",primaryColor:"#6366f1"}}}async create(e){return this.post("/api/crm/pipelines",e)}async retrieve(e){return this.get(`/api/crm/pipelines/${e}`)}async update(e,t){return this.patch(`/api/crm/pipelines/${e}`,t)}async setDefault(e){return this.patch(`/api/crm/pipelines/${e}/default`,{})}async duplicate(e,t){return this.post(`/api/crm/pipelines/${e}/duplicate`,{newName:t})}async archive(e){return this.patch(`/api/crm/pipelines/${e}/archive`,{})}async delete(e){return this.deleteRequest(`/api/crm/pipelines/${e}`)}async board(e){return this.get(`/api/crm/pipelines/${e}/board`)}async forecast(e){return this.get(`/api/crm/pipelines/${e}/forecast`)}async addStage(e,t){return this.post(`/api/crm/pipelines/${e}/stages`,t)}async reorderStages(e,t){return this.patch(`/api/crm/pipelines/${e}/stages/reorder`,{order:t})}async updateStage(e,t){return this.patch(`/api/crm/stages/${e}`,t)}async deleteStage(e,t){return this.deleteRequest(`/api/crm/stages/${e}`,{data:t?{moveLeadsToStageId:t}:void 0})}};var R=class extends i{async getConfig(){return this.get("/api/crm/scoring")}async updateConfig(e){return this.patch("/api/crm/scoring",e)}async recalculate(e){return this.post(`/api/crm/scoring/${e}/recalculate`,{})}};var C=class extends i{async enroll(e){return this.post("/api/crm/sequences/enroll",e)}async unenroll(e){return this.deleteRequest(`/api/crm/sequences/unenroll/${e}`)}async listForLead(e){return this.get(`/api/crm/sequences/lead/${e}`)}};var A=class{leads;pipelines;activities;analytics;automations;sequences;scoring;payments;automationDashboard;constructor(e){this.leads=new P(e),this.pipelines=new $(e),this.activities=new f(e),this.analytics=new b(e),this.automations=new x(e),this.sequences=new C(e),this.scoring=new R(e),this.payments=new w(e),this.automationDashboard=new v(e)}};var I=class extends i{async sendCampaign(e){return this.post("/api/saas/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/emails/test",{to:e})}async listTemplates(e){return this.get("/api/saas/mail/templates",{params:e})}async getTemplate(e){return this.get(`/api/saas/mail/templates/${e}`)}async createTemplate(e){return this.post("/api/saas/mail/templates",e)}async updateTemplate(e,t){return this.put(`/api/saas/mail/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/api/saas/mail/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/api/saas/mail/templates/${e}/preview`,t)}};var k=class extends i{async list(){return this.get("/api/saas/events")}async assign(e){return this.post("/api/saas/events/assign",e)}async unassign(e){return this.post("/api/saas/events/unassign",{name:e})}async unassignBulk(e){return this.post("/api/saas/events/unassign/bulk",{names:e})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}async listCustomEvents(){return this.get("/api/saas/crm/custom-events")}async createCustomEvent(e){return this.post("/api/saas/crm/custom-events",e)}async deleteCustomEvent(e){return this.deleteRequest(`/api/saas/crm/custom-events/${e}`)}async emit(e){return this.post("/api/saas/crm/events/emit",e)}};var E=class extends i{async system(){return(await this.get("/api/saas/health")).data}async clientHealth(){return(await this.get("/api/saas/health/client")).data}async getDiagnosticReport(){return this.clientHealth()}async jobStatus(e){return(await this.get(`/api/saas/jobs/status/${e}`)).data}};var S=class extends i{async listEventLogs(e){return this.get("/api/saas/events/logs",{params:e})}async getEventLog(e){return this.get(`/api/saas/events/logs/${e}`)}async listCallbackLogs(e){return this.get("/api/saas/callbacks/logs",{params:e})}async getStats(){return this.get("/api/saas/events/stats")}};var J=class extends i{async sendCampaign(e){return this.post("/api/saas/marketing/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/marketing/emails/test",{to:e})}},Y=class extends i{async list(e){return this.get("/api/saas/marketing/campaigns",{params:e})}async create(e){return this.post("/api/saas/marketing/campaigns",e)}async retrieve(e){return this.get(`/api/saas/marketing/campaigns/${e}`)}async update(e,t){return this.patch(`/api/saas/marketing/campaigns/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/marketing/campaigns/${e}`)}async send(e,t){return this.post(`/api/saas/marketing/campaigns/${e}/send`,t||{})}async stats(e){return this.get(`/api/saas/marketing/campaigns/${e}/stats`)}},z=class extends i{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},D=class extends i{emails;campaigns;whatsapp;constructor(e){super(e),this.emails=new J(e),this.campaigns=new Y(e),this.whatsapp=new z(e)}};import se from"axios";var L=class extends i{async getUsage(){return this.get("/api/saas/storage/usage")}async createFolder(e){return this.post("/api/saas/storage/folders",{name:e})}async list(e,t){return this.get(`/api/saas/storage/files/${e}`,{params:t})}async delete(e){return this.deleteRequest("/api/saas/storage/files",{params:{key:e}})}async getDownloadUrl(e){return this.post("/api/saas/storage/download-url",{key:e})}async upload(e,t){let a=await this.post("/api/saas/storage/upload-url",t),{uploadUrl:s,key:r}=a.data;await se.put(s,e,{headers:{"Content-Type":t.contentType}});let l=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:r,sizeBytes:l})}};var q=class extends i{async create(e){return this.post("/api/saas/meet",e)}async list(e){return this.get("/api/saas/meet",{params:e})}async retrieve(e){return this.get(`/api/saas/meet/${e}`)}async update(e,t){return this.patch(`/api/saas/meet/${e}`,t)}async reschedule(e,t){return this.patch(`/api/saas/meet/${e}`,t)}async delete(e){return this.update(e,{status:"cancelled"})}};var O=class extends i{async listLogs(e){return this.get("/api/saas/events/logs",{params:e})}async retrieveLog(e){return this.get(`/api/saas/events/logs/${e}`)}async getStats(e){return this.get("/api/saas/events/stats",{params:e})}async listCallbacks(e){return this.get("/api/saas/callbacks/logs",{params:e})}async listAlerts(e){return this.get("/api/crm/notifications",{params:e})}async dismissAlert(e){return this.patch(`/api/crm/notifications/${e}/dismiss`)}async clearAllAlerts(){return this.deleteRequest("/api/crm/notifications/clear-all")}async retryAction(e){return this.post(`/api/crm/notifications/${e}/retry`,{})}};var M=class extends i{async listFailed(){return this.get("/api/saas/admin/queue/failed")}async getStats(){return this.get("/api/saas/admin/queue/stats")}async retryJob(e){return this.post(`/api/saas/admin/queue/${e}/retry`,{})}async deleteJob(e){return this.deleteRequest(`/api/saas/admin/queue/${e}`)}};var G=class extends i{async create(e){return this.post("/api/saas/storage/folders",{name:e})}async delete(e){return this.deleteRequest(`/api/saas/storage/folders/${encodeURIComponent(e)}`)}},Q=class extends i{async list(e,t){return this.get(`/api/saas/storage/files/${e}`,{params:t})}async getUploadUrl(e){return this.post("/api/saas/storage/upload-url",e)}async confirmUpload(e){return this.post("/api/saas/storage/confirm-upload",e)}async getDownloadUrl(e){return this.post("/api/saas/storage/download-url",{key:e})}async delete(e){return this.deleteRequest("/api/saas/storage/files",{params:{key:e}})}},N=class extends i{folders;files;constructor(e){super(e),this.folders=new G(e),this.files=new Q(e)}async usage(){return this.get("/api/saas/storage/usage")}};var h=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},U=class{async constructEvent(e,t,a){if(!t)throw new h("No webhook signature provided");let s=Array.isArray(t)?t[0]:t;s.startsWith("sha256=")&&(s=s.slice(7));try{let r=await import("crypto"),g=r.createHmac("sha256",a).update(e).digest("hex");if(!r.timingSafeEqual(Buffer.from(g),Buffer.from(s)))throw new h("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(r){throw r instanceof h?r:new h(`Webhook payload parsing failed: ${r.message}`)}}};var _=class extends i{async list(e){return this.get("/api/saas/chat/broadcasts",{params:e})}async retrieve(e){return this.get(`/api/saas/chat/broadcasts/${e}`)}async create(e){return this.post("/api/saas/chat/broadcast",e)}async update(e,t){return this.patch(`/api/saas/chat/broadcasts/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/chat/broadcasts/${e}`)}};var F=class extends i{async list(e){return this.get("/api/saas/chat/conversations",{params:e})}async create(e){return this.post("/api/saas/chat/conversations",e)}async retrieve(e){return this.get(`/api/saas/chat/conversations/${e}`)}async messages(e,t){return this.get(`/api/saas/chat/conversations/${e}/messages`,{params:t})}async linkLead(e,t,a){return this.post(`/api/saas/chat/conversations/${e}/link-lead`,{leadId:t,leadData:a})}async markRead(e){return this.post(`/api/saas/chat/conversations/${e}/read`,{})}async delete(e){return this.deleteRequest(`/api/saas/chat/conversations/${e}`)}async bulkDelete(e){return this.post("/api/saas/chat/conversations/bulk-delete",{ids:e})}};var B=class extends i{async send(e){return this.post("/api/saas/chat/send",e)}async sendTemplate(e){return this.post("/api/saas/chat/send",{...e,templateLanguage:e.language||e.templateLanguage||"en_US"})}async star(e,t){return this.post(`/api/saas/chat/messages/${e}/star`,{isStarred:t})}async react(e,t){return this.post(`/api/saas/chat/messages/${e}/react`,{reaction:t})}async markRead(e){return this.post(`/api/saas/chat/conversations/${e}/read`)}async upload(e){let t=new FormData;return t.append("file",e),this.post("/api/saas/chat/upload",t,{headers:{"Content-Type":"multipart/form-data"}})}};var K=class extends i{async list(e){return this.get("/api/saas/chat/templates",{params:e})}async sync(){return this.post("/api/saas/chat/templates/sync",{})}async retrieve(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}`)}async create(e){return this.post("/api/saas/chat/templates",e)}async update(e,t){return this.put(`/api/saas/chat/templates/${e}`,t)}async deleteTemplate(e,t){return this.deleteRequest(`/api/saas/chat/templates/${encodeURIComponent(e)}${t?"?force=true":""}`)}async mappingConfig(){return this.get("/api/saas/chat/templates/mapping/config")}async collections(){return this.get("/api/saas/chat/templates/collections")}async collectionFields(e){return this.get(`/api/saas/chat/templates/collections/${encodeURIComponent(e)}/fields`)}async updateMapping(e,t){return this.put(`/api/saas/chat/templates/${encodeURIComponent(e)}/mapping`,t)}async validate(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/validate`)}async preview(e,t){return this.post(`/api/saas/chat/templates/${encodeURIComponent(e)}/preview`,{context:t})}async getVariableManifest(e){let t=await this.retrieve(e),a=Array.isArray(t.data?.components)?t.data.components:[],s=[];for(let r of a)if(r.text){let l=r.text.match(/{{(\d+)}}/g);if(l)for(let g of l){let m=g.replace(/{{|}}/g,"");s.push({key:`var_${m}`,label:`${r.type} Var {{${m}}}`,type:"string",required:!0,group:r.type,description:`Variable placeholder in template ${r.type}`})}}return{name:`Template variables: ${t.data?.name||e}`,fields:s,uiHints:{icon:"Variables",primaryColor:"#059669"}}}async checkUsage(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/usage`)}};var V=class extends i{messages;conversations;broadcasts;templates;constructor(e){super(e),this.messages=new B(e),this.conversations=new F(e),this.broadcasts=new _(e),this.templates=new K(e)}async upload(e,t){let a=new FormData;return a.append("file",e,t),this.post("/api/saas/chat/upload",a,{headers:typeof a.getHeaders=="function"?a.getHeaders():void 0})}async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}};var re="https://api.ecodrix.com",W=class{client;socket;clientCode;whatsapp;crm;media;meet;notifications;email;logs;events;webhooks;storage;marketing;health;queue;constructor(e){if(!e.apiKey)throw new T("API Key is required");this.clientCode=e.clientCode?.toUpperCase();let t=e.baseUrl??re,a=e.socketUrl||t,s=typeof window<"u"&&typeof window.document<"u",r=s?"browser":typeof process<"u"?`node ${process.version}`:"unknown",l=s?globalThis.navigator?.userAgent||"browser":typeof process<"u"?process.platform:"unknown";if(this.client=ae.create({baseURL:t,headers:{"x-api-key":e.apiKey,"x-client-code":e.clientCode?.toUpperCase(),"Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:"1.0.0",runtime:r,os:l})}}),X(this.client,{retries:3,retryDelay:X.exponentialDelay,retryCondition:g=>X.isNetworkOrIdempotentRequestError(g)||g.response?.status===429,onRetry:(g,m,Z)=>{typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${g}/3): ${Z.method?.toUpperCase()} ${Z.url}. Reason: ${m.message}`)}}),this.whatsapp=new V(this.client),this.crm=new A(this.client),this.media=new L(this.client),this.meet=new q(this.client),this.notifications=new O(this.client),this.email=new I(this.client),this.logs=new S(this.client),this.events=new k(this.client),this.webhooks=new U,this.storage=new N(this.client),this.marketing=new D(this.client),this.health=new E(this.client),this.queue=new M(this.client),this.socket=ne(a,{extraHeaders:{"x-api-key":e.apiKey,"x-client-code":e.clientCode?.toUpperCase()||""}}),this.setupSocket(e.clientCode),s){let g={version:"1.2.2",clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=g,window.ecodrix||(window.ecodrix=this)}}joinRoom(e){this.socket.emit("join-room",e)}leaveRoom(e){this.socket.emit("leave-room",e)}setupSocket(e){this.socket.on("connect",()=>{e&&this.socket.emit("join-room",e.toUpperCase())})}on(e,t){return this.socket.on(e,t),this}disconnect(){this.socket.disconnect()}off(e,t){return this.socket.off(e,t),this}async request(e,t,a,s){try{return(await this.client.request({method:e,url:t,data:a,params:s})).data}catch(r){throw r.response?new u(r.response.data?.message||r.response.data?.error||"Raw Execution Failed",r.response.status,r.response.data?.code):new u(r.message||"Network Error")}}};ce.config();var ee="1.2.3";var pe="Official Isomorphic SDK for the ECODrIx platform. Native support for WhatsApp, CRM, Storage, and Meetings across TS, JS, Python, and Java.",d=new oe;d.name("erix").description(pe).version(ee);function y(n){let e=n.key||process.env.ECOD_API_KEY,t=n.client||process.env.ECOD_CLIENT_CODE;return e||(console.error(o.red("Error: API Key is missing.")),console.log(o.yellow("Set ECOD_API_KEY environment variable or use --key <key>")),process.exit(1)),new W({apiKey:e,clientCode:t,baseUrl:n.baseUrl||process.env.ECOD_BASE_URL})}d.option("-k, --key <key>","ECODrIx API Key").option("-c, --client <code...","Tenant Client Code").option("--base-url <url>","API Base URL override");d.command("whoami").description("Verify current authentication and tenant status").action(async(n,e)=>{let t=e.parent.opts(),a=y(t);console.log(o.cyan("Checking connection to ECODrIx Platform..."));try{let s=await a.request("GET","/api/saas/me/profile");console.log(o.green("\u2714 Authenticated successfully!")),console.log(`${o.bold("User ID:")} ${s.id}`),console.log(`${o.bold("Organisation:")} ${s.organisation?.name||"N/A"}`),t.client&&console.log(`${o.bold("Tenant Code:")} ${o.magenta(t.client)}`)}catch(s){console.error(o.red("\u2716 Authentication failed")),console.error(o.dim(s.message)),process.exit(1)}});var le=d.command("whatsapp").description("WhatsApp Business API operations");le.command("send-template").description("Send a WhatsApp template message").argument("<phone>","Recipient phone number").argument("<template>","Template name").option("-v, --vars <json>","Template variables as JSON string","[]").action(async(n,e,t,a)=>{let s=a.parent.parent.opts(),r=y(s);try{let l=JSON.parse(t.vars);console.log(o.cyan(`Sending template '${e}' to ${n}...`));let g=await r.whatsapp.messages.sendTemplate({to:n,templateName:e,language:"en_US",variables:l});console.log(o.green("\u2714 Message sent successfully!")),console.log(o.dim(`ID: ${g?.id||"N/A"}`))}catch(l){console.error(o.red("\u2716 Failed to send message")),console.error(o.dim(l.message))}});var te=d.command("crm").description("CRM and Lead management");te.command("leads").description("List recent leads").option("-l, --limit <number>","Number of leads to fetch","10").option("-s, --status <status>","Filter by lead status").option("-p, --pipeline <id>","Filter by pipeline ID").option("-q, --search <query>","Search by name or email").action(async(n,e)=>{let t=e.parent.parent.opts(),a=y(t);try{let s=Number.parseInt(n.limit);console.log(o.cyan(`Fetching last ${s} leads...`));let r={limit:s};n.status&&(r.status=n.status),n.pipeline&&(r.pipelineId=n.pipeline),n.search&&(r.search=n.search);let l=await a.crm.leads.list(r),g=Array.isArray(l.data)?l.data:Array.isArray(l)?l:[];if(g.length===0){console.log(o.yellow("No leads found."));return}console.table(g.map(m=>({ID:m.id||m._id,Name:`${m.firstName} ${m.lastName||""}`.trim(),Phone:m.phone,Status:m.status,Score:m.score||0,Created:new Date(m.createdAt).toLocaleDateString()})))}catch(s){console.error(o.red("\u2716 Failed to fetch leads")),console.error(o.dim(s.message))}});te.command("pipelines").description("List all CRM pipelines").action(async(n,e)=>{let t=e.parent.parent.opts(),a=y(t);try{console.log(o.cyan("Fetching pipelines..."));let s=await a.crm.pipelines.list(),r=s.data||s||[];if(r.length===0){console.log(o.yellow("No pipelines found."));return}console.table(r.map(l=>({ID:l.id||l._id,Name:l.name,Default:l.isDefault?"Yes":"No",Stages:l.stages?.length||0})))}catch(s){console.error(o.red("\u2716 Failed to fetch pipelines")),console.error(o.dim(s.message))}});var me=d.command("analytics").description("Business Intelligence Analytics");me.command("overview").description("Get high-level CRM KPIs").option("-r, --range <range>","Date range (e.g., 24h, 7d, 30d, 365d)","30d").action(async(n,e)=>{let t=e.parent.parent.opts(),a=y(t);try{console.log(o.cyan(`Fetching overview metrics for last ${n.range}...`));let s=await a.crm.analytics.overview({range:n.range}),r=s.data||s;console.log(`
|
|
3
3
|
${o.bold("OVERVIEW KPIs:")}`),console.log(`Total Leads: ${o.green(r.totalLeads||0)}`),console.log(`Open Value: ${o.yellow(`$${(r.openValue||0).toLocaleString()}`)}`),console.log(`Won Revenue: ${o.green(`$${(r.wonRevenue||0).toLocaleString()}`)}`),console.log(`Avg Score: ${o.blue(r.avgScore?.toFixed(1)||0)}`),console.log(`Conversion: ${o.magenta(`${(r.conversionRate||0).toFixed(2)}%`)}
|
|
4
4
|
`)}catch(s){console.error(o.red("\u2716 Failed to fetch analytics overview")),console.error(o.dim(s.message))}});var ge=d.command("webhooks").description("Webhook utility tools");ge.command("verify").description("Verify a cryptographic webhook signature").argument("<payload>","The raw request body string").argument("<signature>","The 'x-ecodrix-signature' header value").argument("<secret>","Your webhook signing secret").action(async(n,e,t,a,s)=>{let r=s.parent.parent.opts(),l=y(r);try{await l.webhooks.constructEvent(n,e,t),console.log(o.green("\u2714 Signature is VALID"))}catch(g){console.error(o.red("\u2716 Error during verification")),console.error(o.dim(g.message))}});d.command("shell").alias("repl").description("Start an interactive SDK shell").action(async(n,e)=>{let t=e.parent.opts(),a=y(t);console.log(o.magenta(o.bold(`
|
|
5
5
|
Welcome to the Erix Interactive Shell`))),console.log(o.dim(`SDK Version: ${ee}`)),console.log(o.dim(`The 'ecod' client is pre-initialized and ready.
|
package/dist/index.d.ts
CHANGED
|
@@ -1603,15 +1603,25 @@ declare class Media extends APIResource {
|
|
|
1603
1603
|
*/
|
|
1604
1604
|
createFolder(name: string): Promise<unknown>;
|
|
1605
1605
|
/**
|
|
1606
|
-
* List files within a
|
|
1606
|
+
* List files within a folder, with optional date / search filtering.
|
|
1607
1607
|
*
|
|
1608
|
-
* @param folder - The folder
|
|
1609
|
-
*
|
|
1610
|
-
*
|
|
1608
|
+
* @param folder - The folder name to list, **or `"*"` to fetch all folders**
|
|
1609
|
+
* for the tenant in a single call (returns a merged flat list with a
|
|
1610
|
+
* `folder` field on each file so callers can group/filter client-side).
|
|
1611
|
+
* @param params - Optional `year`, `month`, and keyword search `q` filters.
|
|
1612
|
+
* @returns `{ data: { files, count, totalSizeBytes } }`.
|
|
1611
1613
|
*
|
|
1612
|
-
* @example
|
|
1614
|
+
* @example Single folder
|
|
1615
|
+
* ```typescript
|
|
1616
|
+
* const { data } = await ecod.media.list("invoices", { q: "contract" });
|
|
1617
|
+
* // data.files → files only from the "invoices" folder
|
|
1618
|
+
* ```
|
|
1619
|
+
*
|
|
1620
|
+
* @example All folders
|
|
1613
1621
|
* ```typescript
|
|
1614
|
-
* const { data
|
|
1622
|
+
* const { data } = await ecod.media.list("*");
|
|
1623
|
+
* // data.files → merged files from every folder the tenant has
|
|
1624
|
+
* // Each file has a `folder` field indicating its source folder
|
|
1615
1625
|
* ```
|
|
1616
1626
|
*/
|
|
1617
1627
|
list(folder: string, params?: {
|
|
@@ -2830,6 +2840,12 @@ declare class Ecodrix {
|
|
|
2830
2840
|
* @internal Socket.io client for real-time events.
|
|
2831
2841
|
*/
|
|
2832
2842
|
private readonly socket;
|
|
2843
|
+
/**
|
|
2844
|
+
* The tenant client code this SDK instance is scoped to.
|
|
2845
|
+
* Useful for components that need to read the clientCode back
|
|
2846
|
+
* from a context-provided SDK instance.
|
|
2847
|
+
*/
|
|
2848
|
+
readonly clientCode: string | undefined;
|
|
2833
2849
|
/** WhatsApp messaging and conversation management. */
|
|
2834
2850
|
readonly whatsapp: WhatsApp;
|
|
2835
2851
|
/** CRM resources — Leads and related sub-resources. */
|