drixio 1.1.1 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var Zt=Object.defineProperty;var E=(n,t)=>()=>(n&&(t=n(n=0)),t);var L=(n,t)=>{for(var a in t)Zt(n,a,{get:t[a],enumerable:!0})};import P from"picocolors";function _e(){console.log(`
2
+ var Zt=Object.defineProperty;var E=(n,a)=>()=>(n&&(a=n(n=0)),a);var L=(n,a)=>{for(var t in a)Zt(n,t,{get:a[t],enumerable:!0})};import P from"picocolors";function _e(){console.log(`
3
3
 
4
4
 
5
5
  `+P.bold(Jt(` \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557
@@ -7,14 +7,14 @@ var Zt=Object.defineProperty;var E=(n,t)=>()=>(n&&(t=n(n=0)),t);var L=(n,t)=>{fo
7
7
  `)+ea(` \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551
8
8
  `)+ta(` \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551
9
9
  `)+aa(` \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u255D \u2588\u2588\u2557 \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D
10
- `)+oa(" \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D")))}function se(n,t){let r="\u2550".repeat(72);console.log(P.cyan(`
11
- \u2554${r}\u2557`));let o=72-n.length,e=Math.max(0,Math.floor(o/2)),s=Math.max(0,o-e),c=" ".repeat(e)+P.bold(P.white(n))+" ".repeat(s);console.log(P.cyan("\u2551")+c+P.cyan("\u2551")),console.log(P.cyan(`\u2560${"\u2550".repeat(72)}\u2563`));let i=(l,m)=>{let p=l.padEnd(12),u=` ${P.bold(p)}: ${m}`,d=` ${p}: `+m.replace(/\x1b\[[0-9;]*m/g,""),f=" ".repeat(Math.max(0,72-d.length));console.log(P.cyan("\u2551")+u+f+P.cyan("\u2551"))};for(let l of t)i(l.label,l.value);console.log(P.cyan(`\u255A${"\u2550".repeat(72)}\u255D`)),console.log(P.dim(` Use arrow keys to navigate \u2022 Enter to select \u2022 Ctrl+C to exit
12
- `))}function Fe(n){let t=" Lightweight Interactive TUI Database Client \u2022 v1.1.1 ",a="None",r="-",o="None";n.type==="unknown"?o=P.dim("No configuration found. Please run check to configure."):(a=n.type.toUpperCase(),r=n.targetUrl,o=n.source===".env"?"Loaded from project .env file":n.source==="auto-detected"?"Auto-detected local SQLite file":"Manual connection config"),se(t,[{label:"Database",value:a},{label:"Target",value:r.length>45?"..."+r.slice(-42):r},{label:"Source",value:o},{label:"Working Dir",value:process.cwd().length>45?"..."+process.cwd().slice(-42):process.cwd()}])}var Z,Jt,Xt,ea,ta,aa,oa,$e=E(()=>{"use strict";Z=(n,t,a)=>r=>`\x1B[38;2;${n};${t};${a}m${r}\x1B[39m`,Jt=Z(0,255,255),Xt=Z(0,230,245),ea=Z(0,210,235),ta=Z(0,188,220),aa=Z(0,168,205),oa=Z(0,148,188)});var Se,We=E(()=>{"use strict";Se=class{dbPath;db=null;constructor(t){this.dbPath=t}async getDb(){if(!this.db){if(!(await import("fs")).existsSync(this.dbPath))throw new Error(`Failed to found database file at: ${this.dbPath}`);let a=await import("sqlite");this.db=new a.DatabaseSync(this.dbPath)}return this.db}async getTables(){return(await this.getDb()).prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name;").all().map(r=>r.name)}async getSchema(t){let a=await this.getDb();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new Error(`Invalid table name: ${t}`);return a.prepare(`PRAGMA table_info("${t}")`).all().map(e=>({name:e.name,type:e.type,isPk:e.pk>0,nullable:e.notnull===0}))}async getData(t,a=50,r=0,o,e){let s=await this.getDb();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new Error(`Invalid table name: ${t}`);let i=(await this.getSchema(t)).map(u=>u.name),l=`SELECT * FROM "${t}"`;o&&(l+=` WHERE ${o}`),e&&(l+=` ORDER BY "${e.col}" ${e.asc?"ASC":"DESC"}`),l+=` LIMIT ${a} OFFSET ${r}`;let p=s.prepare(l).all();return{columns:i,rows:p}}async query(t){let r=(await this.getDb()).prepare(t);if(t.trim().toUpperCase().startsWith("SELECT")||t.trim().toUpperCase().startsWith("PRAGMA")){let e=r.all(),s=[];return e.length>0&&(s=Object.keys(e[0])),{columns:s,rows:e}}else return r.run(),{columns:["Result"],rows:[{Result:"Success"}]}}async executeSql(t){(await this.getDb()).exec(t)}async close(){this.db&&(this.db.close(),this.db=null)}async insert(t,a){if(a.length===0)return;let r=await this.getDb(),o=Object.keys(a[0]),e=o.map(()=>"?").join(", "),s=`INSERT INTO "${t}" ("${o.join('", "')}") VALUES (${e})`,c=r.prepare(s);for(let i of a){let l=o.map(m=>i[m]);c.run(...l)}}}});import na from"pg";var xe,je=E(()=>{"use strict";xe=class{client;connected=!1;constructor(t){this.client=new na.Client({connectionString:t})}async connectIfNecessary(){this.connected||(await this.client.connect(),this.connected=!0)}async getTables(){return await this.connectIfNecessary(),(await this.client.query(`
10
+ `)+oa(" \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D")))}function se(n,a){let r="\u2550".repeat(72);console.log(P.cyan(`
11
+ \u2554${r}\u2557`));let o=72-n.length,e=Math.max(0,Math.floor(o/2)),s=Math.max(0,o-e),c=" ".repeat(e)+P.bold(P.white(n))+" ".repeat(s);console.log(P.cyan("\u2551")+c+P.cyan("\u2551")),console.log(P.cyan(`\u2560${"\u2550".repeat(72)}\u2563`));let i=(l,m)=>{let p=l.padEnd(12),u=` ${P.bold(p)}: ${m}`,d=` ${p}: `+m.replace(/\x1b\[[0-9;]*m/g,""),f=" ".repeat(Math.max(0,72-d.length));console.log(P.cyan("\u2551")+u+f+P.cyan("\u2551"))};for(let l of a)i(l.label,l.value);console.log(P.cyan(`\u255A${"\u2550".repeat(72)}\u255D`)),console.log(P.dim(` Use arrow keys to navigate \u2022 Enter to select \u2022 Ctrl+C to exit
12
+ `))}function Fe(n){let a=" Lightweight Interactive TUI Database Client \u2022 v1.1.2 ",t="None",r="-",o="None";n.type==="unknown"?o=P.dim("No configuration found. Please run check to configure."):(t=n.type.toUpperCase(),r=n.targetUrl,o=n.source===".env"?"Loaded from project .env file":n.source==="auto-detected"?"Auto-detected local SQLite file":"Manual connection config"),se(a,[{label:"Database",value:t},{label:"Target",value:r.length>45?"..."+r.slice(-42):r},{label:"Source",value:o},{label:"Working Dir",value:process.cwd().length>45?"..."+process.cwd().slice(-42):process.cwd()}])}var Z,Jt,Xt,ea,ta,aa,oa,$e=E(()=>{"use strict";Z=(n,a,t)=>r=>`\x1B[38;2;${n};${a};${t}m${r}\x1B[39m`,Jt=Z(0,255,255),Xt=Z(0,230,245),ea=Z(0,210,235),ta=Z(0,188,220),aa=Z(0,168,205),oa=Z(0,148,188)});var Se,We=E(()=>{"use strict";Se=class{dbPath;db=null;constructor(a){this.dbPath=a}async getDb(){if(!this.db){if(!(await import("fs")).existsSync(this.dbPath))throw new Error(`Failed to found database file at: ${this.dbPath}`);let t=await import("sqlite");this.db=new t.DatabaseSync(this.dbPath)}return this.db}async getTables(){return(await this.getDb()).prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name;").all().map(r=>r.name)}async getSchema(a){let t=await this.getDb();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a))throw new Error(`Invalid table name: ${a}`);return t.prepare(`PRAGMA table_info("${a}")`).all().map(e=>({name:e.name,type:e.type,isPk:e.pk>0,nullable:e.notnull===0}))}async getData(a,t=50,r=0,o,e){let s=await this.getDb();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a))throw new Error(`Invalid table name: ${a}`);let i=(await this.getSchema(a)).map(u=>u.name),l=`SELECT * FROM "${a}"`;o&&(l+=` WHERE ${o}`),e&&(l+=` ORDER BY "${e.col}" ${e.asc?"ASC":"DESC"}`),l+=` LIMIT ${t} OFFSET ${r}`;let p=s.prepare(l).all();return{columns:i,rows:p}}async query(a){let r=(await this.getDb()).prepare(a);if(a.trim().toUpperCase().startsWith("SELECT")||a.trim().toUpperCase().startsWith("PRAGMA")){let e=r.all(),s=[];return e.length>0&&(s=Object.keys(e[0])),{columns:s,rows:e}}else return r.run(),{columns:["Result"],rows:[{Result:"Success"}]}}async executeSql(a){(await this.getDb()).exec(a)}async close(){this.db&&(this.db.close(),this.db=null)}async insert(a,t){if(t.length===0)return;let r=await this.getDb(),o=Object.keys(t[0]),e=o.map(()=>"?").join(", "),s=`INSERT INTO "${a}" ("${o.join('", "')}") VALUES (${e})`,c=r.prepare(s);for(let i of t){let l=o.map(m=>i[m]);c.run(...l)}}}});import na from"pg";var xe,je=E(()=>{"use strict";xe=class{client;connected=!1;constructor(a){this.client=new na.Client({connectionString:a})}async connectIfNecessary(){this.connected||(await this.client.connect(),this.connected=!0)}async getTables(){return await this.connectIfNecessary(),(await this.client.query(`
13
13
  SELECT tablename
14
14
  FROM pg_catalog.pg_tables
15
15
  WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema'
16
16
  ORDER BY tablename;
17
- `)).rows.map(r=>r.tablename)}async getSchema(t){if(await this.connectIfNecessary(),!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t))throw new Error(`Invalid table name: ${t}`);return(await this.client.query(`
17
+ `)).rows.map(r=>r.tablename)}async getSchema(a){if(await this.connectIfNecessary(),!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a))throw new Error(`Invalid table name: ${a}`);return(await this.client.query(`
18
18
  SELECT c.column_name, c.data_type, c.is_nullable,
19
19
  (SELECT count(*)
20
20
  FROM information_schema.key_column_usage kcu
@@ -25,42 +25,42 @@ var Zt=Object.defineProperty;var E=(n,t)=>()=>(n&&(t=n(n=0)),t);var L=(n,t)=>{fo
25
25
  AND kcu.column_name = c.column_name) as is_pk
26
26
  FROM information_schema.columns c
27
27
  WHERE c.table_name = $1;
28
- `,[t])).rows.map(o=>({name:o.column_name,type:o.data_type,isPk:parseInt(o.is_pk)>0,nullable:o.is_nullable==="YES"}))}async getData(t,a=50,r=0,o,e){if(await this.connectIfNecessary(),!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t))throw new Error(`Invalid table name: ${t}`);let c=(await this.getSchema(t)).map(m=>m.name),i=`SELECT * FROM "${t}"`;o&&(i+=` WHERE ${o}`),e&&(i+=` ORDER BY "${e.col}" ${e.asc?"ASC":"DESC"}`),i+=" LIMIT $1 OFFSET $2";let l=await this.client.query(i,[a,r]);return{columns:c,rows:l.rows}}async query(t){await this.connectIfNecessary();let a=await this.client.query(t),r=[];return a.fields&&(r=a.fields.map(o=>o.name)),{columns:r,rows:a.rows||[]}}async executeSql(t){await this.connectIfNecessary(),await this.client.query(t)}async close(){this.connected&&(await this.client.end(),this.connected=!1)}async insert(t,a){if(a.length===0)return;await this.connectIfNecessary();let r=Object.keys(a[0]);for(let o of a){let e=r.map((i,l)=>`$${l+1}`).join(", "),s=`INSERT INTO "${t}" ("${r.join('", "')}") VALUES (${e})`,c=r.map(i=>o[i]);await this.client.query(s,c)}}}});import sa from"mysql2/promise";var Te,Ve=E(()=>{"use strict";Te=class{connection;pool=null;constructor(t){this.connection=t}async getPool(){return this.pool||(this.pool=sa.createPool(this.connection)),this.pool}async getTables(){let t=await this.getPool(),[a]=await t.query("SHOW TABLES;");return a.map(r=>Object.values(r)[0])}async getSchema(t){let a=await this.getPool();if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t))throw new Error(`Invalid table name: ${t}`);let[r]=await a.query(`SHOW COLUMNS FROM \`${t}\``);return r.map(e=>({name:e.Field,type:e.Type,isPk:e.Key==="PRI",nullable:e.Null==="YES",extra:e.Extra}))}async getData(t,a=50,r=0,o,e){let s=await this.getPool();if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t))throw new Error(`Invalid table name: ${t}`);let i=(await this.getSchema(t)).map(p=>p.name),l=`SELECT * FROM \`${t}\``;o&&(l+=` WHERE ${o}`),e&&(l+=` ORDER BY \`${e.col}\` ${e.asc?"ASC":"DESC"}`),l+=` LIMIT ${a} OFFSET ${r}`;let[m]=await s.query(l);return{columns:i,rows:m}}async query(t){let a=await this.getPool(),[r,o]=await a.query(t),e=[],s=[];return o&&Array.isArray(o)?(e=o.map(c=>c.name),s=r):(e=["Result"],s=[{Result:"Success",AffectedRows:r.affectedRows}]),{columns:e,rows:s}}async executeSql(t){await(await this.getPool()).query(t)}async close(){this.pool&&(await this.pool.end(),this.pool=null)}async insert(t,a){if(a.length===0)return;let r=await this.getPool(),o=Object.keys(a[0]);for(let e of a){let s=o.map(()=>"?").join(", "),c=`INSERT INTO \`${t}\` (\`${o.join("`, `")}\`) VALUES (${s})`,i=o.map(l=>e[l]);await r.query(c,i)}}}});var Qe={};L(Qe,{createDBAdapter:()=>h});function h(n){switch(n.type){case"sqlite":return new Se(n.targetUrl);case"postgres":return new xe(n.targetUrl);case"mysql":return new Te(n.targetUrl);default:throw new Error(`Unsupported database type: ${n.type}`)}}var C=E(()=>{"use strict";We();je();Ve()});function j(n){switch(n){case"sqlite":return new De;case"postgres":return new Le;case"mysql":return new Pe;default:return new De}}var De,Le,Pe,Ce=E(()=>{"use strict";De=class{quoteIdentifier(t){return`"${t}"`}escapeString(t){return t.replace(/'/g,"''")}buildCreateTable(t,a){let r=a.map(e=>{let s="";return e.type==="Integer"&&(s="INTEGER"),e.type==="Text"&&(s="TEXT"),e.type==="Boolean"&&(s="BOOLEAN"),e.type==="Decimal"&&(s="REAL"),e.type==="DateTime"&&(s="DATETIME"),e.type==="Enum"&&e.enumValues&&(s=`TEXT CHECK(${this.quoteIdentifier(e.name)} IN (${e.enumValues.map(c=>`'${this.escapeString(c)}'`).join(", ")}))`),e.isPk&&e.type==="Integer"?s="INTEGER PRIMARY KEY AUTOINCREMENT":e.isPk?s+=" PRIMARY KEY":e.nullable||(s+=" NOT NULL"),e.defaultValue&&e.defaultValue!=="AutoInc"&&!e.defaultValue.startsWith("FK ->")&&(e.defaultValue==="Timestamp"?s+=" DEFAULT CURRENT_TIMESTAMP":s+=` DEFAULT ${e.defaultValue}`),` ${this.quoteIdentifier(e.name)} ${s}`}),o=a.filter(e=>e.fkTarget).map(e=>` FOREIGN KEY (${this.quoteIdentifier(e.name)}) REFERENCES ${this.quoteIdentifier(e.fkTarget.table)}(${this.quoteIdentifier(e.fkTarget.column)})`);return o.length>0&&r.push(...o),`CREATE TABLE ${this.quoteIdentifier(t)} (
28
+ `,[a])).rows.map(o=>({name:o.column_name,type:o.data_type,isPk:parseInt(o.is_pk)>0,nullable:o.is_nullable==="YES"}))}async getData(a,t=50,r=0,o,e){if(await this.connectIfNecessary(),!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a))throw new Error(`Invalid table name: ${a}`);let c=(await this.getSchema(a)).map(m=>m.name),i=`SELECT * FROM "${a}"`;o&&(i+=` WHERE ${o}`),e&&(i+=` ORDER BY "${e.col}" ${e.asc?"ASC":"DESC"}`),i+=" LIMIT $1 OFFSET $2";let l=await this.client.query(i,[t,r]);return{columns:c,rows:l.rows}}async query(a){await this.connectIfNecessary();let t=await this.client.query(a),r=[];return t.fields&&(r=t.fields.map(o=>o.name)),{columns:r,rows:t.rows||[]}}async executeSql(a){await this.connectIfNecessary(),await this.client.query(a)}async close(){this.connected&&(await this.client.end(),this.connected=!1)}async insert(a,t){if(t.length===0)return;await this.connectIfNecessary();let r=Object.keys(t[0]);for(let o of t){let e=r.map((i,l)=>`$${l+1}`).join(", "),s=`INSERT INTO "${a}" ("${r.join('", "')}") VALUES (${e})`,c=r.map(i=>o[i]);await this.client.query(s,c)}}}});import sa from"mysql2/promise";var Te,Ve=E(()=>{"use strict";Te=class{connection;pool=null;constructor(a){this.connection=a}async getPool(){return this.pool||(this.pool=sa.createPool(this.connection)),this.pool}async getTables(){let a=await this.getPool(),[t]=await a.query("SHOW TABLES;");return t.map(r=>Object.values(r)[0])}async getSchema(a){let t=await this.getPool();if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a))throw new Error(`Invalid table name: ${a}`);let[r]=await t.query(`SHOW COLUMNS FROM \`${a}\``);return r.map(e=>({name:e.Field,type:e.Type,isPk:e.Key==="PRI",nullable:e.Null==="YES",extra:e.Extra}))}async getData(a,t=50,r=0,o,e){let s=await this.getPool();if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a))throw new Error(`Invalid table name: ${a}`);let i=(await this.getSchema(a)).map(p=>p.name),l=`SELECT * FROM \`${a}\``;o&&(l+=` WHERE ${o}`),e&&(l+=` ORDER BY \`${e.col}\` ${e.asc?"ASC":"DESC"}`),l+=` LIMIT ${t} OFFSET ${r}`;let[m]=await s.query(l);return{columns:i,rows:m}}async query(a){let t=await this.getPool(),[r,o]=await t.query(a),e=[],s=[];return o&&Array.isArray(o)?(e=o.map(c=>c.name),s=r):(e=["Result"],s=[{Result:"Success",AffectedRows:r.affectedRows}]),{columns:e,rows:s}}async executeSql(a){await(await this.getPool()).query(a)}async close(){this.pool&&(await this.pool.end(),this.pool=null)}async insert(a,t){if(t.length===0)return;let r=await this.getPool(),o=Object.keys(t[0]);for(let e of t){let s=o.map(()=>"?").join(", "),c=`INSERT INTO \`${a}\` (\`${o.join("`, `")}\`) VALUES (${s})`,i=o.map(l=>e[l]);await r.query(c,i)}}}});var Qe={};L(Qe,{createDBAdapter:()=>h});function h(n){switch(n.type){case"sqlite":return new Se(n.targetUrl);case"postgres":return new xe(n.targetUrl);case"mysql":return new Te(n.targetUrl);default:throw new Error(`Unsupported database type: ${n.type}`)}}var C=E(()=>{"use strict";We();je();Ve()});function j(n){switch(n){case"sqlite":return new De;case"postgres":return new Le;case"mysql":return new Pe;default:return new De}}var De,Le,Pe,Ce=E(()=>{"use strict";De=class{quoteIdentifier(a){return`"${a}"`}escapeString(a){return a.replace(/'/g,"''")}buildCreateTable(a,t){let r=t.map(e=>{let s="";return e.type==="Integer"&&(s="INTEGER"),e.type==="Text"&&(s="TEXT"),e.type==="Boolean"&&(s="BOOLEAN"),e.type==="Decimal"&&(s="REAL"),e.type==="DateTime"&&(s="DATETIME"),e.type==="Enum"&&e.enumValues&&(s=`TEXT CHECK(${this.quoteIdentifier(e.name)} IN (${e.enumValues.map(c=>`'${this.escapeString(c)}'`).join(", ")}))`),e.isPk&&e.type==="Integer"?s="INTEGER PRIMARY KEY AUTOINCREMENT":e.isPk?s+=" PRIMARY KEY":e.nullable||(s+=" NOT NULL"),e.defaultValue&&e.defaultValue!=="AutoInc"&&!e.defaultValue.startsWith("FK ->")&&(e.defaultValue==="Timestamp"?s+=" DEFAULT CURRENT_TIMESTAMP":s+=` DEFAULT ${e.defaultValue}`),` ${this.quoteIdentifier(e.name)} ${s}`}),o=t.filter(e=>e.fkTarget).map(e=>` FOREIGN KEY (${this.quoteIdentifier(e.name)}) REFERENCES ${this.quoteIdentifier(e.fkTarget.table)}(${this.quoteIdentifier(e.fkTarget.column)})`);return o.length>0&&r.push(...o),`CREATE TABLE ${this.quoteIdentifier(a)} (
29
29
  ${r.join(`,
30
30
  `)}
31
- );`}},Le=class{quoteIdentifier(t){return`"${t}"`}escapeString(t){return t.replace(/'/g,"''")}buildCreateTable(t,a){let r=a.map(e=>{let s="";return e.isPk&&e.type==="Integer"?s="SERIAL PRIMARY KEY":(e.type==="Integer"&&(s="INTEGER"),e.type==="Text"&&(s="TEXT"),e.type==="Boolean"&&(s="BOOLEAN"),e.type==="Decimal"&&(s="NUMERIC"),e.type==="DateTime"&&(s="TIMESTAMP"),e.type==="Enum"&&e.enumValues&&(s=`VARCHAR(255) CHECK(${this.quoteIdentifier(e.name)} IN (${e.enumValues.map(c=>`'${this.escapeString(c)}'`).join(", ")}))`),e.isPk&&(s+=" PRIMARY KEY"),!e.nullable&&!e.isPk&&(s+=" NOT NULL")),e.defaultValue&&e.defaultValue!=="AutoInc"&&!e.defaultValue.startsWith("FK ->")&&(e.defaultValue==="Timestamp"?s+=" DEFAULT CURRENT_TIMESTAMP":s+=` DEFAULT ${e.defaultValue}`),` ${this.quoteIdentifier(e.name)} ${s}`}),o=a.filter(e=>e.fkTarget).map(e=>` FOREIGN KEY (${this.quoteIdentifier(e.name)}) REFERENCES ${this.quoteIdentifier(e.fkTarget.table)}(${this.quoteIdentifier(e.fkTarget.column)})`);return o.length>0&&r.push(...o),`CREATE TABLE ${this.quoteIdentifier(t)} (
31
+ );`}},Le=class{quoteIdentifier(a){return`"${a}"`}escapeString(a){return a.replace(/'/g,"''")}buildCreateTable(a,t){let r=t.map(e=>{let s="";return e.isPk&&e.type==="Integer"?s="SERIAL PRIMARY KEY":(e.type==="Integer"&&(s="INTEGER"),e.type==="Text"&&(s="TEXT"),e.type==="Boolean"&&(s="BOOLEAN"),e.type==="Decimal"&&(s="NUMERIC"),e.type==="DateTime"&&(s="TIMESTAMP"),e.type==="Enum"&&e.enumValues&&(s=`VARCHAR(255) CHECK(${this.quoteIdentifier(e.name)} IN (${e.enumValues.map(c=>`'${this.escapeString(c)}'`).join(", ")}))`),e.isPk&&(s+=" PRIMARY KEY"),!e.nullable&&!e.isPk&&(s+=" NOT NULL")),e.defaultValue&&e.defaultValue!=="AutoInc"&&!e.defaultValue.startsWith("FK ->")&&(e.defaultValue==="Timestamp"?s+=" DEFAULT CURRENT_TIMESTAMP":s+=` DEFAULT ${e.defaultValue}`),` ${this.quoteIdentifier(e.name)} ${s}`}),o=t.filter(e=>e.fkTarget).map(e=>` FOREIGN KEY (${this.quoteIdentifier(e.name)}) REFERENCES ${this.quoteIdentifier(e.fkTarget.table)}(${this.quoteIdentifier(e.fkTarget.column)})`);return o.length>0&&r.push(...o),`CREATE TABLE ${this.quoteIdentifier(a)} (
32
32
  ${r.join(`,
33
33
  `)}
34
- );`}},Pe=class{quoteIdentifier(t){return`\`${t}\``}escapeString(t){return t.replace(/'/g,"''")}buildCreateTable(t,a){let r=a.map(e=>{let s="";return e.type==="Integer"&&(s="INT"),e.type==="Text"&&(s="VARCHAR(255)"),e.type==="Boolean"&&(s="BOOLEAN"),e.type==="Decimal"&&(s="DOUBLE"),e.type==="DateTime"&&(s="DATETIME"),e.type==="Enum"&&e.enumValues&&(s=`VARCHAR(255) CHECK(${this.quoteIdentifier(e.name)} IN (${e.enumValues.map(c=>`'${this.escapeString(c)}'`).join(", ")}))`),e.isPk&&e.type==="Integer"?s+=" AUTO_INCREMENT PRIMARY KEY":e.isPk&&(s+=" PRIMARY KEY"),!e.nullable&&!e.isPk&&(s+=" NOT NULL"),e.defaultValue&&e.defaultValue!=="AutoInc"&&!e.defaultValue.startsWith("FK ->")&&(e.defaultValue==="Timestamp"?s+=" DEFAULT CURRENT_TIMESTAMP":s+=` DEFAULT ${e.defaultValue}`),` ${this.quoteIdentifier(e.name)} ${s}`}),o=a.filter(e=>e.fkTarget).map(e=>` FOREIGN KEY (${this.quoteIdentifier(e.name)}) REFERENCES ${this.quoteIdentifier(e.fkTarget.table)}(${this.quoteIdentifier(e.fkTarget.column)})`);return o.length>0&&r.push(...o),`CREATE TABLE ${this.quoteIdentifier(t)} (
34
+ );`}},Pe=class{quoteIdentifier(a){return`\`${a}\``}escapeString(a){return a.replace(/'/g,"''")}buildCreateTable(a,t){let r=t.map(e=>{let s="";return e.type==="Integer"&&(s="INT"),e.type==="Text"&&(s="VARCHAR(255)"),e.type==="Boolean"&&(s="BOOLEAN"),e.type==="Decimal"&&(s="DOUBLE"),e.type==="DateTime"&&(s="DATETIME"),e.type==="Enum"&&e.enumValues&&(s=`VARCHAR(255) CHECK(${this.quoteIdentifier(e.name)} IN (${e.enumValues.map(c=>`'${this.escapeString(c)}'`).join(", ")}))`),e.isPk&&e.type==="Integer"?s+=" AUTO_INCREMENT PRIMARY KEY":e.isPk&&(s+=" PRIMARY KEY"),!e.nullable&&!e.isPk&&(s+=" NOT NULL"),e.defaultValue&&e.defaultValue!=="AutoInc"&&!e.defaultValue.startsWith("FK ->")&&(e.defaultValue==="Timestamp"?s+=" DEFAULT CURRENT_TIMESTAMP":s+=` DEFAULT ${e.defaultValue}`),` ${this.quoteIdentifier(e.name)} ${s}`}),o=t.filter(e=>e.fkTarget).map(e=>` FOREIGN KEY (${this.quoteIdentifier(e.name)}) REFERENCES ${this.quoteIdentifier(e.fkTarget.table)}(${this.quoteIdentifier(e.fkTarget.column)})`);return o.length>0&&r.push(...o),`CREATE TABLE ${this.quoteIdentifier(a)} (
35
35
  ${r.join(`,
36
36
  `)}
37
- );`}}});import S from"picocolors";function ee(n,t,a={}){let{title:r,emptyMessage:o="No records found",maxColWidth:e=30}=a,s={},c=0;for(let f of n){let y=f.length;for(let x of t){let I=String(x[f]??"");I.length>y&&(y=I.length)}let b=Math.max(f.length,Math.min(e,y));s[f]=b,c+=b}let i=3*(n.length-1),l=c+i+4,m=Math.max(74,l),p=m-4-i;if(c<p&&n.length>0){let f=n[n.length-1];s[f]+=p-c}let u=(f,y)=>f.length>y?f.slice(0,y-3)+"...":f,d="\u2550".repeat(m-2);if(console.log(S.cyan(`
38
- \u2554${d}\u2557`)),r){let f=m-2-r.length,y=Math.max(0,Math.floor(f/2)),b=Math.max(0,f-y),x=" ".repeat(y)+S.bold(S.white(r))+" ".repeat(b);console.log(S.cyan("\u2551")+x+S.cyan("\u2551")),console.log(S.cyan(`\u2560${d}\u2563`))}if(n.length>0){let f=n.map(y=>S.bold(S.white(u(y,s[y]).padEnd(s[y])))).join(S.cyan(" \u2551 "));console.log(S.cyan("\u2551 ")+f+S.cyan(" \u2551")),console.log(S.cyan(`\u2560${d}\u2563`))}if(t.length===0){let f=m-4-o.length,y=Math.max(0,Math.floor(f/2)),b=Math.max(0,f-y);console.log(S.cyan("\u2551 ")+" ".repeat(y)+S.yellow(o)+" ".repeat(b)+S.cyan(" \u2551"))}else for(let f of t){let y=n.map(b=>S.white(u(String(f[b]??""),s[b]).padEnd(s[b]))).join(S.cyan(" \u2551 "));console.log(S.cyan("\u2551 ")+y+S.cyan(" \u2551"))}console.log(S.cyan(`\u255A${d}\u255D`))}var ve=E(()=>{"use strict"});var at={};L(at,{runQueryCommand:()=>ga});import ce from"picocolors";async function ga(n,t){n.type==="unknown"&&(console.log(ce.red("Error: No database connection found. Cannot run query.")),process.exit(1));let a=h(n),r=t[0];if(!r){let{input:o}=await import("@inquirer/prompts");r=await o({message:"Enter your SQL query:"})}(!r||r.trim()==="")&&(console.log(ce.yellow("No query provided. Exiting.")),process.exit(0));try{let o=await a.query(r);o.columns.length===0&&(console.log(ce.yellow("Query executed successfully. (No output)")),process.exit(0)),ee(o.columns,o.rows,{title:"Query Result",maxColWidth:50}),console.log(ce.dim(`
39
- (${o.rows.length} rows)`)),await a.close(),process.exit(0)}catch(o){console.log(ce.red(`
37
+ );`}}});import S from"picocolors";function ee(n,a,t={}){let{title:r,emptyMessage:o="No records found",maxColWidth:e=30}=t,s={},c=0;for(let f of n){let y=f.length;for(let x of a){let I=String(x[f]??"");I.length>y&&(y=I.length)}let b=Math.max(f.length,Math.min(e,y));s[f]=b,c+=b}let i=3*(n.length-1),l=c+i+4,m=Math.max(74,l),p=m-4-i;if(c<p&&n.length>0){let f=n[n.length-1];s[f]+=p-c}let u=(f,y)=>f.length>y?f.slice(0,y-3)+"...":f,d="\u2550".repeat(m-2);if(console.log(S.cyan(`
38
+ \u2554${d}\u2557`)),r){let f=m-2-r.length,y=Math.max(0,Math.floor(f/2)),b=Math.max(0,f-y),x=" ".repeat(y)+S.bold(S.white(r))+" ".repeat(b);console.log(S.cyan("\u2551")+x+S.cyan("\u2551")),console.log(S.cyan(`\u2560${d}\u2563`))}if(n.length>0){let f=n.map(y=>S.bold(S.white(u(y,s[y]).padEnd(s[y])))).join(S.cyan(" \u2551 "));console.log(S.cyan("\u2551 ")+f+S.cyan(" \u2551")),console.log(S.cyan(`\u2560${d}\u2563`))}if(a.length===0){let f=m-4-o.length,y=Math.max(0,Math.floor(f/2)),b=Math.max(0,f-y);console.log(S.cyan("\u2551 ")+" ".repeat(y)+S.yellow(o)+" ".repeat(b)+S.cyan(" \u2551"))}else for(let f of a){let y=n.map(b=>S.white(u(String(f[b]??""),s[b]).padEnd(s[b]))).join(S.cyan(" \u2551 "));console.log(S.cyan("\u2551 ")+y+S.cyan(" \u2551"))}console.log(S.cyan(`\u255A${d}\u255D`))}var ve=E(()=>{"use strict"});var at={};L(at,{runQueryCommand:()=>ga});import ce from"picocolors";async function ga(n,a){n.type==="unknown"&&(console.log(ce.red("Error: No database connection found. Cannot run query.")),process.exit(1));let t=h(n),r=a[0];if(!r){let{input:o}=await import("@inquirer/prompts");r=await o({message:"Enter your SQL query:"})}(!r||r.trim()==="")&&(console.log(ce.yellow("No query provided. Exiting.")),process.exit(0));try{let o=await t.query(r);o.columns.length===0&&(console.log(ce.yellow("Query executed successfully. (No output)")),process.exit(0)),ee(o.columns,o.rows,{title:"Query Result",maxColWidth:50}),console.log(ce.dim(`
39
+ (${o.rows.length} rows)`)),await t.close(),process.exit(0)}catch(o){console.log(ce.red(`
40
40
  Query Error: ${o.message}
41
- `)),process.exit(1)}}var ot=E(()=>{"use strict";C();ve()});var nt={};L(nt,{runExportCommand:()=>fa});import U from"picocolors";import me from"fs/promises";import ue from"path";async function fa(n,t,a){n.type==="unknown"&&(console.log(U.red("Error: No database connection found. Cannot run export.")),process.exit(1));let r=h(n),o=t[0],e=a.format,s=a["schema-only"],{select:c}=await import("@inquirer/prompts");if(!o){let m=await r.getTables();m.length===0&&(console.log(U.yellow("No tables found in the database.")),process.exit(0));let p=[{name:"All Tables (*)",value:"*"},...m.map(u=>({name:u,value:u}))];o=await c({message:"Which table do you want to export?",choices:p})}e||(e=await c({message:"Which format do you want to export?",choices:[{name:"CSV",value:"csv"},{name:"JSON",value:"json"}]}));let i=ue.join(process.cwd(),"drixio_exports");await me.mkdir(i,{recursive:!0});let l=o==="*"?await r.getTables():[o];console.log(U.cyan(`
41
+ `)),process.exit(1)}}var ot=E(()=>{"use strict";C();ve()});var nt={};L(nt,{runExportCommand:()=>fa});import U from"picocolors";import me from"fs/promises";import ue from"path";async function fa(n,a,t){n.type==="unknown"&&(console.log(U.red("Error: No database connection found. Cannot run export.")),process.exit(1));let r=h(n),o=a[0],e=t.format,s=t["schema-only"],{select:c}=await import("@inquirer/prompts");if(!o){let m=await r.getTables();m.length===0&&(console.log(U.yellow("No tables found in the database.")),process.exit(0));let p=[{name:"All Tables (*)",value:"*"},...m.map(u=>({name:u,value:u}))];o=await c({message:"Which table do you want to export?",choices:p})}e||(e=await c({message:"Which format do you want to export?",choices:[{name:"CSV",value:"csv"},{name:"JSON",value:"json"}]}));let i=ue.join(process.cwd(),"drixio_exports");await me.mkdir(i,{recursive:!0});let l=o==="*"?await r.getTables():[o];console.log(U.cyan(`
42
42
  Starting export to ${i}...`));for(let m of l)try{if(s){let p=await r.getSchema(m);if(e==="json"){let u=ue.join(i,`${m}_schema.json`);await me.writeFile(u,JSON.stringify(p,null,2),"utf-8"),console.log(U.green(`\u2714 Exported Schema (JSON): ${m}`))}else{let u=ue.join(i,`${m}_schema.csv`),d=`Name,Type,IsPrimaryKey,Nullable
43
43
  `,f=p.map(y=>`"${y.name}","${y.type}","${y.isPk}","${y.nullable}"`).join(`
44
44
  `);await me.writeFile(u,d+f,"utf-8"),console.log(U.green(`\u2714 Exported Schema (CSV): ${m}`))}}else{let p=await r.getData(m,9999999,0);if(e==="json"){let u=ue.join(i,`${m}_data.json`);await me.writeFile(u,JSON.stringify(p.rows,null,2),"utf-8"),console.log(U.green(`\u2714 Exported Data (JSON): ${m} (${p.rows.length} rows)`))}else{let u=ue.join(i,`${m}_data.csv`),d="";if(p.columns.length>0){let f=p.columns.join(",")+`
45
45
  `,y=p.rows.map(b=>p.columns.map(x=>`"${String(b[x]??"").replace(/"/g,'""')}"`).join(",")).join(`
46
- `);d=f+y}await me.writeFile(u,d,"utf-8"),console.log(U.green(`\u2714 Exported Data (CSV): ${m} (${p.rows.length} rows)`))}}}catch(p){console.log(U.red(`\u2718 Failed to export table ${m}: ${p.message}`))}await r.close(),console.log(U.cyan("Export complete.")),process.exit(0)}var st=E(()=>{"use strict";C()});import{Hono as ya}from"hono";function rt(n,t){let a=new ya,r=h(t);a.get("/tables",async o=>{try{let e=await r.getTables();return o.json({success:!0,data:e})}catch(e){return o.json({success:!1,error:e.message},500)}}),a.get("/tables/stats",async o=>{try{let e=await r.getTables(),s={};for(let c of e)try{let i=await r.query(`SELECT COUNT(*) as c FROM "${c}"`);if(i&&i.rows&&i.rows.length>0){let l=i.rows[0],m=Object.values(l)[0];s[c]=parseInt(String(m),10)||0}else s[c]=0}catch{s[c]=0}return o.json({success:!0,data:s})}catch(e){return o.json({success:!1,error:e.message},500)}}),a.get("/tables/:name/schema",async o=>{let e=o.req.param("name");try{let s=await r.getSchema(e);return o.json({success:!0,data:s})}catch(s){return o.json({success:!1,error:s.message},500)}}),a.get("/tables/:name/data",async o=>{let e=o.req.param("name"),s=parseInt(o.req.query("limit")||"50",10),c=parseInt(o.req.query("offset")||"0",10),i=o.req.query("where")||"",l=o.req.query("orderCol"),m=o.req.query("orderAsc"),p;l&&(p={col:l,asc:m!=="false"});try{let u=await r.getData(e,s,c,i,p);return o.json({success:!0,data:u})}catch(u){return o.json({success:!1,error:u.message},500)}}),a.post("/query",async o=>{try{let{sql:e}=await o.req.json(),s=await r.query(e);return o.json({success:!0,data:s})}catch(e){return o.json({success:!1,error:e.message},500)}}),n.route("/api",a)}var it=E(()=>{"use strict";C()});var ct={};L(ct,{runStudio:()=>xa});import{serve as ha}from"@hono/node-server";import{Hono as wa}from"hono";import{serveStatic as ba}from"@hono/node-server/serve-static";import Ea from"open";import pe from"path";import lt from"picocolors";import{fileURLToPath as $a}from"url";async function xa(n){let t=new wa;rt(t,n);let r=Ae.includes("src")||Ae.includes("server")?pe.resolve(Ae,"../../dist/studio"):pe.resolve(Ae,"./studio"),o=await import("fs/promises");t.use("/*",ba({root:pe.relative(process.cwd(),r)})),t.get("*",async s=>{let c=pe.join(r,"index.html");try{let i=await o.readFile(c,"utf-8");return s.html(i)}catch{return s.text("Drixio Studio static files not found. Did you run build?",404)}});let e=3e3;console.log(lt.cyan(`
47
- Starting Drixio Studio on http://localhost:${e}...`)),console.log(lt.dim(`Press Ctrl+C to stop the server.
48
- `)),ha({fetch:t.fetch,port:e}),await Ea(`http://localhost:${e}`)}var Sa,Ae,mt=E(()=>{"use strict";it();Sa=$a(import.meta.url),Ae=pe.dirname(Sa)});var ut={};L(ut,{runBackupCommand:()=>Ta});import k from"picocolors";import ke from"fs/promises";import qe from"path";async function Ta(n){n.type==="unknown"&&(console.log(k.red("Error: No database connection found. Cannot run backup.")),process.exit(1));let t=new Date().toISOString().replace(/[:.]/g,"-"),a=qe.join(process.cwd(),`drixio_backup_${t}`);if(console.log(k.cyan(`
49
- Starting database backup...`)),console.log(k.dim(`Database: ${n.type}`)),console.log(k.dim(`Target: ${n.targetUrl}`)),console.log(k.dim(`Backup Directory: ${a}
50
- `)),await ke.mkdir(a,{recursive:!0}),n.type==="sqlite")try{let o=qe.basename(n.targetUrl)||"database.sqlite",e=qe.join(a,o);await ke.copyFile(n.targetUrl,e),console.log(k.green(`\u2714 Copied raw SQLite file to ${e}`))}catch(o){console.log(k.red(`\u2718 Failed to copy SQLite file: ${o.message}`))}let r=h(n);try{let o=await r.getTables();o.length===0&&console.log(k.yellow("No tables found to backup."));for(let e of o)try{let s=await r.getSchema(e),c=await r.getData(e,9999999,0),i={table:e,schema:s,totalRows:c.rows.length,data:c.rows},l=qe.join(a,`${e}.json`);await ke.writeFile(l,JSON.stringify(i,null,2),"utf-8"),console.log(k.green(`\u2714 Dumped table: ${e} (${c.rows.length} rows)`))}catch(s){console.log(k.red(`\u2718 Failed to dump table ${e}: ${s.message}`))}}catch(o){console.log(k.red(`
46
+ `);d=f+y}await me.writeFile(u,d,"utf-8"),console.log(U.green(`\u2714 Exported Data (CSV): ${m} (${p.rows.length} rows)`))}}}catch(p){console.log(U.red(`\u2718 Failed to export table ${m}: ${p.message}`))}await r.close(),console.log(U.cyan("Export complete.")),process.exit(0)}var st=E(()=>{"use strict";C()});import{Hono as ya}from"hono";function rt(n,a){let t=new ya,r=h(a);t.get("/tables",async o=>{try{let e=await r.getTables();return o.json({success:!0,data:e})}catch(e){return o.json({success:!1,error:e.message},500)}}),t.get("/tables/stats",async o=>{try{let e=await r.getTables(),s={};for(let c of e)try{let i=await r.query(`SELECT COUNT(*) as c FROM "${c}"`);if(i&&i.rows&&i.rows.length>0){let l=i.rows[0],m=Object.values(l)[0];s[c]=parseInt(String(m),10)||0}else s[c]=0}catch{s[c]=0}return o.json({success:!0,data:s})}catch(e){return o.json({success:!1,error:e.message},500)}}),t.get("/tables/:name/schema",async o=>{let e=o.req.param("name");try{let s=await r.getSchema(e);return o.json({success:!0,data:s})}catch(s){return o.json({success:!1,error:s.message},500)}}),t.get("/tables/:name/data",async o=>{let e=o.req.param("name"),s=parseInt(o.req.query("limit")||"50",10),c=parseInt(o.req.query("offset")||"0",10),i=o.req.query("where")||"",l=o.req.query("orderCol"),m=o.req.query("orderAsc"),p;l&&(p={col:l,asc:m!=="false"});try{let u=await r.getData(e,s,c,i,p);return o.json({success:!0,data:u})}catch(u){return o.json({success:!1,error:u.message},500)}}),t.post("/query",async o=>{try{let{sql:e}=await o.req.json(),s=await r.query(e);return o.json({success:!0,data:s})}catch(e){return o.json({success:!1,error:e.message},500)}}),n.route("/api",t)}var it=E(()=>{"use strict";C()});var ct={};L(ct,{runStudio:()=>xa});import{serve as ha}from"@hono/node-server";import{Hono as wa}from"hono";import{serveStatic as ba}from"@hono/node-server/serve-static";import Ea from"open";import pe from"path";import lt from"picocolors";import{fileURLToPath as $a}from"url";async function xa(n){let a=new wa;rt(a,n);let r=Ae.includes("src")||Ae.includes("server")?pe.resolve(Ae,"../../dist/studio"):pe.resolve(Ae,"./studio"),o=await import("fs/promises");a.use("/*",ba({root:pe.relative(process.cwd(),r)})),a.get("*",async c=>{let i=pe.join(r,"index.html");try{let l=await o.readFile(i,"utf-8");return c.html(l)}catch{return c.text("Drixio Studio static files not found. Did you run build?",404)}});let e=process.env.PORT?parseInt(process.env.PORT,10):51213,s=await Ta(e);console.log(lt.cyan(`
47
+ Starting Drixio Studio on http://localhost:${s}...`)),console.log(lt.dim(`Press Ctrl+C to stop the server.
48
+ `)),ha({fetch:a.fetch,port:s}),await Ea(`http://localhost:${s}`)}async function Ta(n){let a=await import("net"),t=n;for(;;){if(await new Promise(o=>{let e=a.createServer();e.unref(),e.on("error",()=>o(!1)),e.listen(t,()=>{e.close(()=>o(!0))})}))return t;t++}}var Sa,Ae,mt=E(()=>{"use strict";it();Sa=$a(import.meta.url),Ae=pe.dirname(Sa)});var ut={};L(ut,{runBackupCommand:()=>Da});import k from"picocolors";import ke from"fs/promises";import qe from"path";async function Da(n){n.type==="unknown"&&(console.log(k.red("Error: No database connection found. Cannot run backup.")),process.exit(1));let a=new Date().toISOString().replace(/[:.]/g,"-"),t=qe.join(process.cwd(),`drixio_backup_${a}`);if(console.log(k.cyan(`
49
+ Starting database backup...`)),console.log(k.dim(`Database: ${n.type}`)),console.log(k.dim(`Target: ${n.targetUrl}`)),console.log(k.dim(`Backup Directory: ${t}
50
+ `)),await ke.mkdir(t,{recursive:!0}),n.type==="sqlite")try{let o=qe.basename(n.targetUrl)||"database.sqlite",e=qe.join(t,o);await ke.copyFile(n.targetUrl,e),console.log(k.green(`\u2714 Copied raw SQLite file to ${e}`))}catch(o){console.log(k.red(`\u2718 Failed to copy SQLite file: ${o.message}`))}let r=h(n);try{let o=await r.getTables();o.length===0&&console.log(k.yellow("No tables found to backup."));for(let e of o)try{let s=await r.getSchema(e),c=await r.getData(e,9999999,0),i={table:e,schema:s,totalRows:c.rows.length,data:c.rows},l=qe.join(t,`${e}.json`);await ke.writeFile(l,JSON.stringify(i,null,2),"utf-8"),console.log(k.green(`\u2714 Dumped table: ${e} (${c.rows.length} rows)`))}catch(s){console.log(k.red(`\u2718 Failed to dump table ${e}: ${s.message}`))}}catch(o){console.log(k.red(`
51
51
  Backup Error: ${o.message}`))}finally{await r.close()}console.log(k.cyan(`
52
- Backup successfully completed at ${a}`)),process.exit(0)}var pt=E(()=>{"use strict";C()});var gt={};L(gt,{runImportCommand:()=>va});import M from"picocolors";import dt from"fs/promises";import Da from"path";function Ca(n){let t=n.split(/\r?\n/).filter(e=>e.trim()!=="");if(t.length===0)return[];let a=e=>{let s=[],c="",i=!1;for(let l=0;l<e.length;l++){let m=e[l];m==='"'&&e[l+1]==='"'?(c+='"',l++):m==='"'?i=!i:m===","&&!i?(s.push(c),c=""):c+=m}return s.push(c),s},r=a(t[0]),o=[];for(let e=1;e<t.length;e++){let s=a(t[e]),c={};r.forEach((i,l)=>{c[i]=s[l]??""}),o.push(c)}return o}async function va(n,t,a){n.type==="unknown"&&(console.log(M.red("Error: No database connection found. Cannot run import.")),process.exit(1));let r=h(n),o=t[0],e=a.table,{input:s,select:c}=await import("@inquirer/prompts");o||(o=await s({message:"Enter the path to your CSV or JSON file:"}));let i=Da.resolve(process.cwd(),o);try{await dt.access(i)}catch{console.log(M.red(`Error: File not found at ${i}`)),process.exit(1)}if(!e){let d=await r.getTables();d.length===0&&(console.log(M.yellow("No tables found. Please create a table first.")),process.exit(1)),e=await c({message:"Which table do you want to import data into?",choices:d.map(f=>({name:f,value:f}))})}console.log(M.cyan(`
53
- Reading file...`));let l=await dt.readFile(i,"utf-8"),m=[];if(o.toLowerCase().endsWith(".json"))try{if(m=JSON.parse(l),!Array.isArray(m))throw new Error("JSON root must be an array of objects.")}catch(d){console.log(M.red(`Invalid JSON format: ${d.message}`)),process.exit(1)}else o.toLowerCase().endsWith(".csv")?m=Ca(l):(console.log(M.red("Error: Unsupported file extension. Please provide a .csv or .json file.")),process.exit(1));m.length===0&&(console.log(M.yellow("No data found to import.")),process.exit(0)),console.log(M.cyan(`Importing ${m.length} rows into '${e}'...`));let p=500,u=0;try{for(let d=0;d<m.length;d+=p){let f=m.slice(d,d+p);await r.insert(e,f),u+=f.length,process.stdout.write(`\r${M.dim(`Progress: ${u} / ${m.length}`)}`)}console.log(M.green(`
52
+ Backup successfully completed at ${t}`)),process.exit(0)}var pt=E(()=>{"use strict";C()});var gt={};L(gt,{runImportCommand:()=>Aa});import M from"picocolors";import dt from"fs/promises";import Ca from"path";function va(n){let a=n.split(/\r?\n/).filter(e=>e.trim()!=="");if(a.length===0)return[];let t=e=>{let s=[],c="",i=!1;for(let l=0;l<e.length;l++){let m=e[l];m==='"'&&e[l+1]==='"'?(c+='"',l++):m==='"'?i=!i:m===","&&!i?(s.push(c),c=""):c+=m}return s.push(c),s},r=t(a[0]),o=[];for(let e=1;e<a.length;e++){let s=t(a[e]),c={};r.forEach((i,l)=>{c[i]=s[l]??""}),o.push(c)}return o}async function Aa(n,a,t){n.type==="unknown"&&(console.log(M.red("Error: No database connection found. Cannot run import.")),process.exit(1));let r=h(n),o=a[0],e=t.table,{input:s,select:c}=await import("@inquirer/prompts");o||(o=await s({message:"Enter the path to your CSV or JSON file:"}));let i=Ca.resolve(process.cwd(),o);try{await dt.access(i)}catch{console.log(M.red(`Error: File not found at ${i}`)),process.exit(1)}if(!e){let d=await r.getTables();d.length===0&&(console.log(M.yellow("No tables found. Please create a table first.")),process.exit(1)),e=await c({message:"Which table do you want to import data into?",choices:d.map(f=>({name:f,value:f}))})}console.log(M.cyan(`
53
+ Reading file...`));let l=await dt.readFile(i,"utf-8"),m=[];if(o.toLowerCase().endsWith(".json"))try{if(m=JSON.parse(l),!Array.isArray(m))throw new Error("JSON root must be an array of objects.")}catch(d){console.log(M.red(`Invalid JSON format: ${d.message}`)),process.exit(1)}else o.toLowerCase().endsWith(".csv")?m=va(l):(console.log(M.red("Error: Unsupported file extension. Please provide a .csv or .json file.")),process.exit(1));m.length===0&&(console.log(M.yellow("No data found to import.")),process.exit(0)),console.log(M.cyan(`Importing ${m.length} rows into '${e}'...`));let p=500,u=0;try{for(let d=0;d<m.length;d+=p){let f=m.slice(d,d+p);await r.insert(e,f),u+=f.length,process.stdout.write(`\r${M.dim(`Progress: ${u} / ${m.length}`)}`)}console.log(M.green(`
54
54
 
55
55
  \u2714 Successfully imported ${u} rows into ${e}!`))}catch(d){console.log(M.red(`
56
- \u2718 Import failed at row ${u}: ${d.message}`))}finally{await r.close()}process.exit(0)}var ft=E(()=>{"use strict";C()});var yt={};L(yt,{runSeedCommand:()=>Ra});import O from"picocolors";function de(n){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",a="";for(let r=0;r<n;r++)a+=t.charAt(Math.floor(Math.random()*t.length));return a}function Aa(){let n=["gmail.com","yahoo.com","outlook.com","example.com"],t=de(8).toLowerCase(),a=n[Math.floor(Math.random()*n.length)];return`${t}@${a}`}function qa(n){let t=n.name.toLowerCase();if(t.includes("email"))return Aa();if(t.includes("phone"))return`+1${Math.floor(Math.random()*9e9+1e9)}`;if(t.includes("name"))return`User_${de(5)}`;if(t.includes("url")||t.includes("link"))return`https://example.com/${de(6)}`;if(t.includes("date")||t.includes("time")||t.includes("created")||t.includes("updated"))return new Date(Date.now()-Math.floor(Math.random()*1e10)).toISOString().replace("T"," ").slice(0,19);let a=n.type.toLowerCase();return a.includes("int")||a.includes("num")||a.includes("float")||a.includes("double")?Math.floor(Math.random()*1e3):a.includes("bool")||a==="tinyint(1)"?Math.random()>.5:a.includes("char")||a.includes("text")||a.includes("string")?de(10):de(5)}async function Ra(n,t){n.type==="unknown"&&(console.log(O.red("Error: No database connection found. Cannot run seed.")),process.exit(1));let a=h(n),r=t[0],o=t[1],{input:e,select:s}=await import("@inquirer/prompts");if(!r){let d=await a.getTables();d.length===0&&(console.log(O.yellow("No tables found. Please create a table first.")),process.exit(1)),r=await s({message:"Which table do you want to seed with fake data?",choices:d.map(f=>({name:f,value:f}))})}let c=parseInt(o);if(isNaN(c)||c<=0){let d=await e({message:"How many rows to generate?",default:"50"});c=parseInt(d),(isNaN(c)||c<=0)&&(console.log(O.red("Error: Invalid count number.")),process.exit(1))}console.log(O.cyan(`
57
- Analyzing schema for table '${r}'...`));let i;try{i=await a.getSchema(r)}catch(d){console.log(O.red(`Error: ${d.message}`)),process.exit(1)}let l=i.filter(d=>!d.isPk);l.length===0&&console.log(O.yellow("Table only has Primary Key columns. Seeding might fail if they don't auto-increment.")),console.log(O.cyan(`Generating ${c} records...`));let m=[];for(let d=0;d<c;d++){let f={};for(let y of l.length>0?l:i)f[y.name]=qa(y);m.push(f)}let p=500,u=0;try{n.type==="sqlite"?await a.executeSql("PRAGMA foreign_keys = OFF;"):n.type==="mysql"?await a.executeSql("SET FOREIGN_KEY_CHECKS = 0;"):n.type==="postgres"&&await a.executeSql("SET session_replication_role = replica;");for(let d=0;d<m.length;d+=p){let f=m.slice(d,d+p);await a.insert(r,f),u+=f.length,process.stdout.write(`\r${O.dim(`Progress: ${u} / ${c}`)}`)}console.log(O.green(`
56
+ \u2718 Import failed at row ${u}: ${d.message}`))}finally{await r.close()}process.exit(0)}var ft=E(()=>{"use strict";C()});var yt={};L(yt,{runSeedCommand:()=>La});import O from"picocolors";function de(n){let a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let r=0;r<n;r++)t+=a.charAt(Math.floor(Math.random()*a.length));return t}function qa(){let n=["gmail.com","yahoo.com","outlook.com","example.com"],a=de(8).toLowerCase(),t=n[Math.floor(Math.random()*n.length)];return`${a}@${t}`}function Ra(n){let a=n.name.toLowerCase();if(a.includes("email"))return qa();if(a.includes("phone"))return`+1${Math.floor(Math.random()*9e9+1e9)}`;if(a.includes("name"))return`User_${de(5)}`;if(a.includes("url")||a.includes("link"))return`https://example.com/${de(6)}`;if(a.includes("date")||a.includes("time")||a.includes("created")||a.includes("updated"))return new Date(Date.now()-Math.floor(Math.random()*1e10)).toISOString().replace("T"," ").slice(0,19);let t=n.type.toLowerCase();return t.includes("int")||t.includes("num")||t.includes("float")||t.includes("double")?Math.floor(Math.random()*1e3):t.includes("bool")||t==="tinyint(1)"?Math.random()>.5:t.includes("char")||t.includes("text")||t.includes("string")?de(10):de(5)}async function La(n,a){n.type==="unknown"&&(console.log(O.red("Error: No database connection found. Cannot run seed.")),process.exit(1));let t=h(n),r=a[0],o=a[1],{input:e,select:s}=await import("@inquirer/prompts");if(!r){let d=await t.getTables();d.length===0&&(console.log(O.yellow("No tables found. Please create a table first.")),process.exit(1)),r=await s({message:"Which table do you want to seed with fake data?",choices:d.map(f=>({name:f,value:f}))})}let c=parseInt(o);if(isNaN(c)||c<=0){let d=await e({message:"How many rows to generate?",default:"50"});c=parseInt(d),(isNaN(c)||c<=0)&&(console.log(O.red("Error: Invalid count number.")),process.exit(1))}console.log(O.cyan(`
57
+ Analyzing schema for table '${r}'...`));let i;try{i=await t.getSchema(r)}catch(d){console.log(O.red(`Error: ${d.message}`)),process.exit(1)}let l=i.filter(d=>!d.isPk);l.length===0&&console.log(O.yellow("Table only has Primary Key columns. Seeding might fail if they don't auto-increment.")),console.log(O.cyan(`Generating ${c} records...`));let m=[];for(let d=0;d<c;d++){let f={};for(let y of l.length>0?l:i)f[y.name]=Ra(y);m.push(f)}let p=500,u=0;try{n.type==="sqlite"?await t.executeSql("PRAGMA foreign_keys = OFF;"):n.type==="mysql"?await t.executeSql("SET FOREIGN_KEY_CHECKS = 0;"):n.type==="postgres"&&await t.executeSql("SET session_replication_role = replica;");for(let d=0;d<m.length;d+=p){let f=m.slice(d,d+p);await t.insert(r,f),u+=f.length,process.stdout.write(`\r${O.dim(`Progress: ${u} / ${c}`)}`)}console.log(O.green(`
58
58
 
59
59
  \u2714 Successfully seeded ${u} fake records into ${r}!`))}catch(d){console.log(O.red(`
60
- \u2718 Seed failed: ${d.message}`))}finally{try{n.type==="sqlite"?await a.executeSql("PRAGMA foreign_keys = ON;"):n.type==="mysql"?await a.executeSql("SET FOREIGN_KEY_CHECKS = 1;"):n.type==="postgres"&&await a.executeSql("SET session_replication_role = DEFAULT;")}catch{}await a.close()}process.exit(0)}var ht=E(()=>{"use strict";C()});var wt={};L(wt,{runDiagramCommand:()=>ka});import V from"picocolors";import La from"fs/promises";import Pa from"path";async function ka(n){n.type==="unknown"&&(console.log(V.red("Error: No database connection found. Cannot generate diagram.")),process.exit(1));let t=h(n);console.log(V.cyan(`
61
- Scanning database to generate ER diagram...`));try{let a=await t.getTables();a.length===0&&(console.log(V.yellow("No tables found in the database.")),process.exit(0));let r=`erDiagram
62
- `;for(let s of a){r+=` ${s} {
63
- `;let c=await t.getSchema(s);for(let i of c){let l=i.type.replace(/\s+/g,"_").replace(/[^a-zA-Z0-9_]/g,""),m=i.isPk?" PK":"";r+=` ${l} ${i.name}${m}
60
+ \u2718 Seed failed: ${d.message}`))}finally{try{n.type==="sqlite"?await t.executeSql("PRAGMA foreign_keys = ON;"):n.type==="mysql"?await t.executeSql("SET FOREIGN_KEY_CHECKS = 1;"):n.type==="postgres"&&await t.executeSql("SET session_replication_role = DEFAULT;")}catch{}await t.close()}process.exit(0)}var ht=E(()=>{"use strict";C()});var wt={};L(wt,{runDiagramCommand:()=>Ia});import V from"picocolors";import Pa from"fs/promises";import ka from"path";async function Ia(n){n.type==="unknown"&&(console.log(V.red("Error: No database connection found. Cannot generate diagram.")),process.exit(1));let a=h(n);console.log(V.cyan(`
61
+ Scanning database to generate ER diagram...`));try{let t=await a.getTables();t.length===0&&(console.log(V.yellow("No tables found in the database.")),process.exit(0));let r=`erDiagram
62
+ `;for(let s of t){r+=` ${s} {
63
+ `;let c=await a.getSchema(s);for(let i of c){let l=i.type.replace(/\s+/g,"_").replace(/[^a-zA-Z0-9_]/g,""),m=i.isPk?" PK":"";r+=` ${l} ${i.name}${m}
64
64
  `}r+=` }
65
65
  `}let o=`
66
66
  # Database Schema Diagram
@@ -70,92 +70,92 @@ You can paste this Mermaid code directly into [Draw.io](https://app.diagrams.net
70
70
  \`\`\`mermaid
71
71
  ${r}
72
72
  \`\`\`
73
- `,e=Pa.resolve(process.cwd(),"drixio_schema.md");await La.writeFile(e,o.trim(),"utf-8"),console.log(V.green(`
74
- \u2714 Diagram generated successfully!`)),console.log(V.white(`Output saved to: ${V.bold(e)}`)),console.log(V.dim("Tip: Open this file in VSCode with a Markdown viewer or paste it into Draw.io."))}catch(a){console.log(V.red(`
75
- \u2718 Failed to generate diagram: ${a.message}`))}finally{await t.close()}process.exit(0)}var bt=E(()=>{"use strict";C()});var $t={};L($t,{runExecCommand:()=>Na});import oe from"picocolors";import Et from"fs/promises";import Ia from"path";async function Na(n,t){n.type==="unknown"&&(console.log(oe.red("Error: No database connection found. Cannot run exec.")),process.exit(1));let a=t[0],{input:r}=await import("@inquirer/prompts");a||(a=await r({message:"Enter the path to your .sql file:"}));let o=Ia.resolve(process.cwd(),a);try{await Et.access(o)}catch{console.log(oe.red(`Error: File not found at ${o}`)),process.exit(1)}let e=await Et.readFile(o,"utf-8");e.trim()||(console.log(oe.yellow("File is empty.")),process.exit(0));let s=h(n);console.log(oe.cyan(`
76
- Executing SQL script from ${a}...`));try{await s.executeSql(e),console.log(oe.green("\u2714 Script executed successfully!"))}catch(c){console.log(oe.red(`\u2718 Execution failed: ${c.message}`))}finally{await s.close()}process.exit(0)}var St=E(()=>{"use strict";C()});var xt={};L(xt,{runGenerateTypesCommand:()=>_a});import H from"picocolors";import Ba from"fs/promises";import Ma from"path";function Oa(n){let t=n.toLowerCase();return t.includes("int")||t.includes("num")||t.includes("float")||t.includes("double")||t.includes("real")?"number":t.includes("bool")||t==="tinyint(1)"?"boolean":t.includes("char")||t.includes("text")||t.includes("uuid")||t.includes("string")?"string":t.includes("date")||t.includes("time")?"Date":t.includes("json")?"any":"string"}async function _a(n){n.type==="unknown"&&(console.log(H.red("Error: No database connection found. Cannot generate types.")),process.exit(1));let t=h(n);console.log(H.cyan(`
77
- Scanning database to generate TypeScript interfaces...`));try{let a=await t.getTables();a.length===0&&(console.log(H.yellow("No tables found in the database.")),process.exit(0));let r=`// Generated by Drixio CLI
73
+ `,e=ka.resolve(process.cwd(),"drixio_schema.md");await Pa.writeFile(e,o.trim(),"utf-8"),console.log(V.green(`
74
+ \u2714 Diagram generated successfully!`)),console.log(V.white(`Output saved to: ${V.bold(e)}`)),console.log(V.dim("Tip: Open this file in VSCode with a Markdown viewer or paste it into Draw.io."))}catch(t){console.log(V.red(`
75
+ \u2718 Failed to generate diagram: ${t.message}`))}finally{await a.close()}process.exit(0)}var bt=E(()=>{"use strict";C()});var $t={};L($t,{runExecCommand:()=>Ba});import oe from"picocolors";import Et from"fs/promises";import Na from"path";async function Ba(n,a){n.type==="unknown"&&(console.log(oe.red("Error: No database connection found. Cannot run exec.")),process.exit(1));let t=a[0],{input:r}=await import("@inquirer/prompts");t||(t=await r({message:"Enter the path to your .sql file:"}));let o=Na.resolve(process.cwd(),t);try{await Et.access(o)}catch{console.log(oe.red(`Error: File not found at ${o}`)),process.exit(1)}let e=await Et.readFile(o,"utf-8");e.trim()||(console.log(oe.yellow("File is empty.")),process.exit(0));let s=h(n);console.log(oe.cyan(`
76
+ Executing SQL script from ${t}...`));try{await s.executeSql(e),console.log(oe.green("\u2714 Script executed successfully!"))}catch(c){console.log(oe.red(`\u2718 Execution failed: ${c.message}`))}finally{await s.close()}process.exit(0)}var St=E(()=>{"use strict";C()});var xt={};L(xt,{runGenerateTypesCommand:()=>Fa});import H from"picocolors";import Ma from"fs/promises";import Oa from"path";function _a(n){let a=n.toLowerCase();return a.includes("int")||a.includes("num")||a.includes("float")||a.includes("double")||a.includes("real")?"number":a.includes("bool")||a==="tinyint(1)"?"boolean":a.includes("char")||a.includes("text")||a.includes("uuid")||a.includes("string")?"string":a.includes("date")||a.includes("time")?"Date":a.includes("json")?"any":"string"}async function Fa(n){n.type==="unknown"&&(console.log(H.red("Error: No database connection found. Cannot generate types.")),process.exit(1));let a=h(n);console.log(H.cyan(`
77
+ Scanning database to generate TypeScript interfaces...`));try{let t=await a.getTables();t.length===0&&(console.log(H.yellow("No tables found in the database.")),process.exit(0));let r=`// Generated by Drixio CLI
78
78
  // Database: ${n.type.toUpperCase()}
79
79
 
80
- `;for(let e of a){let s=e.charAt(0).toUpperCase()+e.slice(1).replace(/_([a-z])/g,i=>i[1].toUpperCase());r+=`export interface ${s} {
81
- `;let c=await t.getSchema(e);for(let i of c){let l=Oa(i.type),m=i.nullable?"?":"";r+=` ${i.name}${m}: ${l};
80
+ `;for(let e of t){let s=e.charAt(0).toUpperCase()+e.slice(1).replace(/_([a-z])/g,i=>i[1].toUpperCase());r+=`export interface ${s} {
81
+ `;let c=await a.getSchema(e);for(let i of c){let l=_a(i.type),m=i.nullable?"?":"";r+=` ${i.name}${m}: ${l};
82
82
  `}r+=`}
83
83
 
84
- `}let o=Ma.resolve(process.cwd(),"drixio-types.d.ts");await Ba.writeFile(o,r.trim()+`
85
- `,"utf-8"),console.log(H.green("\u2714 TypeScript interfaces generated successfully!")),console.log(H.white(`Output saved to: ${H.bold(o)}`))}catch(a){console.log(H.red(`
86
- \u2718 Failed to generate types: ${a.message}`))}finally{await t.close()}process.exit(0)}var Tt=E(()=>{"use strict";C()});var Ct={};L(Ct,{runInitCommand:()=>Fa});import $ from"picocolors";import Re from"fs/promises";import Dt from"path";async function Fa(n){let{select:t,input:a,password:r}=await import("@inquirer/prompts"),o=n[0];(!o||!["sqlite","mysql","postgres"].includes(o.toLowerCase()))&&(o=await t({message:"Which database do you want to initialize locally?",choices:[{name:"SQLite (Local File)",value:"sqlite"},{name:"MySQL (Local Server)",value:"mysql"},{name:"PostgreSQL (Local Server)",value:"postgres"}]})),o=o.toLowerCase(),console.log($.cyan(`
87
- Initializing a local ${o} database...`));let e="";if(o==="sqlite"){let i=n[1]||"database.sqlite";!i.endsWith(".sqlite")&&!i.endsWith(".db")&&(i+=".sqlite");let l=Dt.resolve(process.cwd(),i);try{await Re.access(l),console.log($.yellow(`File ${i} already exists.`))}catch{await Re.writeFile(l,""),console.log($.green(`\u2714 Created local database file: ${i}`))}e=`file:${i}`}else{console.log($.dim("Please provide credentials for your local server (e.g. running via XAMPP, Homebrew, etc.)"));let i=await a({message:"Server Host:",default:"localhost"}),l=await a({message:"Server Port:",default:o==="mysql"?"3306":"5432"}),m=await a({message:"Username:",default:o==="mysql"?"root":"postgres"}),p=await r({message:"Password (leave empty if none):"}),u=n[1];u||(u=await a({message:"New Database Name (e.g. my_project):"})),(!u||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u))&&(console.log($.red("Invalid database name. Please use only letters, numbers, and underscores.")),process.exit(1)),console.log($.cyan(`
84
+ `}let o=Oa.resolve(process.cwd(),"drixio-types.d.ts");await Ma.writeFile(o,r.trim()+`
85
+ `,"utf-8"),console.log(H.green("\u2714 TypeScript interfaces generated successfully!")),console.log(H.white(`Output saved to: ${H.bold(o)}`))}catch(t){console.log(H.red(`
86
+ \u2718 Failed to generate types: ${t.message}`))}finally{await a.close()}process.exit(0)}var Tt=E(()=>{"use strict";C()});var Ct={};L(Ct,{runInitCommand:()=>Ua});import $ from"picocolors";import Re from"fs/promises";import Dt from"path";async function Ua(n){let{select:a,input:t,password:r}=await import("@inquirer/prompts"),o=n[0];(!o||!["sqlite","mysql","postgres"].includes(o.toLowerCase()))&&(o=await a({message:"Which database do you want to initialize locally?",choices:[{name:"SQLite (Local File)",value:"sqlite"},{name:"MySQL (Local Server)",value:"mysql"},{name:"PostgreSQL (Local Server)",value:"postgres"}]})),o=o.toLowerCase(),console.log($.cyan(`
87
+ Initializing a local ${o} database...`));let e="";if(o==="sqlite"){let i=n[1]||"database.sqlite";!i.endsWith(".sqlite")&&!i.endsWith(".db")&&(i+=".sqlite");let l=Dt.resolve(process.cwd(),i);try{await Re.access(l),console.log($.yellow(`File ${i} already exists.`))}catch{await Re.writeFile(l,""),console.log($.green(`\u2714 Created local database file: ${i}`))}e=`file:${i}`}else{console.log($.dim("Please provide credentials for your local server (e.g. running via XAMPP, Homebrew, etc.)"));let i=await t({message:"Server Host:",default:"localhost"}),l=await t({message:"Server Port:",default:o==="mysql"?"3306":"5432"}),m=await t({message:"Username:",default:o==="mysql"?"root":"postgres"}),p=await r({message:"Password (leave empty if none):"}),u=n[1];u||(u=await t({message:"New Database Name (e.g. my_project):"})),(!u||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u))&&(console.log($.red("Invalid database name. Please use only letters, numbers, and underscores.")),process.exit(1)),console.log($.cyan(`
88
88
  Connecting to local server to create database '${u}'...`));try{if(o==="mysql"){let b=await(await import("mysql2/promise")).createConnection({host:i,port:parseInt(l),user:m,password:p});await b.query(`CREATE DATABASE IF NOT EXISTS \`${u}\``),await b.end()}else if(o==="postgres"){let y=await import("pg"),b=new y.Client({host:i,port:parseInt(l),user:m,password:p,database:"postgres"});await b.connect(),(await b.query("SELECT 1 FROM pg_database WHERE datname = $1",[u])).rowCount===0&&await b.query(`CREATE DATABASE "${u}"`),await b.end()}console.log($.green(`\u2714 Created local database: ${u}`))}catch(y){console.log($.red(`\u2718 Failed to create database on server: ${y.message}`)),console.log($.dim(`
89
89
  Could not connect to the local ${o} server on ${i}:${l}.`)),(y.code==="ECONNREFUSED"||y.message.includes("ECONNREFUSED")||y.message.includes("connect"))&&(console.log($.yellow(`
90
90
  \u{1F4A1} It seems you don't have ${o} installed or running locally.`)),o==="mysql"?console.log($.white(`\u{1F449} Download MySQL here: ${$.cyan("https://dev.mysql.com/downloads/installer/")}`)):o==="postgres"&&(console.log($.white(`\u{1F449} Download PostgreSQL here: ${$.cyan("https://www.postgresql.org/download/")}`)),console.log($.white(`\u{1F449} Or use Postgres.app for Mac: ${$.cyan("https://postgresapp.com/")}`))),console.log($.dim("(Alternatively, you can run 'drixio init sqlite' for a zero-install local database!)"))),process.exit(1)}let d=o==="postgres"?"postgres://":"mysql://",f=p?`${m}:${p}`:`${m}`;e=`${d}${f}@${i}:${l}/${u}`}let s=Dt.resolve(process.cwd(),".env"),c="";try{c=await Re.readFile(s,"utf-8")}catch{}c.includes("DATABASE_URL=")?(c=c.replace(/DATABASE_URL=.*/g,`DATABASE_URL=${e}`),console.log($.yellow("\u2714 Updated existing .env file with new DATABASE_URL"))):(c+=(c.endsWith(`
91
91
  `)||c.length===0?"":`
92
92
  `)+`DATABASE_URL=${e}
93
93
  `,console.log($.green("\u2714 Saved connection string to .env file"))),await Re.writeFile(s,c,"utf-8"),console.log($.green(`
94
- \u{1F389} Initialization Complete!`)),console.log($.white(`You can now run ${$.bold("npx drixio")} to manage it!`)),process.exit(0)}var vt=E(()=>{"use strict"});var At={};L(At,{runDropDbCommand:()=>ja});import Q from"picocolors";import Ua from"fs/promises";import Wa from"path";async function ja(n){let{select:t,input:a,password:r,confirm:o}=await import("@inquirer/prompts"),e=n[0];(!e||!["sqlite","mysql","postgres"].includes(e.toLowerCase()))&&(e=await t({message:"Which database type do you want to drop?",choices:[{name:"SQLite (Local File)",value:"sqlite"},{name:"MySQL (Local Server)",value:"mysql"},{name:"PostgreSQL (Local Server)",value:"postgres"}]})),e=e.toLowerCase();let s=n[1];if(e==="sqlite"){s||(s=await a({message:"Enter the SQLite filename to delete (e.g. database.sqlite):",default:"database.sqlite"})),!s.endsWith(".sqlite")&&!s.endsWith(".db")&&(s+=".sqlite"),await o({message:`Are you absolutely sure you want to delete ${s}? This cannot be undone!`,default:!1})||(console.log(Q.yellow("Aborted.")),process.exit(0));let i=Wa.resolve(process.cwd(),s);try{await Ua.unlink(i),console.log(Q.green(`\u2714 Deleted local database file: ${s}`))}catch(l){console.log(Q.red(`\u2718 Failed to delete file: ${l.message}`))}}else{console.log(Q.dim(`Please provide credentials for your local ${e} server to drop a database.`));let c=await a({message:"Server Host:",default:"localhost"}),i=await a({message:"Server Port:",default:e==="mysql"?"3306":"5432"}),l=await a({message:"Username:",default:e==="mysql"?"root":"postgres"}),m=await r({message:"Password (leave empty if none):"});s||(s=await a({message:"Which Database Name do you want to DROP?"})),await o({message:`Are you absolutely sure you want to DROP DATABASE '${s}' from ${c}? All data will be lost!`,default:!1})||(console.log(Q.yellow("Aborted.")),process.exit(0)),console.log(Q.cyan(`
95
- Connecting to local server to drop database '${s}'...`));try{if(e==="mysql"){let d=await(await import("mysql2/promise")).createConnection({host:c,port:parseInt(i),user:l,password:m});await d.query(`DROP DATABASE IF EXISTS \`${s}\``),await d.end()}else if(e==="postgres"){let u=await import("pg"),d=new u.Client({host:c,port:parseInt(i),user:l,password:m,database:"postgres"});await d.connect(),await d.query(`DROP DATABASE IF EXISTS "${s}"`),await d.end()}console.log(Q.green(`\u2714 Dropped database: ${s}`))}catch(u){console.log(Q.red(`\u2718 Failed to drop database on server: ${u.message}`)),process.exit(1)}}process.exit(0)}var qt=E(()=>{"use strict"});import{select as Va,Separator as Qa}from"@inquirer/prompts";import Y from"picocolors";var Rt,Lt=E(()=>{"use strict";Rt=async()=>await Va({message:"Table Manager - Choose an action:",theme:{prefix:Y.cyan("\u2713 "),icon:{cursor:Y.cyan("\u203A ")},style:{message:n=>Y.bold(Y.white(n)),highlight:n=>{let t=n.replace(/\x1b\[[0-9;]*m/g,"");return t.includes(" Back")?Y.red(t):Y.cyan(t)}}},choices:[{name:" Create New Table",value:"create",description:"Build a new database table."},{name:" Modify Existing Table",value:"modify",description:"Modify an existing table's schema structure."},{name:" Drop Table",value:"drop",description:"Delete an entire table and its data."},new Qa,{name:Y.dim(" Back"),value:"back",description:"Back to the main menu."}]})});import{input as Ie,select as ne,confirm as Pt}from"@inquirer/prompts";import ge from"picocolors";async function fe(n,t,a=[],r=""){let o="";for(;!o;){if(o=await Ie({message:"Column name (leave empty to cancel/finish):",default:r}),!o.trim())return{col:null,isPk:!1};/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)?a.includes(o)&&(console.log(ge.red("Column name already exists!")),o=""):(console.log(ge.red("Invalid column name. Use only letters, numbers, and underscores.")),o="")}let e=await ne({message:`Select type for column '${o}':`,choices:[{name:"Integer",value:"Integer"},{name:"Text (String)",value:"Text"},{name:"Boolean",value:"Boolean"},{name:"Decimal (Float)",value:"Decimal"},{name:"DateTime",value:"DateTime"},{name:"Enum",value:"Enum"}]}),s;e==="Enum"&&(s=(await Ie({message:"Enter comma-separated Enum values (e.g. active, pending, deleted):"})).split(",").map(d=>d.trim()).filter(d=>d),s.length===0&&console.log(ge.yellow("Warning: No enum values provided.")));let c="";e==="DateTime"&&await Pt({message:"Set default to CURRENT_TIMESTAMP?",default:!1})&&(c="Timestamp");let i=!1,l;if(e!=="DateTime"){let u=[{name:"None",value:"none"}];t||u.push({name:"Primary Key",value:"pk"}),u.push({name:"Foreign Key",value:"fk"});let d=await ne({message:`Key type for '${o}':`,choices:u});if(d==="pk")i=!0,e==="Integer"&&(c="AutoInc");else if(d==="fk"){let f=await n.getTables();if(f.length>0){let y=await ne({message:"Select target table:",choices:f.map(x=>({name:x,value:x}))}),b=await n.getSchema(y);if(b.length>0){let x=await ne({message:"Select target column:",choices:b.map(I=>({name:`${I.name} (${I.type})`,value:I.name}))});l={table:y,column:x},c=`FK -> ${y}.${x}`}else console.log(ge.yellow("Target table has no columns."))}else console.log(ge.yellow("No other tables found to link to."))}}let m=!1;if(i||(m=await Pt({message:`Can '${o}' be NULL?`,default:!0})),!i&&!l&&e!=="DateTime")if(e==="Boolean")c=await ne({message:`Default value for '${o}':`,choices:[{name:"None",value:""},{name:"TRUE",value:"TRUE"},{name:"FALSE",value:"FALSE"}]});else if(e==="Enum"&&s)c=await ne({message:`Default value for '${o}':`,choices:[{name:"None",value:""},...s.map(d=>({name:d,value:`'${d}'`}))]});else{let u=await Ie({message:`Default value for '${o}' (leave empty for none):`});u&&(e==="Text"?c=`'${u.replace(/'/g,"''")}'`:c=u)}return{col:{name:o,type:e,isPk:i,nullable:m,defaultValue:c,fkTarget:l,enumValues:s},isPk:i}}var Ne=E(()=>{"use strict"});import{input as Ka,confirm as kt}from"@inquirer/prompts";import g from"picocolors";async function Nt(n){let t=h(n),a="";for(;!a;)a=await Ka({message:"Enter the new table name:"}),/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)||(console.log(g.red("Invalid table name. Use only letters, numbers, and underscores.")),a="");let r=[],o=!1,e=!0;for(;e;){It(a,r);let l=r.map(u=>u.name),{col:m,isPk:p}=await fe(t,o,l);if(!m)break;p&&(o=!0),r.push(m),e=await kt({theme:{prefix:g.cyan(`
96
- \u2713 `),style:{message:u=>g.bold(g.white(u)),highlight:u=>{let d=u.replace(/\x1b\[[0-9;]*m/g,"");return g.cyan(d)}}},message:"Add another column?",default:!0})}It(a,r),console.log(g.dim("Generating SQL..."));let c=j(n.type).buildCreateTable(a,r);if(console.log(g.cyan(`
94
+ \u{1F389} Initialization Complete!`)),console.log($.white(`You can now run ${$.bold("npx drixio")} to manage it!`)),process.exit(0)}var vt=E(()=>{"use strict"});var At={};L(At,{runDropDbCommand:()=>Va});import Q from"picocolors";import Wa from"fs/promises";import ja from"path";async function Va(n){let{select:a,input:t,password:r,confirm:o}=await import("@inquirer/prompts"),e=n[0];(!e||!["sqlite","mysql","postgres"].includes(e.toLowerCase()))&&(e=await a({message:"Which database type do you want to drop?",choices:[{name:"SQLite (Local File)",value:"sqlite"},{name:"MySQL (Local Server)",value:"mysql"},{name:"PostgreSQL (Local Server)",value:"postgres"}]})),e=e.toLowerCase();let s=n[1];if(e==="sqlite"){s||(s=await t({message:"Enter the SQLite filename to delete (e.g. database.sqlite):",default:"database.sqlite"})),!s.endsWith(".sqlite")&&!s.endsWith(".db")&&(s+=".sqlite"),await o({message:`Are you absolutely sure you want to delete ${s}? This cannot be undone!`,default:!1})||(console.log(Q.yellow("Aborted.")),process.exit(0));let i=ja.resolve(process.cwd(),s);try{await Wa.unlink(i),console.log(Q.green(`\u2714 Deleted local database file: ${s}`))}catch(l){console.log(Q.red(`\u2718 Failed to delete file: ${l.message}`))}}else{console.log(Q.dim(`Please provide credentials for your local ${e} server to drop a database.`));let c=await t({message:"Server Host:",default:"localhost"}),i=await t({message:"Server Port:",default:e==="mysql"?"3306":"5432"}),l=await t({message:"Username:",default:e==="mysql"?"root":"postgres"}),m=await r({message:"Password (leave empty if none):"});s||(s=await t({message:"Which Database Name do you want to DROP?"})),await o({message:`Are you absolutely sure you want to DROP DATABASE '${s}' from ${c}? All data will be lost!`,default:!1})||(console.log(Q.yellow("Aborted.")),process.exit(0)),console.log(Q.cyan(`
95
+ Connecting to local server to drop database '${s}'...`));try{if(e==="mysql"){let d=await(await import("mysql2/promise")).createConnection({host:c,port:parseInt(i),user:l,password:m});await d.query(`DROP DATABASE IF EXISTS \`${s}\``),await d.end()}else if(e==="postgres"){let u=await import("pg"),d=new u.Client({host:c,port:parseInt(i),user:l,password:m,database:"postgres"});await d.connect(),await d.query(`DROP DATABASE IF EXISTS "${s}"`),await d.end()}console.log(Q.green(`\u2714 Dropped database: ${s}`))}catch(u){console.log(Q.red(`\u2718 Failed to drop database on server: ${u.message}`)),process.exit(1)}}process.exit(0)}var qt=E(()=>{"use strict"});import{select as Qa,Separator as Ka}from"@inquirer/prompts";import Y from"picocolors";var Rt,Lt=E(()=>{"use strict";Rt=async()=>await Qa({message:"Table Manager - Choose an action:",theme:{prefix:Y.cyan("\u2713 "),icon:{cursor:Y.cyan("\u203A ")},style:{message:n=>Y.bold(Y.white(n)),highlight:n=>{let a=n.replace(/\x1b\[[0-9;]*m/g,"");return a.includes(" Back")?Y.red(a):Y.cyan(a)}}},choices:[{name:" Create New Table",value:"create",description:"Build a new database table."},{name:" Modify Existing Table",value:"modify",description:"Modify an existing table's schema structure."},{name:" Drop Table",value:"drop",description:"Delete an entire table and its data."},new Ka,{name:Y.dim(" Back"),value:"back",description:"Back to the main menu."}]})});import{input as Ie,select as ne,confirm as Pt}from"@inquirer/prompts";import ge from"picocolors";async function fe(n,a,t=[],r=""){let o="";for(;!o;){if(o=await Ie({message:"Column name (leave empty to cancel/finish):",default:r}),!o.trim())return{col:null,isPk:!1};/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)?t.includes(o)&&(console.log(ge.red("Column name already exists!")),o=""):(console.log(ge.red("Invalid column name. Use only letters, numbers, and underscores.")),o="")}let e=await ne({message:`Select type for column '${o}':`,choices:[{name:"Integer",value:"Integer"},{name:"Text (String)",value:"Text"},{name:"Boolean",value:"Boolean"},{name:"Decimal (Float)",value:"Decimal"},{name:"DateTime",value:"DateTime"},{name:"Enum",value:"Enum"}]}),s;e==="Enum"&&(s=(await Ie({message:"Enter comma-separated Enum values (e.g. active, pending, deleted):"})).split(",").map(d=>d.trim()).filter(d=>d),s.length===0&&console.log(ge.yellow("Warning: No enum values provided.")));let c="";e==="DateTime"&&await Pt({message:"Set default to CURRENT_TIMESTAMP?",default:!1})&&(c="Timestamp");let i=!1,l;if(e!=="DateTime"){let u=[{name:"None",value:"none"}];a||u.push({name:"Primary Key",value:"pk"}),u.push({name:"Foreign Key",value:"fk"});let d=await ne({message:`Key type for '${o}':`,choices:u});if(d==="pk")i=!0,e==="Integer"&&(c="AutoInc");else if(d==="fk"){let f=await n.getTables();if(f.length>0){let y=await ne({message:"Select target table:",choices:f.map(x=>({name:x,value:x}))}),b=await n.getSchema(y);if(b.length>0){let x=await ne({message:"Select target column:",choices:b.map(I=>({name:`${I.name} (${I.type})`,value:I.name}))});l={table:y,column:x},c=`FK -> ${y}.${x}`}else console.log(ge.yellow("Target table has no columns."))}else console.log(ge.yellow("No other tables found to link to."))}}let m=!1;if(i||(m=await Pt({message:`Can '${o}' be NULL?`,default:!0})),!i&&!l&&e!=="DateTime")if(e==="Boolean")c=await ne({message:`Default value for '${o}':`,choices:[{name:"None",value:""},{name:"TRUE",value:"TRUE"},{name:"FALSE",value:"FALSE"}]});else if(e==="Enum"&&s)c=await ne({message:`Default value for '${o}':`,choices:[{name:"None",value:""},...s.map(d=>({name:d,value:`'${d}'`}))]});else{let u=await Ie({message:`Default value for '${o}' (leave empty for none):`});u&&(e==="Text"?c=`'${u.replace(/'/g,"''")}'`:c=u)}return{col:{name:o,type:e,isPk:i,nullable:m,defaultValue:c,fkTarget:l,enumValues:s},isPk:i}}var Ne=E(()=>{"use strict"});import{input as za,confirm as kt}from"@inquirer/prompts";import g from"picocolors";async function Nt(n){let a=h(n),t="";for(;!t;)t=await za({message:"Enter the new table name:"}),/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)||(console.log(g.red("Invalid table name. Use only letters, numbers, and underscores.")),t="");let r=[],o=!1,e=!0;for(;e;){It(t,r);let l=r.map(u=>u.name),{col:m,isPk:p}=await fe(a,o,l);if(!m)break;p&&(o=!0),r.push(m),e=await kt({theme:{prefix:g.cyan(`
96
+ \u2713 `),style:{message:u=>g.bold(g.white(u)),highlight:u=>{let d=u.replace(/\x1b\[[0-9;]*m/g,"");return g.cyan(d)}}},message:"Add another column?",default:!0})}It(t,r),console.log(g.dim("Generating SQL..."));let c=j(n.type).buildCreateTable(t,r);if(console.log(g.cyan(`
97
97
  --- SQL Preview ---`)),console.log(g.yellow(c)),console.log(g.cyan(`-------------------
98
- `)),await kt({message:"Do you want to execute this SQL to build the table?",default:!0}))try{console.log(g.dim("Executing SQL...")),await t.executeSql(c),console.log(g.green(`
99
- \u2713 Table '${a}' created successfully!`))}catch(l){console.log(g.red(`
100
- x Error creating table: ${l.message}`))}finally{await t.close()}else console.log(g.yellow("Aborted table creation.")),await t.close();await za()}async function za(){let{input:n}=await import("@inquirer/prompts");await n({message:"Press Enter to continue..."})}function It(n,t){console.clear(),console.log(`
101
- `);let a={name:20,type:18,key:8,nullable:10,defaultCol:16},r=a.name+a.type+a.key+a.nullable+a.defaultCol+14;console.log(g.cyan(`\u2554${"\u2550".repeat(r)}\u2557`));let o=r-n.length,e=Math.max(0,Math.floor(o/2)),s=Math.max(0,o-e),c=" ".repeat(e)+g.bold(g.white(n))+" ".repeat(s);console.log(g.cyan("\u2551")+c+g.cyan("\u2551"));let i=(l,m,p)=>g.cyan(l+"\u2550".repeat(a.name+2)+m+"\u2550".repeat(a.type+2)+m+"\u2550".repeat(a.key+2)+m+"\u2550".repeat(a.nullable+2)+m+"\u2550".repeat(a.defaultCol+2)+p);console.log(i("\u2560","\u2566","\u2563")),console.log(g.cyan("\u2551 ")+g.bold(g.white("Column Name".padEnd(a.name)))+g.cyan(" \u2551 ")+g.bold(g.white("Type".padEnd(a.type)))+g.cyan(" \u2551 ")+g.bold(g.white("Key".padEnd(a.key)))+g.cyan(" \u2551 ")+g.bold(g.white("Nullable".padEnd(a.nullable)))+g.cyan(" \u2551 ")+g.bold(g.white("Default".padEnd(a.defaultCol)))+g.cyan(" \u2551")),t.length>0&&console.log(i("\u2560","\u256C","\u2563"));for(let l=0;l<t.length;l++){let m=t[l],p=g.white(m.name.padEnd(a.name)),u=g.white(m.type.padEnd(a.type)),d=m.isPk?"PK":"-",f=m.isPk?g.green(d.padEnd(a.key)):g.dim(d.padEnd(a.key)),y=m.nullable?"Yes":"No",b=m.nullable?g.green(y.padEnd(a.nullable)):g.dim(y.padEnd(a.nullable)),x=m.defaultValue||"-",I=m.defaultValue?g.yellow(x.padEnd(a.defaultCol)):g.dim(x.padEnd(a.defaultCol));console.log(g.cyan("\u2551 ")+p+g.cyan(" \u2551 ")+u+g.cyan(" \u2551 ")+f+g.cyan(" \u2551 ")+b+g.cyan(" \u2551 ")+I+g.cyan(" \u2551"))}if(t.length===0){console.log(i("\u2560","\u2569","\u2563"));let l="No columns added yet",m=Math.max(0,Math.floor((r-l.length)/2)),p=Math.max(0,r-l.length-m);console.log(g.cyan("\u2551")+" ".repeat(m)+g.dim(l)+" ".repeat(p)+g.cyan("\u2551")),console.log(g.cyan(`\u255A${"\u2550".repeat(r)}\u255D`))}else console.log(i("\u255A","\u2569","\u255D"));console.log(g.dim(` Leave empty the Column Name to cancel.
102
- `))}var Bt=E(()=>{"use strict";Ce();C();Ne()});import Ha from"fs/promises";import Ya from"path";import{input as Ga}from"@inquirer/prompts";import K from"picocolors";async function Mt(n){if(console.log(K.green(`
98
+ `)),await kt({message:"Do you want to execute this SQL to build the table?",default:!0}))try{console.log(g.dim("Executing SQL...")),await a.executeSql(c),console.log(g.green(`
99
+ \u2713 Table '${t}' created successfully!`))}catch(l){console.log(g.red(`
100
+ x Error creating table: ${l.message}`))}finally{await a.close()}else console.log(g.yellow("Aborted table creation.")),await a.close();await Ha()}async function Ha(){let{input:n}=await import("@inquirer/prompts");await n({message:"Press Enter to continue..."})}function It(n,a){console.clear(),console.log(`
101
+ `);let t={name:20,type:18,key:8,nullable:10,defaultCol:16},r=t.name+t.type+t.key+t.nullable+t.defaultCol+14;console.log(g.cyan(`\u2554${"\u2550".repeat(r)}\u2557`));let o=r-n.length,e=Math.max(0,Math.floor(o/2)),s=Math.max(0,o-e),c=" ".repeat(e)+g.bold(g.white(n))+" ".repeat(s);console.log(g.cyan("\u2551")+c+g.cyan("\u2551"));let i=(l,m,p)=>g.cyan(l+"\u2550".repeat(t.name+2)+m+"\u2550".repeat(t.type+2)+m+"\u2550".repeat(t.key+2)+m+"\u2550".repeat(t.nullable+2)+m+"\u2550".repeat(t.defaultCol+2)+p);console.log(i("\u2560","\u2566","\u2563")),console.log(g.cyan("\u2551 ")+g.bold(g.white("Column Name".padEnd(t.name)))+g.cyan(" \u2551 ")+g.bold(g.white("Type".padEnd(t.type)))+g.cyan(" \u2551 ")+g.bold(g.white("Key".padEnd(t.key)))+g.cyan(" \u2551 ")+g.bold(g.white("Nullable".padEnd(t.nullable)))+g.cyan(" \u2551 ")+g.bold(g.white("Default".padEnd(t.defaultCol)))+g.cyan(" \u2551")),a.length>0&&console.log(i("\u2560","\u256C","\u2563"));for(let l=0;l<a.length;l++){let m=a[l],p=g.white(m.name.padEnd(t.name)),u=g.white(m.type.padEnd(t.type)),d=m.isPk?"PK":"-",f=m.isPk?g.green(d.padEnd(t.key)):g.dim(d.padEnd(t.key)),y=m.nullable?"Yes":"No",b=m.nullable?g.green(y.padEnd(t.nullable)):g.dim(y.padEnd(t.nullable)),x=m.defaultValue||"-",I=m.defaultValue?g.yellow(x.padEnd(t.defaultCol)):g.dim(x.padEnd(t.defaultCol));console.log(g.cyan("\u2551 ")+p+g.cyan(" \u2551 ")+u+g.cyan(" \u2551 ")+f+g.cyan(" \u2551 ")+b+g.cyan(" \u2551 ")+I+g.cyan(" \u2551"))}if(a.length===0){console.log(i("\u2560","\u2569","\u2563"));let l="No columns added yet",m=Math.max(0,Math.floor((r-l.length)/2)),p=Math.max(0,r-l.length-m);console.log(g.cyan("\u2551")+" ".repeat(m)+g.dim(l)+" ".repeat(p)+g.cyan("\u2551")),console.log(g.cyan(`\u255A${"\u2550".repeat(r)}\u255D`))}else console.log(i("\u255A","\u2569","\u255D"));console.log(g.dim(` Leave empty the Column Name to cancel.
102
+ `))}var Bt=E(()=>{"use strict";Ce();C();Ne()});import Ya from"fs/promises";import Ga from"path";import{input as Za}from"@inquirer/prompts";import K from"picocolors";async function Mt(n){if(console.log(K.green(`
103
103
  Initiating SQL table writer for experts. Please ensure database connection is properly configured.`)),n.type==="unknown"){console.log(K.yellow(`
104
- No database connection found. Please setup first.`));return}try{let t=await Ga({message:"Enter the path to your .md or .sql file:"});if(t&&t.trim()){let a=Ya.resolve(process.cwd(),t.trim()),r="";try{r=await Ha.readFile(a,"utf-8")}catch(e){console.log(K.red(`
105
- x Failed to read file: ${e.message}`));return}let o=r;if(a.toLowerCase().endsWith(".md")){let e=[...r.matchAll(/```(?:sql)?\n([\s\S]*?)```/gi)];e.length>0&&(o=e.map(s=>s[1].trim()).join(`
104
+ No database connection found. Please setup first.`));return}try{let a=await Za({message:"Enter the path to your .md or .sql file:"});if(a&&a.trim()){let t=Ga.resolve(process.cwd(),a.trim()),r="";try{r=await Ya.readFile(t,"utf-8")}catch(e){console.log(K.red(`
105
+ x Failed to read file: ${e.message}`));return}let o=r;if(t.toLowerCase().endsWith(".md")){let e=[...r.matchAll(/```(?:sql)?\n([\s\S]*?)```/gi)];e.length>0&&(o=e.map(s=>s[1].trim()).join(`
106
106
 
107
107
  `))}if(o.trim()){console.log(K.dim("Executing SQL..."));let e=h(n);try{await e.executeSql(o),console.log(K.green(`
108
108
  \u2713 SQL executed successfully!`))}finally{await e.close()}}else console.log(K.yellow(`
109
109
  \u26A0\uFE0F No SQL found in the file. Aborted.`))}else console.log(K.yellow(`
110
- No file path entered. Aborted.`))}catch(t){console.log(K.red(`
111
- Error executing SQL: ${t.message}`))}}var Ot=E(()=>{"use strict";C()});import{select as ye,confirm as _t,input as Za}from"@inquirer/prompts";import v from"picocolors";async function Ft(n){let t=h(n);try{let a=await t.getTables();if(a.length===0){console.log(v.yellow("No tables found in the database."));return}let r=await ye({message:"Select a table to drop:",choices:a.map(e=>({name:e,value:e}))});if(await _t({message:`Are you sure you want to DROP TABLE '${r}'? This will delete all its data!`,default:!1})){let e=`DROP TABLE ${r}`;n.type==="sqlite"||n.type==="postgres"?e=`DROP TABLE "${r}"`:n.type==="mysql"&&(e=`DROP TABLE \`${r}\``),await t.executeSql(e),console.log(v.green(`\u2713 Table '${r}' dropped successfully.`))}}catch(a){console.log(v.red(`Error: ${a.message}`))}finally{await t.close()}}async function he(n,t){let a=h(n),r=j(n.type);try{let o=await a.getTables();if(o.length===0){console.log(v.yellow("No tables found in the database."));return}let e=await ye({message:"Select a table to modify:",choices:o.map(c=>({name:c,value:c}))}),s=await a.getSchema(e);if(t==="add"){let c=s.some(m=>m.isPk),i=s.map(m=>m.name),{col:l}=await fe(a,c,i);if(l){let m=r.buildCreateTable("tmp",[l]).split(`
112
- `)[1].trim().replace(/,$/,""),p=`ALTER TABLE ${e} ADD COLUMN ${m}`;n.type==="sqlite"||n.type==="postgres"?p=`ALTER TABLE "${e}" ADD COLUMN ${m}`:n.type==="mysql"&&(p=`ALTER TABLE \`${e}\` ADD COLUMN ${m}`),await a.executeSql(p),console.log(v.green(`\u2713 Column '${l.name}' added successfully.`))}}else if(t==="rename"){if(s.length===0)return console.log(v.yellow("Table has no columns."));let c=await ye({message:"Select a column to rename:",choices:s.map(l=>({name:`${l.name} (${l.type})`,value:l.name}))}),i=await Za({message:`New name for '${c}':`});if(i&&i!==c){let l=`ALTER TABLE ${e} RENAME COLUMN ${c} TO ${i}`;n.type==="sqlite"||n.type==="postgres"?l=`ALTER TABLE "${e}" RENAME COLUMN "${c}" TO "${i}"`:n.type==="mysql"&&(l=`ALTER TABLE \`${e}\` RENAME COLUMN \`${c}\` TO \`${i}\``),await a.executeSql(l),console.log(v.green(`\u2713 Column renamed to '${i}' successfully.`))}}else if(t==="modify"){if(s.length===0)return console.log(v.yellow("Table has no columns."));if(n.type==="sqlite"){console.log(v.yellow("SQLite does not support altering column types directly. Please recreate the table."));return}let c=await ye({message:"Select a column to modify:",choices:s.map(p=>({name:`${p.name} (${p.type})`,value:p.name}))}),i=s.some(p=>p.isPk&&p.name!==c),l=s.map(p=>p.name).filter(p=>p!==c),{col:m}=await fe(a,i,l,c);if(m){let p=r.buildCreateTable("tmp",[m]).split(`
113
- `)[1].trim().replace(/,$/,""),u="";n.type==="postgres"?(console.log(v.yellow("Note: Complex constraint modifications might require raw SQL in Postgres.")),u=`ALTER TABLE "${e}" ALTER COLUMN ${p.replace(m.name,`"${m.name}" TYPE`)}`):n.type==="mysql"&&(u=`ALTER TABLE \`${e}\` MODIFY COLUMN ${p}`);try{await a.executeSql(u),console.log(v.green(`\u2713 Column '${c}' modified successfully.`))}catch(d){console.log(v.red("x Could not modify column automatically. Try using Raw SQL.")),console.log(v.dim(d.message))}}}else if(t==="delete"){if(s.length===0)return console.log(v.yellow("Table has no columns."));let c=await ye({message:"Select a column to delete:",choices:s.map(l=>({name:`${l.name} (${l.type})`,value:l.name}))});if(await _t({message:`Are you sure you want to delete column '${c}'? Data will be lost!`,default:!1})){let l=`ALTER TABLE ${e} DROP COLUMN ${c}`;n.type==="sqlite"||n.type==="postgres"?l=`ALTER TABLE "${e}" DROP COLUMN "${c}"`:n.type==="mysql"&&(l=`ALTER TABLE \`${e}\` DROP COLUMN \`${c}\``);try{await a.executeSql(l),console.log(v.green(`\u2713 Column '${c}' deleted successfully.`))}catch(m){console.log(v.red(`x Error deleting column: ${m.message}`))}}}}catch(o){console.log(v.red(`Error: ${o.message}`))}finally{await a.close()}}var Ut=E(()=>{"use strict";C();Ce();Ne()});var jt={};L(jt,{runTableManagerFlow:()=>Xa});import W from"picocolors";import{select as Wt,Separator as Ja}from"@inquirer/prompts";async function Xa(n){if(n.type==="unknown"){console.log(W.yellow(`
114
- No database connection found. Please setup first.`)),await Be();return}let t=await Promise.resolve().then(()=>(C(),Qe)).then(r=>r.createDBAdapter(n)),a=!0;for(;a;){console.clear();let r="Scanning...";try{r=`${(await t.getTables()).length} tables detected`}catch(s){r=W.red(s.message)}let o=n.targetUrl;switch(se(` Table Builder & Manager \u2022 [${n.type.toUpperCase()}]`,[{label:"Database",value:n.type.toUpperCase()},{label:"Target",value:o.length>45?"..."+o.slice(-42):o},{label:"Tables",value:r}]),await Rt()){case"create":let s=await Wt({message:"How do you want to create the table?",theme:{prefix:W.cyan("\u2713 "),icon:{cursor:W.cyan("\u203A ")},style:{message:c=>W.bold(W.white(c)),highlight:c=>{let i=c.replace(/\x1b\[[0-9;]*m/g,"");return i.includes("Cancel")?W.red(i):W.cyan(i)}}},choices:[{name:" Interactive Wizard (Beginner Friendly)",value:"wizard",description:"Follow the step-by-step guide to build your table."},{name:" Raw SQL (Experts)",value:"sql",description:"Write / Import your own CREATE TABLE statement."},new Ja,{name:W.dim(" Cancel"),value:"cancel",description:"Back to Table Manager"}]});s==="wizard"?await Nt(n):s==="sql"&&await Mt(n);break;case"modify":await eo(n);break;case"drop":await Ft(n),await Be();break;case"back":a=!1;break}}await t.close()}async function eo(n){let t=await Wt({message:"Modify Table Actions:",choices:[{name:"Add Column",value:"add_col"},{name:"Rename Column",value:"rename_col"},{name:"Modify Column Settings (MySQL/Postgres)",value:"mod_col",disabled:n.type==="sqlite"},{name:"Delete Column",value:"del_col"},{name:" Back",value:"back"}]});if(t!=="back"){switch(t){case"add_col":await he(n,"add");break;case"rename_col":await he(n,"rename");break;case"mod_col":await he(n,"modify");break;case"del_col":await he(n,"delete");break}await Be()}}async function Be(){let{input:n}=await import("@inquirer/prompts");await n({message:"Press Enter to continue..."})}var Vt=E(()=>{"use strict";Lt();Bt();Ot();Ut();$e()});$e();import D from"picocolors";import re from"fs/promises";import J from"path";async function A(n){let t=process.cwd();if(n){let e="sqlite";return n.startsWith("postgres://")||n.startsWith("postgresql://")?e="postgres":n.startsWith("mysql://")?e="mysql":e="sqlite",{type:e,targetUrl:n.replace("file:",""),source:"manual"}}let a=[".","prisma","db","database","src/db","src/database"];for(let e of a)try{let s=J.join(t,e),i=(await re.readdir(s)).find(l=>l.endsWith(".db")||l.endsWith(".sqlite")||l.endsWith(".sqlite3"));if(i)return{type:"sqlite",targetUrl:J.join(s,i),source:"auto-detected"}}catch{}let r=J.join(t,"prisma","schema.prisma");try{let e=await re.readFile(r,"utf-8"),s=e.match(/provider\s*=\s*["']([^"']+)["']/),c=e.match(/url\s*=\s*(?:env\(["']([^"']+)["']\)|["']([^"']+)["'])/);if(s){let i=s[1];i==="postgresql"&&(i="postgres");let l="";if(c&&c[2]&&(l=c[2],l.startsWith("file:")&&(l=J.join(t,"prisma",l.replace("file:","")))),l&&(i==="sqlite"||i==="postgres"||i==="mysql"))return{type:i,targetUrl:l,source:".env"}}}catch{}let o=J.join(t,".env");try{let e=await re.readFile(o,"utf-8"),s=["DATABASE_URL","DB_URL","POSTGRES_URL","POSTGRES_PRISMA_URL","MYSQL_URL"];for(let c of s){let i=new RegExp(`${c}\\s*=\\s*["']?([^"'\\r\\n]+)["']?`),l=e.match(i);if(l){let m=l[1];if(m.startsWith("file:")||m.endsWith(".db")||m.includes(".sqlite"))return{type:"sqlite",targetUrl:m.replace("file:",""),source:".env"};if(m.startsWith("postgres://")||m.startsWith("postgresql://"))return{type:"postgres",targetUrl:m,source:".env"};if(m.startsWith("mysql://"))return{type:"mysql",targetUrl:m,source:".env"}}}}catch{}return{type:"unknown",targetUrl:"",source:"manual"}}async function Ue(n){let t=J.join(process.cwd(),".env"),a="";try{a=await re.readFile(t,"utf-8")}catch{}let r=/DATABASE_URL\s*=\s*["']?([^"'\r\n]+)["']?/;r.test(a)?a=a.replace(r,`DATABASE_URL="${n}"`):(a&&!a.endsWith(`
115
- `)&&(a+=`
116
- `),a+=`DATABASE_URL="${n}"
117
- `),await re.writeFile(t,a,"utf-8")}C();import{select as Ze,Separator as le}from"@inquirer/prompts";import T from"picocolors";import{select as ra}from"@inquirer/prompts";import X from"picocolors";var Ke=async n=>await ra({message:"Select a table to edit data:",theme:{prefix:X.cyan("\u2713 "),icon:{cursor:X.cyan("\u203A ")},style:{message:t=>X.bold(X.white(t)),highlight:t=>{let a=t.replace(/\x1b\[[0-9;]*m/g,"");return a.includes(" Back")?X.red(a):X.cyan(a)}}},choices:n});Ce();import{input as ie,select as ia}from"@inquirer/prompts";import w from"picocolors";import la from"fs/promises";import ca from"path";async function ze(n,t,a,r){let o=j(t);console.log(w.cyan(`
118
- --- Add Data to [${a}] ---`)),console.log(w.dim("Leave a field completely empty (press Enter) to skip it (e.g. for AutoInc or NULL)"));let e=[],s=[];for(let i of r){if(i.isPk&&(i.type.toLowerCase().includes("int")||i.type.toLowerCase()==="integer")){console.log(w.dim(`Skipping '${i.name}' (Auto Increment Primary Key)`));continue}let l=await ie({message:`Value for '${i.name}' (${i.type}):`});l.trim()!==""&&(e.push(o.quoteIdentifier(i.name)),s.push(`'${o.escapeString(l)}'`))}if(e.length===0){console.log(w.yellow("No data entered. Aborted."));return}let c=`INSERT INTO ${o.quoteIdentifier(a)} (${e.join(", ")}) VALUES (${s.join(", ")});`;console.log(w.dim(`
119
- Executing: `)+w.yellow(c));try{await n.executeSql(c),console.log(w.green("\u2713 Data added successfully!"))}catch(i){console.log(w.red(`x Failed to add data: ${i.message}`))}}async function He(n,t,a,r){let o=j(t);if(console.log(w.cyan(`
120
- --- Edit Data in [${a}] ---`)),r.length===0)return;let s=(r.find(u=>u.isPk)||r[0]).name,c=await ie({message:`Enter the '${s}' of the record you want to edit:`});if(!c.trim()){console.log(w.yellow("Aborted."));return}let i=await ia({message:"Which column do you want to update?",choices:r.map(u=>({name:u.name,value:u.name}))}),l=await ie({message:`New value for '${i}' (leave empty for NULL):`}),m="NULL";l.trim()!==""&&(m=`'${o.escapeString(l)}'`);let p=`UPDATE ${o.quoteIdentifier(a)} SET ${o.quoteIdentifier(i)} = ${m} WHERE ${o.quoteIdentifier(s)} = '${o.escapeString(c)}';`;console.log(w.dim(`
121
- Executing: `)+w.yellow(p));try{await n.executeSql(p),console.log(w.green("\u2713 Data updated successfully!"))}catch(u){console.log(w.red(`x Failed to update data: ${u.message}`))}}async function Ye(n,t,a,r){let o=j(t);if(console.log(w.cyan(`
122
- --- Delete Data from [${a}] ---`)),r.length===0)return;let s=(r.find(l=>l.isPk)||r[0]).name,c=await ie({message:`Enter the '${s}' of the record you want to delete:`});if(!c.trim()){console.log(w.yellow("Aborted."));return}let i=`DELETE FROM ${o.quoteIdentifier(a)} WHERE ${o.quoteIdentifier(s)} = '${o.escapeString(c)}';`;console.log(w.dim(`
110
+ No file path entered. Aborted.`))}catch(a){console.log(K.red(`
111
+ Error executing SQL: ${a.message}`))}}var Ot=E(()=>{"use strict";C()});import{select as ye,confirm as _t,input as Ja}from"@inquirer/prompts";import v from"picocolors";async function Ft(n){let a=h(n);try{let t=await a.getTables();if(t.length===0){console.log(v.yellow("No tables found in the database."));return}let r=await ye({message:"Select a table to drop:",choices:t.map(e=>({name:e,value:e}))});if(await _t({message:`Are you sure you want to DROP TABLE '${r}'? This will delete all its data!`,default:!1})){let e=`DROP TABLE ${r}`;n.type==="sqlite"||n.type==="postgres"?e=`DROP TABLE "${r}"`:n.type==="mysql"&&(e=`DROP TABLE \`${r}\``),await a.executeSql(e),console.log(v.green(`\u2713 Table '${r}' dropped successfully.`))}}catch(t){console.log(v.red(`Error: ${t.message}`))}finally{await a.close()}}async function he(n,a){let t=h(n),r=j(n.type);try{let o=await t.getTables();if(o.length===0){console.log(v.yellow("No tables found in the database."));return}let e=await ye({message:"Select a table to modify:",choices:o.map(c=>({name:c,value:c}))}),s=await t.getSchema(e);if(a==="add"){let c=s.some(m=>m.isPk),i=s.map(m=>m.name),{col:l}=await fe(t,c,i);if(l){let m=r.buildCreateTable("tmp",[l]).split(`
112
+ `)[1].trim().replace(/,$/,""),p=`ALTER TABLE ${e} ADD COLUMN ${m}`;n.type==="sqlite"||n.type==="postgres"?p=`ALTER TABLE "${e}" ADD COLUMN ${m}`:n.type==="mysql"&&(p=`ALTER TABLE \`${e}\` ADD COLUMN ${m}`),await t.executeSql(p),console.log(v.green(`\u2713 Column '${l.name}' added successfully.`))}}else if(a==="rename"){if(s.length===0)return console.log(v.yellow("Table has no columns."));let c=await ye({message:"Select a column to rename:",choices:s.map(l=>({name:`${l.name} (${l.type})`,value:l.name}))}),i=await Ja({message:`New name for '${c}':`});if(i&&i!==c){let l=`ALTER TABLE ${e} RENAME COLUMN ${c} TO ${i}`;n.type==="sqlite"||n.type==="postgres"?l=`ALTER TABLE "${e}" RENAME COLUMN "${c}" TO "${i}"`:n.type==="mysql"&&(l=`ALTER TABLE \`${e}\` RENAME COLUMN \`${c}\` TO \`${i}\``),await t.executeSql(l),console.log(v.green(`\u2713 Column renamed to '${i}' successfully.`))}}else if(a==="modify"){if(s.length===0)return console.log(v.yellow("Table has no columns."));if(n.type==="sqlite"){console.log(v.yellow("SQLite does not support altering column types directly. Please recreate the table."));return}let c=await ye({message:"Select a column to modify:",choices:s.map(p=>({name:`${p.name} (${p.type})`,value:p.name}))}),i=s.some(p=>p.isPk&&p.name!==c),l=s.map(p=>p.name).filter(p=>p!==c),{col:m}=await fe(t,i,l,c);if(m){let p=r.buildCreateTable("tmp",[m]).split(`
113
+ `)[1].trim().replace(/,$/,""),u="";n.type==="postgres"?(console.log(v.yellow("Note: Complex constraint modifications might require raw SQL in Postgres.")),u=`ALTER TABLE "${e}" ALTER COLUMN ${p.replace(m.name,`"${m.name}" TYPE`)}`):n.type==="mysql"&&(u=`ALTER TABLE \`${e}\` MODIFY COLUMN ${p}`);try{await t.executeSql(u),console.log(v.green(`\u2713 Column '${c}' modified successfully.`))}catch(d){console.log(v.red("x Could not modify column automatically. Try using Raw SQL.")),console.log(v.dim(d.message))}}}else if(a==="delete"){if(s.length===0)return console.log(v.yellow("Table has no columns."));let c=await ye({message:"Select a column to delete:",choices:s.map(l=>({name:`${l.name} (${l.type})`,value:l.name}))});if(await _t({message:`Are you sure you want to delete column '${c}'? Data will be lost!`,default:!1})){let l=`ALTER TABLE ${e} DROP COLUMN ${c}`;n.type==="sqlite"||n.type==="postgres"?l=`ALTER TABLE "${e}" DROP COLUMN "${c}"`:n.type==="mysql"&&(l=`ALTER TABLE \`${e}\` DROP COLUMN \`${c}\``);try{await t.executeSql(l),console.log(v.green(`\u2713 Column '${c}' deleted successfully.`))}catch(m){console.log(v.red(`x Error deleting column: ${m.message}`))}}}}catch(o){console.log(v.red(`Error: ${o.message}`))}finally{await t.close()}}var Ut=E(()=>{"use strict";C();Ce();Ne()});var jt={};L(jt,{runTableManagerFlow:()=>eo});import W from"picocolors";import{select as Wt,Separator as Xa}from"@inquirer/prompts";async function eo(n){if(n.type==="unknown"){console.log(W.yellow(`
114
+ No database connection found. Please setup first.`)),await Be();return}let a=await Promise.resolve().then(()=>(C(),Qe)).then(r=>r.createDBAdapter(n)),t=!0;for(;t;){console.clear();let r="Scanning...";try{r=`${(await a.getTables()).length} tables detected`}catch(s){r=W.red(s.message)}let o=n.targetUrl;switch(se(` Table Builder & Manager \u2022 [${n.type.toUpperCase()}]`,[{label:"Database",value:n.type.toUpperCase()},{label:"Target",value:o.length>45?"..."+o.slice(-42):o},{label:"Tables",value:r}]),await Rt()){case"create":let s=await Wt({message:"How do you want to create the table?",theme:{prefix:W.cyan("\u2713 "),icon:{cursor:W.cyan("\u203A ")},style:{message:c=>W.bold(W.white(c)),highlight:c=>{let i=c.replace(/\x1b\[[0-9;]*m/g,"");return i.includes("Cancel")?W.red(i):W.cyan(i)}}},choices:[{name:" Interactive Wizard (Beginner Friendly)",value:"wizard",description:"Follow the step-by-step guide to build your table."},{name:" Raw SQL (Experts)",value:"sql",description:"Write / Import your own CREATE TABLE statement."},new Xa,{name:W.dim(" Cancel"),value:"cancel",description:"Back to Table Manager"}]});s==="wizard"?await Nt(n):s==="sql"&&await Mt(n);break;case"modify":await to(n);break;case"drop":await Ft(n),await Be();break;case"back":t=!1;break}}await a.close()}async function to(n){let a=await Wt({message:"Modify Table Actions:",choices:[{name:"Add Column",value:"add_col"},{name:"Rename Column",value:"rename_col"},{name:"Modify Column Settings (MySQL/Postgres)",value:"mod_col",disabled:n.type==="sqlite"},{name:"Delete Column",value:"del_col"},{name:" Back",value:"back"}]});if(a!=="back"){switch(a){case"add_col":await he(n,"add");break;case"rename_col":await he(n,"rename");break;case"mod_col":await he(n,"modify");break;case"del_col":await he(n,"delete");break}await Be()}}async function Be(){let{input:n}=await import("@inquirer/prompts");await n({message:"Press Enter to continue..."})}var Vt=E(()=>{"use strict";Lt();Bt();Ot();Ut();$e()});$e();import D from"picocolors";import re from"fs/promises";import J from"path";async function A(n){let a=process.cwd();if(n){let e="sqlite";return n.startsWith("postgres://")||n.startsWith("postgresql://")?e="postgres":n.startsWith("mysql://")?e="mysql":e="sqlite",{type:e,targetUrl:n.replace("file:",""),source:"manual"}}let t=[".","prisma","db","database","src/db","src/database"];for(let e of t)try{let s=J.join(a,e),i=(await re.readdir(s)).find(l=>l.endsWith(".db")||l.endsWith(".sqlite")||l.endsWith(".sqlite3"));if(i)return{type:"sqlite",targetUrl:J.join(s,i),source:"auto-detected"}}catch{}let r=J.join(a,"prisma","schema.prisma");try{let e=await re.readFile(r,"utf-8"),s=e.match(/provider\s*=\s*["']([^"']+)["']/),c=e.match(/url\s*=\s*(?:env\(["']([^"']+)["']\)|["']([^"']+)["'])/);if(s){let i=s[1];i==="postgresql"&&(i="postgres");let l="";if(c&&c[2]&&(l=c[2],l.startsWith("file:")&&(l=J.join(a,"prisma",l.replace("file:","")))),l&&(i==="sqlite"||i==="postgres"||i==="mysql"))return{type:i,targetUrl:l,source:".env"}}}catch{}let o=J.join(a,".env");try{let e=await re.readFile(o,"utf-8"),s=["DATABASE_URL","DB_URL","POSTGRES_URL","POSTGRES_PRISMA_URL","MYSQL_URL"];for(let c of s){let i=new RegExp(`${c}\\s*=\\s*["']?([^"'\\r\\n]+)["']?`),l=e.match(i);if(l){let m=l[1];if(m.startsWith("file:")||m.endsWith(".db")||m.includes(".sqlite"))return{type:"sqlite",targetUrl:m.replace("file:",""),source:".env"};if(m.startsWith("postgres://")||m.startsWith("postgresql://"))return{type:"postgres",targetUrl:m,source:".env"};if(m.startsWith("mysql://"))return{type:"mysql",targetUrl:m,source:".env"}}}}catch{}return{type:"unknown",targetUrl:"",source:"manual"}}async function Ue(n){let a=J.join(process.cwd(),".env"),t="";try{t=await re.readFile(a,"utf-8")}catch{}let r=/DATABASE_URL\s*=\s*["']?([^"'\r\n]+)["']?/;r.test(t)?t=t.replace(r,`DATABASE_URL="${n}"`):(t&&!t.endsWith(`
115
+ `)&&(t+=`
116
+ `),t+=`DATABASE_URL="${n}"
117
+ `),await re.writeFile(a,t,"utf-8")}C();import{select as Ze,Separator as le}from"@inquirer/prompts";import T from"picocolors";import{select as ra}from"@inquirer/prompts";import X from"picocolors";var Ke=async n=>await ra({message:"Select a table to edit data:",theme:{prefix:X.cyan("\u2713 "),icon:{cursor:X.cyan("\u203A ")},style:{message:a=>X.bold(X.white(a)),highlight:a=>{let t=a.replace(/\x1b\[[0-9;]*m/g,"");return t.includes(" Back")?X.red(t):X.cyan(t)}}},choices:n});Ce();import{input as ie,select as ia}from"@inquirer/prompts";import w from"picocolors";import la from"fs/promises";import ca from"path";async function ze(n,a,t,r){let o=j(a);console.log(w.cyan(`
118
+ --- Add Data to [${t}] ---`)),console.log(w.dim("Leave a field completely empty (press Enter) to skip it (e.g. for AutoInc or NULL)"));let e=[],s=[];for(let i of r){if(i.isPk&&(i.type.toLowerCase().includes("int")||i.type.toLowerCase()==="integer")){console.log(w.dim(`Skipping '${i.name}' (Auto Increment Primary Key)`));continue}let l=await ie({message:`Value for '${i.name}' (${i.type}):`});l.trim()!==""&&(e.push(o.quoteIdentifier(i.name)),s.push(`'${o.escapeString(l)}'`))}if(e.length===0){console.log(w.yellow("No data entered. Aborted."));return}let c=`INSERT INTO ${o.quoteIdentifier(t)} (${e.join(", ")}) VALUES (${s.join(", ")});`;console.log(w.dim(`
119
+ Executing: `)+w.yellow(c));try{await n.executeSql(c),console.log(w.green("\u2713 Data added successfully!"))}catch(i){console.log(w.red(`x Failed to add data: ${i.message}`))}}async function He(n,a,t,r){let o=j(a);if(console.log(w.cyan(`
120
+ --- Edit Data in [${t}] ---`)),r.length===0)return;let s=(r.find(u=>u.isPk)||r[0]).name,c=await ie({message:`Enter the '${s}' of the record you want to edit:`});if(!c.trim()){console.log(w.yellow("Aborted."));return}let i=await ia({message:"Which column do you want to update?",choices:r.map(u=>({name:u.name,value:u.name}))}),l=await ie({message:`New value for '${i}' (leave empty for NULL):`}),m="NULL";l.trim()!==""&&(m=`'${o.escapeString(l)}'`);let p=`UPDATE ${o.quoteIdentifier(t)} SET ${o.quoteIdentifier(i)} = ${m} WHERE ${o.quoteIdentifier(s)} = '${o.escapeString(c)}';`;console.log(w.dim(`
121
+ Executing: `)+w.yellow(p));try{await n.executeSql(p),console.log(w.green("\u2713 Data updated successfully!"))}catch(u){console.log(w.red(`x Failed to update data: ${u.message}`))}}async function Ye(n,a,t,r){let o=j(a);if(console.log(w.cyan(`
122
+ --- Delete Data from [${t}] ---`)),r.length===0)return;let s=(r.find(l=>l.isPk)||r[0]).name,c=await ie({message:`Enter the '${s}' of the record you want to delete:`});if(!c.trim()){console.log(w.yellow("Aborted."));return}let i=`DELETE FROM ${o.quoteIdentifier(t)} WHERE ${o.quoteIdentifier(s)} = '${o.escapeString(c)}';`;console.log(w.dim(`
123
123
  Executing: `)+w.yellow(i));try{await n.executeSql(i),console.log(w.green("\u2713 Data deleted successfully!"))}catch(l){console.log(w.red(`x Failed to delete data: ${l.message}`))}}async function Ge(n){console.log(w.cyan(`
124
- --- Expert Mode: Execute Raw SQL ---`));try{let t=await ie({message:"Enter the path to your .md or .sql file:"});if(t&&t.trim()){let a=ca.resolve(process.cwd(),t.trim()),r="";try{r=await la.readFile(a,"utf-8")}catch(e){console.log(w.red(`
125
- x Failed to read file: ${e.message}`));return}let o=r;if(a.toLowerCase().endsWith(".md")){let e=[...r.matchAll(/```(?:sql)?\n([\s\S]*?)```/gi)];e.length>0&&(o=e.map(s=>s[1].trim()).join(`
124
+ --- Expert Mode: Execute Raw SQL ---`));try{let a=await ie({message:"Enter the path to your .md or .sql file:"});if(a&&a.trim()){let t=ca.resolve(process.cwd(),a.trim()),r="";try{r=await la.readFile(t,"utf-8")}catch(e){console.log(w.red(`
125
+ x Failed to read file: ${e.message}`));return}let o=r;if(t.toLowerCase().endsWith(".md")){let e=[...r.matchAll(/```(?:sql)?\n([\s\S]*?)```/gi)];e.length>0&&(o=e.map(s=>s[1].trim()).join(`
126
126
 
127
127
  `))}if(o.trim()){console.log(w.dim(`
128
128
  Executing SQL...`)),console.log(w.yellow(o));try{await n.executeSql(o),console.log(w.green(`
129
129
  \u2713 SQL executed successfully!`))}catch(e){console.log(w.red(`
130
130
  x Error executing SQL: ${e.message}`))}}else console.log(w.yellow(`
131
131
  \u26A0\uFE0F No SQL found in the file. Aborted.`))}else console.log(w.yellow(`
132
- No file path entered. Aborted.`))}catch(t){console.log(w.red(`
133
- Error: ${t.message}`))}}ve();$e();async function Je(n){let t=h(n),a=!0;for(;a;){console.clear();let r=[],o=0,e="Scanning...";try{r=await t.getTables();for(let i of r)try{let l=n.type==="mysql"?"`":'"',m=await t.query(`SELECT COUNT(*) as count FROM ${l}${i}${l}`);m.rows.length>0&&m.rows[0].count!=null&&(o+=Number(m.rows[0].count))}catch{}e=`${o.toLocaleString()} rows across ${r.length} tables`}catch(i){e=T.red(i.message)}let s=n.targetUrl,c=n.source===".env"?"Loaded from project .env file":n.source==="auto-detected"?"Auto-detected local SQLite file":"Manual connection config";se(` Data Browser & Editor \u2022 [${n.type.toUpperCase()}]`,[{label:"Database",value:n.type.toUpperCase()},{label:"Target",value:s.length>45?"..."+s.slice(-42):s},{label:"Source",value:c},{label:"Total Data",value:e}]);try{if(r.length===0){console.log(T.yellow("No tables found in this database.")),await te(),await t.close();return}let i=[...r.map(f=>({name:f,value:f})),new le,{name:T.dim(" Back"),value:"BACK"}],l=await Ke(i);if(l==="BACK"){a=!1;continue}let m=!0,p=1,u="",d=50;for(;m;){console.clear();let f=(p-1)*d,y=await t.getSchema(l),b=y.map(N=>N.name),x;try{x=await t.getData(l,d,f,u)}catch(N){console.log(T.red(`
132
+ No file path entered. Aborted.`))}catch(a){console.log(w.red(`
133
+ Error: ${a.message}`))}}ve();$e();async function Je(n){let a=h(n),t=!0;for(;t;){console.clear();let r=[],o=0,e="Scanning...";try{r=await a.getTables();for(let i of r)try{let l=n.type==="mysql"?"`":'"',m=await a.query(`SELECT COUNT(*) as count FROM ${l}${i}${l}`);m.rows.length>0&&m.rows[0].count!=null&&(o+=Number(m.rows[0].count))}catch{}e=`${o.toLocaleString()} rows across ${r.length} tables`}catch(i){e=T.red(i.message)}let s=n.targetUrl,c=n.source===".env"?"Loaded from project .env file":n.source==="auto-detected"?"Auto-detected local SQLite file":"Manual connection config";se(` Data Browser & Editor \u2022 [${n.type.toUpperCase()}]`,[{label:"Database",value:n.type.toUpperCase()},{label:"Target",value:s.length>45?"..."+s.slice(-42):s},{label:"Source",value:c},{label:"Total Data",value:e}]);try{if(r.length===0){console.log(T.yellow("No tables found in this database.")),await te(),await a.close();return}let i=[...r.map(f=>({name:f,value:f})),new le,{name:T.dim(" Back"),value:"BACK"}],l=await Ke(i);if(l==="BACK"){t=!1;continue}let m=!0,p=1,u="",d=50;for(;m;){console.clear();let f=(p-1)*d,y=await a.getSchema(l),b=y.map(N=>N.name),x;try{x=await a.getData(l,d,f,u)}catch(N){console.log(T.red(`
134
134
  Error fetching data: ${N.message}
135
135
  `)),u="";let{input:R}=await import("@inquirer/prompts");await R({message:"Click Enter to continue..."});continue}let I=x.rows,Kt=` ${l} (Page ${p}) `;ee(b,I,{title:Kt,maxColWidth:30});let zt=I.length===d,Ht=p>1,we=[{name:"Add Data",value:"add"},{name:"Edit Data",value:"edit"},{name:"Delete Data",value:"delete"},new le,{name:"Search Data",value:"search"},{name:u?"Clear Search":T.dim("Clear Search (disabled)"),value:u?"clear_search":"noop"},new le,{name:"Export to CSV",value:"exportCsv"},{name:"Export to JSON",value:"exportJson"},new le];Ht&&we.push({name:"Previous Page",value:"prev"}),zt&&we.push({name:"Next Page",value:"next"}),we.push({name:T.dim(" Back"),value:"BACK"});let q=await Ze({message:"Select an action for this table:",theme:{prefix:T.cyan("\u2713 "),icon:{cursor:T.cyan("\u203A ")},style:{message:N=>T.bold(T.white(N)),highlight:N=>{let R=N.replace(/\x1b\[[0-9;]*m/g,"");return R.includes(" Back")?T.red(R):T.cyan(R)}}},choices:we});if(q==="prev"){p--;continue}if(q==="next"){p++;continue}if(q==="noop")continue;if(q==="BACK"){m=!1;continue}if(q==="clear_search"){u="",p=1;continue}if(q==="search"){let{input:N}=await import("@inquirer/prompts"),_=(await N({message:"Enter Search (e.g. `age > 18` or `John` for fuzzy search):"})).trim();if(_){if(/[=<>]|LIKE|IN|AND|OR/i.test(_))u=_;else{let G=y.filter(F=>F.type.toLowerCase().includes("char")||F.type.toLowerCase().includes("text"));if(G.length>0){let F=n.type==="postgres"?"ILIKE":"LIKE";u=G.map(Ee=>`"${Ee.name}" ${F} '%${_.replace(/'/g,"''")}%'`).join(" OR ")}else u=`"${y[0].name}" = '${_}'`}p=1}continue}if(q==="exportCsv"||q==="exportJson"){try{console.log(T.yellow(`
136
- Exporting data...`));let R=await t.getData(l,9999999,0,u),_=await import("fs/promises"),be=await import("path"),G=be.join(process.cwd(),"drixio_exports");if(await _.mkdir(G,{recursive:!0}),q==="exportCsv"){let F=R.columns.join(",")+`
136
+ Exporting data...`));let R=await a.getData(l,9999999,0,u),_=await import("fs/promises"),be=await import("path"),G=be.join(process.cwd(),"drixio_exports");if(await _.mkdir(G,{recursive:!0}),q==="exportCsv"){let F=R.columns.join(",")+`
137
137
  `,Oe=R.rows.map(Yt=>R.columns.map(Gt=>`"${String(Yt[Gt]??"").replace(/"/g,'""')}"`).join(",")).join(`
138
138
  `),Ee=be.join(G,`${l}.csv`);await _.writeFile(Ee,F+Oe,"utf-8"),console.log(T.green(`
139
139
  Exported to ${Ee}`))}else{let F=be.join(G,`${l}.json`);await _.writeFile(F,JSON.stringify(R.rows,null,2),"utf-8"),console.log(T.green(`
140
140
  Exported to ${F}`))}}catch(R){console.log(T.red(`
141
- Export Error: ${R.message}`))}let{input:N}=await import("@inquirer/prompts");await N({message:"Click Enter to continue..."});continue}let Me=await Ze({message:`Select mode for ${q} data:`,choices:[{name:"Beginner (Interactive Step-by-Step)",value:"beginner"},{name:"Expert (Load SQL from .sql or .md file)",value:"expert"},new le,{name:T.dim("Cancel"),value:"cancel"}]});if(Me!=="cancel"){if(Me==="expert"){await Ge(t),await te();continue}q==="add"?(await ze(t,n.type,l,y),await te()):q==="edit"?(await He(t,n.type,l,y),await te()):q==="delete"&&(await Ye(t,n.type,l,y),await te())}}}catch(i){console.log(T.red(`
142
- x Error: ${i.message}`)),await te(),a=!1}}await t.close()}async function te(){let{input:n}=await import("@inquirer/prompts");await n({message:"Press Enter to continue..."})}import{select as ma,input as ua}from"@inquirer/prompts";import ae from"picocolors";C();async function Xe(n){let t=await ma({message:"What method you want to use to setup database connection?",choices:[{name:" Auto-Config",value:"auto",description:"Automatically detect and setup database connection (May fail for some cases)."},{name:" Manual Config",value:"manual",description:"Manually setup database connection by entering parameters step by step."}]}),a=n;switch(t){case"auto":let r=await A();r.type!=="unknown"?(a=r,console.log(ae.green(`
141
+ Export Error: ${R.message}`))}let{input:N}=await import("@inquirer/prompts");await N({message:"Click Enter to continue..."});continue}let Me=await Ze({message:`Select mode for ${q} data:`,choices:[{name:"Beginner (Interactive Step-by-Step)",value:"beginner"},{name:"Expert (Load SQL from .sql or .md file)",value:"expert"},new le,{name:T.dim("Cancel"),value:"cancel"}]});if(Me!=="cancel"){if(Me==="expert"){await Ge(a),await te();continue}q==="add"?(await ze(a,n.type,l,y),await te()):q==="edit"?(await He(a,n.type,l,y),await te()):q==="delete"&&(await Ye(a,n.type,l,y),await te())}}}catch(i){console.log(T.red(`
142
+ x Error: ${i.message}`)),await te(),t=!1}}await a.close()}async function te(){let{input:n}=await import("@inquirer/prompts");await n({message:"Press Enter to continue..."})}import{select as ma,input as ua}from"@inquirer/prompts";import ae from"picocolors";C();async function Xe(n){let a=await ma({message:"What method you want to use to setup database connection?",choices:[{name:" Auto-Config",value:"auto",description:"Automatically detect and setup database connection (May fail for some cases)."},{name:" Manual Config",value:"manual",description:"Manually setup database connection by entering parameters step by step."}]}),t=n;switch(a){case"auto":let r=await A();r.type!=="unknown"?(t=r,console.log(ae.green(`
143
143
  Database connection setup successfully.`))):console.log(ae.red(`
144
144
  Failed to auto-detect database connection. Please try manual configuration.`));break;case"manual":let o=await ua({message:"Enter the database connection URL: "});if(o){let e=await A(o);console.log(ae.dim(`
145
- Testing connection...`));try{let s=h(e);await s.getTables(),await s.close(),a=e,await Ue(o),console.log(ae.green("\u2713 Database connection setup successfully and saved to .env!"))}catch(s){console.log(ae.red(`
145
+ Testing connection...`));try{let s=h(e);await s.getTables(),await s.close(),t=e,await Ue(o),console.log(ae.green("\u2713 Database connection setup successfully and saved to .env!"))}catch(s){console.log(ae.red(`
146
146
  x Connection failed: ${s.message}
147
147
  Please enter a valid database URL or check your database status.`))}}else console.log(ae.red(`
148
- Failed to detect database connection. Please enter valid database URL.`));break}return a}import{select as pa,Separator as da}from"@inquirer/prompts";import z from"picocolors";var et=async n=>await pa({message:"Select an action:",theme:{prefix:z.cyan("\u2713 "),icon:{cursor:z.cyan("\u203A ")},style:{message:t=>z.bold(z.white(t)),highlight:t=>{let a=t.replace(/\x1b\[[0-9;]*m/g,"");return a.includes("Exit")?z.red(a):z.cyan(a)}}},choices:[{name:" Data Browser & Editor",value:"editor",description:"View, insert, update, and delete row data in your tables.",disabled:n.type==="unknown"},{name:" Run Raw SQL (REPL)",value:"repl",description:"Execute arbitrary SQL queries interactively.",disabled:n.type==="unknown"},{name:" Table Builder & Manager",value:"table",description:"Create new tables, or modify/drop existing tables.",disabled:n.type==="unknown"},new da,{name:n.type==="unknown"?" Setup Connection":" Connection Settings",value:n.type==="unknown"?"setup":"re-configure",description:n.type==="unknown"?"Setup the database connection manually.":"Re-configure the database connection."},{name:z.dim(" Exit"),value:"exit",description:"Exit the Drixio CLI application."}]});C();ve();import B from"picocolors";async function tt(n){if(n.type==="unknown")return;let t=h(n),a=!0,{input:r}=await import("@inquirer/prompts");for(console.clear(),console.log(B.cyan(`
148
+ Failed to detect database connection. Please enter valid database URL.`));break}return t}import{select as pa,Separator as da}from"@inquirer/prompts";import z from"picocolors";var et=async n=>await pa({message:"Select an action:",theme:{prefix:z.cyan("\u2713 "),icon:{cursor:z.cyan("\u203A ")},style:{message:a=>z.bold(z.white(a)),highlight:a=>{let t=a.replace(/\x1b\[[0-9;]*m/g,"");return t.includes("Exit")?z.red(t):z.cyan(t)}}},choices:[{name:" Data Browser & Editor",value:"editor",description:"View, insert, update, and delete row data in your tables.",disabled:n.type==="unknown"},{name:" Run Raw SQL (REPL)",value:"repl",description:"Execute arbitrary SQL queries interactively.",disabled:n.type==="unknown"},{name:" Table Builder & Manager",value:"table",description:"Create new tables, or modify/drop existing tables.",disabled:n.type==="unknown"},new da,{name:n.type==="unknown"?" Setup Connection":" Connection Settings",value:n.type==="unknown"?"setup":"re-configure",description:n.type==="unknown"?"Setup the database connection manually.":"Re-configure the database connection."},{name:z.dim(" Exit"),value:"exit",description:"Exit the Drixio CLI application."}]});C();ve();import B from"picocolors";async function tt(n){if(n.type==="unknown")return;let a=h(n),t=!0,{input:r}=await import("@inquirer/prompts");for(console.clear(),console.log(B.cyan(`
149
149
  \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557`)),console.log(B.cyan("\u2551 Interactive SQL REPL \u2551")),console.log(B.cyan("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563")),console.log(B.cyan("\u2551 ")+B.dim("Type your SQL queries directly. Type 'exit' or 'quit' to Back.")+" "+B.cyan("\u2551")),console.log(B.cyan(`\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
150
- `));a;)try{let e=(await r({message:B.green(`${n.type}>`)})).trim();if(e.toLowerCase()==="exit"||e.toLowerCase()==="quit"){a=!1;continue}if(e==="")continue;let s=await t.query(e);if(s.columns.length===0){console.log(B.yellow("Query executed successfully. (No output)"));continue}ee(s.columns,s.rows,{title:"Query Result",maxColWidth:50}),console.log(B.dim(`
151
- (${s.rows.length} rows)`)),console.log()}catch(o){o.name==="ExitPromptError"?a=!1:console.log(B.red(`
150
+ `));t;)try{let e=(await r({message:B.green(`${n.type}>`)})).trim();if(e.toLowerCase()==="exit"||e.toLowerCase()==="quit"){t=!1;continue}if(e==="")continue;let s=await a.query(e);if(s.columns.length===0){console.log(B.yellow("Query executed successfully. (No output)"));continue}ee(s.columns,s.rows,{title:"Query Result",maxColWidth:50}),console.log(B.dim(`
151
+ (${s.rows.length} rows)`)),console.log()}catch(o){o.name==="ExitPromptError"?t=!1:console.log(B.red(`
152
152
  Error: ${o.message}
153
- `))}}import{parseArgs as to}from"util";async function Qt(){let n=process.argv.slice(2),t;n.length>0&&(n[0].startsWith("postgres://")||n[0].startsWith("postgresql://")||n[0].startsWith("mysql://")||n[0].startsWith("file:"))&&(t=n[0]);let{positionals:a,values:r}=to({args:n,options:{format:{type:"string"},"schema-only":{type:"boolean"},table:{type:"string"},help:{type:"boolean"}},strict:!1,allowPositionals:!0});r.help&&(console.log(D.cyan(`
153
+ `))}}import{parseArgs as ao}from"util";async function Qt(){let n=process.argv.slice(2),a;n.length>0&&(n[0].startsWith("postgres://")||n[0].startsWith("postgresql://")||n[0].startsWith("mysql://")||n[0].startsWith("file:"))&&(a=n[0]);let{positionals:t,values:r}=ao({args:n,options:{format:{type:"string"},"schema-only":{type:"boolean"},table:{type:"string"},help:{type:"boolean"}},strict:!1,allowPositionals:!0});r.help&&(console.log(D.cyan(`
154
154
  Drixio CLI - Modern Database Manager
155
155
  `)),console.log(`${D.bold("Usage:")} npx drixio [command] [options]
156
156
  `),console.log(`${D.bold("Commands:")}`),console.log(` ${D.green("query")} "<sql>" Run a quick SQL query`),console.log(` ${D.green("exec")} <file.sql> Execute a SQL script file`),console.log(` ${D.green("export")} [table] Export table(s) to CSV/JSON`),console.log(` ${D.green("import")} [file] Import JSON/CSV into a table`),console.log(` ${D.green("seed")} [table] [count] Generate fake data for a table`),console.log(` ${D.green("diagram")} Generate a Mermaid ER diagram`),console.log(` ${D.green("generate-types")} Generate TypeScript interfaces`),console.log(` ${D.green("backup")} Backup the entire database`),console.log(` ${D.green("studio")} Launch the Web UI Studio`),console.log(` ${D.green("init")} [db_type] Initialize a local database & .env`),console.log(` ${D.green("drop-db")} [db_type] Drop a local database`),console.log(`
157
157
  ${D.bold("Options:")}`),console.log(" --help Show this help message"),console.log(" --format <type> Specify export format (csv|json)"),console.log(" --schema-only Export schema without data"),console.log(" --table <name> Specify table for import"),console.log(`
158
- If you don't provide a command, Drixio will launch the Interactive UI!`),process.exit(0));let o=t?void 0:a[0];if(o==="query"){let{runQueryCommand:i}=await Promise.resolve().then(()=>(ot(),at)),l=await A();await i(l,a.slice(1));return}if(o==="export"){let{runExportCommand:i}=await Promise.resolve().then(()=>(st(),nt)),l=await A();await i(l,a.slice(1),r);return}if(o==="studio"){let{runStudio:i}=await Promise.resolve().then(()=>(mt(),ct)),l=await A();await i(l);return}if(o==="backup"){let{runBackupCommand:i}=await Promise.resolve().then(()=>(pt(),ut)),l=await A();await i(l);return}if(o==="import"){let{runImportCommand:i}=await Promise.resolve().then(()=>(ft(),gt)),l=await A();await i(l,a.slice(1),r);return}if(o==="seed"){let{runSeedCommand:i}=await Promise.resolve().then(()=>(ht(),yt)),l=await A();await i(l,a.slice(1));return}if(o==="diagram"){let{runDiagramCommand:i}=await Promise.resolve().then(()=>(bt(),wt)),l=await A();await i(l);return}if(o==="exec"){let{runExecCommand:i}=await Promise.resolve().then(()=>(St(),$t)),l=await A();await i(l,a.slice(1));return}if(o==="generate-types"){let{runGenerateTypesCommand:i}=await Promise.resolve().then(()=>(Tt(),xt)),l=await A();await i(l);return}if(o==="init"){let{runInitCommand:i}=await Promise.resolve().then(()=>(vt(),Ct));await i(a.slice(1));return}if(o==="drop-db"){let{runDropDbCommand:i}=await Promise.resolve().then(()=>(qt(),At));await i(a.slice(1));return}let e=!0,s=await A(t);for(;e;)switch(console.clear(),_e(),Fe(s),await et(s)){case"editor":s.type==="unknown"?(console.log(D.yellow(`
158
+ If you don't provide a command, Drixio will launch the Interactive UI!`),process.exit(0));let o=a?void 0:t[0];if(o==="query"){let{runQueryCommand:i}=await Promise.resolve().then(()=>(ot(),at)),l=await A();await i(l,t.slice(1));return}if(o==="export"){let{runExportCommand:i}=await Promise.resolve().then(()=>(st(),nt)),l=await A();await i(l,t.slice(1),r);return}if(o==="studio"){let{runStudio:i}=await Promise.resolve().then(()=>(mt(),ct)),l=await A();await i(l);return}if(o==="backup"){let{runBackupCommand:i}=await Promise.resolve().then(()=>(pt(),ut)),l=await A();await i(l);return}if(o==="import"){let{runImportCommand:i}=await Promise.resolve().then(()=>(ft(),gt)),l=await A();await i(l,t.slice(1),r);return}if(o==="seed"){let{runSeedCommand:i}=await Promise.resolve().then(()=>(ht(),yt)),l=await A();await i(l,t.slice(1));return}if(o==="diagram"){let{runDiagramCommand:i}=await Promise.resolve().then(()=>(bt(),wt)),l=await A();await i(l);return}if(o==="exec"){let{runExecCommand:i}=await Promise.resolve().then(()=>(St(),$t)),l=await A();await i(l,t.slice(1));return}if(o==="generate-types"){let{runGenerateTypesCommand:i}=await Promise.resolve().then(()=>(Tt(),xt)),l=await A();await i(l);return}if(o==="init"){let{runInitCommand:i}=await Promise.resolve().then(()=>(vt(),Ct));await i(t.slice(1));return}if(o==="drop-db"){let{runDropDbCommand:i}=await Promise.resolve().then(()=>(qt(),At));await i(t.slice(1));return}let e=!0,s=await A(a);for(;e;)switch(console.clear(),_e(),Fe(s),await et(s)){case"editor":s.type==="unknown"?(console.log(D.yellow(`
159
159
  No database connection found. Please run ${D.bold("drixio check")} first.`)),await c()):await Je(s);break;case"table":let{runTableManagerFlow:l}=await Promise.resolve().then(()=>(Vt(),jt));await l(s);break;case"repl":await tt(s);break;case"setup":case"re-configure":s=await Xe(s),await c();break;case"exit":e=!1,console.log(D.dim(`
160
160
  Thanks for using Drixio. Goodbye!`));break}async function c(){let{input:i}=await import("@inquirer/prompts");await i({message:"Click Enter to continue..."})}}Qt().catch(n=>{n.name==="ExitPromptError"&&(console.log(`
161
161
  Exit Drixio.`),process.exit(0)),console.error(`
@@ -0,0 +1,126 @@
1
+ (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e=`<header>\r
2
+ <div id="current-path">\r
3
+ <span id="db-name">database</span>\r
4
+ <span id="slash">/</span>\r
5
+ <div id="current-table">\r
6
+ <span class="material-symbols-outlined" id="table-icon"> table </span>\r
7
+ <span id="table-name">users</span>\r
8
+ </div>\r
9
+ </div>\r
10
+ </header>\r
11
+ `,t=`<aside>\r
12
+ <div id="sidebar-header">\r
13
+ <span class="material-symbols-outlined" id="database-icon"> database </span>\r
14
+ <h1 id="brand-title">\r
15
+ DRIXIO\r
16
+ <p id="brand-subtitle">STUDIO</p>\r
17
+ </h1>\r
18
+ </div>\r
19
+ \r
20
+ <div id="sidebar-content">\r
21
+ <div id="search-bar">\r
22
+ <span class="material-symbols-outlined" id="search-icon"> search </span>\r
23
+ <input type="text" placeholder="Search" id="search-input" />\r
24
+ </div>\r
25
+ \r
26
+ <nav id="table-nav">\r
27
+ <!-- Display All Table -->\r
28
+ </nav>\r
29
+ </div>\r
30
+ \r
31
+ <div id="sidebar-footer">\r
32
+ <button id="setting-btn">Settings</button>\r
33
+ </div>\r
34
+ </aside>\r
35
+ `,n=`<nav id="tab-nav">\r
36
+ <button\r
37
+ type="button"\r
38
+ class="tab-btn"\r
39
+ onclick="handleSwitchTab('data-btn')"\r
40
+ id="data-btn"\r
41
+ >\r
42
+ <span class="material-symbols-outlined" id="data-icon"> table_rows </span>\r
43
+ Data\r
44
+ </button>\r
45
+ <button\r
46
+ class="tab-btn"\r
47
+ onclick="handleSwitchTab('schema-btn')"\r
48
+ id="schema-btn"\r
49
+ >\r
50
+ <span class="material-symbols-outlined" id="schema-icon">\r
51
+ grid_layout_side\r
52
+ </span>\r
53
+ Schema (Structure)\r
54
+ </button>\r
55
+ <button class="tab-btn" onclick="handleSwitchTab('erd-btn')" id="erd-btn">\r
56
+ <span class="material-symbols-outlined" id="erd-icon"> schema </span>\r
57
+ ERD Visualization\r
58
+ </button>\r
59
+ <button class="tab-btn" onclick="handleSwitchTab('sql-btn')" id="sql-btn">\r
60
+ <span class="material-symbols-outlined" id="sql-icon"> code </span>\r
61
+ SQL Console\r
62
+ </button>\r
63
+ </nav>\r
64
+ `;async function r(){return await(await fetch(`/api/tables`)).json()}async function i(){return await(await fetch(`/api/tables/stats`)).json()}async function a(e,t={}){let{where:n=``,limit:r=50,offset:i=0,orderCol:a,orderAsc:o}=t,s=new URLSearchParams;n&&s.append(`where`,n),s.append(`limit`,r.toString()),s.append(`offset`,i.toString()),a&&(s.append(`orderCol`,a),s.append(`orderAsc`,o===!1?`false`:`true`));let c=`/api/tables/${e}/data?${s.toString()}`;return await(await fetch(c)).json()}async function o(e){return await(await fetch(`/api/tables/${e}/schema`)).json()}async function s(e){return await(await fetch(`/api/query`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({sql:e})})).json()}async function c(){try{let e=await r(),t=document.getElementById(`table-nav`),n=document.getElementById(`not-found-msg`);n&&n.remove(),e.success&&e.data&&e.data.length>0?(e.data.forEach(e=>{let n=document.createElement(`button`);n.type=`button`,n.className=`table-btn`,n.innerHTML=`<span>${e}</span><span class="table-btn-badge" id="badge-${e}" style="display:none;"></span>`,n.onclick=()=>{window.AppState.currentTable=e,window.AppState.currentTableBtnElement=n,window.renderCurrentView()},t.appendChild(n)}),window.handleSwitchTab(`data-btn`),i().then(e=>{e.success&&e.data&&Object.entries(e.data).forEach(([e,t])=>{let n=document.getElementById(`badge-${e}`);n&&(n.textContent=Number(t).toLocaleString(),n.style.display=`inline-flex`)})}).catch(e=>console.error(`Failed to load table stats:`,e))):(t.innerHTML=`<div id="not-found-msg">No Tables Found.</div>`,window.handleSwitchTab(`data-btn`))}catch(e){console.error(`Failed to fetch tables:`,e)}}async function l(){if(!window.DataGrid)return;let{pendingEdits:e,pendingInserts:t,pkColumn:n}=window.DataGrid,r=window.AppState.currentTable;if(!r||!n){alert(`Cannot save: No Primary Key detected for this table.`);return}let i=[];for(let[t,a]of Object.entries(e)){if(Object.keys(a).length===0)continue;let e=Object.entries(a).map(([e,t])=>t===``?`"${e}" = NULL`:`"${e}" = '${t.replace(/'/g,`''`)}'`).join(`, `);i.push(`UPDATE "${r}" SET ${e} WHERE "${n}" = '${t.replace(/'/g,`''`)}';`)}for(let e=0;e<t.length;e++){let n=t[e];if(Object.keys(n).length===0||!Object.values(n).some(e=>e!==``))continue;let a=Object.keys(n),o=a.map(e=>{let t=n[e];return t===``?`NULL`:`'${t.replace(/'/g,`''`)}'`});i.push(`INSERT INTO "${r}" ("${a.join(`", "`)}") VALUES (${o.join(`, `)});`)}if(window.DataGrid.pendingDeletes)for(let e of window.DataGrid.pendingDeletes)i.push(`DELETE FROM "${r}" WHERE "${n}" = '${e.replace(/'/g,`''`)}';`);if(i.length===0)return;let a=!0,o=``;for(let e of i)try{let t=await s(e);if(!t.success){a=!1,o=t.error;break}}catch(e){a=!1,o=e.message;break}a?window.renderCurrentView():(alert(`Save failed:
65
+ `+o),document.querySelectorAll(`.cell-edited`).forEach(e=>{e.classList.remove(`cell-edited`),e.classList.add(`cell-error`)}))}function u(e,t,n,r=!0){if(r&&window.DataGrid.currentTransaction){let n=e.textContent;(n===`null`||e.classList.contains(`ghost-row`))&&(n=``),n!==t&&window.DataGrid.currentTransaction.push({td:e,oldVal:n,newVal:t})}let i=e.dataset.col;if(e.innerHTML=t||(e.dataset.insertIndex===void 0?`<em>null</em>`:`+ New`),e.dataset.insertIndex!==void 0){let r=parseInt(e.dataset.insertIndex);if(window.DataGrid.pendingInserts[r]||(window.DataGrid.pendingInserts[r]={}),t&&(window.DataGrid.pendingInserts[r][i]=t,e.classList.add(`cell-edited`),e.classList.remove(`ghost-row`),r===window.DataGrid.pendingInserts.length-1)){window.DataGrid.pendingInserts.push({});let t=document.querySelector(`#data-grid-table tbody`),i=document.createElement(`tr`);i.className=`ghost-row-tr`;let a=parseInt(e.dataset.rowIdx)+1;i.innerHTML+=`<td class="row-header" data-row-idx="${a}">*</td>`,n.forEach((e,t)=>{i.innerHTML+=`<td class="data-cell ghost-row" data-row-idx="${a}" data-col-idx="${t}" data-insert-index="${r+1}" data-col="${e}">+ New</td>`}),t.appendChild(i)}}else{let n=e.dataset.pk;t===e.dataset.original?(e.classList.remove(`cell-edited`),e.classList.remove(`cell-error`),window.DataGrid.pendingEdits[n]&&delete window.DataGrid.pendingEdits[n][i]):(window.DataGrid.pendingEdits[n]||(window.DataGrid.pendingEdits[n]={}),window.DataGrid.pendingEdits[n][i]=t,e.classList.add(`cell-edited`),e.classList.remove(`cell-error`))}}function d(){document.querySelectorAll(`.cell-in-range, .cell-selected, .range-top, .range-bottom, .range-left, .range-right`).forEach(e=>{e.classList.remove(`cell-in-range`,`cell-selected`,`range-top`,`range-bottom`,`range-left`,`range-right`)});let e=window.DataGrid.selection;if(e.startRow===-1)return;let t=Math.min(e.startRow,e.endRow),n=Math.max(e.startRow,e.endRow),r=Math.min(e.startCol,e.endCol),i=Math.max(e.startCol,e.endCol);document.querySelectorAll(`td.data-cell`).forEach(a=>{let o=parseInt(a.dataset.rowIdx),s=parseInt(a.dataset.colIdx);o>=t&&o<=n&&s>=r&&s<=i&&(a.classList.add(`cell-in-range`),o===t&&a.classList.add(`range-top`),o===n&&a.classList.add(`range-bottom`),s===r&&a.classList.add(`range-left`),s===i&&a.classList.add(`range-right`),o===e.startRow&&s===e.startCol&&(a.classList.add(`cell-selected`),window.DataGrid.selectedCell=a))})}function f(e,t){e.addEventListener(`mousedown`,e=>{if(e.target.tagName===`INPUT`||e.target.tagName===`SELECT`)return;let n=e.target.closest(`td.row-header`);if(n){let e=parseInt(n.dataset.rowIdx);window.DataGrid.selection={isDragging:!1,startRow:e,endRow:e,startCol:0,endCol:t-1},d();return}let r=e.target.closest(`td.data-cell`);if(!r)return;let i=parseInt(r.dataset.rowIdx),a=parseInt(r.dataset.colIdx);window.DataGrid.selection={isDragging:!0,startRow:i,startCol:a,endRow:i,endCol:a},d()}),e.addEventListener(`mouseover`,e=>{if(!window.DataGrid.selection.isDragging)return;let t=e.target.closest(`td.data-cell`);t&&(window.DataGrid.selection.endRow=parseInt(t.dataset.rowIdx),window.DataGrid.selection.endCol=parseInt(t.dataset.colIdx),d())})}function p(e){let t=document.createElement(`div`);t.className=`resizer`,e.appendChild(t),t.addEventListener(`click`,e=>e.stopPropagation()),t.addEventListener(`mousedown`,t=>{t.preventDefault(),t.stopPropagation();let n=t.pageX,r=e.offsetWidth,i=!1,a=t=>{i=!0,window.DataGrid&&(window.DataGrid.isResizing=!0);let a=r+(t.pageX-n);e.style.width=a+`px`,e.style.minWidth=a+`px`,e.style.maxWidth=a+`px`},o=()=>{document.removeEventListener(`mousemove`,a),document.removeEventListener(`mouseup`,o),document.body.style.cursor=``,i&&setTimeout(()=>{window.DataGrid&&(window.DataGrid.isResizing=!1)},100)};document.body.style.cursor=`col-resize`,document.addEventListener(`mousemove`,a),document.addEventListener(`mouseup`,o)})}function m(e,t,n){e.addEventListener(`dblclick`,e=>{let r=e.target.closest(`td.data-cell`);if(!r||r.querySelector(`input, select`))return;let i=r.dataset.col,a=t.find(e=>e.name===i),o=a?.type?.toUpperCase()||``,s=o.includes(`ENUM`),c=o===`DATE`,l=o.includes(`DATETIME`)||o.includes(`TIMESTAMP`),d=o.includes(`BOOL`)||o===`TINYINT(1)`,f=r.textContent===`null`||r.textContent===`+ New`?``:r.textContent,p;if(s){let e=a.type.match(/enum\((.*?)\)/i),t=[];e&&(t=e[1].split(`,`).map(e=>e.trim().replace(/^'|'$/g,``))),p=document.createElement(`select`),t.forEach(e=>{let t=document.createElement(`option`);t.value=e,t.textContent=e,e===f&&(t.selected=!0),p.appendChild(t)})}else if(c)p=document.createElement(`input`),p.type=`date`,p.value=f;else if(l){p=document.createElement(`input`),p.type=`datetime-local`;let e=f.replace(` `,`T`).slice(0,16);p.value=e}else d?(p=document.createElement(`input`),p.type=`checkbox`,p.checked=f===`1`||f.toLowerCase()===`true`):(p=document.createElement(`input`),p.type=`text`,p.value=f);let m=!1,h=()=>{m=!0;let e=document.getElementById(`modal-editor-overlay`),t=document.getElementById(`modal-textarea`),n=document.getElementById(`modal-cancel-btn`),r=document.getElementById(`modal-save-btn`),a=document.getElementById(`modal-title`);a.textContent=`Edit ${i}`,t.value=p.value,e.style.display=`flex`,t.focus();let o=()=>{e.style.display=`none`,r.onclick=null,n.onclick=null,m=!1,p.focus()};n.onclick=o,r.onclick=()=>{p.value=t.value,o(),g()}};if(r.innerHTML=``,r.appendChild(p),o===``||!s&&!c&&!l&&!d){let e=document.createElement(`span`);e.className=`material-symbols-outlined cell-expand-btn`,e.textContent=`open_in_full`,e.onmousedown=e=>e.preventDefault(),e.onclick=()=>h(),r.appendChild(e),p.style.width=`100%`,p.style.paddingRight=`32px`,p.addEventListener(`keydown`,e=>{e.key===`Enter`&&e.shiftKey?(e.preventDefault(),h()):e.key===`Enter`&&p.blur()})}else p.addEventListener(`keydown`,e=>{e.key===`Enter`&&p.blur()});p.focus();let g=()=>{if(m)return;let e=d?p.checked?`1`:`0`:p.value;l&&e&&(e=e.replace(`T`,` `)+`:00`),window.DataGrid.currentTransaction=[],u(r,e,n),window.DataGrid.currentTransaction.length>0&&window.DataGrid.history.push(window.DataGrid.currentTransaction),window.DataGrid.currentTransaction=null};p.addEventListener(`blur`,()=>{setTimeout(()=>{m||g()},100)})})}function h(){let e=document.getElementById(`filter-val`)?.value.trim(),t=document.getElementById(`filter-op`)?.value,n=document.getElementById(`filter-col`)?.value,r=``;if(e||t===`IS NULL`){let i=e;i&&!i.startsWith(`'`)&&!i.endsWith(`'`)&&isNaN(Number(i))&&(i=`'${i.replace(/'/g,`''`)}'`),r=`"${n}" ${t} ${i}`}return r}function g(e,t,n,r){let i=`<td class="row-header" data-row-idx="${t}">${t+1}</td>`,a=n?e[n]:t;return r.forEach((n,r)=>{let o=e[n]===null?`null`:String(e[n]),s=o.replace(/"/g,`&quot;`),c=o===`null`?`<em>null</em>`:o.replace(/</g,`&lt;`);i+=`<td class="data-cell" data-row-idx="${t}" data-col-idx="${r}" data-pk="${a}" data-col="${n}" data-original="${s}">${c}</td>`}),i}async function _(e,t,n=``,r=!1){document.querySelectorAll(`.table-btn`).forEach(e=>e.classList.remove(`active`)),t&&t.classList.add(`active`);let i=document.getElementById(`table-name`);i&&(i.textContent=e);let s=document.getElementById(`main-content`);s.innerHTML=`<div style='padding:24px;'>Loading...</div>`;try{let i=await o(e);if(!i.success)throw Error(i.error);let c=i.data,l=c.find(e=>e.isPk)?.name;(!r||!window.DataGrid)&&(window.DataGrid={schema:c,pkColumn:l,pendingEdits:{},pendingInserts:[{}],pendingDeletes:new Set,selectedCell:null,history:[],currentTransaction:null,sortState:{col:l||c[0].name,asc:!0},pagination:{limit:50,offset:0,isLoading:!1,hasMore:!0},selection:{isDragging:!1,startRow:-1,startCol:-1,endRow:-1,endCol:-1}});let u=await a(e,{where:n,limit:window.DataGrid.pagination.limit,offset:window.DataGrid.pagination.offset,orderCol:window.DataGrid.sortState.col,orderAsc:window.DataGrid.sortState.asc});if(u.success&&u.data){let r=u.data.rows,i=u.data.columns;window.DataGrid.pagination.hasMore=r.length===window.DataGrid.pagination.limit;let a=`
66
+ <div class="toolbar">
67
+ <div class="filter-group">
68
+ <div class="filter-icon-container">
69
+ <span class="material-symbols-outlined" id="filter-icon">filter_list</span>
70
+ <span>Filter</span>
71
+ </div>
72
+ <select id="filter-col" class="filter-select">${i.map(e=>`<option value="${e}">${e}</option>`).join(``)}</select>
73
+ <select id="filter-op" class="filter-select">
74
+ <option value="=">=</option>
75
+ <option value=">">></option>
76
+ <option value="<"><</option>
77
+ <option value=">=">>=</option>
78
+ <option value="<="><=</option>
79
+ <option value="LIKE">LIKE</option>
80
+ <option value="!=">!=</option>
81
+ </select>
82
+ <input type="text" id="filter-val" class="filter-input" placeholder="Enter value..." />
83
+ </div>
84
+ <button id="btn-run-query"><span class="material-symbols-outlined">check</span> Apply</button>
85
+ ${n?`<button id="btn-clear-query"><span class="material-symbols-outlined">close</span> Clear</button>`:``}
86
+ <button id="btn-refresh-data" title="Refresh Data (F5)"><span class="material-symbols-outlined">refresh</span></button>
87
+ </div>
88
+ `;a+=`<div class="table-container" id="data-grid-container"><table class="data-table" id="data-grid-table"><thead><tr>`,a+=`<th class="row-header">#</th>`,i.forEach(e=>{let t=c.find(t=>t.name===e),n=``,r=``;t&&(t.isPk&&(n=` <span style="opacity:0.5; font-size:10px;">(PK)</span>`),t.name.toLowerCase().includes(`id`)&&!t.isPk&&(n=` <span style="opacity:0.5; font-size:10px;">(FK)</span>`),r=`<br><span style="font-weight:normal; opacity:0.7; font-size:10px; font-family:monospace;">${t.type}</span>`);let i=``;window.DataGrid.sortState.col===e&&(i=window.DataGrid.sortState.asc?`▲`:`▼`),a+=`<th class="sortable" data-col="${e}" style="cursor:pointer; user-select:none;">
89
+ <div style="display: flex; justify-content: space-between; align-items: center;">
90
+ <div>${e}${n}${r}</div>
91
+ <div class="sort-arrow" style="font-size:10px; opacity:0.8; margin-left: 8px; width: 12px; text-align: right;">${i}</div>
92
+ </div>
93
+ </th>`}),a+=`</tr></thead><tbody>`,r&&r.length>0&&r.forEach((e,t)=>{a+=`<tr>${g(e,t,l,i)}</tr>`}),a+=`<tr class="ghost-row-tr">`;let o=r?r.length:0;a+=`<td class="row-header" data-row-idx="${o}">*</td>`,i.forEach((e,t)=>{a+=`<td class="data-cell ghost-row" data-row-idx="${o}" data-col-idx="${t}" data-insert-index="0" data-col="${e}">+ New</td>`}),a+=`</tr></tbody></table></div>`,s.innerHTML=a;let d=document.getElementById(`data-grid-container`);document.querySelectorAll(`th.sortable`).forEach(n=>{n.onclick=r=>{if(window.DataGrid&&window.DataGrid.isResizing)return;if(Object.keys(window.DataGrid.pendingEdits).length>0||window.DataGrid.pendingInserts.length>1||window.DataGrid.pendingDeletes.size>0){alert(`你有未儲存的變更!因為分頁與排序需要向資料庫重新載入資料,請先按下 Ctrl+S 儲存變更,然後再點擊排序。`);return}let i=n.dataset.col;window.DataGrid.sortState.col===i?window.DataGrid.sortState.asc=!window.DataGrid.sortState.asc:(window.DataGrid.sortState.col=i,window.DataGrid.sortState.asc=!0),window.DataGrid.pagination.offset=0,_(e,t,h(),!0)},p(n)}),f(d,i.length),m(d,c,i);let v=document.getElementById(`btn-run-query`),y=document.getElementById(`btn-clear-query`),b=document.getElementById(`filter-val`),x=(n=!0)=>{n&&window.DataGrid&&(window.DataGrid.pagination.offset=0);let r=b?.value.trim(),i=document.getElementById(`filter-op`)?.value;!r&&i!==`IS NULL`||_(e,t,h(),!0)};v&&(v.onclick=()=>x(!0)),b&&b.addEventListener(`keydown`,e=>{e.key===`Enter`&&x(!0)}),y&&(y.onclick=()=>_(e,t,``,!0));let S=()=>{(Object.keys(window.DataGrid.pendingEdits).length>0||window.DataGrid.pendingInserts.length>1||window.DataGrid.pendingDeletes.size>0)&&!confirm(`你有未儲存的變更!如果重新整理,這些變更將會遺失。確定要捨棄變更並重新整理嗎?`)||x(!1)},C=document.getElementById(`btn-refresh-data`);C&&(C.onclick=S),window.DataGrid.refreshData=S}else s.innerHTML=`<div style="padding:24px; color:red;">Error: ${u.error}</div>`}catch(e){s.innerHTML=`<div style="padding:24px; color:red;">Failed to load data: ${e.message}</div>`}}async function v(e,t){document.querySelectorAll(`.table-btn`).forEach(e=>e.classList.remove(`active`)),t&&t.classList.add(`active`);let n=document.getElementById(`table-name`);n&&(n.textContent=e+` (Schema)`);let r=document.getElementById(`main-content`);r.innerHTML=`<div style='padding:24px;'>Loading Schema...</div>`;try{let t=await o(e);if(t.success&&t.data){let e=t.data;if(e.length===0){r.innerHTML=`<div style='padding:24px;'>No schema found.</div>`;return}let n=`<div class="table-container"><table class="data-table"><thead><tr>`;[`Name`,`Type`,`Nullable`,`Primary Key`].forEach(e=>n+=`<th>${e}</th>`),n+=`</tr></thead><tbody>`,e.forEach(e=>{n+=`<tr>
94
+ <td><strong>${e.name}</strong></td>
95
+ <td><code>${e.type}</code></td>
96
+ <td>${e.nullable?`Yes`:`No`}</td>
97
+ <td>${e.isPk?`Yes`:`No`}</td>
98
+ </tr>`}),n+=`</tbody></table></div>`,r.innerHTML=n}else r.innerHTML=`<div style="padding:24px; color:red;">Error: ${t.error}</div>`}catch(e){r.innerHTML=`<div style="padding:24px; color:red;">Failed to load schema: ${e.message}</div>`}}function y(e,t){document.querySelectorAll(`.table-btn`).forEach(e=>e.classList.remove(`active`)),t&&t.classList.add(`active`);let n=document.getElementById(`table-name`);n&&(n.textContent=`SQL Console`);let r=document.getElementById(`main-content`);r.innerHTML=`
99
+ <div id="console-container" style="display: flex; flex-direction: column; flex: 1; height: 100%; min-width: 0;">
100
+ <div id="console-editor-pane" style="flex: 1; display: flex; flex-direction: column; border-bottom: 1px solid var(--color-border); position: relative; min-height: 200px;">
101
+ <div id="sql-editor" style="flex: 1; font-size: 14px;"></div>
102
+ <button id="run-sql-btn" class="primary" style="position: absolute; bottom: 16px; right: 24px; padding: 8px 16px; border-radius: 6px; border: none; background-color: var(--color-primary); color: #fff; font-weight: 600; cursor: pointer; box-shadow: 0 4px 6px rgba(0,0,0,0.1); z-index: 50; display: flex; align-items: center; gap: 6px; transition: all 0.2s;">
103
+ <span class="material-symbols-outlined" style="font-size: 18px;">play_arrow</span> Run (Ctrl+Enter)
104
+ </button>
105
+ </div>
106
+ <div id="console-results-pane" style="flex: 1; display: flex; flex-direction: column; overflow: hidden; background: #fff; min-height: 200px;">
107
+ <div id="console-results-header" style="padding: 8px 16px; background-color: var(--color-bg-secondary); border-bottom: 1px solid var(--color-border); font-size: 12px; color: var(--color-text-soft); font-weight: 600;">RESULTS</div>
108
+ <div class="table-container" id="console-table-container" style="flex: 1;">
109
+ <div style="padding: 24px; color: var(--color-text-soft); text-align: center; font-size: 14px;">Run a query to see results.</div>
110
+ </div>
111
+ </div>
112
+ </div>
113
+ `;let i=window.ace.edit(`sql-editor`);i.setTheme(`ace/theme/chrome`),i.session.setMode(`ace/mode/sql`),i.setOptions({showPrintMargin:!1,fontSize:`14px`,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace`,highlightActiveLine:!0}),window.AppState.lastQuery?i.setValue(window.AppState.lastQuery,1):i.setValue(`-- Enter your SQL query here
114
+ SELECT * FROM sqlite_master;
115
+ `,1),i.focus();let a=async()=>{let e=i.getValue().trim();if(!e)return;window.AppState.lastQuery=e;let t=document.getElementById(`console-table-container`),n=document.getElementById(`console-results-header`);n.textContent=`EXECUTING...`,n.style.color=`var(--color-primary)`,t.innerHTML=`<div style="padding: 24px; text-align: center; color: var(--color-text-soft);">Executing query...</div>`;try{let r=await s(e);if(!r.success){n.textContent=`ERROR`,n.style.color=`red`,t.innerHTML=`<div style="padding: 24px; color: red; font-family: monospace; white-space: pre-wrap;">${r.error}</div>`;return}let i=r.data.rows||[];if(n.textContent=`SUCCESS - ${i.length} rows returned`,n.style.color=`green`,i.length===0){t.innerHTML=`<div style="padding: 24px; text-align: center; color: var(--color-text-soft);">0 rows returned.</div>`;return}let a=Object.keys(i[0]),o=document.createElement(`table`);o.className=`data-table`;let c=document.createElement(`thead`),l=document.createElement(`tr`),u=document.createElement(`th`);u.className=`row-header`,u.textContent=`#`,l.appendChild(u),a.forEach(e=>{let t=document.createElement(`th`);t.textContent=e;let n=document.createElement(`div`);n.className=`resizer`,t.appendChild(n),n.addEventListener(`click`,e=>e.stopPropagation()),n.addEventListener(`mousedown`,e=>{e.preventDefault(),e.stopPropagation();let n=e.pageX,r=t.offsetWidth,i=e=>{let i=r+(e.pageX-n);t.style.width=i+`px`,t.style.minWidth=i+`px`,t.style.maxWidth=i+`px`},a=()=>{document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a),document.body.style.cursor=``};document.body.style.cursor=`col-resize`,document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)}),l.appendChild(t)}),c.appendChild(l),o.appendChild(c);let d=document.createElement(`tbody`);i.forEach((e,t)=>{let n=document.createElement(`tr`),r=document.createElement(`td`);r.className=`row-header`,r.textContent=t+1,n.appendChild(r),a.forEach(t=>{let r=document.createElement(`td`),i=e[t];if(i===null){let e=document.createElement(`span`);e.textContent=`NULL`,e.style.color=`var(--color-text-soft)`,e.style.fontStyle=`italic`,r.appendChild(e)}else r.textContent=String(i);n.appendChild(r)}),d.appendChild(n)}),o.appendChild(d),t.innerHTML=``,t.appendChild(o)}catch(e){n.textContent=`ERROR`,n.style.color=`red`,t.innerHTML=`<div style="padding: 24px; color: red; font-family: monospace; white-space: pre-wrap;">${e.message}</div>`}};document.getElementById(`run-sql-btn`).onclick=a,i.commands.addCommand({name:`run`,bindKey:{win:`Ctrl-Enter`,mac:`Command-Enter`},exec:function(){a()}})}var b=document.getElementById(`header-container`),x=document.getElementById(`sidebar-container`),S=document.getElementById(`tab-container`);b.innerHTML=e,x.innerHTML=t,S.innerHTML=n,window.AppState={currentTable:null,currentTab:`data-btn`,currentTableBtnElement:null},window.handleSwitchTab=function(e){document.querySelectorAll(`.tab-btn`).forEach(e=>e.classList.remove(`isCurrentTab`));let t=document.getElementById(e);t&&t.classList.add(`isCurrentTab`),window.AppState.currentTab=e,window.renderCurrentView()},window.renderEmptyState=function(){let e=document.getElementById(`main-content`);e.innerHTML=`
116
+ <div class="empty-state">
117
+ <span class="material-symbols-outlined">database</span>
118
+ <h2>No Table Selected</h2>
119
+ <p>Select a table from the sidebar to view its data, schema, or run SQL queries.</p>
120
+ </div>
121
+ `},window.renderCurrentView=function(e=``,t=!1){if(!window.AppState.currentTable){window.renderEmptyState();return}if(window.AppState.currentTab===`data-btn`)_(window.AppState.currentTable,window.AppState.currentTableBtnElement,e,t);else if(window.AppState.currentTab===`schema-btn`)v(window.AppState.currentTable,window.AppState.currentTableBtnElement);else if(window.AppState.currentTab===`console-btn`)y(window.AppState.currentTable,window.AppState.currentTableBtnElement);else if(window.AppState.currentTab===`erd-btn`){let e=document.getElementById(`main-content`);e.innerHTML=`<div style='padding:24px; color: var(--color-text-soft);'>ERD Visualization coming soon!</div>`}},window.saveDataGridEdits=l,document.addEventListener(`DOMContentLoaded`,()=>{c(),document.addEventListener(`mouseup`,()=>{window.DataGrid&&window.DataGrid.selection&&(window.DataGrid.selection.isDragging=!1)}),document.addEventListener(`contextmenu`,e=>{if(window.AppState?.currentTab!==`data-btn`||!window.DataGrid)return;let t=e.target.closest(`td.row-header`);if(!t)return;e.preventDefault();let n=parseInt(t.dataset.rowIdx);document.getElementById(`custom-context-menu`)?.remove();let r=document.createElement(`div`);r.id=`custom-context-menu`,r.className=`context-menu`,r.style.top=`${e.clientY}px`,r.style.left=`${e.clientX}px`,r.innerHTML=`
122
+ <div class="context-menu-item danger" id="cmenu-delete">
123
+ <span class="material-symbols-outlined" style="font-size:16px;">delete</span> Delete Row
124
+ </div>
125
+ `,document.body.appendChild(r),document.getElementById(`cmenu-delete`).onclick=()=>{window.DataGrid.currentTransaction=[],window.DataGrid.markRowDeleted(n),window.DataGrid.currentTransaction.length>0&&window.DataGrid.history.push(window.DataGrid.currentTransaction),window.DataGrid.currentTransaction=null,r.remove()};let i=e=>{r.contains(e.target)||(r.remove(),document.removeEventListener(`click`,i))};setTimeout(()=>document.addEventListener(`click`,i),0)}),document.addEventListener(`keydown`,e=>{if(e.key===`F5`){window.AppState?.currentTab===`data-btn`&&window.DataGrid?.refreshData&&(e.preventDefault(),window.DataGrid.refreshData());return}if(!(window.AppState?.currentTab!==`data-btn`||!window.DataGrid)&&!(e.target.tagName===`INPUT`||e.target.tagName===`SELECT`||e.target.tagName===`TEXTAREA`)){if((e.key===`Delete`||e.key===`Backspace`)&&(window.DataGrid.currentTransaction=[],document.querySelectorAll(`.cell-in-range`).forEach(e=>{window.DataGrid.updateCell(e,``)}),window.DataGrid.currentTransaction.length>0&&window.DataGrid.history.push(window.DataGrid.currentTransaction),window.DataGrid.currentTransaction=null),e.key.toLowerCase()===`s`&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),window.saveDataGridEdits()),e.key.toLowerCase()===`c`&&(e.ctrlKey||e.metaKey)){let e=window.DataGrid.selection;if(e.startRow===-1)return;let t=Math.min(e.startRow,e.endRow),n=Math.max(e.startRow,e.endRow),r=Math.min(e.startCol,e.endCol),i=Math.max(e.startCol,e.endCol),a=``;for(let e=t;e<=n;e++){let t=[];for(let n=r;n<=i;n++){let r=document.querySelector(`td.data-cell[data-row-idx="${e}"][data-col-idx="${n}"]`);if(r){let e=r.textContent.replace(/^null$|^\+ New$/,``);t.push(e)}}a+=t.join(` `)+`
126
+ `}navigator.clipboard.writeText(a.trimEnd()),document.querySelectorAll(`.cell-in-range`).forEach(e=>{e.style.backgroundColor=`#bfdbfe`,setTimeout(()=>e.style.backgroundColor=``,150)})}if(e.key===`-`&&(e.ctrlKey||e.metaKey)){e.preventDefault();let t=window.DataGrid.selection;if(t.startRow===-1)return;let n=Math.min(t.startRow,t.endRow),r=Math.max(t.startRow,t.endRow);window.DataGrid.currentTransaction=[];for(let e=n;e<=r;e++)window.DataGrid.markRowDeleted(e);window.DataGrid.currentTransaction.length>0&&window.DataGrid.history.push(window.DataGrid.currentTransaction),window.DataGrid.currentTransaction=null}if(e.key.toLowerCase()===`z`&&(e.ctrlKey||e.metaKey)){e.preventDefault();let t=window.DataGrid.history?.pop();if(t)for(let e=t.length-1;e>=0;e--){let n=t[e];n.type===`delete`?window.DataGrid.unmarkRowDeleted(n.rowIdx,n.pk):window.DataGrid.updateCell(n.td,n.oldVal,!1)}}}}),document.addEventListener(`paste`,e=>{if(window.AppState?.currentTab!==`data-btn`||!window.DataGrid||e.target.tagName===`INPUT`||e.target.tagName===`SELECT`||e.target.tagName===`TEXTAREA`)return;let t=window.DataGrid.selection;if(t.startRow===-1)return;let n=e.clipboardData.getData(`text`);if(!n)return;e.preventDefault();let r=n.split(/\r?\n/).map(e=>e.split(` `)),i=Math.min(t.startRow,t.endRow),a=Math.min(t.startCol,t.endCol);window.DataGrid.currentTransaction=[],r.forEach(e=>{e.forEach((e,t)=>{let n=a+t,r=document.querySelector(`td.data-cell[data-row-idx="${i}"][data-col-idx="${n}"]`);r&&window.DataGrid.updateCell(r,e)}),i++}),window.DataGrid.currentTransaction.length>0&&window.DataGrid.history.push(window.DataGrid.currentTransaction),window.DataGrid.currentTransaction=null})});
@@ -0,0 +1 @@
1
+ @import "https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap";:root{--color-bg-primary:#fff;--color-bg-secondary:#f8fafc;--color-bg-secondary-dark:#f1f5f9;--color-primary:#2c68ec;--color-primary-active:#eff6ff;--color-primary-dark:#285bb8;--color-text:#0f172a;--color-text-soft:#94a3b8;--color-text-secondary:#64748b;--color-border:#e2e8f0;--color-border-soft:#f1f5f9;--ring-primary-2:0 0 0 2px #2c68ec33;--font-inter:"Inter", sans-serif}body,html{background-color:var(--color-bg-primary);width:100vw;height:100vh;color:var(--color-text);font-family:var(--font-inter);margin:0;padding:0;display:flex;overflow:hidden}main{flex-direction:column;flex:1;min-width:0;display:flex}aside{border-right:1px var(--color-border) solid;flex-direction:column;width:256px;height:100vh;display:flex}#sidebar-header{border-bottom:1px var(--color-border-soft) solid;align-items:center;gap:8px;height:64px;padding:0 16px;display:flex}#database-icon{color:var(--color-primary);font-size:26px}#brand-title{letter-spacing:.5px;align-items:center;gap:4px;margin:0;padding:0;font-size:16px;font-weight:bolder;line-height:1;display:flex}#brand-subtitle{background-color:var(--color-primary);color:#fff;border-radius:5px;align-items:center;padding:3px 5px;font-size:10px;font-weight:600;line-height:1;display:flex}#sidebar-content{flex-direction:column;flex:1;gap:24px;padding:16px;display:flex}#search-bar{background-color:var(--color-bg-secondary);border:1px var(--color-border) solid;border-radius:8px;outline:none;align-items:center;padding:0 4px;transition:all .1s linear;display:flex;overflow:hidden}#search-bar:focus-within{border:1px var(--color-primary) solid;box-shadow:var(--ring-primary-2);background-color:#fff;transform:scale(1.02)}#search-icon{color:var(--color-text-soft);margin:0 3px 0 6px;font-size:20px;transition:all .1s linear}#search-bar:focus-within #search-icon{color:var(--color-primary);transform:scale(1.15)}#search-input{background-color:#0000;border:none;outline:none;width:100%;height:34px;font-size:12px}#search-input::placeholder{color:var(--color-text-soft)}#table-nav{flex-direction:column;flex:1;gap:6px;display:flex;overflow-y:auto}#table-nav::-webkit-scrollbar{width:4px}#table-nav::-webkit-scrollbar-track{background:0 0}#table-nav::-webkit-scrollbar-thumb{background:var(--color-border);border-radius:4px}#table-nav::-webkit-scrollbar-thumb:hover{background:var(--color-text-soft)}.table-btn{color:var(--color-text-secondary);cursor:pointer;background-color:#0000;border:1px solid #0000;border-radius:8px;outline:none;justify-content:space-between;align-items:center;padding:10px 16px;font-size:12px;font-weight:500;transition:all .2s;display:flex}.table-btn:hover{background-color:var(--color-bg-secondary);color:var(--color-text)}.table-btn.active{background-color:var(--color-primary-active);border:1px var(--color-primary) solid;color:var(--color-primary);font-weight:600}.table-btn-badge{background-color:var(--color-bg-secondary-dark);color:var(--color-text-secondary);border-radius:10px;place-content:center;min-width:16px;min-height:16px;font-size:8px;font-weight:600;line-height:1;display:flex}.table-btn.active .table-btn-badge{background-color:var(--color-primary);color:#fff}#not-found-msg{color:var(--color-text-soft);flex:1;justify-content:center;align-items:center;font-size:12px;font-weight:400;display:flex}#sidebar-footer{border-top:1px var(--color-border-soft) solid;justify-content:center;align-items:center;padding:16px;display:flex}#setting-btn{background-color:var(--color-bg-secondary);color:var(--color-text-secondary);border:1px var(--color-border) solid;cursor:pointer;border-radius:8px;width:100%;padding:12px 24px;font-weight:600;transition:all .1s linear}#setting-btn:hover{color:var(--color-primary);border:1px var(--color-primary) solid;background-color:var(--color-bg-primary)}header{border-bottom:1px var(--color-border) solid;justify-content:space-between;align-items:center;width:100%;height:64px;padding:0 32px;font-size:14px;font-weight:300;display:flex;position:sticky;top:0}#current-path{text-transform:lowercase;align-items:center;gap:10px;display:flex}#db-name{color:var(--color-text-secondary)}#slash{color:var(--color-text-soft);font-size:18px;font-weight:lighter}#current-table{align-items:center;gap:4px;display:flex}#table-icon{color:var(--color-primary);font-size:20px}#table-name{color:var(--color-text);font-weight:600}#tab-nav{border-bottom:1px var(--color-border) solid;gap:24px;height:48px;padding:0 32px;display:flex}.tab-btn{height:100%;color:var(--color-text-secondary);cursor:pointer;background-color:#0000;border:none;border-bottom:2px solid #0000;outline:none;align-items:center;gap:8px;padding:0 6px;font-size:12px;font-weight:300;line-height:1;transition:all .1s linear;display:flex}.tab-btn:hover{border-bottom:2px var(--color-border) solid;color:var(--color-text)}.tab-btn.isCurrentTab{border-bottom:2px var(--color-primary) solid;color:var(--color-primary)}.tab-btn .material-symbols-outlined{font-size:16px}#main-content{background-color:var(--color-bg-primary);flex-direction:column;flex:1;min-width:0;display:flex;overflow:hidden}.toolbar{border-bottom:1px var(--color-border) solid;background-color:var(--color-bg-secondary);flex-shrink:0;align-items:center;height:48px;display:flex}.filter-group{flex:1;align-items:center;height:100%;transition:all .15s;display:flex;overflow:hidden}.filter-icon-container{background-color:var(--color-bg-secondary);border-right:1px var(--color-border) solid;align-items:center;gap:6px;height:100%;padding:0 16px;font-size:16px;display:flex}.filter-icon-container .material-symbols-outlined{color:var(--color-text-secondary);font-size:18px}.filter-icon-container span:not(.material-symbols-outlined){text-transform:uppercase;color:var(--color-text-secondary);font-size:13px;font-weight:500}.filter-select{height:100%;color:var(--color-text-secondary);border:none;border-right:1px var(--color-border) solid;cursor:pointer;background-color:#0000;outline:none;padding:0 16px;font-size:13px;font-weight:500}.filter-select:hover{background-color:var(--color-bg-secondary)}.filter-input{background:0 0;border:none;outline:none;flex:1;height:100%;padding:0 20px;font-size:13px;font-weight:200}.filter-input::placeholder{color:var(--color-text-soft)}#btn-run-query{background-color:var(--color-primary);color:var(--color-bg-primary);border:none;border-right:1px var(--color-border) solid;cursor:pointer;border-radius:8px;outline:none;justify-content:center;align-items:center;gap:8px;padding:8px 12px;font-size:10px;font-weight:700;transition:all .1s linear;display:flex}#btn-run-query:hover{background-color:var(--color-primary-dark)}#btn-run-query .material-symbols-outlined{margin-bottom:.5px;font-size:16px}#btn-clear-query{background-color:var(--color-bg-primary);color:var(--color-text-secondary);border:none;border:1px var(--color-border) solid;cursor:pointer;border-radius:8px;outline:none;justify-content:center;align-items:center;gap:8px;margin-left:16px;padding:8px 12px;font-size:10px;font-weight:700;transition:all .1s linear;display:flex}#btn-clear-query:hover{background-color:var(--color-bg-secondary-dark);color:var(--color-text)}#btn-run-query:active,#btn-clear-query:active,.btn-primary:active,.btn-secondary:active,.table-btn:active{transform:scale(.96)}#btn-clear-query .material-symbols-outlined{margin-bottom:.5px;font-size:16px}#btn-refresh-data{background-color:var(--color-bg-secondary);border:1px var(--color-border) solid;color:var(--color-text-secondary);cursor:pointer;border-radius:8px;outline:none;justify-content:center;align-items:center;gap:8px;margin:16px;padding:6px;font-size:10px;font-weight:700;transition:all .1s linear;display:flex}#btn-refresh-data:hover{background-color:var(--color-bg-secondary-dark);color:var(--color-text)}#btn-refresh-data .material-symbols-outlined{margin-bottom:.5px;font-size:18px}.sql-console-wrapper{flex-direction:column;height:100%;display:flex}.sql-editor{resize:vertical;border:none;border-bottom:1px var(--color-border) solid;background-color:var(--color-bg-primary);width:100%;height:200px;min-height:100px;color:var(--color-text);outline:none;padding:16px;font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:13px}.sql-editor:focus{background-color:#fcfcfc}.table-container{scrollbar-width:none;-ms-overflow-style:none;background-color:#fff;flex:1;width:100%;min-width:0;overflow:auto}.table-container::-webkit-scrollbar{display:none}.data-table{border-collapse:separate;border-spacing:0;-webkit-user-select:none;user-select:none;width:max-content;min-width:100%}.data-table input,.data-table select{-webkit-user-select:text;user-select:text;box-sizing:border-box}.data-table th,.data-table td{text-align:left;border-bottom:1px var(--color-border-soft) solid;border-right:1px var(--color-border-soft) solid;white-space:nowrap;cursor:cell;height:24px;padding:8px 16px;font-size:13px;position:relative}.data-table th:last-child,.data-table td:last-child{border-color:#2c68ec40}.data-table th{background-color:var(--color-primary);color:var(--color-bg-primary);text-transform:uppercase;letter-spacing:.5px;z-index:10;border-bottom:1px var(--color-border) solid;box-shadow:0 1px 0 var(--color-border);cursor:default;border-right:1px solid #fff3;font-size:11px;font-weight:600;position:sticky;top:0}.data-table td.cell-in-range{--shadow-t:inset 0 0 0 0 transparent;--shadow-b:inset 0 0 0 0 transparent;--shadow-l:inset 0 0 0 0 transparent;--shadow-r:inset 0 0 0 0 transparent;box-shadow:var(--shadow-t), var(--shadow-b), var(--shadow-l), var(--shadow-r);background-color:#dbeafe}.data-table td.range-top{--shadow-t:inset 0 2px 0 0 var(--color-primary)}.data-table td.range-bottom{--shadow-b:inset 0 -2px 0 0 var(--color-primary)}.data-table td.range-left{--shadow-l:inset 2px 0 0 0 var(--color-primary)}.data-table td.range-right{--shadow-r:inset -2px 0 0 0 var(--color-primary)}.data-table td.cell-selected{z-index:5;box-shadow:inset 0 0 0 2px var(--color-primary);background-color:#fff}.data-table td.row-header,.data-table th.row-header{z-index:9;background-color:var(--color-bg-secondary);color:var(--color-text-soft);text-align:center;border-right:1px var(--color-border) solid;width:32px;min-width:32px;padding:8px 4px;font-weight:500;position:sticky;left:0}.data-table th.row-header{z-index:11;background-color:var(--color-primary);color:var(--color-bg-primary)}.data-table td.cell-edited{color:#b45309;background-color:#fffbeb;font-weight:700}.data-table td.cell-error{background-color:#fef2f2}.data-table td.cell-error:not(.cell-in-range):not(.cell-selected){box-shadow:inset 0 0 0 2px #ef4444}.data-table tr.row-deleted td{text-decoration:line-through;color:#ef4444!important;background-color:#fee2e2!important}.data-table td.ghost-row{color:var(--color-text-soft);background-color:#f8fafc;font-style:italic}.data-table td input,.data-table td select{box-sizing:border-box;width:100%;height:100%;box-shadow:var(--ring-primary-2);background-color:#fff;border:none;outline:none;padding:0 16px;font-family:inherit;font-size:13px;position:absolute;top:0;left:0}.data-table tbody tr:hover{background-color:var(--color-bg-secondary)}.context-menu{background-color:var(--color-bg-primary);border:1px var(--color-border) solid;z-index:9999;border-radius:6px;flex-direction:column;min-width:150px;padding:4px;display:flex;position:absolute;box-shadow:0 4px 6px -1px #0000001a,0 2px 4px -2px #0000001a}.context-menu-item{color:var(--color-text);cursor:pointer;border-radius:4px;align-items:center;gap:8px;padding:8px 12px;font-size:13px;display:flex}.context-menu-item:hover{background-color:var(--color-bg-secondary)}.context-menu-item.danger{color:#ef4444}.context-menu-item.danger:hover{background-color:#fef2f2}.resizer{cursor:col-resize;-webkit-user-select:none;user-select:none;z-index:10;width:8px;height:100%;position:absolute;top:0;right:-4px}.resizer:hover,.resizer:active{background-color:var(--color-primary);opacity:.5}.cell-expand-btn{cursor:pointer;color:var(--color-text-soft);border:1px var(--color-border) solid;z-index:10;background-color:#fff;border-radius:4px;justify-content:center;align-items:center;padding:3px;font-size:14px;transition:all .1s;display:flex;position:absolute;top:50%;right:6px;transform:translateY(-50%);box-shadow:0 2px 4px #0000000d}.cell-expand-btn:hover{color:var(--color-primary);border-color:var(--color-primary)}#modal-editor-overlay{-webkit-backdrop-filter:blur(2px);backdrop-filter:blur(2px);z-index:9999;background-color:#0f172a66;justify-content:center;align-items:center;width:100vw;height:100vh;display:flex;position:fixed;top:0;left:0}.modal-editor-container{background-color:var(--color-bg-primary);border-radius:12px;flex-direction:column;width:600px;max-width:90vw;height:500px;max-height:90vh;display:flex;overflow:hidden;box-shadow:0 10px 25px -5px #0000001a,0 8px 10px -6px #0000001a}.modal-header{border-bottom:1px var(--color-border) solid;color:var(--color-text);align-items:center;gap:8px;padding:16px 20px;display:flex}.modal-header h3{margin:0;font-size:16px;font-weight:600}.modal-header .material-symbols-outlined{color:var(--color-primary)}#modal-textarea{resize:none;color:var(--color-text);background-color:var(--color-bg-secondary-dark);border:none;outline:none;flex:1;padding:20px;font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:13px}#modal-textarea:focus{background-color:#fff}.modal-footer{border-top:1px var(--color-border) solid;background-color:var(--color-bg-secondary);justify-content:flex-end;gap:12px;padding:16px 20px;display:flex}.modal-footer button{cursor:pointer;border:1px var(--color-border) solid;color:var(--color-text);background-color:#fff;border-radius:6px;padding:8px 16px;font-size:13px;font-weight:500;transition:all .2s}.modal-footer button:hover{background-color:var(--color-bg-secondary-dark)}.modal-footer button.primary{background-color:var(--color-primary);color:#fff;border-color:var(--color-primary)}.modal-footer button.primary:hover{background-color:var(--color-primary-dark)}
@@ -0,0 +1,43 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <link
7
+ rel="stylesheet"
8
+ href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200"
9
+ />
10
+
11
+ <title>DRIXIO STUDIO</title>
12
+ <!-- Ace Editor for SQL Console -->
13
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.32.7/ace.js" integrity="sha512-V127u0iE/681x9Z+S3Xz/2aQeY6k/Q+TtwO046sA4K8E0KqNqP/n139xJqG1oE31g3m8L7u5T1WwH0tOWePjxw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
14
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.32.7/mode-sql.min.js"></script>
15
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.32.7/theme-chrome.min.js"></script>
16
+ <script type="module" crossorigin src="./assets/index-BMA9iqkf.js"></script>
17
+ <link rel="stylesheet" crossorigin href="./assets/index-D-HpZQEQ.css">
18
+ </head>
19
+
20
+ <body>
21
+ <div id="sidebar-container"></div>
22
+ <main>
23
+ <div id="header-container"></div>
24
+ <div id="tab-container"></div>
25
+ <div id="main-content"></div>
26
+ </main>
27
+
28
+ <div id="modal-editor-overlay" style="display: none;">
29
+ <div class="modal-editor-container">
30
+ <div class="modal-header">
31
+ <span class="material-symbols-outlined">edit_document</span>
32
+ <h3 id="modal-title">Edit Cell</h3>
33
+ </div>
34
+ <textarea id="modal-textarea" placeholder="Enter value..."></textarea>
35
+ <div class="modal-footer">
36
+ <button type="button" id="modal-cancel-btn">Cancel</button>
37
+ <button type="button" id="modal-save-btn" class="primary">Save</button>
38
+ </div>
39
+ </div>
40
+ </div>
41
+
42
+ </body>
43
+ </html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drixio",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "A lightweight interactive TUI database client",
5
5
  "bin": {
6
6
  "drixio": "dist/cli.js"