@ecodrix/erix-api 1.4.0 → 1.4.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 CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import he from"repl";import{Command as Te}from"commander";import fe from"dotenv";import o from"picocolors";import de from"axios";import ce from"axios-retry";var z=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends z{status;code;constructor(e,t,a){super(e),this.name="APIError",this.status=t,this.code=a}},y=class extends u{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},f=class extends u{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var r=class{constructor(e){this.client=e}client;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){if(e.response){let t=e.response.status,a=e.response.data?.message||e.response.data?.error||"API Request Failed",s=e.response.data?.code;switch(t){case 401:throw new y(a);case 403:throw new y(a);case 429:throw new f(a);default:throw new u(a,t,s)}}throw new u(e.message||"Network Error")}};var b=class extends r{async listBlueprints(){return this.get("/api/agency/blueprints")}async createBlueprint(e){return this.post("/api/agency/blueprints",e)}async deployBlueprint(e){return this.post("/api/agency/blueprints/deploy",e)}async getPortfolioStats(e){return this.get(`/api/agency/portfolio/${e}/stats`)}async getPortfolioHealth(e){return this.get(`/api/agency/portfolio/${e}/health`)}async getUsage(e){return this.get(`/api/agency/usage/${e}`)}async listStaff(e){return this.get(`/api/agency/staff/${e}`)}async createStaff(e){return this.post("/api/agency/staff",e)}};var v=class extends r{async getProduct(e){return this.get(`/api/v1/checkout/products/${e}`)}async createSession(e){return this.post("/api/v1/checkout/session",e)}async applyCoupon(e){return this.post("/api/v1/checkout/coupon",e)}async verify(e){return this.post("/api/v1/checkout/verify",e)}async createOrder(e){return this.post("/api/v1/checkout/order",e)}};var P=class extends r{async list(){return this.get("/api/saas/cors")}async create(e){return this.post("/api/saas/cors",e)}async update(e,t){return this.patch(`/api/saas/cors/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/cors/${e}`)}};var X=class extends r{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}`)}},x=class extends r{notes;constructor(e){super(e),this.notes=new X(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 w=class extends r{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 C=class extends r{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 $=class extends r{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/automations/webhook-event",{ruleId:e,eventName:t,payload:a})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}};var R=class extends r{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(i=>({key:`metadata.extra.${i.name}`,label:i.label||i.name,type:i.type||"string",required:!!i.required,options:i.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 c=e.slice(s,s+t).map(g=>this.create(g)),m=await Promise.allSettled(c);for(let g of m)if(g.status==="fulfilled")a.push(g.value);else throw g.reason}return a}async import(e){return this.post("/api/crm/leads/import",{leads:e})}async bulkUpsert(e){return this.import(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}),i=Array.isArray(s.data)?s.data:s||[];if(i.length===0){a=!1;break}for(let c of i)yield c;s.pagination&&t<s.pagination.pages||!s.pagination&&i.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 byStage(e,t,a={}){return this.get(`/api/crm/pipelines/${e}/stages/${t}/leads`,{params:a})}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 bulkArchive(e){return this.patch("/api/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/api/crm/leads",{data:{ids:e}})}async archive(e){return this.patch(`/api/crm/leads/${e}/archive`,{})}};var k=class extends r{async capture(e){return this.post("/api/crm/payments/capture",e)}};var A=class extends r{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 checkInUse(e){return this.get(`/api/crm/pipelines/${e}/in-use`)}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 I=class extends r{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 S=class extends r{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 E=class{leads;pipelines;activities;analytics;automations;sequences;scoring;payments;automationDashboard;constructor(e){this.leads=new R(e),this.pipelines=new A(e),this.activities=new x(e),this.analytics=new w(e),this.automations=new $(e),this.sequences=new S(e),this.scoring=new I(e),this.payments=new k(e),this.automationDashboard=new C(e)}};var D=class extends r{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})}async listTemplates(e){return this.get("/api/saas/marketing/mail/templates",{params:e})}async getTemplate(e){return this.get(`/api/saas/marketing/mail/templates/${e}`)}async createTemplate(e){return this.post("/api/saas/marketing/mail/templates",e)}async updateTemplate(e,t){return this.put(`/api/saas/marketing/mail/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/api/saas/marketing/mail/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/api/saas/marketing/mail/templates/${e}/preview`,t)}};var L=class extends r{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/crm/events/emit",e)}};var q=class extends r{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 O=class extends r{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 Z=class extends r{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})}},ee=class extends r{async list(e){return this.get("/api/saas/marketing/emails/campaigns",{params:e})}async stats(e){return this.get(`/api/saas/marketing/emails/campaigns/${e}/analytics`)}},te=class extends r{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},M=class extends r{emails;campaigns;whatsapp;constructor(e){super(e),this.emails=new Z(e),this.campaigns=new ee(e),this.whatsapp=new te(e)}};import ue from"axios";var N=class extends r{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 aiDescribe(e){return this.post("/api/saas/storage/ai/describe",{key:e})}async upload(e,t){let a=await this.post("/api/saas/storage/upload-url",t),{uploadUrl:s,key:i}=a.data;await ue.put(s,e,{headers:{"Content-Type":t.contentType}});let c=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:i,sizeBytes:c})}};var U=class extends r{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 _=class extends r{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 F=class extends r{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 se=class extends r{async list(){return this.get("/api/clients")}async getCountAndGenerateCode(){return this.get("/api/clients/count")}async retrieve(e){return this.get(`/api/clients/${e}`)}async getApiKey(e){return this.get(`/api/clients/${e}/api-key`)}async rotateApiKey(e){return this.post(`/api/clients/${e}/api-key`,{})}async create(e){return this.post("/api/clients",e)}async getConfig(e){return this.get(`/api/clients/${e}/config`)}async updateConfig(e,t){return this.patch(`/api/clients/${e}/config`,t)}async getConnections(e){return this.get(`/api/clients/${e}/connections`)}async getConnectProviders(e){return this.get(`/api/clients/${e}/connections/providers`)}async connectProvider(e,t,a){return this.post(`/api/clients/${e}/connections/${t}/connect`,a)}async configureProvider(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/configure`,a)}async disconnectProvider(e,t){return this.post(`/api/clients/${e}/connections/${t}/disconnect`,{})}async setConnectionAccess(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/access`,a)}async getDataSource(e){return this.get(`/api/clients/${e}/datasource`)}async manageDataSource(e,t){return this.post(`/api/clients/${e}/datasource`,t)}async updateIdentity(e,t){return this.patch(`/api/clients/${e}/identity`,t)}async googleReauth(e,t={}){return this.post(`/api/clients/${e}/google/reauth`,t)}async delete(e){return this.deleteRequest(`/api/clients/${e}`)}},ae=class extends r{async list(){return this.get("/api/services/blogs")}},ne=class extends r{async add(e){return this.post("/api/services/add-lead",e)}},B=class extends r{clients;blogs;globalLeads;constructor(e){super(e),this.clients=new se(e),this.blogs=new ae(e),this.globalLeads=new ne(e)}};var re=class extends r{async getConfig(){return this.get("/api/settings/email")}async switchProvider(e){return this.post("/api/settings/email/provider",{provider:e})}async saveSmtp(e){return this.post("/api/settings/email/smtp",e)}async initDomainVerification(e){return this.post("/api/settings/email/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/api/settings/email/ses/config",e)}async checkSesVerification(){return this.get("/api/settings/email/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/api/settings/email/ses/domain")}async sendTest(e){return this.post("/api/settings/email/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/api/settings/email/advanced",e)}async getHealth(){return this.get("/api/settings/email/health")}async fixDmarc(){return this.post("/api/settings/email/ses/fix-dmarc",{})}async listProviders(){return this.get("/api/settings/email/providers")}},K=class extends r{email;constructor(e){super(e),this.email=new re(e)}};var ie=class extends r{async create(e){return this.post("/api/saas/storage/folders",{name:e})}async delete(e){return this.deleteRequest(`/api/saas/storage/folders/${encodeURIComponent(e)}`)}},oe=class extends r{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}})}},V=class extends r{folders;files;constructor(e){super(e),this.folders=new ie(e),this.files=new oe(e)}async usage(){return this.get("/api/saas/storage/usage")}};var T=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},H=class{async constructEvent(e,t,a){if(!t)throw new T("No webhook signature provided");let s=Array.isArray(t)?t[0]:t;s.startsWith("sha256=")&&(s=s.slice(7));try{let i=await import("crypto"),m=i.createHmac("sha256",a).update(e).digest("hex");if(!i.timingSafeEqual(Buffer.from(m),Buffer.from(s)))throw new T("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(i){throw i instanceof T?i:new T(`Webhook payload parsing failed: ${i.message}`)}}};var W=class extends r{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 j=class extends r{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 Q=class extends r{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 J=class extends r{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 i of a)if(i.text){let c=i.text.match(/{{(\d+)}}/g);if(c)for(let m of c){let g=m.replace(/{{|}}/g,"");s.push({key:`var_${g}`,label:`${i.type} Var {{${g}}}`,type:"string",required:!0,group:i.type,description:`Variable placeholder in template ${i.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 Y=class extends r{messages;conversations;broadcasts;templates;constructor(e){super(e),this.messages=new Q(e),this.conversations=new j(e),this.broadcasts=new W(e),this.templates=new J(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 ye="https://api.ecodrix.com",G=class{client;socket=null;socketPromise=null;socketQueue=[];clientCode;whatsapp;crm;media;meet;notifications;email;logs;events;webhooks;storage;marketing;health;queue;agency;services;settings;cors;checkout;constructor(e){if(!e.apiKey)throw new y("API Key is required");this.clientCode=e.clientCode?.toUpperCase();let t=e.baseUrl??ye,a=e.socketUrl||t,s=typeof window<"u"&&typeof window.document<"u",i=s?"browser":typeof process<"u"?`node ${process.version}`:"unknown",c=s?globalThis.navigator?.userAgent||"browser":typeof process<"u"?process.platform:"unknown",m={"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:i,os:c})};if(e.coreApiKey&&(m["x-core-api-key"]=e.coreApiKey),this.client=de.create({baseURL:t,headers:m}),ce(this.client,{retries:3,retryDelay:ce.exponentialDelay,retryCondition:g=>ce.isNetworkOrIdempotentRequestError(g)||g.response?.status===429,onRetry:(g,me,pe)=>{typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${g}/3): ${pe.method?.toUpperCase()} ${pe.url}. Reason: ${me.message}`)}}),this.whatsapp=new Y(this.client),this.crm=new E(this.client),this.media=new N(this.client),this.meet=new U(this.client),this.notifications=new _(this.client),this.email=new D(this.client),this.logs=new O(this.client),this.events=new L(this.client),this.webhooks=new H,this.storage=new V(this.client),this.marketing=new M(this.client),this.health=new q(this.client),this.queue=new F(this.client),this.agency=new b(this.client),this.services=new B(this.client),this.settings=new K(this.client),this.cors=new P(this.client),this.checkout=new v(this.client),this.initSocket(a,e.apiKey,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)}}initSocket(e,t,a){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:s})=>{this.socket=s(e,{extraHeaders:{"x-api-key":t,"x-client-code":a?.toUpperCase()||""}}),this.setupSocket(a);for(let{type:i,args:c}of this.socketQueue)i==="joinRoom"?this.socket.emit("join-room",c[0]):i==="leaveRoom"?this.socket.emit("leave-room",c[0]):i==="on"?this.socket.on(c[0],c[1]):i==="off"?this.socket.off(c[0],c[1]):i==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){this.socket?this.socket.emit("join-room",e):this.socketQueue.push({type:"joinRoom",args:[e]})}leaveRoom(e){this.socket?this.socket.emit("leave-room",e):this.socketQueue.push({type:"leaveRoom",args:[e]})}setupSocket(e){this.socket&&this.socket.on("connect",()=>{e&&this.socket.emit("join-room",e.toUpperCase())})}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}disconnect(){this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[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(i){throw i.response?new u(i.response.data?.message||i.response.data?.error||"Raw Execution Failed",i.response.status,i.response.data?.code):new u(i.message||"Network Error")}}};fe.config();var le="1.4.0";var be="Official Isomorphic SDK for the ECODrIx platform. Native support for WhatsApp, CRM, Storage, and Meetings across TS, JS, Python, and Java.",d=new Te;d.name("erix").description(be).version(le);function h(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 G({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=h(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 ve=d.command("whatsapp").description("WhatsApp Business API operations");ve.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(),i=h(s);try{let c=JSON.parse(t.vars);console.log(o.cyan(`Sending template '${e}' to ${n}...`));let m=await i.whatsapp.messages.sendTemplate({to:n,templateName:e,language:"en_US",variables:c});console.log(o.green("\u2714 Message sent successfully!")),console.log(o.dim(`ID: ${m?.id||"N/A"}`))}catch(c){console.error(o.red("\u2716 Failed to send message")),console.error(o.dim(c.message))}});var ge=d.command("crm").description("CRM and Lead management");ge.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=h(t);try{let s=Number.parseInt(n.limit);console.log(o.cyan(`Fetching last ${s} leads...`));let i={limit:s};n.status&&(i.status=n.status),n.pipeline&&(i.pipelineId=n.pipeline),n.search&&(i.search=n.search);let c=await a.crm.leads.list(i),m=Array.isArray(c.data)?c.data:Array.isArray(c)?c:[];if(m.length===0){console.log(o.yellow("No leads found."));return}console.table(m.map(g=>({ID:g.id||g._id,Name:`${g.firstName} ${g.lastName||""}`.trim(),Phone:g.phone,Status:g.status,Score:g.score||0,Created:new Date(g.createdAt).toLocaleDateString()})))}catch(s){console.error(o.red("\u2716 Failed to fetch leads")),console.error(o.dim(s.message))}});ge.command("pipelines").description("List all CRM pipelines").action(async(n,e)=>{let t=e.parent.parent.opts(),a=h(t);try{console.log(o.cyan("Fetching pipelines..."));let s=await a.crm.pipelines.list(),i=s.data||s||[];if(i.length===0){console.log(o.yellow("No pipelines found."));return}console.table(i.map(c=>({ID:c.id||c._id,Name:c.name,Default:c.isDefault?"Yes":"No",Stages:c.stages?.length||0})))}catch(s){console.error(o.red("\u2716 Failed to fetch pipelines")),console.error(o.dim(s.message))}});var Pe=d.command("analytics").description("Business Intelligence Analytics");Pe.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=h(t);try{console.log(o.cyan(`Fetching overview metrics for last ${n.range}...`));let s=await a.crm.analytics.overview({range:n.range}),i=s.data||s;console.log(`
2
+ import Te from"repl";import{Command as fe}from"commander";import be from"dotenv";import o from"picocolors";import ye from"axios";import pe from"axios-retry";var X=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends X{status;code;constructor(e,t,a){super(e),this.name="APIError",this.status=t,this.code=a}},y=class extends u{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},f=class extends u{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var r=class{constructor(e){this.client=e}client;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){if(e.response){let t=e.response.status,a=e.response.data?.message||e.response.data?.error||"API Request Failed",s=e.response.data?.code;switch(t){case 401:throw new y(a);case 403:throw new y(a);case 429:throw new f(a);default:throw new u(a,t,s)}}throw new u(e.message||"Network Error")}};var b=class extends r{async listBlueprints(){return this.get("/api/agency/blueprints")}async createBlueprint(e){return this.post("/api/agency/blueprints",e)}async deployBlueprint(e){return this.post("/api/agency/blueprints/deploy",e)}async getPortfolioStats(e){return this.get(`/api/agency/portfolio/${e}/stats`)}async getPortfolioHealth(e){return this.get(`/api/agency/portfolio/${e}/health`)}async getUsage(e){return this.get(`/api/agency/usage/${e}`)}async listStaff(e){return this.get(`/api/agency/staff/${e}`)}async createStaff(e){return this.post("/api/agency/staff",e)}};var v=class extends r{async getProduct(e){return this.get(`/api/v1/checkout/products/${e}`)}async createSession(e){return this.post("/api/v1/checkout/session",e)}async applyCoupon(e){return this.post("/api/v1/checkout/coupon",e)}async verify(e){return this.post("/api/v1/checkout/verify",e)}async createOrder(e){return this.post("/api/v1/checkout/order",e)}};var P=class extends r{async providers(){return this.get("/api/connect/v1/providers")}async list(){return this.get("/api/connect/v1/connections")}async get_(e){return this.get(`/api/connect/v1/connections/${e}`)}async connect(e,t){return this.post(`/api/connect/v1/connections/${e}/connect`,t)}async configure(e,t){return this.put(`/api/connect/v1/connections/${e}/configure`,t)}async disconnect(e){return this.post(`/api/connect/v1/connections/${e}/disconnect`,{})}async reveal(e){return this.post(`/api/connect/v1/connections/${e}/reveal`,{})}async setAccess(e,t){return this.put(`/api/connect/v1/connections/${e}/access`,t)}};var x=class extends r{async list(){return this.get("/api/saas/cors")}async create(e){return this.post("/api/saas/cors",e)}async update(e,t){return this.patch(`/api/saas/cors/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/cors/${e}`)}};var Z=class extends r{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}`)}},w=class extends r{notes;constructor(e){super(e),this.notes=new Z(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 C=class extends r{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 $=class extends r{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 R=class extends r{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/automations/webhook-event",{ruleId:e,eventName:t,payload:a})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}};var k=class extends r{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(i=>({key:`metadata.extra.${i.name}`,label:i.label||i.name,type:i.type||"string",required:!!i.required,options:i.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 c=e.slice(s,s+t).map(g=>this.create(g)),m=await Promise.allSettled(c);for(let g of m)if(g.status==="fulfilled")a.push(g.value);else throw g.reason}return a}async import(e){return this.post("/api/crm/leads/import",{leads:e})}async bulkUpsert(e){return this.import(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}),i=Array.isArray(s.data)?s.data:s||[];if(i.length===0){a=!1;break}for(let c of i)yield c;s.pagination&&t<s.pagination.pages||!s.pagination&&i.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 byStage(e,t,a={}){return this.get(`/api/crm/pipelines/${e}/stages/${t}/leads`,{params:a})}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 bulkArchive(e){return this.patch("/api/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/api/crm/leads",{data:{ids:e}})}async archive(e){return this.patch(`/api/crm/leads/${e}/archive`,{})}};var A=class extends r{async capture(e){return this.post("/api/crm/payments/capture",e)}};var I=class extends r{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 checkInUse(e){return this.get(`/api/crm/pipelines/${e}/in-use`)}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 S=class extends r{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 E=class extends r{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 D=class{leads;pipelines;activities;analytics;automations;sequences;scoring;payments;automationDashboard;constructor(e){this.leads=new k(e),this.pipelines=new I(e),this.activities=new w(e),this.analytics=new C(e),this.automations=new R(e),this.sequences=new E(e),this.scoring=new S(e),this.payments=new A(e),this.automationDashboard=new $(e)}};var L=class extends r{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})}async listTemplates(e){return this.get("/api/saas/marketing/mail/templates",{params:e})}async getTemplate(e){return this.get(`/api/saas/marketing/mail/templates/${e}`)}async createTemplate(e){return this.post("/api/saas/marketing/mail/templates",e)}async updateTemplate(e,t){return this.put(`/api/saas/marketing/mail/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/api/saas/marketing/mail/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/api/saas/marketing/mail/templates/${e}/preview`,t)}};var q=class extends r{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/crm/events/emit",e)}};var O=class extends r{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 M=class extends r{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 ee=class extends r{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})}},te=class extends r{async list(e){return this.get("/api/saas/marketing/emails/campaigns",{params:e})}async stats(e){return this.get(`/api/saas/marketing/emails/campaigns/${e}/analytics`)}},se=class extends r{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},N=class extends r{emails;campaigns;whatsapp;constructor(e){super(e),this.emails=new ee(e),this.campaigns=new te(e),this.whatsapp=new se(e)}};import de from"axios";var U=class extends r{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 aiDescribe(e){return this.post("/api/saas/storage/ai/describe",{key:e})}async upload(e,t){let a=await this.post("/api/saas/storage/upload-url",t),{uploadUrl:s,key:i}=a.data;await de.put(s,e,{headers:{"Content-Type":t.contentType}});let c=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:i,sizeBytes:c})}};var _=class extends r{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 F=class extends r{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 B=class extends r{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 ae=class extends r{async list(){return this.get("/api/clients")}async getCountAndGenerateCode(){return this.get("/api/clients/count")}async retrieve(e){return this.get(`/api/clients/${e}`)}async getApiKey(e){return this.get(`/api/clients/${e}/api-key`)}async rotateApiKey(e){return this.post(`/api/clients/${e}/api-key`,{})}async create(e){return this.post("/api/clients",e)}async getConfig(e){return this.get(`/api/clients/${e}/config`)}async updateConfig(e,t){return this.patch(`/api/clients/${e}/config`,t)}async getConnections(e){return this.get(`/api/clients/${e}/connections`)}async getConnectProviders(e){return this.get(`/api/clients/${e}/connections/providers`)}async connectProvider(e,t,a){return this.post(`/api/clients/${e}/connections/${t}/connect`,a)}async configureProvider(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/configure`,a)}async disconnectProvider(e,t){return this.post(`/api/clients/${e}/connections/${t}/disconnect`,{})}async revealConnection(e,t){return this.post(`/api/clients/${e}/connections/${t}/reveal`,{})}async setConnectionAccess(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/access`,a)}async getDataSource(e){return this.get(`/api/clients/${e}/datasource`)}async manageDataSource(e,t){return this.post(`/api/clients/${e}/datasource`,t)}async updateIdentity(e,t){return this.patch(`/api/clients/${e}/identity`,t)}async googleReauth(e,t={}){return this.post(`/api/clients/${e}/google/reauth`,t)}async delete(e){return this.deleteRequest(`/api/clients/${e}`)}},ne=class extends r{async list(){return this.get("/api/services/blogs")}},re=class extends r{async add(e){return this.post("/api/services/add-lead",e)}},K=class extends r{clients;blogs;globalLeads;constructor(e){super(e),this.clients=new ae(e),this.blogs=new ne(e),this.globalLeads=new re(e)}};var ie=class extends r{async getConfig(){return this.get("/api/settings/email")}async switchProvider(e){return this.post("/api/settings/email/provider",{provider:e})}async saveSmtp(e){return this.post("/api/settings/email/smtp",e)}async initDomainVerification(e){return this.post("/api/settings/email/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/api/settings/email/ses/config",e)}async checkSesVerification(){return this.get("/api/settings/email/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/api/settings/email/ses/domain")}async sendTest(e){return this.post("/api/settings/email/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/api/settings/email/advanced",e)}async getHealth(){return this.get("/api/settings/email/health")}async fixDmarc(){return this.post("/api/settings/email/ses/fix-dmarc",{})}async listProviders(){return this.get("/api/settings/email/providers")}},V=class extends r{email;constructor(e){super(e),this.email=new ie(e)}};var oe=class extends r{async create(e){return this.post("/api/saas/storage/folders",{name:e})}async delete(e){return this.deleteRequest(`/api/saas/storage/folders/${encodeURIComponent(e)}`)}},ce=class extends r{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}})}},H=class extends r{folders;files;constructor(e){super(e),this.folders=new oe(e),this.files=new ce(e)}async usage(){return this.get("/api/saas/storage/usage")}};var T=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},W=class{async constructEvent(e,t,a){if(!t)throw new T("No webhook signature provided");let s=Array.isArray(t)?t[0]:t;s.startsWith("sha256=")&&(s=s.slice(7));try{let i=await import("crypto"),m=i.createHmac("sha256",a).update(e).digest("hex");if(!i.timingSafeEqual(Buffer.from(m),Buffer.from(s)))throw new T("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(i){throw i instanceof T?i:new T(`Webhook payload parsing failed: ${i.message}`)}}};var j=class extends r{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 Q=class extends r{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 J=class extends r{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 Y=class extends r{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 i of a)if(i.text){let c=i.text.match(/{{(\d+)}}/g);if(c)for(let m of c){let g=m.replace(/{{|}}/g,"");s.push({key:`var_${g}`,label:`${i.type} Var {{${g}}}`,type:"string",required:!0,group:i.type,description:`Variable placeholder in template ${i.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 G=class extends r{messages;conversations;broadcasts;templates;constructor(e){super(e),this.messages=new J(e),this.conversations=new Q(e),this.broadcasts=new j(e),this.templates=new Y(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 he="https://api.ecodrix.com",z=class{client;socket=null;socketPromise=null;socketQueue=[];clientCode;whatsapp;crm;media;meet;notifications;email;logs;events;webhooks;storage;marketing;health;queue;agency;services;settings;cors;checkout;connect;constructor(e){if(!e.apiKey)throw new y("API Key is required");this.clientCode=e.clientCode?.toUpperCase();let t=e.baseUrl??he,a=e.socketUrl||t,s=typeof window<"u"&&typeof window.document<"u",i=s?"browser":typeof process<"u"?`node ${process.version}`:"unknown",c=s?globalThis.navigator?.userAgent||"browser":typeof process<"u"?process.platform:"unknown",m={"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:i,os:c})};if(e.coreApiKey&&(m["x-core-api-key"]=e.coreApiKey),this.client=ye.create({baseURL:t,headers:m}),pe(this.client,{retries:3,retryDelay:pe.exponentialDelay,retryCondition:g=>pe.isNetworkOrIdempotentRequestError(g)||g.response?.status===429,onRetry:(g,ue,le)=>{typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${g}/3): ${le.method?.toUpperCase()} ${le.url}. Reason: ${ue.message}`)}}),this.whatsapp=new G(this.client),this.crm=new D(this.client),this.media=new U(this.client),this.meet=new _(this.client),this.notifications=new F(this.client),this.email=new L(this.client),this.logs=new M(this.client),this.events=new q(this.client),this.webhooks=new W,this.storage=new H(this.client),this.marketing=new N(this.client),this.health=new O(this.client),this.queue=new B(this.client),this.agency=new b(this.client),this.services=new K(this.client),this.settings=new V(this.client),this.cors=new x(this.client),this.checkout=new v(this.client),this.connect=new P(this.client),this.initSocket(a,e.apiKey,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)}}initSocket(e,t,a){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:s})=>{this.socket=s(e,{extraHeaders:{"x-api-key":t,"x-client-code":a?.toUpperCase()||""}}),this.setupSocket(a);for(let{type:i,args:c}of this.socketQueue)i==="joinRoom"?this.socket.emit("join-room",c[0]):i==="leaveRoom"?this.socket.emit("leave-room",c[0]):i==="on"?this.socket.on(c[0],c[1]):i==="off"?this.socket.off(c[0],c[1]):i==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){this.socket?this.socket.emit("join-room",e):this.socketQueue.push({type:"joinRoom",args:[e]})}leaveRoom(e){this.socket?this.socket.emit("leave-room",e):this.socketQueue.push({type:"leaveRoom",args:[e]})}setupSocket(e){this.socket&&this.socket.on("connect",()=>{e&&this.socket.emit("join-room",e.toUpperCase())})}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}disconnect(){this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[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(i){throw i.response?new u(i.response.data?.message||i.response.data?.error||"Raw Execution Failed",i.response.status,i.response.data?.code):new u(i.message||"Network Error")}}};be.config();var ge="1.4.3";var ve="Official Isomorphic SDK for the ECODrIx platform. Native support for WhatsApp, CRM, Storage, and Meetings across TS, JS, Python, and Java.",d=new fe;d.name("erix").description(ve).version(ge);function h(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 z({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=h(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 Pe=d.command("whatsapp").description("WhatsApp Business API operations");Pe.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(),i=h(s);try{let c=JSON.parse(t.vars);console.log(o.cyan(`Sending template '${e}' to ${n}...`));let m=await i.whatsapp.messages.sendTemplate({to:n,templateName:e,language:"en_US",variables:c});console.log(o.green("\u2714 Message sent successfully!")),console.log(o.dim(`ID: ${m?.id||"N/A"}`))}catch(c){console.error(o.red("\u2716 Failed to send message")),console.error(o.dim(c.message))}});var me=d.command("crm").description("CRM and Lead management");me.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=h(t);try{let s=Number.parseInt(n.limit);console.log(o.cyan(`Fetching last ${s} leads...`));let i={limit:s};n.status&&(i.status=n.status),n.pipeline&&(i.pipelineId=n.pipeline),n.search&&(i.search=n.search);let c=await a.crm.leads.list(i),m=Array.isArray(c.data)?c.data:Array.isArray(c)?c:[];if(m.length===0){console.log(o.yellow("No leads found."));return}console.table(m.map(g=>({ID:g.id||g._id,Name:`${g.firstName} ${g.lastName||""}`.trim(),Phone:g.phone,Status:g.status,Score:g.score||0,Created:new Date(g.createdAt).toLocaleDateString()})))}catch(s){console.error(o.red("\u2716 Failed to fetch leads")),console.error(o.dim(s.message))}});me.command("pipelines").description("List all CRM pipelines").action(async(n,e)=>{let t=e.parent.parent.opts(),a=h(t);try{console.log(o.cyan("Fetching pipelines..."));let s=await a.crm.pipelines.list(),i=s.data||s||[];if(i.length===0){console.log(o.yellow("No pipelines found."));return}console.table(i.map(c=>({ID:c.id||c._id,Name:c.name,Default:c.isDefault?"Yes":"No",Stages:c.stages?.length||0})))}catch(s){console.error(o.red("\u2716 Failed to fetch pipelines")),console.error(o.dim(s.message))}});var xe=d.command("analytics").description("Business Intelligence Analytics");xe.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=h(t);try{console.log(o.cyan(`Fetching overview metrics for last ${n.range}...`));let s=await a.crm.analytics.overview({range:n.range}),i=s.data||s;console.log(`
3
3
  ${o.bold("OVERVIEW KPIs:")}`),console.log(`Total Leads: ${o.green(i.totalLeads||0)}`),console.log(`Open Value: ${o.yellow(`$${(i.openValue||0).toLocaleString()}`)}`),console.log(`Won Revenue: ${o.green(`$${(i.wonRevenue||0).toLocaleString()}`)}`),console.log(`Avg Score: ${o.blue(i.avgScore?.toFixed(1)||0)}`),console.log(`Conversion: ${o.magenta(`${(i.conversionRate||0).toFixed(2)}%`)}
4
- `)}catch(s){console.error(o.red("\u2716 Failed to fetch analytics overview")),console.error(o.dim(s.message))}});var xe=d.command("webhooks").description("Webhook utility tools");xe.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 i=s.parent.parent.opts(),c=h(i);try{await c.webhooks.constructEvent(n,e,t),console.log(o.green("\u2714 Signature is VALID"))}catch(m){console.error(o.red("\u2716 Error during verification")),console.error(o.dim(m.message))}});d.command("shell").alias("repl").description("Start an interactive SDK shell").action(async(n,e)=>{let t=e.parent.opts(),a=h(t);console.log(o.magenta(o.bold(`
5
- Welcome to the Erix Interactive Shell`))),console.log(o.dim(`SDK Version: ${le}`)),console.log(o.dim(`The 'ecod' client is pre-initialized and ready.
6
- `));let s=he.start({prompt:o.cyan("erix > "),useColors:!0});s.context.ecod=a,s.context.whatsapp=a.whatsapp,s.context.crm=a.crm,s.context.meet=a.meet,s.context.media=a.media,s.on("exit",()=>{console.log(o.yellow(`
4
+ `)}catch(s){console.error(o.red("\u2716 Failed to fetch analytics overview")),console.error(o.dim(s.message))}});var we=d.command("webhooks").description("Webhook utility tools");we.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 i=s.parent.parent.opts(),c=h(i);try{await c.webhooks.constructEvent(n,e,t),console.log(o.green("\u2714 Signature is VALID"))}catch(m){console.error(o.red("\u2716 Error during verification")),console.error(o.dim(m.message))}});d.command("shell").alias("repl").description("Start an interactive SDK shell").action(async(n,e)=>{let t=e.parent.opts(),a=h(t);console.log(o.magenta(o.bold(`
5
+ Welcome to the Erix Interactive Shell`))),console.log(o.dim(`SDK Version: ${ge}`)),console.log(o.dim(`The 'ecod' client is pre-initialized and ready.
6
+ `));let s=Te.start({prompt:o.cyan("erix > "),useColors:!0});s.context.ecod=a,s.context.whatsapp=a.whatsapp,s.context.crm=a.crm,s.context.meet=a.meet,s.context.media=a.media,s.on("exit",()=>{console.log(o.yellow(`
7
7
  Goodbye!`)),process.exit(0)})});d.command("completion").description("Generate Bash auto-completion script").action(()=>{console.log(`
8
8
  # Erix Bash Completion
9
9
  _erix_completions() {
@@ -1 +1 @@
1
- "use strict";var $e=Object.create;var k=Object.defineProperty,Ie=Object.defineProperties,Ee=Object.getOwnPropertyDescriptor,Se=Object.getOwnPropertyDescriptors,qe=Object.getOwnPropertyNames,Pe=Object.getOwnPropertySymbols,Le=Object.getPrototypeOf,ve=Object.prototype.hasOwnProperty,De=Object.prototype.propertyIsEnumerable;var Me=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var ie=(s,e,t)=>e in s?k(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,b=(s,e)=>{for(var t in e||(e={}))ve.call(e,t)&&ie(s,t,e[t]);if(Pe)for(var t of Pe(e))De.call(e,t)&&ie(s,t,e[t]);return s},w=(s,e)=>Ie(s,Se(e));var Ue=(s,e)=>{for(var t in e)k(s,t,{get:e[t],enumerable:!0})},we=(s,e,t,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of qe(e))!ve.call(s,n)&&n!==t&&k(s,n,{get:()=>e[n],enumerable:!(a=Ee(e,n))||a.enumerable});return s};var C=(s,e,t)=>(t=s!=null?$e(Le(s)):{},we(e||!s||!s.__esModule?k(t,"default",{value:s,enumerable:!0}):t,s)),Oe=s=>we(k({},"__esModule",{value:!0}),s);var i=(s,e,t)=>ie(s,typeof e!="symbol"?e+"":e,t);var oe=function(s,e){this[0]=s,this[1]=e},Re=(s,e,t)=>{var a=(g,l,h,d)=>{try{var P=t[g](l),T=(l=P.value)instanceof oe,x=P.done;Promise.resolve(T?l[0]:l).then(m=>T?a(g==="return"?g:"next",l[1]?{done:m.done,value:m.value}:m,h,d):h({value:m,done:x})).catch(m=>a("throw",m,h,d))}catch(m){d(m)}},n=(g,l,h,d)=>c[g]=P=>(l=new Promise((T,x,m)=>(m=()=>a(g,P,T,x),o?o.then(m):m())),d=()=>o===h&&(o=0),o=h=l.then(d,d),l),o,c={};return t=t.apply(s,e),c[Me("asyncIterator")]=()=>c,n("next"),n("throw"),n("return"),c};var Ke={};Ue(Ke,{APIError:()=>u,AuthenticationError:()=>y,ECODrIx:()=>v,ECODrIxAPI:()=>v,ERROR_RETRY_CONFIG:()=>fe,EcodrixError:()=>A,HTTP_STATUS_ERROR_MAP:()=>Ae,RateLimitError:()=>f,default:()=>je,getErrorDetails:()=>Be,getRetryConfig:()=>He,handleAPIError:()=>_e,isAPIError:()=>Fe});module.exports=Oe(Ke);var Ce=C(require("axios"),1),re=C(require("axios-retry"),1);var A=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends A{constructor(t,a,n){super(t);i(this,"status");i(this,"code");this.name="APIError",this.status=a,this.code=n}},y=class extends u{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},f=class extends u{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var r=class{constructor(e){i(this,"client",e)}async post(e,t,a){try{let n=this.buildConfig(a);return(await this.client.post(e,t,n)).data}catch(n){this.handleError(n)}}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 n=this.buildConfig(a);return(await this.client.patch(e,t,n)).data}catch(n){this.handleError(n)}}async put(e,t,a){try{let n=this.buildConfig(a);return(await this.client.put(e,t,n)).data}catch(n){this.handleError(n)}}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=b({},e);return e.idempotencyKey&&(t.headers=w(b({},t.headers),{"Idempotency-Key":e.idempotencyKey})),t}handleError(e){var t,a,n;if(e.response){let o=e.response.status,c=((t=e.response.data)==null?void 0:t.message)||((a=e.response.data)==null?void 0:a.error)||"API Request Failed",g=(n=e.response.data)==null?void 0:n.code;switch(o){case 401:throw new y(c);case 403:throw new y(c);case 429:throw new f(c);default:throw new u(c,o,g)}}throw new u(e.message||"Network Error")}};var $=class extends r{async listBlueprints(){return this.get("/api/agency/blueprints")}async createBlueprint(e){return this.post("/api/agency/blueprints",e)}async deployBlueprint(e){return this.post("/api/agency/blueprints/deploy",e)}async getPortfolioStats(e){return this.get(`/api/agency/portfolio/${e}/stats`)}async getPortfolioHealth(e){return this.get(`/api/agency/portfolio/${e}/health`)}async getUsage(e){return this.get(`/api/agency/usage/${e}`)}async listStaff(e){return this.get(`/api/agency/staff/${e}`)}async createStaff(e){return this.post("/api/agency/staff",e)}};var I=class extends r{async getProduct(e){return this.get(`/api/v1/checkout/products/${e}`)}async createSession(e){return this.post("/api/v1/checkout/session",e)}async applyCoupon(e){return this.post("/api/v1/checkout/coupon",e)}async verify(e){return this.post("/api/v1/checkout/verify",e)}async createOrder(e){return this.post("/api/v1/checkout/order",e)}};var E=class extends r{async list(){return this.get("/api/saas/cors")}async create(e){return this.post("/api/saas/cors",e)}async update(e,t){return this.patch(`/api/saas/cors/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/cors/${e}`)}};var ce=class extends r{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}`)}},S=class extends r{constructor(t){super(t);i(this,"notes");this.notes=new ce(t)}async timeline(t,a){return this.get(`/api/crm/leads/${t}/timeline`,{params:a})}async list(t,a){return this.get(`/api/crm/leads/${t}/activities`,{params:b({},a)})}async log(t){return this.post(`/api/crm/leads/${t.leadId}/activities`,t)}async logCall(t,a){return this.post(`/api/crm/leads/${t}/calls`,a)}};var q=class extends r{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 L=class extends r{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 D=class extends r{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/automations/webhook-event",{ruleId:e,eventName:t,payload:a})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}};var M=class extends r{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}],n=t.map(o=>({key:`metadata.extra.${o.name}`,label:o.label||o.name,type:o.type||"string",required:!!o.required,options:o.options,group:"Custom Fields"}));return{name:"Lead",fields:[...a,...n],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 n=0;n<e.length;n+=t){let c=e.slice(n,n+t).map(l=>this.create(l)),g=await Promise.allSettled(c);for(let l of g)if(l.status==="fulfilled")a.push(l.value);else throw l.reason}return a}async import(e){return this.post("/api/crm/leads/import",{leads:e})}async bulkUpsert(e){return this.import(e)}async list(e){let t=b({},e);return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/api/crm/leads",{params:t})}listAutoPaging(e){return Re(this,null,function*(){let t=(e==null?void 0:e.page)||1,a=!0;for(;a;){let n=yield new oe(this.list(w(b({},e),{page:t}))),o=Array.isArray(n.data)?n.data:n||[];if(o.length===0){a=!1;break}for(let c of o)yield c;n.pagination&&t<n.pagination.pages||!n.pagination&&o.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 byStage(e,t,a={}){return this.get(`/api/crm/pipelines/${e}/stages/${t}/leads`,{params:a})}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 bulkArchive(e){return this.patch("/api/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/api/crm/leads",{data:{ids:e}})}async archive(e){return this.patch(`/api/crm/leads/${e}/archive`,{})}};var U=class extends r{async capture(e){return this.post("/api/crm/payments/capture",e)}};var O=class extends r{async list(){return this.get("/api/crm/pipelines")}async getStageManifest(e){var n,o;let t=await this.retrieve(e),a=Array.isArray((n=t.data)==null?void 0:n.stages)?t.data.stages:[];return{name:`Pipeline: ${((o=t.data)==null?void 0:o.name)||e}`,fields:a.map(c=>({key:c._id,label:c.name,type:"string",required:!0,options:[{label:c.name,value:c._id}],group:"Stages",uiHints:{color:c.color||"#cbd5e1",probability:c.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 checkInUse(e){return this.get(`/api/crm/pipelines/${e}/in-use`)}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 N=class extends r{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 _=class extends r{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 F=class{constructor(e){i(this,"leads");i(this,"pipelines");i(this,"activities");i(this,"analytics");i(this,"automations");i(this,"sequences");i(this,"scoring");i(this,"payments");i(this,"automationDashboard");this.leads=new M(e),this.pipelines=new O(e),this.activities=new S(e),this.analytics=new q(e),this.automations=new D(e),this.sequences=new _(e),this.scoring=new N(e),this.payments=new U(e),this.automationDashboard=new L(e)}};var B=class extends r{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})}async listTemplates(e){return this.get("/api/saas/marketing/mail/templates",{params:e})}async getTemplate(e){return this.get(`/api/saas/marketing/mail/templates/${e}`)}async createTemplate(e){return this.post("/api/saas/marketing/mail/templates",e)}async updateTemplate(e,t){return this.put(`/api/saas/marketing/mail/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/api/saas/marketing/mail/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/api/saas/marketing/mail/templates/${e}/preview`,t)}};var H=class extends r{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/crm/events/emit",e)}};var j=class extends r{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 K=class extends r{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 pe=class extends r{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})}},le=class extends r{async list(e){return this.get("/api/saas/marketing/emails/campaigns",{params:e})}async stats(e){return this.get(`/api/saas/marketing/emails/campaigns/${e}/analytics`)}},ge=class extends r{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},V=class extends r{constructor(t){super(t);i(this,"emails");i(this,"campaigns");i(this,"whatsapp");this.emails=new pe(t),this.campaigns=new le(t),this.whatsapp=new ge(t)}};var ke=C(require("axios"),1);var Q=class extends r{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 aiDescribe(e){return this.post("/api/saas/storage/ai/describe",{key:e})}async upload(e,t){let a=await this.post("/api/saas/storage/upload-url",t),{uploadUrl:n,key:o}=a.data;await ke.default.put(n,e,{headers:{"Content-Type":t.contentType}});let c=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:o,sizeBytes:c})}};var J=class extends r{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 W=class extends r{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 z=class extends r{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 ue=class extends r{async list(){return this.get("/api/clients")}async getCountAndGenerateCode(){return this.get("/api/clients/count")}async retrieve(e){return this.get(`/api/clients/${e}`)}async getApiKey(e){return this.get(`/api/clients/${e}/api-key`)}async rotateApiKey(e){return this.post(`/api/clients/${e}/api-key`,{})}async create(e){return this.post("/api/clients",e)}async getConfig(e){return this.get(`/api/clients/${e}/config`)}async updateConfig(e,t){return this.patch(`/api/clients/${e}/config`,t)}async getConnections(e){return this.get(`/api/clients/${e}/connections`)}async getConnectProviders(e){return this.get(`/api/clients/${e}/connections/providers`)}async connectProvider(e,t,a){return this.post(`/api/clients/${e}/connections/${t}/connect`,a)}async configureProvider(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/configure`,a)}async disconnectProvider(e,t){return this.post(`/api/clients/${e}/connections/${t}/disconnect`,{})}async setConnectionAccess(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/access`,a)}async getDataSource(e){return this.get(`/api/clients/${e}/datasource`)}async manageDataSource(e,t){return this.post(`/api/clients/${e}/datasource`,t)}async updateIdentity(e,t){return this.patch(`/api/clients/${e}/identity`,t)}async googleReauth(e,t={}){return this.post(`/api/clients/${e}/google/reauth`,t)}async delete(e){return this.deleteRequest(`/api/clients/${e}`)}},me=class extends r{async list(){return this.get("/api/services/blogs")}},ye=class extends r{async add(e){return this.post("/api/services/add-lead",e)}},G=class extends r{constructor(t){super(t);i(this,"clients");i(this,"blogs");i(this,"globalLeads");this.clients=new ue(t),this.blogs=new me(t),this.globalLeads=new ye(t)}};var de=class extends r{async getConfig(){return this.get("/api/settings/email")}async switchProvider(e){return this.post("/api/settings/email/provider",{provider:e})}async saveSmtp(e){return this.post("/api/settings/email/smtp",e)}async initDomainVerification(e){return this.post("/api/settings/email/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/api/settings/email/ses/config",e)}async checkSesVerification(){return this.get("/api/settings/email/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/api/settings/email/ses/domain")}async sendTest(e){return this.post("/api/settings/email/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/api/settings/email/advanced",e)}async getHealth(){return this.get("/api/settings/email/health")}async fixDmarc(){return this.post("/api/settings/email/ses/fix-dmarc",{})}async listProviders(){return this.get("/api/settings/email/providers")}},X=class extends r{constructor(t){super(t);i(this,"email");this.email=new de(t)}};var he=class extends r{async create(e){return this.post("/api/saas/storage/folders",{name:e})}async delete(e){return this.deleteRequest(`/api/saas/storage/folders/${encodeURIComponent(e)}`)}},Te=class extends r{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}})}},Y=class extends r{constructor(t){super(t);i(this,"folders");i(this,"files");this.folders=new he(t),this.files=new Te(t)}async usage(){return this.get("/api/saas/storage/usage")}};var R=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},Z=class{async constructEvent(e,t,a){if(!t)throw new R("No webhook signature provided");let n=Array.isArray(t)?t[0]:t;n.startsWith("sha256=")&&(n=n.slice(7));try{let o=await import("crypto"),g=o.createHmac("sha256",a).update(e).digest("hex");if(!o.timingSafeEqual(Buffer.from(g),Buffer.from(n)))throw new R("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(o){throw o instanceof R?o:new R(`Webhook payload parsing failed: ${o.message}`)}}};var ee=class extends r{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 te=class extends r{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 se=class extends r{async send(e){return this.post("/api/saas/chat/send",e)}async sendTemplate(e){return this.post("/api/saas/chat/send",w(b({},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 ae=class extends r{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){var o,c;let t=await this.retrieve(e),a=Array.isArray((o=t.data)==null?void 0:o.components)?t.data.components:[],n=[];for(let g of a)if(g.text){let l=g.text.match(/{{(\d+)}}/g);if(l)for(let h of l){let d=h.replace(/{{|}}/g,"");n.push({key:`var_${d}`,label:`${g.type} Var {{${d}}}`,type:"string",required:!0,group:g.type,description:`Variable placeholder in template ${g.type}`})}}return{name:`Template variables: ${((c=t.data)==null?void 0:c.name)||e}`,fields:n,uiHints:{icon:"Variables",primaryColor:"#059669"}}}async checkUsage(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/usage`)}};var ne=class extends r{constructor(t){super(t);i(this,"messages");i(this,"conversations");i(this,"broadcasts");i(this,"templates");this.messages=new se(t),this.conversations=new te(t),this.broadcasts=new ee(t),this.templates=new ae(t)}async upload(t,a){let n=new FormData;return n.append("file",t,a),this.post("/api/saas/chat/upload",n,{headers:typeof n.getHeaders=="function"?n.getHeaders():void 0})}async sendTemplate(t){return this.post("/api/saas/marketing/whatsapp/send-template",t)}};var Ne="https://api.ecodrix.com",v=class{constructor(e){i(this,"client");i(this,"socket",null);i(this,"socketPromise",null);i(this,"socketQueue",[]);i(this,"clientCode");i(this,"whatsapp");i(this,"crm");i(this,"media");i(this,"meet");i(this,"notifications");i(this,"email");i(this,"logs");i(this,"events");i(this,"webhooks");i(this,"storage");i(this,"marketing");i(this,"health");i(this,"queue");i(this,"agency");i(this,"services");i(this,"settings");i(this,"cors");i(this,"checkout");var l,h,d,P;if(!e.apiKey)throw new y("API Key is required");this.clientCode=(l=e.clientCode)==null?void 0:l.toUpperCase();let t=(h=e.baseUrl)!=null?h:Ne,a=e.socketUrl||t,n=typeof window!="undefined"&&typeof window.document!="undefined",o=n?"browser":typeof process!="undefined"?`node ${process.version}`:"unknown",c=n?((d=globalThis.navigator)==null?void 0:d.userAgent)||"browser":typeof process!="undefined"?process.platform:"unknown",g={"x-api-key":e.apiKey,"x-client-code":((P=e.clientCode)==null?void 0:P.toUpperCase())||"","Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:"1.0.0",runtime:o,os:c})};if(e.coreApiKey&&(g["x-core-api-key"]=e.coreApiKey),this.client=Ce.default.create({baseURL:t,headers:g}),(0,re.default)(this.client,{retries:3,retryDelay:re.default.exponentialDelay,retryCondition:T=>{var x;return re.default.isNetworkOrIdempotentRequestError(T)||((x=T.response)==null?void 0:x.status)===429},onRetry:(T,x,m)=>{var be,xe;typeof process!="undefined"&&((be=process.env)==null?void 0:be.NODE_ENV)==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${T}/3): ${(xe=m.method)==null?void 0:xe.toUpperCase()} ${m.url}. Reason: ${x.message}`)}}),this.whatsapp=new ne(this.client),this.crm=new F(this.client),this.media=new Q(this.client),this.meet=new J(this.client),this.notifications=new W(this.client),this.email=new B(this.client),this.logs=new K(this.client),this.events=new H(this.client),this.webhooks=new Z,this.storage=new Y(this.client),this.marketing=new V(this.client),this.health=new j(this.client),this.queue=new z(this.client),this.agency=new $(this.client),this.services=new G(this.client),this.settings=new X(this.client),this.cors=new E(this.client),this.checkout=new I(this.client),this.initSocket(a,e.apiKey,e.clientCode),n){let T={version:"1.2.2",clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=T,window.ecodrix||(window.ecodrix=this)}}initSocket(e,t,a){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:n})=>{this.socket=n(e,{extraHeaders:{"x-api-key":t,"x-client-code":(a==null?void 0:a.toUpperCase())||""}}),this.setupSocket(a);for(let{type:o,args:c}of this.socketQueue)o==="joinRoom"?this.socket.emit("join-room",c[0]):o==="leaveRoom"?this.socket.emit("leave-room",c[0]):o==="on"?this.socket.on(c[0],c[1]):o==="off"?this.socket.off(c[0],c[1]):o==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){this.socket?this.socket.emit("join-room",e):this.socketQueue.push({type:"joinRoom",args:[e]})}leaveRoom(e){this.socket?this.socket.emit("leave-room",e):this.socketQueue.push({type:"leaveRoom",args:[e]})}setupSocket(e){this.socket&&this.socket.on("connect",()=>{e&&this.socket.emit("join-room",e.toUpperCase())})}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}disconnect(){this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[e,t]}),this}async request(e,t,a,n){var o,c,g;try{return(await this.client.request({method:e,url:t,data:a,params:n})).data}catch(l){throw l.response?new u(((o=l.response.data)==null?void 0:o.message)||((c=l.response.data)==null?void 0:c.error)||"Raw Execution Failed",l.response.status,(g=l.response.data)==null?void 0:g.code):new u(l.message||"Network Error")}}};var Ae={401:y,403:y,429:f};function _e(s){var e,t,a;if(s.response){let n=s.response.status,o=((e=s.response.data)==null?void 0:e.message)||((t=s.response.data)==null?void 0:t.error)||"API Request Failed",c=(a=s.response.data)==null?void 0:a.code,g=Ae[n]||u;throw g===y?new y(o):g===f?new f(o):new u(o,n,c)}throw new u(s.message||"Network Error")}function Fe(s,e){return s instanceof e}function Be(s){return s instanceof y?{message:s.message,status:s.status,code:s.code,type:"AuthenticationError"}:s instanceof f?{message:s.message,status:s.status,code:s.code,type:"RateLimitError"}:s instanceof u?{message:s.message,status:s.status,code:s.code,type:"APIError"}:{message:s.message||"Unknown error",type:"UnknownError"}}var fe={[y.name]:{shouldRetry:!1,reason:"Authentication errors require fixing credentials, not retrying"},[f.name]:{shouldRetry:!0,maxRetries:3,baseDelay:1e3,backoffMultiplier:2,reason:"Rate limit errors can be retried with exponential backoff"},[u.name]:{shouldRetry:!0,maxRetries:2,baseDelay:500,backoffMultiplier:1.5,reason:"Generic API errors may be transient and worth retrying"}};function He(s){let e=s.constructor.name;return fe[e]||fe[u.name]}var je=v;0&&(module.exports={APIError,AuthenticationError,ECODrIx,ECODrIxAPI,ERROR_RETRY_CONFIG,EcodrixError,HTTP_STATUS_ERROR_MAP,RateLimitError,getErrorDetails,getRetryConfig,handleAPIError,isAPIError});
1
+ "use strict";var Ie=Object.create;var k=Object.defineProperty,Ee=Object.defineProperties,Se=Object.getOwnPropertyDescriptor,qe=Object.getOwnPropertyDescriptors,Le=Object.getOwnPropertyNames,Pe=Object.getOwnPropertySymbols,De=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty,Me=Object.prototype.propertyIsEnumerable;var Ue=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var oe=(s,e,t)=>e in s?k(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,b=(s,e)=>{for(var t in e||(e={}))we.call(e,t)&&oe(s,t,e[t]);if(Pe)for(var t of Pe(e))Me.call(e,t)&&oe(s,t,e[t]);return s},w=(s,e)=>Ee(s,qe(e));var Oe=(s,e)=>{for(var t in e)k(s,t,{get:e[t],enumerable:!0})},Re=(s,e,t,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Le(e))!we.call(s,r)&&r!==t&&k(s,r,{get:()=>e[r],enumerable:!(a=Se(e,r))||a.enumerable});return s};var C=(s,e,t)=>(t=s!=null?Ie(De(s)):{},Re(e||!s||!s.__esModule?k(t,"default",{value:s,enumerable:!0}):t,s)),Ne=s=>Re(k({},"__esModule",{value:!0}),s);var i=(s,e,t)=>oe(s,typeof e!="symbol"?e+"":e,t);var ce=function(s,e){this[0]=s,this[1]=e},ke=(s,e,t)=>{var a=(g,l,h,d)=>{try{var v=t[g](l),T=(l=v.value)instanceof ce,x=v.done;Promise.resolve(T?l[0]:l).then(m=>T?a(g==="return"?g:"next",l[1]?{done:m.done,value:m.value}:m,h,d):h({value:m,done:x})).catch(m=>a("throw",m,h,d))}catch(m){d(m)}},r=(g,l,h,d)=>c[g]=v=>(l=new Promise((T,x,m)=>(m=()=>a(g,v,T,x),o?o.then(m):m())),d=()=>o===h&&(o=0),o=h=l.then(d,d),l),o,c={};return t=t.apply(s,e),c[Ue("asyncIterator")]=()=>c,r("next"),r("throw"),r("return"),c};var Ve={};Oe(Ve,{APIError:()=>u,AuthenticationError:()=>y,ECODrIx:()=>P,ECODrIxAPI:()=>P,ERROR_RETRY_CONFIG:()=>be,EcodrixError:()=>A,HTTP_STATUS_ERROR_MAP:()=>$e,RateLimitError:()=>f,default:()=>Ke,getErrorDetails:()=>He,getRetryConfig:()=>je,handleAPIError:()=>Fe,isAPIError:()=>Be});module.exports=Ne(Ve);var Ae=C(require("axios"),1),ie=C(require("axios-retry"),1);var A=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends A{constructor(t,a,r){super(t);i(this,"status");i(this,"code");this.name="APIError",this.status=a,this.code=r}},y=class extends u{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},f=class extends u{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var n=class{constructor(e){i(this,"client",e)}async post(e,t,a){try{let r=this.buildConfig(a);return(await this.client.post(e,t,r)).data}catch(r){this.handleError(r)}}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 r=this.buildConfig(a);return(await this.client.patch(e,t,r)).data}catch(r){this.handleError(r)}}async put(e,t,a){try{let r=this.buildConfig(a);return(await this.client.put(e,t,r)).data}catch(r){this.handleError(r)}}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=b({},e);return e.idempotencyKey&&(t.headers=w(b({},t.headers),{"Idempotency-Key":e.idempotencyKey})),t}handleError(e){var t,a,r;if(e.response){let o=e.response.status,c=((t=e.response.data)==null?void 0:t.message)||((a=e.response.data)==null?void 0:a.error)||"API Request Failed",g=(r=e.response.data)==null?void 0:r.code;switch(o){case 401:throw new y(c);case 403:throw new y(c);case 429:throw new f(c);default:throw new u(c,o,g)}}throw new u(e.message||"Network Error")}};var $=class extends n{async listBlueprints(){return this.get("/api/agency/blueprints")}async createBlueprint(e){return this.post("/api/agency/blueprints",e)}async deployBlueprint(e){return this.post("/api/agency/blueprints/deploy",e)}async getPortfolioStats(e){return this.get(`/api/agency/portfolio/${e}/stats`)}async getPortfolioHealth(e){return this.get(`/api/agency/portfolio/${e}/health`)}async getUsage(e){return this.get(`/api/agency/usage/${e}`)}async listStaff(e){return this.get(`/api/agency/staff/${e}`)}async createStaff(e){return this.post("/api/agency/staff",e)}};var I=class extends n{async getProduct(e){return this.get(`/api/v1/checkout/products/${e}`)}async createSession(e){return this.post("/api/v1/checkout/session",e)}async applyCoupon(e){return this.post("/api/v1/checkout/coupon",e)}async verify(e){return this.post("/api/v1/checkout/verify",e)}async createOrder(e){return this.post("/api/v1/checkout/order",e)}};var E=class extends n{async providers(){return this.get("/api/connect/v1/providers")}async list(){return this.get("/api/connect/v1/connections")}async get_(e){return this.get(`/api/connect/v1/connections/${e}`)}async connect(e,t){return this.post(`/api/connect/v1/connections/${e}/connect`,t)}async configure(e,t){return this.put(`/api/connect/v1/connections/${e}/configure`,t)}async disconnect(e){return this.post(`/api/connect/v1/connections/${e}/disconnect`,{})}async reveal(e){return this.post(`/api/connect/v1/connections/${e}/reveal`,{})}async setAccess(e,t){return this.put(`/api/connect/v1/connections/${e}/access`,t)}};var S=class extends n{async list(){return this.get("/api/saas/cors")}async create(e){return this.post("/api/saas/cors",e)}async update(e,t){return this.patch(`/api/saas/cors/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/cors/${e}`)}};var pe=class extends n{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}`)}},q=class extends n{constructor(t){super(t);i(this,"notes");this.notes=new pe(t)}async timeline(t,a){return this.get(`/api/crm/leads/${t}/timeline`,{params:a})}async list(t,a){return this.get(`/api/crm/leads/${t}/activities`,{params:b({},a)})}async log(t){return this.post(`/api/crm/leads/${t.leadId}/activities`,t)}async logCall(t,a){return this.post(`/api/crm/leads/${t}/calls`,a)}};var L=class extends n{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 D=class extends n{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 M=class extends n{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/automations/webhook-event",{ruleId:e,eventName:t,payload:a})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}};var U=class extends n{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}],r=t.map(o=>({key:`metadata.extra.${o.name}`,label:o.label||o.name,type:o.type||"string",required:!!o.required,options:o.options,group:"Custom Fields"}));return{name:"Lead",fields:[...a,...r],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 r=0;r<e.length;r+=t){let c=e.slice(r,r+t).map(l=>this.create(l)),g=await Promise.allSettled(c);for(let l of g)if(l.status==="fulfilled")a.push(l.value);else throw l.reason}return a}async import(e){return this.post("/api/crm/leads/import",{leads:e})}async bulkUpsert(e){return this.import(e)}async list(e){let t=b({},e);return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/api/crm/leads",{params:t})}listAutoPaging(e){return ke(this,null,function*(){let t=(e==null?void 0:e.page)||1,a=!0;for(;a;){let r=yield new ce(this.list(w(b({},e),{page:t}))),o=Array.isArray(r.data)?r.data:r||[];if(o.length===0){a=!1;break}for(let c of o)yield c;r.pagination&&t<r.pagination.pages||!r.pagination&&o.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 byStage(e,t,a={}){return this.get(`/api/crm/pipelines/${e}/stages/${t}/leads`,{params:a})}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 bulkArchive(e){return this.patch("/api/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/api/crm/leads",{data:{ids:e}})}async archive(e){return this.patch(`/api/crm/leads/${e}/archive`,{})}};var O=class extends n{async capture(e){return this.post("/api/crm/payments/capture",e)}};var N=class extends n{async list(){return this.get("/api/crm/pipelines")}async getStageManifest(e){var r,o;let t=await this.retrieve(e),a=Array.isArray((r=t.data)==null?void 0:r.stages)?t.data.stages:[];return{name:`Pipeline: ${((o=t.data)==null?void 0:o.name)||e}`,fields:a.map(c=>({key:c._id,label:c.name,type:"string",required:!0,options:[{label:c.name,value:c._id}],group:"Stages",uiHints:{color:c.color||"#cbd5e1",probability:c.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 checkInUse(e){return this.get(`/api/crm/pipelines/${e}/in-use`)}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 _=class extends n{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 F=class extends n{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 B=class{constructor(e){i(this,"leads");i(this,"pipelines");i(this,"activities");i(this,"analytics");i(this,"automations");i(this,"sequences");i(this,"scoring");i(this,"payments");i(this,"automationDashboard");this.leads=new U(e),this.pipelines=new N(e),this.activities=new q(e),this.analytics=new L(e),this.automations=new M(e),this.sequences=new F(e),this.scoring=new _(e),this.payments=new O(e),this.automationDashboard=new D(e)}};var H=class extends n{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})}async listTemplates(e){return this.get("/api/saas/marketing/mail/templates",{params:e})}async getTemplate(e){return this.get(`/api/saas/marketing/mail/templates/${e}`)}async createTemplate(e){return this.post("/api/saas/marketing/mail/templates",e)}async updateTemplate(e,t){return this.put(`/api/saas/marketing/mail/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/api/saas/marketing/mail/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/api/saas/marketing/mail/templates/${e}/preview`,t)}};var j=class extends n{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/crm/events/emit",e)}};var K=class extends n{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 V=class extends n{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 le=class extends n{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})}},ge=class extends n{async list(e){return this.get("/api/saas/marketing/emails/campaigns",{params:e})}async stats(e){return this.get(`/api/saas/marketing/emails/campaigns/${e}/analytics`)}},ue=class extends n{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},Q=class extends n{constructor(t){super(t);i(this,"emails");i(this,"campaigns");i(this,"whatsapp");this.emails=new le(t),this.campaigns=new ge(t),this.whatsapp=new ue(t)}};var Ce=C(require("axios"),1);var J=class extends n{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 aiDescribe(e){return this.post("/api/saas/storage/ai/describe",{key:e})}async upload(e,t){let a=await this.post("/api/saas/storage/upload-url",t),{uploadUrl:r,key:o}=a.data;await Ce.default.put(r,e,{headers:{"Content-Type":t.contentType}});let c=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:o,sizeBytes:c})}};var W=class extends n{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 z=class extends n{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 G=class extends n{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 me=class extends n{async list(){return this.get("/api/clients")}async getCountAndGenerateCode(){return this.get("/api/clients/count")}async retrieve(e){return this.get(`/api/clients/${e}`)}async getApiKey(e){return this.get(`/api/clients/${e}/api-key`)}async rotateApiKey(e){return this.post(`/api/clients/${e}/api-key`,{})}async create(e){return this.post("/api/clients",e)}async getConfig(e){return this.get(`/api/clients/${e}/config`)}async updateConfig(e,t){return this.patch(`/api/clients/${e}/config`,t)}async getConnections(e){return this.get(`/api/clients/${e}/connections`)}async getConnectProviders(e){return this.get(`/api/clients/${e}/connections/providers`)}async connectProvider(e,t,a){return this.post(`/api/clients/${e}/connections/${t}/connect`,a)}async configureProvider(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/configure`,a)}async disconnectProvider(e,t){return this.post(`/api/clients/${e}/connections/${t}/disconnect`,{})}async revealConnection(e,t){return this.post(`/api/clients/${e}/connections/${t}/reveal`,{})}async setConnectionAccess(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/access`,a)}async getDataSource(e){return this.get(`/api/clients/${e}/datasource`)}async manageDataSource(e,t){return this.post(`/api/clients/${e}/datasource`,t)}async updateIdentity(e,t){return this.patch(`/api/clients/${e}/identity`,t)}async googleReauth(e,t={}){return this.post(`/api/clients/${e}/google/reauth`,t)}async delete(e){return this.deleteRequest(`/api/clients/${e}`)}},ye=class extends n{async list(){return this.get("/api/services/blogs")}},de=class extends n{async add(e){return this.post("/api/services/add-lead",e)}},X=class extends n{constructor(t){super(t);i(this,"clients");i(this,"blogs");i(this,"globalLeads");this.clients=new me(t),this.blogs=new ye(t),this.globalLeads=new de(t)}};var he=class extends n{async getConfig(){return this.get("/api/settings/email")}async switchProvider(e){return this.post("/api/settings/email/provider",{provider:e})}async saveSmtp(e){return this.post("/api/settings/email/smtp",e)}async initDomainVerification(e){return this.post("/api/settings/email/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/api/settings/email/ses/config",e)}async checkSesVerification(){return this.get("/api/settings/email/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/api/settings/email/ses/domain")}async sendTest(e){return this.post("/api/settings/email/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/api/settings/email/advanced",e)}async getHealth(){return this.get("/api/settings/email/health")}async fixDmarc(){return this.post("/api/settings/email/ses/fix-dmarc",{})}async listProviders(){return this.get("/api/settings/email/providers")}},Y=class extends n{constructor(t){super(t);i(this,"email");this.email=new he(t)}};var Te=class extends n{async create(e){return this.post("/api/saas/storage/folders",{name:e})}async delete(e){return this.deleteRequest(`/api/saas/storage/folders/${encodeURIComponent(e)}`)}},fe=class extends n{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}})}},Z=class extends n{constructor(t){super(t);i(this,"folders");i(this,"files");this.folders=new Te(t),this.files=new fe(t)}async usage(){return this.get("/api/saas/storage/usage")}};var R=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},ee=class{async constructEvent(e,t,a){if(!t)throw new R("No webhook signature provided");let r=Array.isArray(t)?t[0]:t;r.startsWith("sha256=")&&(r=r.slice(7));try{let o=await import("crypto"),g=o.createHmac("sha256",a).update(e).digest("hex");if(!o.timingSafeEqual(Buffer.from(g),Buffer.from(r)))throw new R("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(o){throw o instanceof R?o:new R(`Webhook payload parsing failed: ${o.message}`)}}};var te=class extends n{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 se=class extends n{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 ae=class extends n{async send(e){return this.post("/api/saas/chat/send",e)}async sendTemplate(e){return this.post("/api/saas/chat/send",w(b({},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 ne=class extends n{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){var o,c;let t=await this.retrieve(e),a=Array.isArray((o=t.data)==null?void 0:o.components)?t.data.components:[],r=[];for(let g of a)if(g.text){let l=g.text.match(/{{(\d+)}}/g);if(l)for(let h of l){let d=h.replace(/{{|}}/g,"");r.push({key:`var_${d}`,label:`${g.type} Var {{${d}}}`,type:"string",required:!0,group:g.type,description:`Variable placeholder in template ${g.type}`})}}return{name:`Template variables: ${((c=t.data)==null?void 0:c.name)||e}`,fields:r,uiHints:{icon:"Variables",primaryColor:"#059669"}}}async checkUsage(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/usage`)}};var re=class extends n{constructor(t){super(t);i(this,"messages");i(this,"conversations");i(this,"broadcasts");i(this,"templates");this.messages=new ae(t),this.conversations=new se(t),this.broadcasts=new te(t),this.templates=new ne(t)}async upload(t,a){let r=new FormData;return r.append("file",t,a),this.post("/api/saas/chat/upload",r,{headers:typeof r.getHeaders=="function"?r.getHeaders():void 0})}async sendTemplate(t){return this.post("/api/saas/marketing/whatsapp/send-template",t)}};var _e="https://api.ecodrix.com",P=class{constructor(e){i(this,"client");i(this,"socket",null);i(this,"socketPromise",null);i(this,"socketQueue",[]);i(this,"clientCode");i(this,"whatsapp");i(this,"crm");i(this,"media");i(this,"meet");i(this,"notifications");i(this,"email");i(this,"logs");i(this,"events");i(this,"webhooks");i(this,"storage");i(this,"marketing");i(this,"health");i(this,"queue");i(this,"agency");i(this,"services");i(this,"settings");i(this,"cors");i(this,"checkout");i(this,"connect");var l,h,d,v;if(!e.apiKey)throw new y("API Key is required");this.clientCode=(l=e.clientCode)==null?void 0:l.toUpperCase();let t=(h=e.baseUrl)!=null?h:_e,a=e.socketUrl||t,r=typeof window!="undefined"&&typeof window.document!="undefined",o=r?"browser":typeof process!="undefined"?`node ${process.version}`:"unknown",c=r?((d=globalThis.navigator)==null?void 0:d.userAgent)||"browser":typeof process!="undefined"?process.platform:"unknown",g={"x-api-key":e.apiKey,"x-client-code":((v=e.clientCode)==null?void 0:v.toUpperCase())||"","Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:"1.0.0",runtime:o,os:c})};if(e.coreApiKey&&(g["x-core-api-key"]=e.coreApiKey),this.client=Ae.default.create({baseURL:t,headers:g}),(0,ie.default)(this.client,{retries:3,retryDelay:ie.default.exponentialDelay,retryCondition:T=>{var x;return ie.default.isNetworkOrIdempotentRequestError(T)||((x=T.response)==null?void 0:x.status)===429},onRetry:(T,x,m)=>{var xe,ve;typeof process!="undefined"&&((xe=process.env)==null?void 0:xe.NODE_ENV)==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${T}/3): ${(ve=m.method)==null?void 0:ve.toUpperCase()} ${m.url}. Reason: ${x.message}`)}}),this.whatsapp=new re(this.client),this.crm=new B(this.client),this.media=new J(this.client),this.meet=new W(this.client),this.notifications=new z(this.client),this.email=new H(this.client),this.logs=new V(this.client),this.events=new j(this.client),this.webhooks=new ee,this.storage=new Z(this.client),this.marketing=new Q(this.client),this.health=new K(this.client),this.queue=new G(this.client),this.agency=new $(this.client),this.services=new X(this.client),this.settings=new Y(this.client),this.cors=new S(this.client),this.checkout=new I(this.client),this.connect=new E(this.client),this.initSocket(a,e.apiKey,e.clientCode),r){let T={version:"1.2.2",clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=T,window.ecodrix||(window.ecodrix=this)}}initSocket(e,t,a){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:r})=>{this.socket=r(e,{extraHeaders:{"x-api-key":t,"x-client-code":(a==null?void 0:a.toUpperCase())||""}}),this.setupSocket(a);for(let{type:o,args:c}of this.socketQueue)o==="joinRoom"?this.socket.emit("join-room",c[0]):o==="leaveRoom"?this.socket.emit("leave-room",c[0]):o==="on"?this.socket.on(c[0],c[1]):o==="off"?this.socket.off(c[0],c[1]):o==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){this.socket?this.socket.emit("join-room",e):this.socketQueue.push({type:"joinRoom",args:[e]})}leaveRoom(e){this.socket?this.socket.emit("leave-room",e):this.socketQueue.push({type:"leaveRoom",args:[e]})}setupSocket(e){this.socket&&this.socket.on("connect",()=>{e&&this.socket.emit("join-room",e.toUpperCase())})}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}disconnect(){this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[e,t]}),this}async request(e,t,a,r){var o,c,g;try{return(await this.client.request({method:e,url:t,data:a,params:r})).data}catch(l){throw l.response?new u(((o=l.response.data)==null?void 0:o.message)||((c=l.response.data)==null?void 0:c.error)||"Raw Execution Failed",l.response.status,(g=l.response.data)==null?void 0:g.code):new u(l.message||"Network Error")}}};var $e={401:y,403:y,429:f};function Fe(s){var e,t,a;if(s.response){let r=s.response.status,o=((e=s.response.data)==null?void 0:e.message)||((t=s.response.data)==null?void 0:t.error)||"API Request Failed",c=(a=s.response.data)==null?void 0:a.code,g=$e[r]||u;throw g===y?new y(o):g===f?new f(o):new u(o,r,c)}throw new u(s.message||"Network Error")}function Be(s,e){return s instanceof e}function He(s){return s instanceof y?{message:s.message,status:s.status,code:s.code,type:"AuthenticationError"}:s instanceof f?{message:s.message,status:s.status,code:s.code,type:"RateLimitError"}:s instanceof u?{message:s.message,status:s.status,code:s.code,type:"APIError"}:{message:s.message||"Unknown error",type:"UnknownError"}}var be={[y.name]:{shouldRetry:!1,reason:"Authentication errors require fixing credentials, not retrying"},[f.name]:{shouldRetry:!0,maxRetries:3,baseDelay:1e3,backoffMultiplier:2,reason:"Rate limit errors can be retried with exponential backoff"},[u.name]:{shouldRetry:!0,maxRetries:2,baseDelay:500,backoffMultiplier:1.5,reason:"Generic API errors may be transient and worth retrying"}};function je(s){let e=s.constructor.name;return be[e]||be[u.name]}var Ke=P;0&&(module.exports={APIError,AuthenticationError,ECODrIx,ECODrIxAPI,ERROR_RETRY_CONFIG,EcodrixError,HTTP_STATUS_ERROR_MAP,RateLimitError,getErrorDetails,getRetryConfig,handleAPIError,isAPIError});
@@ -159,6 +159,66 @@ declare class Checkout extends APIResource {
159
159
  createOrder(payload: CreateOrderPayload): Promise<CheckoutOrderResponse>;
160
160
  }
161
161
 
162
+ /**
163
+ * ERIX-Connect — the tenant-facing connections layer.
164
+ *
165
+ * Connect channels & services (Email, WhatsApp, Instagram, Telegram, Google,
166
+ * Database residency) and grant each platform module (CRM / Flow / LAIE) access.
167
+ * All credentials are stored encrypted and only ever returned MASKED.
168
+ *
169
+ * Tenant-scoped via the SDK's `x-api-key` + `x-client-code` — mounted at
170
+ * `/api/connect/v1/*`.
171
+ */
172
+ declare class Connect extends APIResource {
173
+ /**
174
+ * List the provider registry (cards + connect methods + field metadata).
175
+ */
176
+ providers<T = any>(): Promise<T>;
177
+ /**
178
+ * List the tenant's connections (masked status + active method + per-module
179
+ * access grants).
180
+ */
181
+ list<T = any>(): Promise<T>;
182
+ /**
183
+ * Get a single provider's connection (masked status + grants).
184
+ */
185
+ get_<T = any>(providerId: string): Promise<T>;
186
+ /**
187
+ * Connect a provider via a chosen method.
188
+ * @param providerId e.g. "email" | "whatsapp" | "database" | ...
189
+ * @param payload `{ method, config }` — method is the registry method id
190
+ * (for `database`, the method IS the residency mode: platform|own|hybrid).
191
+ */
192
+ connect<T = any>(providerId: string, payload: {
193
+ method: string;
194
+ config?: Record<string, unknown>;
195
+ }): Promise<T>;
196
+ /**
197
+ * Update an already-connected provider's configuration.
198
+ */
199
+ configure<T = any>(providerId: string, payload: {
200
+ method: string;
201
+ config?: Record<string, unknown>;
202
+ }): Promise<T>;
203
+ /**
204
+ * Disconnect a provider.
205
+ */
206
+ disconnect<T = any>(providerId: string): Promise<T>;
207
+ /**
208
+ * Reveal a provider's DECRYPTED credentials — OWNER-ONLY. The owning tenant
209
+ * can reveal + copy + edit their own credential values. Audited server-side;
210
+ * cross-tenant access is denied. Returns `[{ key, label, value }]`.
211
+ */
212
+ reveal<T = any>(providerId: string): Promise<T>;
213
+ /**
214
+ * Toggle a per-module access grant (crm | flow | laie) for a provider.
215
+ */
216
+ setAccess<T = any>(providerId: string, payload: {
217
+ module: "crm" | "flow" | "laie";
218
+ enabled: boolean;
219
+ }): Promise<T>;
220
+ }
221
+
162
222
  interface CorsOriginCreatePayload {
163
223
  url: string;
164
224
  name?: string;
@@ -2477,6 +2537,10 @@ declare class Clients extends APIResource {
2477
2537
  * Disconnect a provider for a client.
2478
2538
  */
2479
2539
  disconnectProvider<T = any>(clientCode: string, providerId: string): Promise<T>;
2540
+ /**
2541
+ * Reveal a client's DECRYPTED credentials for a provider (admin/agency).
2542
+ */
2543
+ revealConnection<T = any>(clientCode: string, providerId: string): Promise<T>;
2480
2544
  /**
2481
2545
  * Toggle a per-module access grant (crm | flow | laie) for a client's
2482
2546
  * connector.
@@ -3423,6 +3487,8 @@ declare class ECODrIxAPI {
3423
3487
  readonly cors: Cors;
3424
3488
  /** ErixCheckout one-click checkout flow management. */
3425
3489
  readonly checkout: Checkout;
3490
+ /** ERIX-Connect — tenant connections (channels, credentials, DB residency). */
3491
+ readonly connect: Connect;
3426
3492
  constructor(options: ECODrIxAPIOptions);
3427
3493
  private initSocket;
3428
3494
  /**
@@ -1 +1 @@
1
- var xe=Object.defineProperty,Pe=Object.defineProperties;var ve=Object.getOwnPropertyDescriptors;var Te=Object.getOwnPropertySymbols;var we=Object.prototype.hasOwnProperty,Re=Object.prototype.propertyIsEnumerable;var ke=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var te=(s,e,t)=>e in s?xe(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,T=(s,e)=>{for(var t in e||(e={}))we.call(e,t)&&te(s,t,e[t]);if(Te)for(var t of Te(e))Re.call(e,t)&&te(s,t,e[t]);return s},P=(s,e)=>Pe(s,ve(e));var i=(s,e,t)=>te(s,typeof e!="symbol"?e+"":e,t);var se=function(s,e){this[0]=s,this[1]=e},fe=(s,e,t)=>{var a=(l,p,d,y)=>{try{var x=t[l](p),h=(p=x.value)instanceof se,b=x.done;Promise.resolve(h?p[0]:p).then(u=>h?a(l==="return"?l:"next",p[1]?{done:u.done,value:u.value}:u,d,y):d({value:u,done:b})).catch(u=>a("throw",u,d,y))}catch(u){y(u)}},r=(l,p,d,y)=>c[l]=x=>(p=new Promise((h,b,u)=>(u=()=>a(l,x,h,b),o?o.then(u):u())),y=()=>o===d&&(o=0),o=d=p.then(y,y),p),o,c={};return t=t.apply(s,e),c[ke("asyncIterator")]=()=>c,r("next"),r("throw"),r("return"),c};import Ae from"axios";import ye from"axios-retry";var ae=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},g=class extends ae{constructor(t,a,r){super(t);i(this,"status");i(this,"code");this.name="APIError",this.status=a,this.code=r}},m=class extends g{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},f=class extends g{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var n=class{constructor(e){i(this,"client",e)}async post(e,t,a){try{let r=this.buildConfig(a);return(await this.client.post(e,t,r)).data}catch(r){this.handleError(r)}}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 r=this.buildConfig(a);return(await this.client.patch(e,t,r)).data}catch(r){this.handleError(r)}}async put(e,t,a){try{let r=this.buildConfig(a);return(await this.client.put(e,t,r)).data}catch(r){this.handleError(r)}}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=T({},e);return e.idempotencyKey&&(t.headers=P(T({},t.headers),{"Idempotency-Key":e.idempotencyKey})),t}handleError(e){var t,a,r;if(e.response){let o=e.response.status,c=((t=e.response.data)==null?void 0:t.message)||((a=e.response.data)==null?void 0:a.error)||"API Request Failed",l=(r=e.response.data)==null?void 0:r.code;switch(o){case 401:throw new m(c);case 403:throw new m(c);case 429:throw new f(c);default:throw new g(c,o,l)}}throw new g(e.message||"Network Error")}};var R=class extends n{async listBlueprints(){return this.get("/api/agency/blueprints")}async createBlueprint(e){return this.post("/api/agency/blueprints",e)}async deployBlueprint(e){return this.post("/api/agency/blueprints/deploy",e)}async getPortfolioStats(e){return this.get(`/api/agency/portfolio/${e}/stats`)}async getPortfolioHealth(e){return this.get(`/api/agency/portfolio/${e}/health`)}async getUsage(e){return this.get(`/api/agency/usage/${e}`)}async listStaff(e){return this.get(`/api/agency/staff/${e}`)}async createStaff(e){return this.post("/api/agency/staff",e)}};var k=class extends n{async getProduct(e){return this.get(`/api/v1/checkout/products/${e}`)}async createSession(e){return this.post("/api/v1/checkout/session",e)}async applyCoupon(e){return this.post("/api/v1/checkout/coupon",e)}async verify(e){return this.post("/api/v1/checkout/verify",e)}async createOrder(e){return this.post("/api/v1/checkout/order",e)}};var C=class extends n{async list(){return this.get("/api/saas/cors")}async create(e){return this.post("/api/saas/cors",e)}async update(e,t){return this.patch(`/api/saas/cors/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/cors/${e}`)}};var ne=class extends n{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}`)}},A=class extends n{constructor(t){super(t);i(this,"notes");this.notes=new ne(t)}async timeline(t,a){return this.get(`/api/crm/leads/${t}/timeline`,{params:a})}async list(t,a){return this.get(`/api/crm/leads/${t}/activities`,{params:T({},a)})}async log(t){return this.post(`/api/crm/leads/${t.leadId}/activities`,t)}async logCall(t,a){return this.post(`/api/crm/leads/${t}/calls`,a)}};var $=class extends n{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 I=class extends n{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 E=class extends n{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/automations/webhook-event",{ruleId:e,eventName:t,payload:a})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}};var S=class extends n{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}],r=t.map(o=>({key:`metadata.extra.${o.name}`,label:o.label||o.name,type:o.type||"string",required:!!o.required,options:o.options,group:"Custom Fields"}));return{name:"Lead",fields:[...a,...r],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 r=0;r<e.length;r+=t){let c=e.slice(r,r+t).map(p=>this.create(p)),l=await Promise.allSettled(c);for(let p of l)if(p.status==="fulfilled")a.push(p.value);else throw p.reason}return a}async import(e){return this.post("/api/crm/leads/import",{leads:e})}async bulkUpsert(e){return this.import(e)}async list(e){let t=T({},e);return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/api/crm/leads",{params:t})}listAutoPaging(e){return fe(this,null,function*(){let t=(e==null?void 0:e.page)||1,a=!0;for(;a;){let r=yield new se(this.list(P(T({},e),{page:t}))),o=Array.isArray(r.data)?r.data:r||[];if(o.length===0){a=!1;break}for(let c of o)yield c;r.pagination&&t<r.pagination.pages||!r.pagination&&o.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 byStage(e,t,a={}){return this.get(`/api/crm/pipelines/${e}/stages/${t}/leads`,{params:a})}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 bulkArchive(e){return this.patch("/api/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/api/crm/leads",{data:{ids:e}})}async archive(e){return this.patch(`/api/crm/leads/${e}/archive`,{})}};var L=class extends n{async capture(e){return this.post("/api/crm/payments/capture",e)}};var q=class extends n{async list(){return this.get("/api/crm/pipelines")}async getStageManifest(e){var r,o;let t=await this.retrieve(e),a=Array.isArray((r=t.data)==null?void 0:r.stages)?t.data.stages:[];return{name:`Pipeline: ${((o=t.data)==null?void 0:o.name)||e}`,fields:a.map(c=>({key:c._id,label:c.name,type:"string",required:!0,options:[{label:c.name,value:c._id}],group:"Stages",uiHints:{color:c.color||"#cbd5e1",probability:c.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 checkInUse(e){return this.get(`/api/crm/pipelines/${e}/in-use`)}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 D=class extends n{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 U=class extends n{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 M=class{constructor(e){i(this,"leads");i(this,"pipelines");i(this,"activities");i(this,"analytics");i(this,"automations");i(this,"sequences");i(this,"scoring");i(this,"payments");i(this,"automationDashboard");this.leads=new S(e),this.pipelines=new q(e),this.activities=new A(e),this.analytics=new $(e),this.automations=new E(e),this.sequences=new U(e),this.scoring=new D(e),this.payments=new L(e),this.automationDashboard=new I(e)}};var O=class extends n{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})}async listTemplates(e){return this.get("/api/saas/marketing/mail/templates",{params:e})}async getTemplate(e){return this.get(`/api/saas/marketing/mail/templates/${e}`)}async createTemplate(e){return this.post("/api/saas/marketing/mail/templates",e)}async updateTemplate(e,t){return this.put(`/api/saas/marketing/mail/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/api/saas/marketing/mail/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/api/saas/marketing/mail/templates/${e}/preview`,t)}};var N=class extends n{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/crm/events/emit",e)}};var _=class extends n{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 B=class extends n{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 re=class extends n{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})}},ie=class extends n{async list(e){return this.get("/api/saas/marketing/emails/campaigns",{params:e})}async stats(e){return this.get(`/api/saas/marketing/emails/campaigns/${e}/analytics`)}},oe=class extends n{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},H=class extends n{constructor(t){super(t);i(this,"emails");i(this,"campaigns");i(this,"whatsapp");this.emails=new re(t),this.campaigns=new ie(t),this.whatsapp=new oe(t)}};import Ce from"axios";var F=class extends n{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 aiDescribe(e){return this.post("/api/saas/storage/ai/describe",{key:e})}async upload(e,t){let a=await this.post("/api/saas/storage/upload-url",t),{uploadUrl:r,key:o}=a.data;await Ce.put(r,e,{headers:{"Content-Type":t.contentType}});let c=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:o,sizeBytes:c})}};var j=class extends n{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 K=class extends n{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 V=class extends n{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 ce=class extends n{async list(){return this.get("/api/clients")}async getCountAndGenerateCode(){return this.get("/api/clients/count")}async retrieve(e){return this.get(`/api/clients/${e}`)}async getApiKey(e){return this.get(`/api/clients/${e}/api-key`)}async rotateApiKey(e){return this.post(`/api/clients/${e}/api-key`,{})}async create(e){return this.post("/api/clients",e)}async getConfig(e){return this.get(`/api/clients/${e}/config`)}async updateConfig(e,t){return this.patch(`/api/clients/${e}/config`,t)}async getConnections(e){return this.get(`/api/clients/${e}/connections`)}async getConnectProviders(e){return this.get(`/api/clients/${e}/connections/providers`)}async connectProvider(e,t,a){return this.post(`/api/clients/${e}/connections/${t}/connect`,a)}async configureProvider(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/configure`,a)}async disconnectProvider(e,t){return this.post(`/api/clients/${e}/connections/${t}/disconnect`,{})}async setConnectionAccess(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/access`,a)}async getDataSource(e){return this.get(`/api/clients/${e}/datasource`)}async manageDataSource(e,t){return this.post(`/api/clients/${e}/datasource`,t)}async updateIdentity(e,t){return this.patch(`/api/clients/${e}/identity`,t)}async googleReauth(e,t={}){return this.post(`/api/clients/${e}/google/reauth`,t)}async delete(e){return this.deleteRequest(`/api/clients/${e}`)}},pe=class extends n{async list(){return this.get("/api/services/blogs")}},le=class extends n{async add(e){return this.post("/api/services/add-lead",e)}},Q=class extends n{constructor(t){super(t);i(this,"clients");i(this,"blogs");i(this,"globalLeads");this.clients=new ce(t),this.blogs=new pe(t),this.globalLeads=new le(t)}};var ge=class extends n{async getConfig(){return this.get("/api/settings/email")}async switchProvider(e){return this.post("/api/settings/email/provider",{provider:e})}async saveSmtp(e){return this.post("/api/settings/email/smtp",e)}async initDomainVerification(e){return this.post("/api/settings/email/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/api/settings/email/ses/config",e)}async checkSesVerification(){return this.get("/api/settings/email/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/api/settings/email/ses/domain")}async sendTest(e){return this.post("/api/settings/email/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/api/settings/email/advanced",e)}async getHealth(){return this.get("/api/settings/email/health")}async fixDmarc(){return this.post("/api/settings/email/ses/fix-dmarc",{})}async listProviders(){return this.get("/api/settings/email/providers")}},J=class extends n{constructor(t){super(t);i(this,"email");this.email=new ge(t)}};var ue=class extends n{async create(e){return this.post("/api/saas/storage/folders",{name:e})}async delete(e){return this.deleteRequest(`/api/saas/storage/folders/${encodeURIComponent(e)}`)}},me=class extends n{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}})}},W=class extends n{constructor(t){super(t);i(this,"folders");i(this,"files");this.folders=new ue(t),this.files=new me(t)}async usage(){return this.get("/api/saas/storage/usage")}};var v=class extends g{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},G=class{async constructEvent(e,t,a){if(!t)throw new v("No webhook signature provided");let r=Array.isArray(t)?t[0]:t;r.startsWith("sha256=")&&(r=r.slice(7));try{let o=await import("crypto"),l=o.createHmac("sha256",a).update(e).digest("hex");if(!o.timingSafeEqual(Buffer.from(l),Buffer.from(r)))throw new v("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(o){throw o instanceof v?o:new v(`Webhook payload parsing failed: ${o.message}`)}}};var z=class extends n{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 X=class extends n{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 Y=class extends n{async send(e){return this.post("/api/saas/chat/send",e)}async sendTemplate(e){return this.post("/api/saas/chat/send",P(T({},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 Z=class extends n{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){var o,c;let t=await this.retrieve(e),a=Array.isArray((o=t.data)==null?void 0:o.components)?t.data.components:[],r=[];for(let l of a)if(l.text){let p=l.text.match(/{{(\d+)}}/g);if(p)for(let d of p){let y=d.replace(/{{|}}/g,"");r.push({key:`var_${y}`,label:`${l.type} Var {{${y}}}`,type:"string",required:!0,group:l.type,description:`Variable placeholder in template ${l.type}`})}}return{name:`Template variables: ${((c=t.data)==null?void 0:c.name)||e}`,fields:r,uiHints:{icon:"Variables",primaryColor:"#059669"}}}async checkUsage(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/usage`)}};var ee=class extends n{constructor(t){super(t);i(this,"messages");i(this,"conversations");i(this,"broadcasts");i(this,"templates");this.messages=new Y(t),this.conversations=new X(t),this.broadcasts=new z(t),this.templates=new Z(t)}async upload(t,a){let r=new FormData;return r.append("file",t,a),this.post("/api/saas/chat/upload",r,{headers:typeof r.getHeaders=="function"?r.getHeaders():void 0})}async sendTemplate(t){return this.post("/api/saas/marketing/whatsapp/send-template",t)}};var $e="https://api.ecodrix.com",w=class{constructor(e){i(this,"client");i(this,"socket",null);i(this,"socketPromise",null);i(this,"socketQueue",[]);i(this,"clientCode");i(this,"whatsapp");i(this,"crm");i(this,"media");i(this,"meet");i(this,"notifications");i(this,"email");i(this,"logs");i(this,"events");i(this,"webhooks");i(this,"storage");i(this,"marketing");i(this,"health");i(this,"queue");i(this,"agency");i(this,"services");i(this,"settings");i(this,"cors");i(this,"checkout");var p,d,y,x;if(!e.apiKey)throw new m("API Key is required");this.clientCode=(p=e.clientCode)==null?void 0:p.toUpperCase();let t=(d=e.baseUrl)!=null?d:$e,a=e.socketUrl||t,r=typeof window!="undefined"&&typeof window.document!="undefined",o=r?"browser":typeof process!="undefined"?`node ${process.version}`:"unknown",c=r?((y=globalThis.navigator)==null?void 0:y.userAgent)||"browser":typeof process!="undefined"?process.platform:"unknown",l={"x-api-key":e.apiKey,"x-client-code":((x=e.clientCode)==null?void 0:x.toUpperCase())||"","Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:"1.0.0",runtime:o,os:c})};if(e.coreApiKey&&(l["x-core-api-key"]=e.coreApiKey),this.client=Ae.create({baseURL:t,headers:l}),ye(this.client,{retries:3,retryDelay:ye.exponentialDelay,retryCondition:h=>{var b;return ye.isNetworkOrIdempotentRequestError(h)||((b=h.response)==null?void 0:b.status)===429},onRetry:(h,b,u)=>{var de,he;typeof process!="undefined"&&((de=process.env)==null?void 0:de.NODE_ENV)==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${h}/3): ${(he=u.method)==null?void 0:he.toUpperCase()} ${u.url}. Reason: ${b.message}`)}}),this.whatsapp=new ee(this.client),this.crm=new M(this.client),this.media=new F(this.client),this.meet=new j(this.client),this.notifications=new K(this.client),this.email=new O(this.client),this.logs=new B(this.client),this.events=new N(this.client),this.webhooks=new G,this.storage=new W(this.client),this.marketing=new H(this.client),this.health=new _(this.client),this.queue=new V(this.client),this.agency=new R(this.client),this.services=new Q(this.client),this.settings=new J(this.client),this.cors=new C(this.client),this.checkout=new k(this.client),this.initSocket(a,e.apiKey,e.clientCode),r){let h={version:"1.2.2",clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=h,window.ecodrix||(window.ecodrix=this)}}initSocket(e,t,a){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:r})=>{this.socket=r(e,{extraHeaders:{"x-api-key":t,"x-client-code":(a==null?void 0:a.toUpperCase())||""}}),this.setupSocket(a);for(let{type:o,args:c}of this.socketQueue)o==="joinRoom"?this.socket.emit("join-room",c[0]):o==="leaveRoom"?this.socket.emit("leave-room",c[0]):o==="on"?this.socket.on(c[0],c[1]):o==="off"?this.socket.off(c[0],c[1]):o==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){this.socket?this.socket.emit("join-room",e):this.socketQueue.push({type:"joinRoom",args:[e]})}leaveRoom(e){this.socket?this.socket.emit("leave-room",e):this.socketQueue.push({type:"leaveRoom",args:[e]})}setupSocket(e){this.socket&&this.socket.on("connect",()=>{e&&this.socket.emit("join-room",e.toUpperCase())})}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}disconnect(){this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[e,t]}),this}async request(e,t,a,r){var o,c,l;try{return(await this.client.request({method:e,url:t,data:a,params:r})).data}catch(p){throw p.response?new g(((o=p.response.data)==null?void 0:o.message)||((c=p.response.data)==null?void 0:c.error)||"Raw Execution Failed",p.response.status,(l=p.response.data)==null?void 0:l.code):new g(p.message||"Network Error")}}};var Ie={401:m,403:m,429:f};function Os(s){var e,t,a;if(s.response){let r=s.response.status,o=((e=s.response.data)==null?void 0:e.message)||((t=s.response.data)==null?void 0:t.error)||"API Request Failed",c=(a=s.response.data)==null?void 0:a.code,l=Ie[r]||g;throw l===m?new m(o):l===f?new f(o):new g(o,r,c)}throw new g(s.message||"Network Error")}function Ns(s,e){return s instanceof e}function _s(s){return s instanceof m?{message:s.message,status:s.status,code:s.code,type:"AuthenticationError"}:s instanceof f?{message:s.message,status:s.status,code:s.code,type:"RateLimitError"}:s instanceof g?{message:s.message,status:s.status,code:s.code,type:"APIError"}:{message:s.message||"Unknown error",type:"UnknownError"}}var be={[m.name]:{shouldRetry:!1,reason:"Authentication errors require fixing credentials, not retrying"},[f.name]:{shouldRetry:!0,maxRetries:3,baseDelay:1e3,backoffMultiplier:2,reason:"Rate limit errors can be retried with exponential backoff"},[g.name]:{shouldRetry:!0,maxRetries:2,baseDelay:500,backoffMultiplier:1.5,reason:"Generic API errors may be transient and worth retrying"}};function Bs(s){let e=s.constructor.name;return be[e]||be[g.name]}var js=w;export{g as APIError,m as AuthenticationError,w as ECODrIx,w as ECODrIxAPI,be as ERROR_RETRY_CONFIG,ae as EcodrixError,Ie as HTTP_STATUS_ERROR_MAP,f as RateLimitError,js as default,_s as getErrorDetails,Bs as getRetryConfig,Os as handleAPIError,Ns as isAPIError};
1
+ var xe=Object.defineProperty,Pe=Object.defineProperties;var we=Object.getOwnPropertyDescriptors;var fe=Object.getOwnPropertySymbols;var Re=Object.prototype.hasOwnProperty,ke=Object.prototype.propertyIsEnumerable;var Ce=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var se=(s,e,t)=>e in s?xe(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,T=(s,e)=>{for(var t in e||(e={}))Re.call(e,t)&&se(s,t,e[t]);if(fe)for(var t of fe(e))ke.call(e,t)&&se(s,t,e[t]);return s},x=(s,e)=>Pe(s,we(e));var i=(s,e,t)=>se(s,typeof e!="symbol"?e+"":e,t);var ae=function(s,e){this[0]=s,this[1]=e},be=(s,e,t)=>{var a=(l,p,d,y)=>{try{var v=t[l](p),h=(p=v.value)instanceof ae,b=v.done;Promise.resolve(h?p[0]:p).then(u=>h?a(l==="return"?l:"next",p[1]?{done:u.done,value:u.value}:u,d,y):d({value:u,done:b})).catch(u=>a("throw",u,d,y))}catch(u){y(u)}},r=(l,p,d,y)=>c[l]=v=>(p=new Promise((h,b,u)=>(u=()=>a(l,v,h,b),o?o.then(u):u())),y=()=>o===d&&(o=0),o=d=p.then(y,y),p),o,c={};return t=t.apply(s,e),c[Ce("asyncIterator")]=()=>c,r("next"),r("throw"),r("return"),c};import $e from"axios";import de from"axios-retry";var ne=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},g=class extends ne{constructor(t,a,r){super(t);i(this,"status");i(this,"code");this.name="APIError",this.status=a,this.code=r}},m=class extends g{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},f=class extends g{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var n=class{constructor(e){i(this,"client",e)}async post(e,t,a){try{let r=this.buildConfig(a);return(await this.client.post(e,t,r)).data}catch(r){this.handleError(r)}}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 r=this.buildConfig(a);return(await this.client.patch(e,t,r)).data}catch(r){this.handleError(r)}}async put(e,t,a){try{let r=this.buildConfig(a);return(await this.client.put(e,t,r)).data}catch(r){this.handleError(r)}}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=T({},e);return e.idempotencyKey&&(t.headers=x(T({},t.headers),{"Idempotency-Key":e.idempotencyKey})),t}handleError(e){var t,a,r;if(e.response){let o=e.response.status,c=((t=e.response.data)==null?void 0:t.message)||((a=e.response.data)==null?void 0:a.error)||"API Request Failed",l=(r=e.response.data)==null?void 0:r.code;switch(o){case 401:throw new m(c);case 403:throw new m(c);case 429:throw new f(c);default:throw new g(c,o,l)}}throw new g(e.message||"Network Error")}};var R=class extends n{async listBlueprints(){return this.get("/api/agency/blueprints")}async createBlueprint(e){return this.post("/api/agency/blueprints",e)}async deployBlueprint(e){return this.post("/api/agency/blueprints/deploy",e)}async getPortfolioStats(e){return this.get(`/api/agency/portfolio/${e}/stats`)}async getPortfolioHealth(e){return this.get(`/api/agency/portfolio/${e}/health`)}async getUsage(e){return this.get(`/api/agency/usage/${e}`)}async listStaff(e){return this.get(`/api/agency/staff/${e}`)}async createStaff(e){return this.post("/api/agency/staff",e)}};var k=class extends n{async getProduct(e){return this.get(`/api/v1/checkout/products/${e}`)}async createSession(e){return this.post("/api/v1/checkout/session",e)}async applyCoupon(e){return this.post("/api/v1/checkout/coupon",e)}async verify(e){return this.post("/api/v1/checkout/verify",e)}async createOrder(e){return this.post("/api/v1/checkout/order",e)}};var C=class extends n{async providers(){return this.get("/api/connect/v1/providers")}async list(){return this.get("/api/connect/v1/connections")}async get_(e){return this.get(`/api/connect/v1/connections/${e}`)}async connect(e,t){return this.post(`/api/connect/v1/connections/${e}/connect`,t)}async configure(e,t){return this.put(`/api/connect/v1/connections/${e}/configure`,t)}async disconnect(e){return this.post(`/api/connect/v1/connections/${e}/disconnect`,{})}async reveal(e){return this.post(`/api/connect/v1/connections/${e}/reveal`,{})}async setAccess(e,t){return this.put(`/api/connect/v1/connections/${e}/access`,t)}};var A=class extends n{async list(){return this.get("/api/saas/cors")}async create(e){return this.post("/api/saas/cors",e)}async update(e,t){return this.patch(`/api/saas/cors/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/cors/${e}`)}};var re=class extends n{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}`)}},$=class extends n{constructor(t){super(t);i(this,"notes");this.notes=new re(t)}async timeline(t,a){return this.get(`/api/crm/leads/${t}/timeline`,{params:a})}async list(t,a){return this.get(`/api/crm/leads/${t}/activities`,{params:T({},a)})}async log(t){return this.post(`/api/crm/leads/${t.leadId}/activities`,t)}async logCall(t,a){return this.post(`/api/crm/leads/${t}/calls`,a)}};var I=class extends n{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 E=class extends n{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 S=class extends n{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/automations/webhook-event",{ruleId:e,eventName:t,payload:a})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}};var L=class extends n{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}],r=t.map(o=>({key:`metadata.extra.${o.name}`,label:o.label||o.name,type:o.type||"string",required:!!o.required,options:o.options,group:"Custom Fields"}));return{name:"Lead",fields:[...a,...r],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 r=0;r<e.length;r+=t){let c=e.slice(r,r+t).map(p=>this.create(p)),l=await Promise.allSettled(c);for(let p of l)if(p.status==="fulfilled")a.push(p.value);else throw p.reason}return a}async import(e){return this.post("/api/crm/leads/import",{leads:e})}async bulkUpsert(e){return this.import(e)}async list(e){let t=T({},e);return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/api/crm/leads",{params:t})}listAutoPaging(e){return be(this,null,function*(){let t=(e==null?void 0:e.page)||1,a=!0;for(;a;){let r=yield new ae(this.list(x(T({},e),{page:t}))),o=Array.isArray(r.data)?r.data:r||[];if(o.length===0){a=!1;break}for(let c of o)yield c;r.pagination&&t<r.pagination.pages||!r.pagination&&o.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 byStage(e,t,a={}){return this.get(`/api/crm/pipelines/${e}/stages/${t}/leads`,{params:a})}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 bulkArchive(e){return this.patch("/api/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/api/crm/leads",{data:{ids:e}})}async archive(e){return this.patch(`/api/crm/leads/${e}/archive`,{})}};var q=class extends n{async capture(e){return this.post("/api/crm/payments/capture",e)}};var D=class extends n{async list(){return this.get("/api/crm/pipelines")}async getStageManifest(e){var r,o;let t=await this.retrieve(e),a=Array.isArray((r=t.data)==null?void 0:r.stages)?t.data.stages:[];return{name:`Pipeline: ${((o=t.data)==null?void 0:o.name)||e}`,fields:a.map(c=>({key:c._id,label:c.name,type:"string",required:!0,options:[{label:c.name,value:c._id}],group:"Stages",uiHints:{color:c.color||"#cbd5e1",probability:c.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 checkInUse(e){return this.get(`/api/crm/pipelines/${e}/in-use`)}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 U=class extends n{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 M=class extends n{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 O=class{constructor(e){i(this,"leads");i(this,"pipelines");i(this,"activities");i(this,"analytics");i(this,"automations");i(this,"sequences");i(this,"scoring");i(this,"payments");i(this,"automationDashboard");this.leads=new L(e),this.pipelines=new D(e),this.activities=new $(e),this.analytics=new I(e),this.automations=new S(e),this.sequences=new M(e),this.scoring=new U(e),this.payments=new q(e),this.automationDashboard=new E(e)}};var N=class extends n{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})}async listTemplates(e){return this.get("/api/saas/marketing/mail/templates",{params:e})}async getTemplate(e){return this.get(`/api/saas/marketing/mail/templates/${e}`)}async createTemplate(e){return this.post("/api/saas/marketing/mail/templates",e)}async updateTemplate(e,t){return this.put(`/api/saas/marketing/mail/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/api/saas/marketing/mail/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/api/saas/marketing/mail/templates/${e}/preview`,t)}};var _=class extends n{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/crm/events/emit",e)}};var B=class extends n{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 H=class extends n{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 ie=class extends n{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})}},oe=class extends n{async list(e){return this.get("/api/saas/marketing/emails/campaigns",{params:e})}async stats(e){return this.get(`/api/saas/marketing/emails/campaigns/${e}/analytics`)}},ce=class extends n{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},F=class extends n{constructor(t){super(t);i(this,"emails");i(this,"campaigns");i(this,"whatsapp");this.emails=new ie(t),this.campaigns=new oe(t),this.whatsapp=new ce(t)}};import Ae from"axios";var j=class extends n{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 aiDescribe(e){return this.post("/api/saas/storage/ai/describe",{key:e})}async upload(e,t){let a=await this.post("/api/saas/storage/upload-url",t),{uploadUrl:r,key:o}=a.data;await Ae.put(r,e,{headers:{"Content-Type":t.contentType}});let c=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:o,sizeBytes:c})}};var K=class extends n{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 V=class extends n{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 Q=class extends n{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 pe=class extends n{async list(){return this.get("/api/clients")}async getCountAndGenerateCode(){return this.get("/api/clients/count")}async retrieve(e){return this.get(`/api/clients/${e}`)}async getApiKey(e){return this.get(`/api/clients/${e}/api-key`)}async rotateApiKey(e){return this.post(`/api/clients/${e}/api-key`,{})}async create(e){return this.post("/api/clients",e)}async getConfig(e){return this.get(`/api/clients/${e}/config`)}async updateConfig(e,t){return this.patch(`/api/clients/${e}/config`,t)}async getConnections(e){return this.get(`/api/clients/${e}/connections`)}async getConnectProviders(e){return this.get(`/api/clients/${e}/connections/providers`)}async connectProvider(e,t,a){return this.post(`/api/clients/${e}/connections/${t}/connect`,a)}async configureProvider(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/configure`,a)}async disconnectProvider(e,t){return this.post(`/api/clients/${e}/connections/${t}/disconnect`,{})}async revealConnection(e,t){return this.post(`/api/clients/${e}/connections/${t}/reveal`,{})}async setConnectionAccess(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/access`,a)}async getDataSource(e){return this.get(`/api/clients/${e}/datasource`)}async manageDataSource(e,t){return this.post(`/api/clients/${e}/datasource`,t)}async updateIdentity(e,t){return this.patch(`/api/clients/${e}/identity`,t)}async googleReauth(e,t={}){return this.post(`/api/clients/${e}/google/reauth`,t)}async delete(e){return this.deleteRequest(`/api/clients/${e}`)}},le=class extends n{async list(){return this.get("/api/services/blogs")}},ge=class extends n{async add(e){return this.post("/api/services/add-lead",e)}},J=class extends n{constructor(t){super(t);i(this,"clients");i(this,"blogs");i(this,"globalLeads");this.clients=new pe(t),this.blogs=new le(t),this.globalLeads=new ge(t)}};var ue=class extends n{async getConfig(){return this.get("/api/settings/email")}async switchProvider(e){return this.post("/api/settings/email/provider",{provider:e})}async saveSmtp(e){return this.post("/api/settings/email/smtp",e)}async initDomainVerification(e){return this.post("/api/settings/email/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/api/settings/email/ses/config",e)}async checkSesVerification(){return this.get("/api/settings/email/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/api/settings/email/ses/domain")}async sendTest(e){return this.post("/api/settings/email/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/api/settings/email/advanced",e)}async getHealth(){return this.get("/api/settings/email/health")}async fixDmarc(){return this.post("/api/settings/email/ses/fix-dmarc",{})}async listProviders(){return this.get("/api/settings/email/providers")}},W=class extends n{constructor(t){super(t);i(this,"email");this.email=new ue(t)}};var me=class extends n{async create(e){return this.post("/api/saas/storage/folders",{name:e})}async delete(e){return this.deleteRequest(`/api/saas/storage/folders/${encodeURIComponent(e)}`)}},ye=class extends n{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}})}},G=class extends n{constructor(t){super(t);i(this,"folders");i(this,"files");this.folders=new me(t),this.files=new ye(t)}async usage(){return this.get("/api/saas/storage/usage")}};var P=class extends g{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},z=class{async constructEvent(e,t,a){if(!t)throw new P("No webhook signature provided");let r=Array.isArray(t)?t[0]:t;r.startsWith("sha256=")&&(r=r.slice(7));try{let o=await import("crypto"),l=o.createHmac("sha256",a).update(e).digest("hex");if(!o.timingSafeEqual(Buffer.from(l),Buffer.from(r)))throw new P("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(o){throw o instanceof P?o:new P(`Webhook payload parsing failed: ${o.message}`)}}};var X=class extends n{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 Y=class extends n{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 Z=class extends n{async send(e){return this.post("/api/saas/chat/send",e)}async sendTemplate(e){return this.post("/api/saas/chat/send",x(T({},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 ee=class extends n{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){var o,c;let t=await this.retrieve(e),a=Array.isArray((o=t.data)==null?void 0:o.components)?t.data.components:[],r=[];for(let l of a)if(l.text){let p=l.text.match(/{{(\d+)}}/g);if(p)for(let d of p){let y=d.replace(/{{|}}/g,"");r.push({key:`var_${y}`,label:`${l.type} Var {{${y}}}`,type:"string",required:!0,group:l.type,description:`Variable placeholder in template ${l.type}`})}}return{name:`Template variables: ${((c=t.data)==null?void 0:c.name)||e}`,fields:r,uiHints:{icon:"Variables",primaryColor:"#059669"}}}async checkUsage(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/usage`)}};var te=class extends n{constructor(t){super(t);i(this,"messages");i(this,"conversations");i(this,"broadcasts");i(this,"templates");this.messages=new Z(t),this.conversations=new Y(t),this.broadcasts=new X(t),this.templates=new ee(t)}async upload(t,a){let r=new FormData;return r.append("file",t,a),this.post("/api/saas/chat/upload",r,{headers:typeof r.getHeaders=="function"?r.getHeaders():void 0})}async sendTemplate(t){return this.post("/api/saas/marketing/whatsapp/send-template",t)}};var Ie="https://api.ecodrix.com",w=class{constructor(e){i(this,"client");i(this,"socket",null);i(this,"socketPromise",null);i(this,"socketQueue",[]);i(this,"clientCode");i(this,"whatsapp");i(this,"crm");i(this,"media");i(this,"meet");i(this,"notifications");i(this,"email");i(this,"logs");i(this,"events");i(this,"webhooks");i(this,"storage");i(this,"marketing");i(this,"health");i(this,"queue");i(this,"agency");i(this,"services");i(this,"settings");i(this,"cors");i(this,"checkout");i(this,"connect");var p,d,y,v;if(!e.apiKey)throw new m("API Key is required");this.clientCode=(p=e.clientCode)==null?void 0:p.toUpperCase();let t=(d=e.baseUrl)!=null?d:Ie,a=e.socketUrl||t,r=typeof window!="undefined"&&typeof window.document!="undefined",o=r?"browser":typeof process!="undefined"?`node ${process.version}`:"unknown",c=r?((y=globalThis.navigator)==null?void 0:y.userAgent)||"browser":typeof process!="undefined"?process.platform:"unknown",l={"x-api-key":e.apiKey,"x-client-code":((v=e.clientCode)==null?void 0:v.toUpperCase())||"","Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:"1.0.0",runtime:o,os:c})};if(e.coreApiKey&&(l["x-core-api-key"]=e.coreApiKey),this.client=$e.create({baseURL:t,headers:l}),de(this.client,{retries:3,retryDelay:de.exponentialDelay,retryCondition:h=>{var b;return de.isNetworkOrIdempotentRequestError(h)||((b=h.response)==null?void 0:b.status)===429},onRetry:(h,b,u)=>{var he,Te;typeof process!="undefined"&&((he=process.env)==null?void 0:he.NODE_ENV)==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${h}/3): ${(Te=u.method)==null?void 0:Te.toUpperCase()} ${u.url}. Reason: ${b.message}`)}}),this.whatsapp=new te(this.client),this.crm=new O(this.client),this.media=new j(this.client),this.meet=new K(this.client),this.notifications=new V(this.client),this.email=new N(this.client),this.logs=new H(this.client),this.events=new _(this.client),this.webhooks=new z,this.storage=new G(this.client),this.marketing=new F(this.client),this.health=new B(this.client),this.queue=new Q(this.client),this.agency=new R(this.client),this.services=new J(this.client),this.settings=new W(this.client),this.cors=new A(this.client),this.checkout=new k(this.client),this.connect=new C(this.client),this.initSocket(a,e.apiKey,e.clientCode),r){let h={version:"1.2.2",clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=h,window.ecodrix||(window.ecodrix=this)}}initSocket(e,t,a){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:r})=>{this.socket=r(e,{extraHeaders:{"x-api-key":t,"x-client-code":(a==null?void 0:a.toUpperCase())||""}}),this.setupSocket(a);for(let{type:o,args:c}of this.socketQueue)o==="joinRoom"?this.socket.emit("join-room",c[0]):o==="leaveRoom"?this.socket.emit("leave-room",c[0]):o==="on"?this.socket.on(c[0],c[1]):o==="off"?this.socket.off(c[0],c[1]):o==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){this.socket?this.socket.emit("join-room",e):this.socketQueue.push({type:"joinRoom",args:[e]})}leaveRoom(e){this.socket?this.socket.emit("leave-room",e):this.socketQueue.push({type:"leaveRoom",args:[e]})}setupSocket(e){this.socket&&this.socket.on("connect",()=>{e&&this.socket.emit("join-room",e.toUpperCase())})}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}disconnect(){this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[e,t]}),this}async request(e,t,a,r){var o,c,l;try{return(await this.client.request({method:e,url:t,data:a,params:r})).data}catch(p){throw p.response?new g(((o=p.response.data)==null?void 0:o.message)||((c=p.response.data)==null?void 0:c.error)||"Raw Execution Failed",p.response.status,(l=p.response.data)==null?void 0:l.code):new g(p.message||"Network Error")}}};var Ee={401:m,403:m,429:f};function Hs(s){var e,t,a;if(s.response){let r=s.response.status,o=((e=s.response.data)==null?void 0:e.message)||((t=s.response.data)==null?void 0:t.error)||"API Request Failed",c=(a=s.response.data)==null?void 0:a.code,l=Ee[r]||g;throw l===m?new m(o):l===f?new f(o):new g(o,r,c)}throw new g(s.message||"Network Error")}function Fs(s,e){return s instanceof e}function js(s){return s instanceof m?{message:s.message,status:s.status,code:s.code,type:"AuthenticationError"}:s instanceof f?{message:s.message,status:s.status,code:s.code,type:"RateLimitError"}:s instanceof g?{message:s.message,status:s.status,code:s.code,type:"APIError"}:{message:s.message||"Unknown error",type:"UnknownError"}}var ve={[m.name]:{shouldRetry:!1,reason:"Authentication errors require fixing credentials, not retrying"},[f.name]:{shouldRetry:!0,maxRetries:3,baseDelay:1e3,backoffMultiplier:2,reason:"Rate limit errors can be retried with exponential backoff"},[g.name]:{shouldRetry:!0,maxRetries:2,baseDelay:500,backoffMultiplier:1.5,reason:"Generic API errors may be transient and worth retrying"}};function Ks(s){let e=s.constructor.name;return ve[e]||ve[g.name]}var Js=w;export{g as APIError,m as AuthenticationError,w as ECODrIx,w as ECODrIxAPI,ve as ERROR_RETRY_CONFIG,ne as EcodrixError,Ee as HTTP_STATUS_ERROR_MAP,f as RateLimitError,Js as default,js as getErrorDetails,Ks as getRetryConfig,Hs as handleAPIError,Fs as isAPIError};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecodrix/erix-api",
3
- "version": "1.4.0",
3
+ "version": "1.4.3",
4
4
  "author": "ECODrIx Team <contact@ecodrix.com>",
5
5
  "license": "MIT",
6
6
  "description": "Official Isomorphic SDK for the ECODrIx platform. Native support for WhatsApp, CRM, Storage, and Meetings across TS, JS, Python, and Java.",