dashnex 0.7.0 → 0.7.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/README.md CHANGED
@@ -23,6 +23,7 @@ dashnex <command> [options]
23
23
  | `version` | Display the version of the CLI |
24
24
  | `login` | Log in to your DashNex account |
25
25
  | `logout` | Log out and remove local credentials |
26
+ | `switch` | Switch to another business |
26
27
  | `whoami` | Show current logged-in business and user |
27
28
  | `dev` | Run the development server (run in DashNex application folder); `-p/--port`, `-H/--host`, `--https` |
28
29
  | `check` | Run build-time validations (run in DashNex application folder) |
@@ -48,6 +49,11 @@ Sign-in goes through DashNex ID in your browser: approve the request, copy the
48
49
  code you are shown, and paste it back into the CLI. Codes are valid for 10
49
50
  minutes and can only be used once.
50
51
 
52
+ **switch**:
53
+ - `[businessId]` — Business to switch to; without it, pick from the list of your businesses
54
+
55
+ Re-uses the DashNex ID session saved by `dashnex login`, so no new sign-in is needed.
56
+
51
57
  **dev**:
52
58
  - `-p, --port <port>` — Port for the dev server (falls back to the `PORT` env var, then 3000)
53
59
  - `-H, --host <host>` — Host/interface to bind, e.g. `0.0.0.0` when the app runs inside Docker (falls back to the `HOST` env var, then localhost). With `--https` the certificate also covers this host.
@@ -1 +1 @@
1
- import e from"chalk";import s from"fs-extra";import n from"path";var r=e=>e instanceof Error&&("ExitPromptError"===e.name||("AbortError"===e.name||("User force closed the prompt"===e.message||!!e.message.includes("prompt was closed")))),t="Command interrupted.",o=e=>{const s=e.toLowerCase();return s.includes("token")||s.includes("password")||"auth_code"===s},a=e=>{if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(a);const s={};for(const[n,r]of Object.entries(e))o(n)?s[n]="[REDACTED]":s[n]=a(r);return s},i=s=>{process.env.DEBUG&&console.log(e.dim(s))},c=(s,n)=>{if(process.env.DEBUG){const r=a(n);console.log(e.dim(`${s}: ${JSON.stringify(r,null,2)}`))}},p=s=>{process.env.DEBUG&&s instanceof Error&&(console.log(e.dim(`Error: ${s.message}`)),s.stack&&console.log(e.dim(`Stack: ${s.stack}`)))},l=()=>"qa"===process.env.APPLICATION_ENV?"https://api.qa.dashnex.com":"https://api.dashnex.com",u=()=>process.env.DASHNEX_BUSINESS_API_URL?process.env.DASHNEX_BUSINESS_API_URL.replace(/\/+$/,""):"qa"===process.env.APPLICATION_ENV?"https://api.business.qa.dashnex.com":"https://api.business.dashnex.com",d={qa:"https://app.qa.dashnex.com",live:"https://app.dashnex.com"},f={qa:"hacmrrpg1wnjv12oq22p8lfm",live:"paijq1vhr6kxnbm22wjoftep"},h=()=>process.env.DASHNEX_ID_URL?process.env.DASHNEX_ID_URL.replace(/\/+$/,""):d[process.env.APPLICATION_ENV||"live"]||d.live,m=()=>process.env.DASHNEX_OAUTH_CLIENT_ID?process.env.DASHNEX_OAUTH_CLIENT_ID:f[process.env.APPLICATION_ENV||"live"]??"",v={qa:"https://3atfynmu2w.us-east-1.awsapprunner.com",live:"https://rkwbzvhcwh.us-east-1.awsapprunner.com"},k=()=>v[process.env.APPLICATION_ENV||"live"]||v.live,E=async(e,s={})=>{const n=await fetch(e,{...s,headers:{"Content-Type":"application/json",...s.headers}});return{response:n,body:await n.json().catch(()=>({}))}},N=process.env.DASHNEX_DIR||".dashnex",T=e=>n.join(e,N,"settings.json"),g=()=>{console.error(e.red("Please run 'dashnex login' to authenticate.")),console.error(e.green(`If you don't have an account yet, create one at ${h()}`))},w=e=>Boolean(e.idToken),x=async e=>{let r=n.resolve(e);for(;;){const e=T(r);if(await s.pathExists(e))return e;const t=n.dirname(r);if(t===r)return null;r=t}},y=e=>{try{const s=e.split(".");if(3!==s.length)return null;const n=JSON.parse(Buffer.from(s[1],"base64url").toString());return void 0!==n.id?String(n.id):null}catch{return null}},A=(e,s=30)=>{try{const n=e.split(".");if(3!==n.length)return!1;const r=JSON.parse(Buffer.from(n[1],"base64url").toString());if("number"!=typeof r.exp)return!1;const t=Math.floor(Date.now()/1e3),o=r.exp-s<=t;return o&&i(`Token expired or expiring soon (exp: ${r.exp}, now: ${t})`),o}catch{return!1}},S=async(e,n,r)=>{const t=w(r)?`${u()}/business/v1/token/refresh`:`${l()}/auth/v1/token/refresh`;i(`POST ${t}`);const{response:o,body:a}=await E(t,{method:"POST",body:JSON.stringify({refreshToken:e})});if(i(`Response: ${o.status}`),c("Refresh response",a),!o.ok)return i("Token refresh failed"),null;const p=a;if(!p.token||!p.refreshToken)return i("Refresh response missing tokens"),null;const d=await s.readJson(n);return d.token=p.token,d.refreshToken=p.refreshToken,await s.writeJson(n,d,{spaces:2}),i("Updated settings.json with new tokens"),_(p.token,p.refreshToken,n,{...d,token:p.token,refreshToken:p.refreshToken})},_=async(e,s,n,r)=>{if(A(e)){if(!s)return i("Token expired, no refreshToken available"),null;i("Token expired, refreshing proactively");try{return await S(s,n,r)}catch(o){return p(o),null}}const t=w(r)?`${u()}/business/v1/`:`${l()}/users/v1/`;i(`GET ${t}`);try{const{response:o,body:a}=await E(t,{headers:{Authorization:`Bearer ${e}`}});if(i(`Response: ${o.status}`),c("Validation response",a),o.ok){const s=a,n=s.name??s.companyName,t=r.businessId??(void 0!==s.id?String(s.id):void 0);if("string"==typeof n&&void 0!==t)return i(`Token valid, Already logged in as ${n}`),{token:e,businessId:String(t),userName:n}}return s?(i("Validation endpoint rejected token, refreshing"),await S(s,n,r)):(i("Token invalid, no refreshToken available"),null)}catch(o){return p(o),null}},I=async(e=process.cwd())=>{const n=await x(e);if(!n)return!1;try{return w(await s.readJson(n))}catch{return!1}},b=async(n={})=>{const{exitOnFailure:r=!0,dashnexPath:t}=n,o=process.env.DASHNEX_TOKEN;if(o)return A(o)?(i("DASHNEX_TOKEN is expired"),console.error(e.red("DASHNEX_TOKEN is expired. Provide a freshly issued token.")),r&&process.exit(1),null):(i("Using DASHNEX_TOKEN from environment"),{token:o,businessId:y(o)??""});const a=t??await x(process.cwd());if(!a||!(await s.pathExists(a)))return i(".dashnex/settings.json not found"),r&&(g(),process.exit(1)),null;let c;i(`Found settings at ${a}`);try{c=await s.readJson(a)}catch{return i("settings.json parse failed"),r&&(g(),process.exit(1)),null}const{token:p,refreshToken:l,businessId:u}=c;if(!p)return i("settings.json missing token"),r&&(g(),process.exit(1)),null;const d=await _(p,l,a,c);return d||(r&&(g(),process.exit(1)),null)};export{E as a,h as c,i as d,p as f,r as h,T as i,k as l,t as m,I as n,l as o,c as p,N as r,u as s,b as t,m as u};
1
+ import e from"chalk";import s from"fs-extra";import n from"path";var r=e=>e instanceof Error&&("ExitPromptError"===e.name||("AbortError"===e.name||("User force closed the prompt"===e.message||!!e.message.includes("prompt was closed")))),t="Command interrupted.",o=e=>{const s=e.toLowerCase();return s.includes("token")||s.includes("password")||"auth_code"===s},a=e=>{if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(a);const s={};for(const[n,r]of Object.entries(e))o(n)?s[n]="[REDACTED]":s[n]=a(r);return s},i=s=>{process.env.DEBUG&&console.log(e.dim(s))},c=(s,n)=>{if(process.env.DEBUG){const r=a(n);console.log(e.dim(`${s}: ${JSON.stringify(r,null,2)}`))}},p=s=>{process.env.DEBUG&&s instanceof Error&&(console.log(e.dim(`Error: ${s.message}`)),s.stack&&console.log(e.dim(`Stack: ${s.stack}`)))},l=()=>"qa"===process.env.APPLICATION_ENV?"https://api.qa.dashnex.com":"https://api.dashnex.com",u=()=>process.env.DASHNEX_BUSINESS_API_URL?process.env.DASHNEX_BUSINESS_API_URL.replace(/\/+$/,""):"qa"===process.env.APPLICATION_ENV?"https://api.business.qa.dashnex.com":"https://api.business.dashnex.com",d={qa:"https://app.qa.dashnex.com",live:"https://app.dashnex.com"},f={qa:"hacmrrpg1wnjv12oq22p8lfm",live:"paijq1vhr6kxnbm22wjoftep"},h=()=>process.env.DASHNEX_ID_URL?process.env.DASHNEX_ID_URL.replace(/\/+$/,""):d[process.env.APPLICATION_ENV||"live"]||d.live,m=()=>process.env.DASHNEX_OAUTH_CLIENT_ID?process.env.DASHNEX_OAUTH_CLIENT_ID:f[process.env.APPLICATION_ENV||"live"]??"",v={qa:"https://3atfynmu2w.us-east-1.awsapprunner.com",live:"https://rkwbzvhcwh.us-east-1.awsapprunner.com"},k=()=>v[process.env.APPLICATION_ENV||"live"]||v.live,E=async(e,s={})=>{const n=await fetch(e,{...s,headers:{"Content-Type":"application/json",...s.headers}});return{response:n,body:await n.json().catch(()=>({}))}},g=process.env.DASHNEX_DIR||".dashnex",N=e=>n.join(e,g,"settings.json"),T=()=>{console.error(e.red("Please run 'dashnex login' to authenticate.")),console.error(e.green(`If you don't have an account yet, create one at ${h()}`))},w=e=>Boolean(e.idToken),x=async e=>{let r=n.resolve(e);for(;;){const e=N(r);if(await s.pathExists(e))return e;const t=n.dirname(r);if(t===r)return null;r=t}},y=e=>{try{const s=e.split(".");if(3!==s.length)return null;const n=JSON.parse(Buffer.from(s[1],"base64url").toString());return void 0!==n.id?String(n.id):null}catch{return null}},A=(e,s=30)=>{try{const n=e.split(".");if(3!==n.length)return!1;const r=JSON.parse(Buffer.from(n[1],"base64url").toString());if("number"!=typeof r.exp)return!1;const t=Math.floor(Date.now()/1e3),o=r.exp-s<=t;return o&&i(`Token expired or expiring soon (exp: ${r.exp}, now: ${t})`),o}catch{return!1}},S=async(e,n,r)=>{const t=w(r)?`${u()}/business/v1/token/refresh`:`${l()}/auth/v1/token/refresh`;i(`POST ${t}`);const{response:o,body:a}=await E(t,{method:"POST",body:JSON.stringify({refreshToken:e})});if(i(`Response: ${o.status}`),c("Refresh response",a),!o.ok)return i("Token refresh failed"),null;const p=a;if(!p.token||!p.refreshToken)return i("Refresh response missing tokens"),null;const d=await s.readJson(n);return d.token=p.token,d.refreshToken=p.refreshToken,await s.writeJson(n,d,{spaces:2}),i("Updated settings.json with new tokens"),_(p.token,p.refreshToken,n,{...d,token:p.token,refreshToken:p.refreshToken})},_=async(e,s,n,r)=>{if(A(e)){if(!s)return i("Token expired, no refreshToken available"),null;i("Token expired, refreshing proactively");try{return await S(s,n,r)}catch(o){return p(o),null}}const t=w(r)?`${u()}/business/v1/`:`${l()}/users/v1/`;i(`GET ${t}`);try{const{response:o,body:a}=await E(t,{headers:{Authorization:`Bearer ${e}`}});if(i(`Response: ${o.status}`),c("Validation response",a),o.ok){const s=a,n=s.name??s.companyName,t=r.businessId??(void 0!==s.id?String(s.id):void 0);if("string"==typeof n&&void 0!==t)return i(`Token valid, Already logged in as ${n}`),{token:e,businessId:String(t),userName:n}}return s?(i("Validation endpoint rejected token, refreshing"),await S(s,n,r)):(i("Token invalid, no refreshToken available"),null)}catch(o){return p(o),null}},I=async(e=process.cwd())=>{const n=await x(e);if(!n)return!1;try{return w(await s.readJson(n))}catch{return!1}},b=async(n={})=>{const{exitOnFailure:r=!0,dashnexPath:t}=n,o=process.env.DASHNEX_TOKEN;if(o)return A(o)?(i("DASHNEX_TOKEN is expired"),console.error(e.red("DASHNEX_TOKEN is expired. Provide a freshly issued token.")),r&&process.exit(1),null):(i("Using DASHNEX_TOKEN from environment"),{token:o,businessId:y(o)??""});const a=t??await x(process.cwd());if(!a||!(await s.pathExists(a)))return i(".dashnex/settings.json not found"),r&&(T(),process.exit(1)),null;let c;i(`Found settings at ${a}`);try{c=await s.readJson(a)}catch{return i("settings.json parse failed"),r&&(T(),process.exit(1)),null}const{token:p,refreshToken:l,businessId:u}=c;if(!p)return i("settings.json missing token"),r&&(T(),process.exit(1)),null;const d=await _(p,l,a,c);return d||(r&&(T(),process.exit(1)),null)};export{N as a,u as c,m as d,i as f,r as g,t as h,g as i,h as l,c as m,x as n,E as o,p,I as r,l as s,b as t,k as u};
@@ -1 +1 @@
1
- var e={$schema:"https://json.schemastore.org/package",name:"@dashnex/cli",version:"0.7.0",dashnex:{minAppVersion:"1.1.0"},description:"Command-line interface for DashNex framework",homepage:"https://dashnex.io",type:"module",bin:{dashnex:"bin/dashnex"},engines:{node:">=22"},exports:{".":{types:"./dist/server.d.ts",default:"./dist/server.js"},"./client":{types:"./dist/client.d.ts",default:"./dist/client.js"}},scripts:{build:"vite build",dev:"vite build --watch --mode development",test:"vitest run"},keywords:["dashnex","cli"],author:"Dashnex Team",license:"UNLICENSED",dependencies:{"adm-zip":"^0.5.17",chalk:"^5.6.2",commander:"^14.0.3",diff:"^8.0.4",dotenv:"^17.4.2","fs-extra":"^11.3.5",ignore:"^7.0.5",inquirer:"^13.4.3",jiti:"^2.7.0",partysocket:"^1.3.0",ws:"^8.21.0"},devDependencies:{"@dashnex/types":"^1.5.0","@types/adm-zip":"^0.5.8","@types/fs-extra":"^11.0.4","@types/inquirer":"^9.0.9","@types/node":"^25.7.0","@types/ws":"^8.18.1",eslint:"^9.39.4","rollup-plugin-preserve-directives":"^0.4.0",terser:"^5.47.1",typescript:"^5.9.3",vite:"^8.0.8","vite-plugin-dts":"5.0.0-beta.6",vitest:"^4.1.6"},publishConfig:{registry:"https://npm.dashnex.com/"},files:["dist","bin","AGENTS.md","CLAUDE.md"]},s={};export{e as n,s as t};
1
+ var e={$schema:"https://json.schemastore.org/package",name:"@dashnex/cli",version:"0.7.1",dashnex:{minAppVersion:"1.1.0"},description:"Command-line interface for DashNex framework",homepage:"https://dashnex.io",type:"module",bin:{dashnex:"bin/dashnex"},engines:{node:">=22"},exports:{".":{types:"./dist/server.d.ts",default:"./dist/server.js"},"./client":{types:"./dist/client.d.ts",default:"./dist/client.js"}},scripts:{build:"vite build",dev:"vite build --watch --mode development",test:"vitest run"},keywords:["dashnex","cli"],author:"Dashnex Team",license:"UNLICENSED",dependencies:{"adm-zip":"^0.5.17",chalk:"^5.6.2",commander:"^14.0.3",diff:"^8.0.4",dotenv:"^17.4.2","fs-extra":"^11.3.5",ignore:"^7.0.5",inquirer:"^13.4.3",jiti:"^2.7.0",partysocket:"^1.3.0",ws:"^8.21.0"},devDependencies:{"@dashnex/types":"^1.5.0","@types/adm-zip":"^0.5.8","@types/fs-extra":"^11.0.4","@types/inquirer":"^9.0.9","@types/node":"^25.7.0","@types/ws":"^8.18.1",eslint:"^9.39.4","rollup-plugin-preserve-directives":"^0.4.0",terser:"^5.47.1",typescript:"^5.9.3",vite:"^8.0.8","vite-plugin-dts":"5.0.0-beta.6",vitest:"^4.1.6"},publishConfig:{registry:"https://npm.dashnex.com/"},files:["dist","bin","AGENTS.md","CLAUDE.md"]},s={};export{e as n,s as t};
package/dist/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{h as n,m as o,s,t as e}from"./chunks/auth-ezwXxi-m.js";import{Command as t}from"commander";import i from"chalk";import a from"fs-extra";import c from"path";import{fileURLToPath as r,pathToFileURL as d}from"url";import{execSync as l}from"child_process";import{createJiti as m}from"jiti";import p from"dotenv";var f=new t,u=c.dirname(r(import.meta.url)),{version:h,description:g}=JSON.parse(a.readFileSync(c.resolve(u,"..","package.json"),"utf8"));f.name("dashnex").description(g).version(h).option("--ci","Disable spinner and interactive prompts (CI mode)").arguments("[command...]").action(n=>{if(n&&n.length>0){const o=n[0];if(!f.commands.map(n=>n.name()).includes(o)){console.error(i.red(`Unknown command: ${o}`));const n=process.cwd(),s=a.existsSync(c.join(n,"dashnex.json")),e=a.existsSync(c.join(n,"node_modules"));["build","router","bindings","env","db"].includes(o)?s&&!e?console.log(i.yellow(`\`${o}\` is provided by installed modules. Run \`dashnex install\` first.`)):s?console.log(i.green("Run `dashnex` to see available commands.")):console.log(i.yellow(`\`${o}\` must be run inside a DashNex application folder (containing dashnex.json).`)):console.log(i.green("Run `dashnex` to see available commands.")),process.exit(1)}}!function(n){const o=[];o.push("Usage: dashnex [options] [command]"),o.push(""),o.push(n.description()),o.push(""),o.push("Options:"),n.options.forEach(n=>{const s=n.flags.padEnd(20);o.push(` ${s} ${n.description}`)}),o.push(""),o.push("Commands:"),n.commands.forEach(n=>{const s=` ${n.name().padEnd(20)} ${n.description()}`;o.push(s),n.commands.length>0&&n.commands.forEach(n=>{const s=` ${n.name().padEnd(20)} ${n.description()}`;o.push(s)})}),console.log(o.join("\n"))}(f)});var y=null;var x=null;async function j(n,o){const s=[];try{const e=function(n,o){const s=c.join(o,"package.json");if(a.existsSync(s))try{const e=JSON.parse(a.readFileSync(s,"utf8"));if(e.name===n)return o;const t={...e.dependencies,...e.devDependencies}[n];if(t&&(t.startsWith("link:")||t.startsWith("file:"))){const n=c.resolve(o,t.replace(/^(link:|file:)/,""));if(a.existsSync(n))return n}}catch{}const e=c.join(o,"node_modules",n);if(a.existsSync(e))return a.realpathSync(e);if(y){const o=c.join(y,n);if(a.existsSync(o))return o}return e}(n,o),t=[c.join(e,"src","commands","index.ts"),c.join(e,"src","commands","index.js")],i=c.join(e,"dist","commands","index.js"),r=(function(n,o){const s=c.join(o,"package.json");if(!a.existsSync(s))return!1;try{const o=JSON.parse(a.readFileSync(s,"utf8")),e={...o.dependencies,...o.devDependencies}[n];return"string"==typeof e&&(e.startsWith("link:")||e.startsWith("file:"))}catch{return!1}}(n,o)?[...t,i]:[i,...t]).find(n=>a.existsSync(n));if(r){process.env.DEBUG&&console.log(`Loading ${n} commands from: ${r}`);const o=await async function(n){return/\.(ts|mts|cts|tsx)$/.test(n)?(x??=m(import.meta.url,{interopDefault:!1}),await x.import(n)):await import(d(n).href)}(r);let e=[];Array.isArray(o)?e=o:o.default?e=Array.isArray(o.default)?o.default:[]:o.commands&&(e=Array.isArray(o.commands)?o.commands:[]),e.length>0&&s.push(...e)}}catch(e){if(process.env.DEBUG){const o=e instanceof Error?e.message:String(e);console.log(i.yellow(`Module ${n} has no commands or failed to load: ${o}`))}}return s}function S(t,a,c={}){const r=t.command(a.name).description(a.description);a.arguments&&a.arguments.forEach(n=>{const o=n.required?`<${n.name}>`:`[${n.name}]`;void 0!==n.defaultValue?r.argument(o,n.description,n.defaultValue):r.argument(o,n.description)}),r.option("--ci","Disable spinner (CI mode)"),a.options&&a.options.forEach(n=>{void 0!==n.defaultValue?"number"==typeof n.defaultValue?r.option(n.flags,n.description,String(n.defaultValue)):r.option(n.flags,n.description,n.defaultValue):r.option(n.flags,n.description)}),a.subcommands&&a.subcommands.forEach(n=>{S(r,n,{...c,...a.options})}),a.subcommands&&a.subcommands.length>0?r.action(async()=>{r.outputHelp()}):r.action(async(...t)=>{try{const n=t[t.length-1],o=n.opts(),i=n.processedArgs,r={...c,...o};a.arguments?.forEach((n,o)=>{void 0!==i[o]&&(r[n.name]=i[o])}),r.context={auth:{getSession:()=>e()},businessApiBase:s()},await a.handler.execute(r)}catch(r){if(n(r))return void console.log(i.yellow(o));console.error(i.red(`❌ Command failed in ${a.name}:`),r),process.exit(1)}})}(async function(){p.config({quiet:!0}),process.env.DASHNEX_CLI="1",function(){try{y=l("npm root -g",{encoding:"utf8"}).trim()}catch{y=null}}(),process.argv.includes("--ci")&&(process.env.DASHNEX_CI="1");let n=process.cwd();const o=c.dirname(r(import.meta.url)),s=c.resolve(o,"..");process.env.DEBUG&&(console.log(`CLI started from directory: ${n}`),console.log(`CLI package directory: ${s}`),console.log(`Global node_modules: ${y??"not found"}`));const e=await async function(n){try{const s=[],e=/* @__PURE__ */new Set,t=n=>{e.has(n)||(e.add(n),s.push(n))},i=c.join(n,"dashnex.json");if(a.existsSync(i)){const o=c.join(n,"package.json");if(a.existsSync(o)){const n=JSON.parse(a.readFileSync(o,"utf8"));n.name&&t(n.name)}}const r=c.join(n,"package.json");if(a.existsSync(r)){const o=JSON.parse(a.readFileSync(r,"utf8")),s={...o.dependencies,...o.devDependencies,...o.optionalDependencies};for(const[e,i]of Object.entries(s)){if("string"==typeof i&&(i.startsWith("link:")||i.startsWith("file:"))){const o=c.resolve(n,i.replace(/^(link:|file:)/,""));if(a.existsSync(c.join(o,"dashnex.json"))){t(e);continue}}const o=c.join(n,"node_modules",e);a.existsSync(c.join(o,"dashnex.json"))&&t(e)}}if(y&&a.existsSync(y))try{const n=a.readdirSync(y);for(const o of n)if(o.startsWith("@")){const n=c.join(y,o);try{if(a.statSync(n).isDirectory()){const s=a.readdirSync(n);for(const n of s){const s=`${o}/${n}`,e=c.join(y,s);a.existsSync(c.join(e,"dashnex.json"))&&t(s)}}}catch{}}else{const n=c.join(y,o);a.existsSync(c.join(n,"dashnex.json"))&&t(o)}}catch(o){if(process.env.DEBUG){const n=o instanceof Error?o.message:String(o);console.log("⚠ Error scanning global node_modules:",n)}}return s}catch(o){if(process.env.DEBUG){const n=o instanceof Error?o.message:String(o);console.log("⚠ Error reading app package.json:",n)}return[]}}(n);e.includes("@dashnex/cli")||e.push("@dashnex/cli"),process.env.DEBUG&&(console.log(`CLI package directory: ${s}`),console.log(`Discovered modules: ${e.join(", ")}`));for(const r of e){let o=[];if("@dashnex/cli"===r)try{const n=c.join(s,"dist","commands","index.js");if(process.env.DEBUG&&console.log(`Loading @dashnex/cli commands from: ${n}`),await a.pathExists(n)){const s=await import(d(n).href);s.default?o=Array.isArray(s.default)?s.default:[]:s.commands&&(o=Array.isArray(s.commands)?s.commands:[]),process.env.DEBUG&&console.log(`Loaded ${o.length} commands from @dashnex/cli`)}}catch(m){if(process.env.DEBUG){const n=m instanceof Error?m.message:String(m);console.log(i.yellow(`Failed to load @dashnex/cli commands: ${n}`))}}else o=await j(r,n);for(const n of o)S(f,n)}const t=c.join(n,"dist","commands","index.js");if(await a.pathExists(t))try{const{default:n}=await import(d(t).href);if(n&&Array.isArray(n))for(const o of n)S(f,o)}catch(m){if(process.env.DEBUG){const n=m instanceof Error?m.message:String(m);console.error(i.yellow(`⚠ Failed to load application commands: ${n}`))}}f.parse(process.argv)})().catch(s=>{n(s)&&(console.log(i.yellow(o)),process.exit(0)),console.error(i.red("❌ CLI failed:"),s),process.exit(1)});
2
+ import{c as n,g as o,h as s,t as e}from"./chunks/auth-DMO6V5r1.js";import{Command as t}from"commander";import i from"chalk";import a from"fs-extra";import c from"path";import{fileURLToPath as r,pathToFileURL as d}from"url";import{execSync as l}from"child_process";import{createJiti as m}from"jiti";import p from"dotenv";var f=new t,u=c.dirname(r(import.meta.url)),{version:h,description:g}=JSON.parse(a.readFileSync(c.resolve(u,"..","package.json"),"utf8"));f.name("dashnex").description(g).version(h).option("--ci","Disable spinner and interactive prompts (CI mode)").arguments("[command...]").action(n=>{if(n&&n.length>0){const o=n[0];if(!f.commands.map(n=>n.name()).includes(o)){console.error(i.red(`Unknown command: ${o}`));const n=process.cwd(),s=a.existsSync(c.join(n,"dashnex.json")),e=a.existsSync(c.join(n,"node_modules"));["build","router","bindings","env","db"].includes(o)?s&&!e?console.log(i.yellow(`\`${o}\` is provided by installed modules. Run \`dashnex install\` first.`)):s?console.log(i.green("Run `dashnex` to see available commands.")):console.log(i.yellow(`\`${o}\` must be run inside a DashNex application folder (containing dashnex.json).`)):console.log(i.green("Run `dashnex` to see available commands.")),process.exit(1)}}!function(n){const o=[];o.push("Usage: dashnex [options] [command]"),o.push(""),o.push(n.description()),o.push(""),o.push("Options:"),n.options.forEach(n=>{const s=n.flags.padEnd(20);o.push(` ${s} ${n.description}`)}),o.push(""),o.push("Commands:"),n.commands.forEach(n=>{const s=` ${n.name().padEnd(20)} ${n.description()}`;o.push(s),n.commands.length>0&&n.commands.forEach(n=>{const s=` ${n.name().padEnd(20)} ${n.description()}`;o.push(s)})}),console.log(o.join("\n"))}(f)});var y=null;var x=null;async function j(n,o){const s=[];try{const e=function(n,o){const s=c.join(o,"package.json");if(a.existsSync(s))try{const e=JSON.parse(a.readFileSync(s,"utf8"));if(e.name===n)return o;const t={...e.dependencies,...e.devDependencies}[n];if(t&&(t.startsWith("link:")||t.startsWith("file:"))){const n=c.resolve(o,t.replace(/^(link:|file:)/,""));if(a.existsSync(n))return n}}catch{}const e=c.join(o,"node_modules",n);if(a.existsSync(e))return a.realpathSync(e);if(y){const o=c.join(y,n);if(a.existsSync(o))return o}return e}(n,o),t=[c.join(e,"src","commands","index.ts"),c.join(e,"src","commands","index.js")],i=c.join(e,"dist","commands","index.js"),r=(function(n,o){const s=c.join(o,"package.json");if(!a.existsSync(s))return!1;try{const o=JSON.parse(a.readFileSync(s,"utf8")),e={...o.dependencies,...o.devDependencies}[n];return"string"==typeof e&&(e.startsWith("link:")||e.startsWith("file:"))}catch{return!1}}(n,o)?[...t,i]:[i,...t]).find(n=>a.existsSync(n));if(r){process.env.DEBUG&&console.log(`Loading ${n} commands from: ${r}`);const o=await async function(n){return/\.(ts|mts|cts|tsx)$/.test(n)?(x??=m(import.meta.url,{interopDefault:!1}),await x.import(n)):await import(d(n).href)}(r);let e=[];Array.isArray(o)?e=o:o.default?e=Array.isArray(o.default)?o.default:[]:o.commands&&(e=Array.isArray(o.commands)?o.commands:[]),e.length>0&&s.push(...e)}}catch(e){if(process.env.DEBUG){const o=e instanceof Error?e.message:String(e);console.log(i.yellow(`Module ${n} has no commands or failed to load: ${o}`))}}return s}function S(t,a,c={}){const r=t.command(a.name).description(a.description);a.arguments&&a.arguments.forEach(n=>{const o=n.required?`<${n.name}>`:`[${n.name}]`;void 0!==n.defaultValue?r.argument(o,n.description,n.defaultValue):r.argument(o,n.description)}),r.option("--ci","Disable spinner (CI mode)"),a.options&&a.options.forEach(n=>{void 0!==n.defaultValue?"number"==typeof n.defaultValue?r.option(n.flags,n.description,String(n.defaultValue)):r.option(n.flags,n.description,n.defaultValue):r.option(n.flags,n.description)}),a.subcommands&&a.subcommands.forEach(n=>{S(r,n,{...c,...a.options})}),a.subcommands&&a.subcommands.length>0?r.action(async()=>{r.outputHelp()}):r.action(async(...t)=>{try{const o=t[t.length-1],s=o.opts(),i=o.processedArgs,r={...c,...s};a.arguments?.forEach((n,o)=>{void 0!==i[o]&&(r[n.name]=i[o])}),r.context={auth:{getSession:()=>e()},businessApiBase:n()},await a.handler.execute(r)}catch(r){if(o(r))return void console.log(i.yellow(s));console.error(i.red(`❌ Command failed in ${a.name}:`),r),process.exit(1)}})}(async function(){p.config({quiet:!0}),process.env.DASHNEX_CLI="1",function(){try{y=l("npm root -g",{encoding:"utf8"}).trim()}catch{y=null}}(),process.argv.includes("--ci")&&(process.env.DASHNEX_CI="1");let n=process.cwd();const o=c.dirname(r(import.meta.url)),s=c.resolve(o,"..");process.env.DEBUG&&(console.log(`CLI started from directory: ${n}`),console.log(`CLI package directory: ${s}`),console.log(`Global node_modules: ${y??"not found"}`));const e=await async function(n){try{const s=[],e=/* @__PURE__ */new Set,t=n=>{e.has(n)||(e.add(n),s.push(n))},i=c.join(n,"dashnex.json");if(a.existsSync(i)){const o=c.join(n,"package.json");if(a.existsSync(o)){const n=JSON.parse(a.readFileSync(o,"utf8"));n.name&&t(n.name)}}const r=c.join(n,"package.json");if(a.existsSync(r)){const o=JSON.parse(a.readFileSync(r,"utf8")),s={...o.dependencies,...o.devDependencies,...o.optionalDependencies};for(const[e,i]of Object.entries(s)){if("string"==typeof i&&(i.startsWith("link:")||i.startsWith("file:"))){const o=c.resolve(n,i.replace(/^(link:|file:)/,""));if(a.existsSync(c.join(o,"dashnex.json"))){t(e);continue}}const o=c.join(n,"node_modules",e);a.existsSync(c.join(o,"dashnex.json"))&&t(e)}}if(y&&a.existsSync(y))try{const n=a.readdirSync(y);for(const o of n)if(o.startsWith("@")){const n=c.join(y,o);try{if(a.statSync(n).isDirectory()){const s=a.readdirSync(n);for(const n of s){const s=`${o}/${n}`,e=c.join(y,s);a.existsSync(c.join(e,"dashnex.json"))&&t(s)}}}catch{}}else{const n=c.join(y,o);a.existsSync(c.join(n,"dashnex.json"))&&t(o)}}catch(o){if(process.env.DEBUG){const n=o instanceof Error?o.message:String(o);console.log("⚠ Error scanning global node_modules:",n)}}return s}catch(o){if(process.env.DEBUG){const n=o instanceof Error?o.message:String(o);console.log("⚠ Error reading app package.json:",n)}return[]}}(n);e.includes("@dashnex/cli")||e.push("@dashnex/cli"),process.env.DEBUG&&(console.log(`CLI package directory: ${s}`),console.log(`Discovered modules: ${e.join(", ")}`));for(const r of e){let o=[];if("@dashnex/cli"===r)try{const n=c.join(s,"dist","commands","index.js");if(process.env.DEBUG&&console.log(`Loading @dashnex/cli commands from: ${n}`),await a.pathExists(n)){const s=await import(d(n).href);s.default?o=Array.isArray(s.default)?s.default:[]:s.commands&&(o=Array.isArray(s.commands)?s.commands:[]),process.env.DEBUG&&console.log(`Loaded ${o.length} commands from @dashnex/cli`)}}catch(m){if(process.env.DEBUG){const n=m instanceof Error?m.message:String(m);console.log(i.yellow(`Failed to load @dashnex/cli commands: ${n}`))}}else o=await j(r,n);for(const n of o)S(f,n)}const t=c.join(n,"dist","commands","index.js");if(await a.pathExists(t))try{const{default:n}=await import(d(t).href);if(n&&Array.isArray(n))for(const o of n)S(f,o)}catch(m){if(process.env.DEBUG){const n=m instanceof Error?m.message:String(m);console.error(i.yellow(`⚠ Failed to load application commands: ${n}`))}}f.parse(process.argv)})().catch(n=>{o(n)&&(console.log(i.yellow(s)),process.exit(0)),console.error(i.red("❌ CLI failed:"),n),process.exit(1)});
package/dist/client.js CHANGED
@@ -1 +1 @@
1
- import{n as s,t as e}from"./chunks/dashnex-BWlu5keu.js";var n={name:s.name,version:s.version,description:s.description,...e};export{n as default};
1
+ import{n as s,t as e}from"./chunks/dashnex-BKzrTB6t.js";var n={name:s.name,version:s.version,description:s.description,...e};export{n as default};
@@ -1 +1 @@
1
- import{a as e,c as t,d as o,f as s,h as n,i as r,l as a,m as i,n as c,o as l,p as d,r as p,s as u,t as h,u as m}from"../chunks/auth-ezwXxi-m.js";import f from"chalk";import g from"fs-extra";import w from"path";import{fileURLToPath as y}from"url";import{execFileSync as $,spawn as v,spawnSync as k}from"child_process";import x from"fs";import b from"inquirer";import{X509Certificate as S,createHash as E,createPrivateKey as D,randomBytes as T}from"crypto";import C from"net";import P from"os";import A from"adm-zip";import{diffLines as j}from"diff";import N from"ignore";import{WebSocket as I}from"partysocket";import F from"ws";import{inspect as O}from"node:util";import{rm as R}from"node:fs/promises";var B=e=>e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),_=async e=>{const t=(e=>{switch(process.platform){case"darwin":return{command:"open",args:[e]};case"win32":return{command:"cmd",args:["/c","start","",e]};default:return{command:"xdg-open",args:[e]}}})(e);return!!t&&new Promise(e=>{try{const n=v(t.command,t.args,{stdio:"ignore",detached:!0});n.on("error",t=>{s(t),e(!1)}),n.on("spawn",()=>{o(`Opened browser via ${t.command}`),n.unref(),e(!0)})}catch(n){s(n),e(!1)}})},z="urn:ietf:wg:oauth:2.0:oob",L=class extends Error{constructor(e,t){super(e),this.code=t,this.name="OAuthError"}},U=class extends Error{},M=class extends U{},W=e=>{const t=e.data;return t&&"object"==typeof t?t:e},J=e=>{const t=e.items??[];return Array.isArray(t)?t.map(e=>{if(!e||"object"!=typeof e)return null;const t=e,o=Number(t.id);return!Number.isFinite(o)||o<=0?null:{id:o,name:String(t.name??t.companyName??`Business ${o}`).trim()}}).filter(e=>null!==e):[]},H=async(s,n)=>{const r=[];let a=1,i=0;do{const c=`${t()}${s}?page=${a}&perPage=100`;o(`GET ${c}`);const{response:l,body:p}=await e(c,{headers:{Authorization:`Bearer ${n}`}});if(o(`Response: ${l.status}`),d(`Businesses response (${s})`,p),!l.ok){if(401===l.status)throw new M("Your DashNex ID session has expired.");if(404===l.status)throw new U(`Your DashNex ID account is not linked to a contact yet. Finish signing up at ${t()} and try again.`);throw new U("Failed to fetch businesses. Please try again.")}const u=W(p),h=J(u);if(i="number"==typeof u.total?u.total:h.length,r.push(...h),h.length<100||r.length>=i)break;a++}while(r.length<i);return r},G=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],X=(e="")=>{if(process.env.DASHNEX_CI)return{start:()=>{},stop:()=>{},text:()=>{}};let t=null,o=0,s=e;const n=()=>{const e=G[o%G.length];process.stderr.write(`\r${e} ${s}`),o++};return{start:e=>{void 0!==e&&(s=e),t||(o=0,n(),t=setInterval(n,80))},stop:()=>{t&&(clearInterval(t),t=null),process.stderr.write("\r\n")},text:e=>{s=e,t&&n()}}},q=class a{async execute(e={}){o("Login flow started");const t=r(process.cwd()),a=await h({exitOnFailure:!1,dashnexPath:t});if(a)console.log(f.green(`Already logged in as ${a.userName??"user"}`));else{m()||(console.error(f.red("No DashNex ID OAuth client is configured for this environment.")),console.error(f.yellow("Set DASHNEX_OAUTH_CLIENT_ID, or use APPLICATION_ENV=qa.")),process.exit(1));try{const s=await this.readSavedIdToken(t);if(s){o("Resuming with saved DashNex ID session");try{return void(await this.selectBusiness(s,t,e.business))}catch(c){if(!(c instanceof M))throw c;o("Saved DashNex ID session rejected, starting a new sign-in")}}const n=await this.authorize(!1!==e.browser);await this.writeConfig(t,{idToken:n.token,...n.refreshToken&&{idRefreshToken:n.refreshToken}}),await this.selectBusiness(n.token,t,e.business)}catch(c){if(s(c),n(c))return void console.log(f.yellow(i));if((c instanceof L||c instanceof U)&&(console.error(f.red(c.message)),process.exit(1)),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;console.error(f.red("Could not reach DashNex. Check your connection and try again.")),process.exit(1)}}}async authorize(s){const{verifier:n,challenge:r}=(()=>{const e=B(T(32));return{verifier:e,challenge:B(E("sha256").update(e).digest())}})(),a=(e=>{const o=new URL(`${t()}/api/oauth/authorize`);return o.searchParams.set("client_id",m()),o.searchParams.set("redirect_uri",z),o.searchParams.set("response_type","code"),o.searchParams.set("code_challenge",e),o.searchParams.set("code_challenge_method","S256"),o.toString()})(r);o(`Authorize URL: ${a}`);const i=!!s&&await _(a);console.log(""),i?(console.log(f.green("Opened your browser to finish signing in.")),console.log(f.dim("If nothing opened, use this URL:"))):console.log(f.bold("Open this URL to sign in:")),console.log(f.cyan(a)),console.log(""),console.log(f.dim("Approve the request, then copy the code shown and paste it below.")),console.log("");const{code:c}=await b.prompt([{type:"input",name:"code",message:"Paste the code:",validate:e=>!!e.trim()||"Code is required"}]),l=X();l.start("Verifying code...");try{return await(async(s,n)=>{const r=`${t()}/api/oauth/token`;o(`POST ${r}`);const{response:a,body:i}=await e(r,{method:"POST",body:JSON.stringify({grant_type:"authorization_code",client_id:m(),redirect_uri:z,code:s.trim(),code_verifier:n})});if(o(`Response: ${a.status}`),d("Token response",i),!a.ok){const e="string"==typeof i.error?i.error:void 0,t="string"==typeof i.error_description?i.error_description:void 0;if("invalid_grant"===e)throw new L("That code is not valid anymore. Codes expire 10 minutes after they are issued and can only be used once.",e);throw new L(t??"Could not exchange the code for a token.",e)}const c=i;if(!c.access_token)throw new L("The authorization server did not return an access token.");return{token:c.access_token,refreshToken:c.refresh_token,expiresIn:c.expires_in}})(c,n)}finally{l.stop()}}async selectBusiness(s,n,r){const a=X();let i;a.start("Fetching businesses...");try{i=await(async e=>{const t=await H("/api/businesses/my",e),s=await H("/api/businesses/other",e),n=/* @__PURE__ */new Map;for(const o of t)n.set(o.id,o);for(const o of s)n.has(o.id)||n.set(o.id,o);return o(`Businesses (my: ${t.length}, other: ${s.length}, merged: ${n.size})`),[...n.values()]})(s)}finally{a.stop()}0===i.length&&(console.error(f.red("No businesses or teams found for your account!")),console.log(f.green(`Create your first business at ${t()}`)),process.exit(1));const c=await this.pickBusiness(i,r);let l;a.start("Switching business...");try{l=await(async(s,n)=>{const r=`${t()}/api/businesses/${n}/switch`;o(`POST ${r}`);const{response:a,body:i}=await e(r,{method:"POST",headers:{Authorization:`Bearer ${s}`}});if(o(`Response: ${a.status}`),d("Switch response",i),!a.ok){if(401===a.status)throw new M("Your DashNex ID session has expired.");if(403===a.status)throw new U("You do not have access to that business.");throw new U("Failed to switch to business. Please try again.")}const c=W(i);if(!c.token||!c.refreshToken)throw new U("Invalid response from server. Please try again.");return{token:c.token,refreshToken:c.refreshToken,businessId:n}})(s,c.id)}finally{a.stop()}const p={token:l.token,refreshToken:l.refreshToken,businessId:l.businessId,...await this.fetchCliSettings(l.token)};await this.writeConfig(n,p),await this.ensureGitignore(),console.log(f.green(`Logged in as ${c.name}`))}async pickBusiness(e,t){if(t){const s=e.find(e=>String(e.id)===String(t).trim());return s||(console.error(f.red(`Business "${t}" not found.`)),process.exit(1)),o(`Selected business via flag: ${s.id} ${s.name}`),s}if(1===e.length)return o(`Selected business: ${e[0].id} ${e[0].name}`),e[0];const{businessId:s}=await b.prompt([{type:"select",name:"businessId",message:"Select business:",choices:e.map(e=>({name:e.name,value:e.id}))}]),n=e.find(e=>e.id===s)||e[0];return o(`Selected business: ${n.id} ${n.name}`),n}async readSavedIdToken(e){if(!(await g.pathExists(e)))return null;try{return(await g.readJson(e)).idToken??null}catch{return null}}async fetchCliSettings(t){try{const s=`${u()}/business/v1/cli/settings`;o(`GET ${s}`);const{response:n,body:r}=await e(s,{headers:{Authorization:`Bearer ${t}`}});if(o(`Response: ${n.status}`),d("CLI settings response",r),n.ok&&r&&"object"==typeof r)return r}catch(n){s(n)}return{}}static{this.OBSOLETE_KEYS=["issuer"]}async writeConfig(e,t){const s=w.dirname(e);await g.pathExists(s)&&(await g.stat(s)).isFile()&&await g.remove(s),await g.ensureDir(s);let n=t;if(await g.pathExists(e))try{n={...await g.readJson(e),...t};for(const e of a.OBSOLETE_KEYS)delete n[e]}catch{o("Existing settings.json could not be parsed, overwriting")}await g.writeJson(e,n,{spaces:2}),o("Saved credentials to .dashnex/settings.json")}async ensureGitignore(){const e=w.join(process.cwd(),".gitignore");if(!(await g.pathExists(e)))return;let t=await g.readFile(e,"utf8");t.includes(".dashnex")||(t=t.trimEnd(),t.endsWith("\n")||(t+="\n"),t+="\n.dashnex\n",await g.writeFile(e,t))}},Y="v1.4.4",V=w.join(p,"certificates"),K=["localhost","127.0.0.1","::1"],Z="win32"===process.platform,Q=()=>0===k("mkcert",["-version"],{stdio:"ignore",shell:Z}).status?"mkcert":null,ee=async(e={})=>{const t=(e.lookupPath??Q)();if(t)return t;const o=e.cacheDir??w.join(P.homedir(),".dashnex","mkcert"),s=((e=process.platform,t=process.arch)=>{const o="x64"===t?"amd64":t;if("win32"===e)return`mkcert-${Y}-windows-${o}.exe`;if("darwin"===e)return`mkcert-${Y}-darwin-${o}`;if("linux"===e)return`mkcert-${Y}-linux-${o}`;throw new Error(`Unsupported platform for mkcert: ${e}`)})(),n=w.join(o,s);if(await g.pathExists(n))return n;const r=`https://github.com/FiloSottile/mkcert/releases/download/${Y}/${s}`;e.log?.(`mkcert not found, downloading ${Y} to ${n}`);const a=await(e.fetchImpl??fetch)(r);if(!a.ok)throw new Error(`Failed to download mkcert from ${r}: HTTP ${a.status}`);await g.ensureDir(o);const i=`${n}.download`;return await g.writeFile(i,Buffer.from(await a.arrayBuffer())),await g.chmod(i,493),await g.move(i,n,{overwrite:!0}),n},te=(e,t,o)=>{try{const s=new S(g.readFileSync(t)),n=D(g.readFileSync(e));return!!s.checkPrivateKey(n)&&(!(new Date(s.validTo).getTime()<=Date.now())&&o.every(e=>((e,t)=>C.isIP(t)?Boolean(e.checkIP(t)):Boolean(e.checkHost(t)))(s,e)))}catch{return!1}},oe=async(e,t={})=>{const o=t.log??(()=>{}),n=t.certDir??V,r=w.resolve(e,n),a=w.join(r,"localhost-key.pem"),i=w.join(r,"localhost.pem"),c=(e=>{const t=(e??"").trim();return t&&!K.includes(t)?[...K,t]:[...K]})(t.host);try{if(te(a,i,c))return o(`Using existing local certificate from ${w.relative(e,r)||"."}`),{key:a,cert:i};const s=await(t.resolveMkcert??(()=>ee({log:o})))();if(await g.ensureDir(r),o("Generating a trusted local certificate with mkcert (this may prompt for your password once)..."),$(s,["-install","-key-file",a,"-cert-file",i,...c],{stdio:"inherit",shell:Z}),!(await g.pathExists(a))||!(await g.pathExists(i)))throw new Error("mkcert finished but the certificate files were not created");let l;await(async(e,t)=>{const o=w.join(e,".gitignore");if(!(await g.pathExists(o)))return!1;const s=await g.readFile(o,"utf8"),n=s.split(/\r?\n/).map(e=>e.trim()),r=new Set([t,`/${t}`,`${t}/`,`/${t}/`]);if(n.some(e=>r.has(e)))return!1;const a=0===s.length||s.endsWith("\n")?"":"\n";return await g.appendFile(o,`${a}${t}\n`),!0})(e,n.split(w.sep)[0]);try{const e=$(s,["-CAROOT"],{encoding:"utf8",shell:Z}).trim();e&&(l=w.join(e,"rootCA.pem"))}catch{}return o(`Certificates created in ${w.relative(e,r)||"."}`),{key:a,cert:i,...l?{rootCA:l}:{}}}catch(l){return s(l),o(`Failed to set up HTTPS certificates: ${l instanceof Error?l.message:String(l)}`),null}},se=["Using (vars|secrets) defined in ","\\(node:\\d+\\) MaxListenersExceededWarning:","\\(Use `node --trace-warnings","\\[DEP0205\\] DeprecationWarning:","\\(Use `node --trace-deprecation","Detected multiple renderers concurrently rendering the same context provider","\\[WARNING\\].*You have defined bindings to the following internal Durable Objects","You have defined bindings to the following internal Durable Objects",'\\{"name":".+","class_name":".+"\\}',"These will not work in local development, but they should work in production","If you want to develop these locally, you can define your DO in a separate Worker","For detailed instructions, refer to the Durable Objects section here:","developers.cloudflare.com/workers/wrangler/api#supported-bindings","workerd/server/server\\.c\\+\\+.*warning:.*DurableObjectNamespace"],ne=(e,t)=>t.length>0&&t.some(t=>t.test(e)),re=(e,t)=>{let s="";return{write:n=>{const r="string"==typeof n?n:n.toString();s+=r;const a=s.split(/\r?\n/);s=a.pop()??"";for(const s of a){const n=s.trim();n?ne(n,t)?o(`Filtered: ${n}`):e.write(s+"\n"):o("Filtered: <empty line>")}},flush:()=>{const n=s.trim();if(n){if(ne(n,t))return o(`Filtered: ${n}`),void(s="");e.write(s),s=""}else s=""}}},ae=async(e,t={})=>{const n=w.join(e,"dashnex.json"),r=w.join(e,"package.json");if(o(`Checking for dashnex.json at: ${n}`),!(await g.pathExists(n)))throw new Error("Run this command in a DashNex Web application folder.");if(o("dashnex.json found, checking for package.json"),!(await g.pathExists(r)))throw new Error("package.json is missing.");let a;o("package.json found, checking for dev script");try{a=await g.readJson(r)}catch(h){throw s(h),new Error("Failed to read package.json.")}if(!a.scripts||!a.scripts.dev)throw new Error('The "dev" script is missing from package.json. Please add a "dev" script to package.json.');const i=((e,t=process.env)=>{const o=e.port??t.PORT;if(null==o||""===String(o).trim())return;const s=Number(o);if(!Number.isInteger(s)||s<1||s>65535)throw new Error(`Invalid port: ${o}. Use a number between 1 and 65535.`);return s})(t),c=((e,t=process.env)=>{const o=(e.host??t.HOST??"").trim();return""===o?void 0:o})(t);o("dev script found, checking for npm availability");const l=await(async e=>new Promise(t=>{const o=v(`${e} --version`,{stdio:"ignore",shell:!0});o.on("error",()=>{t(!1)}),o.on("close",e=>{t(0===e)})}))("npm");if(o(`npm available: ${l}`),!l)throw new Error("npm is not available. Please install npm to continue.");const d={};if(t.https){const t=await oe(e,{host:c,log:e=>console.log(f.dim(e))});t?(d.DASHNEX_DEV_HTTPS_KEY=t.key,d.DASHNEX_DEV_HTTPS_CERT=t.cert,console.log(f.green("HTTPS enabled for the dev server"+(i?` on https://${c??"localhost"}:${i}`:""))),t.rootCA&&console.log(f.dim(`Local CA: ${t.rootCA} (import it in browsers on other machines, e.g. when the app runs in Docker)`))):console.log(f.yellow("HTTPS is not available, starting the dev server over HTTP instead."))}const p=[];void 0!==i&&p.push("--port",String(i)),void 0!==c&&p.push("--hostname",c);const u=p.length?["--",...p]:[];return o(`npm available, executing: npm run dev${u.length?` ${u.join(" ")}`:""} in ${e}`),(async(e,t=[],o=process.cwd(),n=[],r={})=>{const a=t.length?`${e} ${t.join(" ")}`:e,i=n.length>0;return new Promise((e,t)=>{const c=v(a,{stdio:i?["inherit","pipe","pipe"]:"inherit",cwd:o,shell:!0,env:{...process.env,NODE_ENV:"development",FORCE_COLOR:"1",...r}});if(c.on("error",e=>{s(e),t(e)}),i&&c.stdout&&c.stderr){const t=re(process.stdout,n),o=re(process.stderr,n);c.stdout.on("data",e=>t.write(e)),c.stderr.on("data",e=>o.write(e)),c.on("close",s=>{t.flush(),o.flush(),e(null===s?0:s)})}else c.on("close",t=>{e(null===t?0:t)})})})("npm run dev",u,e,(()=>{const e=[];for(const t of se)try{e.push(new RegExp(t))}catch{o(`Invalid dev output filter pattern ignored: ${t}`)}return e})(),d)},ie=async e=>new Promise(t=>{const o=v(`${e} --version`,{stdio:"ignore",shell:!0});o.on("error",()=>{t(!1)}),o.on("close",e=>{t(0===e)})}),ce=async e=>{let t;if(await ie("pnpm"))t="pnpm install --config.strict-dep-builds=false",o("Using package manager: pnpm");else{if(!(await ie("npm")))throw new Error("Neither pnpm nor npm is available. Install Node.js (which bundles npm) or pnpm to continue.");t="npm install --legacy-peer-deps",o("Using package manager: npm (with --legacy-peer-deps for DashNex peer-dep overlap)")}return o(`Executing: ${t} in ${e}`),new Promise((o,n)=>{const r=[],a=[],i=v(t,{stdio:["ignore","pipe","pipe"],cwd:e,shell:!0,env:{...process.env,NPM_CONFIG_LOGLEVEL:"error"}});i.stdout&&i.stdout.on("data",e=>r.push(e)),i.stderr&&i.stderr.on("data",e=>a.push(e)),i.on("error",e=>{s(e),n(e)}),i.on("close",e=>{const t=null===e?0:e;0!==t&&(r.length&&process.stdout.write(Buffer.concat(r)),a.length&&process.stderr.write(Buffer.concat(a))),o(t)})})},le="Run this command in a DashNex Web application folder.",de=e=>{const t=w.join(e,"dashnex.json");return g.pathExistsSync(t)},pe=(e,t=!1)=>{t||console.log(f.cyan(e))},ue=(e,t,n={})=>{const r=`${e} ${t.join(" ")}`,a=!0===n.silent;return new Promise((t,n)=>{o(`Running: ${r}`);const i=v(r,{stdio:a?["ignore","pipe","pipe"]:"inherit",cwd:process.cwd(),shell:!0});i.on("error",e=>{s(e),n(e)}),i.on("close",s=>{o(`${e} exited with code ${s}`),t(null===s?1:s)})})},he=(e,t)=>new Promise((n,r)=>{o(`Running: ${e} ${t.join(" ")}`);const a=v(e,t,{cwd:process.cwd()});let i="";a.stdout?.on("data",e=>{i+=e.toString()}),a.stderr?.on("data",e=>{i+=e.toString()}),a.on("error",e=>{s(e),r(e)}),a.on("close",t=>{o(`${e} exited with code ${t}`),n({exitCode:null===t?1:t,output:i})})}),me=async e=>{o("Running check: install");try{return 0===await ce(process.cwd())}catch(t){return s(t),!e&&t instanceof Error&&console.error(f.red(t.message)),!1}},fe=async()=>{try{const{output:e}=await he(process.execPath,[process.argv[1],"db","migrate","--help"]);return e.includes("Usage: dashnex db migrate")}catch(e){return s(e),!1}},ge=async e=>{o("Running check: db migrate");try{const{exitCode:t,output:s}=await he(process.execPath,[process.argv[1],"db","migrate"]);return 0===t||(s.includes("Unknown command")?(o("db migrate command is not available, skipping"),!0):(!e&&s.trim().length>0&&process.stderr.write(s),!1))}catch(t){return s(t),!0}},we=e=>new Promise(t=>{const o=v(`${e} --version`,{stdio:"ignore",shell:!0});o.on("error",()=>t(!1)),o.on("close",e=>t(0===e))}),ye=[{name:"TypeScript",command:"npx",args:["tsc","--noEmit"],notFoundMessage:"TypeScript is not available. Please install it with: npm install -D typescript"}],$e=class{async execute(){o("Check flow started"),de(process.cwd())||(console.error(f.red(le)),process.exit(1)),pe("Checking dependencies..."),await me(!1)||(console.error(f.red("Check failed.")),process.exit(1)),o(`Running ${ye.length} check(s)`);for(const t of ye){o(`Running check: ${t.name}`),pe(`Checking ${t.name}...`),await we(t.command)||(console.error(f.red(t.notFoundMessage)),process.exit(1));try{0!==await ue(t.command,t.args)&&(console.error(f.red("Check failed.")),process.exit(1))}catch(e){s(e),console.error(f.red(t.notFoundMessage)),process.exit(1)}}await fe()?(pe("Checking database migrations..."),await ge(!1)||(console.error(f.red("Check failed.")),process.exit(1))):o("db migrate command is not available, skipping"),console.log(f.green("All checks passed."))}async run(e=!1){if(o("Running checks (called from push)"),!de(process.cwd()))return e||console.error(f.red(le)),!1;if(pe("Checking dependencies...",e),!(await me(e)))return!1;const t=e?{silent:!0}:void 0;for(const r of ye){if(o(`Running check: ${r.name}`),pe(`Checking ${r.name}...`,e),!(await we(r.command)))return console.error(f.red(r.notFoundMessage)),!1;try{if(0!==await ue(r.command,r.args,t))return!1}catch(n){return s(n),console.error(f.red(r.notFoundMessage)),!1}}if(await fe()){if(pe("Checking database migrations...",e),!(await ge(e)))return!1}else o("db migrate command is not available, skipping");return e||console.log(f.green("All checks passed.")),!0}},ve=" │ ",ke=e=>e.subarray(0,8192).includes(0),xe=e=>{const t=e.split("\n");return""===t[t.length-1]&&t.pop(),t},be=(e,t)=>{if(null===e)return" ".repeat(t);const o=e.replace(/\t/g," ");return o.length<=t?o.padEnd(t):`${o.slice(0,Math.max(0,t-1))}…`},Se=(e,t,o)=>{const s=Math.max(o??process.stdout.columns??120,43),n=Math.floor((s-3)/2),r=((e,t)=>{const o=[],s=j(e,t);for(let n=0;n<s.length;n+=1){const e=s[n];if(e.removed){const t=xe(e.value),r=s[n+1],a=r?.added?xe(r.value):[];r?.added&&(n+=1);const i=Math.max(t.length,a.length);for(let e=0;e<i;e+=1)o.push({left:t[e]??null,right:a[e]??null,changed:!0})}else if(e.added)for(const t of xe(e.value))o.push({left:null,right:t,changed:!0});else for(const t of xe(e.value))o.push({left:t,right:t,changed:!1})}return o})(e,t),a=/* @__PURE__ */new Set;r.forEach((e,t)=>{if(e.changed)for(let o=Math.max(0,t-3);o<=Math.min(r.length-1,t+3);o+=1)a.add(o)});const i=[];i.push(f.bold(be("local (current)",n))+f.dim(ve)+f.bold("incoming"));let c=-1,l=0,d=0;for(let p=0;p<r.length;p+=1){if(!a.has(p))continue;if(l>=200){d+=1;continue}-1!==c&&p>c+1&&i.push(f.dim("···")),c=p,l+=1;const e=r[p],t=be(e.left,n),o=be(e.right,n);if(!e.changed){i.push(f.dim(t)+f.dim(ve)+f.dim(o));continue}const s=null!==e.left?f.red(t):t,u=null!==e.right?f.green(o):o;i.push(s+f.dim(ve)+u)}return d>0&&i.push(f.dim(`… ${d} more diff line(s) not shown`)),i.join("\n")},Ee=[".dashnex",".git",".vinext",".wrangler","wrangler.jsonc","wrangler.toml",".dev.vars",".github"],De=[".env","wrangler.jsonc"],Te=e=>w.join(e,p,"sync.json"),Ce=e=>E("sha1").update(`blob ${e.length}\0`).update(e).digest("hex"),Pe=e=>e.split(w.sep).join("/"),Ae=e=>Ee.some(t=>e===t||e.startsWith(`${t}/`)),je=async e=>{const t=await(async e=>{const t=N();t.add(Ee);const o=w.join(e,".gitignore");return await g.pathExists(o)&&t.add(await g.readFile(o,"utf8")),t})(e),o=[],s=async n=>{const r=await g.readdir(n,{withFileTypes:!0});for(const a of r){const r=w.join(n,a.name),i=Pe(w.relative(e,r));Ae(i)||t.ignores(a.isDirectory()?`${i}/`:i)||(a.isDirectory()?await s(r):a.isFile()&&o.push(i))}};return await s(e),o},Ne=async(e,t={})=>{const o={},s=await je(e);for(const n of s)o[n]=Ce(await g.readFile(w.join(e,n)));if(t.includeGenerated)for(const n of De){if(n in o)continue;const t=w.join(e,n);(await g.lstat(t).catch(()=>null))?.isFile()&&(o[n]=Ce(await g.readFile(t)))}return o},Ie=async e=>{try{const t=await g.readFile(Te(e),"utf8"),o=JSON.parse(t);return"string"!=typeof o?.commit||"object"!=typeof o?.manifest||null===o.manifest?null:o}catch{return null}},Fe=async(e,t,s)=>{const n={commit:t,manifest:s,updatedAt:/* @__PURE__ */(new Date).toISOString()},r=Te(e);try{await g.ensureDir(w.dirname(r)),await g.writeFile(r,`${JSON.stringify(n,null,2)}\n`),o(`Sync state written: commit ${t}, ${Object.keys(s).length} files`)}catch(a){o(`Failed to write sync state: ${a instanceof Error?a.message:"unknown"}`)}},Oe=1048576,Re=async(e,t)=>{const{install:n}=await b.prompt([{type:"confirm",name:"install",message:"Install dependencies?",default:!0}]);if(!n){if(w.resolve(e)!==w.resolve(t)){const o=w.relative(t,e);console.log(f.cyan(`Run "cd ${o}" to change to the application folder.`))}return}try{const t=X();t.start("Installing dependencies...");try{const s=await ce(e);if(t.stop(),0!==s)return void o(`install exited with code ${s}`)}catch(i){throw t.stop(),i}}catch(i){return s(i),void console.error(f.red(i instanceof Error?i.message:"Failed to run install."))}const{migrate:r}=await b.prompt([{type:"confirm",name:"migrate",message:"Create or update database?",default:!0}]);if(!r)return;o(`Running dashnex db migrate in ${e}`);try{const t=X();t.start("Creating or updating database...");try{const n=await((e,t,o)=>{const n=`${w.join(e,"node_modules",".bin")}${w.delimiter}${process.env.PATH??""}`,r={...process.env,PATH:n};return new Promise((n,a)=>{const i=v(t,{cwd:e,shell:!0,stdio:"inherit",env:o?{...r,...o}:r});i.on("error",e=>{s(e),a(e)}),i.on("close",e=>{n(null===e?0:e)})})})(e,"dashnex db migrate");if(t.stop(),0!==n)return void o(`dashnex db migrate exited with code ${n}`)}catch(i){throw t.stop(),i}}catch(i){return s(i),void console.error(f.red("Failed to run dashnex db migrate."))}const{dev:a}=await b.prompt([{type:"confirm",name:"dev",message:"Run development server?",default:!0}]);if(a)try{await ae(e)}catch(i){s(i),console.error(f.red(i instanceof Error?i.message:"Failed to run dev server."))}},Be=(e,t)=>{if(e.length!==t.length)return`local ${e.length} bytes, incoming ${t.length} bytes`;const o=e.length;for(let s=0;s<o;s+=1)if(e[s]!==t[s]){return`size ${o} matches; first diff at byte ${s} (local=0x${e[s].toString(16).padStart(2,"0")} incoming=0x${t[s].toString(16).padStart(2,"0")})`}return`size ${o} matches; no byte difference (unexpected)`},_e=async(e,t)=>{let o;try{o=await g.lstat(e)}catch{return{kind:"new"}}if(o.isDirectory())return{kind:"different",reason:"target is a directory"};if(o.size!==t.length)return{kind:"different",reason:`local ${o.size} bytes, incoming ${t.length} bytes`};const s=await g.readFile(e);return 0===Buffer.compare(s,t)?{kind:"identical"}:{kind:"different",reason:Be(s,t)}},ze=async(e,t,o)=>{console.log(`\n${f.bold(t)}`);try{const t=await g.readFile(e);if(t.length>Oe||o.length>Oe||ke(t)||ke(o))return void console.log(f.dim(`(no preview: ${Be(t,o)})`));console.log(Se(t.toString("utf8"),o.toString("utf8")))}catch(n){s(n),console.log(f.dim("(no preview available)"))}},Le=async e=>{const{choice:t}=await b.prompt([{type:"expand",name:"choice",message:`Overwrite ${e}?`,default:"y",choices:[{key:"y",name:"yes (overwrite this file)",value:"yes"},{key:"n",name:"no (keep local version)",value:"no"},{key:"a",name:"overwrite all remaining differing files",value:"all"},{key:"s",name:"skip all remaining differing files",value:"skip"}]}]);return t},Ue=async(e,t)=>{const o=t?f.yellow(" (has local changes!)"):"",{choice:s}=await b.prompt([{type:"expand",name:"choice",message:`Delete ${e}? It no longer exists in the application.${o}`,default:"y",choices:[{key:"y",name:"yes (delete this file)",value:"yes"},{key:"n",name:"no (keep this file)",value:"no"},{key:"a",name:"delete all remaining removed files",value:"all"},{key:"s",name:"keep all remaining removed files",value:"skip"}]}]);return s},Me=async(e,t)=>{let o=w.dirname(e);const s=w.resolve(t);for(;w.resolve(o)!==s;)try{if((await g.readdir(o)).length>0)return;await g.rmdir(o),o=w.dirname(o)}catch{return}},We=(e,t)=>w.resolve(e)===w.resolve(t)?"Application is successfully pulled.":`Application is successfully pulled into ${w.relative(t,e)}.`,Je=class{async execute(e={}){o("Pull flow started");const t=await h();if(!t)return;const r=process.cwd();let a;if(e.folder)a=e.folder.trim()||".",o(`Folder argument provided: ${a}`);else{o("No folder argument, prompting user");const{folder:e}=await b.prompt([{type:"input",name:"folder",message:"Which folder to pull the application to?",default:"."}]);a=e.trim()||"."}const c=w.resolve(r,a);o(`Target folder resolved: ${c}`);try{const e=await g.lstat(c).catch(()=>null);e&&!e.isDirectory()&&(console.error(f.red(`Cannot pull into ${c}: path exists and is not a directory.`)),process.exit(1)),await g.ensureDir(c),o(`Target folder ensured: ${c}`)}catch(p){s(p);const e=p instanceof Error?p.message:"Unknown error";console.error(f.red(`Cannot create folder ${c}: ${e}`)),process.exit(1)}const l=w.join(P.tmpdir(),`dashnex-pull-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`),d=X();d.start("Analyzing local files...");try{const n=await Ie(c),a=await Ne(c,{includeGenerated:!0});o(`Local manifest has ${Object.keys(a).length} files`),d.text("Pulling application...");const i=await this.download(t.token,a);d.text("Downloading..."),await g.writeFile(l,i.buffer),o(`Zip written to temp file (${i.viaV2?"v2 diff":"legacy full"} pull)`),d.text("Extracting...");const u=new A(l).getEntries().filter(e=>!e.isDirectory);let h=null;const m=u.find(e=>".dashnex/pull.json"===e.entryName);if(m)try{h=JSON.parse(m.getData().toString("utf8"))}catch(p){s(p)}const y=u.filter(e=>".dashnex"!==e.entryName&&!e.entryName.startsWith(".dashnex/"));o(`Zip has ${y.length} file entries${h?`, meta commit ${h.commit}`:", no meta"}`);const $=e.yes||"1"===process.env.DASHNEX_CI;let v=$?"all":"prompt",k=!1,x=0,b=0,S=0,E=0,D=0;const T=async(e,t,o)=>{try{return await g.ensureDir(w.dirname(e)),await g.writeFile(e,t),o&&await g.chmod(e,o),!0}catch(p){return s(p),!1}};for(const e of y){const t=e.getData(),s=w.join(c,e.entryName),n=w.relative(c,s)||e.entryName,r=(e.header.attr??0)>>16&4095,a=await _e(s,t);if(o(`Entry ${e.entryName}: ${a.kind}${a.reason?` (${a.reason})`:""}`),"identical"===a.kind){E+=1;continue}if("new"===a.kind){await T(s,t,r)?x+=1:D+=1;continue}let i=!1;if("all"===v)i=!0;else if("none"===v)i=!1;else{d.stop(),await ze(s,n,t),k||(console.log(f.dim("Y = yes (default), n = skip, a = overwrite all, s = skip all, h = help")),k=!0);const r=await Le(n);o(`Entry ${e.entryName}: user chose ${r}`),"yes"===r?i=!0:"no"===r?i=!1:"all"===r?(v="all",i=!0):(v="none",i=!1),d.start("Extracting...")}i?await T(s,t,r)?b+=1:D+=1:S+=1}d.stop();let C=0,P=0;if(h&&h.deleted.length>0){const e=await this.applyDeletions(c,h.deleted,n,$);C=e.deleted,P=e.kept}h&&(E+=Math.max(0,Object.keys(h.manifest).length-y.length)),o(`Pull summary: ${x} new, ${b} overwritten, ${S} skipped, ${C} deleted, ${E} unchanged, ${D} failed`);const j=[`${x} new`,`${b} overwritten`,`${S} skipped`,`${E} unchanged`];if((C>0||P>0)&&j.splice(3,0,`${C} deleted`),D>0&&j.push(`${D} failed`),console.log(f.cyan(`Pulled: ${j.join(", ")}`)),h){const e=await Ne(c,{includeGenerated:!0});await Fe(c,h.commit,e)}w.resolve(c)!==w.resolve(r)?(console.log(f.green(We(c,r))),process.chdir(c),o(`Changed working directory to ${c}`)):console.log(f.green(We(c,r))),D>0&&(console.error(f.red(`${D} file(s) failed to write. See DEBUG output for details.`)),process.exit(1)),$?o("Non-interactive mode (--yes or --ci), skipping post-pull child commands"):await Re(c,r)}catch(p){if(d.stop(),s(p),p instanceof Error&&p.message.startsWith("EXIT:"))throw p;if(n(p))return void console.log(f.yellow(i));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}finally{await g.remove(l).catch(()=>{}),o("Temp zip removed")}}async download(e,t){const s=`${u()}/business/v1/cli/v2/pull`;o(`POST ${s}`);const n=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({manifest:t})});if(o(`v2 pull response: ${n.status}`),n.ok)return{buffer:Buffer.from(await n.arrayBuffer()),viaV2:!0};const r=await n.json().catch(()=>({}));var a,i;a=n.status,i=r,404===a&&"string"==typeof i.message&&i.message.startsWith("Cannot ")||this.failFromResponse(n.status,r),o("v2 pull endpoint unavailable, falling back to legacy pull");const c=`${u()}/business/v1/cli/pull`;o(`GET ${c}`);const l=await fetch(c,{headers:{Authorization:`Bearer ${e}`}});if(o(`Legacy pull response: ${l.status}`),!l.ok){const e=await l.json().catch(()=>({}));this.failFromResponse(l.status,e)}return{buffer:Buffer.from(await l.arrayBuffer()),viaV2:!1}}failFromResponse(e,t){let o="Failed to pull application.";if(401===e||403===e)o="Please run 'dashnex login' to authenticate.";else if(404===e)o="Business has no application. Run 'dashnex app create' to create one.";else{const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(t);e&&(o=e)}console.error(f.red(o)),process.exit(1)}async applyDeletions(e,t,n,r){let a=0,i=0;if(!n){const e=t.slice(0,20);console.log(f.yellow("These local files do not exist in the application (kept — no sync state yet):"));for(const t of e)console.log(f.yellow(` ${t}`));return t.length>e.length&&console.log(f.yellow(` … and ${t.length-e.length} more`)),{deleted:a,kept:t.length}}let c=r?"all":"prompt";for(const d of t){if(!(d in n.manifest)){o(`Deletion candidate ${d} was never synced, keeping`);continue}const t=w.join(e,d),r=await g.readFile(t).catch(()=>null);if(null===r)continue;const p=Ce(r)!==n.manifest[d];let u=!1;if("all"===c)u=!0;else if("none"===c)u=!1;else{const e=await Ue(d,p);o(`Deletion ${d}: user chose ${e}`),"yes"===e?u=!0:"no"===e?u=!1:"all"===e?(c="all",u=!0):(c="none",u=!1)}if(u)try{await g.remove(t),await Me(t,e),a+=1}catch(l){s(l),i+=1}else i+=1}return{deleted:a,kept:i}}},He=async e=>{const t=`${u()}/business/v1/agreements/payment-processing/status`;o(`GET ${t}`);const s=await fetch(t,{headers:{Authorization:`Bearer ${e}`}});if(o(`Payment agreement response: ${s.status}`),!s.ok)return!0;if((await s.json().catch(()=>({}))).hasAccepted)return!0;const n=`${await(async()=>"qa"===process.env.APPLICATION_ENV?"https://business.qa.dashnex.com":"https://business.dashnex.com")()}/money/agreement/`;return console.error(f.red(`You need to accept Master Payment Processing Agreement first by visiting this link: ${n}`)),!1},Ge=async(e,t={})=>{const n=t.ciMode??!1;return!!(await He(e))&&!!(await(async(e,t)=>{const n=`${u()}/business/v1/tos/latest`;o(`GET ${n}`);const r=await fetch(n,{headers:{Authorization:`Bearer ${e}`}});if(o(`TOS latest response: ${r.status}`),r.ok)return!0;if(404!==r.status)return!0;const a=`${u()}/business/v1/tos/current`;o(`GET ${a}`);const i=await fetch(a,{headers:{Authorization:`Bearer ${e}`}});if(o(`TOS current response: ${i.status}`),!i.ok)return o("Could not fetch current TOS, skipping check"),!0;const c=await i.json().catch(()=>({})),l=c.version??"unknown";if(c.text&&(console.log(f.dim("─".repeat(60))),console.log(f.bold(`Terms of Service ${l}`)),console.log(f.dim("─".repeat(60))),console.log(c.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(f.dim("─".repeat(60)))),t)return console.log(f.yellow(`By proceeding you accept the Terms of Service ${l}.`)),!0;const{accept:d}=await b.prompt([{type:"confirm",name:"accept",message:`By creating an application you accept the Terms of Service ${l}. Continue?`,default:!0}]);if(!d)return console.log(f.yellow("Cancelled.")),!1;try{const t=`${u()}/business/v1/tos/${c.id}/accept`;o(`POST ${t}`),await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({})})}catch(p){s(p)}return!0})(e,n))},Xe=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,qe=e=>new Promise(t=>setTimeout(t,e)),Ye=e=>e.appFullCustomDomain?e.appFullCustomDomain:e.subdomain?"qa"===(process.env.APPLICATION_ENV??"")?`https://${e.subdomain}.dashnex.dev`:`https://${e.subdomain}.dashnexcloud.com`:null,Ve=3e5,Ke=99,Ze=e=>new Promise(t=>setTimeout(t,e)),Qe=async(e,t,n,r)=>{const a=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"text/event-stream"}});if(o(`SSE connection opened: ${a.status}`),!a.ok){const e=a.status;let t="Failed to start deployment.";if(401===e||403===e)t="Please run 'dashnex login' to authenticate.";else try{const e=await a.text(),o=JSON.parse(e);"string"==typeof o.error?t=o.error:"string"==typeof o.message&&(t=o.message)}catch{}throw console.error(f.red(t)),new Error(`HTTP ${e}: ${t}`)}if(!a.body)throw new Error("Response body is null");o("SSE connection established successfully"),r?.();const i=a.body.getReader();try{for await(const e of async function*(e){const t=new TextDecoder("utf-8");let o="";for(;;){const{value:s,done:n}=await e.read();if(n)break;o+=t.decode(s,{stream:!0});const r=o.split("\n");o=r.pop()||"";let a="";for(const e of r)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})}}(i))try{if(!e.data){o("Received empty SSE event");continue}const t=JSON.parse(e.data);o(`SSE message received: ${JSON.stringify(t)}`),n(t)}catch(c){s(c),o(`Failed to parse SSE event data: ${e.data}`)}}finally{i.releaseLock()}},et=class{async execute(e={}){o("Deploy flow started");const t=await h();if(!t)return;if(!1!==e.check?(o("Running pre-deploy checks"),await(new $e).run(!1)||(console.error(f.red("Deploy aborted: checks failed. Re-run with --no-check to skip.")),process.exit(1))):o("Skipping pre-deploy checks (--no-check)"),!(await Ge(t.token,{ciMode:!0})))return;const r=`${a()}/business/v1/applications/deploy`;o(`GET ${r} (SSE)`);let c=0,l="",d=!1,p=0,u=!1;const m=X();let g=0,w=0,y=null;const $=(e,t)=>{const o=Math.round(e);m.text(`[${o}%] ${t}`)},v=()=>{k();const e=c,t=Date.now(),o=Ve*((Ke-e)/Ke);y=setInterval(()=>{const s=Date.now()-t;let n;if(w>t){const e=Date.now()-w,t=Ke-g,o=3030.3030303030305*t;n=Math.min(g+e/o*t,Ke)}else n=Math.min(e+s/o*(Ke-e),Ke);n>c&&(c=n,$(c,l))},200)},k=()=>{y&&(clearInterval(y),y=null)};let x=!1;const b=e=>{if(u=!0,"string"==typeof e.error)return k(),m.stop(),console.error(f.red(e.error)),d=!0,void(x=!0);"string"==typeof e.message&&(l=e.message),"number"==typeof e.progress&&(g=e.progress,w=Date.now(),e.progress>c&&(c=e.progress)),"string"!=typeof e.message&&"number"!=typeof e.progress||(c>=100?(k(),m.stop(),d=!0):$(c,l))};for(;p<=5;)try{return u?$(c,l):m.start("Connecting..."),v(),await Qe(r,t.token,b,()=>{u||(m.text(`[${Math.round(c)}%] Deployment in progress...`),l="Deployment in progress...")}),k(),m.stop(),o("SSE connection closed"),x&&process.exit(1),void(d&&await this.showDeployedUrl(t.token))}catch(S){if(k(),s(S),o(`SSE connection error: ${S}`),d)return m.stop(),void(x&&process.exit(1));if(n(S))return m.stop(),void console.log(f.yellow(i));S instanceof Error&&S.message.startsWith("HTTP")&&(m.stop(),console.error(f.red("Could not complete deployment. Check your connection and try again.")),process.exit(1)),p++,p>5&&(m.stop(),console.error(f.red("Deployment failed. Maximum reconnection attempts exceeded.")),process.exit(1));const e=Math.min(1e3*Math.pow(2,p-1),3e4);o(`Connection error. Reconnecting in ${e/1e3}s... (attempt ${p}/5)`),await Ze(e)}}async showDeployedUrl(e){try{const t=`${u()}/business/v1/applications`;o(`GET ${t} (for deployed URL)`);const s=await fetch(t,{headers:{Authorization:`Bearer ${e}`}});if(!s.ok)return;const n=await s.json().catch(()=>({})),r=Ye({subdomain:n.subdomain,appFullCustomDomain:n.appFullCustomDomain});r&&console.log(`Application is deployed to ${f.cyan(r)}`)}catch(t){s(t)}}},tt=104857600,ot=class extends Error{},st=class extends Error{},nt=class extends Error{},rt="/business/v1/cli/tail-token";async function at(e,t={}){const o=`${u()}${rt}${t.debug?"?debug=1":""}`;try{await fetch(o,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})}catch{}}var it=["log","info","warn","error","debug"],ct={error:4,warn:3,log:2,info:2,debug:1};function lt(e){return"string"==typeof e&&it.includes(e)}function dt(e){return e.map(e=>"string"==typeof e?e:function(e){try{return JSON.stringify(e)}catch{return String(e)}}(e)).join(" ")}function pt(e){return e<10?`0${e}`:String(e)}function ut(e){const t=new Date(e);return`${pt(t.getHours())}:${pt(t.getMinutes())}:${pt(t.getSeconds())}.${o=t.getMilliseconds(),o<10?`00${o}`:o<100?`0${o}`:String(o)}`;var o}function ht(e,t){if("string"==typeof e)return e;if("object"==typeof(o=e)&&null!==o&&"string"==typeof o.name&&"string"==typeof o.message&&Object.keys(o).every(e=>"name"===e||"message"===e||"stack"===e)){const t=`${e.name}: ${e.message}`;return e.stack?`${t}\n${e.stack}`:t}var o;return O(e,{colors:t,depth:2,breakLength:120})}var mt={error:e=>f.red(e),warn:e=>f.yellow(e),debug:e=>f.dim(e),log:e=>e,info:e=>e};function ft(e,t){const o=t.color?f.dim(ut(e.ts)):ut(e.ts),s=e.level.toUpperCase().padEnd(5),n=[o,t.color?mt[e.level](s):s];n.push(e.args.map(e=>ht(e,t.color)).join(" "));let r=n.join(" ");if(e.truncated){const e=" …(truncated)";r+=t.color?f.dim(e):e}return r}function gt(e,t,o){let s;try{s=JSON.parse(e)}catch{return{kind:"malformed",raw:e}}if("object"!=typeof s||null===s||!lt(s.level))return{kind:"malformed",raw:e};const n=s;return Array.isArray(n.args)||(n.args=void 0===n.args?[]:[n.args]),r=n.level,a=t.minLevel,ct[r]>=ct[a]&&function(e,t){return!t||t.test(dt(e.args))}(n,t.filter)?{kind:"line",line:ft(n,o)}:{kind:"filtered"};var r,a}var wt=new Set([4401,4403]);var yt=[{label:"node_modules",segments:["node_modules"],description:"installed dependencies"},{label:"node_modules/.vite",segments:["node_modules",".vite"],description:"vite cache"},{label:"node_modules/.vite-temp",segments:["node_modules",".vite-temp"],description:"vite cache"},{label:"src/dashnex",segments:["src","dashnex"],description:"generated module registry"},{label:"dist",segments:["dist"],description:"build output"}],$t={label:".wrangler",segments:[".wrangler"],description:"local database"},vt=async e=>{await R(e,{recursive:!0,force:!0,maxRetries:5,retryDelay:100})},kt={name:"app",description:"Manage DashNex applications (should be executed in application folder)",handler:{execute:async()=>{}},options:[],subcommands:[{name:"create",description:"Create a new DashNex application",handler:new class{async pollApplicationCreated(e,t,n=5e3,r=6e4){const a=Date.now();let i=0;for(;Date.now()-a<r;){i++,o(`Polling application status (attempt ${i})...`);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(c){s(c),o(`Poll attempt ${i} failed with network error`)}await qe(n)}return{ready:!1}}async execute(e={}){o("Create flow started");const t=await h();if(!t)return;o("Auth valid, checking if business already has application");const r=X(),a=`${u()}/business/v1/applications`;o(`GET ${a}`),r.start("Checking application status...");try{const e=await fetch(a,{headers:{Authorization:`Bearer ${t.token}`}});r.stop(),o(`Applications response: ${e.status}`),o(`Applications response body: ${await e.text()}`),404!==e.status&&(console.error(f.red("Business already has an application. Run 'dashnex app pull' to pull the existing one.")),process.exit(1))}catch(y){if(r.stop(),s(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(n(y))return void console.log(f.yellow(i));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}o("No existing application, checking agreements");const c=void 0!==e.subdomain;if(!(await Ge(t.token,{ciMode:c})))return;let l;o("Agreements checked, proceeding to subdomain prompt");const d=e=>`${u()}/business/v1/applications/check-subdomain?subdomain=${encodeURIComponent(e)}`;let p=e.subdomain?.trim();for(;;){if(p)l=p,p=void 0,o(`Subdomain provided via flag: ${l}`);else{if(c)return console.error(f.red("Subdomain is not available.")),void process.exit(1);{const{sub:e}=await b.prompt([{type:"input",name:"sub",message:"Pick your subdomain:",validate:e=>!!e.trim()||"Subdomain is required"}]);l=e.trim()}}o(`Checking subdomain: ${l}`);const e=d(l);o(`GET ${e}`),r.start("Checking subdomain...");try{const s=await fetch(e,{headers:{Authorization:`Bearer ${t.token}`}});r.stop(),o(`Check subdomain response: ${s.status}`);const n=await s.text();if(o(`Check subdomain response body: ${n}`),!s.ok){const e=s.headers.get("content-type")??"";let t="Failed to check subdomain availability.";if(401!==s.status&&403!==s.status||(t="Please run 'dashnex login' to authenticate.",console.error(f.red(t)),process.exit(1)),e.includes("application/json")){const e=JSON.parse(n);o(`Check subdomain error body: ${JSON.stringify(e)}`);const s=Xe(e);s&&(t=s)}console.error(f.red(t));continue}const a=JSON.parse(n);if(o(`Check subdomain parsed body: ${JSON.stringify(a)}`),a.available){o(`Subdomain ${l} is available`);break}console.error(f.red("Subdomain is not available. Please choose a different one."))}catch(y){if(r.stop(),s(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(n(y))return void console.log(f.yellow(i));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}const m=`${u()}/business/v1/cli/create`;o(`POST ${m}`);const g={subdomain:l};e.template&&(g.template=e.template,o(`Template: ${e.template}`));const w=JSON.stringify(g);o(`Create request body: ${w}`),r.start("Creating application...");try{const a=await fetch(m,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:w});r.stop(),o(`Create response: ${a.status}`);const l=await a.text();if(o(`Create response body: ${l}`),503===a.status){o("Create returned 503, polling for application creation..."),r.start("Waiting for application to be ready...");const e=`${u()}/business/v1/applications`,s=await this.pollApplicationCreated(e,t.token);r.stop(),s.ready||(console.error(f.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(f.red("Application creation failed. Please try again.")),process.exit(1)),o("Application found after polling")}else if(!a.ok){const e=a.headers.get("content-type")??"";let t="Failed to create application.";if(401===a.status||403===a.status)t="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e=JSON.parse(l);o(`Create error body parsed: ${JSON.stringify(e)}`);const s=Xe(e);s&&(t=s)}console.error(f.red(t)),process.exit(1)}let d;if(o("Application created successfully"),!0===e.pull?(d=!0,o("--pull flag set, pulling without prompting")):!1===e.pull?(d=!1,o("--no-pull flag set, skipping pull")):c?(d=!1,o("CI mode (--subdomain), skipping pull")):(d=(await b.prompt([{type:"confirm",name:"pull",message:"Pull the application locally?",default:!0}])).pull,o(`User chose to pull: ${d}`)),d){o("Running pull flow");try{await(new Je).execute()}catch(y){if(s(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(n(y))return void console.log(f.yellow(i));console.error(f.red("Failed to pull application."))}}else console.log(f.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(y){if(r.stop(),s(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(n(y))return void console.log(f.yellow(i));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[{flags:"-t, --template <template>",description:"Template (name@branch-or-tag)",defaultValue:"webapp-base@live"},{flags:"--subdomain <subdomain>",description:"Subdomain (CI mode, skip prompts)"},{flags:"--pull",description:"Auto-pull after creation (skip prompt)"},{flags:"--no-pull",description:"Skip the pull prompt and show the success message"}]},{name:"pull",description:"Pull existing application to specified folder",handler:new Je,arguments:[{name:"folder",description:"Target folder (defaults to interactive prompt)"}],options:[{flags:"-y, --yes",description:"Skip prompts and child commands (CI mode)"}]},{name:"push",description:"Push local application to DashNex",handler:new class{async execute(e={}){o("Push flow started"),await g.pathExists(w.join(process.cwd(),"dashnex.json"))||(console.error(f.red("Not a DashNex application folder (dashnex.json not found).")),console.error(f.red("Run this command from your application root.")),process.exit(1)),!1!==e.check?(o("Running pre-push checks"),await(new $e).run(!1)||(console.error(f.red("Push aborted: checks failed. Re-run with --no-check to skip.")),process.exit(1))):o("Skipping pre-push checks (--no-check)");const t=await h();if(!t)return;const r=process.cwd(),a=X();try{a.start("Analyzing local files...");const s=await Ie(r),n=await Ne(r);o(`Local manifest has ${Object.keys(n).length} files`),a.text("Comparing with remote...");const i=await this.requestPlan(t.token,n,s?.commit);a.stop(),"legacy"===i?(o("v2 push endpoints unavailable, falling back to legacy zip push"),await this.pushLegacy(t.token,r,a)):await this.pushDiff(t.token,r,n,i,e,a),await this.promptAndDeploy(e)}catch(c){if(a.stop(),s(c),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;if(n(c))return void console.log(f.yellow(i));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}async requestPlan(e,t,s){const n=`${u()}/business/v1/cli/v2/push/plan`;o(`POST ${n}`);const r=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({manifest:t,lastSyncCommit:s})});if(o(`Plan response: ${r.status}`),r.ok)return await r.json();const a=await r.json().catch(()=>({}));if(((e,t)=>404===e&&"string"==typeof t.message&&t.message.startsWith("Cannot "))(r.status,a))return"legacy";this.failFromResponse(r.status,a,"Failed to push application.")}async pushDiff(e,t,s,n,r,a){let i=n;if(i.remoteChanged.length>0&&!r.force){console.error(f.red("Remote application has changes you don't have locally:"));for(const e of i.remoteChanged.slice(0,20))console.error(f.red(` ${e}`));i.remoteChanged.length>20&&console.error(f.red(` … and ${i.remoteChanged.length-20} more`)),console.error(f.red("Run 'dashnex app pull' first, or push anyway with --force.")),process.exit(1)}const c=i.upload.filter(e=>e in s);let l=i.delete;if(0!==c.length||0!==l.length){if(l.length>0){const e=await Ie(t),s=r.yes||"1"===process.env.DASHNEX_CI;console.log(f.yellow(`${l.length} file(s) will be deleted from the application repository:`));for(const t of l.slice(0,20))console.log(f.yellow(` ${t}`));if(l.length>20&&console.log(f.yellow(` … and ${l.length-20} more`)),!s){const{confirmDelete:t}=await b.prompt([{type:"confirm",name:"confirmDelete",message:"Delete these files from the remote repository?",default:null!==e}]);t||(o("User declined remote deletions, pushing without them"),l=[])}}if(0!==c.length||0!==l.length)for(let n=1;;n+=1){a.start(1===n?"Uploading changes...":"Remote changed, retrying...");const d=await this.applyPush(e,t,c,l,i.baseCommit);if(a.stop(),"ok"===d.status){await Fe(t,d.commit,s);const e=[`${c.length} file(s) updated`];return l.length>0&&e.push(`${l.length} deleted`),console.log(f.cyan(`Pushed: ${e.join(", ")}`)),void console.log(f.green("Application pushed successfully."))}n>=2&&(console.error(f.red("Remote repository keeps changing, please retry the push.")),process.exit(1)),o("Push apply conflicted, re-planning");const p=await Ie(t),u=await this.requestPlan(e,s,p?.commit);"legacy"===u&&(console.error(f.red("Failed to push application.")),process.exit(1)),u.remoteChanged.length>0&&!r.force&&(console.error(f.red("Remote application changed during the push. Run 'dashnex app pull' first, or push with --force.")),process.exit(1)),i=u}else console.log(f.green("Everything up to date."))}else console.log(f.green("Everything up to date."))}async applyPush(e,t,s,n,r){const a=new A;for(const o of s){const e=w.join(t,...o.split("/")),s=w.posix.dirname(o);a.addLocalFile(e,"."===s?"":s,w.posix.basename(o))}const i=w.join(P.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`);try{a.writeZip(i),o(`Diff zip written to ${i} (${s.length} files, ${n.length} deletions)`),await this.ensureZipWithinLimit(i);const t=`${u()}/business/v1/cli/v2/push/apply`;o(`POST ${t}`);const c=await g.readFile(i),l=new FormData;l.append("file",new Blob([c],{type:"application/zip"}),"diff.zip"),l.append("baseCommit",r),l.append("deletions",JSON.stringify(n));const d=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:l});if(o(`Apply response: ${d.status}`),409===d.status)return{status:"conflict"};if(!d.ok){const e=await d.json().catch(()=>({}));this.failFromResponse(d.status,e,"Failed to push application.")}return{status:"ok",commit:(await d.json().catch(()=>({}))).commit??""}}finally{await g.remove(i).catch(()=>{})}}async pushLegacy(e,t,s){const n=await Ne(t),r=Object.keys(n);o(`Legacy push including ${r.length} files`);const a=new A;for(const o of r){const e=w.join(t,...o.split("/")),s=w.posix.dirname(o);a.addLocalFile(e,"."===s?"":s,w.posix.basename(o))}const i=w.join(P.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`);try{s.start("Packaging application..."),a.writeZip(i),o(`Zip written to ${i}`),await this.ensureZipWithinLimit(i);const t=`${u()}/business/v1/cli/push`;o(`POST ${t}`);const n=await g.readFile(i),r=new FormData;r.append("file",new Blob([n],{type:"application/zip"}),"archive.zip"),s.text("Uploading...");const c=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:r});if(s.stop(),o(`Response: ${c.status}`),!c.ok){const e=await c.json().catch(()=>({}));this.failFromResponse(c.status,e,"Failed to push application.")}console.log(f.green("Application pushed successfully."))}finally{await g.remove(i).catch(()=>{}),o("Temp zip removed")}}async ensureZipWithinLimit(e){const{size:t}=await g.stat(e);if(t>tt){const e=e=>(e/1048576).toFixed(1);console.error(f.red(`Push package is ${e(t)} MB — the maximum is ${e(tt)} MB.`)),console.error(f.red("Remove or .gitignore large files and try again.")),process.exit(1)}}failFromResponse(e,t,o){let s=o;if(401===e||403===e)s="Please run 'dashnex login' to authenticate.";else{const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(t);e&&(s=e)}console.error(f.red(s)),process.exit(1)}async promptAndDeploy(e){let t;void 0!==e.deploy?(t=e.deploy,o(`Deploy decided via flag: ${t}`)):"1"===process.env.DASHNEX_CI?(t=!1,o("CI mode: skipping deploy prompt (use --deploy to deploy)")):(t=(await b.prompt([{type:"confirm",name:"deploy",message:"Deploy the application?",default:!0}])).deploy,o(`User chose to deploy: ${t}`)),t&&(o("Running deploy flow"),await(new et).execute())}},options:[{flags:"--deploy",description:"Auto-deploy after push (skip prompt)"},{flags:"--no-deploy",description:"Skip deploy prompt"},{flags:"--no-check",description:"Skip pre-push checks"},{flags:"-f, --force",description:"Push even when the remote has changes you don't have locally"},{flags:"-y, --yes",description:"Skip prompts (CI mode)"}]},{name:"delete",description:"Delete application from DashNex",handler:new class{async execute(e={}){if(o("Delete flow started"),!e.yes){const{confirm:e}=await b.prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to delete this application? This action cannot be undone.",default:!1}]);if(!e)return o("User cancelled deletion"),void console.log(f.yellow("Deletion cancelled."))}const t=await h();if(!t)return;const r=`${u()}/business/v1/applications`;o(`DELETE ${r}`);const a=X();a.start("Deleting application...");try{const e=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`}});if(a.stop(),o(`Response: ${e.status}`),!e.ok){const t=e.headers.get("content-type")??"";let o="Failed to delete application.";if(401===e.status||403===e.status)o="Please run 'dashnex login' to authenticate.";else if(t.includes("application/json")){const t=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(await e.json().catch(()=>({})));t&&(o=t)}console.error(f.red(o)),process.exit(1)}const s=await e.json().catch(()=>({})),n="string"==typeof s.message?s.message:"Application deleted successfully.";o("Application deleted successfully"),console.log(f.green(n))}catch(c){if(a.stop(),s(c),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;if(n(c))return void console.log(f.yellow(i));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[{flags:"-y, --yes",description:"Skip confirmation prompt"}]},{name:"deploy",description:"Deploy application to DashNex",handler:new et,options:[{flags:"--no-check",description:"Skip pre-deploy checks"}]},{name:"status",description:"Show current application status",handler:new class{async execute(){o("Status flow started");const e=await h();if(!e)return;const t=`${u()}/business/v1/applications`;o(`GET ${t}`);const r=X();r.start("Fetching application status...");try{const s=await fetch(t,{headers:{Authorization:`Bearer ${e.token}`}});if(r.stop(),o(`Response: ${s.status}`),404===s.status)return void console.log(f.yellow("Application not created"));if(!s.ok){const e=s.headers.get("content-type")??"";let t="Failed to fetch application status.";if(401===s.status||403===s.status)t="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e=await s.json().catch(()=>({}));"string"==typeof e.error?t=e.error:"string"==typeof e.message&&(t=e.message)}console.error(f.red(t)),process.exit(1)}const n=await s.json().catch(()=>({}));o(`Application body: ${JSON.stringify(n)}`);const a=n.status??"unknown";console.log(`Status: ${f.cyan(a)}`);const i=Ye(n);i&&console.log(`URL: ${f.cyan(i)}`)}catch(a){if(r.stop(),s(a),a instanceof Error&&a.message.startsWith("EXIT:"))throw a;if(n(a))return void console.log(f.yellow(i));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[]},{name:"clear",description:"Delete local dependencies, caches and build output",handler:new class{async execute(e={}){o("Clear flow started");const t=process.cwd();g.pathExistsSync(w.join(t,"dashnex.json"))||(console.error(f.red("Run this command in a DashNex Web application folder.")),process.exit(1));const r=e.yes||"1"===process.env.DASHNEX_CI;o(`Non-interactive: ${r}`);try{const e=await this.collectTargets(t),n=w.join(t,...$t.segments),i=await g.pathExists(n),c=i&&!r;if(i&&r&&e.push($t),0===e.length&&!c)return void console.log(f.yellow("Nothing to clear."));const l=[];if(e.length>0){console.log("The following will be deleted:");for(const t of e)console.log(` ${f.cyan(t.label)} ${f.dim(`(${t.description})`)}`);if(!r){const{confirm:e}=await b.prompt([{type:"confirm",name:"confirm",message:"Delete these files?",default:!1}]);if(!e)return o("User cancelled clear"),void console.log(f.yellow("Cancelled."))}for(const n of e){const e=w.join(t,...n.segments);o(`Removing ${e}`);try{await vt(e),console.log(f.green(`Removed ${n.label}`))}catch(a){s(a),l.push(n.label)}}}if(c){const{confirm:e}=await b.prompt([{type:"confirm",name:"confirm",message:"Delete the local database as well?",default:!1}]);if(e){o(`Removing ${n}`);try{await vt(n),console.log(f.green(`Removed ${$t.label}`))}catch(a){s(a),l.push($t.label)}}}if(l.length>0){for(const e of l)console.error(f.red(`Could not delete ${e} — it may be in use. Stop 'dashnex dev' and try again.`));process.exit(1)}console.log(f.green("Clear complete. Run 'dashnex install' to set the application up again."))}catch(a){if(a instanceof Error&&a.message.startsWith("EXIT:"))throw a;if(s(a),n(a))return void console.log(f.yellow(i));throw a}}async collectTargets(e){const t=[];for(const o of yt)await g.pathExists(w.join(e,...o.segments))&&t.push(o);return t.filter(o=>!t.some(t=>t!==o&&((e,t)=>{const o=w.relative(t,e);return""!==o&&!o.startsWith("..")&&!w.isAbsolute(o)})(w.join(e,...o.segments),w.join(e,...t.segments))))}},options:[{flags:"-y, --yes",description:"Skip prompts and keep the local database (CI mode)"}]},{name:"tail",description:"Stream live console/debug logs from the deployed worker (Ctrl+C to stop)",handler:new class{async execute(e={}){const t=e.level??"log";lt(t)||(console.error(f.red(`Invalid --level '${e.level}'. Use one of: log, info, warn, error, debug.`)),process.exit(1));let n=null;if(e.filter)try{n=new RegExp(e.filter)}catch{console.error(f.red(`Invalid --filter regular expression: ${e.filter}`)),process.exit(1)}const r=await h();if(!r)return;const a=!!e.debug;let i;try{i=await async function(e,t={}){const s=`${u()}${rt}`;o(`POST ${s}${t.debug?" (debug)":""}`);const n=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({debug:!!t.debug})});if(o(`Response: ${n.status}`),401===n.status||403===n.status)throw new ot("Not authorised to tail this application.");if(404===n.status)throw new st("Business has no application, or the tail endpoint is unavailable.");if(!n.ok)throw new nt(`Failed to start tail (status ${n.status}).`);const r=await n.json().catch(()=>({}));if(!r.token||!r.workerUrl)throw new nt("Malformed tail-token response from the platform.");return{token:r.token,workerUrl:r.workerUrl,expiresAt:"number"==typeof r.expiresAt?r.expiresAt:0}}(r.token,{debug:a})}catch(k){s(k),k instanceof ot&&(console.error(f.red(k.message)),process.exit(1)),k instanceof st&&(console.error(f.red(k.message)),process.exit(2)),console.error(f.red(k instanceof Error?k.message:"Could not start tail. Check your connection.")),process.exit(3)}const c={color:!!process.stdout.isTTY},l={minLevel:t,filter:n},d=(p=i.workerUrl,`${/^(localhost|127\.0\.0\.1)/.test(p)?"ws":"wss"}://${p}/api/realtime/tail`);var p;const m=`dashnex.tail.token.${i.token}`;console.log(f.dim(`Tailing ${i.workerUrl} — Ctrl+C to stop.`)),a&&console.log(f.dim("Debug logging enabled on the worker (DEBUG=1); may take a minute to take effect."));let g=!1,w=Date.now();const y=setInterval(()=>{g||Date.now()-w>=3e4&&(console.log(f.dim("(no logs in 30s)")),w=Date.now())},5e3),$=new I(d,m,{WebSocket:F,connectionTimeout:1e4,maxReconnectionDelay:16e3}),v=async e=>{if(!g){g=!0,clearInterval(y);try{$.close()}catch{}await Promise.race([at(r.token,{debug:a}),new Promise(e=>setTimeout(e,3e3))]),process.exit(e)}};process.on("SIGINT",()=>{console.log(),v(0)}),$.binaryType="arraybuffer",$.addEventListener("message",e=>{w=Date.now();const t=gt("string"==typeof e.data?e.data:"",l,c);"line"===t.kind?console.log(t.line):"malformed"===t.kind&&console.error(f.dim(`[malformed frame] ${t.raw}`))}),$.addEventListener("close",e=>{if(!g)return wt.has(e.code)?(console.error(f.red("Tail token was rejected (auth). Exiting.")),void v(1)):void o(`socket closed (code ${e.code}); reconnecting…`)}),$.addEventListener("error",e=>{o(`socket error: ${e.message??"unknown"}`)}),await new Promise(()=>{})}},options:[{flags:"--level <level>",description:"Minimum level: log, info, warn, error, debug"},{flags:"--filter <regex>",description:"Only show records whose args match this regex"},{flags:"--debug",description:"Also enable DEBUG=1 on the worker so debug-gated logs are shown"}]}]},xt={name:"secrets",description:"Manage DashNex secrets",handler:{execute:async()=>{}},options:[],subcommands:[{name:"list",description:"List all secret names bound to the worker",handler:new class{async execute(){o("Secrets list flow started");const e=await h();if(!e)return;const t=`${u()}/business/v1/cli/secrets`;o(`GET ${t}`);const r=X();r.start("Fetching secrets...");try{const s=await fetch(t,{headers:{Authorization:`Bearer ${e.token}`}});if(r.stop(),o(`Response: ${s.status}`),!s.ok){let e="Failed to fetch secrets.";401===s.status||403===s.status?e="Please run 'dashnex login' to authenticate.":404===s.status?e="Business has no application.":502===s.status&&(e="Error fetching secrets. Make sure your application is deployed."),console.error(f.red(e)),process.exit(1)}const n=(await s.json()).secrets??[];if(0===n.length)return void console.log(f.yellow("No secrets set."));console.log(f.bold(`\nSecrets (${n.length}):\n`)),n.forEach(({name:e})=>{console.log(` ${f.cyan(e)}`)}),console.log("")}catch(a){if(r.stop(),s(a),a instanceof Error&&a.message.startsWith("EXIT:"))throw a;if(n(a))return void console.log(f.yellow(i));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[]},{name:"set",description:"Create or update a secret (prompts for missing KEY/VALUE)",handler:new class{async execute(e={}){o("Secrets set flow started");let{name:t,value:r}=e;const a="1"===process.env.DASHNEX_CI;t||(a&&(console.error(f.red("--name is required in CI mode (--ci).")),process.exit(1)),t=(await b.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim()),r||(a&&(console.error(f.red("--value is required in CI mode (--ci).")),process.exit(1)),r=(await b.prompt([{type:"password",name:"value",message:`Enter value for ${t}:`,mask:"*",validate:e=>""!==e||"Value is required"}])).value);const c=await h();if(!c)return;const l=`${u()}/business/v1/cli/secrets`;o(`PUT ${l}`);const d=X();d.start(`Setting secret '${t}'...`);try{const e=await fetch(l,{method:"PUT",headers:{Authorization:`Bearer ${c.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:t,value:r})});if(d.stop(),o(`Response: ${e.status}`),!e.ok){let t="Failed to set secret.";401===e.status||403===e.status?t="Please run 'dashnex login' to authenticate.":400===e.status?t="Missing or empty name / value.":404===e.status?t="Business has no application.":502===e.status&&(t="Error setting secret. Make sure your application is deployed."),console.error(f.red(t)),process.exit(1)}o(`Secret '${t}' set successfully`),console.log(f.green(`Secret '${t}' set successfully.`))}catch(p){if(d.stop(),s(p),p instanceof Error&&p.message.startsWith("EXIT:"))throw p;if(n(p))return void console.log(f.yellow(i));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},arguments:[{name:"name",description:"Secret name (KEY)"},{name:"value",description:"Secret value"}],options:[{flags:"--name <name>",description:"Secret name (alternative to positional KEY)"},{flags:"--value <value>",description:"Secret value (alternative to positional VALUE)"}]},{name:"delete",description:"Delete a secret (prompts for missing KEY)",handler:new class{async execute(e={}){o("Secrets delete flow started");let{name:t}=e;const r="1"===process.env.DASHNEX_CI;t||(r&&(console.error(f.red("--name is required in CI mode (--ci).")),process.exit(1)),t=(await b.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim());const a=await h();if(!a)return;const c=`${u()}/business/v1/cli/secrets/${encodeURIComponent(t)}`;o(`DELETE ${c}`);const l=X();l.start(`Deleting secret '${t}'...`);try{const e=await fetch(c,{method:"DELETE",headers:{Authorization:`Bearer ${a.token}`}});if(l.stop(),o(`Response: ${e.status}`),!e.ok){let o="Failed to delete secret.";401===e.status||403===e.status?o="Please run 'dashnex login' to authenticate.":404===e.status?o=`Secret '${t}' not found.`:502===e.status&&(o="Error deleting secret. Make sure your application is deployed."),console.error(f.red(o)),process.exit(1)}o(`Secret '${t}' deleted successfully`),console.log(f.green(`Secret '${t}' deleted.`))}catch(d){if(l.stop(),s(d),d instanceof Error&&d.message.startsWith("EXIT:"))throw d;if(n(d))return void console.log(f.yellow(i));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},arguments:[{name:"name",description:"Secret name (KEY)"}],options:[{flags:"--name <name>",description:"Secret name (alternative to positional KEY)"}]}]},bt=[{name:"version",description:"Display the version of the CLI",handler:new class{async execute(e){const t=w.dirname(y(import.meta.url)),o=JSON.parse(x.readFileSync(w.resolve(t,"..","..","package.json"),"utf8"));console.log(o.version)}},options:[]},{name:"login",description:"Log in to your DashNex account",handler:new q,options:[{flags:"--business <id>",description:"Business ID to select (skip prompt)"},{flags:"--no-browser",description:"Print the sign-in URL instead of opening a browser"}]},{name:"logout",description:"Log out and remove local credentials",handler:new class{async execute(){const e=r(process.cwd());if(await g.pathExists(e)){const t=await g.readJson(e);delete t.token,delete t.refreshToken,delete t.businessId,await g.writeJson(e,t,{spaces:2})}console.log(f.green("Logged out."))}},options:[]},{name:"whoami",description:"Show current logged-in business and user",handler:new class{async execute(){o("Whoami flow started");const e=await h();if(!e)return;const t=await c()?`${u()}/business/v1/`:`${l()}/users/v1/`;o(`GET ${t}`);const r=X();r.start("Fetching user info...");try{const s=await fetch(t,{headers:{Authorization:`Bearer ${e.token}`}});if(r.stop(),o(`Response: ${s.status}`),!s.ok){const e=s.headers.get("content-type")??"";let t="Failed to fetch user info.";if(401===s.status||403===s.status)t="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e="string"==typeof(a=await s.json().catch(()=>({}))).error?a.error:"string"==typeof a.message?a.message:void 0;e&&(t=e)}console.error(f.red(t)),process.exit(1)}const n=await s.json().catch(()=>({})),i="string"==typeof n.name?n.name:"string"==typeof n.companyName?n.companyName:"Unknown",c=n.memberUser,l=c&&"string"==typeof c.fullName?c.fullName:c&&"string"==typeof c.name?c.name:"Unknown";o(`Whoami: ${i} (${l})`),console.log(f.green(`You are logged in as ${i} (${l})`))}catch(d){if(r.stop(),s(d),d instanceof Error&&d.message.startsWith("EXIT:"))throw d;if(n(d))return void console.log(f.yellow(i));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}var a}},options:[]},{name:"dev",description:"Run the development server (run in DashNex application folder)",handler:new class{async execute(e={}){o("Dev flow started");try{const t=await ae(process.cwd(),e);process.exit(t)}catch(t){if(t instanceof Error&&t.message.startsWith("EXIT:"))throw t;s(t),t instanceof Error?console.error(f.red(t.message)):console.error(f.red("Failed to run npm run dev")),process.exit(1)}}},options:[{flags:"-p, --port <port>",description:"Port for the dev server (default: PORT env or 3000)"},{flags:"-H, --host <host>",description:"Host to bind, e.g. 0.0.0.0 inside Docker (default: HOST env or localhost)"},{flags:"--https",description:"Serve over HTTPS with a trusted local certificate (mkcert)"}]},{name:"check",description:"Run build-time validations (run in DashNex application folder)",handler:new $e,options:[]},{name:"install",description:"Install dependencies using pnpm (preferred) or npm (run in DashNex application folder)",handler:new class{async execute(){o("Install flow started");const e=w.join(process.cwd(),"dashnex.json");await g.pathExists(e)||(console.error(f.red("Run this command in a DashNex Web application folder.")),process.exit(1));const t=process.cwd(),n=X();n.start("Installing dependencies...");try{const e=await ce(t);n.stop(),0!==e&&process.exit(e),console.log(f.green("Dependencies installed.")),process.exit(0)}catch(r){n.stop(),s(r),r instanceof Error?console.error(f.red(r.message)):console.error(f.red("Failed to run install")),process.exit(1)}}},options:[]},kt,xt];export{bt as default};
1
+ import{a as e,c as t,d as o,f as s,g as n,h as r,i as a,l as i,m as c,n as l,o as d,p,r as u,s as h,t as m,u as g}from"../chunks/auth-DMO6V5r1.js";import f from"chalk";import w from"fs-extra";import y from"path";import{fileURLToPath as $}from"url";import{execFileSync as v,spawn as k,spawnSync as x}from"child_process";import b from"fs";import S from"inquirer";import{X509Certificate as E,createHash as D,createPrivateKey as T,randomBytes as C}from"crypto";import P from"net";import A from"os";import j from"adm-zip";import{diffLines as N}from"diff";import I from"ignore";import{WebSocket as F}from"partysocket";import R from"ws";import{inspect as O}from"node:util";import{rm as B}from"node:fs/promises";var z=e=>e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),_=async e=>{const t=(e=>{switch(process.platform){case"darwin":return{command:"open",args:[e]};case"win32":return{command:"cmd",args:["/c","start","",e]};default:return{command:"xdg-open",args:[e]}}})(e);return!!t&&new Promise(e=>{try{const o=k(t.command,t.args,{stdio:"ignore",detached:!0});o.on("error",t=>{p(t),e(!1)}),o.on("spawn",()=>{s(`Opened browser via ${t.command}`),o.unref(),e(!0)})}catch(o){p(o),e(!1)}})},L="urn:ietf:wg:oauth:2.0:oob",U=class extends Error{constructor(e,t){super(e),this.code=t,this.name="OAuthError"}},M=class extends Error{},W=class extends M{},J=e=>{const t=e.data;return t&&"object"==typeof t?t:e},H=e=>{const t=e.items??[];return Array.isArray(t)?t.map(e=>{if(!e||"object"!=typeof e)return null;const t=e,o=Number(t.id);return!Number.isFinite(o)||o<=0?null:{id:o,name:String(t.name??t.companyName??`Business ${o}`).trim()}}).filter(e=>null!==e):[]},X=async(e,t)=>{const o=[];let n=1,r=0;do{const a=`${i()}${e}?page=${n}&perPage=100`;s(`GET ${a}`);const{response:l,body:p}=await d(a,{headers:{Authorization:`Bearer ${t}`}});if(s(`Response: ${l.status}`),c(`Businesses response (${e})`,p),!l.ok){if(401===l.status)throw new W("Your DashNex ID session has expired.");if(404===l.status)throw new M(`Your DashNex ID account is not linked to a contact yet. Finish signing up at ${i()} and try again.`);throw new M("Failed to fetch businesses. Please try again.")}const u=J(p),h=H(u);if(r="number"==typeof u.total?u.total:h.length,o.push(...h),h.length<100||o.length>=r)break;n++}while(o.length<r);return o},G=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],q=(e="")=>{if(process.env.DASHNEX_CI)return{start:()=>{},stop:()=>{},text:()=>{}};let t=null,o=0,s=e;const n=()=>{const e=G[o%G.length];process.stderr.write(`\r${e} ${s}`),o++};return{start:e=>{void 0!==e&&(s=e),t||(o=0,n(),t=setInterval(n,80))},stop:()=>{t&&(clearInterval(t),t=null),process.stderr.write("\r\n")},text:e=>{s=e,t&&n()}}},Y=["issuer"],V=async(e,t,o={})=>{const n=q();let r;n.start("Fetching businesses...");try{r=await(async e=>{const t=await X("/api/businesses/my",e),o=await X("/api/businesses/other",e),n=/* @__PURE__ */new Map;for(const s of t)n.set(s.id,s);for(const s of o)n.has(s.id)||n.set(s.id,s);return s(`Businesses (my: ${t.length}, other: ${o.length}, merged: ${n.size})`),[...n.values()]})(e)}finally{n.stop()}0===r.length&&(console.error(f.red("No businesses or teams found for your account!")),console.log(f.green(`Create your first business at ${i()}`)),process.exit(1));const a=await K(r,o);let l;n.start("Switching business...");try{l=await(async(e,t)=>{const o=`${i()}/api/businesses/${t}/switch`;s(`POST ${o}`);const{response:n,body:r}=await d(o,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(s(`Response: ${n.status}`),c("Switch response",r),!n.ok){if(401===n.status)throw new W("Your DashNex ID session has expired.");if(403===n.status)throw new M("You do not have access to that business.");throw new M("Failed to switch to business. Please try again.")}const a=J(r);if(!a.token||!a.refreshToken)throw new M("Invalid response from server. Please try again.");return{token:a.token,refreshToken:a.refreshToken,businessId:t}})(e,a.id)}finally{n.stop()}return await Q(t,{token:l.token,refreshToken:l.refreshToken,businessId:l.businessId,...await Z(l.token)}),await ee(),a},K=async(e,t)=>{if(void 0!==t.businessId){const o=e.find(e=>String(e.id)===String(t.businessId).trim());return o||(console.error(f.red(`Business "${t.businessId}" not found.`)),process.exit(1)),s(`Selected business via argument: ${o.id} ${o.name}`),o}if(1===e.length)return s(`Selected business: ${e[0].id} ${e[0].name}`),e[0];const o=e.find(e=>String(e.id)===String(t.currentBusinessId)),{businessId:n}=await S.prompt([{type:"select",name:"businessId",message:"Select business:",choices:e.map(e=>({name:e===o?`${e.name} ${f.dim("(current)")}`:e.name,value:e.id})),...o&&{default:o.id}}]),r=e.find(e=>e.id===n)||e[0];return s(`Selected business: ${r.id} ${r.name}`),r},Z=async e=>{try{const o=`${t()}/business/v1/cli/settings`;s(`GET ${o}`);const{response:n,body:r}=await d(o,{headers:{Authorization:`Bearer ${e}`}});if(s(`Response: ${n.status}`),c("CLI settings response",r),n.ok&&r&&"object"==typeof r)return r}catch(o){p(o)}return{}},Q=async(e,t)=>{const o=y.dirname(e);await w.pathExists(o)&&(await w.stat(o)).isFile()&&await w.remove(o),await w.ensureDir(o);let n=t;if(await w.pathExists(e))try{n={...await w.readJson(e),...t};for(const e of Y)delete n[e]}catch{s("Existing settings.json could not be parsed, overwriting")}await w.writeJson(e,n,{spaces:2}),s("Saved credentials to .dashnex/settings.json")},ee=async()=>{const e=y.join(process.cwd(),".gitignore");if(!(await w.pathExists(e)))return;let t=await w.readFile(e,"utf8");t.includes(".dashnex")||(t=t.trimEnd(),t.endsWith("\n")||(t+="\n"),t+="\n.dashnex\n",await w.writeFile(e,t))},te="v1.4.4",oe=y.join(a,"certificates"),se=["localhost","127.0.0.1","::1"],ne="win32"===process.platform,re=()=>0===x("mkcert",["-version"],{stdio:"ignore",shell:ne}).status?"mkcert":null,ae=async(e={})=>{const t=(e.lookupPath??re)();if(t)return t;const o=e.cacheDir??y.join(A.homedir(),".dashnex","mkcert"),s=((e=process.platform,t=process.arch)=>{const o="x64"===t?"amd64":t;if("win32"===e)return`mkcert-${te}-windows-${o}.exe`;if("darwin"===e)return`mkcert-${te}-darwin-${o}`;if("linux"===e)return`mkcert-${te}-linux-${o}`;throw new Error(`Unsupported platform for mkcert: ${e}`)})(),n=y.join(o,s);if(await w.pathExists(n))return n;const r=`https://github.com/FiloSottile/mkcert/releases/download/${te}/${s}`;e.log?.(`mkcert not found, downloading ${te} to ${n}`);const a=await(e.fetchImpl??fetch)(r);if(!a.ok)throw new Error(`Failed to download mkcert from ${r}: HTTP ${a.status}`);await w.ensureDir(o);const i=`${n}.download`;return await w.writeFile(i,Buffer.from(await a.arrayBuffer())),await w.chmod(i,493),await w.move(i,n,{overwrite:!0}),n},ie=(e,t,o)=>{try{const s=new E(w.readFileSync(t)),n=T(w.readFileSync(e));return!!s.checkPrivateKey(n)&&(!(new Date(s.validTo).getTime()<=Date.now())&&o.every(e=>((e,t)=>P.isIP(t)?Boolean(e.checkIP(t)):Boolean(e.checkHost(t)))(s,e)))}catch{return!1}},ce=async(e,t={})=>{const o=t.log??(()=>{}),s=t.certDir??oe,n=y.resolve(e,s),r=y.join(n,"localhost-key.pem"),a=y.join(n,"localhost.pem"),i=(e=>{const t=(e??"").trim();return t&&!se.includes(t)?[...se,t]:[...se]})(t.host);try{if(ie(r,a,i))return o(`Using existing local certificate from ${y.relative(e,n)||"."}`),{key:r,cert:a};const c=await(t.resolveMkcert??(()=>ae({log:o})))();if(await w.ensureDir(n),o("Generating a trusted local certificate with mkcert (this may prompt for your password once)..."),v(c,["-install","-key-file",r,"-cert-file",a,...i],{stdio:"inherit",shell:ne}),!(await w.pathExists(r))||!(await w.pathExists(a)))throw new Error("mkcert finished but the certificate files were not created");let l;await(async(e,t)=>{const o=y.join(e,".gitignore");if(!(await w.pathExists(o)))return!1;const s=await w.readFile(o,"utf8"),n=s.split(/\r?\n/).map(e=>e.trim()),r=new Set([t,`/${t}`,`${t}/`,`/${t}/`]);if(n.some(e=>r.has(e)))return!1;const a=0===s.length||s.endsWith("\n")?"":"\n";return await w.appendFile(o,`${a}${t}\n`),!0})(e,s.split(y.sep)[0]);try{const e=v(c,["-CAROOT"],{encoding:"utf8",shell:ne}).trim();e&&(l=y.join(e,"rootCA.pem"))}catch{}return o(`Certificates created in ${y.relative(e,n)||"."}`),{key:r,cert:a,...l?{rootCA:l}:{}}}catch(c){return p(c),o(`Failed to set up HTTPS certificates: ${c instanceof Error?c.message:String(c)}`),null}},le=["Using (vars|secrets) defined in ","\\(node:\\d+\\) MaxListenersExceededWarning:","\\(Use `node --trace-warnings","\\[DEP0205\\] DeprecationWarning:","\\(Use `node --trace-deprecation","Detected multiple renderers concurrently rendering the same context provider","\\[WARNING\\].*You have defined bindings to the following internal Durable Objects","You have defined bindings to the following internal Durable Objects",'\\{"name":".+","class_name":".+"\\}',"These will not work in local development, but they should work in production","If you want to develop these locally, you can define your DO in a separate Worker","For detailed instructions, refer to the Durable Objects section here:","developers.cloudflare.com/workers/wrangler/api#supported-bindings","workerd/server/server\\.c\\+\\+.*warning:.*DurableObjectNamespace"],de=(e,t)=>t.length>0&&t.some(t=>t.test(e)),pe=(e,t)=>{let o="";return{write:n=>{const r="string"==typeof n?n:n.toString();o+=r;const a=o.split(/\r?\n/);o=a.pop()??"";for(const o of a){const n=o.trim();n?de(n,t)?s(`Filtered: ${n}`):e.write(o+"\n"):s("Filtered: <empty line>")}},flush:()=>{const n=o.trim();if(n){if(de(n,t))return s(`Filtered: ${n}`),void(o="");e.write(o),o=""}else o=""}}},ue=async(e,t={})=>{const o=y.join(e,"dashnex.json"),n=y.join(e,"package.json");if(s(`Checking for dashnex.json at: ${o}`),!(await w.pathExists(o)))throw new Error("Run this command in a DashNex Web application folder.");if(s("dashnex.json found, checking for package.json"),!(await w.pathExists(n)))throw new Error("package.json is missing.");let r;s("package.json found, checking for dev script");try{r=await w.readJson(n)}catch(h){throw p(h),new Error("Failed to read package.json.")}if(!r.scripts||!r.scripts.dev)throw new Error('The "dev" script is missing from package.json. Please add a "dev" script to package.json.');const a=((e,t=process.env)=>{const o=e.port??t.PORT;if(null==o||""===String(o).trim())return;const s=Number(o);if(!Number.isInteger(s)||s<1||s>65535)throw new Error(`Invalid port: ${o}. Use a number between 1 and 65535.`);return s})(t),i=((e,t=process.env)=>{const o=(e.host??t.HOST??"").trim();return""===o?void 0:o})(t);s("dev script found, checking for npm availability");const c=await(async e=>new Promise(t=>{const o=k(`${e} --version`,{stdio:"ignore",shell:!0});o.on("error",()=>{t(!1)}),o.on("close",e=>{t(0===e)})}))("npm");if(s(`npm available: ${c}`),!c)throw new Error("npm is not available. Please install npm to continue.");const l={};if(t.https){const t=await ce(e,{host:i,log:e=>console.log(f.dim(e))});t?(l.DASHNEX_DEV_HTTPS_KEY=t.key,l.DASHNEX_DEV_HTTPS_CERT=t.cert,console.log(f.green("HTTPS enabled for the dev server"+(a?` on https://${i??"localhost"}:${a}`:""))),t.rootCA&&console.log(f.dim(`Local CA: ${t.rootCA} (import it in browsers on other machines, e.g. when the app runs in Docker)`))):console.log(f.yellow("HTTPS is not available, starting the dev server over HTTP instead."))}const d=[];void 0!==a&&d.push("--port",String(a)),void 0!==i&&d.push("--hostname",i);const u=d.length?["--",...d]:[];return s(`npm available, executing: npm run dev${u.length?` ${u.join(" ")}`:""} in ${e}`),(async(e,t=[],o=process.cwd(),s=[],n={})=>{const r=t.length?`${e} ${t.join(" ")}`:e,a=s.length>0;return new Promise((e,t)=>{const i=k(r,{stdio:a?["inherit","pipe","pipe"]:"inherit",cwd:o,shell:!0,env:{...process.env,NODE_ENV:"development",FORCE_COLOR:"1",...n}});if(i.on("error",e=>{p(e),t(e)}),a&&i.stdout&&i.stderr){const t=pe(process.stdout,s),o=pe(process.stderr,s);i.stdout.on("data",e=>t.write(e)),i.stderr.on("data",e=>o.write(e)),i.on("close",s=>{t.flush(),o.flush(),e(null===s?0:s)})}else i.on("close",t=>{e(null===t?0:t)})})})("npm run dev",u,e,(()=>{const e=[];for(const t of le)try{e.push(new RegExp(t))}catch{s(`Invalid dev output filter pattern ignored: ${t}`)}return e})(),l)},he=async e=>new Promise(t=>{const o=k(`${e} --version`,{stdio:"ignore",shell:!0});o.on("error",()=>{t(!1)}),o.on("close",e=>{t(0===e)})}),me=async e=>{let t;if(await he("pnpm"))t="pnpm install --config.strict-dep-builds=false",s("Using package manager: pnpm");else{if(!(await he("npm")))throw new Error("Neither pnpm nor npm is available. Install Node.js (which bundles npm) or pnpm to continue.");t="npm install --legacy-peer-deps",s("Using package manager: npm (with --legacy-peer-deps for DashNex peer-dep overlap)")}return s(`Executing: ${t} in ${e}`),new Promise((o,s)=>{const n=[],r=[],a=k(t,{stdio:["ignore","pipe","pipe"],cwd:e,shell:!0,env:{...process.env,NPM_CONFIG_LOGLEVEL:"error"}});a.stdout&&a.stdout.on("data",e=>n.push(e)),a.stderr&&a.stderr.on("data",e=>r.push(e)),a.on("error",e=>{p(e),s(e)}),a.on("close",e=>{const t=null===e?0:e;0!==t&&(n.length&&process.stdout.write(Buffer.concat(n)),r.length&&process.stderr.write(Buffer.concat(r))),o(t)})})},ge="Run this command in a DashNex Web application folder.",fe=e=>{const t=y.join(e,"dashnex.json");return w.pathExistsSync(t)},we=(e,t=!1)=>{t||console.log(f.cyan(e))},ye=(e,t,o={})=>{const n=`${e} ${t.join(" ")}`,r=!0===o.silent;return new Promise((t,o)=>{s(`Running: ${n}`);const a=k(n,{stdio:r?["ignore","pipe","pipe"]:"inherit",cwd:process.cwd(),shell:!0});a.on("error",e=>{p(e),o(e)}),a.on("close",o=>{s(`${e} exited with code ${o}`),t(null===o?1:o)})})},$e=(e,t)=>new Promise((o,n)=>{s(`Running: ${e} ${t.join(" ")}`);const r=k(e,t,{cwd:process.cwd()});let a="";r.stdout?.on("data",e=>{a+=e.toString()}),r.stderr?.on("data",e=>{a+=e.toString()}),r.on("error",e=>{p(e),n(e)}),r.on("close",t=>{s(`${e} exited with code ${t}`),o({exitCode:null===t?1:t,output:a})})}),ve=async e=>{s("Running check: install");try{return 0===await me(process.cwd())}catch(t){return p(t),!e&&t instanceof Error&&console.error(f.red(t.message)),!1}},ke=async()=>{try{const{output:e}=await $e(process.execPath,[process.argv[1],"db","migrate","--help"]);return e.includes("Usage: dashnex db migrate")}catch(e){return p(e),!1}},xe=async e=>{s("Running check: db migrate");try{const{exitCode:t,output:o}=await $e(process.execPath,[process.argv[1],"db","migrate"]);return 0===t||(o.includes("Unknown command")?(s("db migrate command is not available, skipping"),!0):(!e&&o.trim().length>0&&process.stderr.write(o),!1))}catch(t){return p(t),!0}},be=e=>new Promise(t=>{const o=k(`${e} --version`,{stdio:"ignore",shell:!0});o.on("error",()=>t(!1)),o.on("close",e=>t(0===e))}),Se=[{name:"TypeScript",command:"npx",args:["tsc","--noEmit"],notFoundMessage:"TypeScript is not available. Please install it with: npm install -D typescript"}],Ee=class{async execute(){s("Check flow started"),fe(process.cwd())||(console.error(f.red(ge)),process.exit(1)),we("Checking dependencies..."),await ve(!1)||(console.error(f.red("Check failed.")),process.exit(1)),s(`Running ${Se.length} check(s)`);for(const t of Se){s(`Running check: ${t.name}`),we(`Checking ${t.name}...`),await be(t.command)||(console.error(f.red(t.notFoundMessage)),process.exit(1));try{0!==await ye(t.command,t.args)&&(console.error(f.red("Check failed.")),process.exit(1))}catch(e){p(e),console.error(f.red(t.notFoundMessage)),process.exit(1)}}await ke()?(we("Checking database migrations..."),await xe(!1)||(console.error(f.red("Check failed.")),process.exit(1))):s("db migrate command is not available, skipping"),console.log(f.green("All checks passed."))}async run(e=!1){if(s("Running checks (called from push)"),!fe(process.cwd()))return e||console.error(f.red(ge)),!1;if(we("Checking dependencies...",e),!(await ve(e)))return!1;const t=e?{silent:!0}:void 0;for(const n of Se){if(s(`Running check: ${n.name}`),we(`Checking ${n.name}...`,e),!(await be(n.command)))return console.error(f.red(n.notFoundMessage)),!1;try{if(0!==await ye(n.command,n.args,t))return!1}catch(o){return p(o),console.error(f.red(n.notFoundMessage)),!1}}if(await ke()){if(we("Checking database migrations...",e),!(await xe(e)))return!1}else s("db migrate command is not available, skipping");return e||console.log(f.green("All checks passed.")),!0}},De=" │ ",Te=e=>e.subarray(0,8192).includes(0),Ce=e=>{const t=e.split("\n");return""===t[t.length-1]&&t.pop(),t},Pe=(e,t)=>{if(null===e)return" ".repeat(t);const o=e.replace(/\t/g," ");return o.length<=t?o.padEnd(t):`${o.slice(0,Math.max(0,t-1))}…`},Ae=(e,t,o)=>{const s=Math.max(o??process.stdout.columns??120,43),n=Math.floor((s-3)/2),r=((e,t)=>{const o=[],s=N(e,t);for(let n=0;n<s.length;n+=1){const e=s[n];if(e.removed){const t=Ce(e.value),r=s[n+1],a=r?.added?Ce(r.value):[];r?.added&&(n+=1);const i=Math.max(t.length,a.length);for(let e=0;e<i;e+=1)o.push({left:t[e]??null,right:a[e]??null,changed:!0})}else if(e.added)for(const t of Ce(e.value))o.push({left:null,right:t,changed:!0});else for(const t of Ce(e.value))o.push({left:t,right:t,changed:!1})}return o})(e,t),a=/* @__PURE__ */new Set;r.forEach((e,t)=>{if(e.changed)for(let o=Math.max(0,t-3);o<=Math.min(r.length-1,t+3);o+=1)a.add(o)});const i=[];i.push(f.bold(Pe("local (current)",n))+f.dim(De)+f.bold("incoming"));let c=-1,l=0,d=0;for(let p=0;p<r.length;p+=1){if(!a.has(p))continue;if(l>=200){d+=1;continue}-1!==c&&p>c+1&&i.push(f.dim("···")),c=p,l+=1;const e=r[p],t=Pe(e.left,n),o=Pe(e.right,n);if(!e.changed){i.push(f.dim(t)+f.dim(De)+f.dim(o));continue}const s=null!==e.left?f.red(t):t,u=null!==e.right?f.green(o):o;i.push(s+f.dim(De)+u)}return d>0&&i.push(f.dim(`… ${d} more diff line(s) not shown`)),i.join("\n")},je=[".dashnex",".git",".vinext",".wrangler","wrangler.jsonc","wrangler.toml",".dev.vars",".github"],Ne=[".env","wrangler.jsonc"],Ie=e=>y.join(e,a,"sync.json"),Fe=e=>D("sha1").update(`blob ${e.length}\0`).update(e).digest("hex"),Re=e=>e.split(y.sep).join("/"),Oe=e=>je.some(t=>e===t||e.startsWith(`${t}/`)),Be=async e=>{const t=await(async e=>{const t=I();t.add(je);const o=y.join(e,".gitignore");return await w.pathExists(o)&&t.add(await w.readFile(o,"utf8")),t})(e),o=[],s=async n=>{const r=await w.readdir(n,{withFileTypes:!0});for(const a of r){const r=y.join(n,a.name),i=Re(y.relative(e,r));Oe(i)||t.ignores(a.isDirectory()?`${i}/`:i)||(a.isDirectory()?await s(r):a.isFile()&&o.push(i))}};return await s(e),o},ze=async(e,t={})=>{const o={},s=await Be(e);for(const n of s)o[n]=Fe(await w.readFile(y.join(e,n)));if(t.includeGenerated)for(const n of Ne){if(n in o)continue;const t=y.join(e,n);(await w.lstat(t).catch(()=>null))?.isFile()&&(o[n]=Fe(await w.readFile(t)))}return o},_e=async e=>{try{const t=await w.readFile(Ie(e),"utf8"),o=JSON.parse(t);return"string"!=typeof o?.commit||"object"!=typeof o?.manifest||null===o.manifest?null:o}catch{return null}},Le=async(e,t,o)=>{const n={commit:t,manifest:o,updatedAt:/* @__PURE__ */(new Date).toISOString()},r=Ie(e);try{await w.ensureDir(y.dirname(r)),await w.writeFile(r,`${JSON.stringify(n,null,2)}\n`),s(`Sync state written: commit ${t}, ${Object.keys(o).length} files`)}catch(a){s(`Failed to write sync state: ${a instanceof Error?a.message:"unknown"}`)}},Ue=1048576,Me=async(e,t)=>{const{install:o}=await S.prompt([{type:"confirm",name:"install",message:"Install dependencies?",default:!0}]);if(!o){if(y.resolve(e)!==y.resolve(t)){const o=y.relative(t,e);console.log(f.cyan(`Run "cd ${o}" to change to the application folder.`))}return}try{const t=q();t.start("Installing dependencies...");try{const o=await me(e);if(t.stop(),0!==o)return void s(`install exited with code ${o}`)}catch(a){throw t.stop(),a}}catch(a){return p(a),void console.error(f.red(a instanceof Error?a.message:"Failed to run install."))}const{migrate:n}=await S.prompt([{type:"confirm",name:"migrate",message:"Create or update database?",default:!0}]);if(!n)return;s(`Running dashnex db migrate in ${e}`);try{const t=q();t.start("Creating or updating database...");try{const o=await((e,t,o)=>{const s=`${y.join(e,"node_modules",".bin")}${y.delimiter}${process.env.PATH??""}`,n={...process.env,PATH:s};return new Promise((s,r)=>{const a=k(t,{cwd:e,shell:!0,stdio:"inherit",env:o?{...n,...o}:n});a.on("error",e=>{p(e),r(e)}),a.on("close",e=>{s(null===e?0:e)})})})(e,"dashnex db migrate");if(t.stop(),0!==o)return void s(`dashnex db migrate exited with code ${o}`)}catch(a){throw t.stop(),a}}catch(a){return p(a),void console.error(f.red("Failed to run dashnex db migrate."))}const{dev:r}=await S.prompt([{type:"confirm",name:"dev",message:"Run development server?",default:!0}]);if(r)try{await ue(e)}catch(a){p(a),console.error(f.red(a instanceof Error?a.message:"Failed to run dev server."))}},We=(e,t)=>{if(e.length!==t.length)return`local ${e.length} bytes, incoming ${t.length} bytes`;const o=e.length;for(let s=0;s<o;s+=1)if(e[s]!==t[s]){return`size ${o} matches; first diff at byte ${s} (local=0x${e[s].toString(16).padStart(2,"0")} incoming=0x${t[s].toString(16).padStart(2,"0")})`}return`size ${o} matches; no byte difference (unexpected)`},Je=async(e,t)=>{let o;try{o=await w.lstat(e)}catch{return{kind:"new"}}if(o.isDirectory())return{kind:"different",reason:"target is a directory"};if(o.size!==t.length)return{kind:"different",reason:`local ${o.size} bytes, incoming ${t.length} bytes`};const s=await w.readFile(e);return 0===Buffer.compare(s,t)?{kind:"identical"}:{kind:"different",reason:We(s,t)}},He=async(e,t,o)=>{console.log(`\n${f.bold(t)}`);try{const t=await w.readFile(e);if(t.length>Ue||o.length>Ue||Te(t)||Te(o))return void console.log(f.dim(`(no preview: ${We(t,o)})`));console.log(Ae(t.toString("utf8"),o.toString("utf8")))}catch(s){p(s),console.log(f.dim("(no preview available)"))}},Xe=async e=>{const{choice:t}=await S.prompt([{type:"expand",name:"choice",message:`Overwrite ${e}?`,default:"y",choices:[{key:"y",name:"yes (overwrite this file)",value:"yes"},{key:"n",name:"no (keep local version)",value:"no"},{key:"a",name:"overwrite all remaining differing files",value:"all"},{key:"s",name:"skip all remaining differing files",value:"skip"}]}]);return t},Ge=async(e,t)=>{const o=t?f.yellow(" (has local changes!)"):"",{choice:s}=await S.prompt([{type:"expand",name:"choice",message:`Delete ${e}? It no longer exists in the application.${o}`,default:"y",choices:[{key:"y",name:"yes (delete this file)",value:"yes"},{key:"n",name:"no (keep this file)",value:"no"},{key:"a",name:"delete all remaining removed files",value:"all"},{key:"s",name:"keep all remaining removed files",value:"skip"}]}]);return s},qe=async(e,t)=>{let o=y.dirname(e);const s=y.resolve(t);for(;y.resolve(o)!==s;)try{if((await w.readdir(o)).length>0)return;await w.rmdir(o),o=y.dirname(o)}catch{return}},Ye=(e,t)=>y.resolve(e)===y.resolve(t)?"Application is successfully pulled.":`Application is successfully pulled into ${y.relative(t,e)}.`,Ve=class{async execute(e={}){s("Pull flow started");const t=await m();if(!t)return;const o=process.cwd();let a;if(e.folder)a=e.folder.trim()||".",s(`Folder argument provided: ${a}`);else{s("No folder argument, prompting user");const{folder:e}=await S.prompt([{type:"input",name:"folder",message:"Which folder to pull the application to?",default:"."}]);a=e.trim()||"."}const i=y.resolve(o,a);s(`Target folder resolved: ${i}`);try{const e=await w.lstat(i).catch(()=>null);e&&!e.isDirectory()&&(console.error(f.red(`Cannot pull into ${i}: path exists and is not a directory.`)),process.exit(1)),await w.ensureDir(i),s(`Target folder ensured: ${i}`)}catch(d){p(d);const e=d instanceof Error?d.message:"Unknown error";console.error(f.red(`Cannot create folder ${i}: ${e}`)),process.exit(1)}const c=y.join(A.tmpdir(),`dashnex-pull-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`),l=q();l.start("Analyzing local files...");try{const n=await _e(i),r=await ze(i,{includeGenerated:!0});s(`Local manifest has ${Object.keys(r).length} files`),l.text("Pulling application...");const a=await this.download(t.token,r);l.text("Downloading..."),await w.writeFile(c,a.buffer),s(`Zip written to temp file (${a.viaV2?"v2 diff":"legacy full"} pull)`),l.text("Extracting...");const u=new j(c).getEntries().filter(e=>!e.isDirectory);let h=null;const m=u.find(e=>".dashnex/pull.json"===e.entryName);if(m)try{h=JSON.parse(m.getData().toString("utf8"))}catch(d){p(d)}const g=u.filter(e=>".dashnex"!==e.entryName&&!e.entryName.startsWith(".dashnex/"));s(`Zip has ${g.length} file entries${h?`, meta commit ${h.commit}`:", no meta"}`);const $=e.yes||"1"===process.env.DASHNEX_CI;let v=$?"all":"prompt",k=!1,x=0,b=0,S=0,E=0,D=0;const T=async(e,t,o)=>{try{return await w.ensureDir(y.dirname(e)),await w.writeFile(e,t),o&&await w.chmod(e,o),!0}catch(d){return p(d),!1}};for(const e of g){const t=e.getData(),o=y.join(i,e.entryName),n=y.relative(i,o)||e.entryName,r=(e.header.attr??0)>>16&4095,a=await Je(o,t);if(s(`Entry ${e.entryName}: ${a.kind}${a.reason?` (${a.reason})`:""}`),"identical"===a.kind){E+=1;continue}if("new"===a.kind){await T(o,t,r)?x+=1:D+=1;continue}let c=!1;if("all"===v)c=!0;else if("none"===v)c=!1;else{l.stop(),await He(o,n,t),k||(console.log(f.dim("Y = yes (default), n = skip, a = overwrite all, s = skip all, h = help")),k=!0);const r=await Xe(n);s(`Entry ${e.entryName}: user chose ${r}`),"yes"===r?c=!0:"no"===r?c=!1:"all"===r?(v="all",c=!0):(v="none",c=!1),l.start("Extracting...")}c?await T(o,t,r)?b+=1:D+=1:S+=1}l.stop();let C=0,P=0;if(h&&h.deleted.length>0){const e=await this.applyDeletions(i,h.deleted,n,$);C=e.deleted,P=e.kept}h&&(E+=Math.max(0,Object.keys(h.manifest).length-g.length)),s(`Pull summary: ${x} new, ${b} overwritten, ${S} skipped, ${C} deleted, ${E} unchanged, ${D} failed`);const A=[`${x} new`,`${b} overwritten`,`${S} skipped`,`${E} unchanged`];if((C>0||P>0)&&A.splice(3,0,`${C} deleted`),D>0&&A.push(`${D} failed`),console.log(f.cyan(`Pulled: ${A.join(", ")}`)),h){const e=await ze(i,{includeGenerated:!0});await Le(i,h.commit,e)}y.resolve(i)!==y.resolve(o)?(console.log(f.green(Ye(i,o))),process.chdir(i),s(`Changed working directory to ${i}`)):console.log(f.green(Ye(i,o))),D>0&&(console.error(f.red(`${D} file(s) failed to write. See DEBUG output for details.`)),process.exit(1)),$?s("Non-interactive mode (--yes or --ci), skipping post-pull child commands"):await Me(i,o)}catch(d){if(l.stop(),p(d),d instanceof Error&&d.message.startsWith("EXIT:"))throw d;if(n(d))return void console.log(f.yellow(r));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}finally{await w.remove(c).catch(()=>{}),s("Temp zip removed")}}async download(e,o){const n=`${t()}/business/v1/cli/v2/pull`;s(`POST ${n}`);const r=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({manifest:o})});if(s(`v2 pull response: ${r.status}`),r.ok)return{buffer:Buffer.from(await r.arrayBuffer()),viaV2:!0};const a=await r.json().catch(()=>({}));var i,c;i=r.status,c=a,404===i&&"string"==typeof c.message&&c.message.startsWith("Cannot ")||this.failFromResponse(r.status,a),s("v2 pull endpoint unavailable, falling back to legacy pull");const l=`${t()}/business/v1/cli/pull`;s(`GET ${l}`);const d=await fetch(l,{headers:{Authorization:`Bearer ${e}`}});if(s(`Legacy pull response: ${d.status}`),!d.ok){const e=await d.json().catch(()=>({}));this.failFromResponse(d.status,e)}return{buffer:Buffer.from(await d.arrayBuffer()),viaV2:!1}}failFromResponse(e,t){let o="Failed to pull application.";if(401===e||403===e)o="Please run 'dashnex login' to authenticate.";else if(404===e)o="Business has no application. Run 'dashnex app create' to create one.";else{const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(t);e&&(o=e)}console.error(f.red(o)),process.exit(1)}async applyDeletions(e,t,o,n){let r=0,a=0;if(!o){const e=t.slice(0,20);console.log(f.yellow("These local files do not exist in the application (kept — no sync state yet):"));for(const t of e)console.log(f.yellow(` ${t}`));return t.length>e.length&&console.log(f.yellow(` … and ${t.length-e.length} more`)),{deleted:r,kept:t.length}}let i=n?"all":"prompt";for(const l of t){if(!(l in o.manifest)){s(`Deletion candidate ${l} was never synced, keeping`);continue}const t=y.join(e,l),n=await w.readFile(t).catch(()=>null);if(null===n)continue;const d=Fe(n)!==o.manifest[l];let u=!1;if("all"===i)u=!0;else if("none"===i)u=!1;else{const e=await Ge(l,d);s(`Deletion ${l}: user chose ${e}`),"yes"===e?u=!0:"no"===e?u=!1:"all"===e?(i="all",u=!0):(i="none",u=!1)}if(u)try{await w.remove(t),await qe(t,e),r+=1}catch(c){p(c),a+=1}else a+=1}return{deleted:r,kept:a}}},Ke=async e=>{const o=`${t()}/business/v1/agreements/payment-processing/status`;s(`GET ${o}`);const n=await fetch(o,{headers:{Authorization:`Bearer ${e}`}});if(s(`Payment agreement response: ${n.status}`),!n.ok)return!0;if((await n.json().catch(()=>({}))).hasAccepted)return!0;const r=`${await(async()=>"qa"===process.env.APPLICATION_ENV?"https://business.qa.dashnex.com":"https://business.dashnex.com")()}/money/agreement/`;return console.error(f.red(`You need to accept Master Payment Processing Agreement first by visiting this link: ${r}`)),!1},Ze=async(e,o={})=>{const n=o.ciMode??!1;return!!(await Ke(e))&&!!(await(async(e,o)=>{const n=`${t()}/business/v1/tos/latest`;s(`GET ${n}`);const r=await fetch(n,{headers:{Authorization:`Bearer ${e}`}});if(s(`TOS latest response: ${r.status}`),r.ok)return!0;if(404!==r.status)return!0;const a=`${t()}/business/v1/tos/current`;s(`GET ${a}`);const i=await fetch(a,{headers:{Authorization:`Bearer ${e}`}});if(s(`TOS current response: ${i.status}`),!i.ok)return s("Could not fetch current TOS, skipping check"),!0;const c=await i.json().catch(()=>({})),l=c.version??"unknown";if(c.text&&(console.log(f.dim("─".repeat(60))),console.log(f.bold(`Terms of Service ${l}`)),console.log(f.dim("─".repeat(60))),console.log(c.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(f.dim("─".repeat(60)))),o)return console.log(f.yellow(`By proceeding you accept the Terms of Service ${l}.`)),!0;const{accept:d}=await S.prompt([{type:"confirm",name:"accept",message:`By creating an application you accept the Terms of Service ${l}. Continue?`,default:!0}]);if(!d)return console.log(f.yellow("Cancelled.")),!1;try{const o=`${t()}/business/v1/tos/${c.id}/accept`;s(`POST ${o}`),await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({})})}catch(u){p(u)}return!0})(e,n))},Qe=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,et=e=>new Promise(t=>setTimeout(t,e)),tt=e=>e.appFullCustomDomain?e.appFullCustomDomain:e.subdomain?"qa"===(process.env.APPLICATION_ENV??"")?`https://${e.subdomain}.dashnex.dev`:`https://${e.subdomain}.dashnexcloud.com`:null,ot=3e5,st=99,nt=e=>new Promise(t=>setTimeout(t,e)),rt=async(e,t,o,n)=>{const r=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"text/event-stream"}});if(s(`SSE connection opened: ${r.status}`),!r.ok){const e=r.status;let t="Failed to start deployment.";if(401===e||403===e)t="Please run 'dashnex login' to authenticate.";else try{const e=await r.text(),o=JSON.parse(e);"string"==typeof o.error?t=o.error:"string"==typeof o.message&&(t=o.message)}catch{}throw console.error(f.red(t)),new Error(`HTTP ${e}: ${t}`)}if(!r.body)throw new Error("Response body is null");s("SSE connection established successfully"),n?.();const a=r.body.getReader();try{for await(const e of async function*(e){const t=new TextDecoder("utf-8");let o="";for(;;){const{value:s,done:n}=await e.read();if(n)break;o+=t.decode(s,{stream:!0});const r=o.split("\n");o=r.pop()||"";let a="";for(const e of r)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})}}(a))try{if(!e.data){s("Received empty SSE event");continue}const t=JSON.parse(e.data);s(`SSE message received: ${JSON.stringify(t)}`),o(t)}catch(i){p(i),s(`Failed to parse SSE event data: ${e.data}`)}}finally{a.releaseLock()}},at=class{async execute(e={}){s("Deploy flow started");const t=await m();if(!t)return;if(!1!==e.check?(s("Running pre-deploy checks"),await(new Ee).run(!1)||(console.error(f.red("Deploy aborted: checks failed. Re-run with --no-check to skip.")),process.exit(1))):s("Skipping pre-deploy checks (--no-check)"),!(await Ze(t.token,{ciMode:!0})))return;const o=`${g()}/business/v1/applications/deploy`;s(`GET ${o} (SSE)`);let a=0,i="",c=!1,l=0,d=!1;const u=q();let h=0,w=0,y=null;const $=(e,t)=>{const o=Math.round(e);u.text(`[${o}%] ${t}`)},v=()=>{k();const e=a,t=Date.now(),o=ot*((st-e)/st);y=setInterval(()=>{const s=Date.now()-t;let n;if(w>t){const e=Date.now()-w,t=st-h,o=3030.3030303030305*t;n=Math.min(h+e/o*t,st)}else n=Math.min(e+s/o*(st-e),st);n>a&&(a=n,$(a,i))},200)},k=()=>{y&&(clearInterval(y),y=null)};let x=!1;const b=e=>{if(d=!0,"string"==typeof e.error)return k(),u.stop(),console.error(f.red(e.error)),c=!0,void(x=!0);"string"==typeof e.message&&(i=e.message),"number"==typeof e.progress&&(h=e.progress,w=Date.now(),e.progress>a&&(a=e.progress)),"string"!=typeof e.message&&"number"!=typeof e.progress||(a>=100?(k(),u.stop(),c=!0):$(a,i))};for(;l<=5;)try{return d?$(a,i):u.start("Connecting..."),v(),await rt(o,t.token,b,()=>{d||(u.text(`[${Math.round(a)}%] Deployment in progress...`),i="Deployment in progress...")}),k(),u.stop(),s("SSE connection closed"),x&&process.exit(1),void(c&&await this.showDeployedUrl(t.token))}catch(S){if(k(),p(S),s(`SSE connection error: ${S}`),c)return u.stop(),void(x&&process.exit(1));if(n(S))return u.stop(),void console.log(f.yellow(r));S instanceof Error&&S.message.startsWith("HTTP")&&(u.stop(),console.error(f.red("Could not complete deployment. Check your connection and try again.")),process.exit(1)),l++,l>5&&(u.stop(),console.error(f.red("Deployment failed. Maximum reconnection attempts exceeded.")),process.exit(1));const e=Math.min(1e3*Math.pow(2,l-1),3e4);s(`Connection error. Reconnecting in ${e/1e3}s... (attempt ${l}/5)`),await nt(e)}}async showDeployedUrl(e){try{const o=`${t()}/business/v1/applications`;s(`GET ${o} (for deployed URL)`);const n=await fetch(o,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)return;const r=await n.json().catch(()=>({})),a=tt({subdomain:r.subdomain,appFullCustomDomain:r.appFullCustomDomain});a&&console.log(`Application is deployed to ${f.cyan(a)}`)}catch(o){p(o)}}},it=104857600,ct=class extends Error{},lt=class extends Error{},dt=class extends Error{},pt="/business/v1/cli/tail-token";async function ut(e,o={}){const s=`${t()}${pt}${o.debug?"?debug=1":""}`;try{await fetch(s,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})}catch{}}var ht=["log","info","warn","error","debug"],mt={error:4,warn:3,log:2,info:2,debug:1};function gt(e){return"string"==typeof e&&ht.includes(e)}function ft(e){return e.map(e=>"string"==typeof e?e:function(e){try{return JSON.stringify(e)}catch{return String(e)}}(e)).join(" ")}function wt(e){return e<10?`0${e}`:String(e)}function yt(e){const t=new Date(e);return`${wt(t.getHours())}:${wt(t.getMinutes())}:${wt(t.getSeconds())}.${o=t.getMilliseconds(),o<10?`00${o}`:o<100?`0${o}`:String(o)}`;var o}function $t(e,t){if("string"==typeof e)return e;if("object"==typeof(o=e)&&null!==o&&"string"==typeof o.name&&"string"==typeof o.message&&Object.keys(o).every(e=>"name"===e||"message"===e||"stack"===e)){const t=`${e.name}: ${e.message}`;return e.stack?`${t}\n${e.stack}`:t}var o;return O(e,{colors:t,depth:2,breakLength:120})}var vt={error:e=>f.red(e),warn:e=>f.yellow(e),debug:e=>f.dim(e),log:e=>e,info:e=>e};function kt(e,t){const o=t.color?f.dim(yt(e.ts)):yt(e.ts),s=e.level.toUpperCase().padEnd(5),n=[o,t.color?vt[e.level](s):s];n.push(e.args.map(e=>$t(e,t.color)).join(" "));let r=n.join(" ");if(e.truncated){const e=" …(truncated)";r+=t.color?f.dim(e):e}return r}function xt(e,t,o){let s;try{s=JSON.parse(e)}catch{return{kind:"malformed",raw:e}}if("object"!=typeof s||null===s||!gt(s.level))return{kind:"malformed",raw:e};const n=s;return Array.isArray(n.args)||(n.args=void 0===n.args?[]:[n.args]),r=n.level,a=t.minLevel,mt[r]>=mt[a]&&function(e,t){return!t||t.test(ft(e.args))}(n,t.filter)?{kind:"line",line:kt(n,o)}:{kind:"filtered"};var r,a}var bt=new Set([4401,4403]);var St=[{label:"node_modules",segments:["node_modules"],description:"installed dependencies"},{label:"node_modules/.vite",segments:["node_modules",".vite"],description:"vite cache"},{label:"node_modules/.vite-temp",segments:["node_modules",".vite-temp"],description:"vite cache"},{label:"src/dashnex",segments:["src","dashnex"],description:"generated module registry"},{label:"dist",segments:["dist"],description:"build output"}],Et={label:".wrangler",segments:[".wrangler"],description:"local database"},Dt=async e=>{await B(e,{recursive:!0,force:!0,maxRetries:5,retryDelay:100})},Tt={name:"app",description:"Manage DashNex applications (should be executed in application folder)",handler:{execute:async()=>{}},options:[],subcommands:[{name:"create",description:"Create a new DashNex application",handler:new class{async pollApplicationCreated(e,t,o=5e3,n=6e4){const r=Date.now();let a=0;for(;Date.now()-r<n;){a++,s(`Polling application status (attempt ${a})...`);try{const o=await fetch(e,{headers:{Authorization:`Bearer ${t}`}});if(s(`Poll response: ${o.status}`),200===o.status){const e=await o.json();if(s(`Poll response body status: ${e.status}`),"creating"!==e.status)return s(`Application status is "${e.status}", creation complete`),{ready:!0,status:e.status};s('Application status is still "creating", continuing to poll...')}}catch(i){p(i),s(`Poll attempt ${a} failed with network error`)}await et(o)}return{ready:!1}}async execute(e={}){s("Create flow started");const o=await m();if(!o)return;s("Auth valid, checking if business already has application");const a=q(),i=`${t()}/business/v1/applications`;s(`GET ${i}`),a.start("Checking application status...");try{const e=await fetch(i,{headers:{Authorization:`Bearer ${o.token}`}});a.stop(),s(`Applications response: ${e.status}`),s(`Applications response body: ${await e.text()}`),404!==e.status&&(console.error(f.red("Business already has an application. Run 'dashnex app pull' to pull the existing one.")),process.exit(1))}catch(y){if(a.stop(),p(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(n(y))return void console.log(f.yellow(r));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}s("No existing application, checking agreements");const c=void 0!==e.subdomain;if(!(await Ze(o.token,{ciMode:c})))return;let l;s("Agreements checked, proceeding to subdomain prompt");const d=e=>`${t()}/business/v1/applications/check-subdomain?subdomain=${encodeURIComponent(e)}`;let u=e.subdomain?.trim();for(;;){if(u)l=u,u=void 0,s(`Subdomain provided via flag: ${l}`);else{if(c)return console.error(f.red("Subdomain is not available.")),void process.exit(1);{const{sub:e}=await S.prompt([{type:"input",name:"sub",message:"Pick your subdomain:",validate:e=>!!e.trim()||"Subdomain is required"}]);l=e.trim()}}s(`Checking subdomain: ${l}`);const e=d(l);s(`GET ${e}`),a.start("Checking subdomain...");try{const t=await fetch(e,{headers:{Authorization:`Bearer ${o.token}`}});a.stop(),s(`Check subdomain response: ${t.status}`);const n=await t.text();if(s(`Check subdomain response body: ${n}`),!t.ok){const e=t.headers.get("content-type")??"";let o="Failed to check subdomain availability.";if(401!==t.status&&403!==t.status||(o="Please run 'dashnex login' to authenticate.",console.error(f.red(o)),process.exit(1)),e.includes("application/json")){const e=JSON.parse(n);s(`Check subdomain error body: ${JSON.stringify(e)}`);const t=Qe(e);t&&(o=t)}console.error(f.red(o));continue}const r=JSON.parse(n);if(s(`Check subdomain parsed body: ${JSON.stringify(r)}`),r.available){s(`Subdomain ${l} is available`);break}console.error(f.red("Subdomain is not available. Please choose a different one."))}catch(y){if(a.stop(),p(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(n(y))return void console.log(f.yellow(r));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}const h=`${t()}/business/v1/cli/create`;s(`POST ${h}`);const g={subdomain:l};e.template&&(g.template=e.template,s(`Template: ${e.template}`));const w=JSON.stringify(g);s(`Create request body: ${w}`),a.start("Creating application...");try{const i=await fetch(h,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:w});a.stop(),s(`Create response: ${i.status}`);const l=await i.text();if(s(`Create response body: ${l}`),503===i.status){s("Create returned 503, polling for application creation..."),a.start("Waiting for application to be ready...");const e=`${t()}/business/v1/applications`,n=await this.pollApplicationCreated(e,o.token);a.stop(),n.ready||(console.error(f.red("Application creation is taking longer than expected. Try again later or run 'dashnex app pull' to check.")),process.exit(1)),"failed"===n.status&&(console.error(f.red("Application creation failed. Please try again.")),process.exit(1)),s("Application found after polling")}else if(!i.ok){const e=i.headers.get("content-type")??"";let t="Failed to create application.";if(401===i.status||403===i.status)t="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e=JSON.parse(l);s(`Create error body parsed: ${JSON.stringify(e)}`);const o=Qe(e);o&&(t=o)}console.error(f.red(t)),process.exit(1)}let d;if(s("Application created successfully"),!0===e.pull?(d=!0,s("--pull flag set, pulling without prompting")):!1===e.pull?(d=!1,s("--no-pull flag set, skipping pull")):c?(d=!1,s("CI mode (--subdomain), skipping pull")):(d=(await S.prompt([{type:"confirm",name:"pull",message:"Pull the application locally?",default:!0}])).pull,s(`User chose to pull: ${d}`)),d){s("Running pull flow");try{await(new Ve).execute()}catch(y){if(p(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(n(y))return void console.log(f.yellow(r));console.error(f.red("Failed to pull application."))}}else console.log(f.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(y){if(a.stop(),p(y),y instanceof Error&&y.message.startsWith("EXIT:"))throw y;if(n(y))return void console.log(f.yellow(r));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[{flags:"-t, --template <template>",description:"Template (name@branch-or-tag)",defaultValue:"webapp-base@live"},{flags:"--subdomain <subdomain>",description:"Subdomain (CI mode, skip prompts)"},{flags:"--pull",description:"Auto-pull after creation (skip prompt)"},{flags:"--no-pull",description:"Skip the pull prompt and show the success message"}]},{name:"pull",description:"Pull existing application to specified folder",handler:new Ve,arguments:[{name:"folder",description:"Target folder (defaults to interactive prompt)"}],options:[{flags:"-y, --yes",description:"Skip prompts and child commands (CI mode)"}]},{name:"push",description:"Push local application to DashNex",handler:new class{async execute(e={}){s("Push flow started"),await w.pathExists(y.join(process.cwd(),"dashnex.json"))||(console.error(f.red("Not a DashNex application folder (dashnex.json not found).")),console.error(f.red("Run this command from your application root.")),process.exit(1)),!1!==e.check?(s("Running pre-push checks"),await(new Ee).run(!1)||(console.error(f.red("Push aborted: checks failed. Re-run with --no-check to skip.")),process.exit(1))):s("Skipping pre-push checks (--no-check)");const t=await m();if(!t)return;const o=process.cwd(),a=q();try{a.start("Analyzing local files...");const n=await _e(o),r=await ze(o);s(`Local manifest has ${Object.keys(r).length} files`),a.text("Comparing with remote...");const i=await this.requestPlan(t.token,r,n?.commit);a.stop(),"legacy"===i?(s("v2 push endpoints unavailable, falling back to legacy zip push"),await this.pushLegacy(t.token,o,a)):await this.pushDiff(t.token,o,r,i,e,a),await this.promptAndDeploy(e)}catch(i){if(a.stop(),p(i),i instanceof Error&&i.message.startsWith("EXIT:"))throw i;if(n(i))return void console.log(f.yellow(r));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}async requestPlan(e,o,n){const r=`${t()}/business/v1/cli/v2/push/plan`;s(`POST ${r}`);const a=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({manifest:o,lastSyncCommit:n})});if(s(`Plan response: ${a.status}`),a.ok)return await a.json();const i=await a.json().catch(()=>({}));if(((e,t)=>404===e&&"string"==typeof t.message&&t.message.startsWith("Cannot "))(a.status,i))return"legacy";this.failFromResponse(a.status,i,"Failed to push application.")}async pushDiff(e,t,o,n,r,a){let i=n;if(i.remoteChanged.length>0&&!r.force){console.error(f.red("Remote application has changes you don't have locally:"));for(const e of i.remoteChanged.slice(0,20))console.error(f.red(` ${e}`));i.remoteChanged.length>20&&console.error(f.red(` … and ${i.remoteChanged.length-20} more`)),console.error(f.red("Run 'dashnex app pull' first, or push anyway with --force.")),process.exit(1)}const c=i.upload.filter(e=>e in o);let l=i.delete;if(0!==c.length||0!==l.length){if(l.length>0){const e=await _e(t),o=r.yes||"1"===process.env.DASHNEX_CI;console.log(f.yellow(`${l.length} file(s) will be deleted from the application repository:`));for(const t of l.slice(0,20))console.log(f.yellow(` ${t}`));if(l.length>20&&console.log(f.yellow(` … and ${l.length-20} more`)),!o){const{confirmDelete:t}=await S.prompt([{type:"confirm",name:"confirmDelete",message:"Delete these files from the remote repository?",default:null!==e}]);t||(s("User declined remote deletions, pushing without them"),l=[])}}if(0!==c.length||0!==l.length)for(let n=1;;n+=1){a.start(1===n?"Uploading changes...":"Remote changed, retrying...");const d=await this.applyPush(e,t,c,l,i.baseCommit);if(a.stop(),"ok"===d.status){await Le(t,d.commit,o);const e=[`${c.length} file(s) updated`];return l.length>0&&e.push(`${l.length} deleted`),console.log(f.cyan(`Pushed: ${e.join(", ")}`)),void console.log(f.green("Application pushed successfully."))}n>=2&&(console.error(f.red("Remote repository keeps changing, please retry the push.")),process.exit(1)),s("Push apply conflicted, re-planning");const p=await _e(t),u=await this.requestPlan(e,o,p?.commit);"legacy"===u&&(console.error(f.red("Failed to push application.")),process.exit(1)),u.remoteChanged.length>0&&!r.force&&(console.error(f.red("Remote application changed during the push. Run 'dashnex app pull' first, or push with --force.")),process.exit(1)),i=u}else console.log(f.green("Everything up to date."))}else console.log(f.green("Everything up to date."))}async applyPush(e,o,n,r,a){const i=new j;for(const t of n){const e=y.join(o,...t.split("/")),s=y.posix.dirname(t);i.addLocalFile(e,"."===s?"":s,y.posix.basename(t))}const c=y.join(A.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`);try{i.writeZip(c),s(`Diff zip written to ${c} (${n.length} files, ${r.length} deletions)`),await this.ensureZipWithinLimit(c);const o=`${t()}/business/v1/cli/v2/push/apply`;s(`POST ${o}`);const l=await w.readFile(c),d=new FormData;d.append("file",new Blob([l],{type:"application/zip"}),"diff.zip"),d.append("baseCommit",a),d.append("deletions",JSON.stringify(r));const p=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:d});if(s(`Apply response: ${p.status}`),409===p.status)return{status:"conflict"};if(!p.ok){const e=await p.json().catch(()=>({}));this.failFromResponse(p.status,e,"Failed to push application.")}return{status:"ok",commit:(await p.json().catch(()=>({}))).commit??""}}finally{await w.remove(c).catch(()=>{})}}async pushLegacy(e,o,n){const r=await ze(o),a=Object.keys(r);s(`Legacy push including ${a.length} files`);const i=new j;for(const t of a){const e=y.join(o,...t.split("/")),s=y.posix.dirname(t);i.addLocalFile(e,"."===s?"":s,y.posix.basename(t))}const c=y.join(A.tmpdir(),`dashnex-push-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`);try{n.start("Packaging application..."),i.writeZip(c),s(`Zip written to ${c}`),await this.ensureZipWithinLimit(c);const o=`${t()}/business/v1/cli/push`;s(`POST ${o}`);const r=await w.readFile(c),a=new FormData;a.append("file",new Blob([r],{type:"application/zip"}),"archive.zip"),n.text("Uploading...");const l=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:a});if(n.stop(),s(`Response: ${l.status}`),!l.ok){const e=await l.json().catch(()=>({}));this.failFromResponse(l.status,e,"Failed to push application.")}console.log(f.green("Application pushed successfully."))}finally{await w.remove(c).catch(()=>{}),s("Temp zip removed")}}async ensureZipWithinLimit(e){const{size:t}=await w.stat(e);if(t>it){const e=e=>(e/1048576).toFixed(1);console.error(f.red(`Push package is ${e(t)} MB — the maximum is ${e(it)} MB.`)),console.error(f.red("Remove or .gitignore large files and try again.")),process.exit(1)}}failFromResponse(e,t,o){let s=o;if(401===e||403===e)s="Please run 'dashnex login' to authenticate.";else{const e=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(t);e&&(s=e)}console.error(f.red(s)),process.exit(1)}async promptAndDeploy(e){let t;void 0!==e.deploy?(t=e.deploy,s(`Deploy decided via flag: ${t}`)):"1"===process.env.DASHNEX_CI?(t=!1,s("CI mode: skipping deploy prompt (use --deploy to deploy)")):(t=(await S.prompt([{type:"confirm",name:"deploy",message:"Deploy the application?",default:!0}])).deploy,s(`User chose to deploy: ${t}`)),t&&(s("Running deploy flow"),await(new at).execute())}},options:[{flags:"--deploy",description:"Auto-deploy after push (skip prompt)"},{flags:"--no-deploy",description:"Skip deploy prompt"},{flags:"--no-check",description:"Skip pre-push checks"},{flags:"-f, --force",description:"Push even when the remote has changes you don't have locally"},{flags:"-y, --yes",description:"Skip prompts (CI mode)"}]},{name:"delete",description:"Delete application from DashNex",handler:new class{async execute(e={}){if(s("Delete flow started"),!e.yes){const{confirm:e}=await S.prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to delete this application? This action cannot be undone.",default:!1}]);if(!e)return s("User cancelled deletion"),void console.log(f.yellow("Deletion cancelled."))}const o=await m();if(!o)return;const a=`${t()}/business/v1/applications`;s(`DELETE ${a}`);const i=q();i.start("Deleting application...");try{const e=await fetch(a,{method:"DELETE",headers:{Authorization:`Bearer ${o.token}`}});if(i.stop(),s(`Response: ${e.status}`),!e.ok){const t=e.headers.get("content-type")??"";let o="Failed to delete application.";if(401===e.status||403===e.status)o="Please run 'dashnex login' to authenticate.";else if(t.includes("application/json")){const t=(e=>"string"==typeof e.error?e.error:"string"==typeof e.message?e.message:void 0)(await e.json().catch(()=>({})));t&&(o=t)}console.error(f.red(o)),process.exit(1)}const t=await e.json().catch(()=>({})),n="string"==typeof t.message?t.message:"Application deleted successfully.";s("Application deleted successfully"),console.log(f.green(n))}catch(c){if(i.stop(),p(c),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;if(n(c))return void console.log(f.yellow(r));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[{flags:"-y, --yes",description:"Skip confirmation prompt"}]},{name:"deploy",description:"Deploy application to DashNex",handler:new at,options:[{flags:"--no-check",description:"Skip pre-deploy checks"}]},{name:"status",description:"Show current application status",handler:new class{async execute(){s("Status flow started");const e=await m();if(!e)return;const o=`${t()}/business/v1/applications`;s(`GET ${o}`);const a=q();a.start("Fetching application status...");try{const t=await fetch(o,{headers:{Authorization:`Bearer ${e.token}`}});if(a.stop(),s(`Response: ${t.status}`),404===t.status)return void console.log(f.yellow("Application not created"));if(!t.ok){const e=t.headers.get("content-type")??"";let o="Failed to fetch application status.";if(401===t.status||403===t.status)o="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e=await t.json().catch(()=>({}));"string"==typeof e.error?o=e.error:"string"==typeof e.message&&(o=e.message)}console.error(f.red(o)),process.exit(1)}const n=await t.json().catch(()=>({}));s(`Application body: ${JSON.stringify(n)}`);const r=n.status??"unknown";console.log(`Status: ${f.cyan(r)}`);const i=tt(n);i&&console.log(`URL: ${f.cyan(i)}`)}catch(i){if(a.stop(),p(i),i instanceof Error&&i.message.startsWith("EXIT:"))throw i;if(n(i))return void console.log(f.yellow(r));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[]},{name:"clear",description:"Delete local dependencies, caches and build output",handler:new class{async execute(e={}){s("Clear flow started");const t=process.cwd();w.pathExistsSync(y.join(t,"dashnex.json"))||(console.error(f.red("Run this command in a DashNex Web application folder.")),process.exit(1));const o=e.yes||"1"===process.env.DASHNEX_CI;s(`Non-interactive: ${o}`);try{const e=await this.collectTargets(t),n=y.join(t,...Et.segments),r=await w.pathExists(n),i=r&&!o;if(r&&o&&e.push(Et),0===e.length&&!i)return void console.log(f.yellow("Nothing to clear."));const c=[];if(e.length>0){console.log("The following will be deleted:");for(const t of e)console.log(` ${f.cyan(t.label)} ${f.dim(`(${t.description})`)}`);if(!o){const{confirm:e}=await S.prompt([{type:"confirm",name:"confirm",message:"Delete these files?",default:!1}]);if(!e)return s("User cancelled clear"),void console.log(f.yellow("Cancelled."))}for(const o of e){const e=y.join(t,...o.segments);s(`Removing ${e}`);try{await Dt(e),console.log(f.green(`Removed ${o.label}`))}catch(a){p(a),c.push(o.label)}}}if(i){const{confirm:e}=await S.prompt([{type:"confirm",name:"confirm",message:"Delete the local database as well?",default:!1}]);if(e){s(`Removing ${n}`);try{await Dt(n),console.log(f.green(`Removed ${Et.label}`))}catch(a){p(a),c.push(Et.label)}}}if(c.length>0){for(const e of c)console.error(f.red(`Could not delete ${e} — it may be in use. Stop 'dashnex dev' and try again.`));process.exit(1)}console.log(f.green("Clear complete. Run 'dashnex install' to set the application up again."))}catch(a){if(a instanceof Error&&a.message.startsWith("EXIT:"))throw a;if(p(a),n(a))return void console.log(f.yellow(r));throw a}}async collectTargets(e){const t=[];for(const o of St)await w.pathExists(y.join(e,...o.segments))&&t.push(o);return t.filter(o=>!t.some(t=>t!==o&&((e,t)=>{const o=y.relative(t,e);return""!==o&&!o.startsWith("..")&&!y.isAbsolute(o)})(y.join(e,...o.segments),y.join(e,...t.segments))))}},options:[{flags:"-y, --yes",description:"Skip prompts and keep the local database (CI mode)"}]},{name:"tail",description:"Stream live console/debug logs from the deployed worker (Ctrl+C to stop)",handler:new class{async execute(e={}){const o=e.level??"log";gt(o)||(console.error(f.red(`Invalid --level '${e.level}'. Use one of: log, info, warn, error, debug.`)),process.exit(1));let n=null;if(e.filter)try{n=new RegExp(e.filter)}catch{console.error(f.red(`Invalid --filter regular expression: ${e.filter}`)),process.exit(1)}const r=await m();if(!r)return;const a=!!e.debug;let i;try{i=await async function(e,o={}){const n=`${t()}${pt}`;s(`POST ${n}${o.debug?" (debug)":""}`);const r=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({debug:!!o.debug})});if(s(`Response: ${r.status}`),401===r.status||403===r.status)throw new ct("Not authorised to tail this application.");if(404===r.status)throw new lt("Business has no application, or the tail endpoint is unavailable.");if(!r.ok)throw new dt(`Failed to start tail (status ${r.status}).`);const a=await r.json().catch(()=>({}));if(!a.token||!a.workerUrl)throw new dt("Malformed tail-token response from the platform.");return{token:a.token,workerUrl:a.workerUrl,expiresAt:"number"==typeof a.expiresAt?a.expiresAt:0}}(r.token,{debug:a})}catch(k){p(k),k instanceof ct&&(console.error(f.red(k.message)),process.exit(1)),k instanceof lt&&(console.error(f.red(k.message)),process.exit(2)),console.error(f.red(k instanceof Error?k.message:"Could not start tail. Check your connection.")),process.exit(3)}const c={color:!!process.stdout.isTTY},l={minLevel:o,filter:n},d=(u=i.workerUrl,`${/^(localhost|127\.0\.0\.1)/.test(u)?"ws":"wss"}://${u}/api/realtime/tail`);var u;const h=`dashnex.tail.token.${i.token}`;console.log(f.dim(`Tailing ${i.workerUrl} — Ctrl+C to stop.`)),a&&console.log(f.dim("Debug logging enabled on the worker (DEBUG=1); may take a minute to take effect."));let g=!1,w=Date.now();const y=setInterval(()=>{g||Date.now()-w>=3e4&&(console.log(f.dim("(no logs in 30s)")),w=Date.now())},5e3),$=new F(d,h,{WebSocket:R,connectionTimeout:1e4,maxReconnectionDelay:16e3}),v=async e=>{if(!g){g=!0,clearInterval(y);try{$.close()}catch{}await Promise.race([ut(r.token,{debug:a}),new Promise(e=>setTimeout(e,3e3))]),process.exit(e)}};process.on("SIGINT",()=>{console.log(),v(0)}),$.binaryType="arraybuffer",$.addEventListener("message",e=>{w=Date.now();const t=xt("string"==typeof e.data?e.data:"",l,c);"line"===t.kind?console.log(t.line):"malformed"===t.kind&&console.error(f.dim(`[malformed frame] ${t.raw}`))}),$.addEventListener("close",e=>{if(!g)return bt.has(e.code)?(console.error(f.red("Tail token was rejected (auth). Exiting.")),void v(1)):void s(`socket closed (code ${e.code}); reconnecting…`)}),$.addEventListener("error",e=>{s(`socket error: ${e.message??"unknown"}`)}),await new Promise(()=>{})}},options:[{flags:"--level <level>",description:"Minimum level: log, info, warn, error, debug"},{flags:"--filter <regex>",description:"Only show records whose args match this regex"},{flags:"--debug",description:"Also enable DEBUG=1 on the worker so debug-gated logs are shown"}]}]},Ct={name:"secrets",description:"Manage DashNex secrets",handler:{execute:async()=>{}},options:[],subcommands:[{name:"list",description:"List all secret names bound to the worker",handler:new class{async execute(){s("Secrets list flow started");const e=await m();if(!e)return;const o=`${t()}/business/v1/cli/secrets`;s(`GET ${o}`);const a=q();a.start("Fetching secrets...");try{const t=await fetch(o,{headers:{Authorization:`Bearer ${e.token}`}});if(a.stop(),s(`Response: ${t.status}`),!t.ok){let e="Failed to fetch secrets.";401===t.status||403===t.status?e="Please run 'dashnex login' to authenticate.":404===t.status?e="Business has no application.":502===t.status&&(e="Error fetching secrets. Make sure your application is deployed."),console.error(f.red(e)),process.exit(1)}const n=(await t.json()).secrets??[];if(0===n.length)return void console.log(f.yellow("No secrets set."));console.log(f.bold(`\nSecrets (${n.length}):\n`)),n.forEach(({name:e})=>{console.log(` ${f.cyan(e)}`)}),console.log("")}catch(i){if(a.stop(),p(i),i instanceof Error&&i.message.startsWith("EXIT:"))throw i;if(n(i))return void console.log(f.yellow(r));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},options:[]},{name:"set",description:"Create or update a secret (prompts for missing KEY/VALUE)",handler:new class{async execute(e={}){s("Secrets set flow started");let{name:o,value:a}=e;const i="1"===process.env.DASHNEX_CI;o||(i&&(console.error(f.red("--name is required in CI mode (--ci).")),process.exit(1)),o=(await S.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim()),a||(i&&(console.error(f.red("--value is required in CI mode (--ci).")),process.exit(1)),a=(await S.prompt([{type:"password",name:"value",message:`Enter value for ${o}:`,mask:"*",validate:e=>""!==e||"Value is required"}])).value);const c=await m();if(!c)return;const l=`${t()}/business/v1/cli/secrets`;s(`PUT ${l}`);const d=q();d.start(`Setting secret '${o}'...`);try{const e=await fetch(l,{method:"PUT",headers:{Authorization:`Bearer ${c.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:o,value:a})});if(d.stop(),s(`Response: ${e.status}`),!e.ok){let t="Failed to set secret.";401===e.status||403===e.status?t="Please run 'dashnex login' to authenticate.":400===e.status?t="Missing or empty name / value.":404===e.status?t="Business has no application.":502===e.status&&(t="Error setting secret. Make sure your application is deployed."),console.error(f.red(t)),process.exit(1)}s(`Secret '${o}' set successfully`),console.log(f.green(`Secret '${o}' set successfully.`))}catch(u){if(d.stop(),p(u),u instanceof Error&&u.message.startsWith("EXIT:"))throw u;if(n(u))return void console.log(f.yellow(r));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},arguments:[{name:"name",description:"Secret name (KEY)"},{name:"value",description:"Secret value"}],options:[{flags:"--name <name>",description:"Secret name (alternative to positional KEY)"},{flags:"--value <value>",description:"Secret value (alternative to positional VALUE)"}]},{name:"delete",description:"Delete a secret (prompts for missing KEY)",handler:new class{async execute(e={}){s("Secrets delete flow started");let{name:o}=e;const a="1"===process.env.DASHNEX_CI;o||(a&&(console.error(f.red("--name is required in CI mode (--ci).")),process.exit(1)),o=(await S.prompt([{type:"input",name:"name",message:"Secret name:",validate:e=>""!==e.trim()||"Name is required"}])).name.trim());const i=await m();if(!i)return;const c=`${t()}/business/v1/cli/secrets/${encodeURIComponent(o)}`;s(`DELETE ${c}`);const l=q();l.start(`Deleting secret '${o}'...`);try{const e=await fetch(c,{method:"DELETE",headers:{Authorization:`Bearer ${i.token}`}});if(l.stop(),s(`Response: ${e.status}`),!e.ok){let t="Failed to delete secret.";401===e.status||403===e.status?t="Please run 'dashnex login' to authenticate.":404===e.status?t=`Secret '${o}' not found.`:502===e.status&&(t="Error deleting secret. Make sure your application is deployed."),console.error(f.red(t)),process.exit(1)}s(`Secret '${o}' deleted successfully`),console.log(f.green(`Secret '${o}' deleted.`))}catch(d){if(l.stop(),p(d),d instanceof Error&&d.message.startsWith("EXIT:"))throw d;if(n(d))return void console.log(f.yellow(r));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}}},arguments:[{name:"name",description:"Secret name (KEY)"}],options:[{flags:"--name <name>",description:"Secret name (alternative to positional KEY)"}]}]},Pt=[{name:"version",description:"Display the version of the CLI",handler:new class{async execute(e){const t=y.dirname($(import.meta.url)),o=JSON.parse(b.readFileSync(y.resolve(t,"..","..","package.json"),"utf8"));console.log(o.version)}},options:[]},{name:"login",description:"Log in to your DashNex account",handler:new class{async execute(t={}){s("Login flow started");const a=e(process.cwd()),i=await m({exitOnFailure:!1,dashnexPath:a});if(i)console.log(f.green(`Already logged in as ${i.userName??"user"}`));else{o()||(console.error(f.red("No DashNex ID OAuth client is configured for this environment.")),console.error(f.yellow("Set DASHNEX_OAUTH_CLIENT_ID, or use APPLICATION_ENV=qa.")),process.exit(1));try{const e=await this.readSavedIdToken(a);if(e){s("Resuming with saved DashNex ID session");try{return void(await this.selectBusiness(e,a,t.business))}catch(c){if(!(c instanceof W))throw c;s("Saved DashNex ID session rejected, starting a new sign-in")}}const o=await this.authorize(!1!==t.browser);await Q(a,{idToken:o.token,...o.refreshToken&&{idRefreshToken:o.refreshToken}}),await this.selectBusiness(o.token,a,t.business)}catch(c){if(p(c),n(c))return void console.log(f.yellow(r));if((c instanceof U||c instanceof M)&&(console.error(f.red(c.message)),process.exit(1)),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;console.error(f.red("Could not reach DashNex. Check your connection and try again.")),process.exit(1)}}}async authorize(e){const{verifier:t,challenge:n}=(()=>{const e=z(C(32));return{verifier:e,challenge:z(D("sha256").update(e).digest())}})(),r=(e=>{const t=new URL(`${i()}/api/oauth/authorize`);return t.searchParams.set("client_id",o()),t.searchParams.set("redirect_uri",L),t.searchParams.set("response_type","code"),t.searchParams.set("code_challenge",e),t.searchParams.set("code_challenge_method","S256"),t.toString()})(n);s(`Authorize URL: ${r}`);const a=!!e&&await _(r);console.log(""),a?(console.log(f.green("Opened your browser to finish signing in.")),console.log(f.dim("If nothing opened, use this URL:"))):console.log(f.bold("Open this URL to sign in:")),console.log(f.cyan(r)),console.log(""),console.log(f.dim("Approve the request, then copy the code shown and paste it below.")),console.log("");const{code:l}=await S.prompt([{type:"input",name:"code",message:"Paste the code:",validate:e=>!!e.trim()||"Code is required"}]),p=q();p.start("Verifying code...");try{return await(async(e,t)=>{const n=`${i()}/api/oauth/token`;s(`POST ${n}`);const{response:r,body:a}=await d(n,{method:"POST",body:JSON.stringify({grant_type:"authorization_code",client_id:o(),redirect_uri:L,code:e.trim(),code_verifier:t})});if(s(`Response: ${r.status}`),c("Token response",a),!r.ok){const e="string"==typeof a.error?a.error:void 0,t="string"==typeof a.error_description?a.error_description:void 0;if("invalid_grant"===e)throw new U("That code is not valid anymore. Codes expire 10 minutes after they are issued and can only be used once.",e);throw new U(t??"Could not exchange the code for a token.",e)}const l=a;if(!l.access_token)throw new U("The authorization server did not return an access token.");return{token:l.access_token,refreshToken:l.refresh_token,expiresIn:l.expires_in}})(l,t)}finally{p.stop()}}async selectBusiness(e,t,o){const s=await V(e,t,{businessId:o});console.log(f.green(`Logged in as ${s.name}`))}async readSavedIdToken(e){if(!(await w.pathExists(e)))return null;try{return(await w.readJson(e)).idToken??null}catch{return null}}},options:[{flags:"--business <id>",description:"Business ID to select (skip prompt)"},{flags:"--no-browser",description:"Print the sign-in URL instead of opening a browser"}]},{name:"logout",description:"Log out and remove local credentials",handler:new class{async execute(){const t=e(process.cwd());if(await w.pathExists(t)){const e=await w.readJson(t);delete e.token,delete e.refreshToken,delete e.businessId,await w.writeJson(t,e,{spaces:2})}console.log(f.green("Logged out."))}},options:[]},{name:"switch",description:"Switch to another business (prompts when no ID is given)",handler:new class{async execute(e={}){s("Switch flow started");const t=await l(process.cwd()),o=t?await this.readSession(t):null;t&&o?.token||(console.error(f.red("Please run 'dashnex login' to authenticate.")),process.exit(1)),o.idToken||(console.error(f.red("Switching businesses requires signing in with DashNex ID.")),console.error(f.yellow("Run 'dashnex logout' and then 'dashnex login' to sign in again.")),process.exit(1));try{const s=await V(o.idToken,t,{businessId:e.businessId,currentBusinessId:o.businessId});console.log(f.green(`Switched to ${s.name}`))}catch(a){if(p(a),n(a))return void console.log(f.yellow(r));if(a instanceof W&&(console.error(f.red(a.message)),console.error(f.yellow("Run 'dashnex logout' and then 'dashnex login' to sign in again.")),process.exit(1)),a instanceof M&&(console.error(f.red(a.message)),process.exit(1)),a instanceof Error&&a.message.startsWith("EXIT:"))throw a;console.error(f.red("Could not reach DashNex. Check your connection and try again.")),process.exit(1)}}async readSession(e){try{return await w.readJson(e)}catch{return null}}},arguments:[{name:"businessId",description:"Business ID to switch to (skip prompt)"}],options:[]},{name:"whoami",description:"Show current logged-in business and user",handler:new class{async execute(){s("Whoami flow started");const e=await m();if(!e)return;const o=await u()?`${t()}/business/v1/`:`${h()}/users/v1/`;s(`GET ${o}`);const a=q();a.start("Fetching user info...");try{const t=await fetch(o,{headers:{Authorization:`Bearer ${e.token}`}});if(a.stop(),s(`Response: ${t.status}`),!t.ok){const e=t.headers.get("content-type")??"";let o="Failed to fetch user info.";if(401===t.status||403===t.status)o="Please run 'dashnex login' to authenticate.";else if(e.includes("application/json")){const e="string"==typeof(i=await t.json().catch(()=>({}))).error?i.error:"string"==typeof i.message?i.message:void 0;e&&(o=e)}console.error(f.red(o)),process.exit(1)}const n=await t.json().catch(()=>({})),r="string"==typeof n.name?n.name:"string"==typeof n.companyName?n.companyName:"Unknown",c=n.memberUser,l=c&&"string"==typeof c.fullName?c.fullName:c&&"string"==typeof c.name?c.name:"Unknown";s(`Whoami: ${r} (${l})`),console.log(f.green(`You are logged in as ${r} (${l})`))}catch(c){if(a.stop(),p(c),c instanceof Error&&c.message.startsWith("EXIT:"))throw c;if(n(c))return void console.log(f.yellow(r));console.error(f.red("Could not reach DashNex API. Check your connection and try again.")),process.exit(1)}var i}},options:[]},{name:"dev",description:"Run the development server (run in DashNex application folder)",handler:new class{async execute(e={}){s("Dev flow started");try{const t=await ue(process.cwd(),e);process.exit(t)}catch(t){if(t instanceof Error&&t.message.startsWith("EXIT:"))throw t;p(t),t instanceof Error?console.error(f.red(t.message)):console.error(f.red("Failed to run npm run dev")),process.exit(1)}}},options:[{flags:"-p, --port <port>",description:"Port for the dev server (default: PORT env or 3000)"},{flags:"-H, --host <host>",description:"Host to bind, e.g. 0.0.0.0 inside Docker (default: HOST env or localhost)"},{flags:"--https",description:"Serve over HTTPS with a trusted local certificate (mkcert)"}]},{name:"check",description:"Run build-time validations (run in DashNex application folder)",handler:new Ee,options:[]},{name:"install",description:"Install dependencies using pnpm (preferred) or npm (run in DashNex application folder)",handler:new class{async execute(){s("Install flow started");const e=y.join(process.cwd(),"dashnex.json");await w.pathExists(e)||(console.error(f.red("Run this command in a DashNex Web application folder.")),process.exit(1));const t=process.cwd(),o=q();o.start("Installing dependencies...");try{const e=await me(t);o.stop(),0!==e&&process.exit(e),console.log(f.green("Dependencies installed.")),process.exit(0)}catch(n){o.stop(),p(n),n instanceof Error?console.error(f.red(n.message)):console.error(f.red("Failed to run install")),process.exit(1)}}},options:[]},Tt,Ct];export{Pt as default};
package/dist/server.js CHANGED
@@ -1 +1 @@
1
- import{n as s,t as e}from"./chunks/dashnex-BWlu5keu.js";var n={name:s.name,version:s.version,description:s.description,...e};export{n as default};
1
+ import{n as s,t as e}from"./chunks/dashnex-BKzrTB6t.js";var n={name:s.name,version:s.version,description:s.description,...e};export{n as default};
@@ -12,20 +12,5 @@ export declare class LoginCommand implements CliCommand {
12
12
  */
13
13
  private authorize;
14
14
  private selectBusiness;
15
- private pickBusiness;
16
15
  private readSavedIdToken;
17
- private fetchCliSettings;
18
- /**
19
- * Keys this command used to write and no longer does. Merging preserves
20
- * everything by default, so anything we retired has to be dropped explicitly
21
- * or it lingers in every settings file that ever saw an older CLI.
22
- */
23
- private static readonly OBSOLETE_KEYS;
24
- /**
25
- * Merges into settings.json rather than replacing it. The file also holds
26
- * business CLI settings and anything an app or module put there, so a login
27
- * must only ever add or update its own keys.
28
- */
29
- private writeConfig;
30
- private ensureGitignore;
31
16
  }
@@ -0,0 +1,8 @@
1
+ import { CliCommand } from '@dashnex/types';
2
+ export interface SwitchCommandOptions {
3
+ businessId?: string;
4
+ }
5
+ export declare class SwitchCommand implements CliCommand {
6
+ execute(options?: SwitchCommandOptions): Promise<void>;
7
+ private readSession;
8
+ }
@@ -7,6 +7,7 @@ export interface EnsureLoggedInOptions {
7
7
  exitOnFailure?: boolean;
8
8
  dashnexPath?: string;
9
9
  }
10
+ export declare const findDashnexPath: (startDir: string) => Promise<string | null>;
10
11
  /**
11
12
  * Whether the stored credentials were minted through DashNex ID, i.e. whether a
12
13
  * DashNex ID session token is on file. Commands use this to pick the API that
@@ -0,0 +1,19 @@
1
+ import { Business } from './businesses.js';
2
+ export interface SelectBusinessOptions {
3
+ /** Business ID to switch to without prompting. */
4
+ businessId?: string | number;
5
+ /** Business the session is currently on; preselected in the picker. */
6
+ currentBusinessId?: string | number;
7
+ }
8
+ /**
9
+ * Lists the businesses the DashNex ID session can reach, lets the user pick
10
+ * one (or takes `businessId`), exchanges the session for a token scoped to it
11
+ * and saves that token to settings.json.
12
+ */
13
+ export declare const selectBusiness: (idToken: string, dashnexPath: string, options?: SelectBusinessOptions) => Promise<Business>;
14
+ /**
15
+ * Merges into settings.json rather than replacing it. The file also holds
16
+ * business CLI settings and anything an app or module put there, so the CLI
17
+ * must only ever add or update its own keys.
18
+ */
19
+ export declare const writeSettings: (dashnexPath: string, config: Record<string, unknown>) => Promise<void>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "dashnex",
4
- "version": "0.7.0",
4
+ "version": "0.7.1",
5
5
  "dashnex": {
6
6
  "minAppVersion": "1.1.0"
7
7
  },