@ecodrix/erix-api 1.4.4 → 1.5.1
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 +8 -8
- package/dist/ts/cjs/index.cjs +1 -1
- package/dist/ts/esm/index.d.ts +2402 -23
- package/dist/ts/esm/index.js +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import fe from"repl";import{Command as be}from"commander";import ve from"dotenv";import o from"picocolors";import he from"axios";import pe from"axios-retry";var Z=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},m=class extends Z{status;code;constructor(e,t,a){super(e),this.name="APIError",this.status=t,this.code=a}},d=class extends m{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},f=class extends m{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var n=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 d(a);case 403:throw new d(a);case 429:throw new f(a);default:throw new m(a,t,s)}}throw new m(e.message||"Network Error")}};var b=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 v=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 P=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 x=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 ee=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}`)}},w=class extends n{notes;constructor(e){super(e),this.notes=new ee(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 R=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 C=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 $=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 k=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}],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 p=e.slice(s,s+t).map(g=>this.create(g)),u=await Promise.allSettled(p);for(let g of u)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 p of i)yield p;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 n{async capture(e){return this.post("/api/crm/payments/capture",e)}};var I=class extends n{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 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 E=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 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 R(e),this.automations=new $(e),this.sequences=new E(e),this.scoring=new S(e),this.payments=new A(e),this.automationDashboard=new C(e)}};var L=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 q=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 O=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 M=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 te=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})}},se=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`)}},ae=class extends n{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},N=class extends n{emails;campaigns;whatsapp;constructor(e){super(e),this.emails=new te(e),this.campaigns=new se(e),this.whatsapp=new ae(e)}};import de from"axios";var U=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:s,key:i}=a.data;await de.put(s,e,{headers:{"Content-Type":t.contentType}});let p=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:i,sizeBytes:p})}};var _=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 F=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 B=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 K=class extends n{async list(){return this.get("/api/laie/v1/relays")}async create(e){return this.post("/api/laie/v1/relays",e)}async update(e,t){return this.patch(`/api/laie/v1/relays/${e}`,t)}async delete(e){return this.deleteRequest(`/api/laie/v1/relays/${e}`)}async getConfig(){return this.get("/api/laie/v1/relays/config")}async updateConfig(e){return this.patch("/api/laie/v1/relays/config",e)}async ping(){return this.post("/api/laie/v1/relays/ping")}async provision(e={}){return this.post("/api/laie/v1/relays/provision",e)}async retire(e){return this.post(`/api/laie/v1/relays/${e}/retire`)}};var ne=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}`)}},re=class extends n{async list(){return this.get("/api/services/blogs")}},ie=class extends n{async add(e){return this.post("/api/services/add-lead",e)}},H=class extends n{clients;blogs;globalLeads;constructor(e){super(e),this.clients=new ne(e),this.blogs=new re(e),this.globalLeads=new ie(e)}};var oe=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")}},V=class extends n{email;constructor(e){super(e),this.email=new oe(e)}};var ce=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)}`)}},le=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{folders;files;constructor(e){super(e),this.folders=new ce(e),this.files=new le(e)}async usage(){return this.get("/api/saas/storage/usage")}};var T=class extends m{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},j=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"),u=i.createHmac("sha256",a).update(e).digest("hex");if(!i.timingSafeEqual(Buffer.from(u),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 Q=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 J=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",{...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 G=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){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 p=i.text.match(/{{(\d+)}}/g);if(p)for(let u of p){let g=u.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 z=class extends n{messages;conversations;broadcasts;templates;constructor(e){super(e),this.messages=new Y(e),this.conversations=new J(e),this.broadcasts=new Q(e),this.templates=new G(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 Te="https://api.ecodrix.com",X=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;relays;checkout;connect;constructor(e){if(!e.apiKey)throw new d("API Key is required");this.clientCode=e.clientCode?.toUpperCase();let t=e.baseUrl??Te,a=e.socketUrl||t,s=typeof window<"u"&&typeof window.document<"u",i=s?"browser":typeof process<"u"?`node ${process.version}`:"unknown",p=s?globalThis.navigator?.userAgent||"browser":typeof process<"u"?process.platform:"unknown",u={"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:p})};if(e.coreApiKey&&(u["x-core-api-key"]=e.coreApiKey),this.client=he.create({baseURL:t,headers:u}),pe(this.client,{retries:3,retryDelay:pe.exponentialDelay,retryCondition:g=>pe.isNetworkOrIdempotentRequestError(g)||g.response?.status===429,onRetry:(g,ye,ge)=>{typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${g}/3): ${ge.method?.toUpperCase()} ${ge.url}. Reason: ${ye.message}`)}}),this.whatsapp=new z(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 j,this.storage=new W(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 H(this.client),this.settings=new V(this.client),this.cors=new x(this.client),this.relays=new K(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:p}of this.socketQueue)i==="joinRoom"?this.socket.emit("join-room",p[0]):i==="leaveRoom"?this.socket.emit("leave-room",p[0]):i==="on"?this.socket.on(p[0],p[1]):i==="off"?this.socket.off(p[0],p[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 m(i.response.data?.message||i.response.data?.error||"Raw Execution Failed",i.response.status,i.response.data?.code):new m(i.message||"Network Error")}}};ve.config();var ue="1.4.4";var Pe="Official Isomorphic SDK for the ECODrIx platform. Native support for WhatsApp, CRM, Storage, and Meetings across TS, JS, Python, and Java.",y=new be;y.name("erix").description(Pe).version(ue);function h(r){let e=r.key||process.env.ECOD_API_KEY,t=r.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 X({apiKey:e,clientCode:t,baseUrl:r.baseUrl||process.env.ECOD_BASE_URL})}y.option("-k, --key <key>","ECODrIx API Key").option("-c, --client <code...","Tenant Client Code").option("--base-url <url>","API Base URL override");y.command("whoami").description("Verify current authentication and tenant status").action(async(r,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 xe=y.command("whatsapp").description("WhatsApp Business API operations");xe.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(r,e,t,a)=>{let s=a.parent.parent.opts(),i=h(s);try{let p=JSON.parse(t.vars);console.log(o.cyan(`Sending template '${e}' to ${r}...`));let u=await i.whatsapp.messages.sendTemplate({to:r,templateName:e,language:"en_US",variables:p});console.log(o.green("\u2714 Message sent successfully!")),console.log(o.dim(`ID: ${u?.id||"N/A"}`))}catch(p){console.error(o.red("\u2716 Failed to send message")),console.error(o.dim(p.message))}});var me=y.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(r,e)=>{let t=e.parent.parent.opts(),a=h(t);try{let s=Number.parseInt(r.limit);console.log(o.cyan(`Fetching last ${s} leads...`));let i={limit:s};r.status&&(i.status=r.status),r.pipeline&&(i.pipelineId=r.pipeline),r.search&&(i.search=r.search);let p=await a.crm.leads.list(i),u=Array.isArray(p.data)?p.data:Array.isArray(p)?p:[];if(u.length===0){console.log(o.yellow("No leads found."));return}console.table(u.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(r,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(p=>({ID:p.id||p._id,Name:p.name,Default:p.isDefault?"Yes":"No",Stages:p.stages?.length||0})))}catch(s){console.error(o.red("\u2716 Failed to fetch pipelines")),console.error(o.dim(s.message))}});var we=y.command("analytics").description("Business Intelligence Analytics");we.command("overview").description("Get high-level CRM KPIs").option("-r, --range <range>","Date range (e.g., 24h, 7d, 30d, 365d)","30d").action(async(r,e)=>{let t=e.parent.parent.opts(),a=h(t);try{console.log(o.cyan(`Fetching overview metrics for last ${r.range}...`));let s=await a.crm.analytics.overview({range:r.range}),i=s.data||s;console.log(`
|
|
3
|
-
${
|
|
4
|
-
`)}catch(s){console.error(
|
|
5
|
-
Welcome to the Erix Interactive Shell`))),console.log(
|
|
6
|
-
`));let s=
|
|
7
|
-
Goodbye!`)),process.exit(0)})});
|
|
2
|
+
import Ce from"repl";import{Command as Ae}from"commander";import Ie from"dotenv";import p from"picocolors";import Re from"axios";import be from"axios-retry";var oe=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends oe{status;code;constructor(e,t,n){super(e),this.name="APIError",this.status=t,this.code=n}},y=class extends u{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},T=class extends u{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var a=class{constructor(e){this.client=e}client;async post(e,t,n){try{let s=this.buildConfig(n);return(await this.client.post(e,t,s)).data}catch(s){this.handleError(s)}}async get(e,t){try{let n=this.buildConfig(t);return(await this.client.get(e,n)).data}catch(n){this.handleError(n)}}async patch(e,t,n){try{let s=this.buildConfig(n);return(await this.client.patch(e,t,s)).data}catch(s){this.handleError(s)}}async put(e,t,n){try{let s=this.buildConfig(n);return(await this.client.put(e,t,s)).data}catch(s){this.handleError(s)}}async deleteRequest(e,t){try{let n=this.buildConfig(t);return(await this.client.delete(e,n)).data}catch(n){this.handleError(n)}}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,n=e.response.data?.message||e.response.data?.error||"API Request Failed",s=e.response.data?.code;switch(t){case 401:throw new y(n);case 403:throw new y(n);case 429:throw new T(n);default:throw new u(n,t,s)}}throw new u(e.message||"Network Error")}};var P=class extends a{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 a{async listNichePacks(e={}){return this.get("/api/admin/onboarding/niche-packs",{params:f(e)})}async getNichePack(e,t){let n=t?{version:t}:void 0;return this.get(`/api/admin/onboarding/niche-packs/${encodeURIComponent(e)}`,{params:n})}async createNichePack(e){return this.post("/api/admin/onboarding/niche-packs",e)}async updateNichePack(e,t,n){let s=n?{version:n}:void 0;return this.patch(`/api/admin/onboarding/niche-packs/${encodeURIComponent(e)}`,t,{params:s})}async publishNichePack(e,t){let n=t?{version:t}:void 0;return this.post(`/api/admin/onboarding/niche-packs/${encodeURIComponent(e)}/publish`,void 0,{params:n})}async unpublishNichePack(e,t){let n=t?{version:t}:void 0;return this.post(`/api/admin/onboarding/niche-packs/${encodeURIComponent(e)}/unpublish`,void 0,{params:n})}async forkNichePack(e,t={}){return this.post(`/api/admin/onboarding/niche-packs/${encodeURIComponent(e)}/fork`,t)}async smokeTestNichePack(e,t={},n){let s=n?{version:n}:void 0;return this.post(`/api/admin/onboarding/niche-packs/${encodeURIComponent(e)}/smoke-test`,t,{params:s})}async listOnboardingConfigs(e={}){return this.get("/api/admin/onboarding/configs",{params:f(e)})}async createOnboardingConfig(e){return this.post("/api/admin/onboarding/configs",e)}async updateOnboardingConfig(e,t,n){return this.patch(`/api/admin/onboarding/configs/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async publishOnboardingConfig(e,t){return this.post(`/api/admin/onboarding/configs/${encodeURIComponent(e)}/${encodeURIComponent(t)}/publish`)}async listOnboardingExperiments(e={}){return this.get("/api/admin/onboarding/experiments",{params:f(e)})}async getOnboardingExperiment(e){return this.get(`/api/admin/onboarding/experiments/${encodeURIComponent(e)}`)}async createOnboardingExperiment(e){return this.post("/api/admin/onboarding/experiments",e)}async updateOnboardingExperiment(e,t){return this.patch(`/api/admin/onboarding/experiments/${encodeURIComponent(e)}`,t)}async deleteOnboardingExperiment(e){return this.deleteRequest(`/api/admin/onboarding/experiments/${encodeURIComponent(e)}`)}async getOnboardingFunnel(e={}){return this.get("/api/admin/onboarding/analytics/funnel",{params:f(e)})}async getOnboardingTimeOnStep(e={}){return this.get("/api/admin/onboarding/analytics/time-on-step",{params:f(e)})}async getOnboardingAbandonment(e={}){return this.get("/api/admin/onboarding/analytics/abandonment",{params:f(e)})}};function f(r){let e={};for(let[t,n]of Object.entries(r))n!==void 0&&(e[t]=n);return e}var x=class extends a{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 w=class extends a{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 test(e){return this.post(`/api/connect/v1/connections/${e}/test`,{})}async setAccess(e,t){return this.put(`/api/connect/v1/connections/${e}/access`,t)}async createPaymentLink(e){return this.post("/api/connect/v1/connections/payments/payment-link",e)}};var R=class extends a{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 a{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}`)}},k=class extends a{notes;constructor(e){super(e),this.notes=new ce(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 a{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 A=class extends a{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 I=class extends a{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,n){return this.post("/api/crm/automations/webhook-event",{ruleId:e,eventName:t,payload:n})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}};var $=class extends a{async create(e){return this.post("/api/crm/leads",e)}async describe(){let e=await this.fields(),t=Array.isArray(e.data)?e.data:[],n=[{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:[...n,...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 n=[];for(let s=0;s<e.length;s+=t){let g=e.slice(s,s+t).map(l=>this.create(l)),d=await Promise.allSettled(g);for(let l of d)if(l.status==="fulfilled")n.push(l.value);else throw l.reason}return n}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,n=!0;for(;n;){let s=await this.list({...e,page:t}),i=Array.isArray(s.data)?s.data:s||[];if(i.length===0){n=!1;break}for(let g of i)yield g;s.pagination&&t<s.pagination.pages||!s.pagination&&i.length>0?t++:n=!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,n={}){return this.get(`/api/crm/pipelines/${e}/stages/${t}/leads`,{params:n})}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,n){return this.post(`/api/crm/leads/${e}/convert`,{outcome:t,reason:n})}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,n){return this.patch(`/api/crm/notes/${t}`,n)}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`,{})}async profile(e){return this.get(`/api/crm/leads/${e}/profile`)}async invoices(e){return this.get(`/api/crm/leads/${e}/invoices`)}async projects(e){return this.get(`/api/crm/leads/${e}/projects`)}async conversations(e){return this.get(`/api/crm/leads/${e}/conversations`)}async meetings(e){return this.get(`/api/crm/leads/${e}/meetings`)}async sequences(e){return this.get(`/api/crm/leads/${e}/sequences`)}};var S=class extends a{async capture(e){return this.post("/api/crm/payments/capture",e)}};var O=class extends a{async list(){return this.get("/api/crm/pipelines")}async getStageManifest(e){let t=await this.retrieve(e),n=Array.isArray(t.data?.stages)?t.data.stages:[];return{name:`Pipeline: ${t.data?.name||e}`,fields:n.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 E=class extends a{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 L=class extends a{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 $(e),this.pipelines=new O(e),this.activities=new k(e),this.analytics=new C(e),this.automations=new I(e),this.sequences=new L(e),this.scoring=new E(e),this.payments=new S(e),this.automationDashboard=new A(e)}};var N=class extends a{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 a{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 M=class extends a{async list(e){return this.get("/api/flow/v1/workflows",{params:e})}async create(e){return this.post("/api/flow/v1/workflows",e)}async getWorkflow(e){return this.get(`/api/flow/v1/workflows/${e}`)}async update(e,t){return this.put(`/api/flow/v1/workflows/${e}`,t)}async run(e,t){return this.post(`/api/flow/v1/workflows/${e}/run`,t??{})}async getRun(e){return this.get(`/api/flow/v1/runs/${e}`)}async getRunRecords(e){return this.get(`/api/flow/v1/runs/${e}/records`)}async retry(e){return this.post(`/api/flow/v1/runs/${e}/retry`,{})}async approve(e,t){return this.post(`/api/flow/v1/runs/${e}/approve`,t)}async getRunLogs(e){return this.get(`/api/flow/v1/runs/${e}/logs`)}async templates(e){return this.get("/api/flow/v1/templates",{params:e})}async installTemplate(e,t){return this.post(`/api/flow/v1/templates/${e}/install`,t??{})}};var U=class extends a{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 _=class extends a{async list(e){return this.get("/api/saas/invoices",{params:e})}async getInvoice(e){return this.get(`/api/saas/invoices/${e}`)}async create(e){return this.post("/api/saas/invoices",e)}async update(e,t){return this.patch(`/api/saas/invoices/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/invoices/${e}`)}async sendViaWhatsApp(e){return this.post(`/api/saas/invoices/${e}/send-whatsapp`,{})}async getSettings(){return this.get("/api/saas/invoice-settings")}async updateSettings(e){return this.patch("/api/saas/invoice-settings",e)}};var F=class extends a{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 a{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 a{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`)}},le=class extends a{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},B=class extends a{emails;campaigns;whatsapp;constructor(e){super(e),this.emails=new pe(e),this.campaigns=new ge(e),this.whatsapp=new le(e)}};import we from"axios";var V=class extends a{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 n=await this.post("/api/saas/storage/upload-url",t),{uploadUrl:s,key:i}=n.data;await we.put(s,e,{headers:{"Content-Type":t.contentType}});let g=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:i,sizeBytes:g})}};var j=class extends a{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 a{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 W=class extends a{async global(e){return this.post("/api/onboarding/global",e)}async start(e){return this.post("/api/onboarding/start",e)}async answer(e){return this.post("/api/onboarding/answer",e)}async state(e){return this.get("/api/onboarding/state",{params:{productId:e}})}async complete(e){return this.post("/api/onboarding/complete",e)}async edit(e){return this.post("/api/onboarding/edit",e)}async previewWorkspace(e){return this.get("/api/onboarding/preview-workspace",{params:{sessionId:e}})}};var H=class extends a{async get(e){return super.get(`/api/persona/${e}`)}async reinforce(e){return this.post("/api/persona/reinforce",e)}async confidence(e){return super.get("/api/persona/confidence",{params:{productId:e}})}async timeline(e,t){return(await super.get(`/api/persona/${e}/timeline`,{params:t}))?.data??{entries:[],hasMore:!1}}async followups(e){return(await super.get(`/api/persona/${e}/followups`))?.data?.entries??[]}};var Q=class extends a{async conversations(){return this.get("/api/saas/portal-inbox/conversations")}async messages(e){return this.get(`/api/saas/portal-inbox/conversations/${e}/messages`)}async reply(e,t){return this.post(`/api/saas/portal-inbox/conversations/${e}/messages`,t)}};var z=class extends a{async list(e){return this.get(`/api/saas/projects/${e}/documents`)}async upload(e,t){return this.post(`/api/saas/projects/${e}/documents`,t)}async toggleSignature(e,t,n){return this.patch(`/api/saas/projects/${e}/documents/${t}/signature`,{required:n})}async addSigner(e,t,n){return this.post(`/api/saas/projects/${e}/documents/${t}/signers`,n)}async sign(e,t,n){return this.post(`/api/saas/projects/${e}/documents/${t}/sign`,n??{})}async decline(e,t){return this.post(`/api/saas/projects/${e}/documents/${t}/decline`,{})}async stampSign(e,t,n){return this.post(`/api/saas/projects/${e}/documents/${t}/stamp-sign`,n)}};var J=class extends a{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 Y=class extends a{async list(){return this.get("/api/laie/v1/relays")}async create(e){return this.post("/api/laie/v1/relays",e)}async update(e,t){return this.patch(`/api/laie/v1/relays/${e}`,t)}async delete(e){return this.deleteRequest(`/api/laie/v1/relays/${e}`)}async getConfig(){return this.get("/api/laie/v1/relays/config")}async updateConfig(e){return this.patch("/api/laie/v1/relays/config",e)}async ping(){return this.post("/api/laie/v1/relays/ping")}async provision(e={}){return this.post("/api/laie/v1/relays/provision",e)}async retire(e){return this.post(`/api/laie/v1/relays/${e}/retire`)}};var de=class extends a{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,n){return this.post(`/api/clients/${e}/connections/${t}/connect`,n)}async configureProvider(e,t,n){return this.put(`/api/clients/${e}/connections/${t}/configure`,n)}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,n){return this.put(`/api/clients/${e}/connections/${t}/access`,n)}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}`)}},ue=class extends a{async list(){return this.get("/api/services/blogs")}},me=class extends a{async add(e){return this.post("/api/services/add-lead",e)}},G=class extends a{clients;blogs;globalLeads;constructor(e){super(e),this.clients=new de(e),this.blogs=new ue(e),this.globalLeads=new me(e)}};var ye=class extends a{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 a{email;constructor(e){super(e),this.email=new ye(e)}};var he=class extends a{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 a{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 a{folders;files;constructor(e){super(e),this.folders=new he(e),this.files=new fe(e)}async usage(){return this.get("/api/saas/storage/usage")}};var b=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},ee=class{async constructEvent(e,t,n){if(!t)throw new b("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"),d=i.createHmac("sha256",n).update(e).digest("hex");if(!i.timingSafeEqual(Buffer.from(d),Buffer.from(s)))throw new b("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(i){throw i instanceof b?i:new b(`Webhook payload parsing failed: ${i.message}`)}}};var te=class extends a{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 ne=class extends a{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,n){return this.post(`/api/saas/chat/conversations/${e}/link-lead`,{leadId:t,leadData:n})}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 a{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 ae=class extends a{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),n=Array.isArray(t.data?.components)?t.data.components:[],s=[];for(let i of n)if(i.text){let g=i.text.match(/{{(\d+)}}/g);if(g)for(let d of g){let l=d.replace(/{{|}}/g,"");s.push({key:`var_${l}`,label:`${i.type} Var {{${l}}}`,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 re=class extends a{messages;conversations;broadcasts;templates;constructor(e){super(e),this.messages=new se(e),this.conversations=new ne(e),this.broadcasts=new te(e),this.templates=new ae(e)}async upload(e,t){let n=new FormData;return n.append("file",e,t),this.post("/api/saas/chat/upload",n,{headers:typeof n.getHeaders=="function"?n.getHeaders():void 0})}async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}};var ke="https://api.ecodrix.com",ie=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;relays;checkout;connect;onboarding;adminOnboarding;persona;flow;portalInbox;projectDocuments;invoices;constructor(e){if(!e.apiKey)throw new y("API Key is required");this.clientCode=e.clientCode?.toUpperCase();let t=e.baseUrl??ke,n=e.socketUrl||t,s=typeof window<"u"&&typeof window.document<"u",i=s?"browser":typeof process<"u"?`node ${process.version}`:"unknown",g=s?globalThis.navigator?.userAgent||"browser":typeof process<"u"?process.platform:"unknown",d={"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:g})};if(e.coreApiKey&&(d["x-core-api-key"]=e.coreApiKey),this.client=Re.create({baseURL:t,headers:d}),be(this.client,{retries:3,retryDelay:be.exponentialDelay,retryCondition:l=>be.isNetworkOrIdempotentRequestError(l)||l.response?.status===429,onRetry:(l,xe,Te)=>{typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${l}/3): ${Te.method?.toUpperCase()} ${Te.url}. Reason: ${xe.message}`)}}),this.whatsapp=new re(this.client),this.crm=new D(this.client),this.media=new V(this.client),this.meet=new j(this.client),this.notifications=new K(this.client),this.email=new N(this.client),this.logs=new F(this.client),this.events=new q(this.client),this.webhooks=new ee,this.storage=new Z(this.client),this.marketing=new B(this.client),this.health=new U(this.client),this.queue=new J(this.client),this.agency=new P(this.client),this.services=new G(this.client),this.settings=new X(this.client),this.cors=new R(this.client),this.relays=new Y(this.client),this.checkout=new x(this.client),this.connect=new w(this.client),this.onboarding=new W(this.client),this.adminOnboarding=new v(this.client),this.persona=new H(this.client),this.flow=new M(this.client),this.portalInbox=new Q(this.client),this.projectDocuments=new z(this.client),this.invoices=new _(this.client),this.initSocket(n,e.apiKey,e.clientCode),s){let l={version:"1.2.2",clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=l,window.ecodrix||(window.ecodrix=this)}}initSocket(e,t,n){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":n?.toUpperCase()||""}}),this.setupSocket(n);for(let{type:i,args:g}of this.socketQueue)i==="joinRoom"?this.socket.emit("join-room",g[0]):i==="leaveRoom"?this.socket.emit("leave-room",g[0]):i==="on"?this.socket.on(g[0],g[1]):i==="off"?this.socket.off(g[0],g[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,n,s){try{return(await this.client.request({method:e,url:t,data:n,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")}}};Ie.config();var Pe="1.5.1";var $e="Official Isomorphic SDK for the ECODrIx platform. Native support for WhatsApp, CRM, Storage, and Meetings across TS, JS, Python, and Java.",m=new Ae;m.name("erix").description($e).version(Pe);function h(r){let e=r.key||process.env.ECOD_API_KEY,t=r.client||process.env.ECOD_CLIENT_CODE;return e||(console.error(p.red("Error: API Key is missing.")),console.log(p.yellow("Set ECOD_API_KEY environment variable or use --key <key>")),process.exit(1)),new ie({apiKey:e,clientCode:t,baseUrl:r.baseUrl||process.env.ECOD_BASE_URL})}m.option("-k, --key <key>","ECODrIx API Key").option("-c, --client <code...","Tenant Client Code").option("--base-url <url>","API Base URL override");m.command("whoami").description("Verify current authentication and tenant status").action(async(r,e)=>{let t=e.parent.opts(),n=h(t);console.log(p.cyan("Checking connection to ECODrIx Platform..."));try{let s=await n.request("GET","/api/saas/me/profile");console.log(p.green("\u2714 Authenticated successfully!")),console.log(`${p.bold("User ID:")} ${s.id}`),console.log(`${p.bold("Organisation:")} ${s.organisation?.name||"N/A"}`),t.client&&console.log(`${p.bold("Tenant Code:")} ${p.magenta(t.client)}`)}catch(s){console.error(p.red("\u2716 Authentication failed")),console.error(p.dim(s.message)),process.exit(1)}});var Se=m.command("whatsapp").description("WhatsApp Business API operations");Se.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(r,e,t,n)=>{let s=n.parent.parent.opts(),i=h(s);try{let g=JSON.parse(t.vars);console.log(p.cyan(`Sending template '${e}' to ${r}...`));let d=await i.whatsapp.messages.sendTemplate({to:r,templateName:e,language:"en_US",variables:g});console.log(p.green("\u2714 Message sent successfully!")),console.log(p.dim(`ID: ${d?.id||"N/A"}`))}catch(g){console.error(p.red("\u2716 Failed to send message")),console.error(p.dim(g.message))}});var ve=m.command("crm").description("CRM and Lead management");ve.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(r,e)=>{let t=e.parent.parent.opts(),n=h(t);try{let s=Number.parseInt(r.limit);console.log(p.cyan(`Fetching last ${s} leads...`));let i={limit:s};r.status&&(i.status=r.status),r.pipeline&&(i.pipelineId=r.pipeline),r.search&&(i.search=r.search);let g=await n.crm.leads.list(i),d=Array.isArray(g.data)?g.data:Array.isArray(g)?g:[];if(d.length===0){console.log(p.yellow("No leads found."));return}console.table(d.map(l=>({ID:l.id||l._id,Name:`${l.firstName} ${l.lastName||""}`.trim(),Phone:l.phone,Status:l.status,Score:l.score||0,Created:new Date(l.createdAt).toLocaleDateString()})))}catch(s){console.error(p.red("\u2716 Failed to fetch leads")),console.error(p.dim(s.message))}});ve.command("pipelines").description("List all CRM pipelines").action(async(r,e)=>{let t=e.parent.parent.opts(),n=h(t);try{console.log(p.cyan("Fetching pipelines..."));let s=await n.crm.pipelines.list(),i=s.data||s||[];if(i.length===0){console.log(p.yellow("No pipelines found."));return}console.table(i.map(g=>({ID:g.id||g._id,Name:g.name,Default:g.isDefault?"Yes":"No",Stages:g.stages?.length||0})))}catch(s){console.error(p.red("\u2716 Failed to fetch pipelines")),console.error(p.dim(s.message))}});var Oe=m.command("analytics").description("Business Intelligence Analytics");Oe.command("overview").description("Get high-level CRM KPIs").option("-r, --range <range>","Date range (e.g., 24h, 7d, 30d, 365d)","30d").action(async(r,e)=>{let t=e.parent.parent.opts(),n=h(t);try{console.log(p.cyan(`Fetching overview metrics for last ${r.range}...`));let s=await n.crm.analytics.overview({range:r.range}),i=s.data||s;console.log(`
|
|
3
|
+
${p.bold("OVERVIEW KPIs:")}`),console.log(`Total Leads: ${p.green(i.totalLeads||0)}`),console.log(`Open Value: ${p.yellow(`$${(i.openValue||0).toLocaleString()}`)}`),console.log(`Won Revenue: ${p.green(`$${(i.wonRevenue||0).toLocaleString()}`)}`),console.log(`Avg Score: ${p.blue(i.avgScore?.toFixed(1)||0)}`),console.log(`Conversion: ${p.magenta(`${(i.conversionRate||0).toFixed(2)}%`)}
|
|
4
|
+
`)}catch(s){console.error(p.red("\u2716 Failed to fetch analytics overview")),console.error(p.dim(s.message))}});var Ee=m.command("webhooks").description("Webhook utility tools");Ee.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(r,e,t,n,s)=>{let i=s.parent.parent.opts(),g=h(i);try{await g.webhooks.constructEvent(r,e,t),console.log(p.green("\u2714 Signature is VALID"))}catch(d){console.error(p.red("\u2716 Error during verification")),console.error(p.dim(d.message))}});m.command("shell").alias("repl").description("Start an interactive SDK shell").action(async(r,e)=>{let t=e.parent.opts(),n=h(t);console.log(p.magenta(p.bold(`
|
|
5
|
+
Welcome to the Erix Interactive Shell`))),console.log(p.dim(`SDK Version: ${Pe}`)),console.log(p.dim(`The 'ecod' client is pre-initialized and ready.
|
|
6
|
+
`));let s=Ce.start({prompt:p.cyan("erix > "),useColors:!0});s.context.ecod=n,s.context.whatsapp=n.whatsapp,s.context.crm=n.crm,s.context.meet=n.meet,s.context.media=n.media,s.on("exit",()=>{console.log(p.yellow(`
|
|
7
|
+
Goodbye!`)),process.exit(0)})});m.command("completion").description("Generate Bash auto-completion script").action(()=>{console.log(`
|
|
8
8
|
# Erix Bash Completion
|
|
9
9
|
_erix_completions() {
|
|
10
10
|
local cur opts
|
|
@@ -34,5 +34,5 @@ _erix_completions() {
|
|
|
34
34
|
esac
|
|
35
35
|
}
|
|
36
36
|
complete -F _erix_completions erix
|
|
37
|
-
`.trim()),console.error(
|
|
38
|
-
# To enable, run: eval "$(erix completion)"`)),console.error(
|
|
37
|
+
`.trim()),console.error(p.yellow(`
|
|
38
|
+
# To enable, run: eval "$(erix completion)"`)),console.error(p.dim("# Or add it to your ~/.bashrc: erix completion >> ~/.bashrc"))});m.parse();
|
package/dist/ts/cjs/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Ee=Object.create;var k=Object.defineProperty,Se=Object.defineProperties,qe=Object.getOwnPropertyDescriptor,Le=Object.getOwnPropertyDescriptors,De=Object.getOwnPropertyNames,Re=Object.getOwnPropertySymbols,Me=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty,Ue=Object.prototype.propertyIsEnumerable;var Oe=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var ce=(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)&&ce(s,t,e[t]);if(Re)for(var t of Re(e))Ue.call(e,t)&&ce(s,t,e[t]);return s},R=(s,e)=>Se(s,Le(e));var Ne=(s,e)=>{for(var t in e)k(s,t,{get:e[t],enumerable:!0})},ke=(s,e,t,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of De(e))!we.call(s,r)&&r!==t&&k(s,r,{get:()=>e[r],enumerable:!(a=qe(e,r))||a.enumerable});return s};var C=(s,e,t)=>(t=s!=null?Ee(Me(s)):{},ke(e||!s||!s.__esModule?k(t,"default",{value:s,enumerable:!0}):t,s)),_e=s=>ke(k({},"__esModule",{value:!0}),s);var i=(s,e,t)=>ce(s,typeof e!="symbol"?e+"":e,t);var pe=function(s,e){this[0]=s,this[1]=e},Ce=(s,e,t)=>{var a=(g,l,h,d)=>{try{var v=t[g](l),T=(l=v.value)instanceof pe,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[Oe("asyncIterator")]=()=>c,r("next"),r("throw"),r("return"),c};var Qe={};Ne(Qe,{APIError:()=>u,AuthenticationError:()=>y,ECODrIx:()=>P,ECODrIxAPI:()=>P,ERROR_RETRY_CONFIG:()=>xe,EcodrixError:()=>$,HTTP_STATUS_ERROR_MAP:()=>Ie,RateLimitError:()=>f,Relays:()=>A,default:()=>Ve,getErrorDetails:()=>je,getRetryConfig:()=>Ke,handleAPIError:()=>Fe,isAPIError:()=>Be});module.exports=_e(Qe);var $e=C(require("axios"),1),oe=C(require("axios-retry"),1);var $=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends ${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=R(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 I=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 E=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 S=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 q=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 le=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}`)}},L=class extends n{constructor(t){super(t);i(this,"notes");this.notes=new le(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 D=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 M=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 U=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 O=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 Ce(this,null,function*(){let t=(e==null?void 0:e.page)||1,a=!0;for(;a;){let r=yield new pe(this.list(R(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 N=class extends n{async capture(e){return this.post("/api/crm/payments/capture",e)}};var _=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 H=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 O(e),this.pipelines=new _(e),this.activities=new L(e),this.analytics=new D(e),this.automations=new U(e),this.sequences=new F(e),this.scoring=new H(e),this.payments=new N(e),this.automationDashboard=new M(e)}};var j=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 K=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 V=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 Q=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 ge=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})}},ue=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`)}},me=class extends n{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},J=class extends n{constructor(t){super(t);i(this,"emails");i(this,"campaigns");i(this,"whatsapp");this.emails=new ge(t),this.campaigns=new ue(t),this.whatsapp=new me(t)}};var Ae=C(require("axios"),1);var W=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.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 z=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 G=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 X=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 A=class extends n{async list(){return this.get("/api/laie/v1/relays")}async create(e){return this.post("/api/laie/v1/relays",e)}async update(e,t){return this.patch(`/api/laie/v1/relays/${e}`,t)}async delete(e){return this.deleteRequest(`/api/laie/v1/relays/${e}`)}async getConfig(){return this.get("/api/laie/v1/relays/config")}async updateConfig(e){return this.patch("/api/laie/v1/relays/config",e)}async ping(){return this.post("/api/laie/v1/relays/ping")}async provision(e={}){return this.post("/api/laie/v1/relays/provision",e)}async retire(e){return this.post(`/api/laie/v1/relays/${e}/retire`)}};var ye=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}`)}},de=class extends n{async list(){return this.get("/api/services/blogs")}},he=class extends n{async add(e){return this.post("/api/services/add-lead",e)}},Y=class extends n{constructor(t){super(t);i(this,"clients");i(this,"blogs");i(this,"globalLeads");this.clients=new ye(t),this.blogs=new de(t),this.globalLeads=new he(t)}};var Te=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")}},Z=class extends n{constructor(t){super(t);i(this,"email");this.email=new Te(t)}};var fe=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)}`)}},be=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}})}},ee=class extends n{constructor(t){super(t);i(this,"folders");i(this,"files");this.folders=new fe(t),this.files=new be(t)}async usage(){return this.get("/api/saas/storage/usage")}};var w=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},te=class{async constructEvent(e,t,a){if(!t)throw new w("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 w("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(o){throw o instanceof w?o:new w(`Webhook payload parsing failed: ${o.message}`)}}};var se=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 ae=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 ne=class extends n{async send(e){return this.post("/api/saas/chat/send",e)}async sendTemplate(e){return this.post("/api/saas/chat/send",R(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 re=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 ie=class extends n{constructor(t){super(t);i(this,"messages");i(this,"conversations");i(this,"broadcasts");i(this,"templates");this.messages=new ne(t),this.conversations=new ae(t),this.broadcasts=new se(t),this.templates=new re(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 He="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,"relays");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:He,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=$e.default.create({baseURL:t,headers:g}),(0,oe.default)(this.client,{retries:3,retryDelay:oe.default.exponentialDelay,retryCondition:T=>{var x;return oe.default.isNetworkOrIdempotentRequestError(T)||((x=T.response)==null?void 0:x.status)===429},onRetry:(T,x,m)=>{var ve,Pe;typeof process!="undefined"&&((ve=process.env)==null?void 0:ve.NODE_ENV)==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${T}/3): ${(Pe=m.method)==null?void 0:Pe.toUpperCase()} ${m.url}. Reason: ${x.message}`)}}),this.whatsapp=new ie(this.client),this.crm=new B(this.client),this.media=new W(this.client),this.meet=new z(this.client),this.notifications=new G(this.client),this.email=new j(this.client),this.logs=new Q(this.client),this.events=new K(this.client),this.webhooks=new te,this.storage=new ee(this.client),this.marketing=new J(this.client),this.health=new V(this.client),this.queue=new X(this.client),this.agency=new I(this.client),this.services=new Y(this.client),this.settings=new Z(this.client),this.cors=new q(this.client),this.relays=new A(this.client),this.checkout=new E(this.client),this.connect=new S(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 Ie={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=Ie[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 je(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 xe={[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 Ke(s){let e=s.constructor.name;return xe[e]||xe[u.name]}var Ve=P;0&&(module.exports={APIError,AuthenticationError,ECODrIx,ECODrIxAPI,ERROR_RETRY_CONFIG,EcodrixError,HTTP_STATUS_ERROR_MAP,RateLimitError,Relays,getErrorDetails,getRetryConfig,handleAPIError,isAPIError});
|
|
1
|
+
"use strict";var Ue=Object.create;var L=Object.defineProperty,Be=Object.defineProperties,_e=Object.getOwnPropertyDescriptor,Ve=Object.getOwnPropertyDescriptors,je=Object.getOwnPropertyNames,Ee=Object.getOwnPropertySymbols,He=Object.getPrototypeOf,$e=Object.prototype.hasOwnProperty,We=Object.prototype.propertyIsEnumerable;var Ke=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n);var fe=(n,e,t)=>e in n?L(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,T=(n,e)=>{for(var t in e||(e={}))$e.call(e,t)&&fe(n,t,e[t]);if(Ee)for(var t of Ee(e))We.call(e,t)&&fe(n,t,e[t]);return n},k=(n,e)=>Be(n,Ve(e));var ze=(n,e)=>{for(var t in e)L(n,t,{get:e[t],enumerable:!0})},Le=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of je(e))!$e.call(n,a)&&a!==t&&L(n,a,{get:()=>e[a],enumerable:!(s=_e(e,a))||s.enumerable});return n};var D=(n,e,t)=>(t=n!=null?Ue(He(n)):{},Le(e||!n||!n.__esModule?L(t,"default",{value:n,enumerable:!0}):t,n)),Qe=n=>Le(L({},"__esModule",{value:!0}),n);var i=(n,e,t)=>fe(n,typeof e!="symbol"?e+"":e,t);var he=function(n,e){this[0]=n,this[1]=e},De=(n,e,t)=>{var s=(l,g,f,y)=>{try{var P=t[l](g),h=(g=P.value)instanceof he,x=P.done;Promise.resolve(h?g[0]:g).then(u=>h?s(l==="return"?l:"next",g[1]?{done:u.done,value:u.value}:u,f,y):f({value:u,done:x})).catch(u=>s("throw",u,f,y))}catch(u){y(u)}},a=(l,g,f,y)=>p[l]=P=>(g=new Promise((h,x,u)=>(u=()=>s(l,P,h,x),o?o.then(u):u())),y=()=>o===f&&(o=0),o=f=g.then(y,y),g),o,p={};return t=t.apply(n,e),p[Ke("asyncIterator")]=()=>p,a("next"),a("throw"),a("return"),p};var tt={};ze(tt,{APIError:()=>d,AdminOnboarding:()=>w,AuthenticationError:()=>m,ECODrIx:()=>R,ECODrIxAPI:()=>R,ERROR_RETRY_CONFIG:()=>Ie,EcodrixError:()=>F,Flow:()=>C,HTTP_STATUS_ERROR_MAP:()=>Me,Invoices:()=>A,LEAD_STATUS_VALUES:()=>Ne,Onboarding:()=>I,Persona:()=>O,PortalInbox:()=>S,ProjectDocuments:()=>E,RateLimitError:()=>b,Relays:()=>N,default:()=>et,getErrorDetails:()=>Xe,getRetryConfig:()=>Ze,handleAPIError:()=>Je,isAPIError:()=>Ye});module.exports=Qe(tt);var qe=D(require("axios"),1),ye=D(require("axios-retry"),1);var F=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},d=class extends F{constructor(t,s,a){super(t);i(this,"status");i(this,"code");this.name="APIError",this.status=s,this.code=a}},m=class extends d{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},b=class extends d{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,s){try{let a=this.buildConfig(s);return(await this.client.post(e,t,a)).data}catch(a){this.handleError(a)}}async get(e,t){try{let s=this.buildConfig(t);return(await this.client.get(e,s)).data}catch(s){this.handleError(s)}}async patch(e,t,s){try{let a=this.buildConfig(s);return(await this.client.patch(e,t,a)).data}catch(a){this.handleError(a)}}async put(e,t,s){try{let a=this.buildConfig(s);return(await this.client.put(e,t,a)).data}catch(a){this.handleError(a)}}async deleteRequest(e,t){try{let s=this.buildConfig(t);return(await this.client.delete(e,s)).data}catch(s){this.handleError(s)}}buildConfig(e){if(!e)return;let t=T({},e);return e.idempotencyKey&&(t.headers=k(T({},t.headers),{"Idempotency-Key":e.idempotencyKey})),t}handleError(e){var t,s,a;if(e.response){let o=e.response.status,p=((t=e.response.data)==null?void 0:t.message)||((s=e.response.data)==null?void 0:s.error)||"API Request Failed",l=(a=e.response.data)==null?void 0:a.code;switch(o){case 401:throw new m(p);case 403:throw new m(p);case 429:throw new b(p);default:throw new d(p,o,l)}}throw new d(e.message||"Network Error")}};var q=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 w=class extends r{async listNichePacks(e={}){return this.get("/api/admin/onboarding/niche-packs",{params:v(e)})}async getNichePack(e,t){let s=t?{version:t}:void 0;return this.get(`/api/admin/onboarding/niche-packs/${encodeURIComponent(e)}`,{params:s})}async createNichePack(e){return this.post("/api/admin/onboarding/niche-packs",e)}async updateNichePack(e,t,s){let a=s?{version:s}:void 0;return this.patch(`/api/admin/onboarding/niche-packs/${encodeURIComponent(e)}`,t,{params:a})}async publishNichePack(e,t){let s=t?{version:t}:void 0;return this.post(`/api/admin/onboarding/niche-packs/${encodeURIComponent(e)}/publish`,void 0,{params:s})}async unpublishNichePack(e,t){let s=t?{version:t}:void 0;return this.post(`/api/admin/onboarding/niche-packs/${encodeURIComponent(e)}/unpublish`,void 0,{params:s})}async forkNichePack(e,t={}){return this.post(`/api/admin/onboarding/niche-packs/${encodeURIComponent(e)}/fork`,t)}async smokeTestNichePack(e,t={},s){let a=s?{version:s}:void 0;return this.post(`/api/admin/onboarding/niche-packs/${encodeURIComponent(e)}/smoke-test`,t,{params:a})}async listOnboardingConfigs(e={}){return this.get("/api/admin/onboarding/configs",{params:v(e)})}async createOnboardingConfig(e){return this.post("/api/admin/onboarding/configs",e)}async updateOnboardingConfig(e,t,s){return this.patch(`/api/admin/onboarding/configs/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,s)}async publishOnboardingConfig(e,t){return this.post(`/api/admin/onboarding/configs/${encodeURIComponent(e)}/${encodeURIComponent(t)}/publish`)}async listOnboardingExperiments(e={}){return this.get("/api/admin/onboarding/experiments",{params:v(e)})}async getOnboardingExperiment(e){return this.get(`/api/admin/onboarding/experiments/${encodeURIComponent(e)}`)}async createOnboardingExperiment(e){return this.post("/api/admin/onboarding/experiments",e)}async updateOnboardingExperiment(e,t){return this.patch(`/api/admin/onboarding/experiments/${encodeURIComponent(e)}`,t)}async deleteOnboardingExperiment(e){return this.deleteRequest(`/api/admin/onboarding/experiments/${encodeURIComponent(e)}`)}async getOnboardingFunnel(e={}){return this.get("/api/admin/onboarding/analytics/funnel",{params:v(e)})}async getOnboardingTimeOnStep(e={}){return this.get("/api/admin/onboarding/analytics/time-on-step",{params:v(e)})}async getOnboardingAbandonment(e={}){return this.get("/api/admin/onboarding/analytics/abandonment",{params:v(e)})}};function v(n){let e={};for(let[t,s]of Object.entries(n))s!==void 0&&(e[t]=s);return e}var M=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 U=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 test(e){return this.post(`/api/connect/v1/connections/${e}/test`,{})}async setAccess(e,t){return this.put(`/api/connect/v1/connections/${e}/access`,t)}async createPaymentLink(e){return this.post("/api/connect/v1/connections/payments/payment-link",e)}};var B=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 be=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}`)}},_=class extends r{constructor(t){super(t);i(this,"notes");this.notes=new be(t)}async timeline(t,s){return this.get(`/api/crm/leads/${t}/timeline`,{params:s})}async list(t,s){return this.get(`/api/crm/leads/${t}/activities`,{params:T({},s)})}async log(t){return this.post(`/api/crm/leads/${t.leadId}/activities`,t)}async logCall(t,s){return this.post(`/api/crm/leads/${t}/calls`,s)}};var V=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 j=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 H=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,s){return this.post("/api/crm/automations/webhook-event",{ruleId:e,eventName:t,payload:s})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}};var Ne=["open","won","lost","archived"],W=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:[],s=[{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}],a=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:[...s,...a],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 s=[];for(let a=0;a<e.length;a+=t){let p=e.slice(a,a+t).map(g=>this.create(g)),l=await Promise.allSettled(p);for(let g of l)if(g.status==="fulfilled")s.push(g.value);else throw g.reason}return s}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 De(this,null,function*(){let t=(e==null?void 0:e.page)||1,s=!0;for(;s;){let a=yield new he(this.list(k(T({},e),{page:t}))),o=Array.isArray(a.data)?a.data:a||[];if(o.length===0){s=!1;break}for(let p of o)yield p;a.pagination&&t<a.pagination.pages||!a.pagination&&o.length>0?t++:s=!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,s={}){return this.get(`/api/crm/pipelines/${e}/stages/${t}/leads`,{params:s})}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,s){return this.post(`/api/crm/leads/${e}/convert`,{outcome:t,reason:s})}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,s){return this.patch(`/api/crm/notes/${t}`,s)}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`,{})}async profile(e){return this.get(`/api/crm/leads/${e}/profile`)}async invoices(e){return this.get(`/api/crm/leads/${e}/invoices`)}async projects(e){return this.get(`/api/crm/leads/${e}/projects`)}async conversations(e){return this.get(`/api/crm/leads/${e}/conversations`)}async meetings(e){return this.get(`/api/crm/leads/${e}/meetings`)}async sequences(e){return this.get(`/api/crm/leads/${e}/sequences`)}};var K=class extends r{async capture(e){return this.post("/api/crm/payments/capture",e)}};var z=class extends r{async list(){return this.get("/api/crm/pipelines")}async getStageManifest(e){var a,o;let t=await this.retrieve(e),s=Array.isArray((a=t.data)==null?void 0:a.stages)?t.data.stages:[];return{name:`Pipeline: ${((o=t.data)==null?void 0:o.name)||e}`,fields:s.map(p=>({key:p._id,label:p.name,type:"string",required:!0,options:[{label:p.name,value:p._id}],group:"Stages",uiHints:{color:p.color||"#cbd5e1",probability:p.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 Q=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 G=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 J=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 W(e),this.pipelines=new z(e),this.activities=new _(e),this.analytics=new V(e),this.automations=new H(e),this.sequences=new G(e),this.scoring=new Q(e),this.payments=new K(e),this.automationDashboard=new j(e)}};var Y=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 X=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 C=class extends r{async list(e){return this.get("/api/flow/v1/workflows",{params:e})}async create(e){return this.post("/api/flow/v1/workflows",e)}async getWorkflow(e){return this.get(`/api/flow/v1/workflows/${e}`)}async update(e,t){return this.put(`/api/flow/v1/workflows/${e}`,t)}async run(e,t){return this.post(`/api/flow/v1/workflows/${e}/run`,t!=null?t:{})}async getRun(e){return this.get(`/api/flow/v1/runs/${e}`)}async getRunRecords(e){return this.get(`/api/flow/v1/runs/${e}/records`)}async retry(e){return this.post(`/api/flow/v1/runs/${e}/retry`,{})}async approve(e,t){return this.post(`/api/flow/v1/runs/${e}/approve`,t)}async getRunLogs(e){return this.get(`/api/flow/v1/runs/${e}/logs`)}async templates(e){return this.get("/api/flow/v1/templates",{params:e})}async installTemplate(e,t){return this.post(`/api/flow/v1/templates/${e}/install`,t!=null?t:{})}};var Z=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 A=class extends r{async list(e){return this.get("/api/saas/invoices",{params:e})}async getInvoice(e){return this.get(`/api/saas/invoices/${e}`)}async create(e){return this.post("/api/saas/invoices",e)}async update(e,t){return this.patch(`/api/saas/invoices/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/invoices/${e}`)}async sendViaWhatsApp(e){return this.post(`/api/saas/invoices/${e}/send-whatsapp`,{})}async getSettings(){return this.get("/api/saas/invoice-settings")}async updateSettings(e){return this.patch("/api/saas/invoice-settings",e)}};var ee=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 Te=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})}},xe=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`)}},Pe=class extends r{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},te=class extends r{constructor(t){super(t);i(this,"emails");i(this,"campaigns");i(this,"whatsapp");this.emails=new Te(t),this.campaigns=new xe(t),this.whatsapp=new Pe(t)}};var Fe=D(require("axios"),1);var ne=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 s=await this.post("/api/saas/storage/upload-url",t),{uploadUrl:a,key:o}=s.data;await Fe.default.put(a,e,{headers:{"Content-Type":t.contentType}});let p=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:o,sizeBytes:p})}};var se=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 re=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 I=class extends r{async global(e){return this.post("/api/onboarding/global",e)}async start(e){return this.post("/api/onboarding/start",e)}async answer(e){return this.post("/api/onboarding/answer",e)}async state(e){return this.get("/api/onboarding/state",{params:{productId:e}})}async complete(e){return this.post("/api/onboarding/complete",e)}async edit(e){return this.post("/api/onboarding/edit",e)}async previewWorkspace(e){return this.get("/api/onboarding/preview-workspace",{params:{sessionId:e}})}};var O=class extends r{async get(e){return super.get(`/api/persona/${e}`)}async reinforce(e){return this.post("/api/persona/reinforce",e)}async confidence(e){return super.get("/api/persona/confidence",{params:{productId:e}})}async timeline(e,t){var a;let s=await super.get(`/api/persona/${e}/timeline`,{params:t});return(a=s==null?void 0:s.data)!=null?a:{entries:[],hasMore:!1}}async followups(e){var s,a;let t=await super.get(`/api/persona/${e}/followups`);return(a=(s=t==null?void 0:t.data)==null?void 0:s.entries)!=null?a:[]}};var S=class extends r{async conversations(){return this.get("/api/saas/portal-inbox/conversations")}async messages(e){return this.get(`/api/saas/portal-inbox/conversations/${e}/messages`)}async reply(e,t){return this.post(`/api/saas/portal-inbox/conversations/${e}/messages`,t)}};var E=class extends r{async list(e){return this.get(`/api/saas/projects/${e}/documents`)}async upload(e,t){return this.post(`/api/saas/projects/${e}/documents`,t)}async toggleSignature(e,t,s){return this.patch(`/api/saas/projects/${e}/documents/${t}/signature`,{required:s})}async addSigner(e,t,s){return this.post(`/api/saas/projects/${e}/documents/${t}/signers`,s)}async sign(e,t,s){return this.post(`/api/saas/projects/${e}/documents/${t}/sign`,s!=null?s:{})}async decline(e,t){return this.post(`/api/saas/projects/${e}/documents/${t}/decline`,{})}async stampSign(e,t,s){return this.post(`/api/saas/projects/${e}/documents/${t}/stamp-sign`,s)}};var ae=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 N=class extends r{async list(){return this.get("/api/laie/v1/relays")}async create(e){return this.post("/api/laie/v1/relays",e)}async update(e,t){return this.patch(`/api/laie/v1/relays/${e}`,t)}async delete(e){return this.deleteRequest(`/api/laie/v1/relays/${e}`)}async getConfig(){return this.get("/api/laie/v1/relays/config")}async updateConfig(e){return this.patch("/api/laie/v1/relays/config",e)}async ping(){return this.post("/api/laie/v1/relays/ping")}async provision(e={}){return this.post("/api/laie/v1/relays/provision",e)}async retire(e){return this.post(`/api/laie/v1/relays/${e}/retire`)}};var Re=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,s){return this.post(`/api/clients/${e}/connections/${t}/connect`,s)}async configureProvider(e,t,s){return this.put(`/api/clients/${e}/connections/${t}/configure`,s)}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,s){return this.put(`/api/clients/${e}/connections/${t}/access`,s)}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}`)}},ke=class extends r{async list(){return this.get("/api/services/blogs")}},ve=class extends r{async add(e){return this.post("/api/services/add-lead",e)}},ie=class extends r{constructor(t){super(t);i(this,"clients");i(this,"blogs");i(this,"globalLeads");this.clients=new Re(t),this.blogs=new ke(t),this.globalLeads=new ve(t)}};var we=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")}},oe=class extends r{constructor(t){super(t);i(this,"email");this.email=new we(t)}};var Ce=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)}`)}},Ae=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}})}},ce=class extends r{constructor(t){super(t);i(this,"folders");i(this,"files");this.folders=new Ce(t),this.files=new Ae(t)}async usage(){return this.get("/api/saas/storage/usage")}};var $=class extends d{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},pe=class{async constructEvent(e,t,s){if(!t)throw new $("No webhook signature provided");let a=Array.isArray(t)?t[0]:t;a.startsWith("sha256=")&&(a=a.slice(7));try{let o=await import("crypto"),l=o.createHmac("sha256",s).update(e).digest("hex");if(!o.timingSafeEqual(Buffer.from(l),Buffer.from(a)))throw new $("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(o){throw o instanceof $?o:new $(`Webhook payload parsing failed: ${o.message}`)}}};var ge=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 le=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,s){return this.post(`/api/saas/chat/conversations/${e}/link-lead`,{leadId:t,leadData:s})}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 de=class extends r{async send(e){return this.post("/api/saas/chat/send",e)}async sendTemplate(e){return this.post("/api/saas/chat/send",k(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 ue=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,p;let t=await this.retrieve(e),s=Array.isArray((o=t.data)==null?void 0:o.components)?t.data.components:[],a=[];for(let l of s)if(l.text){let g=l.text.match(/{{(\d+)}}/g);if(g)for(let f of g){let y=f.replace(/{{|}}/g,"");a.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: ${((p=t.data)==null?void 0:p.name)||e}`,fields:a,uiHints:{icon:"Variables",primaryColor:"#059669"}}}async checkUsage(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/usage`)}};var me=class extends r{constructor(t){super(t);i(this,"messages");i(this,"conversations");i(this,"broadcasts");i(this,"templates");this.messages=new de(t),this.conversations=new le(t),this.broadcasts=new ge(t),this.templates=new ue(t)}async upload(t,s){let a=new FormData;return a.append("file",t,s),this.post("/api/saas/chat/upload",a,{headers:typeof a.getHeaders=="function"?a.getHeaders():void 0})}async sendTemplate(t){return this.post("/api/saas/marketing/whatsapp/send-template",t)}};var Ge="https://api.ecodrix.com",R=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,"relays");i(this,"checkout");i(this,"connect");i(this,"onboarding");i(this,"adminOnboarding");i(this,"persona");i(this,"flow");i(this,"portalInbox");i(this,"projectDocuments");i(this,"invoices");var g,f,y,P;if(!e.apiKey)throw new m("API Key is required");this.clientCode=(g=e.clientCode)==null?void 0:g.toUpperCase();let t=(f=e.baseUrl)!=null?f:Ge,s=e.socketUrl||t,a=typeof window!="undefined"&&typeof window.document!="undefined",o=a?"browser":typeof process!="undefined"?`node ${process.version}`:"unknown",p=a?((y=globalThis.navigator)==null?void 0:y.userAgent)||"browser":typeof process!="undefined"?process.platform:"unknown",l={"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:p})};if(e.coreApiKey&&(l["x-core-api-key"]=e.coreApiKey),this.client=qe.default.create({baseURL:t,headers:l}),(0,ye.default)(this.client,{retries:3,retryDelay:ye.default.exponentialDelay,retryCondition:h=>{var x;return ye.default.isNetworkOrIdempotentRequestError(h)||((x=h.response)==null?void 0:x.status)===429},onRetry:(h,x,u)=>{var Oe,Se;typeof process!="undefined"&&((Oe=process.env)==null?void 0:Oe.NODE_ENV)==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${h}/3): ${(Se=u.method)==null?void 0:Se.toUpperCase()} ${u.url}. Reason: ${x.message}`)}}),this.whatsapp=new me(this.client),this.crm=new J(this.client),this.media=new ne(this.client),this.meet=new se(this.client),this.notifications=new re(this.client),this.email=new Y(this.client),this.logs=new ee(this.client),this.events=new X(this.client),this.webhooks=new pe,this.storage=new ce(this.client),this.marketing=new te(this.client),this.health=new Z(this.client),this.queue=new ae(this.client),this.agency=new q(this.client),this.services=new ie(this.client),this.settings=new oe(this.client),this.cors=new B(this.client),this.relays=new N(this.client),this.checkout=new M(this.client),this.connect=new U(this.client),this.onboarding=new I(this.client),this.adminOnboarding=new w(this.client),this.persona=new O(this.client),this.flow=new C(this.client),this.portalInbox=new S(this.client),this.projectDocuments=new E(this.client),this.invoices=new A(this.client),this.initSocket(s,e.apiKey,e.clientCode),a){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,s){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:a})=>{this.socket=a(e,{extraHeaders:{"x-api-key":t,"x-client-code":(s==null?void 0:s.toUpperCase())||""}}),this.setupSocket(s);for(let{type:o,args:p}of this.socketQueue)o==="joinRoom"?this.socket.emit("join-room",p[0]):o==="leaveRoom"?this.socket.emit("leave-room",p[0]):o==="on"?this.socket.on(p[0],p[1]):o==="off"?this.socket.off(p[0],p[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,s,a){var o,p,l;try{return(await this.client.request({method:e,url:t,data:s,params:a})).data}catch(g){throw g.response?new d(((o=g.response.data)==null?void 0:o.message)||((p=g.response.data)==null?void 0:p.error)||"Raw Execution Failed",g.response.status,(l=g.response.data)==null?void 0:l.code):new d(g.message||"Network Error")}}};var Me={401:m,403:m,429:b};function Je(n){var e,t,s;if(n.response){let a=n.response.status,o=((e=n.response.data)==null?void 0:e.message)||((t=n.response.data)==null?void 0:t.error)||"API Request Failed",p=(s=n.response.data)==null?void 0:s.code,l=Me[a]||d;throw l===m?new m(o):l===b?new b(o):new d(o,a,p)}throw new d(n.message||"Network Error")}function Ye(n,e){return n instanceof e}function Xe(n){return n instanceof m?{message:n.message,status:n.status,code:n.code,type:"AuthenticationError"}:n instanceof b?{message:n.message,status:n.status,code:n.code,type:"RateLimitError"}:n instanceof d?{message:n.message,status:n.status,code:n.code,type:"APIError"}:{message:n.message||"Unknown error",type:"UnknownError"}}var Ie={[m.name]:{shouldRetry:!1,reason:"Authentication errors require fixing credentials, not retrying"},[b.name]:{shouldRetry:!0,maxRetries:3,baseDelay:1e3,backoffMultiplier:2,reason:"Rate limit errors can be retried with exponential backoff"},[d.name]:{shouldRetry:!0,maxRetries:2,baseDelay:500,backoffMultiplier:1.5,reason:"Generic API errors may be transient and worth retrying"}};function Ze(n){let e=n.constructor.name;return Ie[e]||Ie[d.name]}var et=R;0&&(module.exports={APIError,AdminOnboarding,AuthenticationError,ECODrIx,ECODrIxAPI,ERROR_RETRY_CONFIG,EcodrixError,Flow,HTTP_STATUS_ERROR_MAP,Invoices,LEAD_STATUS_VALUES,Onboarding,Persona,PortalInbox,ProjectDocuments,RateLimitError,Relays,getErrorDetails,getRetryConfig,handleAPIError,isAPIError});
|