@unreal-orm/cli 1.0.0-alpha.7 → 1.0.0-alpha.8

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.
Files changed (2) hide show
  1. package/dist/index.js +66 -66
  2. package/package.json +63 -51
package/dist/index.js CHANGED
@@ -1,25 +1,25 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as B2}from"node:module";var $2=Object.create;var{getPrototypeOf:Q2,defineProperty:N0,getOwnPropertyNames:J2}=Object;var X2=Object.prototype.hasOwnProperty;var Z0=($,J,Q)=>{Q=$!=null?$2(Q2($)):{};let X=J||!$||!$.__esModule?N0(Q,"default",{value:$,enumerable:!0}):Q;for(let Z of J2($))if(!X2.call(X,Z))N0(X,Z,{get:()=>$[Z],enumerable:!0});return X};var Z2=($,J)=>{for(var Q in J)N0($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:(X)=>J[Q]=()=>X})};var S0=($,J)=>()=>($&&(J=$($=0)),J);var B0=B2(import.meta.url);class Q1{lineCount=0;log($=""){console.log($),this.lineCount+=$.split(`
3
- `).length}clear(){if(this.lineCount>0)process.stdout.moveCursor(0,-this.lineCount),process.stdout.clearScreenDown(),this.lineCount=0}reset(){this.lineCount=0}}var J1;var X1=S0(()=>{J1=new Q1});import r from"chalk";import Y2 from"ora";var J0,y,Y;var u=S0(()=>{X1();J0={success:"✅",error:"❌",warning:"⚠️",info:"ℹ️",step:"\uD83D\uDD39",arrow:"➜",line:"─",corner:"└─"},y={primary:r.hex("#FF00A0"),secondary:r.cyan,success:r.green,error:r.red,warning:r.yellow,info:r.blue,dim:r.gray,code:r.hex("#E0E0E0"),url:r.underline.cyan},Y={header($,J){if(console.log(""),console.log(y.primary.bold(` ${$} `)),J)console.log(y.dim(` ${J}`));console.log("")},divider(){console.log(y.dim(J0.line.repeat(60)))},success($){console.log(y.success(`${J0.success} ${$}`))},error($,J){if(console.log(y.error(`${J0.error} ${$}`)),J)if(J instanceof Error)console.log(y.dim(` ${J.stack||J.message}`));else console.log(y.dim(` ${String(J)}`))},warn($){console.log(y.warning(`${J0.warning} ${$}`))},info($){console.log(y.info(`${J0.info} ${$}`))},step($,J){console.log(y.secondary(`${J0.step} ${$}`)+(J?y.dim(` ${J}`):""))},spin($){return Y2({text:$,color:"cyan",spinner:"dots"}).start()},code($){return y.code($)},cmd($){return y.code(`$ ${$}`)},link($,J){return y.url(J||$)},dim($){return y.dim($)},bold($){return r.bold($)},newline(){console.log("")},get printer(){return J1},theme:y,symbols:J0}});var G1={};Z2(G1,{promptText:()=>M0,promptSelectWithDisabled:()=>T0,promptSelect:()=>k0,promptForConnection:()=>E0,promptFileReview:()=>U0,confirm:()=>z2});import Y0 from"prompts";async function E0($){let J=$.embedded,Q=await Y0([{type:!J&&!$.url?"text":null,name:"url",message:"Database URL:",initial:"http://localhost:8000"},{type:!J&&!$.username?"text":null,name:"username",message:"Username:",initial:"root"},{type:!J&&!$.password?"password":null,name:"password",message:"Password:"},{type:!J&&!$.authLevel?"select":null,name:"authLevel",message:"Auth level:",choices:[{title:"Root",value:"root"},{title:"Namespace",value:"namespace"},{title:"Database",value:"database"}],initial:0},{type:!$.namespace?"text":null,name:"namespace",message:"Namespace:"},{type:!$.database?"text":null,name:"database",message:"Database:"}],{onCancel:()=>{Y.newline(),Y.warn("Operation cancelled."),process.exit(0)}});if(J)return{embedded:J==="memory"?"memory":`file://${J}`,namespace:$.namespace||Q.namespace,database:$.database||Q.database};let X=$.url||Q.url,Z=$.username||Q.username,B=$.password||Q.password,_=$.authLevel||Q.authLevel||"root",G=$.namespace||Q.namespace,j=$.database||Q.database,U;if(_==="database")U={username:Z,password:B,namespace:G,database:j};else if(_==="namespace")U={username:Z,password:B,namespace:G};else U={username:Z,password:B};return{url:X,namespace:G,database:j,authentication:U}}async function z2($,J=!0){return(await Y0({type:"confirm",name:"value",message:$,initial:J},{onCancel:()=>{console.log(`
4
- Operation cancelled.`),process.exit(0)}})).value}async function M0($,J){return(await Y0({type:"text",name:"value",message:$,initial:J},{onCancel:()=>{Y.newline(),Y.warn("Operation cancelled."),process.exit(0)}})).value||""}async function k0($,J){return(await Y0({type:"select",name:"value",message:$,choices:J},{onCancel:()=>{console.log(`
5
- Operation cancelled.`),process.exit(0)}})).value}async function T0($,J){return(await Y0({type:"select",name:"value",message:$,choices:J.map((X)=>({title:X.title,value:X.value,disabled:X.disabled}))},{onCancel:()=>{console.log(`
6
- Operation cancelled.`),process.exit(0)}})).value}async function U0($,J,Q){let Z=(await Y0({type:"text",name:"action",message:`[${J}/${Q}] Apply this change? (y)es / (n)o / (a)ccept all / (c)ancel`,validate:(B)=>{let _=B.toLowerCase().trim();if(["y","yes","n","no","a","all","c","cancel"].includes(_))return!0;return"Please enter: y/yes, n/no, a/all, or c/cancel"}},{onCancel:()=>{Y.newline(),Y.warn("Operation cancelled."),process.exit(0)}})).action.toLowerCase().trim();if(Z==="y"||Z==="yes")return"yes";if(Z==="n"||Z==="no")return"no";if(Z==="a"||Z==="all")return"all";if(Z==="c"||Z==="cancel")return"cancel";return"no"}var G0=S0(()=>{u()});import{Command as h4}from"@commander-js/extra-typings";u();import{Command as G2}from"@commander-js/extra-typings";import f from"prompts";import T from"node:fs/promises";import h from"node:path";import{execSync as Z1}from"node:child_process";var __dirname="E:\\GitHub\\unreal-orm\\packages\\unreal-cli\\src\\commands",m=()=>{Y.newline(),Y.warn("Operation cancelled."),process.exit(0)},Y1=new G2("init").description("Initialize UnrealORM in your project").option("--url <url>","SurrealDB URL").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <ns>","Namespace").option("-d, --database <db>","Database").option("-e, --embedded <mode>","Embedded mode (memory or file path)").option("--sample","Generate sample schema tables").option("--from-db","Import schema from existing database").option("--from-surql <file>","Import schema from .surql file").option("--install","Install dependencies automatically").option("--no-install","Skip dependency installation").option("--pm <manager>","Package manager (npm, yarn, pnpm, bun)").action(async($)=>{Y.header("\uD83D\uDE80 UnrealORM Setup","Initialize your project with UnrealORM");let J,Q;if($.url)Q="remote";else if($.embedded)Q=$.embedded==="memory"?"memory":"file";else Q=(await f({type:"select",name:"connectionMode",message:"How will you connect to SurrealDB?",choices:[{title:"Remote (URL)",value:"remote",description:"Connect via WebSocket/HTTP"},{title:"Embedded (Memory)",value:"memory",description:"In-memory, great for dev/testing"},{title:"Embedded (File)",value:"file",description:"Persist to local file"}]},{onCancel:m})).connectionMode;if(!Q)Y.error("Operation cancelled."),process.exit(1);if(Q==="remote"){let I=$.url||(await f({type:"text",name:"url",message:"SurrealDB URL:",initial:"ws://localhost:8000"},{onCancel:m})).url,O=$.username,w=$.password,P="root";if(!O||!w){let g=await f([{type:$.username?null:"select",name:"authLevel",message:"Authentication level:",choices:[{title:"Root",value:"root"},{title:"Namespace",value:"namespace"},{title:"Database",value:"database"}]},{type:$.username?null:"text",name:"username",message:"Username:",initial:"root"},{type:$.password?null:"password",name:"password",message:"Password:"}],{onCancel:m});O=$.username||g.username,w=$.password||g.password,P=g.authLevel||"root"}let{namespace:F,database:L}=$,N=[];if(!F&&(P!=="root"||!L))N.push({type:"text",name:"namespace",message:"Namespace:",initial:"test"});if(!L)N.push({type:"text",name:"database",message:"Database:",initial:"test"});if(N.length>0){let g=await f(N,{onCancel:m});F=F||g.namespace,L=L||g.database}let v,x=O||"",S=w||"";if(P==="database"&&F&&L)v={username:x,password:S,namespace:F,database:L};else if(P==="namespace"&&F)v={username:x,password:S,namespace:F};else v={username:x,password:S};J={url:I,authentication:v,namespace:F,database:L}}else if(Q==="memory"){let{namespace:I,database:O}=$;if(!I||!O){let w=await f([{type:I?null:"text",name:"namespace",message:"Namespace:",initial:"test"},{type:O?null:"text",name:"database",message:"Database:",initial:"test"}],{onCancel:m});I=I||w.namespace,O=O||w.database}J={embedded:"memory",namespace:I,database:O},Y.newline(),Y.warn("Note: Embedded mode requires @surrealdb/node package")}else{let I=$.embedded!=="surrealkv"?$.embedded:void 0,O=$.namespace,w=$.database;if(!I)I=(await f({type:"text",name:"path",message:"Database file path:",initial:"./data/local"},{onCancel:m})).path;if(!O||!w){let P=await f([{type:O?null:"text",name:"namespace",message:"Namespace:",initial:"test"},{type:w?null:"text",name:"database",message:"Database:",initial:"test"}],{onCancel:m});O=O||P.namespace,w=w||P.database}J={embedded:I?.startsWith("surrealkv://")?I:`surrealkv://${I}`,namespace:O,database:w},Y.newline(),Y.warn("Note: Embedded mode requires @surrealdb/node package"),Y.newline()}let Z=await T.access(h.join(process.cwd(),"src")).then(()=>!0).catch(()=>!1)?"./src/unreal":"./unreal",_=(await f({type:"text",name:"path",message:"Where should the unreal folder be created?",initial:Z},{onCancel:m})).path||Z,G=h.resolve(process.cwd(),_),j=h.join(G,"tables");await T.mkdir(j,{recursive:!0}),Y.success(`Created ${_}/ folder structure`);let U=j2(_);await T.writeFile(h.join(process.cwd(),"unreal.config.json"),JSON.stringify(U,null,"\t")),Y.success("Created unreal.config.json");let W=K2(Q);await T.writeFile(h.join(G,"surreal.ts"),W),Y.success(`Created ${_}/surreal.ts`);let V=U2(J,Q),q=h.join(process.cwd(),".env"),H=await T.access(q).then(()=>!0).catch(()=>!1);if(Y.newline(),H){if((await f({type:"confirm",name:"appendEnv",message:"Append SurrealDB config to existing .env file?",initial:!0},{onCancel:m})).appendEnv)if((await T.readFile(q,"utf-8")).includes("SURREAL_URL"))Y.warn(".env already contains SURREAL_* variables, skipping append");else await T.appendFile(q,`
2
+ import{createRequire as j2}from"node:module";var Y2=Object.defineProperty;var G2=($,J)=>{for(var Q in J)Y2($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:(X)=>J[Q]=()=>X})};var R0=($,J)=>()=>($&&(J=$($=0)),J);var G0=j2(import.meta.url);function Z1($){x0=$}function h(){return x0==="silent"}function B1(){return x0==="debug"}var x0="normal";var z0=()=>{};class Y1{lineCount=0;log($=""){if(h())return;console.log($),this.lineCount+=$.split(`
3
+ `).length}clear(){if(this.lineCount>0)process.stdout.moveCursor(0,-this.lineCount),process.stdout.clearScreenDown(),this.lineCount=0}reset(){this.lineCount=0}}var G1;var j1=R0(()=>{z0();G1=new Y1});import s from"chalk";import U2 from"ora";var B0,b,t,Y;var c=R0(()=>{j1();z0();B0={success:"✅",error:"❌",warning:"⚠️",info:"ℹ️",step:"\uD83D\uDD39",arrow:"➜",line:"─",corner:"└─"},b={primary:s.hex("#FF00A0"),secondary:s.cyan,success:s.green,error:s.red,warning:s.yellow,info:s.blue,dim:s.gray,code:s.hex("#E0E0E0"),url:s.underline.cyan},t={succeed:()=>t,fail:()=>t,stop:()=>t,start:()=>t,warn:()=>t,info:()=>t,clear:()=>t,render:()=>t,frame:()=>"",get isSpinning(){return!1},get text(){return""},set text($){},get color(){return"cyan"},set color($){},get indent(){return 0},set indent($){},get spinner(){return{interval:0,frames:[]}},set spinner($){},get interval(){return 0},get prefixText(){return""},set prefixText($){},get suffixText(){return""},set suffixText($){},[Symbol.dispose]:()=>{}},Y={header($,J){if(h())return;if(console.log(""),console.log(b.primary.bold(` ${$} `)),J)console.log(b.dim(` ${J}`));console.log("")},divider(){if(h())return;console.log(b.dim(B0.line.repeat(60)))},success($){if(h())return;console.log(b.success(`${B0.success} ${$}`))},error($,J){if(h()){if(console.error($),J)console.error(J instanceof Error?J.message:String(J));return}if(console.log(b.error(`${B0.error} ${$}`)),J)if(J instanceof Error)console.log(b.dim(` ${J.stack||J.message}`));else console.log(b.dim(` ${String(J)}`))},warn($){if(h()){console.warn($);return}console.log(b.warning(`${B0.warning} ${$}`))},info($){if(h())return;console.log(b.info(`${B0.info} ${$}`))},step($,J){if(h())return;console.log(b.secondary(`${B0.step} ${$}`)+(J?b.dim(` ${J}`):""))},spin($){if(h())return t;return U2({text:$,color:"cyan",spinner:"dots"}).start()},code($){return b.code($)},cmd($){return b.code(`$ ${$}`)},link($,J){return b.url(J||$)},dim($){if(h())return"";return b.dim($)},bold($){return s.bold($)},newline(){if(h())return;console.log("")},get printer(){return G1},theme:b,symbols:B0}});var z1={};G2(z1,{promptText:()=>P0,promptSelectWithDisabled:()=>y0,promptSelect:()=>C0,promptForConnection:()=>I0,promptFileReview:()=>q0,confirm:()=>W2});import j0 from"prompts";async function I0($){let J=$.embedded,Q=await j0([{type:!J&&!$.url?"text":null,name:"url",message:"Database URL:",initial:"http://localhost:8000"},{type:!J&&!$.username?"text":null,name:"username",message:"Username:",initial:"root"},{type:!J&&!$.password?"password":null,name:"password",message:"Password:"},{type:!J&&!$.authLevel?"select":null,name:"authLevel",message:"Auth level:",choices:[{title:"Root",value:"root"},{title:"Namespace",value:"namespace"},{title:"Database",value:"database"}],initial:0},{type:!$.namespace?"text":null,name:"namespace",message:"Namespace:"},{type:!$.database?"text":null,name:"database",message:"Database:"}],{onCancel:()=>{Y.newline(),Y.warn("Operation cancelled."),process.exit(0)}});if(J)return{embedded:J==="memory"?"memory":`file://${J}`,namespace:$.namespace||Q.namespace,database:$.database||Q.database};let X=$.url||Q.url,Z=$.username||Q.username,B=$.password||Q.password,j=$.authLevel||Q.authLevel||"root",G=$.namespace||Q.namespace,U=$.database||Q.database,K;if(j==="database")K={username:Z,password:B,namespace:G,database:U};else if(j==="namespace")K={username:Z,password:B,namespace:G};else K={username:Z,password:B};return{url:X,namespace:G,database:U,authentication:K}}async function W2($,J=!0){return(await j0({type:"confirm",name:"value",message:$,initial:J},{onCancel:()=>{console.log(`
4
+ Operation cancelled.`),process.exit(0)}})).value}async function P0($,J){return(await j0({type:"text",name:"value",message:$,initial:J},{onCancel:()=>{Y.newline(),Y.warn("Operation cancelled."),process.exit(0)}})).value||""}async function C0($,J){return(await j0({type:"select",name:"value",message:$,choices:J},{onCancel:()=>{console.log(`
5
+ Operation cancelled.`),process.exit(0)}})).value}async function y0($,J){return(await j0({type:"select",name:"value",message:$,choices:J.map((X)=>({title:X.title,value:X.value,disabled:X.disabled}))},{onCancel:()=>{console.log(`
6
+ Operation cancelled.`),process.exit(0)}})).value}async function q0($,J,Q){let Z=(await j0({type:"text",name:"action",message:`[${J}/${Q}] Apply this change? (y)es / (n)o / (a)ccept all / (c)ancel`,validate:(B)=>{let j=B.toLowerCase().trim();if(["y","yes","n","no","a","all","c","cancel"].includes(j))return!0;return"Please enter: y/yes, n/no, a/all, or c/cancel"}},{onCancel:()=>{Y.newline(),Y.warn("Operation cancelled."),process.exit(0)}})).action.toLowerCase().trim();if(Z==="y"||Z==="yes")return"yes";if(Z==="n"||Z==="no")return"no";if(Z==="a"||Z==="all")return"all";if(Z==="c"||Z==="cancel")return"cancel";return"no"}var U0=R0(()=>{c()});import{Command as u4}from"@commander-js/extra-typings";c();import{Command as K2}from"@commander-js/extra-typings";import m from"prompts";import x from"node:fs/promises";import p from"node:path";import{execSync as U1}from"node:child_process";var __dirname="E:\\GitHub\\unreal-orm\\packages\\unreal-cli\\src\\commands",u=()=>{Y.newline(),Y.warn("Operation cancelled."),process.exit(0)},_1=new K2("init").description("Initialize UnrealORM in your project").option("--url <url>","SurrealDB URL").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <ns>","Namespace").option("-d, --database <db>","Database").option("-e, --embedded <mode>","Embedded mode (memory or file path)").option("--sample","Generate sample schema tables").option("--from-db","Import schema from existing database").option("--from-surql <file>","Import schema from .surql file").option("--install","Install dependencies automatically").option("--no-install","Skip dependency installation").option("--pm <manager>","Package manager (npm, yarn, pnpm, bun)").action(async($)=>{Y.header("\uD83D\uDE80 UnrealORM Setup","Initialize your project with UnrealORM");let J,Q;if($.url)Q="remote";else if($.embedded)Q=$.embedded==="memory"?"memory":"file";else Q=(await m({type:"select",name:"connectionMode",message:"How will you connect to SurrealDB?",choices:[{title:"Remote (URL)",value:"remote",description:"Connect via WebSocket/HTTP"},{title:"Embedded (Memory)",value:"memory",description:"In-memory, great for dev/testing"},{title:"Embedded (File)",value:"file",description:"Persist to local file"}]},{onCancel:u})).connectionMode;if(!Q)Y.error("Operation cancelled."),process.exit(1);if(Q==="remote"){let I=$.url||(await m({type:"text",name:"url",message:"SurrealDB URL:",initial:"ws://localhost:8000"},{onCancel:u})).url,O=$.username,w=$.password,P="root";if(!O||!w){let f=await m([{type:$.username?null:"select",name:"authLevel",message:"Authentication level:",choices:[{title:"Root",value:"root"},{title:"Namespace",value:"namespace"},{title:"Database",value:"database"}]},{type:$.username?null:"text",name:"username",message:"Username:",initial:"root"},{type:$.password?null:"password",name:"password",message:"Password:"}],{onCancel:u});O=$.username||f.username,w=$.password||f.password,P=f.authLevel||"root"}let{namespace:F,database:N}=$,S=[];if(!F&&(P!=="root"||!N))S.push({type:"text",name:"namespace",message:"Namespace:",initial:"test"});if(!N)S.push({type:"text",name:"database",message:"Database:",initial:"test"});if(S.length>0){let f=await m(S,{onCancel:u});F=F||f.namespace,N=N||f.database}let v,y=O||"",k=w||"";if(P==="database"&&F&&N)v={username:y,password:k,namespace:F,database:N};else if(P==="namespace"&&F)v={username:y,password:k,namespace:F};else v={username:y,password:k};J={url:I,authentication:v,namespace:F,database:N}}else if(Q==="memory"){let{namespace:I,database:O}=$;if(!I||!O){let w=await m([{type:I?null:"text",name:"namespace",message:"Namespace:",initial:"test"},{type:O?null:"text",name:"database",message:"Database:",initial:"test"}],{onCancel:u});I=I||w.namespace,O=O||w.database}J={embedded:"memory",namespace:I,database:O},Y.newline(),Y.warn("Note: Embedded mode requires @surrealdb/node package")}else{let I=$.embedded!=="surrealkv"?$.embedded:void 0,O=$.namespace,w=$.database;if(!I)I=(await m({type:"text",name:"path",message:"Database file path:",initial:"./data/local"},{onCancel:u})).path;if(!O||!w){let P=await m([{type:O?null:"text",name:"namespace",message:"Namespace:",initial:"test"},{type:w?null:"text",name:"database",message:"Database:",initial:"test"}],{onCancel:u});O=O||P.namespace,w=w||P.database}J={embedded:I?.startsWith("surrealkv://")?I:`surrealkv://${I}`,namespace:O,database:w},Y.newline(),Y.warn("Note: Embedded mode requires @surrealdb/node package"),Y.newline()}let Z=await x.access(p.join(process.cwd(),"src")).then(()=>!0).catch(()=>!1)?"./src/unreal":"./unreal",j=(await m({type:"text",name:"path",message:"Where should the unreal folder be created?",initial:Z},{onCancel:u})).path||Z,G=p.resolve(process.cwd(),j),U=p.join(G,"tables");await x.mkdir(U,{recursive:!0}),Y.success(`Created ${j}/ folder structure`);let K=z2(j);await x.writeFile(p.join(process.cwd(),"unreal.config.json"),JSON.stringify(K,null,"\t")),Y.success("Created unreal.config.json");let W=H2(Q);await x.writeFile(p.join(G,"surreal.ts"),W),Y.success(`Created ${j}/surreal.ts`);let V=q2(J,Q),q=p.join(process.cwd(),".env"),H=await x.access(q).then(()=>!0).catch(()=>!1);if(Y.newline(),H){if((await m({type:"confirm",name:"appendEnv",message:"Append SurrealDB config to existing .env file?",initial:!0},{onCancel:u})).appendEnv)if((await x.readFile(q,"utf-8")).includes("SURREAL_URL"))Y.warn(".env already contains SURREAL_* variables, skipping append");else await x.appendFile(q,`
7
7
 
8
8
  ${V}
9
- `),Y.success("Appended SurrealDB config to .env")}else if((await f({type:"confirm",name:"createEnv",message:"Create .env file with SurrealDB config?",initial:!0},{onCancel:m})).createEnv)await T.writeFile(q,`${V}
10
- `),Y.success("Created .env file"),Y.info(" Remember to add .env to your .gitignore!");let K=_2(),z=["unreal-orm@latest","surrealdb@alpha"],M=["@unreal-orm/cli"];if(Q==="memory"||Q==="file")z.push("@surrealdb/node@alpha");let E=$.install;if(E===void 0){let I=[...z,...M.map((w)=>`${w} (dev)`)],{install:O}=await f({type:"confirm",name:"install",message:`Install dependencies? (${I.join(", ")})`,initial:!0},{onCancel:m});E=O}if(E){let I=$.pm??"";if(!I){let P=[{title:"npm",value:"npm"},{title:"yarn",value:"yarn"},{title:"pnpm",value:"pnpm"},{title:"bun",value:"bun"}],F=P.findIndex((N)=>N.value===K),{pm:L}=await f({type:"select",name:"pm",message:"Package manager:",choices:P,initial:F>=0?F:0},{onCancel:m});I=L??K}let O=B1(I,z,!1);Y.newline(),Y.info(`Running: ${O}...`);try{Z1(O,{stdio:"inherit"})}catch(P){Y.error("Failed to install dependencies")}let w=B1(I,M,!0);Y.info(`Running: ${w}...`);try{Z1(w,{stdio:"inherit"}),Y.success("Dependencies installed")}catch(P){Y.error("Failed to install dev dependencies")}}let A="none";if($.sample)A="sample";else if($.fromDb)A="from-db";else if($.fromSurql)A="from-surql";else A=(await f({type:"select",name:"action",message:"What would you like to do next?",choices:[{title:"Generate sample tables",value:"sample",description:"User, Post, Follow tables with indexes & relations"},{title:"Import from Database",value:"from-db",description:"Introspect existing DB"},{title:"Import from .surql file",value:"from-surql",description:"Parse SurrealQL file"},{title:"Nothing for now",value:"none"}]},{onCancel:m})).action;if(A==="sample"){let I=h.resolve(__dirname,"../../examples/simple"),O=["User.ts","Post.ts","Follow.ts"];for(let w of O){let P=await T.readFile(h.join(I,w),"utf-8");await T.writeFile(h.join(j,w),P)}Y.success("Generated sample tables:"),console.log(Y.dim(" • User.ts - Basic user table with indexes")),console.log(Y.dim(" • Post.ts - Posts with record links, arrays, and methods")),console.log(Y.dim(" • Follow.ts - Relation table (graph edge) example"))}else if(A==="from-db")Y.info("Run 'unreal pull' to import schema from database");else if(A==="from-surql")Y.info("Run 'unreal pull --file <path>' to import schema");if(Y.newline(),(await f({type:"confirm",name:"addImport",message:"Add import to your entry point? (e.g., index.ts, main.ts)",initial:!0},{onCancel:m})).addImport){let I=["src/index.ts","src/main.ts","src/app.ts","index.ts","main.ts","app.ts"],O=null;for(let F of I){let L=h.join(process.cwd(),F);if(await T.access(L).then(()=>!0).catch(()=>!1)){O=F;break}}let P=(await f({type:"text",name:"entryPoint",message:"Entry point file:",initial:O||"src/index.ts"},{onCancel:m})).entryPoint;if(P){let F=h.join(process.cwd(),P),L=await T.access(F).then(()=>!0).catch(()=>!1),N=h.dirname(F),v=h.relative(N,G);if(!v.startsWith("."))v=`./${v}`;v=v.replace(/\\/g,"/");let x=`// Initialize database connection and configure ORM (must be first import)
11
- import "${v}/surreal";`;if(L){let S=await T.readFile(F,"utf-8");if(S.includes("/surreal"))Y.warn("Entry point already imports surreal.ts, skipping");else{let g=`${x}
12
- ${S}`;await T.writeFile(F,g),Y.success(`Added import to ${P}`)}}else{let S=`${x}
9
+ `),Y.success("Appended SurrealDB config to .env")}else if((await m({type:"confirm",name:"createEnv",message:"Create .env file with SurrealDB config?",initial:!0},{onCancel:u})).createEnv)await x.writeFile(q,`${V}
10
+ `),Y.success("Created .env file"),Y.info(" Remember to add .env to your .gitignore!");let _=_2(),z=["unreal-orm@latest","surrealdb@2.0.0"],M=["@unreal-orm/cli"];if(Q==="memory"||Q==="file")z.push("@surrealdb/node@3.0.1");let E=$.install;if(E===void 0){let I=[...z,...M.map((w)=>`${w} (dev)`)],{install:O}=await m({type:"confirm",name:"install",message:`Install dependencies? (${I.join(", ")})`,initial:!0},{onCancel:u});E=O}if(E){let I=$.pm??"";if(!I){let P=[{title:"npm",value:"npm"},{title:"yarn",value:"yarn"},{title:"pnpm",value:"pnpm"},{title:"bun",value:"bun"}],F=P.findIndex((S)=>S.value===_),{pm:N}=await m({type:"select",name:"pm",message:"Package manager:",choices:P,initial:F>=0?F:0},{onCancel:u});I=N??_}let O=K1(I,z,!1);Y.newline(),Y.info(`Running: ${O}...`);try{U1(O,{stdio:"inherit"})}catch(P){Y.error("Failed to install dependencies")}let w=K1(I,M,!0);Y.info(`Running: ${w}...`);try{U1(w,{stdio:"inherit"}),Y.success("Dependencies installed")}catch(P){Y.error("Failed to install dev dependencies")}}let A="none";if($.sample)A="sample";else if($.fromDb)A="from-db";else if($.fromSurql)A="from-surql";else A=(await m({type:"select",name:"action",message:"What would you like to do next?",choices:[{title:"Generate sample tables",value:"sample",description:"User, Post, Follow tables with indexes & relations"},{title:"Import from Database",value:"from-db",description:"Introspect existing DB"},{title:"Import from .surql file",value:"from-surql",description:"Parse SurrealQL file"},{title:"Nothing for now",value:"none"}]},{onCancel:u})).action;if(A==="sample"){let I=p.resolve(__dirname,"../../examples/simple"),O=["User.ts","Post.ts","Follow.ts"];for(let w of O){let P=await x.readFile(p.join(I,w),"utf-8");await x.writeFile(p.join(U,w),P)}Y.success("Generated sample tables:"),console.log(Y.dim(" • User.ts - Basic user table with indexes")),console.log(Y.dim(" • Post.ts - Posts with record links, arrays, and methods")),console.log(Y.dim(" • Follow.ts - Relation table (graph edge) example"))}else if(A==="from-db")Y.info("Run 'unreal pull' to import schema from database");else if(A==="from-surql")Y.info("Run 'unreal pull --file <path>' to import schema");if(Y.newline(),(await m({type:"confirm",name:"addImport",message:"Add import to your entry point? (e.g., index.ts, main.ts)",initial:!0},{onCancel:u})).addImport){let I=["src/index.ts","src/main.ts","src/app.ts","index.ts","main.ts","app.ts"],O=null;for(let F of I){let N=p.join(process.cwd(),F);if(await x.access(N).then(()=>!0).catch(()=>!1)){O=F;break}}let P=(await m({type:"text",name:"entryPoint",message:"Entry point file:",initial:O||"src/index.ts"},{onCancel:u})).entryPoint;if(P){let F=p.join(process.cwd(),P),N=await x.access(F).then(()=>!0).catch(()=>!1),S=p.dirname(F),v=p.relative(S,G);if(!v.startsWith("."))v=`./${v}`;v=v.replace(/\\/g,"/");let y=`// Initialize database connection and configure ORM (must be first import)
11
+ import "${v}/surreal";`;if(N){let k=await x.readFile(F,"utf-8");if(k.includes("/surreal"))Y.warn("Entry point already imports surreal.ts, skipping");else{let f=`${y}
12
+ ${k}`;await x.writeFile(F,f),Y.success(`Added import to ${P}`)}}else{let k=`${y}
13
13
 
14
14
  // Your app code here
15
15
  console.log("Hello from UnrealORM!");
16
- `;await T.mkdir(h.dirname(F),{recursive:!0}),await T.writeFile(F,S),Y.success(`Created ${P} with import`)}}}Y.header("UnrealORM setup complete!","You are ready to build!"),console.log(Y.dim("Project structure:")),console.log(Y.dim(" unreal.config.json - Path configuration")),console.log(Y.dim(` ${_}/`)),console.log(Y.dim(" surreal.ts - Database connection & ORM config")),console.log(Y.dim(" tables/ - Table definitions")),Y.newline(),console.log(Y.dim("Quick start:")),console.log(Y.dim(` 1. Import "${_}/surreal" in your entry point`)),console.log(Y.dim(" 2. Define tables in tables/ directory")),console.log(Y.dim(" 3. Use models: await User.select({ limit: 10 })")),Y.newline(),console.log(Y.dim("CLI commands:")),console.log(Y.dim(" • unreal pull - Import schema from database")),console.log(Y.dim(" • unreal push - Apply local schema to database")),console.log(Y.dim(" • unreal diff - Compare schemas")),Y.newline(),Y.warn("⭐ If you find UnrealORM useful, please give us a star on GitHub!"),console.log(Y.dim(` https://github.com/Jimpex/unreal-orm
17
- `))});function _2(){let $=process.env.npm_config_user_agent;if($?.startsWith("bun"))return"bun";if($?.startsWith("pnpm"))return"pnpm";if($?.startsWith("yarn"))return"yarn";return"npm"}function B1($,J,Q){let X=J.join(" "),Z=Q?" -D":"";switch($){case"bun":return`bun add${Z} ${X}`;case"pnpm":return`pnpm add${Z} ${X}`;case"yarn":return`yarn add${Z} ${X}`;default:return`npm install${Q?" --save-dev":""} ${X}`}}function j2($){return{$schema:"./node_modules/unreal-orm/schema.json",path:$}}function U2($,J){let Q=J==="memory"||J==="file",X=["# SurrealDB Connection (generated by UnrealORM)"];if(Q){let Z="embedded"in $?$.embedded:"mem://",B=Z==="memory"?"mem://":Z;X.push(`SURREAL_URL=${B}`),X.push(`SURREAL_NS=${$.namespace}`),X.push(`SURREAL_DB=${$.database}`)}else{let Z="url"in $?$.url:"ws://localhost:8000",B="authentication"in $&&$.authentication&&typeof $.authentication==="object"?$.authentication:null,_=B&&"username"in B?B.username:"",G=B&&"password"in B?B.password:"";X.push(`SURREAL_URL=${Z}`),X.push(`SURREAL_NS=${$.namespace}`),X.push(`SURREAL_DB=${$.database}`),X.push(`SURREAL_USER=${_}`),X.push(`SURREAL_PASS=${G}`)}return X.join(`
18
- `)}function K2($){let J=$==="memory"||$==="file",Q=J?"Embedded":"Remote",X=J?"mem://, surrealkv://./data":"ws://localhost:8000",Z=["SURREAL_URL","SURREAL_NS","SURREAL_DB"];if(!J)Z.push("SURREAL_USER","SURREAL_PASS");let B=J?`import { Unreal } from "unreal-orm";
16
+ `;await x.mkdir(p.dirname(F),{recursive:!0}),await x.writeFile(F,k),Y.success(`Created ${P} with import`)}}}Y.header("UnrealORM setup complete!","You are ready to build!"),console.log(Y.dim("Project structure:")),console.log(Y.dim(" unreal.config.json - Path configuration")),console.log(Y.dim(` ${j}/`)),console.log(Y.dim(" surreal.ts - Database connection & ORM config")),console.log(Y.dim(" tables/ - Table definitions")),Y.newline(),console.log(Y.dim("Quick start:")),console.log(Y.dim(` 1. Import "${j}/surreal" in your entry point`)),console.log(Y.dim(" 2. Define tables in tables/ directory")),console.log(Y.dim(" 3. Use models: await User.select({ limit: 10 })")),Y.newline(),console.log(Y.dim("CLI commands:")),console.log(Y.dim(" • unreal pull - Import schema from database")),console.log(Y.dim(" • unreal push - Apply local schema to database")),console.log(Y.dim(" • unreal diff - Compare schemas")),Y.newline(),Y.warn("⭐ If you find UnrealORM useful, please give us a star on GitHub!"),console.log(Y.dim(` https://github.com/Jimpex/unreal-orm
17
+ `))});function _2(){let $=process.env.npm_config_user_agent;if($?.startsWith("bun"))return"bun";if($?.startsWith("pnpm"))return"pnpm";if($?.startsWith("yarn"))return"yarn";return"npm"}function K1($,J,Q){let X=J.join(" "),Z=Q?" -D":"";switch($){case"bun":return`bun add${Z} ${X}`;case"pnpm":return`pnpm add${Z} ${X}`;case"yarn":return`yarn add${Z} ${X}`;default:return`npm install${Q?" --save-dev":""} ${X}`}}function z2($){return{$schema:"./node_modules/unreal-orm/schema.json",path:$}}function q2($,J){let Q=J==="memory"||J==="file",X=["# SurrealDB Connection (generated by UnrealORM)"];if(Q){let Z="embedded"in $?$.embedded:"mem://",B=Z==="memory"?"mem://":Z;X.push(`SURREAL_URL=${B}`),X.push(`SURREAL_NS=${$.namespace}`),X.push(`SURREAL_DB=${$.database}`)}else{let Z="url"in $?$.url:"ws://localhost:8000",B="authentication"in $&&$.authentication&&typeof $.authentication==="object"?$.authentication:null,j=B&&"username"in B?B.username:"",G=B&&"password"in B?B.password:"";X.push(`SURREAL_URL=${Z}`),X.push(`SURREAL_NS=${$.namespace}`),X.push(`SURREAL_DB=${$.database}`),X.push(`SURREAL_USER=${j}`),X.push(`SURREAL_PASS=${G}`)}return X.join(`
18
+ `)}function H2($){let J=$==="memory"||$==="file",Q=J?"Embedded":"Remote",X=J?"mem://, surrealkv://./data":"ws://localhost:8000",Z=["SURREAL_URL","SURREAL_NS","SURREAL_DB"];if(!J)Z.push("SURREAL_USER","SURREAL_PASS");let B=J?`import { Unreal } from "unreal-orm";
19
19
  import { createRemoteEngines, Surreal } from "surrealdb";
20
20
  import { createNodeEngines } from "@surrealdb/node";`:`import { Unreal } from "unreal-orm";
21
- import { Surreal } from "surrealdb";`,_=Z.map((q)=>`const ${q} = process.env.${q};`).join(`
22
- `),G=Z.join(" || !"),j=Z.join(", "),U=J?`db = new Surreal({
21
+ import { Surreal } from "surrealdb";`,j=Z.map((q)=>`const ${q} = process.env.${q};`).join(`
22
+ `),G=Z.join(" || !"),U=Z.join(", "),K=J?`db = new Surreal({
23
23
  engines: {
24
24
  ...createRemoteEngines(),
25
25
  ...createNodeEngines(),
@@ -78,11 +78,11 @@ ${B}
78
78
  // Environment Configuration
79
79
  // =============================================================================
80
80
 
81
- ${_}
81
+ ${j}
82
82
 
83
83
  if (!${G}) {
84
84
  throw new Error(
85
- "Missing required SurrealDB environment variables: ${j}\\n" +
85
+ "Missing required SurrealDB environment variables: ${U}\\n" +
86
86
  "Make sure your .env file exists and contains these variables."
87
87
  );
88
88
  }
@@ -122,7 +122,7 @@ export async function getDatabase(): Promise<Surreal> {
122
122
  export async function connect(): Promise<Surreal> {
123
123
  if (db) return db;
124
124
 
125
- ${U}
125
+ ${K}
126
126
 
127
127
  await db.connect(${V}, ${W});
128
128
 
@@ -150,10 +150,10 @@ export async function close(): Promise<void> {
150
150
  // This enables implicit database usage in model methods:
151
151
  // await User.select({ limit: 10 }) // No need to pass db
152
152
  Unreal.configure({ getDatabase });
153
- `}import{Command as r2}from"@commander-js/extra-typings";import{existsSync as u0,mkdirSync as o2,writeFileSync as s2,readFileSync as i2,readdirSync as a2,unlinkSync as n2}from"node:fs";import{join as D1}from"node:path";import{Surreal as U1}from"surrealdb";import{existsSync as K1}from"node:fs";import{resolve as x0}from"node:path";u();import{existsSync as _1,readFileSync as q2}from"node:fs";import{join as D0}from"node:path";import{createJiti as H2}from"jiti";var W2=H2(import.meta.url,{interopDefault:!0});async function C0($){return W2.import($)}async function o($=process.cwd()){let J=D0($,"unreal.config.json"),Q=D0($,"unreal.config.ts");if(_1(J))try{let X=q2(J,"utf-8");return{path:JSON.parse(X).path||"./unreal"}}catch(X){console.warn("Warning: Found unreal.config.json but failed to load it:",X instanceof Error?X.message:String(X))}if(_1(Q))try{return{path:(await C0(Q)).default.schema?.output?.replace("/tables","")||"./unreal"}}catch(X){console.warn("Warning: Found unreal.config.ts but failed to load it:",X instanceof Error?X.message:String(X))}return null}function A2($){return D0($.path||"./unreal","tables")}function R0($){return D0($.path||"./unreal","surreal.ts")}function j1(){Y.error("No configuration found."),Y.info("Please run 'unreal init' to create a configuration file first."),Y.newline(),process.exit(1)}async function n($){let{cliOutput:J,config:Q,allowPrompt:X=!0}=$;if(J)return J;if(Q?.path)return Y.dim("✓ Loaded configuration from unreal.config.json"),Y.newline(),A2(Q);if(Q&&!Q.path)Y.warn("Configuration found but 'path' is not set."),Y.dim("Tip: Run 'unreal init' to set up your project properly"),Y.newline();else if(!Q)Y.dim("No configuration found."),Y.dim("Tip: Run 'unreal init' to set up a project with saved settings"),Y.newline();if(X){let{promptText:Z}=await Promise.resolve().then(() => (G0(),G1));return await Z("Schema directory path:","./unreal/tables")||"./unreal/tables"}return"./unreal/tables"}G0();u();async function s($){let{cliOptions:J,config:Q,allowPrompt:X=!0,exitOnFailure:Z=!0,skipAutoConfig:B=!1}=$;if(J.url||J.username||J.password||J.namespace||J.database||J.authLevel||J.embedded){let G={url:J.url,username:J.username,password:J.password,namespace:J.namespace,database:J.database,authLevel:J.authLevel,embedded:J.embedded},j=await E0(G);return q1(j)}if(Q&&!B){let G=x0(process.cwd(),R0(Q));if(K1(G))return z1(G)}if(X){let G=Q?K1(x0(process.cwd(),R0(Q))):!1,j=await T0("Connection method:",[{title:G?"Use config (surreal.ts)":"Use config (surreal.ts) - not found",value:"config",disabled:!G},{title:"Enter connection details manually",value:"manual"}]);if(!j)process.exit(0);if(j==="config"&&Q){let W=x0(process.cwd(),R0(Q));return z1(W)}let U=await E0({});return q1(U)}if(Z)j1();return null}async function z1($){let J=Y.spin("Loading database client from surreal.ts...");try{try{(await import("dotenv")).config({quiet:!0})}catch{}let Q=await C0($),X;if(Q.getDatabase)X=await Q.getDatabase();else if(Q.connect)X=await Q.connect();else if(Q.default&&typeof Q.default==="object"&&"getDatabase"in Q.default){let Z=Q.default;if(Z.getDatabase)X=await Z.getDatabase()}else if(Q.default)X=Q.default;if(!X)J.fail("surreal.ts must export getDatabase() or connect()"),process.exit(1);return J.succeed("Connected using surreal.ts"),X}catch(Q){J.fail("Failed to load surreal.ts"),Y.error(Q instanceof Error?Q.message:String(Q)),Y.newline(),Y.dim("Tip: You can also provide connection flags directly:"),Y.dim(" unreal <command> --url ws://localhost:8000 -u root -p root -n test -d test"),Y.newline(),process.exit(1)}}async function q1($){let J;if("embedded"in $)try{let{createNodeEngines:Q}=await import("@surrealdb/node"),X=$.embedded==="memory"?"mem://":$.embedded;J=new U1({engines:Q()}),await J.connect(X,$)}catch(Q){throw Error(`Failed to initialize embedded SurrealDB. Make sure @surrealdb/node is installed and your environment supports native bindings.
154
- Original Error: ${Q}`)}else J=new U1,await J.connect($.url,$);if($.namespace&&$.database)await J.use({namespace:$.namespace,database:$.database});return J}import{parseFieldDefinition as V2,parseIndexDefinition as O2,parseTableDefinition as E2}from"unreal-orm";function y0($,J){if(!$)throw Error(`${J}: No data returned`);return $}import b0 from"chalk";var I0=[];function C($,J,Q){I0.push({feature:$,reason:J,suggestion:Q})}function t($,J,Q){if($==="field"){if(Q.includes("TYPE object")&&Q.includes("{"))return C(`Field '${J}'`,"Object field with inline schema definition","Object fields are parsed as Field.object({}) - you may need to manually define the schema"),!1;if(Q.includes("TYPE geometry<")){let Z=Q.match(/geometry<(\w+)>/)?.[1];if(Z&&!["point","linestring","polygon","multipoint","multilinestring","multipolygon","collection","feature"].includes(Z.toLowerCase()))C(`Field '${J}'`,`Uncommon geometry type: ${Z}`,"Verify the generated Field.geometry() call is correct")}}if($==="index"){if(Q.includes("MTREE")||Q.includes("HNSW"))return C(`Index '${J}'`,"Vector index (MTREE/HNSW) detected","Vector indexes are not yet fully supported in code generation"),!1;if(Q.includes("SEARCH ANALYZER"))C(`Index '${J}'`,"Search analyzer index detected","Search indexes are parsed but may need manual configuration")}if($==="table"){if(Q.includes("CHANGEFEED"))C(`Table '${J}'`,"Changefeed configuration detected","Changefeeds are not yet supported in code generation")}if($==="event")return C(`Event '${J}'`,"Events/triggers are not yet supported","You'll need to manually create event definitions"),!1;if($==="analyzer")return C(`Analyzer '${J}'`,"Analyzers are not yet supported","Analyzer definitions will be skipped"),!1;if($==="function")return C(`Function '${J}'`,"Custom functions are not yet supported","Function definitions will be skipped"),!1;if($==="param")return C(`Parameter '${J}'`,"Database parameters are not yet supported","Parameter definitions will be skipped"),!1;return!0}function e(){if(I0.length===0)return;console.log(b0.yellow(`
153
+ `}import{Command as a2}from"@commander-js/extra-typings";import{existsSync as d0,mkdirSync as i2,writeFileSync as n2,readFileSync as t2,readdirSync as e2,unlinkSync as $4}from"node:fs";import{join as L1}from"node:path";import{Surreal as A1}from"surrealdb";import{existsSync as V1}from"node:fs";import{resolve as g0}from"node:path";c();import{existsSync as q1,readFileSync as A2}from"node:fs";import{join as F0}from"node:path";import{createJiti as V2}from"jiti";var O2=V2(import.meta.url,{interopDefault:!0});async function b0($){return O2.import($)}async function a($=process.cwd()){let J=F0($,"unreal.config.json"),Q=F0($,"unreal.config.ts");if(q1(J))try{let X=A2(J,"utf-8");return{path:JSON.parse(X).path||"./unreal"}}catch(X){console.warn("Warning: Found unreal.config.json but failed to load it:",X instanceof Error?X.message:String(X))}if(q1(Q))try{return{path:(await b0(Q)).default.schema?.output?.replace("/tables","")||"./unreal"}}catch(X){console.warn("Warning: Found unreal.config.ts but failed to load it:",X instanceof Error?X.message:String(X))}return null}function E2($){return F0($.path||"./unreal","tables")}function w0($){return F0($.path||"./unreal","surreal.ts")}function H1(){Y.error("No configuration found."),Y.info("Please run 'unreal init' to create a configuration file first."),Y.newline(),process.exit(1)}async function $0($){let{cliOutput:J,config:Q,allowPrompt:X=!0}=$;if(J)return J;if(Q?.path)return Y.dim("✓ Loaded configuration from unreal.config.json"),Y.newline(),E2(Q);if(Q&&!Q.path)Y.warn("Configuration found but 'path' is not set."),Y.dim("Tip: Run 'unreal init' to set up your project properly"),Y.newline();else if(!Q)Y.dim("No configuration found."),Y.dim("Tip: Run 'unreal init' to set up a project with saved settings"),Y.newline();if(X){let{promptText:Z}=await Promise.resolve().then(() => (U0(),z1));return await Z("Schema directory path:","./unreal/tables")||"./unreal/tables"}return"./unreal/tables"}U0();c();z0();var W1=performance.now();function L($){if(!B1())return;let J=performance.now(),Q=J-W1;W1=J,console.log(`[DEBUG +${Q.toFixed(0)}ms] ${$}`)}async function i($){let{cliOptions:J,config:Q,allowPrompt:X=!0,exitOnFailure:Z=!0,skipAutoConfig:B=!1}=$;if(J.url||J.username||J.password||J.namespace||J.database||J.authLevel||J.embedded){let G={url:J.url,username:J.username,password:J.password,namespace:J.namespace,database:J.database,authLevel:J.authLevel,embedded:J.embedded},U=await I0(G);return L("Connecting via CLI flags"),E1(U)}if(Q&&!B){let G=g0(process.cwd(),w0(Q));if(V1(G))return L("Connecting via surreal.ts config"),O1(G)}if(X){let G=Q?V1(g0(process.cwd(),w0(Q))):!1,U=await y0("Connection method:",[{title:G?"Use config (surreal.ts)":"Use config (surreal.ts) - not found",value:"config",disabled:!G},{title:"Enter connection details manually",value:"manual"}]);if(!U)process.exit(0);if(U==="config"&&Q){let W=g0(process.cwd(),w0(Q));return O1(W)}let K=await I0({});return E1(K)}if(Z)H1();return null}async function O1($){let J=Y.spin("Loading database client from surreal.ts...");try{try{(await import("dotenv")).config({quiet:!0})}catch{}let Q=await b0($),X;if(Q.getDatabase)X=await Q.getDatabase();else if(Q.connect)X=await Q.connect();else if(Q.default&&typeof Q.default==="object"&&"getDatabase"in Q.default){let Z=Q.default;if(Z.getDatabase)X=await Z.getDatabase()}else if(Q.default)X=Q.default;if(!X)J.fail("surreal.ts must export getDatabase() or connect()"),process.exit(1);return J.succeed("Connected using surreal.ts"),X}catch(Q){J.fail("Failed to load surreal.ts"),Y.error(Q instanceof Error?Q.message:String(Q)),Y.newline(),Y.dim("Tip: You can also provide connection flags directly:"),Y.dim(" unreal <command> --url ws://localhost:8000 -u root -p root -n test -d test"),Y.newline(),process.exit(1)}}async function E1($){let J;if("embedded"in $)try{let{createNodeEngines:Q}=await import("@surrealdb/node"),X=$.embedded==="memory"?"mem://":$.embedded;J=new A1({engines:Q()}),await J.connect(X,$),L("Embedded connection established")}catch(Q){throw Error(`Failed to initialize embedded SurrealDB. Make sure @surrealdb/node is installed and your environment supports native bindings.
154
+ Original Error: ${Q}`)}else J=new A1,await J.connect($.url,$),L("Remote connection established");if($.namespace&&$.database)await J.use({namespace:$.namespace,database:$.database});return J}import{parseFieldDefinition as M2,parseIndexDefinition as D2,parseTableDefinition as R2}from"unreal-orm";function f0($,J){if(!$)throw Error(`${J}: No data returned`);return $}import h0 from"chalk";var L0=[];function C($,J,Q){L0.push({feature:$,reason:J,suggestion:Q})}function Q0($,J,Q){if($==="field"){if(Q.includes("TYPE object")&&Q.includes("{"))return C(`Field '${J}'`,"Object field with inline schema definition","Object fields are parsed as Field.object({}) - you may need to manually define the schema"),!1;if(Q.includes("TYPE geometry<")){let Z=Q.match(/geometry<(\w+)>/)?.[1];if(Z&&!["point","linestring","polygon","multipoint","multilinestring","multipolygon","collection","feature"].includes(Z.toLowerCase()))C(`Field '${J}'`,`Uncommon geometry type: ${Z}`,"Verify the generated Field.geometry() call is correct")}}if($==="index"){if(Q.includes("MTREE")||Q.includes("HNSW"))return C(`Index '${J}'`,"Vector index (MTREE/HNSW) detected","Vector indexes are not yet fully supported in code generation"),!1;if(Q.includes("SEARCH ANALYZER"))C(`Index '${J}'`,"Search analyzer index detected","Search indexes are parsed but may need manual configuration")}if($==="table"){if(Q.includes("CHANGEFEED"))C(`Table '${J}'`,"Changefeed configuration detected","Changefeeds are not yet supported in code generation")}if($==="event")return C(`Event '${J}'`,"Events/triggers are not yet supported","You'll need to manually create event definitions"),!1;if($==="analyzer")return C(`Analyzer '${J}'`,"Analyzers are not yet supported","Analyzer definitions will be skipped"),!1;if($==="function")return C(`Function '${J}'`,"Custom functions are not yet supported","Function definitions will be skipped"),!1;if($==="param")return C(`Parameter '${J}'`,"Database parameters are not yet supported","Parameter definitions will be skipped"),!1;return!0}function J0(){if(L0.length===0)return;console.log(h0.yellow(`
155
155
  ⚠️ Warnings:
156
- `));for(let $ of I0)if(console.log(b0.yellow(` • ${$.feature}: ${$.reason}`)),$.suggestion)console.log(b0.dim(` → ${$.suggestion}`));console.log()}function _0(){I0.length=0}async function $0($){let[J]=await $.query("INFO FOR DB").collect(),Q=y0(J,"Failed to get DB info"),X=Q.tables||{};if(Q.analyzers&&Object.keys(Q.analyzers).length>0)for(let B of Object.keys(Q.analyzers))t("analyzer",B,Q.analyzers[B]||"");if(Q.functions&&Object.keys(Q.functions).length>0)for(let B of Object.keys(Q.functions))t("function",B,Q.functions[B]||"");if(Q.params&&Object.keys(Q.params).length>0)for(let B of Object.keys(Q.params))t("param",B,Q.params[B]||"");let Z=[];for(let B of Object.keys(X)){let _;try{let[z]=await $.query(`INFO FOR TABLE ${B}`).collect();_=y0(z,`Failed to get info for table ${B}`)}catch(z){console.warn(`Failed to get info for table ${B}:`,z instanceof Error?z.message:String(z));continue}let G=X[B];if(!G){console.warn(`No DDL found for table ${B}`);continue}t("table",B,G);let j=E2(G),U=[],W=_.fields||{};for(let z of Object.keys(W)){let M=W[z];if(M){t("field",z,M);try{U.push(V2(M))}catch(E){console.warn(`Failed to parse field ${z} on table ${B}`,E)}}}let V=[],q=_.indexes||{};for(let z of Object.keys(q)){let M=q[z];if(M){if(t("index",z,M))try{V.push(O2(M))}catch(A){console.warn(`Failed to parse index ${z} on table ${B}`,A)}}}let H=[],K=_.events||{};for(let z of Object.keys(K)){let M=K[z];if(M)t("event",z,M)}if(j.name&&j.type)Z.push({name:j.name,type:j.type,drop:j.drop||!1,schemafull:j.schemafull||!1,viewQuery:j.viewQuery,permissions:j.permissions||{},fields:U,indexes:V,events:H})}return{tables:Z}}G0();import{compareSchemas as x2}from"unreal-orm";function P0($){let J=new Map;for(let Q of $.tables){let X=D2(Q);J.set(`${z0(Q.name)}.ts`,X)}return J}function M2($,J,Q){let X=$.matchAll(/record<(\w+)>/g);for(let Z of X){let B=Z[1];if(B&&B!==J)Q.add(`import { ${z0(B)} } from './${z0(B)}';`)}}function D2($){let J=new Set;J.add("import { Table, Field, Index } from 'unreal-orm';"),J.add("import { surql } from 'surrealdb';");for(let B of $.fields)M2(B.type,$.name,J);let Q=z0($.name),X=[],Z=`${Array.from(J).join(`
156
+ `));for(let $ of L0)if(console.log(h0.yellow(` • ${$.feature}: ${$.reason}`)),$.suggestion)console.log(h0.dim(` → ${$.suggestion}`));console.log()}function K0(){L0.length=0}async function X0($){let[J]=await $.query("INFO FOR DB").collect(),Q=f0(J,"Failed to get DB info"),X=Q.tables||{};if(Q.analyzers&&Object.keys(Q.analyzers).length>0)for(let B of Object.keys(Q.analyzers))Q0("analyzer",B,Q.analyzers[B]||"");if(Q.functions&&Object.keys(Q.functions).length>0)for(let B of Object.keys(Q.functions))Q0("function",B,Q.functions[B]||"");if(Q.params&&Object.keys(Q.params).length>0)for(let B of Object.keys(Q.params))Q0("param",B,Q.params[B]||"");let Z=[];for(let B of Object.keys(X)){let j;try{let[z]=await $.query(`INFO FOR TABLE ${B}`).collect();j=f0(z,`Failed to get info for table ${B}`)}catch(z){console.warn(`Failed to get info for table ${B}:`,z instanceof Error?z.message:String(z));continue}let G=X[B];if(!G){console.warn(`No DDL found for table ${B}`);continue}Q0("table",B,G);let U=R2(G),K=[],W=j.fields||{};for(let z of Object.keys(W)){let M=W[z];if(M){Q0("field",z,M);try{K.push(M2(M))}catch(E){console.warn(`Failed to parse field ${z} on table ${B}`,E)}}}let V=[],q=j.indexes||{};for(let z of Object.keys(q)){let M=q[z];if(M){if(Q0("index",z,M))try{V.push(D2(M))}catch(A){console.warn(`Failed to parse index ${z} on table ${B}`,A)}}}let H=[],_=j.events||{};for(let z of Object.keys(_)){let M=_[z];if(M)Q0("event",z,M)}if(U.name&&U.type)Z.push({name:U.name,type:U.type,drop:U.drop||!1,schemafull:U.schemafull||!1,viewQuery:U.viewQuery,permissions:U.permissions||{},fields:K,indexes:V,events:H})}return{tables:Z}}U0();import{compareSchemas as g2}from"unreal-orm";function N0($){let J=new Map;for(let Q of $.tables){let X=P2(Q);J.set(`${W0(Q.name)}.ts`,X)}return J}function I2($,J,Q){let X=$.matchAll(/record<(\w+)>/g);for(let Z of X){let B=Z[1];if(B&&B!==J)Q.add(`import { ${W0(B)} } from './${W0(B)}';`)}}function P2($){let J=new Set;J.add("import { Table, Field, Index } from 'unreal-orm';"),J.add("import { surql } from 'surrealdb';");for(let B of $.fields)I2(B.type,$.name,J);let Q=W0($.name),X=[],Z=`${Array.from(J).join(`
157
157
  `)}
158
158
 
159
159
  `;if($.type==="VIEW"){if(Z+=`export class ${Q} extends Table.view({
@@ -164,75 +164,75 @@ Original Error: ${Q}`)}else J=new U1,await J.connect($.url,$);if($.namespace&&$.
164
164
  `,Z+=` name: "${$.name}",
165
165
  `,$.schemafull)Z+=` schemafull: true,
166
166
  `;Z+=` fields: {
167
- `,Z+=H1($.fields," "),Z+=` },
167
+ `,Z+=M1($.fields," "),Z+=` },
168
168
  `,Z+=`}) {}
169
169
  `}else{if(Z+=`export class ${Q} extends Table.normal({
170
170
  `,Z+=` name: "${$.name}",
171
171
  `,$.schemafull)Z+=` schemafull: true,
172
172
  `;Z+=` fields: {
173
- `,Z+=H1($.fields," "),Z+=` },
173
+ `,Z+=M1($.fields," "),Z+=` },
174
174
  `,Z+=`}) {}
175
175
  `}if($.indexes.length>0){Z+=`
176
- `;for(let B of $.indexes){let G=(B.name.includes($.name)?B.name:`${$.name}_${B.name}`).replace(/[^a-zA-Z0-9_]/g,"_");Z+=F2(B,Q,G),X.push(G)}}return Z+=`
176
+ `;for(let B of $.indexes){let G=(B.name.includes($.name)?B.name:`${$.name}_${B.name}`).replace(/[^a-zA-Z0-9_]/g,"_");Z+=N2(B,Q,G),X.push(G)}}return Z+=`
177
177
  export const ${Q}Definitions = [${Q}${X.length>0?`, ${X.join(", ")}`:""}];
178
- `,Z}function R2($){let J=[],Q="";for(let X=0;X<$.length;X++){let Z=$[X];if(Z==="."){if(Q)J.push(Q);Q=""}else if(Z==="["&&$.slice(X,X+3)==="[*]"){if(Q)J.push(Q);J.push("[*]"),Q="",X+=2}else Q+=Z}if(Q)J.push(Q);return J}function I2($){let J=$.filter((X)=>!X.name.endsWith(".*")),Q={children:new Map};for(let X of J){let Z=R2(X.name),B=Q;for(let _=0;_<Z.length;_++){let G=Z[_];if(G==="[*]"){if(!B.arrayElement)B.arrayElement={children:new Map};B=B.arrayElement}else if(G){if(!B.children.has(G))B.children.set(G,{children:new Map});B=B.children.get(G)}}B.field=X}return Q}function H1($,J){let Q=I2($);return g0(Q,J)}function g0($,J){let Q="";for(let[X,Z]of $.children)if(Z.arrayElement&&Z.arrayElement.children.size>0){let B=Z.field?f0(Z.field):"";Q+=`${J}${X}: Field.array(Field.object({
179
- `,Q+=g0(Z.arrayElement,`${J} `),Q+=`${J}})${B?`, ${B}`:""}),
180
- `}else if(Z.children.size>0){let B=Z.field?f0(Z.field):"";Q+=`${J}${X}: Field.object({
181
- `,Q+=g0(Z,`${J} `),Q+=`${J}}${B?`, ${B}`:""}),
182
- `}else if(Z.field)Q+=`${J}${X}: ${P2(Z.field)},
183
- `;return Q}function f0($){let J=[];if($.default)J.push(`default: surql\`${$.default}\``);if($.value)J.push(`value: surql\`${$.value}\``);if($.assert)J.push(`assert: surql\`${$.assert}\``);if($.readonly)J.push("readonly: true");return J.length>0?`{ ${J.join(", ")} }`:""}function P2($){let J=f0($),Q=$.type;if(Q.startsWith("option<")){let X=Q.match(/option<(.+)>/)?.[1];if(X)return`Field.option(${K0(X,J||"")})`}if(Q.includes(" | ")){let X=Q.split(" | ").map((B)=>B.trim());if(X.includes("none")){let B=X.filter((_)=>_!=="none");if(B.length===1&&B[0])return`Field.option(${K0(B[0],J||"")})`}return`Field.custom('${Q.replace(/'/g,"\\'")}'${J?`, ${J}`:""}) /* TODO: Specify union type */`}return K0(Q,J||"")}function K0($,J){let Q=J?J:"";if($==="string")return`Field.string(${Q})`;if($==="int")return`Field.int(${Q})`;if($==="float")return`Field.float(${Q})`;if($==="number")return`Field.number(${Q})`;if($==="bool")return`Field.bool(${Q})`;if($==="datetime")return`Field.datetime(${Q})`;if($==="duration")return`Field.duration(${Q})`;if($==="decimal")return`Field.decimal(${Q})`;if($==="uuid")return`Field.uuid(${Q})`;if($==="bytes")return`Field.bytes(${Q})`;if($==="any")return`Field.any(${Q})`;if($.startsWith("array<")){let X=$.slice(6,-1);return`Field.array(${K0(X,"")}${Q?`, ${Q}`:""})`}if($.startsWith("set<")){let X=$.slice(4,-1);return`Field.set(${K0(X,"")}${Q?`, ${Q}`:""})`}if($.startsWith("record<")){let X=$.match(/record<(\w+)>/);if(X?.[1]){let Z=X[1];return`Field.record(() => ${z0(Z)}${Q?`, ${Q}`:""})`}return`Field.record(() => Object${Q?`, ${Q}`:""})`}if($.startsWith("geometry<")){let X=$.match(/geometry<(\w+)>/);if(X?.[1])return`Field.geometry('${X[1]}'${Q?`, ${Q}`:""})`}if($==="geometry")return`Field.geometry('feature'${Q?`, ${Q}`:""})`;if($==="object")return`Field.object({}${Q?`, ${Q}`:""})`;return`Field.custom('${$}'${Q?`, ${Q}`:""}) /* TODO: Specify type, e.g., Field.custom<YourType>(...) */`}function F2($,J,Q){let X=`export const ${Q} = Index.define(() => ${J}, {
178
+ `,Z}function F2($){let J=[],Q="";for(let X=0;X<$.length;X++){let Z=$[X];if(Z==="."){if(Q)J.push(Q);Q=""}else if(Z==="["&&$.slice(X,X+3)==="[*]"){if(Q)J.push(Q);J.push("[*]"),Q="",X+=2}else Q+=Z}if(Q)J.push(Q);return J}function w2($){let J=$.filter((X)=>!X.name.endsWith(".*")),Q={children:new Map};for(let X of J){let Z=F2(X.name),B=Q;for(let j=0;j<Z.length;j++){let G=Z[j];if(G==="[*]"){if(!B.arrayElement)B.arrayElement={children:new Map};B=B.arrayElement}else if(G){if(!B.children.has(G))B.children.set(G,{children:new Map});B=B.children.get(G)}}B.field=X}return Q}function M1($,J){let Q=w2($);return m0(Q,J)}function m0($,J){let Q="";for(let[X,Z]of $.children)if(Z.arrayElement&&Z.arrayElement.children.size>0){let B=Z.field?p0(Z.field):"";Q+=`${J}${X}: Field.array(Field.object({
179
+ `,Q+=m0(Z.arrayElement,`${J} `),Q+=`${J}})${B?`, ${B}`:""}),
180
+ `}else if(Z.children.size>0){let B=Z.field?p0(Z.field):"";Q+=`${J}${X}: Field.object({
181
+ `,Q+=m0(Z,`${J} `),Q+=`${J}}${B?`, ${B}`:""}),
182
+ `}else if(Z.field)Q+=`${J}${X}: ${L2(Z.field)},
183
+ `;return Q}function p0($){let J=[];if($.default)J.push(`default: surql\`${$.default}\``);if($.value)J.push(`value: surql\`${$.value}\``);if($.assert)J.push(`assert: surql\`${$.assert}\``);if($.readonly)J.push("readonly: true");return J.length>0?`{ ${J.join(", ")} }`:""}function L2($){let J=p0($),Q=$.type;if(Q.startsWith("option<")){let X=Q.match(/option<(.+)>/)?.[1];if(X)return`Field.option(${H0(X,J||"")})`}if(Q.includes(" | ")){let X=Q.split(" | ").map((B)=>B.trim());if(X.includes("none")){let B=X.filter((j)=>j!=="none");if(B.length===1&&B[0])return`Field.option(${H0(B[0],J||"")})`}return`Field.custom('${Q.replace(/'/g,"\\'")}'${J?`, ${J}`:""}) /* TODO: Specify union type */`}return H0(Q,J||"")}function H0($,J){let Q=J?J:"";if($==="string")return`Field.string(${Q})`;if($==="int")return`Field.int(${Q})`;if($==="float")return`Field.float(${Q})`;if($==="number")return`Field.number(${Q})`;if($==="bool")return`Field.bool(${Q})`;if($==="datetime")return`Field.datetime(${Q})`;if($==="duration")return`Field.duration(${Q})`;if($==="decimal")return`Field.decimal(${Q})`;if($==="uuid")return`Field.uuid(${Q})`;if($==="bytes")return`Field.bytes(${Q})`;if($==="any")return`Field.any(${Q})`;if($.startsWith("array<")){let X=$.slice(6,-1);return`Field.array(${H0(X,"")}${Q?`, ${Q}`:""})`}if($.startsWith("set<")){let X=$.slice(4,-1);return`Field.set(${H0(X,"")}${Q?`, ${Q}`:""})`}if($.startsWith("record<")){let X=$.match(/record<(\w+)>/);if(X?.[1]){let Z=X[1];return`Field.record(() => ${W0(Z)}${Q?`, ${Q}`:""})`}return`Field.record(() => Object${Q?`, ${Q}`:""})`}if($.startsWith("geometry<")){let X=$.match(/geometry<(\w+)>/);if(X?.[1])return`Field.geometry('${X[1]}'${Q?`, ${Q}`:""})`}if($==="geometry")return`Field.geometry('feature'${Q?`, ${Q}`:""})`;if($==="object")return`Field.object({}${Q?`, ${Q}`:""})`;return`Field.custom('${$}'${Q?`, ${Q}`:""}) /* TODO: Specify type, e.g., Field.custom<YourType>(...) */`}function N2($,J,Q){let X=`export const ${Q} = Index.define(() => ${J}, {
184
184
  `;if(X+=` name: "${$.name}",
185
185
  `,X+=` fields: [${$.columns.map((Z)=>`"${Z}"`).join(", ")}],
186
186
  `,$.unique)X+=` unique: true,
187
187
  `;return X+=`});
188
- `,X}function z0($){return $.split("_").map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join("")}import{compareSchemas as w2}from"unreal-orm";function W1($,J,Q){let X=L2(J,Q);if(X.length===0)return{content:$,addedFields:[],addedIndexes:[],removedFields:[],removedIndexes:[]};let Z=$,B=[],_=[],G=[],j=[],U=X.filter((H)=>H.type==="field_added");for(let H of U){if(!H.field)continue;let K=J.fields.find((M)=>M.name===H.field);if(!K)continue;if(K.name.includes("."))continue;if(K.name.includes("[*]"))continue;let z=v2(K);Z=N2(Z,K.name,z),B.push(K.name)}let W=X.filter((H)=>H.type==="index_added");for(let H of W){if(!H.index)continue;let K=J.indexes.find((E)=>E.name===H.index);if(!K)continue;let z=A1(J.name),M=k2(K,z);Z=S2(Z,K.name,M,z),_.push(K.name)}let V=X.filter((H)=>H.type==="field_removed");for(let H of V){if(!H.field)continue;if(H.field.includes("."))continue;if(H.field.includes("[*]"))continue;Z=T2(Z,H.field),G.push(H.field)}let q=X.filter((H)=>H.type==="index_removed");for(let H of q){if(!H.index)continue;Z=C2(Z,H.index),j.push(H.index)}return{content:Z,addedFields:B,addedIndexes:_,removedFields:G,removedIndexes:j}}function L2($,J){return w2({tables:[$]},{tables:[J]})}function v2($){let J=[];if($.default)J.push(`default: surql\`${$.default}\``);if($.value)J.push(`value: surql\`${$.value}\``);if($.assert)J.push(`assert: surql\`${$.assert}\``);let Q=J.length>0?`{ ${J.join(", ")} }`:"";return q0($.type,Q)}function q0($,J){let Q=J||"";if($.startsWith("option<")){let X=$.match(/option<(.+)>/)?.[1];if(X)return`Field.option(${q0(X,"")})${Q?`, ${Q}`:""}`}if($.includes(" | ")){let X=$.split(" | ").map((Z)=>Z.trim());if(X.includes("none")){let Z=X.filter((B)=>B!=="none");if(Z.length===1&&Z[0])return`Field.option(${q0(Z[0],"")})${Q?`, ${Q}`:""}`}}if($==="string")return`Field.string(${Q})`;if($==="int")return`Field.int(${Q})`;if($==="float")return`Field.float(${Q})`;if($==="number")return`Field.number(${Q})`;if($==="bool")return`Field.bool(${Q})`;if($==="datetime")return`Field.datetime(${Q})`;if($==="duration")return`Field.duration(${Q})`;if($==="decimal")return`Field.decimal(${Q})`;if($==="uuid")return`Field.uuid(${Q})`;if($==="bytes")return`Field.bytes(${Q})`;if($==="any")return`Field.any(${Q})`;if($.startsWith("array<")){let X=$.slice(6,-1);return`Field.array(${q0(X,"")}${Q?`, ${Q}`:""})`}if($.startsWith("set<")){let X=$.slice(4,-1);return`Field.set(${q0(X,"")}${Q?`, ${Q}`:""})`}if($.startsWith("record<")){let X=$.match(/record<(\w+)>/);if(X?.[1]){let Z=X[1];return`Field.record(() => ${A1(Z)}${Q?`, ${Q}`:""})`}}return`Field.custom('${$}'${Q?`, ${Q}`:""})`}function N2($,J,Q){let X=$.match(/fields:\s*\{/);if(!X||X.index===void 0)return $;let Z=X.index+X[0].length,B=1,_=Z;for(let z=Z;z<$.length&&B>0;z++){if($[z]==="{")B++;if($[z]==="}")B--;if(B===0){_=z;break}}let G=$.slice(Z,_),j=G.match(/\n(\s+)\w+:/),U=j?j[1]:" ",W=G.trim(),V=W.length>0&&!W.endsWith(","),q=$,H=_;if(V){let z=G.match(/\S\s*$/);if(z&&z.index!==void 0){let M=Z+z.index+1;q=`${$.slice(0,M)},${$.slice(M)}`,H++}}let K=`
189
- ${U}// Added from database
190
- ${U}${J}: ${Q},`;return`${q.slice(0,H)}${K}
191
- ${q.slice(H)}`}function S2($,J,Q,X){let Z=$.match(new RegExp(`export const ${X}Definitions\\s*=`));if(Z&&Z.index!==void 0){let B=Z.index,_=`// Added from database
188
+ `,X}function W0($){return $.split("_").map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join("")}import{compareSchemas as v2}from"unreal-orm";function D1($,J,Q){let X=S2(J,Q);if(X.length===0)return{content:$,addedFields:[],addedIndexes:[],removedFields:[],removedIndexes:[]};let Z=$,B=[],j=[],G=[],U=[],K=X.filter((H)=>H.type==="field_added");for(let H of K){if(!H.field)continue;let _=J.fields.find((M)=>M.name===H.field);if(!_)continue;if(_.name.includes("."))continue;if(_.name.includes("[*]"))continue;let z=k2(_);Z=T2(Z,_.name,z),B.push(_.name)}let W=X.filter((H)=>H.type==="index_added");for(let H of W){if(!H.index)continue;let _=J.indexes.find((E)=>E.name===H.index);if(!_)continue;let z=R1(J.name),M=C2(_,z);Z=x2(Z,_.name,M,z),j.push(_.name)}let V=X.filter((H)=>H.type==="field_removed");for(let H of V){if(!H.field)continue;if(H.field.includes("."))continue;if(H.field.includes("[*]"))continue;Z=y2(Z,H.field),G.push(H.field)}let q=X.filter((H)=>H.type==="index_removed");for(let H of q){if(!H.index)continue;Z=b2(Z,H.index),U.push(H.index)}return{content:Z,addedFields:B,addedIndexes:j,removedFields:G,removedIndexes:U}}function S2($,J){return v2({tables:[$]},{tables:[J]})}function k2($){let J=[];if($.default)J.push(`default: surql\`${$.default}\``);if($.value)J.push(`value: surql\`${$.value}\``);if($.assert)J.push(`assert: surql\`${$.assert}\``);let Q=J.length>0?`{ ${J.join(", ")} }`:"";return A0($.type,Q)}function A0($,J){let Q=J||"";if($.startsWith("option<")){let X=$.match(/option<(.+)>/)?.[1];if(X)return`Field.option(${A0(X,"")})${Q?`, ${Q}`:""}`}if($.includes(" | ")){let X=$.split(" | ").map((Z)=>Z.trim());if(X.includes("none")){let Z=X.filter((B)=>B!=="none");if(Z.length===1&&Z[0])return`Field.option(${A0(Z[0],"")})${Q?`, ${Q}`:""}`}}if($==="string")return`Field.string(${Q})`;if($==="int")return`Field.int(${Q})`;if($==="float")return`Field.float(${Q})`;if($==="number")return`Field.number(${Q})`;if($==="bool")return`Field.bool(${Q})`;if($==="datetime")return`Field.datetime(${Q})`;if($==="duration")return`Field.duration(${Q})`;if($==="decimal")return`Field.decimal(${Q})`;if($==="uuid")return`Field.uuid(${Q})`;if($==="bytes")return`Field.bytes(${Q})`;if($==="any")return`Field.any(${Q})`;if($.startsWith("array<")){let X=$.slice(6,-1);return`Field.array(${A0(X,"")}${Q?`, ${Q}`:""})`}if($.startsWith("set<")){let X=$.slice(4,-1);return`Field.set(${A0(X,"")}${Q?`, ${Q}`:""})`}if($.startsWith("record<")){let X=$.match(/record<(\w+)>/);if(X?.[1]){let Z=X[1];return`Field.record(() => ${R1(Z)}${Q?`, ${Q}`:""})`}}return`Field.custom('${$}'${Q?`, ${Q}`:""})`}function T2($,J,Q){let X=$.match(/fields:\s*\{/);if(!X||X.index===void 0)return $;let Z=X.index+X[0].length,B=1,j=Z;for(let z=Z;z<$.length&&B>0;z++){if($[z]==="{")B++;if($[z]==="}")B--;if(B===0){j=z;break}}let G=$.slice(Z,j),U=G.match(/\n(\s+)\w+:/),K=U?U[1]:" ",W=G.trim(),V=W.length>0&&!W.endsWith(","),q=$,H=j;if(V){let z=G.match(/\S\s*$/);if(z&&z.index!==void 0){let M=Z+z.index+1;q=`${$.slice(0,M)},${$.slice(M)}`,H++}}let _=`
189
+ ${K}// Added from database
190
+ ${K}${J}: ${Q},`;return`${q.slice(0,H)}${_}
191
+ ${q.slice(H)}`}function x2($,J,Q,X){let Z=$.match(new RegExp(`export const ${X}Definitions\\s*=`));if(Z&&Z.index!==void 0){let B=Z.index,j=`// Added from database
192
192
  ${Q}
193
- `,G=$.slice(0,B)+_+$.slice(B),j=J.replace(/[^a-zA-Z0-9_]/g,"_");return G=G.replace(new RegExp(`(export const ${X}Definitions\\s*=\\s*\\[${X})([,\\s\\w]*)(\\])`),`$1$2, ${j}$3`),G}return`${$}
193
+ `,G=$.slice(0,B)+j+$.slice(B),U=J.replace(/[^a-zA-Z0-9_]/g,"_");return G=G.replace(new RegExp(`(export const ${X}Definitions\\s*=\\s*\\[${X})([,\\s\\w]*)(\\])`),`$1$2, ${U}$3`),G}return`${$}
194
194
  // Added from database
195
- ${Q}`}function k2($,J){let X=`export const ${$.name.replace(/[^a-zA-Z0-9_]/g,"_")} = Index.define(() => ${J}, {
195
+ ${Q}`}function C2($,J){let X=`export const ${$.name.replace(/[^a-zA-Z0-9_]/g,"_")} = Index.define(() => ${J}, {
196
196
  `;if(X+=` name: "${$.name}",
197
197
  `,X+=` fields: [${$.columns.map((Z)=>`"${Z}"`).join(", ")}],
198
198
  `,$.unique)X+=` unique: true,
199
199
  `;return X+=`});
200
- `,X}function T2($,J){let Q=new RegExp(`([ \\t]*)(${h0(J)}\\s*:\\s*(?:Field\\.|\\{))`),X=$.match(Q);if(!X||X.index===void 0)return $;let Z=X[1]??"",B=X.index+Z.length,_=0,G=0,j=0,U=B,W=!1,V="",q=!1;for(let E=B;E<$.length;E++){let A=$[E],R=E>0?$[E-1]:"";if((A==='"'||A==="'"||A==="`")&&R!=="\\"){if(!W&&!q)if(A==="`")q=!0;else W=!0,V=A;else if(q&&A==="`")q=!1;else if(W&&A===V)W=!1;continue}if(W||q)continue;if(A==="(")_++;if(A===")")_--;if(A==="{")G++;if(A==="}")G--;if(A==="[")j++;if(A==="]")j--;if(_===0&&j===0){if(G===0&&A===","){U=E+1;break}if(G===-1&&A==="}"){U=E;while(U>B&&/\s/.test($[U-1]||""))U--;break}}}let z=$.slice(B,U).split(`
200
+ `,X}function y2($,J){let Q=new RegExp(`([ \\t]*)(${u0(J)}\\s*:\\s*(?:Field\\.|\\{))`),X=$.match(Q);if(!X||X.index===void 0)return $;let Z=X[1]??"",B=X.index+Z.length,j=0,G=0,U=0,K=B,W=!1,V="",q=!1;for(let E=B;E<$.length;E++){let A=$[E],R=E>0?$[E-1]:"";if((A==='"'||A==="'"||A==="`")&&R!=="\\"){if(!W&&!q)if(A==="`")q=!0;else W=!0,V=A;else if(q&&A==="`")q=!1;else if(W&&A===V)W=!1;continue}if(W||q)continue;if(A==="(")j++;if(A===")")j--;if(A==="{")G++;if(A==="}")G--;if(A==="[")U++;if(A==="]")U--;if(j===0&&U===0){if(G===0&&A===","){K=E+1;break}if(G===-1&&A==="}"){K=E;while(K>B&&/\s/.test($[K-1]||""))K--;break}}}let z=$.slice(B,K).split(`
201
201
  `).map((E,A)=>{if(A===0)return`${Z}// ${E}`;let I=E.match(/^(\s*)/)?.[1]??"",O=E.slice(I.length);return`${I}// ${O}`}).join(`
202
202
  `),M=`${Z}// Removed from database - uncomment if needed
203
- `;return $.slice(0,B)+M+z+$.slice(U)}function C2($,J){let Q=J.replace(/[^a-zA-Z0-9_]/g,"_"),X=new RegExp(`export\\s+const\\s+${h0(Q)}\\s*=\\s*Index\\.define`),Z=$.match(X);if(!Z||Z.index===void 0)return $;let B=Z.index,_=0,G=0,j=B,U=!1;for(let M=B;M<$.length;M++){let E=$[M];if(E==="(")G++,U=!0;if(E===")")G--;if(E==="{")_++;if(E==="}")_--;if(U&&G===0&&_===0){if(j=M+1,$[M+1]===";")j=M+2;break}}let H=`// Removed from database - uncomment if needed
204
- ${$.slice(B,j).split(`
203
+ `;return $.slice(0,B)+M+z+$.slice(K)}function b2($,J){let Q=J.replace(/[^a-zA-Z0-9_]/g,"_"),X=new RegExp(`export\\s+const\\s+${u0(Q)}\\s*=\\s*Index\\.define`),Z=$.match(X);if(!Z||Z.index===void 0)return $;let B=Z.index,j=0,G=0,U=B,K=!1;for(let M=B;M<$.length;M++){let E=$[M];if(E==="(")G++,K=!0;if(E===")")G--;if(E==="{")j++;if(E==="}")j--;if(K&&G===0&&j===0){if(U=M+1,$[M+1]===";")U=M+2;break}}let H=`// Removed from database - uncomment if needed
204
+ ${$.slice(B,U).split(`
205
205
  `).map((M)=>{let A=M.match(/^(\s*)/)?.[1]??"",R=M.slice(A.length);return`${A}// ${R}`}).join(`
206
- `)}`,K=$.slice(0,B)+H+$.slice(j),z=new RegExp(`,\\s*${h0(Q)}(?=[\\s,\\]])`);return K=K.replace(z,""),K}function h0($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function A1($){return $.split("_").map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join("")}import N6 from"chalk";function V1($,J,Q){let X=[],Z=P0($),B=new Set,_=Q?x2($,Q):[];for(let G of _)B.add(G.table);for(let[G,j]of Z){let U=J.get(G),W=G.replace(".ts","").toLowerCase();if(!U)X.push({filename:G,type:"create",newContent:j});else if(U!==j)if(Q){if(B.has(W)){let V=$.tables.find((H)=>H.name===W),q=Q.tables.find((H)=>H.name===W);if(V&&q){let H=W1(U,V,q);X.push({filename:G,type:"update",oldContent:U,newContent:H.content,addedFields:H.addedFields,addedIndexes:H.addedIndexes,removedFields:H.removedFields,removedIndexes:H.removedIndexes})}else X.push({filename:G,type:"update",oldContent:U,newContent:j})}}else X.push({filename:G,type:"update",oldContent:U,newContent:j})}for(let G of J.keys())if(!Z.has(G))X.push({filename:G,type:"delete",oldContent:J.get(G),newContent:""});return X}import{extractTableFromModel as y2,extractIndexFromDefinition as b2,isModelClass as g2,isIndexDefinition as f2}from"unreal-orm";import{readdirSync as h2}from"node:fs";import{join as m2,resolve as u2}from"node:path";import{createJiti as p2}from"jiti";var c2=p2(import.meta.url,{interopDefault:!0});async function Q0($){let J=[];for(let Q of h2($).filter((X)=>X.endsWith(".ts"))){let X=u2(m2($,Q));try{let Z=await c2.import(X),B=new Map,_=[];for(let[,G]of Object.entries(Z))if(g2(G)){let j=y2(G);B.set(j.name,j)}else if(f2(G)){let{index:j,tableName:U}=b2(G);_.push({index:j,tableName:U})}for(let{index:G,tableName:j}of _){let U=B.get(j);if(U)U.indexes.push(G)}J.push(...B.values())}catch(Z){console.warn(`Failed to import ${Q}:`,Z)}}return{tables:J}}import b from"chalk";import{diffLines as O1}from"diff";var m0=3;function E1($,J,Q){let X=[];if(!J){X.push(b.bold.green(`
207
- +++ ${$} (new file)`)),X.push(b.dim("─".repeat(60)));let _=Q.split(`
208
- `).slice(0,20);for(let G of _)X.push(b.green(`+ ${G}`));if(Q.split(`
209
- `).length>20)X.push(b.dim(`... ${Q.split(`
210
- `).length-20} more lines`));return X.push(b.dim("─".repeat(60))),X.join(`
211
- `)}X.push(b.bold(`
212
- --- ${$}`)),X.push(b.bold(`+++ ${$}`)),X.push(b.dim("─".repeat(60)));let Z=O1(J,Q),B=d2(Z);if(B.length===0)X.push(b.dim(" (no changes)"));for(let _ of B){X.push(b.cyan(`@@ -${_.oldStart},${_.oldLines} +${_.newStart},${_.newLines} @@`));for(let G of _.lines)if(G.type==="added")X.push(b.green(`+ ${G.content}`));else if(G.type==="removed")X.push(b.red(`- ${G.content}`));else X.push(b.dim(` ${G.content}`));X.push("")}return X.push(b.dim("─".repeat(60))),X.join(`
213
- `)}function d2($){return l2($)}function l2($){let J=[],Q=null,X=[],Z=1,B=1;for(let _ of $){if(!_)continue;let G=_.value.split(`
214
- `);if(G[G.length-1]==="")G.pop();for(let j of G){let U=_.added?"added":_.removed?"removed":"context";if(X.push({type:U,content:j,oldLine:U!=="added"?Z:void 0,newLine:U!=="removed"?B:void 0}),U!=="added")Z++;if(U!=="removed")B++}}for(let _=0;_<X.length;_++){let G=X[_];if(!G)continue;if(G.type==="added"||G.type==="removed"){if(!Q){let j=Math.max(0,_-m0),U=X.slice(j,_),W=U[0],V=W?.oldLine??G.oldLine??1,q=W?.newLine??G.newLine??1;Q={oldStart:V,newStart:q,oldLines:0,newLines:0,lines:[]};for(let H of U)if(H)Q.lines.push({type:"context",content:H.content}),Q.oldLines++,Q.newLines++}if(Q.lines.push({type:G.type,content:G.content}),G.type!=="added")Q.oldLines++;if(G.type!=="removed")Q.newLines++}else if(Q){let j=-1;for(let W=_+1;W<X.length;W++){let V=X[W];if(V&&V.type!=="context"){j=W;break}}if(j!==-1){if(j-_<=m0*2){Q.lines.push({type:"context",content:G.content}),Q.oldLines++,Q.newLines++;continue}}if(Q.lines.slice().reverse().findIndex((W)=>W.type!=="context")<m0)Q.lines.push({type:"context",content:G.content}),Q.oldLines++,Q.newLines++;else J.push(Q),Q=null}}if(Q)J.push(Q);return J}function M1($,J){if(!$)return`New file (${J.split(`
215
- `).length} lines)`;let Q=O1($,J),X=0,Z=0;for(let _ of Q){let G=_.value.split(`
216
- `).length-1;if(_.added)X+=G;else if(_.removed)Z+=G}if(X===0&&Z===0)return"No changes";let B=[];if(X>0)B.push(b.green(`+${X}`));if(Z>0)B.push(b.red(`-${Z}`));return B.join(" ")}u();var R1=new r2().name("pull").description("Introspect database and generate TypeScript schema").option("--url <url>","Database URL (e.g., http://localhost:8000)").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Auth level: root, namespace, or database").option("-s, --schema-dir <path>","Schema directory path").option("--embedded <mode>","Use embedded mode (memory or file path)").option("-y, --yes","Skip confirmation prompt").action(async($)=>{Y.header("UnrealORM Pull","Introspect database and generate schema"),_0();let J=await o(),Q=await n({cliOutput:$.schemaDir,config:J}),X=$.url||$.username||$.password||$.namespace||$.database||$.authLevel||$.embedded,Z=await s({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:J,skipAutoConfig:!$.yes&&!X});if(!Z)Y.error("Failed to establish database connection."),process.exit(1);let B=Y.spin("Introspecting database schema..."),_;try{_=await $0(Z),B.succeed(`Found ${_.tables.length} table(s)`)}catch(K){B.fail("Failed to introspect database"),Y.error(K instanceof Error?K.message:String(K)),await Z.close(),process.exit(1)}B.start("Planning file changes...");let G=new Map;if(u0(Q))try{let K=a2(Q).filter((z)=>z.endsWith(".ts"));for(let z of K){let M=i2(D1(Q,z),"utf-8");G.set(z,M)}}catch(K){}let j;if(u0(Q))try{j=await Q0(Q)}catch{}let U;try{U=V1(_,G,j),B.succeed("File changes planned")}catch(K){B.fail("Failed to plan file changes"),Y.error(K instanceof Error?K.message:String(K)),await Z.close(),process.exit(1)}if(U.length===0)Y.success("All files are up to date!"),await Z.close(),e(),process.exit(0);let W=U.filter((K)=>K.type==="create").length,V=U.filter((K)=>K.type==="delete").length,q=U.filter((K)=>K.type==="update").length;if(Y.divider(),Y.info("FILE CHANGE SUMMARY (Database -> Code)"),Y.divider(),Y.newline(),Y.printer.log(` Total files: ${Y.bold(String(U.length))}`),W>0)Y.printer.log(` ${Y.theme.success("+")} New files: ${W}`);if(V>0)Y.printer.log(` ${Y.theme.error("-")} Deleted files: ${V}`);if(q>0)Y.printer.log(` ${Y.theme.warning("~")} Updated files: ${q}`);Y.newline();for(let K of U){let z=K.type==="create"?Y.theme.success("+"):K.type==="delete"?Y.theme.error("-"):Y.theme.warning("~");Y.printer.log(` ${z} ${K.filename}`)}Y.newline();let H=[];if(!$.yes){let K=!1;Y.divider(),Y.info("FILE REVIEW"),Y.divider(),Y.newline();for(let z of U){if(!z)continue;if(K){H.push(z);continue}Y.printer.clear();let M=z.type==="create"?Y.theme.success("CREATE"):z.type==="delete"?Y.theme.error("DELETE"):Y.theme.warning("UPDATE");Y.printer.log(Y.bold(`[${U.indexOf(z)+1}/${U.length}] ${M}: ${z.filename}`)),Y.printer.log(Y.dim(` ${M1(z.oldContent,z.newContent)}`)),Y.printer.log(E1(z.filename,z.oldContent,z.newContent));let E=await U0(z.filename,U.indexOf(z)+1,U.length);if(E==="cancel")Y.newline(),Y.warn("Operation cancelled."),await Z.close(),process.exit(0);if(E==="all"){K=!0,H.push(z);for(let A of U.slice(U.indexOf(z)+1))if(A)H.push(A);break}if(E==="yes")H.push(z)}if(Y.printer.clear(),H.length===0)Y.warn("No files selected. Operation cancelled."),await Z.close(),process.exit(0);Y.divider(),Y.success("APPLYING SELECTED CHANGES"),Y.divider(),Y.info(`Will apply ${H.length} of ${U.length} file changes`),Y.newline()}else Y.divider(),Y.success("APPLYING ALL CHANGES (--yes flag)"),Y.divider(),Y.info(`Applying all ${U.length} file changes`),Y.newline(),H.push(...U);B.start("Applying file changes...");try{if(!u0(Q))o2(Q,{recursive:!0});for(let K of H){let z=D1(Q,K.filename);if(K.type==="delete")n2(z);else s2(z,K.newContent,"utf-8")}B.succeed(`Applied ${H.length} file change(s) to ${Q}`)}catch(K){B.fail("Failed to apply file changes"),Y.error(K instanceof Error?K.message:String(K)),await Z.close(),process.exit(1)}await Z.close(),e(),Y.header("Schema pull complete!"),Y.dim("Changes applied:");for(let K of H){let z=K.type==="create"?"+":K.type==="delete"?"-":"~";console.log(Y.dim(` ${z} ${K.filename}`))}Y.newline()});import{Command as $4}from"@commander-js/extra-typings";import{existsSync as Q4}from"node:fs";G0();import{compareSchemas as J4}from"unreal-orm";function d0($,J,Q){return t2($,J,Q)}function t2($,J,Q){let X=J.tables.find((B)=>B.name===$.table),Z=Q.tables.find((B)=>B.name===$.table);switch($.type){case"table_added":{if(!X)return null;return e2(X)}case"table_removed":return`REMOVE TABLE ${$.table};`;case"table_type_changed":{if(!X)return null;return I1(X,!0)}case"field_added":{if(!X||!$.field)return null;let B=X.fields.find((_)=>_.name===$.field);if(!B)return null;return p0($.table,B)}case"field_removed":return`REMOVE FIELD ${$.field} ON TABLE ${$.table};`;case"field_type_changed":case"field_default_changed":case"field_assertion_changed":{if(!X||!$.field)return null;let B=X.fields.find((_)=>_.name===$.field);if(!B)return null;return p0($.table,B,!0)}case"index_added":{if(!X||!$.index)return null;let B=X.indexes.find((_)=>_.name===$.index);if(!B)return null;return c0($.table,B)}case"index_removed":return`REMOVE INDEX ${$.index} ON TABLE ${$.table};`;case"index_modified":{if(!X||!$.index)return null;let B=X.indexes.find((_)=>_.name===$.index);if(!B)return null;return c0($.table,B,!0)}default:return null}}function e2($){let J=[];J.push(I1($));for(let Q of $.fields){if(Q.name.includes("[*]"))continue;let X=$.type==="RELATION"&&(Q.name==="in"||Q.name==="out");J.push(p0($.name,Q,X))}for(let Q of $.indexes)J.push(c0($.name,Q));return J.join(`
217
- `)}function I1($,J=!1){let X=[`${J?"DEFINE TABLE OVERWRITE":"DEFINE TABLE"} ${$.name}`];if($.type==="RELATION")X.push("TYPE RELATION");else if($.type==="VIEW"){if(X.push("TYPE ANY"),$.viewQuery)X.push(`AS ${$.viewQuery}`)}if($.schemafull)X.push("SCHEMAFULL");let Z=[];if($.permissions.select)Z.push(`FOR select ${$.permissions.select}`);if($.permissions.create)Z.push(`FOR create ${$.permissions.create}`);if($.permissions.update)Z.push(`FOR update ${$.permissions.update}`);if($.permissions.delete)Z.push(`FOR delete ${$.permissions.delete}`);if(Z.length>0)X.push(`PERMISSIONS ${Z.join(", ")}`);return`${X.join(" ")};`}function p0($,J,Q=!1){let Z=[`${Q?"DEFINE FIELD OVERWRITE":"DEFINE FIELD"} ${J.name} ON TABLE ${$}`];if(J.flex)Z.push("FLEXIBLE");if(J.type)Z.push(`TYPE ${J.type}`);if(J.value)Z.push(`VALUE ${J.value}`);if(J.assert)Z.push(`ASSERT ${J.assert}`);if(J.default)Z.push(`DEFAULT ${J.default}`);let B=[];if(J.permissions.select)B.push(`FOR select ${J.permissions.select}`);if(J.permissions.create)B.push(`FOR create ${J.permissions.create}`);if(J.permissions.update)B.push(`FOR update ${J.permissions.update}`);if(J.permissions.delete)B.push(`FOR delete ${J.permissions.delete}`);if(B.length>0)Z.push(`PERMISSIONS ${B.join(", ")}`);return`${Z.join(" ")};`}function c0($,J,Q=!1){let Z=[`${Q?"DEFINE INDEX OVERWRITE":"DEFINE INDEX"} ${J.name} ON TABLE ${$}`];if(J.columns&&J.columns.length>0)Z.push(`FIELDS ${J.columns.join(", ")}`);if(J.unique)Z.push("UNIQUE");if(J.search)Z.push("SEARCH ANALYZER");return`${Z.join(" ")};`}u();var P1=new $4().name("push").description("Apply TypeScript schema to database").option("--url <url>","Database URL (e.g., http://localhost:8000)").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Auth level: root, namespace, or database").option("-s, --schema-dir <path>","Schema directory path").option("--embedded <mode>","Use embedded mode (memory or file path)").option("-y, --yes","Skip confirmation prompt").action(async($)=>{Y.header("UnrealORM Push","Apply code schema to database"),_0();let J=await o(),Q=await n({cliOutput:$.schemaDir,config:J});if(!Q4(Q))Y.error(`Schema directory not found: ${Q}`),Y.info("Run 'unreal pull' first to generate schema files."),Y.newline(),process.exit(1);let X=$.url||$.username||$.password||$.namespace||$.database||$.authLevel||$.embedded,Z=await s({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:J,skipAutoConfig:!$.yes&&!X});if(!Z)Y.error("Failed to establish database connection."),process.exit(1);let B=Y.spin("Loading code schema..."),_;try{_=await Q0(Q),B.succeed(`Loaded ${_.tables.length} table(s) from ${Q}`)}catch(K){B.fail("Failed to load code schema"),Y.error(K instanceof Error?K.message:String(K)),process.exit(1)}B=Y.spin("Introspecting database schema...");let G;try{G=await $0(Z),B.succeed(`Found ${G.tables.length} table(s) in database`)}catch(K){B.fail("Failed to introspect database"),Y.error(K instanceof Error?K.message:String(K)),await Z.close(),process.exit(1)}B.start("Comparing schemas...");let j=J4(_,G,!0);if(B.succeed("Comparison complete"),j.length===0)Y.success("Schemas are identical. Nothing to push."),await Z.close(),e(),process.exit(0);let U=j.filter((K)=>K.type.includes("added")).length,W=j.filter((K)=>K.type.includes("removed")).length,V=j.length-U-W;if(Y.divider(),Y.info("CHANGE SUMMARY (Code -> Database)"),Y.divider(),Y.newline(),Y.printer.log(` Total changes: ${Y.bold(String(j.length))}`),U>0)Y.printer.log(` ${Y.theme.success("+")} Additions: ${U}`);if(W>0)Y.printer.log(` ${Y.theme.error("-")} Removals: ${W}`);if(V>0)Y.printer.log(` ${Y.theme.warning("~")} Modifications: ${V}`);Y.newline();for(let K of j){let z=K.type.includes("added")?Y.theme.success("+"):K.type.includes("removed")?Y.theme.error("-"):Y.theme.warning("~");Y.printer.log(` ${z} ${K.description}`)}Y.newline();let q=[];if(!$.yes){let K=!1;Y.divider(),Y.info("CHANGE REVIEW"),Y.divider(),Y.newline();for(let z=0;z<j.length;z++){let M=j[z];if(!M)continue;if(K){q.push(M);continue}Y.printer.clear();let E=M.type.includes("added")?Y.theme.success("ADD"):M.type.includes("removed")?Y.theme.error("REMOVE"):Y.theme.warning("MODIFY");Y.printer.log(Y.bold(`[${z+1}/${j.length}] ${E}: ${M.description}`));let A=d0(M,_,G);if(A)Y.printer.log(Y.dim(`
206
+ `)}`,_=$.slice(0,B)+H+$.slice(U),z=new RegExp(`,\\s*${u0(Q)}(?=[\\s,\\]])`);return _=_.replace(z,""),_}function u0($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function R1($){return $.split("_").map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join("")}import f6 from"chalk";function I1($,J,Q){let X=[],Z=N0($),B=new Set,j=Q?g2($,Q):[];for(let G of j)B.add(G.table);for(let[G,U]of Z){let K=J.get(G),W=G.replace(".ts","").toLowerCase();if(!K)X.push({filename:G,type:"create",newContent:U});else if(K!==U)if(Q){if(B.has(W)){let V=$.tables.find((H)=>H.name===W),q=Q.tables.find((H)=>H.name===W);if(V&&q){let H=D1(K,V,q);X.push({filename:G,type:"update",oldContent:K,newContent:H.content,addedFields:H.addedFields,addedIndexes:H.addedIndexes,removedFields:H.removedFields,removedIndexes:H.removedIndexes})}else X.push({filename:G,type:"update",oldContent:K,newContent:U})}}else X.push({filename:G,type:"update",oldContent:K,newContent:U})}for(let G of J.keys())if(!Z.has(G))X.push({filename:G,type:"delete",oldContent:J.get(G),newContent:""});return X}import{extractTableFromModel as f2,extractIndexFromDefinition as h2,isModelClass as m2,isIndexDefinition as p2}from"unreal-orm";import{readdirSync as u2}from"node:fs";import{join as c2,resolve as d2}from"node:path";import{createJiti as l2}from"jiti";var r2=l2(import.meta.url,{interopDefault:!0});async function Z0($){let J=[];for(let Q of u2($).filter((X)=>X.endsWith(".ts"))){let X=d2(c2($,Q));try{let Z=await r2.import(X),B=new Map,j=[];for(let[,G]of Object.entries(Z))if(m2(G)){let U=f2(G);B.set(U.name,U)}else if(p2(G)){let{index:U,tableName:K}=h2(G);j.push({index:U,tableName:K})}for(let{index:G,tableName:U}of j){let K=B.get(U);if(K)K.indexes.push(G)}J.push(...B.values())}catch(Z){console.warn(`Failed to import ${Q}:`,Z)}}return{tables:J}}import g from"chalk";import{diffLines as P1}from"diff";var c0=3;function F1($,J,Q){let X=[];if(!J){X.push(g.bold.green(`
207
+ +++ ${$} (new file)`)),X.push(g.dim("─".repeat(60)));let j=Q.split(`
208
+ `).slice(0,20);for(let G of j)X.push(g.green(`+ ${G}`));if(Q.split(`
209
+ `).length>20)X.push(g.dim(`... ${Q.split(`
210
+ `).length-20} more lines`));return X.push(g.dim("─".repeat(60))),X.join(`
211
+ `)}X.push(g.bold(`
212
+ --- ${$}`)),X.push(g.bold(`+++ ${$}`)),X.push(g.dim("─".repeat(60)));let Z=P1(J,Q),B=o2(Z);if(B.length===0)X.push(g.dim(" (no changes)"));for(let j of B){X.push(g.cyan(`@@ -${j.oldStart},${j.oldLines} +${j.newStart},${j.newLines} @@`));for(let G of j.lines)if(G.type==="added")X.push(g.green(`+ ${G.content}`));else if(G.type==="removed")X.push(g.red(`- ${G.content}`));else X.push(g.dim(` ${G.content}`));X.push("")}return X.push(g.dim("─".repeat(60))),X.join(`
213
+ `)}function o2($){return s2($)}function s2($){let J=[],Q=null,X=[],Z=1,B=1;for(let j of $){if(!j)continue;let G=j.value.split(`
214
+ `);if(G[G.length-1]==="")G.pop();for(let U of G){let K=j.added?"added":j.removed?"removed":"context";if(X.push({type:K,content:U,oldLine:K!=="added"?Z:void 0,newLine:K!=="removed"?B:void 0}),K!=="added")Z++;if(K!=="removed")B++}}for(let j=0;j<X.length;j++){let G=X[j];if(!G)continue;if(G.type==="added"||G.type==="removed"){if(!Q){let U=Math.max(0,j-c0),K=X.slice(U,j),W=K[0],V=W?.oldLine??G.oldLine??1,q=W?.newLine??G.newLine??1;Q={oldStart:V,newStart:q,oldLines:0,newLines:0,lines:[]};for(let H of K)if(H)Q.lines.push({type:"context",content:H.content}),Q.oldLines++,Q.newLines++}if(Q.lines.push({type:G.type,content:G.content}),G.type!=="added")Q.oldLines++;if(G.type!=="removed")Q.newLines++}else if(Q){let U=-1;for(let W=j+1;W<X.length;W++){let V=X[W];if(V&&V.type!=="context"){U=W;break}}if(U!==-1){if(U-j<=c0*2){Q.lines.push({type:"context",content:G.content}),Q.oldLines++,Q.newLines++;continue}}if(Q.lines.slice().reverse().findIndex((W)=>W.type!=="context")<c0)Q.lines.push({type:"context",content:G.content}),Q.oldLines++,Q.newLines++;else J.push(Q),Q=null}}if(Q)J.push(Q);return J}function w1($,J){if(!$)return`New file (${J.split(`
215
+ `).length} lines)`;let Q=P1($,J),X=0,Z=0;for(let j of Q){let G=j.value.split(`
216
+ `).length-1;if(j.added)X+=G;else if(j.removed)Z+=G}if(X===0&&Z===0)return"No changes";let B=[];if(X>0)B.push(g.green(`+${X}`));if(Z>0)B.push(g.red(`-${Z}`));return B.join(" ")}c();var N1=new a2().name("pull").description("Introspect database and generate TypeScript schema").option("--url <url>","Database URL (e.g., http://localhost:8000)").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Auth level: root, namespace, or database").option("-s, --schema-dir <path>","Schema directory path").option("--embedded <mode>","Use embedded mode (memory or file path)").option("--log-level <level>","Log output level: silent, normal, debug","normal").option("-y, --yes","Skip confirmation prompt").action(async($)=>{Y.header("UnrealORM Pull","Introspect database and generate schema"),K0(),L("Loading config");let J=await a(),Q=await $0({cliOutput:$.schemaDir,config:J}),X=$.url||$.username||$.password||$.namespace||$.database||$.authLevel||$.embedded;L("Resolving database connection");let Z=await i({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:J,skipAutoConfig:!$.yes&&!X});if(!Z)Y.error("Failed to establish database connection."),process.exit(1);L("Introspecting database schema");let B=Y.spin("Introspecting database schema..."),j;try{j=await X0(Z),B.succeed(`Found ${j.tables.length} table(s)`)}catch(_){B.fail("Failed to introspect database"),Y.error(_ instanceof Error?_.message:String(_)),await Z.close(),process.exit(1)}L("Planning file changes"),B.start("Planning file changes...");let G=new Map;if(d0(Q))try{let _=e2(Q).filter((z)=>z.endsWith(".ts"));for(let z of _){let M=t2(L1(Q,z),"utf-8");G.set(z,M)}}catch(_){}let U;if(d0(Q))try{U=await Z0(Q)}catch{}let K;try{K=I1(j,G,U),B.succeed("File changes planned")}catch(_){B.fail("Failed to plan file changes"),Y.error(_ instanceof Error?_.message:String(_)),await Z.close(),process.exit(1)}if(K.length===0)Y.success("All files are up to date!"),await Z.close(),J0(),process.exit(0);let W=K.filter((_)=>_.type==="create").length,V=K.filter((_)=>_.type==="delete").length,q=K.filter((_)=>_.type==="update").length;if(Y.divider(),Y.info("FILE CHANGE SUMMARY (Database -> Code)"),Y.divider(),Y.newline(),Y.printer.log(` Total files: ${Y.bold(String(K.length))}`),W>0)Y.printer.log(` ${Y.theme.success("+")} New files: ${W}`);if(V>0)Y.printer.log(` ${Y.theme.error("-")} Deleted files: ${V}`);if(q>0)Y.printer.log(` ${Y.theme.warning("~")} Updated files: ${q}`);Y.newline();for(let _ of K){let z=_.type==="create"?Y.theme.success("+"):_.type==="delete"?Y.theme.error("-"):Y.theme.warning("~");Y.printer.log(` ${z} ${_.filename}`)}Y.newline();let H=[];if(!$.yes){let _=!1;Y.divider(),Y.info("FILE REVIEW"),Y.divider(),Y.newline();for(let z of K){if(!z)continue;if(_){H.push(z);continue}Y.printer.clear();let M=z.type==="create"?Y.theme.success("CREATE"):z.type==="delete"?Y.theme.error("DELETE"):Y.theme.warning("UPDATE");Y.printer.log(Y.bold(`[${K.indexOf(z)+1}/${K.length}] ${M}: ${z.filename}`)),Y.printer.log(Y.dim(` ${w1(z.oldContent,z.newContent)}`)),Y.printer.log(F1(z.filename,z.oldContent,z.newContent));let E=await q0(z.filename,K.indexOf(z)+1,K.length);if(E==="cancel")Y.newline(),Y.warn("Operation cancelled."),await Z.close(),process.exit(0);if(E==="all"){_=!0,H.push(z);for(let A of K.slice(K.indexOf(z)+1))if(A)H.push(A);break}if(E==="yes")H.push(z)}if(Y.printer.clear(),H.length===0)Y.warn("No files selected. Operation cancelled."),await Z.close(),process.exit(0);Y.divider(),Y.success("APPLYING SELECTED CHANGES"),Y.divider(),Y.info(`Will apply ${H.length} of ${K.length} file changes`),Y.newline()}else Y.divider(),Y.success("APPLYING ALL CHANGES (--yes flag)"),Y.divider(),Y.info(`Applying all ${K.length} file changes`),Y.newline(),H.push(...K);L(`Applying ${H.length} file change(s)`),B.start("Applying file changes...");try{if(!d0(Q))i2(Q,{recursive:!0});for(let _ of H){let z=L1(Q,_.filename);if(_.type==="delete")$4(z);else n2(z,_.newContent,"utf-8")}B.succeed(`Applied ${H.length} file change(s) to ${Q}`)}catch(_){B.fail("Failed to apply file changes"),Y.error(_ instanceof Error?_.message:String(_)),await Z.close(),process.exit(1)}await Z.close(),J0(),Y.header("Schema pull complete!"),Y.dim("Changes applied:");for(let _ of H){let z=_.type==="create"?"+":_.type==="delete"?"-":"~";console.log(Y.dim(` ${z} ${_.filename}`))}Y.newline()});import{Command as X4}from"@commander-js/extra-typings";import{existsSync as Z4}from"node:fs";U0();import{compareSchemas as B4}from"unreal-orm";function o0($,J,Q){return Q4($,J,Q)}function Q4($,J,Q){let X=J.tables.find((B)=>B.name===$.table),Z=Q.tables.find((B)=>B.name===$.table);switch($.type){case"table_added":{if(!X)return null;return J4(X)}case"table_removed":return`REMOVE TABLE ${$.table};`;case"table_type_changed":{if(!X)return null;return v1(X,!0)}case"field_added":{if(!X||!$.field)return null;let B=X.fields.find((j)=>j.name===$.field);if(!B)return null;return l0($.table,B)}case"field_removed":return`REMOVE FIELD ${$.field} ON TABLE ${$.table};`;case"field_type_changed":case"field_default_changed":case"field_assertion_changed":{if(!X||!$.field)return null;let B=X.fields.find((j)=>j.name===$.field);if(!B)return null;return l0($.table,B,!0)}case"index_added":{if(!X||!$.index)return null;let B=X.indexes.find((j)=>j.name===$.index);if(!B)return null;return r0($.table,B)}case"index_removed":return`REMOVE INDEX ${$.index} ON TABLE ${$.table};`;case"index_modified":{if(!X||!$.index)return null;let B=X.indexes.find((j)=>j.name===$.index);if(!B)return null;return r0($.table,B,!0)}default:return null}}function J4($){let J=[];J.push(v1($));for(let Q of $.fields){if(Q.name.includes("[*]"))continue;let X=$.type==="RELATION"&&(Q.name==="in"||Q.name==="out");J.push(l0($.name,Q,X))}for(let Q of $.indexes)J.push(r0($.name,Q));return J.join(`
217
+ `)}function v1($,J=!1){let X=[`${J?"DEFINE TABLE OVERWRITE":"DEFINE TABLE"} ${$.name}`];if($.type==="RELATION")X.push("TYPE RELATION");else if($.type==="VIEW"){if(X.push("TYPE ANY"),$.viewQuery)X.push(`AS ${$.viewQuery}`)}if($.schemafull)X.push("SCHEMAFULL");let Z=[];if($.permissions.select)Z.push(`FOR select ${$.permissions.select}`);if($.permissions.create)Z.push(`FOR create ${$.permissions.create}`);if($.permissions.update)Z.push(`FOR update ${$.permissions.update}`);if($.permissions.delete)Z.push(`FOR delete ${$.permissions.delete}`);if(Z.length>0)X.push(`PERMISSIONS ${Z.join(", ")}`);return`${X.join(" ")};`}function l0($,J,Q=!1){let Z=[`${Q?"DEFINE FIELD OVERWRITE":"DEFINE FIELD"} ${J.name} ON TABLE ${$}`];if(J.flex)Z.push("FLEXIBLE");if(J.type)Z.push(`TYPE ${J.type}`);if(J.value)Z.push(`VALUE ${J.value}`);if(J.assert)Z.push(`ASSERT ${J.assert}`);if(J.default)Z.push(`DEFAULT ${J.default}`);let B=[];if(J.permissions.select)B.push(`FOR select ${J.permissions.select}`);if(J.permissions.create)B.push(`FOR create ${J.permissions.create}`);if(J.permissions.update)B.push(`FOR update ${J.permissions.update}`);if(J.permissions.delete)B.push(`FOR delete ${J.permissions.delete}`);if(B.length>0)Z.push(`PERMISSIONS ${B.join(", ")}`);return`${Z.join(" ")};`}function r0($,J,Q=!1){let Z=[`${Q?"DEFINE INDEX OVERWRITE":"DEFINE INDEX"} ${J.name} ON TABLE ${$}`];if(J.columns&&J.columns.length>0)Z.push(`FIELDS ${J.columns.join(", ")}`);if(J.unique)Z.push("UNIQUE");if(J.search)Z.push("SEARCH ANALYZER");return`${Z.join(" ")};`}c();var S1=new X4().name("push").description("Apply TypeScript schema to database").option("--url <url>","Database URL (e.g., http://localhost:8000)").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Auth level: root, namespace, or database").option("-s, --schema-dir <path>","Schema directory path").option("--embedded <mode>","Use embedded mode (memory or file path)").option("--log-level <level>","Log output level: silent, normal, debug","normal").option("-y, --yes","Skip confirmation prompt").action(async($)=>{Y.header("UnrealORM Push","Apply code schema to database"),K0(),L("Loading config");let J=await a(),Q=await $0({cliOutput:$.schemaDir,config:J});if(L(`Schema dir resolved: ${Q}`),!Z4(Q))Y.error(`Schema directory not found: ${Q}`),Y.info("Run 'unreal pull' first to generate schema files."),Y.newline(),process.exit(1);let X=$.url||$.username||$.password||$.namespace||$.database||$.authLevel||$.embedded;L("Resolving database connection");let Z=await i({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:J,skipAutoConfig:!$.yes&&!X});if(!Z)Y.error("Failed to establish database connection."),process.exit(1);L("Loading code schema");let B=Y.spin("Loading code schema..."),j;try{j=await Z0(Q),B.succeed(`Loaded ${j.tables.length} table(s) from ${Q}`)}catch(_){B.fail("Failed to load code schema"),Y.error(_ instanceof Error?_.message:String(_)),process.exit(1)}L("Introspecting database schema"),B=Y.spin("Introspecting database schema...");let G;try{G=await X0(Z),B.succeed(`Found ${G.tables.length} table(s) in database`)}catch(_){B.fail("Failed to introspect database"),Y.error(_ instanceof Error?_.message:String(_)),await Z.close(),process.exit(1)}L("Comparing schemas"),B.start("Comparing schemas...");let U=B4(j,G,!0);if(B.succeed("Comparison complete"),U.length===0)Y.success("Schemas are identical. Nothing to push."),await Z.close(),J0(),process.exit(0);let K=U.filter((_)=>_.type.includes("added")).length,W=U.filter((_)=>_.type.includes("removed")).length,V=U.length-K-W;if(Y.divider(),Y.info("CHANGE SUMMARY (Code -> Database)"),Y.divider(),Y.newline(),Y.printer.log(` Total changes: ${Y.bold(String(U.length))}`),K>0)Y.printer.log(` ${Y.theme.success("+")} Additions: ${K}`);if(W>0)Y.printer.log(` ${Y.theme.error("-")} Removals: ${W}`);if(V>0)Y.printer.log(` ${Y.theme.warning("~")} Modifications: ${V}`);Y.newline();for(let _ of U){let z=_.type.includes("added")?Y.theme.success("+"):_.type.includes("removed")?Y.theme.error("-"):Y.theme.warning("~");Y.printer.log(` ${z} ${_.description}`)}Y.newline();let q=[];if(!$.yes){let _=!1;Y.divider(),Y.info("CHANGE REVIEW"),Y.divider(),Y.newline();for(let z=0;z<U.length;z++){let M=U[z];if(!M)continue;if(_){q.push(M);continue}Y.printer.clear();let E=M.type.includes("added")?Y.theme.success("ADD"):M.type.includes("removed")?Y.theme.error("REMOVE"):Y.theme.warning("MODIFY");Y.printer.log(Y.bold(`[${z+1}/${U.length}] ${E}: ${M.description}`));let A=o0(M,j,G);if(A)Y.printer.log(Y.dim(`
218
218
  \uD83D\uDCDD SurrealQL Statement:`)),Y.printer.log(Y.theme.secondary(` ${A}
219
219
  `));else Y.printer.log(Y.dim(`
220
220
  ⚠️ No SurrealQL generated for this change
221
- `));let R=await U0("this change",z+1,j.length);if(R==="cancel")Y.newline(),Y.warn("Operation cancelled."),await Z.close(),process.exit(0);if(R==="all"){K=!0,q.push(M);for(let I=z+1;I<j.length;I++){let O=j[I];if(O)q.push(O)}break}if(R==="yes")q.push(M)}if(Y.printer.clear(),q.length===0)Y.warn("No changes selected. Operation cancelled."),await Z.close(),process.exit(0);Y.divider(),Y.success("APPLYING SELECTED CHANGES"),Y.divider(),Y.info(`Will apply ${q.length} of ${j.length} change(s)`),Y.newline()}else Y.divider(),Y.success("APPLYING ALL CHANGES (--yes flag)"),Y.divider(),Y.info(`Applying all ${j.length} change(s)`),Y.newline(),q.push(...j);let H=[];for(let K of q){let z=d0(K,_,G);if(z)H.push(z)}B.start("Applying schema changes...");try{let K=H.flatMap((z)=>z.split(`
222
- `).filter((M)=>M.trim())).join("");await Z.query(`BEGIN;${K}COMMIT;`),B.succeed("Schema changes applied successfully")}catch(K){B.fail("Failed to apply schema changes"),Y.error(K instanceof Error?K.message:String(K)),await Z.close(),process.exit(1)}await Z.close(),e(),Y.header("Schema push complete!"),Y.dim(`Applied ${q.length} of ${j.length} change(s) to database`),Y.newline()});import{Command as Z4}from"@commander-js/extra-typings";import{existsSync as l0,readFileSync as B4,readdirSync as Y4}from"node:fs";import{join as G4}from"node:path";import p from"chalk";function w1($,J=!1){if($.length===0)return p.green("✓ Schemas are identical");let Q=[],X=new Map;for(let Z of $){let B=X.get(Z.table)||[];B.push(Z),X.set(Z.table,B)}for(let[Z,B]of X){Q.push(p.bold(`
223
- ${Z}:`));for(let _ of B){let G=X4(_.type),j=_.description;if(_.type.includes("added"))j=p.green(_.description);else if(_.type.includes("removed"))j=p.red(_.description);else j=p.yellow(_.description);if(Q.push(` ${G} ${j}`),J&&(_.oldValue!==void 0||_.newValue!==void 0)){if(_.oldValue!==void 0)Q.push(p.dim(" Old: ")+p.red(F1(_.oldValue)));if(_.newValue!==void 0)Q.push(p.dim(" New: ")+p.green(F1(_.newValue)))}}}return Q.join(`
224
- `)}function X4($){if($.includes("added"))return p.green("+");if($.includes("removed"))return p.red("-");return p.yellow("~")}function F1($){if(Array.isArray($))return`[${$.join(", ")}]`;if(typeof $==="object"&&$!==null){if("query"in $&&typeof $.query==="string")return $.query;let J=JSON.stringify($);if(J.length<50)return J;return JSON.stringify($,null,2)}return String($)}u();import{compareSchemas as _4}from"unreal-orm";function j4($,J){let Q={added:[],removed:[],modified:[],unchanged:[]};for(let[X,Z]of $){let B=G4(J,X);if(!l0(B))Q.added.push(X);else{let _=B4(B,"utf-8");if(_.trim()!==Z.trim())Q.modified.push({filename:X,databaseContent:Z,codeContent:_});else Q.unchanged.push(X)}}if(l0(J)){let X=Y4(J).filter((Z)=>Z.endsWith(".ts"));for(let Z of X)if(!$.has(Z))Q.removed.push(Z)}return Q}function U4($){let J=$.databaseContent.split(`
221
+ `));let R=await q0("this change",z+1,U.length);if(R==="cancel")Y.newline(),Y.warn("Operation cancelled."),await Z.close(),process.exit(0);if(R==="all"){_=!0,q.push(M);for(let I=z+1;I<U.length;I++){let O=U[I];if(O)q.push(O)}break}if(R==="yes")q.push(M)}if(Y.printer.clear(),q.length===0)Y.warn("No changes selected. Operation cancelled."),await Z.close(),process.exit(0);Y.divider(),Y.success("APPLYING SELECTED CHANGES"),Y.divider(),Y.info(`Will apply ${q.length} of ${U.length} change(s)`),Y.newline()}else Y.divider(),Y.success("APPLYING ALL CHANGES (--yes flag)"),Y.divider(),Y.info(`Applying all ${U.length} change(s)`),Y.newline(),q.push(...U);let H=[];for(let _ of q){let z=o0(_,j,G);if(z)H.push(z)}L(`Applying ${H.length} SQL statement(s)`),B.start("Applying schema changes...");try{let _=H.flatMap((z)=>z.split(`
222
+ `).filter((M)=>M.trim())).join("");await Z.query(`BEGIN;${_}COMMIT;`),B.succeed("Schema changes applied successfully")}catch(_){B.fail("Failed to apply schema changes"),Y.error(_ instanceof Error?_.message:String(_)),await Z.close(),process.exit(1)}await Z.close(),J0(),Y.header("Schema push complete!"),Y.dim(`Applied ${q.length} of ${U.length} change(s) to database`),Y.newline()});import{Command as G4}from"@commander-js/extra-typings";import{existsSync as s0,readFileSync as j4,readdirSync as U4}from"node:fs";import{join as K4}from"node:path";import d from"chalk";function T1($,J=!1){if($.length===0)return d.green("✓ Schemas are identical");let Q=[],X=new Map;for(let Z of $){let B=X.get(Z.table)||[];B.push(Z),X.set(Z.table,B)}for(let[Z,B]of X){Q.push(d.bold(`
223
+ ${Z}:`));for(let j of B){let G=Y4(j.type),U=j.description;if(j.type.includes("added"))U=d.green(j.description);else if(j.type.includes("removed"))U=d.red(j.description);else U=d.yellow(j.description);if(Q.push(` ${G} ${U}`),J&&(j.oldValue!==void 0||j.newValue!==void 0)){if(j.oldValue!==void 0)Q.push(d.dim(" Old: ")+d.red(k1(j.oldValue)));if(j.newValue!==void 0)Q.push(d.dim(" New: ")+d.green(k1(j.newValue)))}}}return Q.join(`
224
+ `)}function Y4($){if($.includes("added"))return d.green("+");if($.includes("removed"))return d.red("-");return d.yellow("~")}function k1($){if(Array.isArray($))return`[${$.join(", ")}]`;if(typeof $==="object"&&$!==null){if("query"in $&&typeof $.query==="string")return $.query;let J=JSON.stringify($);if(J.length<50)return J;return JSON.stringify($,null,2)}return String($)}c();import{compareSchemas as _4}from"unreal-orm";function z4($,J){let Q={added:[],removed:[],modified:[],unchanged:[]};for(let[X,Z]of $){let B=K4(J,X);if(!s0(B))Q.added.push(X);else{let j=j4(B,"utf-8");if(j.trim()!==Z.trim())Q.modified.push({filename:X,databaseContent:Z,codeContent:j});else Q.unchanged.push(X)}}if(s0(J)){let X=U4(J).filter((Z)=>Z.endsWith(".ts"));for(let Z of X)if(!$.has(Z))Q.removed.push(Z)}return Q}function q4($){let J=$.databaseContent.split(`
225
225
  `).length,Q=$.codeContent.split(`
226
- `).length,X=J-Q;if(X>0)return`+${X} lines`;if(X<0)return`${X} lines`;return"content changed"}function K4($){let J={total:$.length,tables:0,fields:0,indexes:0};for(let Q of $)if(Q.type.startsWith("table_"))J.tables++;else if(Q.type.startsWith("field_"))J.fields++;else if(Q.type.startsWith("index_"))J.indexes++;return J}function z4($){let{added:J,removed:Q,modified:X,unchanged:Z}=$;if(Y.header("Schema Diff Summary"),J.length>0){console.log(Y.theme.success(`+ Added (${J.length}):`));for(let _ of J)console.log(` + ${_}`);Y.newline()}if(Q.length>0){console.log(Y.theme.error(`- Removed (${Q.length}):`));for(let _ of Q)console.log(` - ${_}`);Y.newline()}if(X.length>0){console.log(Y.theme.warning(`~ Modified (${X.length}):`));for(let _ of X)console.log(` ~ ${_.filename}`),console.log(Y.dim(` Database: from database (${U4(_)})`)),console.log(Y.dim(" Code: current file"));Y.newline()}if(Z.length>0){console.log(Y.theme.dim(`= Unchanged (${Z.length}):`));let _=Z.join(", ");console.log(Y.dim(` ${_}`)),Y.newline()}if(J.length>0||Q.length>0||X.length>0)console.log(Y.bold(`${J.length+Q.length+X.length} file(s) changed, ${Z.length} unchanged`)),Y.newline(),Y.info('Run "unreal pull" to sync your code schema with the database.');else Y.success("Code schema is in sync with database")}var L1=new Z4().name("diff").description("Compare TypeScript schema with database schema").option("--url <url>","Database URL (e.g., http://localhost:8000)").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Auth level: root, namespace, or database").option("-s, --schema-dir <path>","Schema directory path").option("-e, --embedded <mode>","Use embedded mode (memory or file path)").option("--detailed","Show detailed field-level changes").action(async($)=>{try{Y.header("UnrealORM Diff","Compare code vs database schema");let J=await o(),Q=await n({cliOutput:$.schemaDir,config:J}),X=await s({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:J,skipAutoConfig:!0});if(!X)Y.error("Failed to establish database connection."),process.exit(1);let Z=Y.spin("Introspecting database schema"),B=await $0(X);Z.succeed("Introspected database schema");let _=null;if(l0(Q)){let G=Y.spin("Parsing code schema");try{_=await Q0(Q),G.succeed("Parsed code schema")}catch(j){G.fail("Could not parse code schema"),Y.warn(`${j instanceof Error?j.message:String(j)}`),Y.dim("Falling back to file-based comparison"),Y.newline()}}if(_){let G=_4(B,_);if(G.length===0){Y.success("No schema differences detected. Code and database schemas are in sync."),await X.close();return}let j=K4(G),U=w1(G,$.detailed);Y.divider(),Y.info("Schema Changes"),Y.divider(),Y.newline(),console.log(U);let W=[];if(j.fields>0)W.push(Y.theme.warning(`${j.fields} field(s)`));if(j.indexes>0)W.push(Y.theme.info(`${j.indexes} index(es)`));if(j.tables>0)W.push(Y.theme.primary(`${j.tables} table(s)`));if(Y.newline(),console.log(Y.bold(`${j.total} change(s): ${W.join(", ")}`)),!$.detailed&&j.total>0)Y.newline(),Y.dim("Tip: Use --detailed flag to see old/new values for changes");Y.newline(),console.log(Y.theme.secondary("Run"),Y.bold("unreal pull"),Y.theme.secondary("or"),Y.bold("unreal push"),Y.theme.secondary("to sync your code schema with the database.")),Y.newline()}else{let G=P0(B),j=j4(G,Q);z4(j)}await X.close()}catch(J){Y.error("Error:",J),process.exit(1)}});import{Command as E4}from"@commander-js/extra-typings";import{promises as M4,existsSync as D4}from"node:fs";import r0 from"node:path";import{promises as q4}from"node:fs";import{parseTableDefinition as H4,parseFieldDefinition as W4,parseIndexDefinition as A4}from"unreal-orm";var N1={};function v1($){return{name:$,type:"NORMAL",schemafull:!0,drop:!1,permissions:N1,fields:[],indexes:[],events:[]}}async function S1($){let J=await q4.readFile($,"utf-8");return O4(J)}function V4($){let J=$.replace(/--.*$/gm,"");return J=J.replace(/\/\*[\s\S]*?\*\//g,""),J}function O4($){let J=new Map,X=V4($).split(";").map((Z)=>Z.trim()).filter((Z)=>Z.length>0);for(let Z of X){let _=Z.replace(/\s+/g," ").trim().toUpperCase();try{if(_.startsWith("DEFINE TABLE")){let G=H4(Z);if(G.name)J.set(G.name,{name:G.name,type:G.type??"NORMAL",schemafull:G.schemafull??!0,drop:G.drop??!1,permissions:G.permissions??N1,viewQuery:G.viewQuery,fields:[],indexes:[],events:[]});else C("DEFINE TABLE","Could not extract table name",`Statement: ${Z.slice(0,80)}...`)}else if(_.startsWith("DEFINE FIELD")){let G=W4(Z),j=Z.match(/\bON\s+(?:TABLE\s+)?(\w+)/i);if(j?.[1]){let U=j[1],W=J.get(U);if(!W)W=v1(U),J.set(U,W);W.fields.push(G)}else C("DEFINE FIELD","Could not extract table name from field definition",`Statement: ${Z.slice(0,80)}...`)}else if(_.startsWith("DEFINE INDEX")){let G=A4(Z),j=Z.match(/\bON\s+(?:TABLE\s+)?(\w+)/i);if(j?.[1]){let U=j[1],W=J.get(U);if(!W)W=v1(U),J.set(U,W);W.indexes.push(G)}else C("DEFINE INDEX","Could not extract table name from index definition",`Statement: ${Z.slice(0,80)}...`)}else if(_.startsWith("DEFINE EVENT"))C("DEFINE EVENT","Events are not yet supported","Event definitions will be skipped");else if(_.startsWith("DEFINE ANALYZER"));else if(_.startsWith("DEFINE FUNCTION"))C("DEFINE FUNCTION","Custom functions are not yet supported","Function definitions will be skipped");else if(_.startsWith("DEFINE PARAM"))C("DEFINE PARAM","Database parameters are not yet supported","Parameter definitions will be skipped");else if(_.startsWith("DEFINE USER"));else if(_.startsWith("DEFINE ACCESS"));else if(_.startsWith("OPTION"));}catch(G){let j=G instanceof Error?G.message:String(G);C("Parse error",j,`Statement: ${Z.slice(0,80)}${Z.length>80?"...":""}`)}}return{tables:Array.from(J.values())}}G0();u();var T1=new E4("mermaid").description("Generate a Mermaid ERD diagram from TypeScript schema, database, or .surql file").option("-o, --output <path>","Output file path for .mermaid file").option("-s, --schema-dir <path>","Schema directory path (for --code mode)").option("-c, --config <path>","Path to config file").option("--stdout","Print to stdout instead of file").option("--code","Use TypeScript schema definitions").option("--db","Use database connection (introspect live database)").option("--surql <path>","Use a .surql schema file").option("--url <url>","Database URL (implies --db)").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Auth level: root, namespace, or database").option("--embedded <mode>","Use embedded mode (memory or file path)").action(async($)=>{Y.header("Mermaid ERD Generator","Visualize your schema"),_0();let J=Y.spin("Loading configuration...");try{let Q=await o($.config);if(Q)J.succeed("Configuration loaded");else J.info("No configuration file found (using defaults/flags)");let X=$.output;if(!X&&!$.stdout)J.stop(),X=await M0("Output file path:",Q?r0.join(Q.path,"schema.mermaid"):"./unreal/schema.mermaid");let Z=$.url||$.username||$.password||$.namespace||$.database||$.embedded,B;if($.surql)B="surql";else if($.db||Z)B="database";else if($.code)B="code";if(!B){if(J.stop(),B=await k0("Schema source:",[{title:"TypeScript schema (./unreal/tables/)",value:"code"},{title:"Database (introspect live database)",value:"database"},{title:"SurrealQL file (.surql)",value:"surql"}]),!B)process.exit(0)}let _;if(B==="code"){J.stop();let j=await n({cliOutput:$.schemaDir,config:Q});J.start(`Extracting schema from ${j}...`),_=await Q0(j),J.succeed(`Found ${_.tables.length} tables from TypeScript schema`)}else if(B==="database"){J.stop();let j=await s({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:Q,skipAutoConfig:!0});if(!j)Y.error("Failed to establish database connection."),process.exit(1);J.start("Introspecting database schema...");try{_=await $0(j),J.succeed(`Found ${_.tables.length} tables from database`)}finally{await j.close()}}else{let j=typeof $.surql==="string"?$.surql:"";if(!j)J.stop(),j=await M0("Path to .surql file:","./schema.surql");let U=r0.resolve(process.cwd(),j);if(!D4(U))J.fail(`File not found: ${U}`),process.exit(1);J.start(`Parsing ${j}...`),_=await S1(U),J.succeed(`Found ${_.tables.length} tables from .surql file`)}J.start("Generating Mermaid diagram...");let G=R4(_);if(J.succeed("Diagram generated"),$.stdout)console.log(`
227
- ${G}`);else{let j=r0.resolve(process.cwd(),X||"./unreal/schema.mermaid");await M4.writeFile(j,G),Y.success(`Saved to ${j}`),Y.dim(`Tip: Preview with VS Code Mermaid extension,
228
- https://mermiko.com, or https://mermaid.live`)}e()}catch(Q){J.fail("Failed to generate diagram"),Y.error(Q instanceof Error?Q.message:String(Q)),process.exit(1)}});function R4($){let J=["erDiagram"],Q=$.tables.filter((G)=>G.type==="NORMAL"),X=$.tables.filter((G)=>G.type==="RELATION"),Z=$.tables.filter((G)=>G.type==="VIEW"),B=[],_=new Map;for(let G of $.tables){let j=new Set;for(let U of G.indexes){let W=U.columns[0];if(U.unique&&U.columns.length===1&&W)j.add(W)}if(j.size>0&&G.name)_.set(G.name,j)}if(Q.length>0){J.push(" %% === TABLES ===");for(let G of Q){let j=k1(G,_);J.push(...j.lines),B.push(...j.relationships)}}if(X.length>0){J.push(" %% === RELATIONS (Graph Edges) ===");for(let G of X){let j=I4(G,_);J.push(...j.lines),B.push(...j.relationships)}}if(Z.length>0){J.push(" %% === VIEWS ===");for(let G of Z){let j=k1(G,_);J.push(...j.lines)}}if(B.length>0)J.push(""),J.push(" %% === RELATIONSHIPS ==="),J.push(...B);return J.join(`
229
- `)}function k1($,J){let Q=[],X=[],Z=$.fields.filter((G)=>!G.name.includes(".")&&!G.name.includes("[")),B=c($.name),_=J.get($.name)??new Set;Q.push(` ${B} {`);for(let G of Z){let j=H0(G.type),U=c(G.name),W=C1(G,_),q=G.name==="id"||G.assert?.includes("!= NONE")?`*${U}`:U,H=` ${j} ${q}`;if(W)H+=` ${W}`;Q.push(H);let K=G.type.match(/^record<(\w+)>$/);if(K?.[1]){let z=c(K[1]),M=G.assert?.includes("!= NONE"),E=_.has(G.name),A=M?"--":"..",O=`${E?"|":"}"}${M?"|":"o"}`,w="||";X.push(` ${B} ${O}${A}|| ${z} : "${G.name}"`)}}return Q.push(" }"),Q.push(""),{lines:Q,relationships:X}}function I4($,J){let Q=[],X=[],Z=c($.name),B=J.get($.name)??new Set,_=$.fields.find((V)=>V.name==="in"),G=$.fields.find((V)=>V.name==="out"),j=_?.type.match(/^record<(\w+)>$/)?.[1],U=G?.type.match(/^record<(\w+)>$/)?.[1],W=$.fields.filter((V)=>V.name!=="in"&&V.name!=="out"&&!V.name.includes(".")&&!V.name.includes("["));if(W.length===0){if(j&&U){let V=c(j),q=c(U);X.push(` ${V} }|--|{ ${q} : "${$.name}"`)}return{lines:[],relationships:X}}if(Q.push(` ${Z} {`),_&&j)Q.push(` ${c(j)} *in FK`);if(G&&U)Q.push(` ${c(U)} *out FK`);for(let V of W){let q=H0(V.type),H=c(V.name),K=C1(V,B),M=V.name==="id"||V.assert?.includes("!= NONE")?`*${H}`:H,E=` ${q} ${M}`;if(K)E+=` ${K}`;Q.push(E)}if(Q.push(" }"),Q.push(""),j&&U){let V=c(j),q=c(U);X.push(` ${V} ||--o{ ${Z} : "in"`),X.push(` ${Z} }o--|| ${q} : "out"`)}return{lines:Q,relationships:X}}function c($){return $.replace(/[^a-zA-Z0-9_]/g,"_")}function H0($){if($.startsWith("record<"))return"record";if($==="record")return"record";if($.startsWith("array<")){let Q=$.slice(6,-1);return`array_${H0(Q)}`}if($==="array")return"array";if($.startsWith("option<")){let Q=$.slice(7,-1);return H0(Q)}if($.startsWith("set<")){let Q=$.slice(4,-1);return`set_${H0(Q)}`}if($.startsWith("geometry<"))return`geo_${$.slice(9,-1)}`;if($.startsWith("range<"))return"range";if($.includes("|"))return"enum";return{string:"string",int:"int",float:"float",bool:"bool",datetime:"datetime",duration:"duration",decimal:"decimal",number:"number",object:"object",array:"array",any:"any",bytes:"bytes",uuid:"uuid",ulid:"ulid",geometry:"geometry",point:"point",line:"line",polygon:"polygon",multipoint:"multipoint",multiline:"multiline",multipolygon:"multipolygon",collection:"collection",null:"null",none:"none"}[$]||$}function C1($,J){let Q=[];if($.name==="id")Q.push("PK");if($.type.startsWith("record<"))Q.push("FK");if(J.has($.name))Q.push("UK");return Q.join(",")}u();import{Command as P4}from"@commander-js/extra-typings";var x1="https://github.com/Jimpex/unreal-orm",y1=new P4("github").description("Open the UnrealORM GitHub repository").action(async()=>{let{exec:$}=await import("node:child_process"),{platform:J}=await import("node:os"),Q=J()==="win32"?"start":J()==="darwin"?"open":"xdg-open";$(`${Q} ${x1}`,(X)=>{if(X)Y.info(`Visit: ${x1}`)})});u();import{Command as F4}from"@commander-js/extra-typings";var b1="https://unreal-orm.jimpex.dev",g1=new F4("docs").description("Open the UnrealORM documentation").action(async()=>{let{exec:$}=await import("node:child_process"),{platform:J}=await import("node:os"),Q=J()==="win32"?"start":J()==="darwin"?"open":"xdg-open";$(`${Q} ${b1}`,(X)=>{if(X)Y.info(`Visit: ${b1}`)})});import{Command as T4}from"@commander-js/extra-typings";u();var f1="\x1B[?25l",o0="\x1B[?25h";function h1(){process.stdout.write("\x1B[?1049h\x1B[?7l\x1B[H\x1B[J")}function s0(){process.stdout.write("\x1B[?7h\x1B[?1049l")}function d(){let $=process.stdout.rows||24;process.stdout.write(`\x1B[1;${$}r\x1B[H\x1B[J`)}function X0(){let $=process.stdout.rows||24;process.stdout.write(`\x1B[1;${$}r\x1B[H\x1B[J`)}async function l(){return new Promise(($)=>{let J=process.stdin,Q=J.isRaw;J.setRawMode(!0),J.resume(),J.setEncoding("utf8");let X=(Z)=>{if(J.setRawMode(Q),J.pause(),J.removeListener("data",X),Z==="\x03")process.stdout.write("\x1B[?25h"),process.exit(0);$(Z)};J.once("data",X)})}var i0="\x1BCANCEL";async function F0($,J=""){process.stdout.write("\x1B[?25h"),process.stdout.write($);let Q=J;if(J)process.stdout.write(J);return new Promise((X)=>{let Z=process.stdin;Z.setRawMode(!0),Z.resume(),Z.setEncoding("utf8");let B=(_)=>{if(_==="\x03")process.stdout.write("\x1B[?25h"),process.exit(0);if(_==="\r"||_===`
226
+ `).length,X=J-Q;if(X>0)return`+${X} lines`;if(X<0)return`${X} lines`;return"content changed"}function H4($){let J={total:$.length,tables:0,fields:0,indexes:0};for(let Q of $)if(Q.type.startsWith("table_"))J.tables++;else if(Q.type.startsWith("field_"))J.fields++;else if(Q.type.startsWith("index_"))J.indexes++;return J}function W4($){let{added:J,removed:Q,modified:X,unchanged:Z}=$;if(Y.header("Schema Diff Summary"),J.length>0){console.log(Y.theme.success(`+ Added (${J.length}):`));for(let j of J)console.log(` + ${j}`);Y.newline()}if(Q.length>0){console.log(Y.theme.error(`- Removed (${Q.length}):`));for(let j of Q)console.log(` - ${j}`);Y.newline()}if(X.length>0){console.log(Y.theme.warning(`~ Modified (${X.length}):`));for(let j of X)console.log(` ~ ${j.filename}`),console.log(Y.dim(` Database: from database (${q4(j)})`)),console.log(Y.dim(" Code: current file"));Y.newline()}if(Z.length>0){console.log(Y.theme.dim(`= Unchanged (${Z.length}):`));let j=Z.join(", ");console.log(Y.dim(` ${j}`)),Y.newline()}if(J.length>0||Q.length>0||X.length>0)console.log(Y.bold(`${J.length+Q.length+X.length} file(s) changed, ${Z.length} unchanged`)),Y.newline(),Y.info('Run "unreal pull" to sync your code schema with the database.');else Y.success("Code schema is in sync with database")}var x1=new G4().name("diff").description("Compare TypeScript schema with database schema").option("--url <url>","Database URL (e.g., http://localhost:8000)").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Auth level: root, namespace, or database").option("-s, --schema-dir <path>","Schema directory path").option("-e, --embedded <mode>","Use embedded mode (memory or file path)").option("--detailed","Show detailed field-level changes").option("--log-level <level>","Log output level: silent, normal, debug","normal").action(async($)=>{try{Y.header("UnrealORM Diff","Compare code vs database schema"),L("Loading config");let J=await a(),Q=await $0({cliOutput:$.schemaDir,config:J});L("Resolving database connection");let X=await i({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:J,skipAutoConfig:!0});if(!X)Y.error("Failed to establish database connection."),process.exit(1);L("Introspecting database schema");let Z=Y.spin("Introspecting database schema"),B=await X0(X);Z.succeed("Introspected database schema"),L("Parsing code schema");let j=null;if(s0(Q)){let G=Y.spin("Parsing code schema");try{j=await Z0(Q),G.succeed("Parsed code schema")}catch(U){G.fail("Could not parse code schema"),Y.warn(`${U instanceof Error?U.message:String(U)}`),Y.dim("Falling back to file-based comparison"),Y.newline()}}if(j){L("Comparing schemas (semantic)");let G=_4(B,j);if(G.length===0){Y.success("No schema differences detected. Code and database schemas are in sync."),await X.close();return}let U=H4(G),K=T1(G,$.detailed);Y.divider(),Y.info("Schema Changes"),Y.divider(),Y.newline(),console.log(K);let W=[];if(U.fields>0)W.push(Y.theme.warning(`${U.fields} field(s)`));if(U.indexes>0)W.push(Y.theme.info(`${U.indexes} index(es)`));if(U.tables>0)W.push(Y.theme.primary(`${U.tables} table(s)`));if(Y.newline(),console.log(Y.bold(`${U.total} change(s): ${W.join(", ")}`)),!$.detailed&&U.total>0)Y.newline(),Y.dim("Tip: Use --detailed flag to see old/new values for changes");Y.newline(),console.log(Y.theme.secondary("Run"),Y.bold("unreal pull"),Y.theme.secondary("or"),Y.bold("unreal push"),Y.theme.secondary("to sync your code schema with the database.")),Y.newline()}else{let G=N0(B),U=z4(G,Q);W4(U)}await X.close()}catch(J){Y.error("Error:",J),process.exit(1)}});import{Command as R4}from"@commander-js/extra-typings";import{promises as I4,existsSync as P4}from"node:fs";import a0 from"node:path";import{promises as A4}from"node:fs";import{parseTableDefinition as V4,parseFieldDefinition as O4,parseIndexDefinition as E4}from"unreal-orm";var y1={};function C1($){return{name:$,type:"NORMAL",schemafull:!0,drop:!1,permissions:y1,fields:[],indexes:[],events:[]}}async function b1($){let J=await A4.readFile($,"utf-8");return D4(J)}function M4($){let J=$.replace(/--.*$/gm,"");return J=J.replace(/\/\*[\s\S]*?\*\//g,""),J}function D4($){let J=new Map,X=M4($).split(";").map((Z)=>Z.trim()).filter((Z)=>Z.length>0);for(let Z of X){let j=Z.replace(/\s+/g," ").trim().toUpperCase();try{if(j.startsWith("DEFINE TABLE")){let G=V4(Z);if(G.name)J.set(G.name,{name:G.name,type:G.type??"NORMAL",schemafull:G.schemafull??!0,drop:G.drop??!1,permissions:G.permissions??y1,viewQuery:G.viewQuery,fields:[],indexes:[],events:[]});else C("DEFINE TABLE","Could not extract table name",`Statement: ${Z.slice(0,80)}...`)}else if(j.startsWith("DEFINE FIELD")){let G=O4(Z),U=Z.match(/\bON\s+(?:TABLE\s+)?(\w+)/i);if(U?.[1]){let K=U[1],W=J.get(K);if(!W)W=C1(K),J.set(K,W);W.fields.push(G)}else C("DEFINE FIELD","Could not extract table name from field definition",`Statement: ${Z.slice(0,80)}...`)}else if(j.startsWith("DEFINE INDEX")){let G=E4(Z),U=Z.match(/\bON\s+(?:TABLE\s+)?(\w+)/i);if(U?.[1]){let K=U[1],W=J.get(K);if(!W)W=C1(K),J.set(K,W);W.indexes.push(G)}else C("DEFINE INDEX","Could not extract table name from index definition",`Statement: ${Z.slice(0,80)}...`)}else if(j.startsWith("DEFINE EVENT"))C("DEFINE EVENT","Events are not yet supported","Event definitions will be skipped");else if(j.startsWith("DEFINE ANALYZER"));else if(j.startsWith("DEFINE FUNCTION"))C("DEFINE FUNCTION","Custom functions are not yet supported","Function definitions will be skipped");else if(j.startsWith("DEFINE PARAM"))C("DEFINE PARAM","Database parameters are not yet supported","Parameter definitions will be skipped");else if(j.startsWith("DEFINE USER"));else if(j.startsWith("DEFINE ACCESS"));else if(j.startsWith("OPTION"));}catch(G){let U=G instanceof Error?G.message:String(G);C("Parse error",U,`Statement: ${Z.slice(0,80)}${Z.length>80?"...":""}`)}}return{tables:Array.from(J.values())}}U0();c();var f1=new R4("mermaid").description("Generate a Mermaid ERD diagram from TypeScript schema, database, or .surql file").option("-o, --output <path>","Output file path for .mermaid file").option("-s, --schema-dir <path>","Schema directory path (for --code mode)").option("-c, --config <path>","Path to config file").option("--stdout","Print to stdout instead of file").option("--code","Use TypeScript schema definitions").option("--db","Use database connection (introspect live database)").option("--surql <path>","Use a .surql schema file").option("--url <url>","Database URL (implies --db)").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Auth level: root, namespace, or database").option("--embedded <mode>","Use embedded mode (memory or file path)").option("--log-level <level>","Log output level: silent, normal, debug","normal").action(async($)=>{Y.header("Mermaid ERD Generator","Visualize your schema"),K0();let J=Y.spin("Loading configuration...");try{L("Loading config");let Q=await a($.config);if(Q)J.succeed("Configuration loaded");else J.info("No configuration file found (using defaults/flags)");let X=$.output;if(!X&&!$.stdout)J.stop(),X=await P0("Output file path:",Q?a0.join(Q.path,"schema.mermaid"):"./unreal/schema.mermaid");let Z=$.url||$.username||$.password||$.namespace||$.database||$.embedded,B;if($.surql)B="surql";else if($.db||Z)B="database";else if($.code)B="code";if(!B){if(J.stop(),B=await C0("Schema source:",[{title:"TypeScript schema (./unreal/tables/)",value:"code"},{title:"Database (introspect live database)",value:"database"},{title:"SurrealQL file (.surql)",value:"surql"}]),!B)process.exit(0)}let j;if(B==="code"){J.stop();let U=await $0({cliOutput:$.schemaDir,config:Q});J.start(`Extracting schema from ${U}...`),L("Extracting code schema"),j=await Z0(U),J.succeed(`Found ${j.tables.length} tables from TypeScript schema`)}else if(B==="database"){J.stop();let U=await i({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:Q,skipAutoConfig:!0});if(!U)Y.error("Failed to establish database connection."),process.exit(1);L("Introspecting database schema"),J.start("Introspecting database schema...");try{j=await X0(U),J.succeed(`Found ${j.tables.length} tables from database`)}finally{await U.close()}}else{let U=typeof $.surql==="string"?$.surql:"";if(!U)J.stop(),U=await P0("Path to .surql file:","./schema.surql");let K=a0.resolve(process.cwd(),U);if(!P4(K))J.fail(`File not found: ${K}`),process.exit(1);J.start(`Parsing ${U}...`),j=await b1(K),J.succeed(`Found ${j.tables.length} tables from .surql file`)}L("Generating Mermaid diagram"),J.start("Generating Mermaid diagram...");let G=F4(j);if(J.succeed("Diagram generated"),$.stdout)console.log(`
227
+ ${G}`);else{let U=a0.resolve(process.cwd(),X||"./unreal/schema.mermaid");await I4.writeFile(U,G),Y.success(`Saved to ${U}`),Y.dim(`Tip: Preview with VS Code Mermaid extension,
228
+ https://mermiko.com, or https://mermaid.live`)}J0()}catch(Q){J.fail("Failed to generate diagram"),Y.error(Q instanceof Error?Q.message:String(Q)),process.exit(1)}});function F4($){let J=["erDiagram"],Q=$.tables.filter((G)=>G.type==="NORMAL"),X=$.tables.filter((G)=>G.type==="RELATION"),Z=$.tables.filter((G)=>G.type==="VIEW"),B=[],j=new Map;for(let G of $.tables){let U=new Set;for(let K of G.indexes){let W=K.columns[0];if(K.unique&&K.columns.length===1&&W)U.add(W)}if(U.size>0&&G.name)j.set(G.name,U)}if(Q.length>0){J.push(" %% === TABLES ===");for(let G of Q){let U=g1(G,j);J.push(...U.lines),B.push(...U.relationships)}}if(X.length>0){J.push(" %% === RELATIONS (Graph Edges) ===");for(let G of X){let U=w4(G,j);J.push(...U.lines),B.push(...U.relationships)}}if(Z.length>0){J.push(" %% === VIEWS ===");for(let G of Z){let U=g1(G,j);J.push(...U.lines)}}if(B.length>0)J.push(""),J.push(" %% === RELATIONSHIPS ==="),J.push(...B);return J.join(`
229
+ `)}function g1($,J){let Q=[],X=[],Z=$.fields.filter((G)=>!G.name.includes(".")&&!G.name.includes("[")),B=l($.name),j=J.get($.name)??new Set;Q.push(` ${B} {`);for(let G of Z){let U=V0(G.type),K=l(G.name),W=h1(G,j),q=G.name==="id"||G.assert?.includes("!= NONE")?`*${K}`:K,H=` ${U} ${q}`;if(W)H+=` ${W}`;Q.push(H);let _=G.type.match(/^record<(\w+)>$/);if(_?.[1]){let z=l(_[1]),M=G.assert?.includes("!= NONE"),E=j.has(G.name),A=M?"--":"..",O=`${E?"|":"}"}${M?"|":"o"}`,w="||";X.push(` ${B} ${O}${A}|| ${z} : "${G.name}"`)}}return Q.push(" }"),Q.push(""),{lines:Q,relationships:X}}function w4($,J){let Q=[],X=[],Z=l($.name),B=J.get($.name)??new Set,j=$.fields.find((V)=>V.name==="in"),G=$.fields.find((V)=>V.name==="out"),U=j?.type.match(/^record<(\w+)>$/)?.[1],K=G?.type.match(/^record<(\w+)>$/)?.[1],W=$.fields.filter((V)=>V.name!=="in"&&V.name!=="out"&&!V.name.includes(".")&&!V.name.includes("["));if(W.length===0){if(U&&K){let V=l(U),q=l(K);X.push(` ${V} }|--|{ ${q} : "${$.name}"`)}return{lines:[],relationships:X}}if(Q.push(` ${Z} {`),j&&U)Q.push(` ${l(U)} *in FK`);if(G&&K)Q.push(` ${l(K)} *out FK`);for(let V of W){let q=V0(V.type),H=l(V.name),_=h1(V,B),M=V.name==="id"||V.assert?.includes("!= NONE")?`*${H}`:H,E=` ${q} ${M}`;if(_)E+=` ${_}`;Q.push(E)}if(Q.push(" }"),Q.push(""),U&&K){let V=l(U),q=l(K);X.push(` ${V} ||--o{ ${Z} : "in"`),X.push(` ${Z} }o--|| ${q} : "out"`)}return{lines:Q,relationships:X}}function l($){return $.replace(/[^a-zA-Z0-9_]/g,"_")}function V0($){if($.startsWith("record<"))return"record";if($==="record")return"record";if($.startsWith("array<")){let Q=$.slice(6,-1);return`array_${V0(Q)}`}if($==="array")return"array";if($.startsWith("option<")){let Q=$.slice(7,-1);return V0(Q)}if($.startsWith("set<")){let Q=$.slice(4,-1);return`set_${V0(Q)}`}if($.startsWith("geometry<"))return`geo_${$.slice(9,-1)}`;if($.startsWith("range<"))return"range";if($.includes("|"))return"enum";return{string:"string",int:"int",float:"float",bool:"bool",datetime:"datetime",duration:"duration",decimal:"decimal",number:"number",object:"object",array:"array",any:"any",bytes:"bytes",uuid:"uuid",ulid:"ulid",geometry:"geometry",point:"point",line:"line",polygon:"polygon",multipoint:"multipoint",multiline:"multiline",multipolygon:"multipolygon",collection:"collection",null:"null",none:"none"}[$]||$}function h1($,J){let Q=[];if($.name==="id")Q.push("PK");if($.type.startsWith("record<"))Q.push("FK");if(J.has($.name))Q.push("UK");return Q.join(",")}c();import{Command as L4}from"@commander-js/extra-typings";var m1="https://github.com/Jimpex/unreal-orm",p1=new L4("github").description("Open the UnrealORM GitHub repository").action(async()=>{let{exec:$}=await import("node:child_process"),{platform:J}=await import("node:os"),Q=J()==="win32"?"start":J()==="darwin"?"open":"xdg-open";$(`${Q} ${m1}`,(X)=>{if(X)Y.info(`Visit: ${m1}`)})});c();import{Command as N4}from"@commander-js/extra-typings";var u1="https://unreal-orm.jimpex.dev",c1=new N4("docs").description("Open the UnrealORM documentation").action(async()=>{let{exec:$}=await import("node:child_process"),{platform:J}=await import("node:os"),Q=J()==="win32"?"start":J()==="darwin"?"open":"xdg-open";$(`${Q} ${u1}`,(X)=>{if(X)Y.info(`Visit: ${u1}`)})});import{Command as y4}from"@commander-js/extra-typings";c();var d1="\x1B[?25l",i0="\x1B[?25h";function l1(){process.stdout.write("\x1B[?1049h\x1B[?7l\x1B[H\x1B[J")}function n0(){process.stdout.write("\x1B[?7h\x1B[?1049l")}function r(){let $=process.stdout.rows||24;process.stdout.write(`\x1B[1;${$}r\x1B[H\x1B[J`)}function Y0(){let $=process.stdout.rows||24;process.stdout.write(`\x1B[1;${$}r\x1B[H\x1B[J`)}async function o(){return new Promise(($)=>{let J=process.stdin,Q=J.isRaw;J.setRawMode(!0),J.resume(),J.setEncoding("utf8");let X=(Z)=>{if(J.setRawMode(Q),J.pause(),J.removeListener("data",X),Z==="\x03")process.stdout.write("\x1B[?25h"),process.exit(0);$(Z)};J.once("data",X)})}var t0="\x1BCANCEL";async function v0($,J=""){process.stdout.write("\x1B[?25h"),process.stdout.write($);let Q=J;if(J)process.stdout.write(J);return new Promise((X)=>{let Z=process.stdin;Z.setRawMode(!0),Z.resume(),Z.setEncoding("utf8");let B=(j)=>{if(j==="\x03")process.stdout.write("\x1B[?25h"),process.exit(0);if(j==="\r"||j===`
230
230
  `)Z.setRawMode(!1),Z.pause(),Z.removeListener("data",B),process.stdout.write(`
231
- `),process.stdout.write("\x1B[?25l"),X(Q);else if(_==="\x1B")Z.setRawMode(!1),Z.pause(),Z.removeListener("data",B),process.stdout.write(`
232
- `),process.stdout.write("\x1B[?25l"),X(i0);else if(_===""||_==="\b"){if(Q.length>0)Q=Q.slice(0,-1),process.stdout.write("\b \b")}else if(_>=" "&&_<="~")Q+=_,process.stdout.write(_)};Z.on("data",B)})}function w0($){return $===i0}async function L0($,J){let Q=$.split(`
233
- `),X=0,Z=0,B=0,_=-1,G=process.stdout.rows||24,j=process.stdout.columns||80,U=G-6,W=3,V=(E,A)=>{process.stdout.write(`\x1B[${E};${A}H`)},q=(E,A)=>{V(E,1),process.stdout.write(`\x1B[2K${A}`)},H=()=>{X0(),console.log(` \x1B[1m${J.title}\x1B[0m`),console.log(` \x1B[90m${J.subtitle}\x1B[0m`),console.log(`\x1B[90m${"─".repeat(Math.min(j,80))}\x1B[0m`);let E=Math.min(B+U,Q.length);for(let A=B;A<E;A++)K(A);for(let A=E-B;A<U;A++)console.log("\x1B[90m ~\x1B[0m");M(),_=B},K=(E)=>{let A=Q[E]??"",R=String(E+1).padStart(3," "),I=E===X,O=A;if(O.length>j-8)O=`${O.slice(0,j-11)}...`;if(I){let w=O.slice(0,Z),P=O[Z]??" ",F=O.slice(Z+1);console.log(`\x1B[90m${R}\x1B[0m \x1B[36m${w}\x1B[7m${P}\x1B[0m${F}`)}else console.log(`\x1B[90m${R}\x1B[0m ${O}`)},z=(E)=>{let A=B;if(X<B)B=X;else if(X>=B+U)B=X-U+1;if(B!==A||B!==_){H();return}if(E!==void 0&&E!==X&&E>=B&&E<B+U){let N=W+1+(E-B),v=Q[E]??"",x=String(E+1).padStart(3," "),S=v;if(S.length>j-8)S=`${S.slice(0,j-11)}...`;q(N,`\x1B[90m${x}\x1B[0m ${S}`)}let R=W+1+(X-B),I=Q[X]??"",O=String(X+1).padStart(3," "),w=I;if(w.length>j-8)w=`${w.slice(0,j-11)}...`;let P=w.slice(0,Z),F=w[Z]??" ",L=w.slice(Z+1);q(R,`\x1B[90m${O}\x1B[0m \x1B[36m${P}\x1B[7m${F}\x1B[0m${L}`),M()},M=()=>{let E=W+U+1,A=Math.min(B+U,Q.length),R=`Ln ${X+1}, Col ${Z+1}`,I=Q.length>U?` | ${B+1}-${A}/${Q.length}`:"";q(E,`\x1B[90m ${R}${I} | Ctrl+S save | Esc cancel\x1B[0m`)};return process.stdout.write("\x1B[?25h"),H(),new Promise((E)=>{let A=process.stdin;A.setRawMode(!0),A.resume(),A.setEncoding("utf8");let R=(O)=>{A.setRawMode(!1),A.pause(),A.removeListener("data",I),process.stdout.write("\x1B[?25l"),E(O)},I=(O)=>{let w=X,P=Q[X]??"",F=!1;if(O==="\x03")process.stdout.write("\x1B[?25h"),process.exit(0);if(O==="\x13"){R(Q.join(`
234
- `));return}if(O==="\x1B"&&O.length===1){R(i0);return}if(O==="\x1B[A"){if(X>0)X--,Z=Math.min(Z,(Q[X]??"").length)}else if(O==="\x1B[B"){if(X<Q.length-1)X++,Z=Math.min(Z,(Q[X]??"").length)}else if(O==="\x1B[C"){if(Z<P.length)Z++;else if(X<Q.length-1)X++,Z=0}else if(O==="\x1B[D"){if(Z>0)Z--;else if(X>0)X--,Z=(Q[X]??"").length}else if(O==="\x1B[H"||O==="\x1B[1~")Z=0;else if(O==="\x1B[F"||O==="\x1B[4~")Z=P.length;else if(O==="\x1B[5~")X=Math.max(0,X-U),Z=Math.min(Z,(Q[X]??"").length);else if(O==="\x1B[6~")X=Math.min(Q.length-1,X+U),Z=Math.min(Z,(Q[X]??"").length);else if(O==="\r"||O===`
235
- `){let L=P.slice(0,Z),N=P.slice(Z);Q[X]=L,Q.splice(X+1,0,N),X++,Z=0,F=!0}else if(O===""||O==="\b"){if(Z>0)Q[X]=P.slice(0,Z-1)+P.slice(Z),Z--;else if(X>0){let L=Q[X-1]??"";Z=L.length,Q[X-1]=L+P,Q.splice(X,1),X--,F=!0}}else if(O==="\x1B[3~"){if(Z<P.length)Q[X]=P.slice(0,Z)+P.slice(Z+1);else if(X<Q.length-1)Q[X]=`${P}${Q[X+1]??""}`,Q.splice(X+1,1),F=!0}else if(O==="\t")Q[X]=`${P.slice(0,Z)} ${P.slice(Z)}`,Z+=2;else if(O.length===1&&O>=" "&&O<="~")Q[X]=`${P.slice(0,Z)}${O}${P.slice(Z)}`,Z++;if(F)H();else z(w)};A.on("data",I)})}import j0 from"chalk";var D={primary:j0.hex("#FF00A0"),dim:j0.gray,highlight:j0.cyan,success:j0.green,warning:j0.yellow,error:j0.red},k={topLeft:"┌",topRight:"┐",bottomLeft:"└",bottomRight:"┘",horizontal:"─",vertical:"│",teeRight:"├",teeLeft:"┤",teeDown:"┬",teeUp:"┴",cross:"┼"};import w4 from"chalk";function i($,J){let Q=Math.min(process.stdout.columns||80,80);if(console.log(D.primary.bold(` ${$}`)),J)console.log(D.dim(` ${J}`));console.log(D.dim(k.horizontal.repeat(Q)))}function u1($,J,Q,X){console.log(D.dim(` ${k.topLeft}${Q.map((B)=>k.horizontal.repeat(B)).join(k.teeDown)}${k.topRight}`));let Z=$.map((B,_)=>m1(B,Q[_]??10)).join(D.dim(k.vertical));console.log(`${D.dim(` ${k.vertical}`)}${w4.bold(Z)}${D.dim(k.vertical)}`),console.log(D.dim(` ${k.teeRight}${Q.map((B)=>k.horizontal.repeat(B)).join(k.cross)}${k.teeLeft}`));for(let B=0;B<J.length;B++){let _=J[B];if(!_)continue;let j=B===X?D.primary("▸ "):" ",U=_.map((W,V)=>m1(W,Q[V]??10)).join(D.dim(k.vertical));console.log(`${j}${D.dim(k.vertical)}${U}${D.dim(k.vertical)}`)}console.log(D.dim(` ${k.bottomLeft}${Q.map((B)=>k.horizontal.repeat(B)).join(k.teeUp)}${k.bottomRight}`))}function m1($,J){let Q=v0($);if(Q.length>=J)return`${L4($,J-1)}…`;return $+" ".repeat(J-Q.length)}function L4($,J){let Q=0,X=0,Z=/\x1b\[[0-9;]*m/g;while(X<$.length&&Q<J){Z.lastIndex=X;let _=Z.exec($);if(_&&_.index===X)X=Z.lastIndex;else Q++,X++}let B=$.slice(0,X);if($.includes("\x1B[")&&!B.endsWith("\x1B[0m"))return`${B}\x1B[0m`;return B}function v0($){return $.replace(/\x1b\[[0-9;]*m/g,"")}async function W0($){d(),i("Confirm",""),console.log(""),console.log(D.warning(` ${$}`)),console.log(""),console.log(D.dim(" y yes • n no"));let J=await l();return J==="y"||J==="Y"}async function p1($,J){return d(),i("Confirm Action",""),console.log(""),console.log(D.warning(` ${$}`)),console.log(""),await F0(" > ")===J}async function A0($){d(),i("Error",""),console.log(""),console.log(D.error(` ${$}`)),console.log(""),console.log(D.dim(" Press any key to continue...")),await l()}async function c1($){d(),i("Success",""),console.log(""),console.log(D.success(` ${$}`)),console.log(""),console.log(D.dim(" Press any key to continue...")),await l()}function l1($){if($==="timeout")return D.warning("timeout");if($==="?")return D.dim("?");if($>=1e6)return D.highlight(`${($/1e6).toFixed(1)}M`);if($>=1000)return D.highlight(`${($/1000).toFixed(1)}K`);return D.highlight(String($))}function V0($,J=40){if($===void 0||$===null)return D.dim("null");if(Array.isArray($)){if($.length===0)return D.dim("[]");if($.length<=5){let Z=`[${$.map((B)=>d1(B)).join(", ")}]`;if(Z.length>J)return D.dim(`[${$.length} items]`);return D.dim(Z)}return D.dim(`[${$.length} items]`)}if(typeof $==="object"){let X=String($);if(X!=="[object Object]"){if(X.length>J)return D.dim(`${X.slice(0,J-3)}...`);return D.dim(X)}let Z=Object.keys($);if(Z.length===0)try{let B=JSON.stringify($);if(B.length>J)return D.dim(`${B.slice(0,J-3)}...`);return D.dim(B)}catch{return D.dim("{}")}if(Z.length<=5){let _=`{${Z.map((G)=>`${G}: ${d1($[G])}`).join(", ")}}`;if(_.length>J)return D.dim(`{${Z.length} fields}`);return D.dim(_)}return D.dim(`{${Z.length} fields}`)}if(typeof $==="boolean")return $?D.success("true"):D.error("false");if(typeof $==="number")return D.highlight(String($));let Q=String($).replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");if(Q.length>J)return`${Q.slice(0,J-3)}...`;return Q}function d1($){if($===void 0||$===null)return"null";if(Array.isArray($))return`[${$.length}]`;if(typeof $==="object"){let J=String($);if(J!=="[object Object]"){if(J.length>15)return`${J.slice(0,12)}...`;return J}let Q=Object.keys($);if(Q.length===0)try{let X=JSON.stringify($);if(X.length>15)return`${X.slice(0,12)}...`;return X}catch{return"{}"}return`{${Q.length}}`}if(typeof $==="string"){let J=$.replace(/\n/g,"\\n");if(J.length>15)return`"${J.slice(0,12)}..."`;return`"${J}"`}return String($)}function a0($){if(!$)return"";try{return JSON.parse($)}catch{if($==="true")return!0;if($==="false")return!1;if($==="null")return null;let J=Number($);if(!Number.isNaN(J)&&$.trim()!=="")return J;return $}}async function r1($,J,Q){let X=Q.id?String(Q.id):"unknown",Z=0,B={...Q},_={...Q},G=[],j=()=>Object.keys(_).sort((q,H)=>{if(q==="id")return-1;if(H==="id")return 1;return q.localeCompare(H)}),U=(q)=>{for(let H of G){if(H.type==="add"&&H.key===q)return"added";if(H.type==="edit"&&H.key===q)return"edited";if(H.type==="remove"&&H.key===q)return"removed"}return null},W=()=>G.length>0,V=(q=!1)=>{if(q)d();else X0();let H=process.stdout.rows||24,K=process.stdout.columns||80,z=Math.max(3,H-5),M=G.length,E=M>0?`${M} changes • s save • x discard`:J;i(`Record: ${X}`,E);let A=j(),R=Math.min(Math.max(...A.map((F)=>F.length),8),20),I=K-R-6,O=0;if(Z>=z)O=Z-z+1;let w=Math.min(O+z,A.length);for(let F=O;F<w;F++){let L=A[F];if(!L)continue;let N=_[L],v=F===Z,x=U(L),S=v?D.primary("▸ "):" ",g;if(x==="added")g=D.success(`+ ${L.slice(0,R-2).padEnd(R-2)}`);else if(x==="edited")g=D.warning(`~ ${L.slice(0,R-2).padEnd(R-2)}`);else if(x==="removed")g=D.error(`- ${L.slice(0,R-2).padEnd(R-2)}`);else if(v)g=D.primary.bold(L.slice(0,R).padEnd(R));else g=D.highlight(L.slice(0,R).padEnd(R));let e1=V0(N,I);console.log(`${S}${g} ${e1}`)}let P=A.length>z?`${O+1}-${w}/${A.length} • `:"";console.log(D.dim(` ${P}↑↓ nav • e edit • + add • - del • d delete • b back • q quit`))};V(!0);while(!0){let q=await l(),H=j();if(q==="q"){if(W()){if(!await W0("Discard unsaved changes?")){V();continue}}throw Error("EXIT")}if(q==="b"||q==="\x1B"){if(W()){if(!await W0("Discard unsaved changes?")){V();continue}}return"back"}if(q==="\x1B[A"||q==="k")Z=Math.max(0,Z-1),V();else if(q==="\x1B[B"||q==="j")Z=Math.min(H.length-1,Z+1),V();else if(q==="e"||q==="\r"||q===`
236
- `){let K=H[Z];if(K&&K!=="id"){let z=_[K],M=await v4(K,z);if(M!==void 0){let E=B[K];if(JSON.stringify(M)!==JSON.stringify(E)){let A=G.findIndex((R)=>R.type==="edit"&&R.key===K);if(A>=0)G.splice(A,1);G.push({type:"edit",key:K,oldValue:E,newValue:M})}else{let A=G.findIndex((R)=>R.type==="edit"&&R.key===K);if(A>=0)G.splice(A,1)}_[K]=M}V()}else if(K==="id")await A0("Cannot edit the id field"),V()}else if(q==="+"||q==="="){let K=await N4();if(K)_[K.key]=K.value,G.push({type:"add",key:K.key,value:K.value});V()}else if(q==="-"||q==="_"){let K=H[Z];if(K&&K!=="id"){if(U(K)==="added"){let M=G.findIndex((E)=>E.type==="add"&&E.key===K);if(M>=0)G.splice(M,1);delete _[K]}else G.push({type:"remove",key:K,oldValue:B[K]}),delete _[K];Z=Math.min(Z,H.length-2),V()}else if(K==="id")await A0("Cannot remove the id field"),V()}else if(q==="u"||q==="U"){let K=G.pop();if(K){if(K.type==="edit")_[K.key]=K.oldValue;else if(K.type==="add")delete _[K.key];else if(K.type==="remove")_[K.key]=K.oldValue}V()}else if(q==="x"||q==="X"){if(W()){if(await W0("Discard all changes?")){G.length=0;for(let z of Object.keys(_))delete _[z];Object.assign(_,B)}V()}}else if(q==="s"||q==="S"){if(W()){if(await W0(`Save ${G.length} change${G.length>1?"s":""}?`))try{let z=[],M=[],E={};for(let R of G)if(R.type==="edit"||R.type==="add"){let I=`p_${R.key.replace(/[^a-zA-Z0-9]/g,"_")}`;z.push(`\`${R.key}\` = $${I}`),E[I]=R.type==="edit"?R.newValue:R.value}else if(R.type==="remove")M.push(`\`${R.key}\``);let A=`UPDATE ${X}`;if(z.length>0)A+=` SET ${z.join(", ")}`;if(M.length>0)A+=` UNSET ${M.join(", ")}`;A+=` TIMEOUT ${$.timeout}s`,await $.db.query(A,E).collect(),G.length=0;for(let R of Object.keys(B))delete B[R];Object.assign(B,_),await c1("Changes saved successfully")}catch(z){await A0(`Failed to save: ${z instanceof Error?z.message:String(z)}`)}V()}}else if(q==="d"||q==="D")if(await p1(`Delete record ${X}? Type "delete" to confirm:`,"delete"))try{return await $.db.query(`DELETE ${X} TIMEOUT ${$.timeout}s`).collect(),"deleted"}catch(z){await A0(`Failed to delete: ${z instanceof Error?z.message:String(z)}`),V()}else V()}}async function v4($,J){let Q=typeof J==="object"?JSON.stringify(J,null,2):String(J??""),X=await L0(Q,{title:`Edit: ${$}`,subtitle:"Arrows to move • Type to edit • Ctrl+S save • Esc cancel"});if(w0(X))return;return a0(X)}async function N4(){let $=await L0("",{title:"Add Field - Enter Name",subtitle:"Type field name • Ctrl+S confirm • Esc cancel"});if(w0($)||!$.trim())return null;let J=await L0("",{title:`Add Field: ${$.trim()}`,subtitle:"Type value (JSON for objects/arrays) • Ctrl+S confirm • Esc cancel"});if(w0(J))return null;return{key:$.trim(),value:a0(J)}}async function o1($,J,Q){let X=0,Z=0,B=[],_=[],G=!0,j=!0,U=Q,W=async()=>{G=!0,V(j),j=!1;let[q]=await $.db.query(`SELECT * FROM \`${J}\` LIMIT ${$.pageSize} START ${X} TIMEOUT ${$.timeout}s`).collect();B=q||[];let H=new Set(["id"]);for(let K of B)for(let z of Object.keys(K))H.add(z);_=Array.from(H),Z=Math.min(Z,Math.max(0,B.length-1)),G=!1,V()},V=(q=!1)=>{if(q)d();else X0();let H=process.stdout.rows||24,K=Math.max(3,H-9),z=B.slice(0,K),M=U!==void 0?` (${U} records)`:"",E=Math.floor(X/$.pageSize)+1,A=U!==void 0?Math.ceil(U/$.pageSize):"?";if(i(`Table: ${J}${M}`,`Page ${E}/${A}`),G){console.log(D.dim(" Loading records..."));return}if(B.length===0){console.log(D.dim(" No records found.")),console.log(D.dim(" b back • q quit"));return}let R=process.stdout.columns||80,I=Math.floor(R/_.length)-1,O=_.map((N)=>{let v=N.length;for(let x of z){let S=V0(x[N]);v=Math.max(v,v0(S).length)}return Math.min(v+2,I)}),w=z.map((N,v)=>_.map((x)=>{let S=V0(N[x]);return v===Z?D.primary(v0(S)):S}));u1(_,w,O,Z);let P=X+z.length,F=U!==void 0?`/${U}`:"",L=X+Z+1;console.log(D.dim(` ${L}${F} • ${X+1}-${P} • ↑↓ select • Enter view • ←→ page • b back • q quit`))};await W();while(!0){let q=await l();if(q==="q")throw Error("EXIT");if(q==="b"||q==="\x1B")return;if(q==="\x1B[A"||q==="k"){if(Z>0)Z--,V();else if(X>0)X=Math.max(0,X-$.pageSize),Z=$.pageSize-1,await W()}else if(q==="\x1B[B"||q==="j"){if(Z<B.length-1)Z++,V();else if(U===void 0||X+B.length<U)X+=$.pageSize,Z=0,await W()}else if(q==="\x1B[D"||q==="h"||q==="["){if(X>0)X=Math.max(0,X-$.pageSize),Z=0,await W()}else if(q==="\x1B[C"||q==="l"||q==="]"){if(U===void 0||X+$.pageSize<U)X+=$.pageSize,Z=0,await W()}else if(q==="\r"||q===`
237
- `){let H=B[Z];if(H)if(await r1($,J,H)==="deleted")await W();else await W()}else if(q==="g")X=0,Z=0,await W();else if(q==="G"&&U!==void 0)X=Math.max(0,Math.floor((U-1)/$.pageSize)*$.pageSize),Z=0,await W()}}async function S4($,J,Q){return $.query(`SELECT count() FROM \`${J}\` GROUP ALL TIMEOUT ${Q}s`).collect().then((X)=>X[0]?.[0]?.count??"timeout").catch(()=>"timeout")}async function k4($,J,Q,X,Z){let B=0,_=async()=>{while(B<J.length){let j=B++,U=J[j];if(!U)continue;U.count=await S4($,U.name,Q),Z()}},G=Array.from({length:Math.min(X,J.length)},()=>_());await Promise.all(G)}async function s1($){let J=0,Q=[],X=[],Z=!0,B="",_=async()=>{Z=!0,G(!0);let[U]=await $.db.query("INFO FOR DB").collect(),W=U;if(!W?.tables)throw Error("Failed to retrieve database info");if(Q=Object.keys(W.tables).sort().map((q)=>({name:q,count:"?"})),X=Q,Z=!1,G(),!$.skipCount)await k4($.db,Q,$.timeout,$.concurrency,G)},G=(U=!1)=>{if(U)d();else X0();let W=process.stdout.rows||24,V=Math.max(5,W-4),q=B?` ${D.highlight(`[filter: ${B}]`)}`:"";if(i(`Tables${q}`,`${X.length} tables`),Z){console.log(D.dim(" Loading tables..."));return}if(X.length===0){if(B)console.log(D.warning(` No tables matching "${B}"`)),console.log(D.dim(" Press Esc to clear filter"));else console.log(D.warning(" No tables found in database."));return}let H=0;if(J>=V)H=J-V+1;let K=Math.min(H+V,X.length);for(let M=H;M<K;M++){let E=X[M];if(!E)continue;let A=M===J,R=A?D.primary("▸ "):" ",I=A?D.primary.bold(E.name):E.name,O=l1(E.count);console.log(`${R}${I} ${D.dim("(")}${O}${D.dim(")")}`)}let z=X.length>V?`${H+1}-${K}/${X.length} • `:"";console.log(D.dim(` ${z}↑↓ nav • Enter select • / filter • r refresh • q quit`))};if(await _(),X.length===0&&!B){await l();return}let j=()=>{if(B){let U=B.toLowerCase();X=Q.filter((W)=>W.name.toLowerCase().includes(U))}else X=Q;J=Math.min(J,Math.max(0,X.length-1))};while(!0){let U=await l();if(U==="q")throw Error("EXIT");if(U==="\x1B"){if(B)B="",j(),G();else throw Error("EXIT");continue}if(U==="\x1B[A"||U==="k")J=Math.max(0,J-1),G();else if(U==="\x1B[B"||U==="j")J=Math.min(X.length-1,J+1),G();else if(U==="\r"||U===`
238
- `){let W=X[J];if(W){let V=typeof W.count==="number"?W.count:void 0;await o1($,W.name,V),G(!0)}}else if(U==="g")J=0,G();else if(U==="G")J=X.length-1,G();else if(U==="r"||U==="R")B="",J=0,await _();else if(U==="/")G(),B=await F0(D.highlight(" Filter: ")),j(),G()}}var C4=15,n0=5,i1=100,t0=3,e0=5,a1=new T4("view").description("Interactive TUI for browsing database tables and records").option("--url <url>","Database URL").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Authentication level (root, namespace, database)").option("-e, --embedded <mode>","Use embedded mode (memory or file path)").option("--page-size <size>",`Records per page (${n0}-${i1}, default: auto)`).option("--timeout <seconds>",`Query timeout in seconds (default: ${t0})`).option("--concurrency <count>",`Max concurrent count queries (default: ${e0})`).option("--no-count","Skip fetching table record counts").action(async($)=>{Y.header("Database Viewer","Interactive table browser");let J=await o(),Q=await s({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:J,skipAutoConfig:!0});if(!Q)return;let X=process.stdout.rows||24,Z=C4;if($.pageSize){let j=Number.parseInt($.pageSize,10);if(!Number.isNaN(j))Z=Math.max(n0,Math.min(i1,j))}else Z=Math.max(n0,Math.min(X-10,30));let B=$.timeout?Math.max(1,Number.parseInt($.timeout,10)||t0):t0,_=$.concurrency?Math.max(1,Number.parseInt($.concurrency,10)||e0):e0,G={db:Q,pageSize:Z,terminalHeight:X,timeout:B,concurrency:_,skipCount:!$.count};h1(),process.stdout.write(f1);try{await s1(G)}catch(j){if(j instanceof Error&&j.message==="EXIT");else{process.stdout.write(o0),s0(),Y.error(j instanceof Error?j.message:String(j)),await Q.close();return}}process.stdout.write(o0),s0(),await Q.close()});u();import{createRequire as x4}from"node:module";var O0=x4(import.meta.url);function y4(){try{let $=O0.resolve("@unreal-orm/cli/package.json");return O0($).version}catch{try{return O0("../../package.json").version}catch{return"unknown"}}}var $1=y4(),b4="https://registry.npmjs.org";async function g4($,J="latest"){try{let Q=await fetch(`${b4}/${$}`);if(!Q.ok)return null;let X=await Q.json();return X["dist-tags"][J]??X["dist-tags"].latest??null}catch{return null}}async function n1($,J,Q="latest"){let X=await g4($,Q);if(!X)return null;return{current:J,latest:X,isOutdated:X!==J}}function f4(){try{let $=O0.resolve("unreal-orm/package.json",{paths:[process.cwd()]});return O0($).version}catch{return null}}async function t1(){if(process.env.CI||process.env.UNREAL_SKIP_UPDATE_CHECK)return;try{let[$,J]=await Promise.all([n1("@unreal-orm/cli",$1,"latest"),(async()=>{let X=f4();if(!X)return null;return n1("unreal-orm",X,"latest")})()]),Q=[];if($?.isOutdated)Q.push(` @unreal-orm/cli: ${Y.dim($.current)} → ${Y.theme.success($.latest)}`);if(J?.isOutdated)Q.push(` unreal-orm: ${Y.dim(J.current)} → ${Y.theme.success(J.latest)}`);if(Q.length>0){Y.newline(),Y.warn("\uD83D\uDCE6 Updates available:");for(let X of Q)console.log(X);Y.dim("\n Run `npm update @unreal-orm/cli unreal-orm` to update\n")}}catch{}}var a=new h4().name("unreal").description("UnrealORM CLI for SurrealDB").version($1).hook("postAction",async()=>{await t1()});a.addCommand(Y1);a.addCommand(R1);a.addCommand(P1);a.addCommand(L1);a.addCommand(T1);a.addCommand(g1);a.addCommand(a1);a.addCommand(y1);a.parse();
231
+ `),process.stdout.write("\x1B[?25l"),X(Q);else if(j==="\x1B")Z.setRawMode(!1),Z.pause(),Z.removeListener("data",B),process.stdout.write(`
232
+ `),process.stdout.write("\x1B[?25l"),X(t0);else if(j===""||j==="\b"){if(Q.length>0)Q=Q.slice(0,-1),process.stdout.write("\b \b")}else if(j>=" "&&j<="~")Q+=j,process.stdout.write(j)};Z.on("data",B)})}function S0($){return $===t0}async function k0($,J){let Q=$.split(`
233
+ `),X=0,Z=0,B=0,j=-1,G=process.stdout.rows||24,U=process.stdout.columns||80,K=G-6,W=3,V=(E,A)=>{process.stdout.write(`\x1B[${E};${A}H`)},q=(E,A)=>{V(E,1),process.stdout.write(`\x1B[2K${A}`)},H=()=>{Y0(),console.log(` \x1B[1m${J.title}\x1B[0m`),console.log(` \x1B[90m${J.subtitle}\x1B[0m`),console.log(`\x1B[90m${"─".repeat(Math.min(U,80))}\x1B[0m`);let E=Math.min(B+K,Q.length);for(let A=B;A<E;A++)_(A);for(let A=E-B;A<K;A++)console.log("\x1B[90m ~\x1B[0m");M(),j=B},_=(E)=>{let A=Q[E]??"",R=String(E+1).padStart(3," "),I=E===X,O=A;if(O.length>U-8)O=`${O.slice(0,U-11)}...`;if(I){let w=O.slice(0,Z),P=O[Z]??" ",F=O.slice(Z+1);console.log(`\x1B[90m${R}\x1B[0m \x1B[36m${w}\x1B[7m${P}\x1B[0m${F}`)}else console.log(`\x1B[90m${R}\x1B[0m ${O}`)},z=(E)=>{let A=B;if(X<B)B=X;else if(X>=B+K)B=X-K+1;if(B!==A||B!==j){H();return}if(E!==void 0&&E!==X&&E>=B&&E<B+K){let S=W+1+(E-B),v=Q[E]??"",y=String(E+1).padStart(3," "),k=v;if(k.length>U-8)k=`${k.slice(0,U-11)}...`;q(S,`\x1B[90m${y}\x1B[0m ${k}`)}let R=W+1+(X-B),I=Q[X]??"",O=String(X+1).padStart(3," "),w=I;if(w.length>U-8)w=`${w.slice(0,U-11)}...`;let P=w.slice(0,Z),F=w[Z]??" ",N=w.slice(Z+1);q(R,`\x1B[90m${O}\x1B[0m \x1B[36m${P}\x1B[7m${F}\x1B[0m${N}`),M()},M=()=>{let E=W+K+1,A=Math.min(B+K,Q.length),R=`Ln ${X+1}, Col ${Z+1}`,I=Q.length>K?` | ${B+1}-${A}/${Q.length}`:"";q(E,`\x1B[90m ${R}${I} | Ctrl+S save | Esc cancel\x1B[0m`)};return process.stdout.write("\x1B[?25h"),H(),new Promise((E)=>{let A=process.stdin;A.setRawMode(!0),A.resume(),A.setEncoding("utf8");let R=(O)=>{A.setRawMode(!1),A.pause(),A.removeListener("data",I),process.stdout.write("\x1B[?25l"),E(O)},I=(O)=>{let w=X,P=Q[X]??"",F=!1;if(O==="\x03")process.stdout.write("\x1B[?25h"),process.exit(0);if(O==="\x13"){R(Q.join(`
234
+ `));return}if(O==="\x1B"&&O.length===1){R(t0);return}if(O==="\x1B[A"){if(X>0)X--,Z=Math.min(Z,(Q[X]??"").length)}else if(O==="\x1B[B"){if(X<Q.length-1)X++,Z=Math.min(Z,(Q[X]??"").length)}else if(O==="\x1B[C"){if(Z<P.length)Z++;else if(X<Q.length-1)X++,Z=0}else if(O==="\x1B[D"){if(Z>0)Z--;else if(X>0)X--,Z=(Q[X]??"").length}else if(O==="\x1B[H"||O==="\x1B[1~")Z=0;else if(O==="\x1B[F"||O==="\x1B[4~")Z=P.length;else if(O==="\x1B[5~")X=Math.max(0,X-K),Z=Math.min(Z,(Q[X]??"").length);else if(O==="\x1B[6~")X=Math.min(Q.length-1,X+K),Z=Math.min(Z,(Q[X]??"").length);else if(O==="\r"||O===`
235
+ `){let N=P.slice(0,Z),S=P.slice(Z);Q[X]=N,Q.splice(X+1,0,S),X++,Z=0,F=!0}else if(O===""||O==="\b"){if(Z>0)Q[X]=P.slice(0,Z-1)+P.slice(Z),Z--;else if(X>0){let N=Q[X-1]??"";Z=N.length,Q[X-1]=N+P,Q.splice(X,1),X--,F=!0}}else if(O==="\x1B[3~"){if(Z<P.length)Q[X]=P.slice(0,Z)+P.slice(Z+1);else if(X<Q.length-1)Q[X]=`${P}${Q[X+1]??""}`,Q.splice(X+1,1),F=!0}else if(O==="\t")Q[X]=`${P.slice(0,Z)} ${P.slice(Z)}`,Z+=2;else if(O.length===1&&O>=" "&&O<="~")Q[X]=`${P.slice(0,Z)}${O}${P.slice(Z)}`,Z++;if(F)H();else z(w)};A.on("data",I)})}import _0 from"chalk";var D={primary:_0.hex("#FF00A0"),dim:_0.gray,highlight:_0.cyan,success:_0.green,warning:_0.yellow,error:_0.red},T={topLeft:"┌",topRight:"┐",bottomLeft:"└",bottomRight:"┘",horizontal:"─",vertical:"│",teeRight:"├",teeLeft:"┤",teeDown:"┬",teeUp:"┴",cross:"┼"};import v4 from"chalk";function n($,J){let Q=Math.min(process.stdout.columns||80,80);if(console.log(D.primary.bold(` ${$}`)),J)console.log(D.dim(` ${J}`));console.log(D.dim(T.horizontal.repeat(Q)))}function o1($,J,Q,X){console.log(D.dim(` ${T.topLeft}${Q.map((B)=>T.horizontal.repeat(B)).join(T.teeDown)}${T.topRight}`));let Z=$.map((B,j)=>r1(B,Q[j]??10)).join(D.dim(T.vertical));console.log(`${D.dim(` ${T.vertical}`)}${v4.bold(Z)}${D.dim(T.vertical)}`),console.log(D.dim(` ${T.teeRight}${Q.map((B)=>T.horizontal.repeat(B)).join(T.cross)}${T.teeLeft}`));for(let B=0;B<J.length;B++){let j=J[B];if(!j)continue;let U=B===X?D.primary("▸ "):" ",K=j.map((W,V)=>r1(W,Q[V]??10)).join(D.dim(T.vertical));console.log(`${U}${D.dim(T.vertical)}${K}${D.dim(T.vertical)}`)}console.log(D.dim(` ${T.bottomLeft}${Q.map((B)=>T.horizontal.repeat(B)).join(T.teeUp)}${T.bottomRight}`))}function r1($,J){let Q=T0($);if(Q.length>=J)return`${S4($,J-1)}…`;return $+" ".repeat(J-Q.length)}function S4($,J){let Q=0,X=0,Z=/\x1b\[[0-9;]*m/g;while(X<$.length&&Q<J){Z.lastIndex=X;let j=Z.exec($);if(j&&j.index===X)X=Z.lastIndex;else Q++,X++}let B=$.slice(0,X);if($.includes("\x1B[")&&!B.endsWith("\x1B[0m"))return`${B}\x1B[0m`;return B}function T0($){return $.replace(/\x1b\[[0-9;]*m/g,"")}async function O0($){r(),n("Confirm",""),console.log(""),console.log(D.warning(` ${$}`)),console.log(""),console.log(D.dim(" y yes • n no"));let J=await o();return J==="y"||J==="Y"}async function s1($,J){return r(),n("Confirm Action",""),console.log(""),console.log(D.warning(` ${$}`)),console.log(""),await v0(" > ")===J}async function E0($){r(),n("Error",""),console.log(""),console.log(D.error(` ${$}`)),console.log(""),console.log(D.dim(" Press any key to continue...")),await o()}async function a1($){r(),n("Success",""),console.log(""),console.log(D.success(` ${$}`)),console.log(""),console.log(D.dim(" Press any key to continue...")),await o()}function n1($){if($==="timeout")return D.warning("timeout");if($==="?")return D.dim("?");if($>=1e6)return D.highlight(`${($/1e6).toFixed(1)}M`);if($>=1000)return D.highlight(`${($/1000).toFixed(1)}K`);return D.highlight(String($))}function M0($,J=40){if($===void 0||$===null)return D.dim("null");if(Array.isArray($)){if($.length===0)return D.dim("[]");if($.length<=5){let Z=`[${$.map((B)=>i1(B)).join(", ")}]`;if(Z.length>J)return D.dim(`[${$.length} items]`);return D.dim(Z)}return D.dim(`[${$.length} items]`)}if(typeof $==="object"){let X=String($);if(X!=="[object Object]"){if(X.length>J)return D.dim(`${X.slice(0,J-3)}...`);return D.dim(X)}let Z=Object.keys($);if(Z.length===0)try{let B=JSON.stringify($);if(B.length>J)return D.dim(`${B.slice(0,J-3)}...`);return D.dim(B)}catch{return D.dim("{}")}if(Z.length<=5){let j=`{${Z.map((G)=>`${G}: ${i1($[G])}`).join(", ")}}`;if(j.length>J)return D.dim(`{${Z.length} fields}`);return D.dim(j)}return D.dim(`{${Z.length} fields}`)}if(typeof $==="boolean")return $?D.success("true"):D.error("false");if(typeof $==="number")return D.highlight(String($));let Q=String($).replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");if(Q.length>J)return`${Q.slice(0,J-3)}...`;return Q}function i1($){if($===void 0||$===null)return"null";if(Array.isArray($))return`[${$.length}]`;if(typeof $==="object"){let J=String($);if(J!=="[object Object]"){if(J.length>15)return`${J.slice(0,12)}...`;return J}let Q=Object.keys($);if(Q.length===0)try{let X=JSON.stringify($);if(X.length>15)return`${X.slice(0,12)}...`;return X}catch{return"{}"}return`{${Q.length}}`}if(typeof $==="string"){let J=$.replace(/\n/g,"\\n");if(J.length>15)return`"${J.slice(0,12)}..."`;return`"${J}"`}return String($)}function e0($){if(!$)return"";try{return JSON.parse($)}catch{if($==="true")return!0;if($==="false")return!1;if($==="null")return null;let J=Number($);if(!Number.isNaN(J)&&$.trim()!=="")return J;return $}}async function t1($,J,Q){let X=Q.id?String(Q.id):"unknown",Z=0,B={...Q},j={...Q},G=[],U=()=>Object.keys(j).sort((q,H)=>{if(q==="id")return-1;if(H==="id")return 1;return q.localeCompare(H)}),K=(q)=>{for(let H of G){if(H.type==="add"&&H.key===q)return"added";if(H.type==="edit"&&H.key===q)return"edited";if(H.type==="remove"&&H.key===q)return"removed"}return null},W=()=>G.length>0,V=(q=!1)=>{if(q)r();else Y0();let H=process.stdout.rows||24,_=process.stdout.columns||80,z=Math.max(3,H-5),M=G.length,E=M>0?`${M} changes • s save • x discard`:J;n(`Record: ${X}`,E);let A=U(),R=Math.min(Math.max(...A.map((F)=>F.length),8),20),I=_-R-6,O=0;if(Z>=z)O=Z-z+1;let w=Math.min(O+z,A.length);for(let F=O;F<w;F++){let N=A[F];if(!N)continue;let S=j[N],v=F===Z,y=K(N),k=v?D.primary("▸ "):" ",f;if(y==="added")f=D.success(`+ ${N.slice(0,R-2).padEnd(R-2)}`);else if(y==="edited")f=D.warning(`~ ${N.slice(0,R-2).padEnd(R-2)}`);else if(y==="removed")f=D.error(`- ${N.slice(0,R-2).padEnd(R-2)}`);else if(v)f=D.primary.bold(N.slice(0,R).padEnd(R));else f=D.highlight(N.slice(0,R).padEnd(R));let B2=M0(S,I);console.log(`${k}${f} ${B2}`)}let P=A.length>z?`${O+1}-${w}/${A.length} • `:"";console.log(D.dim(` ${P}↑↓ nav • e edit • + add • - del • d delete • b back • q quit`))};V(!0);while(!0){let q=await o(),H=U();if(q==="q"){if(W()){if(!await O0("Discard unsaved changes?")){V();continue}}throw Error("EXIT")}if(q==="b"||q==="\x1B"){if(W()){if(!await O0("Discard unsaved changes?")){V();continue}}return"back"}if(q==="\x1B[A"||q==="k")Z=Math.max(0,Z-1),V();else if(q==="\x1B[B"||q==="j")Z=Math.min(H.length-1,Z+1),V();else if(q==="e"||q==="\r"||q===`
236
+ `){let _=H[Z];if(_&&_!=="id"){let z=j[_],M=await k4(_,z);if(M!==void 0){let E=B[_];if(JSON.stringify(M)!==JSON.stringify(E)){let A=G.findIndex((R)=>R.type==="edit"&&R.key===_);if(A>=0)G.splice(A,1);G.push({type:"edit",key:_,oldValue:E,newValue:M})}else{let A=G.findIndex((R)=>R.type==="edit"&&R.key===_);if(A>=0)G.splice(A,1)}j[_]=M}V()}else if(_==="id")await E0("Cannot edit the id field"),V()}else if(q==="+"||q==="="){let _=await T4();if(_)j[_.key]=_.value,G.push({type:"add",key:_.key,value:_.value});V()}else if(q==="-"||q==="_"){let _=H[Z];if(_&&_!=="id"){if(K(_)==="added"){let M=G.findIndex((E)=>E.type==="add"&&E.key===_);if(M>=0)G.splice(M,1);delete j[_]}else G.push({type:"remove",key:_,oldValue:B[_]}),delete j[_];Z=Math.min(Z,H.length-2),V()}else if(_==="id")await E0("Cannot remove the id field"),V()}else if(q==="u"||q==="U"){let _=G.pop();if(_){if(_.type==="edit")j[_.key]=_.oldValue;else if(_.type==="add")delete j[_.key];else if(_.type==="remove")j[_.key]=_.oldValue}V()}else if(q==="x"||q==="X"){if(W()){if(await O0("Discard all changes?")){G.length=0;for(let z of Object.keys(j))delete j[z];Object.assign(j,B)}V()}}else if(q==="s"||q==="S"){if(W()){if(await O0(`Save ${G.length} change${G.length>1?"s":""}?`))try{let z=[],M=[],E={};for(let R of G)if(R.type==="edit"||R.type==="add"){let I=`p_${R.key.replace(/[^a-zA-Z0-9]/g,"_")}`;z.push(`\`${R.key}\` = $${I}`),E[I]=R.type==="edit"?R.newValue:R.value}else if(R.type==="remove")M.push(`\`${R.key}\``);let A=`UPDATE ${X}`;if(z.length>0)A+=` SET ${z.join(", ")}`;if(M.length>0)A+=` UNSET ${M.join(", ")}`;A+=` TIMEOUT ${$.timeout}s`,await $.db.query(A,E).collect(),G.length=0;for(let R of Object.keys(B))delete B[R];Object.assign(B,j),await a1("Changes saved successfully")}catch(z){await E0(`Failed to save: ${z instanceof Error?z.message:String(z)}`)}V()}}else if(q==="d"||q==="D")if(await s1(`Delete record ${X}? Type "delete" to confirm:`,"delete"))try{return await $.db.query(`DELETE ${X} TIMEOUT ${$.timeout}s`).collect(),"deleted"}catch(z){await E0(`Failed to delete: ${z instanceof Error?z.message:String(z)}`),V()}else V()}}async function k4($,J){let Q=typeof J==="object"?JSON.stringify(J,null,2):String(J??""),X=await k0(Q,{title:`Edit: ${$}`,subtitle:"Arrows to move • Type to edit • Ctrl+S save • Esc cancel"});if(S0(X))return;return e0(X)}async function T4(){let $=await k0("",{title:"Add Field - Enter Name",subtitle:"Type field name • Ctrl+S confirm • Esc cancel"});if(S0($)||!$.trim())return null;let J=await k0("",{title:`Add Field: ${$.trim()}`,subtitle:"Type value (JSON for objects/arrays) • Ctrl+S confirm • Esc cancel"});if(S0(J))return null;return{key:$.trim(),value:e0(J)}}async function e1($,J,Q){let X=0,Z=0,B=[],j=[],G=!0,U=!0,K=Q,W=async()=>{G=!0,V(U),U=!1;let[q]=await $.db.query(`SELECT * FROM \`${J}\` LIMIT ${$.pageSize} START ${X} TIMEOUT ${$.timeout}s`).collect();B=q||[];let H=new Set(["id"]);for(let _ of B)for(let z of Object.keys(_))H.add(z);j=Array.from(H),Z=Math.min(Z,Math.max(0,B.length-1)),G=!1,V()},V=(q=!1)=>{if(q)r();else Y0();let H=process.stdout.rows||24,_=Math.max(3,H-9),z=B.slice(0,_),M=K!==void 0?` (${K} records)`:"",E=Math.floor(X/$.pageSize)+1,A=K!==void 0?Math.ceil(K/$.pageSize):"?";if(n(`Table: ${J}${M}`,`Page ${E}/${A}`),G){console.log(D.dim(" Loading records..."));return}if(B.length===0){console.log(D.dim(" No records found.")),console.log(D.dim(" b back • q quit"));return}let R=process.stdout.columns||80,I=Math.floor(R/j.length)-1,O=j.map((S)=>{let v=S.length;for(let y of z){let k=M0(y[S]);v=Math.max(v,T0(k).length)}return Math.min(v+2,I)}),w=z.map((S,v)=>j.map((y)=>{let k=M0(S[y]);return v===Z?D.primary(T0(k)):k}));o1(j,w,O,Z);let P=X+z.length,F=K!==void 0?`/${K}`:"",N=X+Z+1;console.log(D.dim(` ${N}${F} • ${X+1}-${P} • ↑↓ select • Enter view • ←→ page • b back • q quit`))};await W();while(!0){let q=await o();if(q==="q")throw Error("EXIT");if(q==="b"||q==="\x1B")return;if(q==="\x1B[A"||q==="k"){if(Z>0)Z--,V();else if(X>0)X=Math.max(0,X-$.pageSize),Z=$.pageSize-1,await W()}else if(q==="\x1B[B"||q==="j"){if(Z<B.length-1)Z++,V();else if(K===void 0||X+B.length<K)X+=$.pageSize,Z=0,await W()}else if(q==="\x1B[D"||q==="h"||q==="["){if(X>0)X=Math.max(0,X-$.pageSize),Z=0,await W()}else if(q==="\x1B[C"||q==="l"||q==="]"){if(K===void 0||X+$.pageSize<K)X+=$.pageSize,Z=0,await W()}else if(q==="\r"||q===`
237
+ `){let H=B[Z];if(H)if(await t1($,J,H)==="deleted")await W();else await W()}else if(q==="g")X=0,Z=0,await W();else if(q==="G"&&K!==void 0)X=Math.max(0,Math.floor((K-1)/$.pageSize)*$.pageSize),Z=0,await W()}}async function x4($,J,Q){return $.query(`SELECT count() FROM \`${J}\` GROUP ALL TIMEOUT ${Q}s`).collect().then((X)=>X[0]?.[0]?.count??"timeout").catch(()=>"timeout")}async function C4($,J,Q,X,Z){let B=0,j=async()=>{while(B<J.length){let U=B++,K=J[U];if(!K)continue;K.count=await x4($,K.name,Q),Z()}},G=Array.from({length:Math.min(X,J.length)},()=>j());await Promise.all(G)}async function $2($){let J=0,Q=[],X=[],Z=!0,B="",j=async()=>{Z=!0,G(!0);let[K]=await $.db.query("INFO FOR DB").collect(),W=K;if(!W?.tables)throw Error("Failed to retrieve database info");if(Q=Object.keys(W.tables).sort().map((q)=>({name:q,count:"?"})),X=Q,Z=!1,G(),!$.skipCount)await C4($.db,Q,$.timeout,$.concurrency,G)},G=(K=!1)=>{if(K)r();else Y0();let W=process.stdout.rows||24,V=Math.max(5,W-4),q=B?` ${D.highlight(`[filter: ${B}]`)}`:"";if(n(`Tables${q}`,`${X.length} tables`),Z){console.log(D.dim(" Loading tables..."));return}if(X.length===0){if(B)console.log(D.warning(` No tables matching "${B}"`)),console.log(D.dim(" Press Esc to clear filter"));else console.log(D.warning(" No tables found in database."));return}let H=0;if(J>=V)H=J-V+1;let _=Math.min(H+V,X.length);for(let M=H;M<_;M++){let E=X[M];if(!E)continue;let A=M===J,R=A?D.primary("▸ "):" ",I=A?D.primary.bold(E.name):E.name,O=n1(E.count);console.log(`${R}${I} ${D.dim("(")}${O}${D.dim(")")}`)}let z=X.length>V?`${H+1}-${_}/${X.length} • `:"";console.log(D.dim(` ${z}↑↓ nav • Enter select • / filter • r refresh • q quit`))};if(await j(),X.length===0&&!B){await o();return}let U=()=>{if(B){let K=B.toLowerCase();X=Q.filter((W)=>W.name.toLowerCase().includes(K))}else X=Q;J=Math.min(J,Math.max(0,X.length-1))};while(!0){let K=await o();if(K==="q")throw Error("EXIT");if(K==="\x1B"){if(B)B="",U(),G();else throw Error("EXIT");continue}if(K==="\x1B[A"||K==="k")J=Math.max(0,J-1),G();else if(K==="\x1B[B"||K==="j")J=Math.min(X.length-1,J+1),G();else if(K==="\r"||K===`
238
+ `){let W=X[J];if(W){let V=typeof W.count==="number"?W.count:void 0;await e1($,W.name,V),G(!0)}}else if(K==="g")J=0,G();else if(K==="G")J=X.length-1,G();else if(K==="r"||K==="R")B="",J=0,await j();else if(K==="/")G(),B=await v0(D.highlight(" Filter: ")),U(),G()}}var b4=15,$1=5,Q2=100,Q1=3,J1=5,J2=new y4("view").description("Interactive TUI for browsing database tables and records").option("--url <url>","Database URL").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Authentication level (root, namespace, database)").option("-e, --embedded <mode>","Use embedded mode (memory or file path)").option("--page-size <size>",`Records per page (${$1}-${Q2}, default: auto)`).option("--timeout <seconds>",`Query timeout in seconds (default: ${Q1})`).option("--concurrency <count>",`Max concurrent count queries (default: ${J1})`).option("--no-count","Skip fetching table record counts").action(async($)=>{Y.header("Database Viewer","Interactive table browser");let J=await a(),Q=await i({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:J,skipAutoConfig:!0});if(!Q)return;let X=process.stdout.rows||24,Z=b4;if($.pageSize){let U=Number.parseInt($.pageSize,10);if(!Number.isNaN(U))Z=Math.max($1,Math.min(Q2,U))}else Z=Math.max($1,Math.min(X-10,30));let B=$.timeout?Math.max(1,Number.parseInt($.timeout,10)||Q1):Q1,j=$.concurrency?Math.max(1,Number.parseInt($.concurrency,10)||J1):J1,G={db:Q,pageSize:Z,terminalHeight:X,timeout:B,concurrency:j,skipCount:!$.count};l1(),process.stdout.write(d1);try{await $2(G)}catch(U){if(U instanceof Error&&U.message==="EXIT");else{process.stdout.write(i0),n0(),Y.error(U instanceof Error?U.message:String(U)),await Q.close();return}}process.stdout.write(i0),n0(),await Q.close()});c();import{createRequire as g4}from"node:module";var D0=g4(import.meta.url);function f4(){try{let $=D0.resolve("@unreal-orm/cli/package.json");return D0($).version}catch{try{return D0("../../package.json").version}catch{return"unknown"}}}var X1=f4(),h4="https://registry.npmjs.org";async function m4($,J="latest"){try{let Q=await fetch(`${h4}/${$}`);if(!Q.ok)return null;let X=await Q.json();return X["dist-tags"][J]??X["dist-tags"].latest??null}catch{return null}}async function X2($,J,Q="latest"){let X=await m4($,Q);if(!X)return null;return{current:J,latest:X,isOutdated:X!==J}}function p4(){try{let $=D0.resolve("unreal-orm/package.json",{paths:[process.cwd()]});return D0($).version}catch{return null}}async function Z2(){if(process.env.CI||process.env.UNREAL_SKIP_UPDATE_CHECK)return;try{let[$,J]=await Promise.all([X2("@unreal-orm/cli",X1,"latest"),(async()=>{let X=p4();if(!X)return null;return X2("unreal-orm",X,"latest")})()]),Q=[];if($?.isOutdated)Q.push(` @unreal-orm/cli: ${Y.dim($.current)} → ${Y.theme.success($.latest)}`);if(J?.isOutdated)Q.push(` unreal-orm: ${Y.dim(J.current)} → ${Y.theme.success(J.latest)}`);if(Q.length>0){Y.newline(),Y.warn("\uD83D\uDCE6 Updates available:");for(let X of Q)console.log(X);Y.dim("\n Run `npm update @unreal-orm/cli unreal-orm` to update\n")}}catch{}}z0();var e=new u4().name("unreal").description("UnrealORM CLI for SurrealDB").version(X1).hook("preAction",($,J)=>{let Q=J.getOptionValue("logLevel");if(Q)Z1(Q);L("Debug logging enabled")}).hook("postAction",async()=>{if(!h())await Z2();process.exit(0)});e.addCommand(_1);e.addCommand(N1);e.addCommand(S1);e.addCommand(x1);e.addCommand(f1);e.addCommand(c1);e.addCommand(J2);e.addCommand(p1);e.parse();
package/package.json CHANGED
@@ -1,52 +1,64 @@
1
1
  {
2
- "name": "@unreal-orm/cli",
3
- "version": "1.0.0-alpha.7",
4
- "description": "CLI tools for UnrealORM - schema introspection, diffing, and migrations for SurrealDB",
5
- "type": "module",
6
- "main": "dist/index.js",
7
- "bin": {
8
- "unreal": "dist/index.js"
9
- },
10
- "publishConfig": {
11
- "access": "public",
12
- "tag": "latest"
13
- },
14
- "scripts": {
15
- "build": "bun build ./src/index.ts --outdir ./dist --target node --format esm --packages external --minify",
16
- "prepublishOnly": "bun run build",
17
- "publish:flow": "bun run build && bun publish"
18
- },
19
- "dependencies": {
20
- "@commander-js/extra-typings": "^14.0.0",
21
- "chalk": "^5.6.2",
22
- "commander": "^14.0.2",
23
- "diff": "^8.0.2",
24
- "dotenv": "^17.2.3",
25
- "jiti": "^2.6.1",
26
- "ora": "^9.0.0",
27
- "prompts": "^2.4.2",
28
- "unreal-orm": "1.0.0-alpha.3"
29
- },
30
- "devDependencies": {
31
- "@types/bun": "latest",
32
- "@types/diff": "^8.0.0",
33
- "@types/prompts": "^2.4.9"
34
- },
35
- "peerDependencies": {
36
- "surrealdb": "^2.0.0-alpha.14",
37
- "typescript": "^5"
38
- },
39
- "keywords": ["surrealdb", "orm", "cli", "schema", "migrations", "unreal-orm"],
40
- "author": "Jimpex <contact@jimpex.dev> (https://jimpex.dev)",
41
- "license": "ISC",
42
- "repository": {
43
- "type": "git",
44
- "url": "git+https://github.com/jimpex/unreal-orm.git",
45
- "directory": "packages/unreal-cli"
46
- },
47
- "bugs": {
48
- "url": "https://github.com/jimpex/unreal-orm/issues"
49
- },
50
- "homepage": "https://unreal-orm.jimpex.dev",
51
- "files": ["dist", "package.json", "README.md", "LICENSE"]
52
- }
2
+ "name": "@unreal-orm/cli",
3
+ "version": "1.0.0-alpha.8",
4
+ "description": "CLI tools for UnrealORM - schema introspection, diffing, and migrations for SurrealDB",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "bin": {
8
+ "unreal": "dist/index.js"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public",
12
+ "tag": "latest"
13
+ },
14
+ "dependencies": {
15
+ "@commander-js/extra-typings": "^14.0.0",
16
+ "chalk": "^5.6.2",
17
+ "commander": "^14.0.2",
18
+ "diff": "^8.0.2",
19
+ "dotenv": "^17.2.3",
20
+ "jiti": "^2.6.1",
21
+ "ora": "^9.0.0",
22
+ "prompts": "^2.4.2",
23
+ "unreal-orm": "1.0.0-alpha.8"
24
+ },
25
+ "devDependencies": {
26
+ "@types/bun": "latest",
27
+ "@types/diff": "^8.0.0",
28
+ "@types/prompts": "^2.4.9",
29
+ "@surrealdb/node": "^3.0.1"
30
+ },
31
+ "peerDependencies": {
32
+ "surrealdb": "^2.0.0",
33
+ "typescript": "^5"
34
+ },
35
+ "keywords": [
36
+ "surrealdb",
37
+ "orm",
38
+ "cli",
39
+ "schema",
40
+ "migrations",
41
+ "unreal-orm"
42
+ ],
43
+ "author": "Jimpex <contact@jimpex.dev> (https://jimpex.dev)",
44
+ "license": "ISC",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/jimpex/unreal-orm.git",
48
+ "directory": "packages/unreal-cli"
49
+ },
50
+ "bugs": {
51
+ "url": "https://github.com/jimpex/unreal-orm/issues"
52
+ },
53
+ "homepage": "https://unreal-orm.jimpex.dev",
54
+ "files": [
55
+ "dist",
56
+ "package.json",
57
+ "README.md",
58
+ "LICENSE"
59
+ ],
60
+ "scripts": {
61
+ "build": "bun build ./src/index.ts --outdir ./dist --target node --format esm --packages external --minify",
62
+ "publish:flow": "bun run build && bun publish"
63
+ }
64
+ }