@dashnex/cli 0.5.32 → 0.5.34

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.
@@ -1 +1 @@
1
- import e from"inquirer";import t from"chalk";import{debug as o,debugError as s}from"../../lib/debug.js";import{getBusinessApiBase as a}from"../../lib/api.js";import{ensureLoggedIn as i}from"../../services/auth.js";import{createSpinner as r}from"../../lib/spinner.js";import{isUserInterrupt as n,INTERRUPTED_MESSAGE as l}from"../../lib/errors.js";import{PullCommand as c}from"./pull.js";const p=e=>Array.isArray(e.message)&&e.message.length>0?e.message.join("\n"):"string"==typeof e.message?e.message:"string"==typeof e.error?e.error:void 0,u=e=>new Promise(t=>setTimeout(t,e));class d{async pollApplicationCreated(e,t,a=5e3,i=6e4){const r=Date.now();let n=0;for(;Date.now()-r<i;){n++,o(`Polling application status (attempt ${n})...`);try{const s=await fetch(e,{headers:{Authorization:`Bearer ${t}`}});if(o(`Poll response: ${s.status}`),200===s.status){const e=await s.json();if(o(`Poll response body status: ${e.status}`),"creating"!==e.status)return o(`Application status is "${e.status}", creation complete`),{ready:!0,status:e.status};o('Application status is still "creating", continuing to poll...')}}catch(l){s(l),o(`Poll attempt ${n} failed with network error`)}await u(a)}return{ready:!1}}async execute(u={}){o("Create flow started");const d=await i();if(!d)return;o("Auth valid, checking if business already has application");const h=r(),m=`${a()}/business/v1/applications`;o(`GET ${m}`),h.start("Checking application status...");try{const e=await fetch(m,{headers:{Authorization:`Bearer ${d.token}`}});h.stop(),o(`Applications response: ${e.status}`);const s=await e.text();o(`Applications response body: ${s}`),404!==e.status&&(console.error(t.red("Business already has an application. Run 'dashnex app pull' to pull the existing one.")),process.exit(1))}catch(k){if(h.stop(),s(k),k instanceof Error&&k.message.startsWith("EXIT:"))throw k;if(n(k))return void console.log(t.yellow(l));console.error(t.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}let f;o("No existing application, proceeding to subdomain prompt");const g=e=>`${a()}/business/v1/applications/check-subdomain?subdomain=${encodeURIComponent(e)}`,y=void 0!==u.subdomain;let b=u.subdomain?.trim();for(;;){if(b)f=b,b=void 0,o(`Subdomain provided via flag: ${f}`);else{if(y)return console.error(t.red("Subdomain is not available.")),void process.exit(1);{const{sub:t}=await e.prompt([{type:"input",name:"sub",message:"Pick your subdomain:",validate:e=>!!e.trim()||"Subdomain is required"}]);f=t.trim()}}o(`Checking subdomain: ${f}`);const a=g(f);o(`GET ${a}`),h.start("Checking subdomain...");try{const e=await fetch(a,{headers:{Authorization:`Bearer ${d.token}`}});h.stop(),o(`Check subdomain response: ${e.status}`);const s=await e.text();if(o(`Check subdomain response body: ${s}`),!e.ok){const a=e.headers.get("content-type")??"";let i="Failed to check subdomain availability.";if(401!==e.status&&403!==e.status||(i="Please run 'dashnex login' to authenticate.",console.error(t.red(i)),process.exit(1)),a.includes("application/json")){const e=JSON.parse(s);o(`Check subdomain error body: ${JSON.stringify(e)}`);const t=p(e);t&&(i=t)}console.error(t.red(i));continue}const i=JSON.parse(s);if(o(`Check subdomain parsed body: ${JSON.stringify(i)}`),i.available){o(`Subdomain ${f} is available`);break}console.error(t.red("Subdomain is not available. Please choose a different one."))}catch(k){if(h.stop(),s(k),k instanceof Error&&k.message.startsWith("EXIT:"))throw k;if(n(k))return void console.log(t.yellow(l));console.error(t.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}const w=`${a()}/business/v1/cli/create`;o(`POST ${w}`);const $={subdomain:f};u.template&&($.template=u.template,o(`Template: ${u.template}`));const x=JSON.stringify($);o(`Create request body: ${x}`),h.start("Creating application...");try{const i=await fetch(w,{method:"POST",headers:{Authorization:`Bearer ${d.token}`,"Content-Type":"application/json"},body:x});h.stop(),o(`Create response: ${i.status}`);const r=await i.text();if(o(`Create response body: ${r}`),503===i.status){o("Create returned 503, polling for application creation..."),console.log(t.yellow("Application is being created, please wait..."));const e=`${a()}/business/v1/applications`,s=await this.pollApplicationCreated(e,d.token);s.ready||(console.error(t.red("Application creation is taking longer than expected. Try again later or run 'dashnex app pull' to check.")),process.exit(1)),"failed"===s.status&&(console.error(t.red("Application creation failed. Please try again.")),process.exit(1)),o("Application found after polling")}else if(!i.ok){const e=i.headers.get("content-type")??"";let s="Failed to create application.";if(401===i.status||403===i.status)s="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e=JSON.parse(r);o(`Create error body parsed: ${JSON.stringify(e)}`);const t=p(e);t&&(s=t)}console.error(t.red(s)),process.exit(1)}let u;if(o("Application created successfully"),y)u=!1,o("CI mode (--subdomain), skipping pull");else{u=(await e.prompt([{type:"confirm",name:"pull",message:"Pull the application locally?",default:!0}])).pull,o(`User chose to pull: ${u}`)}if(u){o("Running pull flow");try{const e=new c;await e.execute()}catch(k){if(s(k),k instanceof Error&&k.message.startsWith("EXIT:"))throw k;if(n(k))return void console.log(t.yellow(l));console.error(t.red("Failed to pull application."))}}else console.log(t.green("Application is created successfully. Run 'dashnex app pull' to pull it to your computer or 'dashnex app deploy' to deploy it to the cloud."))}catch(k){if(h.stop(),s(k),k instanceof Error&&k.message.startsWith("EXIT:"))throw k;if(n(k))return void console.log(t.yellow(l));console.error(t.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}}export{d as CreateCommand};
1
+ import e from"inquirer";import t from"chalk";import{debug as o,debugError as s}from"../../lib/debug.js";import{getBusinessApiBase as a}from"../../lib/api.js";import{ensureLoggedIn as i}from"../../services/auth.js";import{createSpinner as r}from"../../lib/spinner.js";import{isUserInterrupt as n,INTERRUPTED_MESSAGE as l}from"../../lib/errors.js";import{PullCommand as c}from"./pull.js";import{ensureAgreements as p}from"../../services/agreements.js";const u=e=>Array.isArray(e.message)&&e.message.length>0?e.message.join("\n"):"string"==typeof e.message?e.message:"string"==typeof e.error?e.error:void 0,d=e=>new Promise(t=>setTimeout(t,e));class m{async pollApplicationCreated(e,t,a=5e3,i=6e4){const r=Date.now();let n=0;for(;Date.now()-r<i;){n++,o(`Polling application status (attempt ${n})...`);try{const s=await fetch(e,{headers:{Authorization:`Bearer ${t}`}});if(o(`Poll response: ${s.status}`),200===s.status){const e=await s.json();if(o(`Poll response body status: ${e.status}`),"creating"!==e.status)return o(`Application status is "${e.status}", creation complete`),{ready:!0,status:e.status};o('Application status is still "creating", continuing to poll...')}}catch(l){s(l),o(`Poll attempt ${n} failed with network error`)}await d(a)}return{ready:!1}}async execute(d={}){o("Create flow started");const m=await i();if(!m)return;o("Auth valid, checking if business already has application");const h=r(),f=`${a()}/business/v1/applications`;o(`GET ${f}`),h.start("Checking application status...");try{const e=await fetch(f,{headers:{Authorization:`Bearer ${m.token}`}});h.stop(),o(`Applications response: ${e.status}`);const s=await e.text();o(`Applications response body: ${s}`),404!==e.status&&(console.error(t.red("Business already has an application. Run 'dashnex app pull' to pull the existing one.")),process.exit(1))}catch(C){if(h.stop(),s(C),C instanceof Error&&C.message.startsWith("EXIT:"))throw C;if(n(C))return void console.log(t.yellow(l));console.error(t.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}o("No existing application, checking agreements");const g=void 0!==d.subdomain;if(!(await p(m.token,{ciMode:g})))return;let y;o("Agreements checked, proceeding to subdomain prompt");const b=e=>`${a()}/business/v1/applications/check-subdomain?subdomain=${encodeURIComponent(e)}`;let w=d.subdomain?.trim();for(;;){if(w)y=w,w=void 0,o(`Subdomain provided via flag: ${y}`);else{if(g)return console.error(t.red("Subdomain is not available.")),void process.exit(1);{const{sub:t}=await e.prompt([{type:"input",name:"sub",message:"Pick your subdomain:",validate:e=>!!e.trim()||"Subdomain is required"}]);y=t.trim()}}o(`Checking subdomain: ${y}`);const a=b(y);o(`GET ${a}`),h.start("Checking subdomain...");try{const e=await fetch(a,{headers:{Authorization:`Bearer ${m.token}`}});h.stop(),o(`Check subdomain response: ${e.status}`);const s=await e.text();if(o(`Check subdomain response body: ${s}`),!e.ok){const a=e.headers.get("content-type")??"";let i="Failed to check subdomain availability.";if(401!==e.status&&403!==e.status||(i="Please run 'dashnex login' to authenticate.",console.error(t.red(i)),process.exit(1)),a.includes("application/json")){const e=JSON.parse(s);o(`Check subdomain error body: ${JSON.stringify(e)}`);const t=u(e);t&&(i=t)}console.error(t.red(i));continue}const i=JSON.parse(s);if(o(`Check subdomain parsed body: ${JSON.stringify(i)}`),i.available){o(`Subdomain ${y} is available`);break}console.error(t.red("Subdomain is not available. Please choose a different one."))}catch(C){if(h.stop(),s(C),C instanceof Error&&C.message.startsWith("EXIT:"))throw C;if(n(C))return void console.log(t.yellow(l));console.error(t.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}const $=`${a()}/business/v1/cli/create`;o(`POST ${$}`);const k={subdomain:y};d.template&&(k.template=d.template,o(`Template: ${d.template}`));const x=JSON.stringify(k);o(`Create request body: ${x}`),h.start("Creating application...");try{const i=await fetch($,{method:"POST",headers:{Authorization:`Bearer ${m.token}`,"Content-Type":"application/json"},body:x});h.stop(),o(`Create response: ${i.status}`);const r=await i.text();if(o(`Create response body: ${r}`),503===i.status){o("Create returned 503, polling for application creation..."),console.log(t.yellow("Application is being created, please wait..."));const e=`${a()}/business/v1/applications`,s=await this.pollApplicationCreated(e,m.token);s.ready||(console.error(t.red("Application creation is taking longer than expected. Try again later or run 'dashnex app pull' to check.")),process.exit(1)),"failed"===s.status&&(console.error(t.red("Application creation failed. Please try again.")),process.exit(1)),o("Application found after polling")}else if(!i.ok){const e=i.headers.get("content-type")??"";let s="Failed to create application.";if(401===i.status||403===i.status)s="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e=JSON.parse(r);o(`Create error body parsed: ${JSON.stringify(e)}`);const t=u(e);t&&(s=t)}console.error(t.red(s)),process.exit(1)}let p;if(o("Application created successfully"),g)p=!1,o("CI mode (--subdomain), skipping pull");else{p=(await e.prompt([{type:"confirm",name:"pull",message:"Pull the application locally?",default:!0}])).pull,o(`User chose to pull: ${p}`)}if(p){o("Running pull flow");try{const e=new c;await e.execute()}catch(C){if(s(C),C instanceof Error&&C.message.startsWith("EXIT:"))throw C;if(n(C))return void console.log(t.yellow(l));console.error(t.red("Failed to pull application."))}}else console.log(t.green("Application is created successfully. Run 'dashnex app pull' to pull it to your computer or 'dashnex app deploy' to deploy it to the cloud."))}catch(C){if(h.stop(),s(C),C instanceof Error&&C.message.startsWith("EXIT:"))throw C;if(n(C))return void console.log(t.yellow(l));console.error(t.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}}export{m as CreateCommand};
@@ -1 +1 @@
1
- import e from"chalk";import{debug as t,debugError as o}from"../../lib/debug.js";import{getDeployerBase as s,getBusinessApiBase as r}from"../../lib/api.js";import{ensureLoggedIn as n}from"../../services/auth.js";import{createSpinner as a}from"../../lib/spinner.js";import{isUserInterrupt as i,INTERRUPTED_MESSAGE as c}from"../../lib/errors.js";import{getApplicationUrl as l}from"../../lib/app-url.js";const p=3e5,d=99,m=e=>new Promise(t=>setTimeout(t,e)),f=async(s,r,n,a)=>{const i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"text/event-stream"}});if(t(`SSE connection opened: ${i.status}`),!i.ok){const t=i.status;let o="Failed to start deployment.";if(401===t||403===t)o="Please run 'dashnex login' to authenticate.";else try{const e=await i.text(),t=JSON.parse(e);"string"==typeof t.error?o=t.error:"string"==typeof t.message&&(o=t.message)}catch{}throw console.error(e.red(o)),new Error(`HTTP ${t}: ${o}`)}if(!i.body)throw new Error("Response body is null");t("SSE connection established successfully"),a?.();const c=i.body.getReader();try{for await(const e of async function*(e){const t=new TextDecoder("utf-8");let o="";for(;;){const{value:s,done:r}=await e.read();if(r)break;o+=t.decode(s,{stream:!0});const n=o.split("\n");o=n.pop()||"";let a="";for(const e of n)e.startsWith("data: ")?a=e.slice(6):""===e&&a&&(yield{data:a},a="")}if(o.startsWith("data: ")){const e=o.slice(6);e&&(yield{data:e})}}(c))try{if(!e.data){t("Received empty SSE event");continue}const o=JSON.parse(e.data);t(`SSE message received: ${JSON.stringify(o)}`),n(o)}catch(l){o(l),t(`Failed to parse SSE event data: ${e.data}`)}}finally{c.releaseLock()}};class u{async execute(){t("Deploy flow started");const r=await n();if(!r)return;const l=`${s()}/business/v1/applications/deploy`;t(`GET ${l} (SSE)`);let u=0,y="",h=!1,g=0,w=!1;const S=a();let $=0,b=0,v=null;const x=(e,t)=>{const o=Math.round(e);S.text(`[${o}%] ${t}`)},E=()=>{D();const e=u,t=Date.now(),o=p*((d-e)/d);v=setInterval(()=>{const s=Date.now()-t;let r;if(b>t){const e=Date.now()-b,t=d-$,o=t*3030.3030303030305;r=Math.min($+e/o*t,d)}else r=Math.min(e+s/o*(d-e),d);r>u&&(u=r,x(u,y))},200)},D=()=>{v&&(clearInterval(v),v=null)};let T=!1;const k=t=>{if(w=!0,"string"==typeof t.error)return D(),S.stop(),console.error(e.red(t.error)),h=!0,void(T=!0);if("string"==typeof t.message&&(y=t.message),"number"==typeof t.progress&&($=t.progress,b=Date.now(),t.progress>u&&(u=t.progress)),"string"==typeof t.message||"number"==typeof t.progress)if(u>=100){D(),S.stop();const t=y||"Application is deployed";process.stdout.write(`${e.green(t)}\n`),h=!0}else x(u,y)};for(;g<=5;)try{return w?x(u,y):S.start("Connecting..."),E(),await f(l,r.token,k,()=>{w||(S.text(`[${Math.round(u)}%] Deployment in progress...`),y="Deployment in progress...")}),D(),S.stop(),t("SSE connection closed"),T&&process.exit(1),void(h&&await this.showDeployedUrl(r.token))}catch(j){if(D(),o(j),t(`SSE connection error: ${j}`),h)return S.stop(),void(T&&process.exit(1));if(i(j))return S.stop(),void console.log(e.yellow(c));j instanceof Error&&j.message.startsWith("HTTP")&&(S.stop(),console.error(e.red("Could not complete deployment. Check your connection and try again.")),process.exit(1)),g++,g>5&&(S.stop(),console.error(e.red("Deployment failed. Maximum reconnection attempts exceeded.")),process.exit(1));const s=Math.min(1e3*Math.pow(2,g-1),3e4);t(`Connection error. Reconnecting in ${s/1e3}s... (attempt ${g}/5)`),await m(s)}}async showDeployedUrl(s){try{const o=`${r()}/business/v1/applications`;t(`GET ${o} (for deployed URL)`);const n=await fetch(o,{headers:{Authorization:`Bearer ${s}`}});if(!n.ok)return;const a=await n.json().catch(()=>({})),i=l({subdomain:a.subdomain,appFullCustomDomain:a.appFullCustomDomain});i&&console.log(`Application is deployed to ${e.cyan(i)}`)}catch(n){o(n)}}}export{u as DeployCommand};
1
+ import e from"chalk";import{debug as t,debugError as o}from"../../lib/debug.js";import{getDeployerBase as s,getBusinessApiBase as r}from"../../lib/api.js";import{ensureLoggedIn as n}from"../../services/auth.js";import{createSpinner as a}from"../../lib/spinner.js";import{isUserInterrupt as i,INTERRUPTED_MESSAGE as c}from"../../lib/errors.js";import{getApplicationUrl as l}from"../../lib/app-url.js";import{ensureAgreements as p}from"../../services/agreements.js";const d=3e5,m=99,f=e=>new Promise(t=>setTimeout(t,e)),u=async(s,r,n,a)=>{const i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"text/event-stream"}});if(t(`SSE connection opened: ${i.status}`),!i.ok){const t=i.status;let o="Failed to start deployment.";if(401===t||403===t)o="Please run 'dashnex login' to authenticate.";else try{const e=await i.text(),t=JSON.parse(e);"string"==typeof t.error?o=t.error:"string"==typeof t.message&&(o=t.message)}catch{}throw console.error(e.red(o)),new Error(`HTTP ${t}: ${o}`)}if(!i.body)throw new Error("Response body is null");t("SSE connection established successfully"),a?.();const c=i.body.getReader();try{for await(const e of async function*(e){const t=new TextDecoder("utf-8");let o="";for(;;){const{value:s,done:r}=await e.read();if(r)break;o+=t.decode(s,{stream:!0});const n=o.split("\n");o=n.pop()||"";let a="";for(const e of n)e.startsWith("data: ")?a=e.slice(6):""===e&&a&&(yield{data:a},a="")}if(o.startsWith("data: ")){const e=o.slice(6);e&&(yield{data:e})}}(c))try{if(!e.data){t("Received empty SSE event");continue}const o=JSON.parse(e.data);t(`SSE message received: ${JSON.stringify(o)}`),n(o)}catch(l){o(l),t(`Failed to parse SSE event data: ${e.data}`)}}finally{c.releaseLock()}};class y{async execute(){t("Deploy flow started");const r=await n();if(!r)return;if(!(await p(r.token,{ciMode:!0})))return;const l=`${s()}/business/v1/applications/deploy`;t(`GET ${l} (SSE)`);let y=0,h="",g=!1,w=0,S=!1;const $=a();let b=0,v=0,x=null;const E=(e,t)=>{const o=Math.round(e);$.text(`[${o}%] ${t}`)},D=()=>{k();const e=y,t=Date.now(),o=d*((m-e)/m);x=setInterval(()=>{const s=Date.now()-t;let r;if(v>t){const e=Date.now()-v,t=m-b,o=t*3030.3030303030305;r=Math.min(b+e/o*t,m)}else r=Math.min(e+s/o*(m-e),m);r>y&&(y=r,E(y,h))},200)},k=()=>{x&&(clearInterval(x),x=null)};let T=!1;const j=t=>{if(S=!0,"string"==typeof t.error)return k(),$.stop(),console.error(e.red(t.error)),g=!0,void(T=!0);if("string"==typeof t.message&&(h=t.message),"number"==typeof t.progress&&(b=t.progress,v=Date.now(),t.progress>y&&(y=t.progress)),"string"==typeof t.message||"number"==typeof t.progress)if(y>=100){k(),$.stop();const t=h||"Application is deployed";process.stdout.write(`${e.green(t)}\n`),g=!0}else E(y,h)};for(;w<=5;)try{return S?E(y,h):$.start("Connecting..."),D(),await u(l,r.token,j,()=>{S||($.text(`[${Math.round(y)}%] Deployment in progress...`),h="Deployment in progress...")}),k(),$.stop(),t("SSE connection closed"),T&&process.exit(1),void(g&&await this.showDeployedUrl(r.token))}catch(M){if(k(),o(M),t(`SSE connection error: ${M}`),g)return $.stop(),void(T&&process.exit(1));if(i(M))return $.stop(),void console.log(e.yellow(c));M instanceof Error&&M.message.startsWith("HTTP")&&($.stop(),console.error(e.red("Could not complete deployment. Check your connection and try again.")),process.exit(1)),w++,w>5&&($.stop(),console.error(e.red("Deployment failed. Maximum reconnection attempts exceeded.")),process.exit(1));const s=Math.min(1e3*Math.pow(2,w-1),3e4);t(`Connection error. Reconnecting in ${s/1e3}s... (attempt ${w}/5)`),await f(s)}}async showDeployedUrl(s){try{const o=`${r()}/business/v1/applications`;t(`GET ${o} (for deployed URL)`);const n=await fetch(o,{headers:{Authorization:`Bearer ${s}`}});if(!n.ok)return;const a=await n.json().catch(()=>({})),i=l({subdomain:a.subdomain,appFullCustomDomain:a.appFullCustomDomain});i&&console.log(`Application is deployed to ${e.cyan(i)}`)}catch(n){o(n)}}}export{y as DeployCommand};
@@ -1 +1 @@
1
- import e from"inquirer";import s from"chalk";import r from"fs-extra";import o from"path";import{debug as t,debugJson as n,debugError as i}from"../lib/debug.js";import{getApiBase as a,apiFetch as d}from"../lib/api.js";import{ensureLoggedIn as l}from"../services/auth.js";import{createSpinner as c}from"../lib/spinner.js";import{isUserInterrupt as u,INTERRUPTED_MESSAGE as p}from"../lib/errors.js";const m=(e,r,o)=>{const t=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(r);let n=o;429===e.status?n="Too many requests. Please wait a moment and try again.":e.status>=500?n="DashNex API is temporarily unavailable. Please try again later.":t&&(n=t),console.error(s.red(n)),process.exit(1)};class h{async execute(r={}){t("Login flow started");const h=process.cwd(),f=o.join(h,".dashnex"),g=await l({exitOnFailure:!1,dashnexPath:f});if(g)console.log(s.green(`Already logged in as ${g.userName??"user"}`));else try{let o,l;if(r.email&&r.password)o=r.email.trim(),l=r.password,t("Email and password provided via flags");else{const{username:s,password:r}=await e.prompt([{type:"input",name:"username",message:"Email:",validate:e=>!!e.trim()||"Email is required"},{type:"password",name:"password",message:"Password:",mask:"*",validate:e=>!!e||"Password is required"}]);o=s.trim(),l=r}t("Email provided");const u=c();u.start("Logging in..."),t(`POST ${a()}/auth/v1/login`);const{response:p,body:h}=await d(`${a()}/auth/v1/login`,{method:"POST",body:JSON.stringify({username:o,password:l})});u.stop(),t(`Response: ${p.status}`),n("Login response",h),p.ok||(i(new Error(`Login failed: ${p.status} ${JSON.stringify(h)}`)),401===p.status&&(console.error(s.red("Invalid username or password.")),process.exit(1)),m(p,h,"Login failed. Please try again."));const g=h;if(g.two_fa_required&&g.token){t(`2FA required, type: ${g.type||"unknown"}`);const e=await this.handle2FA(g.token,g.type,r.code);e||process.exit(1),await this.completeLogin(e,f,r.business)}else g.token&&g.refreshToken?await this.completeLogin({token:g.token,refreshToken:g.refreshToken},f,r.business):(console.error(s.red("Invalid response from server. Please try again.")),process.exit(1))}catch(y){if(i(y),u(y))return void console.log(s.yellow(p));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}async handle2FA(r,o,l){if("sms"===o){t(`POST ${a()}/auth/v1/two-fa/sms`);try{const{response:e}=await d(`${a()}/auth/v1/two-fa/sms`,{method:"POST",headers:{Authorization:`Bearer ${r}`},body:JSON.stringify({})});t(`Response: ${e.status}`)}catch(f){return i(f),console.error(s.red("Could not send SMS code. Check your connection and try again.")),null}}const c="sms"===o?"Check your phone for the code":"Check your authenticator app for the code",h=l?1:3;for(let g=1;g<=h;g++){let o;if(l&&1===g)o=l,t("2FA code provided via flag");else{o=(await e.prompt([{type:"input",name:"auth_code",message:`Enter code (${c}):`,validate:e=>!!e.trim()||"Code is required"}])).auth_code}t(`POST ${a()}/auth/v1/2fa-check`);try{const{response:i,body:l}=await d(`${a()}/auth/v1/2fa-check`,{method:"POST",headers:{Authorization:`Bearer ${r}`},body:JSON.stringify({auth_code:o.trim()})});if(t(`Response: ${i.status}`),n("2FA check response",l),i.ok){const e=l;if(e.token&&e.refreshToken)return{token:e.token,refreshToken:e.refreshToken}}if(i.status>=400&&i.status<500){if(console.error(s.red("Invalid code. Please try again.")),g<h){const{retry:s}=await e.prompt([{type:"confirm",name:"retry",message:"Try again?",default:!0}]);if(!s)return null}continue}m(i,l,"2FA verification failed. Please try again.")}catch(f){return i(f),u(f)?(console.log(s.yellow(p)),null):(console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),null)}}return null}async completeLogin(o,l,u){const p=c();p.start("Fetching businesses..."),t(`GET ${a()}/users/v1/business/my`);const{response:h,body:f}=await d(`${a()}/users/v1/business/my`,{headers:{Authorization:`Bearer ${o.token}`}});p.stop(),t(`Response: ${h.status}`),n("Businesses response",f),h.ok||(i(new Error(`Business fetch failed: ${h.status}`)),m(h,f,"Failed to fetch businesses. Please try again."));const g=this.parseBusinesses(f);let y;if(t(`Businesses: ${g.length}`),0===g.length&&(console.error(s.red("No businesses found for your account.")),process.exit(1)),u){const e=g.find(e=>e.id===u);e||(console.error(s.red(`Business "${u}" not found.`)),process.exit(1)),y=e,t(`Selected business via flag: ${y.id} ${y.name}`)}else if(1===g.length)y=g[0],t(`Selected business: ${y.id} ${y.name}`);else{const{businessId:s}=await e.prompt([{type:"select",name:"businessId",message:"Select business:",choices:g.map(e=>({name:e.name,value:e.id}))}]);y=g.find(e=>e.id===s)||g[0],t(`Selected business: ${y.id} ${y.name}`)}p.start("Switching business..."),t(`GET ${a()}/business/v1/login?_switch_business=${y.id}`);const{response:w,body:k}=await d(`${a()}/business/v1/login?_switch_business=${y.id}`,{headers:{Authorization:`Bearer ${o.token}`}});p.stop(),t(`Response: ${w.status}`),n("Business login response",k),w.ok||(i(new Error(`Business login failed: ${w.status}`)),m(w,k,"Failed to switch to business. Please try again."));const b=k;b.token&&b.refreshToken||(console.error(s.red("Invalid response from server. Please try again.")),process.exit(1));const $={token:b.token,refreshToken:b.refreshToken,businessId:y.id};await r.writeJson(l,$,{spaces:2}),t("Saved credentials to .dashnex"),this.ensureGitignore(),console.log(s.green(`Logged in as ${y.name}`))}parseBusinesses(e){const s=Array.isArray(e)?e:e.items??e.data??e.businesses??[];return Array.isArray(s)?s.map(e=>{if(e&&"object"==typeof e){const s=e,r=String(s.id??s.business_id??"").trim(),o=String(s.name??s.companyName??s.business_name??"Unknown").trim();if(r)return{id:r,name:o}}return null}).filter(e=>null!==e):[]}async ensureGitignore(){const e=o.join(process.cwd(),".gitignore");if(!(await r.pathExists(e)))return;let s=await r.readFile(e,"utf8");s.includes(".dashnex")||(s=s.trimEnd(),s.endsWith("\n")||(s+="\n"),s+="\n.dashnex\n",await r.writeFile(e,s))}}export{h as LoginCommand};
1
+ import e from"inquirer";import s from"chalk";import r from"fs-extra";import o from"path";import{debug as t,debugJson as n,debugError as i}from"../lib/debug.js";import{getApiBase as a,apiFetch as d}from"../lib/api.js";import{ensureLoggedIn as l}from"../services/auth.js";import{createSpinner as c}from"../lib/spinner.js";import{isUserInterrupt as u,INTERRUPTED_MESSAGE as p}from"../lib/errors.js";const m=(e,r,o)=>{const t=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(r);let n=o;429===e.status?n="Too many requests. Please wait a moment and try again.":e.status>=500?n="DashNex API is temporarily unavailable. Please try again later.":t&&(n=t),console.error(s.red(n)),process.exit(1)};class h{async execute(r={}){t("Login flow started");const h=process.cwd(),f=o.join(h,".dashnex"),g=await l({exitOnFailure:!1,dashnexPath:f});if(g)console.log(s.green(`Already logged in as ${g.userName??"user"}`));else try{let o,l;if(r.email)o=r.email.trim(),t("Email provided via flag");else{const{username:s}=await e.prompt([{type:"input",name:"username",message:"Email:",validate:e=>!!e.trim()||"Email is required"}]);o=s.trim()}if(r.password)l=r.password,t("Password provided via flag");else{const{password:s}=await e.prompt([{type:"password",name:"password",message:"Password:",mask:"*",validate:e=>!!e||"Password is required"}]);l=s}t("Email provided");const u=c();u.start("Logging in..."),t(`POST ${a()}/auth/v1/login`);const{response:p,body:h}=await d(`${a()}/auth/v1/login`,{method:"POST",body:JSON.stringify({username:o,password:l})});u.stop(),t(`Response: ${p.status}`),n("Login response",h),p.ok||(i(new Error(`Login failed: ${p.status} ${JSON.stringify(h)}`)),401===p.status&&(console.error(s.red("Invalid username or password.")),process.exit(1)),m(p,h,"Login failed. Please try again."));const g=h;if(g.two_fa_required&&g.token){t(`2FA required, type: ${g.type||"unknown"}`);const e=await this.handle2FA(g.token,g.type,r.code);e||process.exit(1),await this.completeLogin(e,f,r.business)}else g.token&&g.refreshToken?await this.completeLogin({token:g.token,refreshToken:g.refreshToken},f,r.business):(console.error(s.red("Invalid response from server. Please try again.")),process.exit(1))}catch(y){if(i(y),u(y))return void console.log(s.yellow(p));console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}async handle2FA(r,o,l){if("sms"===o){t(`POST ${a()}/auth/v1/two-fa/sms`);try{const{response:e}=await d(`${a()}/auth/v1/two-fa/sms`,{method:"POST",headers:{Authorization:`Bearer ${r}`},body:JSON.stringify({})});t(`Response: ${e.status}`)}catch(f){return i(f),console.error(s.red("Could not send SMS code. Check your connection and try again.")),null}}const c="sms"===o?"Check your phone for the code":"Check your authenticator app for the code",h=l?1:3;for(let g=1;g<=h;g++){let o;if(l&&1===g)o=l,t("2FA code provided via flag");else{o=(await e.prompt([{type:"input",name:"auth_code",message:`Enter code (${c}):`,validate:e=>!!e.trim()||"Code is required"}])).auth_code}t(`POST ${a()}/auth/v1/2fa-check`);try{const{response:i,body:l}=await d(`${a()}/auth/v1/2fa-check`,{method:"POST",headers:{Authorization:`Bearer ${r}`},body:JSON.stringify({auth_code:o.trim()})});if(t(`Response: ${i.status}`),n("2FA check response",l),i.ok){const e=l;if(e.token&&e.refreshToken)return{token:e.token,refreshToken:e.refreshToken}}if(i.status>=400&&i.status<500){if(console.error(s.red("Invalid code. Please try again.")),g<h){const{retry:s}=await e.prompt([{type:"confirm",name:"retry",message:"Try again?",default:!0}]);if(!s)return null}continue}m(i,l,"2FA verification failed. Please try again.")}catch(f){return i(f),u(f)?(console.log(s.yellow(p)),null):(console.error(s.red("Could not reach DashNex API. Check your connection and try again.")),null)}}return null}async completeLogin(o,l,u){const p=c();p.start("Fetching businesses..."),t(`GET ${a()}/users/v1/business/my`);const{response:h,body:f}=await d(`${a()}/users/v1/business/my`,{headers:{Authorization:`Bearer ${o.token}`}});p.stop(),t(`Response: ${h.status}`),n("Businesses response",f),h.ok||(i(new Error(`Business fetch failed: ${h.status}`)),m(h,f,"Failed to fetch businesses. Please try again."));const g=this.parseBusinesses(f);let y;if(t(`Businesses: ${g.length}`),0===g.length&&(console.error(s.red("No businesses found for your account.")),process.exit(1)),u){const e=g.find(e=>e.id===u);e||(console.error(s.red(`Business "${u}" not found.`)),process.exit(1)),y=e,t(`Selected business via flag: ${y.id} ${y.name}`)}else if(1===g.length)y=g[0],t(`Selected business: ${y.id} ${y.name}`);else{const{businessId:s}=await e.prompt([{type:"select",name:"businessId",message:"Select business:",choices:g.map(e=>({name:e.name,value:e.id}))}]);y=g.find(e=>e.id===s)||g[0],t(`Selected business: ${y.id} ${y.name}`)}p.start("Switching business..."),t(`GET ${a()}/business/v1/login?_switch_business=${y.id}`);const{response:w,body:k}=await d(`${a()}/business/v1/login?_switch_business=${y.id}`,{headers:{Authorization:`Bearer ${o.token}`}});p.stop(),t(`Response: ${w.status}`),n("Business login response",k),w.ok||(i(new Error(`Business login failed: ${w.status}`)),m(w,k,"Failed to switch to business. Please try again."));const b=k;b.token&&b.refreshToken||(console.error(s.red("Invalid response from server. Please try again.")),process.exit(1));const $={token:b.token,refreshToken:b.refreshToken,businessId:y.id};await r.writeJson(l,$,{spaces:2}),t("Saved credentials to .dashnex"),this.ensureGitignore(),console.log(s.green(`Logged in as ${y.name}`))}parseBusinesses(e){const s=Array.isArray(e)?e:e.items??e.data??e.businesses??[];return Array.isArray(s)?s.map(e=>{if(e&&"object"==typeof e){const s=e,r=String(s.id??s.business_id??"").trim(),o=String(s.name??s.companyName??s.business_name??"Unknown").trim();if(r)return{id:r,name:o}}return null}).filter(e=>null!==e):[]}async ensureGitignore(){const e=o.join(process.cwd(),".gitignore");if(!(await r.pathExists(e)))return;let s=await r.readFile(e,"utf8");s.includes(".dashnex")||(s=s.trimEnd(),s.endsWith("\n")||(s+="\n"),s+="\n.dashnex\n",await r.writeFile(e,s))}}export{h as LoginCommand};
@@ -1 +1 @@
1
- const e="@dashnex/cli",a="0.5.32",n="Command-line interface for DashNex framework",o={name:e,version:a,description:n};export{o as default,n as description,e as name,a as version};
1
+ const e="@dashnex/cli",a="0.5.34",n="Command-line interface for DashNex framework",o={name:e,version:a,description:n};export{o as default,n as description,e as name,a as version};
@@ -0,0 +1 @@
1
+ import e from"chalk";import t from"inquirer";import{debug as r,debugError as n}from"../lib/debug.js";import{getBusinessApiBase as o}from"../lib/api.js";import{getApplicationUrl as a}from"../lib/app-url.js";const s=async t=>{const n=`${o()}/business/v1/agreements/payment-processing/status`;r(`GET ${n}`);const s=await fetch(n,{headers:{Authorization:`Bearer ${t}`}});if(r(`Payment agreement response: ${s.status}`),!s.ok)return!0;if((await s.json().catch(()=>({}))).hasAccepted)return!0;const i=await(async e=>{try{const t=`${o()}/business/v1/applications`,r=await fetch(t,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)return null;const n=await r.json().catch(()=>({}));return a({subdomain:n.subdomain,appFullCustomDomain:n.appFullCustomDomain})}catch{return null}})(t),c=i?`${i}/money/agreement/`:"your business dashboard under Money > Agreement";return console.error(e.red(`You need to accept Master Payment Processing Agreement first by visiting this link: ${c}`)),!1},i=async(a,i={})=>{const c=i.ciMode??!1;if(!(await s(a)))return!1;const l=await(async(a,s)=>{const i=`${o()}/business/v1/tos/latest`;r(`GET ${i}`);const c=await fetch(i,{headers:{Authorization:`Bearer ${a}`}});if(r(`TOS latest response: ${c.status}`),c.ok)return!0;if(404!==c.status)return!0;const l=`${o()}/business/v1/tos/current`;r(`GET ${l}`);const p=await fetch(l,{headers:{Authorization:`Bearer ${a}`}});if(r(`TOS current response: ${p.status}`),!p.ok)return r("Could not fetch current TOS, skipping check"),!0;const u=await p.json().catch(()=>({})),m=u.version??"unknown";if(u.text&&(console.log(e.dim("─".repeat(60))),console.log(e.bold(`Terms of Service ${m}`)),console.log(e.dim("─".repeat(60))),console.log(u.text.replace(/<br\s*\/?>/gi,"\n").replace(/<\/p>/gi,"\n\n").replace(/<\/div>/gi,"\n").replace(/<\/li>/gi,"\n").replace(/<[^>]+>/g,"").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," ").replace(/\n{3,}/g,"\n\n").trim()),console.log(e.dim("─".repeat(60)))),s)return console.log(e.yellow(`By proceeding you accept the Terms of Service ${m}.`)),!0;const{accept:g}=await t.prompt([{type:"confirm",name:"accept",message:`By creating an application you accept the Terms of Service ${m}. Continue?`,default:!0}]);if(!g)return console.log(e.yellow("Cancelled.")),!1;try{const e=`${o()}/business/v1/tos/${u.id}/accept`;r(`POST ${e}`),await fetch(e,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({})})}catch(h){n(h)}return!0})(a,c);return!!l};export{i as ensureAgreements};
@@ -0,0 +1,3 @@
1
+ export declare const ensureAgreements: (token: string, options?: {
2
+ ciMode?: boolean;
3
+ }) => Promise<boolean>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@dashnex/cli",
4
- "version": "0.5.32",
4
+ "version": "0.5.34",
5
5
  "description": "Command-line interface for DashNex framework",
6
6
  "homepage": "https://dashnex.io",
7
7
  "type": "module",