@vaiftech/cli 1.7.3 → 1.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {c,d,e,h,g,f,b,a}from'./chunk-M2UHM7B7.js';import'dotenv/config';import {program}from'commander';import l from'chalk';import C from'fs';import w from'path';import U from'ora';import ze from'readline';var Te=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Le(e,o,t="public"){let i=await fetch(`${Te}/v1/projects/${o}/schema?schema=${t}`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!i.ok){let r=await i.text();throw new Error(`Failed to fetch schema: ${r}`)}return i.json()}async function ie(e){let o=U(),t=b();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;o.start("Loading configuration...");try{r=await a(i);}catch(s){o.fail("Failed to load config"),console.log(l.red(`
2
+ import {c,d,e,h,g,f,b,a}from'./chunk-WYTLXCHQ.js';import'dotenv/config';import {program}from'commander';import l from'chalk';import C from'fs';import w from'path';import U from'ora';import ze from'readline';var Te=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Le(e,o,t="public"){let i=await fetch(`${Te}/v1/projects/${o}/schema?schema=${t}`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!i.ok){let r=await i.text();throw new Error(`Failed to fetch schema: ${r}`)}return i.json()}async function ie(e){let o=U(),t=b();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;o.start("Loading configuration...");try{r=await a(i);}catch(s){o.fail("Failed to load config"),console.log(l.red(`
3
3
  Error: ${s}`)),process.exit(1);}r||(o.fail("No configuration found"),console.log(l.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let c=e.projectId||r.projectId||process.env.VAIF_PROJECT_ID||t.projectId;c||(o.fail("No project ID specified"),console.log(l.yellow(`
4
4
  Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),o.text="Fetching remote schema...";try{let s=e.schema||r.database?.schema||"public",n=await Le(t.token,c,s);o.succeed("Schema fetched successfully");let a=e.output||w.resolve("vaif.schema.json"),d={$schema:"https://vaif.studio/schemas/schema.json",projectId:c,schema:s,pulledAt:new Date().toISOString(),...n};C.writeFileSync(a,JSON.stringify(d,null,2),"utf-8"),console.log(""),console.log(l.green(`Schema saved to: ${a}`)),console.log(""),console.log(l.gray("Schema summary:")),console.log(l.gray(` Tables: ${(n.tables||[]).length}`)),console.log(l.gray(` Enums: ${(n.enums||[]).length}`)),console.log(l.gray(` Functions: ${(n.functions||[]).length}`)),console.log(""),console.log(l.gray("Next steps:")),console.log(l.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(l.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(s){o.fail("Failed to fetch schema"),s instanceof Error&&console.log(l.red(`
5
5
  Error: ${s.message}`)),process.exit(1);}}var ce=process.env.VAIF_API_URL||"https://api.vaif.studio";function Be(e){let o=ze.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{o.question(e,i=>{o.close(),t(i);});})}async function Je(e,o,t){let i=await fetch(`${ce}/v1/projects/${o}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!i.ok){let r=await i.text();throw new Error(`Failed to preview changes: ${r}`)}return i.json()}async function Ke(e,o,t){let i=await fetch(`${ce}/v1/projects/${o}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!i.ok){let r=await i.text();throw new Error(`Failed to apply changes: ${r}`)}return i.json()}function Me(e){if(console.log(""),console.log(l.bold("Schema Changes:")),console.log(""),e.added.length===0&&e.modified.length===0&&e.removed.length===0){console.log(l.gray(" No changes detected. Schema is up to date."));return}if(e.added.length>0){console.log(l.green.bold(" + Added:"));for(let o of e.added)console.log(l.green(` + ${o.type}: ${o.name}`));console.log("");}if(e.modified.length>0){console.log(l.yellow.bold(" ~ Modified:"));for(let o of e.modified){console.log(l.yellow(` ~ ${o.type}: ${o.name}`));for(let t of o.changes)console.log(l.gray(` ${t}`));}console.log("");}if(e.removed.length>0){console.log(l.red.bold(" - Removed:"));for(let o of e.removed)console.log(l.red(` - ${o.type}: ${o.name}`));console.log("");}}async function ae(e){let o=U(),t=b();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;o.start("Loading configuration...");try{r=await a(i);}catch(a){o.fail("Failed to load config"),console.log(l.red(`
@@ -30,4 +30,4 @@ Error: ${c.message}`)),process.exit(1);}}async function Pe(e,o){let t=U(),i=J(),
30
30
  Error: ${s.message}`)),process.exit(1);}}async function xe(e,o){let t=U(),i=J(),r=await K(o.config),c=M(o,r,i);console.log(""),console.log(l.bold("VAIF Delete Secret")),console.log(""),t.start("Finding secret...");try{let s=new URL(`${N}/functions/secrets/project/${c}`);o.envId&&s.searchParams.set("envId",o.envId);let n=await fetch(s.toString(),{headers:{Authorization:`Bearer ${i.token}`}});if(!n.ok)throw new Error(`Failed to fetch secrets: ${await n.text()}`);let d=(await n.json()).find(f=>f.key===e);d||(t.fail(`Secret "${e}" not found`),process.exit(1)),t.text=`Deleting secret "${e}"...`;let p=await fetch(`${N}/functions/secrets/${d.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${i.token}`}});if(!p.ok)throw new Error(`Failed to delete secret: ${await p.text()}`);t.succeed(`Deleted secret "${e}"`),console.log("");}catch(s){t.fail("Failed to delete secret"),s instanceof Error&&console.log(l.red(`
31
31
  Error: ${s.message}`)),process.exit(1);}}var Fe=process.env.VAIF_API_URL||"https://api.vaif.studio";function oo(e){try{let o=new URL(e);return o.password&&(o.password="****"),o.toString()}catch{return e.replace(/:[^@/]+@/,":****@")}}async function ke(e){let o=U(),t=b();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let c=e.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;c||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),o.start("Fetching project info...");try{let s=await fetch(`${Fe}/v1/projects/${c}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok){let p=await s.text();throw new Error(`Failed to fetch project: ${p}`)}let n=await s.json();o.stop(),console.log(""),console.log(l.bold("VAIF Project Info")),console.log("");let a=16,d=(p,f)=>{console.log(` ${l.gray(p.padEnd(a))} ${f}`);};d("Name:",l.white(n.name||"N/A")),d("Project ID:",l.white(c)),d("Region:",l.white(n.region||"us-east-1")),d("Plan:",l.white(n.plan||n.tier||"free")),d("Created:",l.white(n.createdAt?new Date(n.createdAt).toLocaleDateString():"N/A")),console.log(""),d("API URL:",l.cyan(n.apiUrl||`${Fe}/v1`)),d("WS URL:",l.cyan(n.wsUrl||n.realtimeUrl||"N/A")),d("DB URL:",l.cyan(n.databaseUrl?oo(n.databaseUrl):"N/A")),d("Storage URL:",l.cyan(n.storageUrl||"N/A")),console.log("");}catch(s){o.fail("Failed to fetch project info"),s instanceof Error&&console.log(l.red(`
32
32
  Error: ${s.message}`)),process.exit(1);}}var no=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Ce(e){let o=U(),t=b();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let c=e.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;c||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),o.start("Fetching project status...");try{let s=await fetch(`${no}/v1/projects/${c}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok){let y=await s.text();throw new Error(`Failed to fetch project status: ${y}`)}let n=await s.json();o.stop(),console.log(""),console.log(l.bold("VAIF Project Status")),console.log("");let a=22,d=(y,D)=>{console.log(` ${l.gray(y.padEnd(a))} ${D}`);};d("Project:",l.white(n.name||c)),d("Plan:",l.white(n.plan||n.tier||"free")),console.log(""),console.log(l.gray(" --- Resources ---")),console.log("");let p=n.tableCount??n.tables?.length??"N/A",f=n.functionCount??n.functions?.length??"N/A",g=n.bucketCount??n.storage?.buckets?.length??"N/A",h=n.activeConnections??n.connections??"N/A";d("Tables:",l.white(String(p))),d("Functions:",l.white(String(f))),d("Storage Buckets:",l.white(String(g))),d("Active Connections:",l.white(String(h))),n.usage&&(console.log(""),console.log(l.gray(" --- Usage ---")),console.log(""),n.usage.dbSize&&d("Database Size:",l.white(n.usage.dbSize)),n.usage.storageSize&&d("Storage Size:",l.white(n.usage.storageSize)),n.usage.bandwidth&&d("Bandwidth:",l.white(n.usage.bandwidth)),n.usage.functionInvocations!=null&&d("Function Invocations:",l.white(String(n.usage.functionInvocations)))),console.log("");}catch(s){o.fail("Failed to fetch project status"),s instanceof Error&&console.log(l.red(`
33
- Error: ${s.message}`)),process.exit(1);}}var De="1.7.3",Q=l.hex("#00f0ff"),Y=l.hex("#7b61ff"),H=l.hex("#ff3dff"),X=l.hex("#00ff9d"),j=l.hex("#555570"),O=l.hex("#00f0ff");function so(){console.log(""),console.log(Q(" \u2566 \u2566")+Y("\u2554\u2550\u2557\u2566")+H("\u2554\u2550\u2557 ")+X("\u2554\u2550\u2557\u2566 \u2566")),console.log(Q(" \u255A\u2557\u2554\u255D")+Y("\u2560\u2550\u2563\u2551")+H("\u2560\u2563 ")+X("\u2551 \u2551 \u2551")),console.log(Q(" \u255A\u255D ")+Y("\u2569 \u2569\u2569")+H("\u255A ")+X("\u255A\u2550\u255D\u2569\u2550\u255D\u2569")),console.log(""),console.log(j(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(O(" VAIF Studio CLI")+j(` v${De}`)),console.log(j(" Build full-stack apps at lightning speed")),console.log(j(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(""),console.log(l.bold(" Quick Start")),console.log(j(" $ ")+O("vaif login")+j(" Authenticate")),console.log(j(" $ ")+O("vaif init -t react-spa")+j(" Scaffold project")),console.log(j(" $ ")+O("vaif db push")+j(" Push migrations")),console.log(j(" $ ")+O("vaif generate")+j(" Generate types")),console.log(j(" $ ")+O("vaif functions deploy")+j(" Deploy functions")),console.log(""),console.log(l.bold(" Categories")),console.log(j(" auth ")+l.white("login, logout, whoami")),console.log(j(" project ")+l.white("init, templates, info, status")),console.log(j(" schema ")+l.white("pull, push, generate")),console.log(j(" database ")+l.white("db push, db pull, db seed, db reset")),console.log(j(" deploy ")+l.white("functions deploy, functions list")),console.log(j(" security ")+l.white("keys, secrets")),console.log(""),console.log(j(" Run ")+O("vaif <command> --help")+j(" for details")),console.log(j(" Docs: ")+l.underline("https://docs.vaif.studio")),console.log("");}program.name("vaif").description("VAIF CLI - Type generation and development tools").version(De);program.command("login").description("Authenticate with VAIF (opens browser)").option("-e, --email","Login with email/password instead of browser").option("-p, --project-id <id>","Default project ID").action(c);program.command("logout").description("Log out and remove stored credentials").action(d);program.command("whoami").description("Show current authenticated user").action(e);program.command("init").description("Initialize VAIF configuration in your project").option("--typescript","Setup for TypeScript project").option("-f, --force","Overwrite existing config").option("-t, --template <name>","Scaffold from a template (run vaif templates for list)").option("--features <features>","Comma-separated features to include: auth,database,realtime,storage,functions").option("--add-features <features>","Add features to an existing project (requires --template)").action(h);program.command("templates").alias("tpl").description("List available project templates").action(g);program.command("info").description("Show project information (name, region, URLs)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(ke);program.command("status").description("Show project status (tables, functions, storage, connections)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(Ce);program.command("pull").description("Pull database schema from your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-o, --output <path>","Output file path","vaif.schema.json").option("-s, --schema <name>","Schema name","public").option("-p, --project-id <id>","Project ID (overrides config)").action(ie);program.command("push").description("Push local schema changes to your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-s, --schema <path>","Schema file path","vaif.schema.json").option("-p, --project-id <id>","Project ID (overrides config)").option("--dry-run","Preview changes without applying").option("-f, --force","Apply changes without confirmation").action(ae);program.command("generate").alias("gen").description("Generate TypeScript types from your database schema").option("-c, --connection <url>","Database connection string").option("-o, --output <path>","Output file path","./src/types/database.ts").option("--schema <name>","Schema name","public").option("--config <path>","Config file path","vaif.config.json").option("--dry-run","Preview generated types without writing").action(f);var Ee=program.command("functions").alias("fn").description("Manage serverless functions");Ee.command("deploy").description("Deploy functions to your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID").option("-n, --name <name>","Function name filter").option("-r, --runtime <runtime>","Runtime (nodejs, typescript, python)").option("--entrypoint <file>","Specific entrypoint file").option("--dry-run","Preview deployment without deploying").action(de);Ee.command("list").alias("ls").description("List deployed functions").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID").action(pe);var q=program.command("db").description("Database management commands");q.command("push").description("Push local Drizzle migrations to VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-d, --dir <path>","Migrations directory","./drizzle").option("--dry-run","Preview without applying").action(he);q.command("pull").description("Pull schema from VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-o, --output <path>","Output file","vaif.schema.json").action(ye);q.command("seed").description("Seed your database with test data").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --file <path>","Specific seed file").option("-t, --table <name>","Seed specific table only").option("--truncate","Truncate tables before seeding").option("--dry-run","Preview seeding without inserting data").action(me);q.command("reset").description("Reset database (drop all tables and data)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --force","Confirm reset (required)").action(we);var Re=program.command("keys").description("Manage API keys");Re.command("generate").description("Generate a new API key").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-n, --name <name>","Key name").action($e);Re.command("list").alias("ls").description("List API keys").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(be);var W=program.command("secrets").alias("sec").description("Manage function secrets");W.command("set <name> [value]").description("Create or update a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").option("--from-file <path>","Read secret value from a file").action(Se);W.command("list").alias("ls").description("List all secrets (names only)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Ae);W.command("get <name>").description("Reveal a secret value").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Pe);W.command("delete <name>").description("Delete a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(xe);process.argv.slice(2).length||(so(),process.exit(0));program.parse(process.argv);
33
+ Error: ${s.message}`)),process.exit(1);}}var De="1.7.5",Q=l.hex("#00f0ff"),Y=l.hex("#7b61ff"),H=l.hex("#ff3dff"),X=l.hex("#00ff9d"),j=l.hex("#555570"),O=l.hex("#00f0ff");function so(){console.log(""),console.log(Q(" \u2566 \u2566")+Y("\u2554\u2550\u2557\u2566")+H("\u2554\u2550\u2557 ")+X("\u2554\u2550\u2557\u2566 \u2566")),console.log(Q(" \u255A\u2557\u2554\u255D")+Y("\u2560\u2550\u2563\u2551")+H("\u2560\u2563 ")+X("\u2551 \u2551 \u2551")),console.log(Q(" \u255A\u255D ")+Y("\u2569 \u2569\u2569")+H("\u255A ")+X("\u255A\u2550\u255D\u2569\u2550\u255D\u2569")),console.log(""),console.log(j(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(O(" VAIF Studio CLI")+j(` v${De}`)),console.log(j(" Build full-stack apps at lightning speed")),console.log(j(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(""),console.log(l.bold(" Quick Start")),console.log(j(" $ ")+O("vaif login")+j(" Authenticate")),console.log(j(" $ ")+O("vaif init -t react-spa")+j(" Scaffold project")),console.log(j(" $ ")+O("vaif db push")+j(" Push migrations")),console.log(j(" $ ")+O("vaif generate")+j(" Generate types")),console.log(j(" $ ")+O("vaif functions deploy")+j(" Deploy functions")),console.log(""),console.log(l.bold(" Categories")),console.log(j(" auth ")+l.white("login, logout, whoami")),console.log(j(" project ")+l.white("init, templates, info, status")),console.log(j(" schema ")+l.white("pull, push, generate")),console.log(j(" database ")+l.white("db push, db pull, db seed, db reset")),console.log(j(" deploy ")+l.white("functions deploy, functions list")),console.log(j(" security ")+l.white("keys, secrets")),console.log(""),console.log(j(" Run ")+O("vaif <command> --help")+j(" for details")),console.log(j(" Docs: ")+l.underline("https://docs.vaif.studio")),console.log("");}program.name("vaif").description("VAIF CLI - Type generation and development tools").version(De);program.command("login").description("Authenticate with VAIF (opens browser)").option("-e, --email","Login with email/password instead of browser").option("-p, --project-id <id>","Default project ID").action(c);program.command("logout").description("Log out and remove stored credentials").action(d);program.command("whoami").description("Show current authenticated user").action(e);program.command("init").description("Initialize VAIF configuration in your project").option("--typescript","Setup for TypeScript project").option("-f, --force","Overwrite existing config").option("-t, --template <name>","Scaffold from a template (run vaif templates for list)").option("--features <features>","Comma-separated features to include: auth,database,realtime,storage,functions").option("--add-features <features>","Add features to an existing project (requires --template)").action(h);program.command("templates").alias("tpl").description("List available project templates").action(g);program.command("info").description("Show project information (name, region, URLs)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(ke);program.command("status").description("Show project status (tables, functions, storage, connections)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(Ce);program.command("pull").description("Pull database schema from your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-o, --output <path>","Output file path","vaif.schema.json").option("-s, --schema <name>","Schema name","public").option("-p, --project-id <id>","Project ID (overrides config)").action(ie);program.command("push").description("Push local schema changes to your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-s, --schema <path>","Schema file path","vaif.schema.json").option("-p, --project-id <id>","Project ID (overrides config)").option("--dry-run","Preview changes without applying").option("-f, --force","Apply changes without confirmation").action(ae);program.command("generate").alias("gen").description("Generate TypeScript types from your database schema").option("-c, --connection <url>","Database connection string").option("-o, --output <path>","Output file path","./src/types/database.ts").option("--schema <name>","Schema name","public").option("--config <path>","Config file path","vaif.config.json").option("--dry-run","Preview generated types without writing").action(f);var Ee=program.command("functions").alias("fn").description("Manage serverless functions");Ee.command("deploy").description("Deploy functions to your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID").option("-n, --name <name>","Function name filter").option("-r, --runtime <runtime>","Runtime (nodejs, typescript, python)").option("--entrypoint <file>","Specific entrypoint file").option("--dry-run","Preview deployment without deploying").action(de);Ee.command("list").alias("ls").description("List deployed functions").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID").action(pe);var q=program.command("db").description("Database management commands");q.command("push").description("Push local Drizzle migrations to VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-d, --dir <path>","Migrations directory","./drizzle").option("--dry-run","Preview without applying").action(he);q.command("pull").description("Pull schema from VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-o, --output <path>","Output file","vaif.schema.json").action(ye);q.command("seed").description("Seed your database with test data").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --file <path>","Specific seed file").option("-t, --table <name>","Seed specific table only").option("--truncate","Truncate tables before seeding").option("--dry-run","Preview seeding without inserting data").action(me);q.command("reset").description("Reset database (drop all tables and data)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --force","Confirm reset (required)").action(we);var Re=program.command("keys").description("Manage API keys");Re.command("generate").description("Generate a new API key").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-n, --name <name>","Key name").action($e);Re.command("list").alias("ls").description("List API keys").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(be);var W=program.command("secrets").alias("sec").description("Manage function secrets");W.command("set <name> [value]").description("Create or update a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").option("--from-file <path>","Read secret value from a file").action(Se);W.command("list").alias("ls").description("List all secrets (names only)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Ae);W.command("get <name>").description("Reveal a secret value").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Pe);W.command("delete <name>").description("Delete a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(xe);process.argv.slice(2).length||(so(),process.exit(0));program.parse(process.argv);
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';var v=require('fs'),w=require('path'),q=require('dotenv'),G=require('pg'),H=require('ora'),p=require('chalk'),W=require('prettier'),B=require('os'),K=require('readline');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var v__default=/*#__PURE__*/_interopDefault(v);var w__default=/*#__PURE__*/_interopDefault(w);var q__default=/*#__PURE__*/_interopDefault(q);var G__default=/*#__PURE__*/_interopDefault(G);var H__default=/*#__PURE__*/_interopDefault(H);var p__default=/*#__PURE__*/_interopDefault(p);var W__default=/*#__PURE__*/_interopDefault(W);var B__default=/*#__PURE__*/_interopDefault(B);var K__default=/*#__PURE__*/_interopDefault(K);q__default.default.config();async function E(i){let a=w__default.default.resolve(i);if(!v__default.default.existsSync(a))return null;try{let t=v__default.default.readFileSync(a,"utf-8"),e=JSON.parse(t);return e.database?.url&&(e.database.url=V(e.database.url)),e.api?.apiKey&&(e.api.apiKey=V(e.api.apiKey)),e}catch{throw new Error(`Failed to parse config file: ${i}`)}}function V(i){return i.replace(/\$\{([^}]+)\}/g,(a,t)=>process.env[t]||a)}var Y=w__default.default.join(B__default.default.homedir(),".vaif"),k=w__default.default.join(Y,"auth.json");process.env.VAIF_API_URL||"https://api.vaif.studio";function O(){if(!v__default.default.existsSync(k))return null;try{let i=v__default.default.readFileSync(k,"utf-8");return JSON.parse(i)}catch{return null}}var J=process.env.VAIF_API_URL||"https://api.vaif.studio";async function X(i,a){let t=await fetch(`${J}/schema-engine/introspect/${a}`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});if(!t.ok){let l=await t.text();throw new Error(`API introspection failed: ${l}`)}let e=await t.json();if(!e.ok||!e.schemaExists)throw new Error("Project schema does not exist yet. Push a migration first with `vaif db push`.");let r=new Map,o=[];for(let l of e.tables){let c=l.columns.map(n=>({column_name:n.name,data_type:n.type,is_nullable:n.nullable?"YES":"NO",column_default:n.default,udt_name:n.type,is_identity:n.primaryKey&&n.default?.includes("gen_random_uuid")?"YES":"NO",character_maximum_length:null,numeric_precision:null,numeric_scale:null}));r.set(l.name,c);for(let n of l.foreignKeys)o.push({constraint_name:n.constraintName,table_name:l.name,column_name:n.columnName,foreign_table_name:n.refTable,foreign_column_name:n.refColumn});}return {tables:r,enums:new Map,foreignKeys:o}}async function Q(i,a){let t=await i.query(`
1
+ 'use strict';var y=require('fs'),w=require('path'),B=require('dotenv'),G=require('pg'),H=require('ora'),d=require('chalk'),W=require('prettier'),q=require('os'),K=require('readline');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var y__default=/*#__PURE__*/_interopDefault(y);var w__default=/*#__PURE__*/_interopDefault(w);var B__default=/*#__PURE__*/_interopDefault(B);var G__default=/*#__PURE__*/_interopDefault(G);var H__default=/*#__PURE__*/_interopDefault(H);var d__default=/*#__PURE__*/_interopDefault(d);var W__default=/*#__PURE__*/_interopDefault(W);var q__default=/*#__PURE__*/_interopDefault(q);var K__default=/*#__PURE__*/_interopDefault(K);B__default.default.config();async function E(i){let a=w__default.default.resolve(i);if(!y__default.default.existsSync(a))return null;try{let t=y__default.default.readFileSync(a,"utf-8"),e=JSON.parse(t);return e.database?.url&&(e.database.url=V(e.database.url)),e.api?.apiKey&&(e.api.apiKey=V(e.api.apiKey)),e}catch{throw new Error(`Failed to parse config file: ${i}`)}}function V(i){return i.replace(/\$\{([^}]+)\}/g,(a,t)=>process.env[t]||a)}var Y=w__default.default.join(q__default.default.homedir(),".vaif"),k=w__default.default.join(Y,"auth.json");process.env.VAIF_API_URL||"https://api.vaif.studio";function O(){if(!y__default.default.existsSync(k))return null;try{let i=y__default.default.readFileSync(k,"utf-8");return JSON.parse(i)}catch{return null}}var J=process.env.VAIF_API_URL||"https://api.vaif.studio";async function X(i,a){let t=await fetch(`${J}/schema-engine/introspect/${a}`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});if(!t.ok){let l=await t.text();throw new Error(`API introspection failed: ${l}`)}let e=await t.json();if(!e.ok||!e.schemaExists)throw new Error("Project schema does not exist yet. Push a migration first with `vaif db push`.");let r=new Map,o=[];for(let l of e.tables){let c=l.columns.map(n=>({column_name:n.name,data_type:n.type,is_nullable:n.nullable?"YES":"NO",column_default:n.default,udt_name:n.type,is_identity:n.primaryKey&&n.default?.includes("gen_random_uuid")?"YES":"NO",character_maximum_length:null,numeric_precision:null,numeric_scale:null}));r.set(l.name,c);for(let n of l.foreignKeys)o.push({constraint_name:n.constraintName,table_name:l.name,column_name:n.columnName,foreign_table_name:n.refTable,foreign_column_name:n.refColumn});}return {tables:r,enums:new Map,foreignKeys:o}}async function Q(i,a){let t=await i.query(`
2
2
  SELECT table_name, table_type
3
3
  FROM information_schema.tables
4
4
  WHERE table_schema = $1
@@ -44,9 +44,9 @@
44
44
  JOIN pg_namespace n ON n.oid = t.typnamespace
45
45
  WHERE n.nspname = $1
46
46
  ORDER BY t.typname, e.enumsortorder
47
- `,[a]),u=new Map;for(let c of t.rows)u.set(c.table_name,[]);for(let c of e.rows){let n=u.get(c.table_name);n&&n.push(c);}let l=new Map;for(let c of o.rows){let n=l.get(c.enum_name)||[];n.push(c.enum_value),l.set(c.enum_name,n);}return {tables:u,enums:l,foreignKeys:r.rows}}var S={smallint:"number",integer:"number",bigint:"string",int2:"number",int4:"number",int8:"string",decimal:"string",numeric:"string",real:"number",float4:"number",float8:"number","double precision":"number",money:"string",boolean:"boolean",bool:"boolean",text:"string",varchar:"string",char:"string",character:"string","character varying":"string",name:"string",citext:"string",date:"string",time:"string",timetz:"string","time without time zone":"string","time with time zone":"string",timestamp:"string",timestamptz:"string","timestamp without time zone":"string","timestamp with time zone":"string",interval:"string",bytea:"Buffer",uuid:"string",json:"unknown",jsonb:"unknown",inet:"string",cidr:"string",macaddr:"string",macaddr8:"string",point:"{ x: number; y: number }",line:"string",lseg:"string",box:"string",path:"string",polygon:"string",circle:"string",ARRAY:"unknown[]"};function Z(i,a){let{data_type:t,udt_name:e,is_nullable:r}=i;if(a.has(e)){let l=a.get(e).map(c=>`"${c}"`).join(" | ");return r==="YES"?`(${l}) | null`:l}if(t==="ARRAY"){let u=e.replace(/^_/,"");if(a.has(u)){let n=a.get(u).map(s=>`"${s}"`).join(" | ");return r==="YES"?`(${n})[] | null`:`(${n})[]`}let l=S[u]||"unknown";return r==="YES"?`${l}[] | null`:`${l}[]`}let o=S[t]||S[e]||"unknown";return r==="YES"&&(o=`${o} | null`),o}function x(i){return i.split(/[_\-\s]+/).map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join("")}function ee(i,a){let t=x(i),e=a.map(r=>` | "${r}"`).join(`
47
+ `,[a]),u=new Map;for(let c of t.rows)u.set(c.table_name,[]);for(let c of e.rows){let n=u.get(c.table_name);n&&n.push(c);}let l=new Map;for(let c of o.rows){let n=l.get(c.enum_name)||[];n.push(c.enum_value),l.set(c.enum_name,n);}return {tables:u,enums:l,foreignKeys:r.rows}}var x={smallint:"number",integer:"number",bigint:"string",int2:"number",int4:"number",int8:"string",decimal:"string",numeric:"string",real:"number",float4:"number",float8:"number","double precision":"number",money:"string",boolean:"boolean",bool:"boolean",text:"string",varchar:"string",char:"string",character:"string","character varying":"string",name:"string",citext:"string",date:"string",time:"string",timetz:"string","time without time zone":"string","time with time zone":"string",timestamp:"string",timestamptz:"string","timestamp without time zone":"string","timestamp with time zone":"string",interval:"string",bytea:"Buffer",uuid:"string",json:"unknown",jsonb:"unknown",inet:"string",cidr:"string",macaddr:"string",macaddr8:"string",point:"{ x: number; y: number }",line:"string",lseg:"string",box:"string",path:"string",polygon:"string",circle:"string",ARRAY:"unknown[]"};function Z(i,a){let{data_type:t,udt_name:e,is_nullable:r}=i;if(a.has(e)){let l=a.get(e).map(c=>`"${c}"`).join(" | ");return r==="YES"?`(${l}) | null`:l}if(t==="ARRAY"){let u=e.replace(/^_/,"");if(a.has(u)){let n=a.get(u).map(s=>`"${s}"`).join(" | ");return r==="YES"?`(${n})[] | null`:`(${n})[]`}let l=x[u]||"unknown";return r==="YES"?`${l}[] | null`:`${l}[]`}let o=x[t]||x[e]||"unknown";return r==="YES"&&(o=`${o} | null`),o}function S(i){return i.split(/[_\-\s]+/).map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join("")}function ee(i,a){let t=S(i),e=a.map(r=>` | "${r}"`).join(`
48
48
  `);return `export type ${t} =
49
- ${e};`}function te(i,a,t){let e=x(i),r=[],o=[],u=[];for(let s of a){let m=Z(s,t),d=s.column_name,g=s.column_default!==null||s.is_identity==="YES",y=s.is_nullable==="YES";r.push(` ${d}: ${m};`),g||s.column_name==="id"?o.push(` ${d}?: ${m.replace(" | null","")} | null;`):y?o.push(` ${d}?: ${m};`):o.push(` ${d}: ${m.replace(" | null","")};`),u.push(` ${d}?: ${m.replace(" | null","")} | null;`);}let l=`export interface ${e} {
49
+ ${e};`}function te(i,a,t){let e=S(i),r=[],o=[],u=[];for(let s of a){let m=Z(s,t),p=s.column_name,g=s.column_default!==null||s.is_identity==="YES",v=s.is_nullable==="YES";r.push(` ${p}: ${m};`),g||s.column_name==="id"?o.push(` ${p}?: ${m.replace(" | null","")} | null;`):v?o.push(` ${p}?: ${m};`):o.push(` ${p}: ${m.replace(" | null","")};`),u.push(` ${p}?: ${m.replace(" | null","")} | null;`);}let l=`export interface ${e} {
50
50
  ${r.join(`
51
51
  `)}
52
52
  }`,c=`export interface ${e}Insert {
@@ -55,12 +55,12 @@ ${o.join(`
55
55
  }`,n=`export interface ${e}Update {
56
56
  ${u.join(`
57
57
  `)}
58
- }`;return {base:l,insert:c,update:n}}function ae(i,a,t){let e=["/**"," * Auto-generated TypeScript types from database schema"," * Generated by @vaiftech/cli",` * Generated at: ${new Date().toISOString()}`," * "," * DO NOT EDIT MANUALLY - changes will be overwritten"," */",""];if(a.size>0){e.push("// ============ ENUMS ============"),e.push("");for(let[o,u]of a)e.push(ee(o,u)),e.push("");}e.push("// ============ TABLES ============"),e.push("");let r=[];for(let[o,u]of i){let{base:l,insert:c,update:n}=te(o,u,a);r.push(o),e.push(l),e.push(""),e.push(c),e.push(""),e.push(n),e.push("");}e.push("// ============ DATABASE SCHEMA ============"),e.push(""),e.push("export interface Database {");for(let o of r){let u=x(o);e.push(` ${o}: {`),e.push(` Row: ${u};`),e.push(` Insert: ${u}Insert;`),e.push(` Update: ${u}Update;`),e.push(" };");}return e.push("}"),e.push(""),e.push("export type TableName = keyof Database;"),e.push(""),e.push("// ============ HELPER TYPES ============"),e.push(""),e.push('export type Row<T extends TableName> = Database[T]["Row"];'),e.push('export type Insert<T extends TableName> = Database[T]["Insert"];'),e.push('export type Update<T extends TableName> = Database[T]["Update"];'),e.push(""),e.join(`
59
- `)}async function ne(i){let a=H__default.default("Loading configuration...").start();try{let t=await E(i.config),e=i.connection||t?.database?.url||process.env.DATABASE_URL,r=e&&!e.includes("${"),o,u,l;if(r){a.text="Connecting to database...";let d=new G__default.default.Client({connectionString:e});await d.connect(),a.text="Introspecting schema...",{tables:o,enums:u,foreignKeys:l}=await Q(d,i.schema),await d.end();}else {let d=O();(!d||!d.token)&&(a.fail("No database connection and not logged in"),console.log(p__default.default.yellow(`
60
- Either:`)),console.log(p__default.default.gray(" 1. Run `vaif login` to authenticate (no DATABASE_URL needed)")),console.log(p__default.default.gray(" 2. Set DATABASE_URL in your .env file")),console.log(p__default.default.gray(" 3. Pass --connection postgresql://user:pass@host:5432/db")),process.exit(1));let g=t?.projectId||process.env.VAIF_PROJECT_ID||d.projectId;g||(a.fail("No project ID specified"),console.log(p__default.default.yellow(`
61
- Set projectId in vaif.config.json or use VAIF_PROJECT_ID env var.`)),process.exit(1)),a.text="Introspecting schema via API...",{tables:o,enums:u,foreignKeys:l}=await X(d.token,g);}if(o.size===0){a.warn("No tables found"),console.log(p__default.default.yellow(`
62
- Push a migration first: vaif db push`));return}a.text=`Generating types for ${o.size} tables...`;let c=ae(o,u,l),n=await W__default.default.format(c,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100});if(i.dryRun){a.succeed("Generated types (dry run):"),console.log(""),console.log(p__default.default.gray("\u2500".repeat(60))),console.log(n),console.log(p__default.default.gray("\u2500".repeat(60)));return}let s=w__default.default.resolve(i.output),m=w__default.default.dirname(s);v__default.default.existsSync(m)||v__default.default.mkdirSync(m,{recursive:!0}),v__default.default.writeFileSync(s,n,"utf-8"),a.succeed(`Generated types for ${o.size} tables \u2192 ${p__default.default.cyan(i.output)}`),console.log(""),console.log(p__default.default.green("Generated:")),console.log(p__default.default.gray(` Tables: ${o.size}`)),console.log(p__default.default.gray(` Enums: ${u.size}`)),console.log(""),console.log(p__default.default.gray("Import in your code:")),console.log(p__default.default.cyan(` import type { Database, Row, Insert, Update } from "${i.output.replace(/\.ts$/,"")}";`));}catch(t){a.fail("Failed to generate types"),t instanceof Error&&(console.error(p__default.default.red(`
63
- Error: ${t.message}`)),t.message.includes("ECONNREFUSED")&&console.log(p__default.default.yellow(`
58
+ }`;return {base:l,insert:c,update:n}}function ae(i,a,t){let e=["/**"," * Auto-generated TypeScript types from database schema"," * Generated by @vaiftech/cli",` * Generated at: ${new Date().toISOString()}`," * "," * DO NOT EDIT MANUALLY - changes will be overwritten"," */",""];if(a.size>0){e.push("// ============ ENUMS ============"),e.push("");for(let[o,u]of a)e.push(ee(o,u)),e.push("");}e.push("// ============ TABLES ============"),e.push("");let r=[];for(let[o,u]of i){let{base:l,insert:c,update:n}=te(o,u,a);r.push(o),e.push(l),e.push(""),e.push(c),e.push(""),e.push(n),e.push("");}e.push("// ============ DATABASE SCHEMA ============"),e.push(""),e.push("export interface Database {");for(let o of r){let u=S(o);e.push(` ${o}: {`),e.push(` Row: ${u};`),e.push(` Insert: ${u}Insert;`),e.push(` Update: ${u}Update;`),e.push(" };");}return e.push("}"),e.push(""),e.push("export type TableName = keyof Database;"),e.push(""),e.push("// ============ HELPER TYPES ============"),e.push(""),e.push('export type Row<T extends TableName> = Database[T]["Row"];'),e.push('export type Insert<T extends TableName> = Database[T]["Insert"];'),e.push('export type Update<T extends TableName> = Database[T]["Update"];'),e.push(""),e.join(`
59
+ `)}async function ne(i){let a=H__default.default("Loading configuration...").start();try{let t=await E(i.config),e=i.connection||t?.database?.url||process.env.DATABASE_URL,r=e&&!e.includes("${"),o,u,l;if(r){a.text="Connecting to database...";let p=new G__default.default.Client({connectionString:e});await p.connect(),a.text="Introspecting schema...",{tables:o,enums:u,foreignKeys:l}=await Q(p,i.schema),await p.end();}else {let p=O();(!p||!p.token)&&(a.fail("No database connection and not logged in"),console.log(d__default.default.yellow(`
60
+ Either:`)),console.log(d__default.default.gray(" 1. Run `vaif login` to authenticate (no DATABASE_URL needed)")),console.log(d__default.default.gray(" 2. Set DATABASE_URL in your .env file")),console.log(d__default.default.gray(" 3. Pass --connection postgresql://user:pass@host:5432/db")),process.exit(1));let g=t?.projectId||process.env.VAIF_PROJECT_ID||p.projectId;g||(a.fail("No project ID specified"),console.log(d__default.default.yellow(`
61
+ Set projectId in vaif.config.json or use VAIF_PROJECT_ID env var.`)),process.exit(1)),a.text="Introspecting schema via API...",{tables:o,enums:u,foreignKeys:l}=await X(p.token,g);}if(o.size===0){a.warn("No tables found"),console.log(d__default.default.yellow(`
62
+ Push a migration first: vaif db push`));return}a.text=`Generating types for ${o.size} tables...`;let c=ae(o,u,l),n=await W__default.default.format(c,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100});if(i.dryRun){a.succeed("Generated types (dry run):"),console.log(""),console.log(d__default.default.gray("\u2500".repeat(60))),console.log(n),console.log(d__default.default.gray("\u2500".repeat(60)));return}let s=w__default.default.resolve(i.output),m=w__default.default.dirname(s);y__default.default.existsSync(m)||y__default.default.mkdirSync(m,{recursive:!0}),y__default.default.writeFileSync(s,n,"utf-8"),a.succeed(`Generated types for ${o.size} tables \u2192 ${d__default.default.cyan(i.output)}`),console.log(""),console.log(d__default.default.green("Generated:")),console.log(d__default.default.gray(` Tables: ${o.size}`)),console.log(d__default.default.gray(` Enums: ${u.size}`)),console.log(""),console.log(d__default.default.gray("Import in your code:")),console.log(d__default.default.cyan(` import type { Database, Row, Insert, Update } from "${i.output.replace(/\.ts$/,"")}";`));}catch(t){a.fail("Failed to generate types"),t instanceof Error&&(console.error(d__default.default.red(`
63
+ Error: ${t.message}`)),t.message.includes("ECONNREFUSED")&&console.log(d__default.default.yellow(`
64
64
  Make sure your database is running and accessible.`))),process.exit(1);}}var b=[{name:"database",label:"Database",description:"CRUD queries, type-safe operations"},{name:"auth",label:"Authentication",description:"login, signup, OAuth, sessions"},{name:"realtime",label:"Realtime",description:"live subscriptions, presence"},{name:"storage",label:"Storage",description:"file uploads, signed URLs"},{name:"functions",label:"Functions",description:"serverless function calls"}],ie={"nextjs-fullstack":{name:"Next.js Full-Stack",description:"Next.js app with server/client VAIF client, auth middleware, and React hooks",tag:"Next.js",defaultFeatures:["database","auth"],files:[{path:"package.json",content:`{
65
65
  "name": "my-vaif-app",
66
66
  "private": true,
@@ -278,7 +278,21 @@ A full-stack Next.js application powered by [VAIF Studio](https://vaif.studio),
278
278
  ## Documentation
279
279
 
280
280
  Full documentation is available at <https://docs.vaif.studio>.
281
- `}],featureFiles:{auth:[{path:"middleware.ts",content:`import { NextResponse, type NextRequest } from "next/server";
281
+ `}],featureFiles:{auth:[{path:"app/page.tsx",content:`import Link from "next/link";
282
+
283
+ export default function Home() {
284
+ return (
285
+ <main style={{ maxWidth: 600, margin: "80px auto", textAlign: "center" }}>
286
+ <h1>Welcome to VAIF</h1>
287
+ <p>Your Next.js app is ready. Start building!</p>
288
+ <p style={{ marginTop: 24 }}>
289
+ <Link href="/login" style={{ marginRight: 16 }}>Log in</Link>
290
+ <Link href="/signup">Sign up</Link>
291
+ </p>
292
+ </main>
293
+ );
294
+ }
295
+ `},{path:"middleware.ts",content:`import { NextResponse, type NextRequest } from "next/server";
282
296
  import { createVaifClient } from "@vaiftech/client";
283
297
  import { authMiddleware } from "@vaiftech/auth/nextjs";
284
298
 
@@ -325,12 +339,12 @@ export default function LoginPage() {
325
339
  setLoading(true);
326
340
  setError(null);
327
341
 
328
- const { error } = await vaif.auth.signInWithPassword({ email, password });
329
- if (error) {
330
- setError(error.message);
331
- setLoading(false);
332
- } else {
342
+ try {
343
+ await vaif.auth.login(email, password);
333
344
  router.push("/dashboard");
345
+ } catch (err: any) {
346
+ setError(err.message || "Login failed");
347
+ setLoading(false);
334
348
  }
335
349
  }
336
350
 
@@ -372,12 +386,12 @@ export default function SignupPage() {
372
386
  setLoading(true);
373
387
  setError(null);
374
388
 
375
- const { error } = await vaif.auth.signUp({ email, password });
376
- if (error) {
377
- setError(error.message);
378
- setLoading(false);
379
- } else {
389
+ try {
390
+ await vaif.auth.signUp(email, password);
380
391
  router.push("/");
392
+ } catch (err: any) {
393
+ setError(err.message || "Sign up failed");
394
+ setLoading(false);
381
395
  }
382
396
  }
383
397
 
@@ -768,7 +782,33 @@ A single-page React application built with [Vite](https://vite.dev/) and powered
768
782
  ## Documentation
769
783
 
770
784
  Full documentation is available at <https://docs.vaif.studio>.
771
- `}],featureFiles:{auth:[{path:"src/pages/Login.tsx",content:`import { useState } from "react";
785
+ `}],featureFiles:{auth:[{path:"src/App.tsx",content:`import { Routes, Route, Link } from "react-router-dom";
786
+ import Login from "./pages/Login";
787
+ import Signup from "./pages/Signup";
788
+
789
+ export default function App() {
790
+ return (
791
+ <Routes>
792
+ <Route path="/" element={<Home />} />
793
+ <Route path="/login" element={<Login />} />
794
+ <Route path="/signup" element={<Signup />} />
795
+ </Routes>
796
+ );
797
+ }
798
+
799
+ function Home() {
800
+ return (
801
+ <div style={{ maxWidth: 600, margin: "80px auto", textAlign: "center" }}>
802
+ <h1>Welcome to VAIF</h1>
803
+ <p>Your app is ready. Start building!</p>
804
+ <p style={{ marginTop: 24 }}>
805
+ <Link to="/login" style={{ marginRight: 16 }}>Log in</Link>
806
+ <Link to="/signup">Sign up</Link>
807
+ </p>
808
+ </div>
809
+ );
810
+ }
811
+ `},{path:"src/pages/Login.tsx",content:`import { useState } from "react";
772
812
  import { useNavigate } from "react-router-dom";
773
813
  import { vaif } from "../lib/vaif";
774
814
 
@@ -784,12 +824,12 @@ export default function Login() {
784
824
  setLoading(true);
785
825
  setError(null);
786
826
 
787
- const { error } = await vaif.auth.signInWithPassword({ email, password });
788
- if (error) {
789
- setError(error.message);
790
- setLoading(false);
791
- } else {
827
+ try {
828
+ await vaif.auth.login(email, password);
792
829
  navigate("/");
830
+ } catch (err: any) {
831
+ setError(err.message || "Login failed");
832
+ setLoading(false);
793
833
  }
794
834
  }
795
835
 
@@ -829,12 +869,12 @@ export default function Signup() {
829
869
  setLoading(true);
830
870
  setError(null);
831
871
 
832
- const { error } = await vaif.auth.signUp({ email, password });
833
- if (error) {
834
- setError(error.message);
835
- setLoading(false);
836
- } else {
872
+ try {
873
+ await vaif.auth.signUp(email, password);
837
874
  navigate("/");
875
+ } catch (err: any) {
876
+ setError(err.message || "Sign up failed");
877
+ setLoading(false);
838
878
  }
839
879
  }
840
880
 
@@ -873,21 +913,15 @@ export function AuthGuard({ children, fallback }: AuthGuardProps) {
873
913
  const [authenticated, setAuthenticated] = useState(false);
874
914
 
875
915
  useEffect(() => {
876
- vaif.auth.getSession().then(({ data }) => {
877
- if (data.session) {
916
+ vaif.auth.getUser()
917
+ .then(() => {
878
918
  setAuthenticated(true);
879
- } else {
919
+ setLoading(false);
920
+ })
921
+ .catch(() => {
880
922
  navigate("/login");
881
- }
882
- setLoading(false);
883
- });
884
-
885
- const { data: { subscription } } = vaif.auth.onAuthStateChange((_event, session) => {
886
- setAuthenticated(!!session);
887
- if (!session) navigate("/login");
888
- });
889
-
890
- return () => subscription.unsubscribe();
923
+ setLoading(false);
924
+ });
891
925
  }, [navigate]);
892
926
 
893
927
  if (loading) return fallback ?? <div>Loading...</div>;
@@ -1435,7 +1469,39 @@ A React Native / Expo mobile application powered by [VAIF Studio](https://vaif.s
1435
1469
  ## Documentation
1436
1470
 
1437
1471
  Full documentation is available at <https://docs.vaif.studio>.
1438
- `}],featureFiles:{auth:[{path:"app/(auth)/login.tsx",content:`import { useState } from "react";
1472
+ `}],featureFiles:{auth:[{path:"app/index.tsx",content:`import { View, Text, StyleSheet, TouchableOpacity } from "react-native";
1473
+ import { useRouter } from "expo-router";
1474
+
1475
+ export default function HomeScreen() {
1476
+ const router = useRouter();
1477
+
1478
+ return (
1479
+ <View style={styles.container}>
1480
+ <Text style={styles.title}>Welcome to VAIF</Text>
1481
+ <Text style={styles.subtitle}>Your mobile app is ready. Start building!</Text>
1482
+ <View style={styles.buttons}>
1483
+ <TouchableOpacity style={styles.button} onPress={() => router.push("/(auth)/login")}>
1484
+ <Text style={styles.buttonText}>Log In</Text>
1485
+ </TouchableOpacity>
1486
+ <TouchableOpacity style={[styles.button, styles.secondaryButton]} onPress={() => router.push("/(auth)/signup")}>
1487
+ <Text style={[styles.buttonText, styles.secondaryText]}>Sign Up</Text>
1488
+ </TouchableOpacity>
1489
+ </View>
1490
+ </View>
1491
+ );
1492
+ }
1493
+
1494
+ const styles = StyleSheet.create({
1495
+ container: { flex: 1, alignItems: "center", justifyContent: "center", padding: 24 },
1496
+ title: { fontSize: 28, fontWeight: "bold", marginBottom: 8 },
1497
+ subtitle: { fontSize: 16, color: "#666", textAlign: "center", marginBottom: 32 },
1498
+ buttons: { gap: 12, width: "100%" },
1499
+ button: { backgroundColor: "#0070f3", borderRadius: 8, padding: 14, alignItems: "center" },
1500
+ secondaryButton: { backgroundColor: "transparent", borderWidth: 1, borderColor: "#0070f3" },
1501
+ buttonText: { color: "#fff", fontSize: 16, fontWeight: "600" },
1502
+ secondaryText: { color: "#0070f3" },
1503
+ });
1504
+ `},{path:"app/(auth)/login.tsx",content:`import { useState } from "react";
1439
1505
  import { View, Text, TextInput, TouchableOpacity, StyleSheet, Alert } from "react-native";
1440
1506
  import { useRouter } from "expo-router";
1441
1507
  import { vaif } from "../../lib/vaif";
@@ -1448,10 +1514,14 @@ export default function LoginScreen() {
1448
1514
 
1449
1515
  async function handleLogin() {
1450
1516
  setLoading(true);
1451
- const { error } = await vaif.auth.signInWithPassword({ email, password });
1452
- setLoading(false);
1453
- if (error) Alert.alert("Error", error.message);
1454
- else router.replace("/");
1517
+ try {
1518
+ await vaif.auth.login(email, password);
1519
+ router.replace("/");
1520
+ } catch (err: any) {
1521
+ Alert.alert("Error", err.message || "Login failed");
1522
+ } finally {
1523
+ setLoading(false);
1524
+ }
1455
1525
  }
1456
1526
 
1457
1527
  return (
@@ -1486,10 +1556,14 @@ export default function SignupScreen() {
1486
1556
 
1487
1557
  async function handleSignup() {
1488
1558
  setLoading(true);
1489
- const { error } = await vaif.auth.signUp({ email, password });
1490
- setLoading(false);
1491
- if (error) Alert.alert("Error", error.message);
1492
- else router.replace("/");
1559
+ try {
1560
+ await vaif.auth.signUp(email, password);
1561
+ router.replace("/");
1562
+ } catch (err: any) {
1563
+ Alert.alert("Error", err.message || "Sign up failed");
1564
+ } finally {
1565
+ setLoading(false);
1566
+ }
1493
1567
  }
1494
1568
 
1495
1569
  return (
@@ -1836,7 +1910,7 @@ class _LoginScreenState extends State<LoginScreen> {
1836
1910
  setState(() { _loading = true; _error = null; });
1837
1911
 
1838
1912
  try {
1839
- await vaif.auth.signInWithPassword(
1913
+ await vaif.auth.login(
1840
1914
  email: _emailController.text,
1841
1915
  password: _passwordController.text,
1842
1916
  );
@@ -3674,18 +3748,18 @@ export const posts = pgTable("posts", {
3674
3748
 
3675
3749
  return Response.json({ message: \`Hello, \${name}!\` });
3676
3750
  }
3677
- `}]},dependencies:["@vaiftech/client","@vaiftech/auth"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create a 'product-images' storage bucket in your VAIF dashboard","Import storage helpers from '@/lib/storage' in your API routes","Use uploadProductImage() in your product creation flow","Run: npx vaif generate to generate TypeScript types"]}};async function oe(i){if(!process.stdin.isTTY||!process.stdout.isTTY)return i;let a=new Set(i.map(e=>b.findIndex(r=>r.name===e)).filter(e=>e>=0)),t=0;return new Promise(e=>{let r=K__default.default.createInterface({input:process.stdin,output:process.stdout});K__default.default.emitKeypressEvents(process.stdin,r),process.stdin.setRawMode&&process.stdin.setRawMode(true);function o(){let l=b.length+2;process.stdout.write(`\x1B[${l}A`),u();}function u(){console.log(p__default.default.bold(`
3678
- ? Which VAIF features do you want to include?`)),b.forEach((l,c)=>{let n=a.has(c)?p__default.default.green("[x]"):"[ ]",s=c===t?p__default.default.cyan("> "):" ";console.log(`${s}${n} ${l.label} ${p__default.default.gray(`(${l.description})`)}`);}),console.log(p__default.default.gray(" (up/down to move, space to toggle, enter to confirm)"));}u(),process.stdin.on("keypress",(l,c)=>{if(c.name==="up"&&t>0)t--,o();else if(c.name==="down"&&t<b.length-1)t++,o();else if(c.name==="space")a.has(t)?a.delete(t):a.add(t),o();else if(c.name==="return"){process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close();let n=[...a].sort().map(s=>b[s].name);e(n.length>0?n:i);}else c.name==="c"&&c.ctrl&&(process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close(),process.exit(0));});})}async function F(i,a={}){let t=ie[i];t||(console.log(p__default.default.red(`
3679
- Unknown template: ${i}`)),console.log(p__default.default.yellow(`Run 'vaif templates' to see available templates.
3680
- `)),process.exit(1));let e;a.features&&a.features.length>0?e=a.features.filter(n=>b.some(s=>s.name===n)):a.addOnly?(console.log(p__default.default.red(`
3681
- No features specified.`)),console.log(p__default.default.yellow("Usage: vaif init --template <name> --add-features <features>")),console.log(p__default.default.gray("Available features: auth, database, realtime, storage, functions")),process.exit(1)):t.featureFiles&&Object.keys(t.featureFiles).length>0?e=await oe(t.defaultFeatures??["database","auth"]):e=t.defaultFeatures??[],a.addOnly?(console.log(""),console.log(p__default.default.bold(`Adding features to ${p__default.default.cyan(t.name)} project...`)),console.log(p__default.default.gray(` Features: ${e.join(", ")}`)),console.log("")):(console.log(""),console.log(p__default.default.bold(`Scaffolding ${p__default.default.cyan(t.name)} template...`)),e.length>0&&console.log(p__default.default.gray(` Features: ${e.join(", ")}`)),console.log(""));let r=a.addOnly?[]:[...t.files];if(t.featureFiles)for(let n of e){let s=t.featureFiles[n];s&&r.push(...s);}let o=0,u=0;for(let n of r){let s=w__default.default.resolve(n.path),m=w__default.default.dirname(s);if(v__default.default.existsSync(m)||v__default.default.mkdirSync(m,{recursive:true}),n.path==="package.json"&&v__default.default.existsSync(s)&&!a.force)try{let d=JSON.parse(v__default.default.readFileSync(s,"utf-8")),g=JSON.parse(n.content),y=N=>{if(!N)return {};let L={};for(let[z,_]of Object.entries(N))!_.startsWith("workspace:")&&!_.startsWith("link:")&&!_.startsWith("file:")&&(L[z]=_);return L};d.dependencies={...y(d.dependencies),...g.dependencies||{}},d.devDependencies={...y(d.devDependencies),...g.devDependencies||{}},g.scripts&&(d.scripts={...d.scripts||{},...g.scripts}),v__default.default.writeFileSync(s,JSON.stringify(d,null,2)+`
3682
- `,"utf-8"),console.log(p__default.default.green(` merge ${n.path} (added dependencies)`)),o++;continue}catch{}if(v__default.default.existsSync(s)&&!a.force){console.log(p__default.default.yellow(` skip ${n.path} (already exists)`)),u++;continue}v__default.default.writeFileSync(s,n.content,"utf-8"),console.log(p__default.default.green(` create ${n.path}`)),o++;}console.log(""),o>0&&console.log(p__default.default.green(`Created ${o} file${o!==1?"s":""}.`)),u>0&&console.log(p__default.default.yellow(`Skipped ${u} file${u!==1?"s":""} (use --force to overwrite).`));let l={auth:{"@vaiftech/auth":"^1.0.0"},database:{},realtime:{},storage:{},functions:{}},c=w__default.default.resolve("package.json");if(v__default.default.existsSync(c)&&e.length>0)try{let n=JSON.parse(v__default.default.readFileSync(c,"utf-8")),s=!1;for(let m of e){let d=l[m];if(d)for(let[g,y]of Object.entries(d))n.dependencies?.[g]||(n.dependencies=n.dependencies||{},n.dependencies[g]=y,s=!0);}s&&v__default.default.writeFileSync(c,JSON.stringify(n,null,2)+`
3683
- `,"utf-8");}catch{}(t.dependencies?.length||t.devDependencies?.length)&&(console.log(""),console.log(p__default.default.bold("Install dependencies:")),t.dependencies?.length&&console.log(p__default.default.cyan(` npm install ${t.dependencies.join(" ")}`)),t.devDependencies?.length&&console.log(p__default.default.cyan(` npm install -D ${t.devDependencies.join(" ")}`))),console.log(""),console.log(p__default.default.bold.green("Project scaffolded successfully!")),console.log(""),console.log(p__default.default.bold(" Next steps:")),t.postInstructions.forEach(n=>{console.log(p__default.default.gray(` ${n}`));}),console.log(""),console.log(p__default.default.gray(" Get your project credentials at https://vaif.studio/app/security/api-keys")),console.log("");}var se={$schema:"https://vaif.studio/schemas/config.json",projectId:"",database:{url:"${DATABASE_URL}",schema:"public"},types:{output:"./src/types/database.ts"},api:{baseUrl:"https://api.vaif.studio"}};async function le(i){if(i.addFeatures){i.template||(console.log(p__default.default.red(`
3684
- --add-features requires --template to know which template to use.`)),console.log(p__default.default.gray("Example: vaif init --template react-spa --add-features functions,storage")),process.exit(1));let e=i.addFeatures.split(",").map(r=>r.trim());await F(i.template,{force:i.force,features:e,addOnly:true});return}let a=H__default.default("Initializing VAIF configuration...").start(),t=w__default.default.resolve("vaif.config.json");v__default.default.existsSync(t)&&!i.force&&(a.fail("vaif.config.json already exists"),console.log(p__default.default.yellow(`
3685
- Use --force to overwrite existing configuration.`)),process.exit(1));try{if(v__default.default.writeFileSync(t,JSON.stringify(se,null,2),"utf-8"),a.succeed("Created vaif.config.json"),i.template){let e=i.features?i.features.split(",").map(r=>r.trim()):void 0;await F(i.template,{force:i.force,features:e});}else {let e=w__default.default.resolve(".env.example");if(v__default.default.existsSync(e)||(v__default.default.writeFileSync(e,`# VAIF Configuration
3751
+ `}]},dependencies:["@vaiftech/client","@vaiftech/auth"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create a 'product-images' storage bucket in your VAIF dashboard","Import storage helpers from '@/lib/storage' in your API routes","Use uploadProductImage() in your product creation flow","Run: npx vaif generate to generate TypeScript types"]}};async function oe(i){if(!process.stdin.isTTY||!process.stdout.isTTY)return i;let a=new Set(i.map(e=>b.findIndex(r=>r.name===e)).filter(e=>e>=0)),t=0;return new Promise(e=>{let r=K__default.default.createInterface({input:process.stdin,output:process.stdout});K__default.default.emitKeypressEvents(process.stdin,r),process.stdin.setRawMode&&process.stdin.setRawMode(true);function o(){let l=b.length+2;process.stdout.write(`\x1B[${l}A`),u();}function u(){console.log(d__default.default.bold(`
3752
+ ? Which VAIF features do you want to include?`)),b.forEach((l,c)=>{let n=a.has(c)?d__default.default.green("[x]"):"[ ]",s=c===t?d__default.default.cyan("> "):" ";console.log(`${s}${n} ${l.label} ${d__default.default.gray(`(${l.description})`)}`);}),console.log(d__default.default.gray(" (up/down to move, space to toggle, enter to confirm)"));}u(),process.stdin.on("keypress",(l,c)=>{if(c.name==="up"&&t>0)t--,o();else if(c.name==="down"&&t<b.length-1)t++,o();else if(c.name==="space")a.has(t)?a.delete(t):a.add(t),o();else if(c.name==="return"){process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close();let n=[...a].sort().map(s=>b[s].name);e(n.length>0?n:i);}else c.name==="c"&&c.ctrl&&(process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close(),process.exit(0));});})}async function F(i,a={}){let t=ie[i];t||(console.log(d__default.default.red(`
3753
+ Unknown template: ${i}`)),console.log(d__default.default.yellow(`Run 'vaif templates' to see available templates.
3754
+ `)),process.exit(1));let e;a.features&&a.features.length>0?e=a.features.filter(n=>b.some(s=>s.name===n)):a.addOnly?(console.log(d__default.default.red(`
3755
+ No features specified.`)),console.log(d__default.default.yellow("Usage: vaif init --template <name> --add-features <features>")),console.log(d__default.default.gray("Available features: auth, database, realtime, storage, functions")),process.exit(1)):t.featureFiles&&Object.keys(t.featureFiles).length>0?e=await oe(t.defaultFeatures??["database","auth"]):e=t.defaultFeatures??[],a.addOnly?(console.log(""),console.log(d__default.default.bold(`Adding features to ${d__default.default.cyan(t.name)} project...`)),console.log(d__default.default.gray(` Features: ${e.join(", ")}`)),console.log("")):(console.log(""),console.log(d__default.default.bold(`Scaffolding ${d__default.default.cyan(t.name)} template...`)),e.length>0&&console.log(d__default.default.gray(` Features: ${e.join(", ")}`)),console.log(""));let r=a.addOnly?[]:[...t.files];if(t.featureFiles)for(let n of e){let s=t.featureFiles[n];s&&r.push(...s);}let o=0,u=0;for(let n of r){let s=w__default.default.resolve(n.path),m=w__default.default.dirname(s);if(y__default.default.existsSync(m)||y__default.default.mkdirSync(m,{recursive:true}),n.path==="package.json"&&y__default.default.existsSync(s)&&!a.force)try{let p=JSON.parse(y__default.default.readFileSync(s,"utf-8")),g=JSON.parse(n.content),v=L=>{if(!L)return {};let N={};for(let[z,_]of Object.entries(L))!_.startsWith("workspace:")&&!_.startsWith("link:")&&!_.startsWith("file:")&&(N[z]=_);return N};p.dependencies={...v(p.dependencies),...g.dependencies||{}},p.devDependencies={...v(p.devDependencies),...g.devDependencies||{}},g.scripts&&(p.scripts={...p.scripts||{},...g.scripts}),y__default.default.writeFileSync(s,JSON.stringify(p,null,2)+`
3756
+ `,"utf-8"),console.log(d__default.default.green(` merge ${n.path} (added dependencies)`)),o++;continue}catch{}if(y__default.default.existsSync(s)&&!a.force){console.log(d__default.default.yellow(` skip ${n.path} (already exists)`)),u++;continue}y__default.default.writeFileSync(s,n.content,"utf-8"),console.log(d__default.default.green(` create ${n.path}`)),o++;}console.log(""),o>0&&console.log(d__default.default.green(`Created ${o} file${o!==1?"s":""}.`)),u>0&&console.log(d__default.default.yellow(`Skipped ${u} file${u!==1?"s":""} (use --force to overwrite).`));let l={auth:{"@vaiftech/auth":"^1.0.0"},database:{},realtime:{},storage:{},functions:{}},c=w__default.default.resolve("package.json");if(y__default.default.existsSync(c)&&e.length>0)try{let n=JSON.parse(y__default.default.readFileSync(c,"utf-8")),s=!1;for(let m of e){let p=l[m];if(p)for(let[g,v]of Object.entries(p))n.dependencies?.[g]||(n.dependencies=n.dependencies||{},n.dependencies[g]=v,s=!0);}s&&y__default.default.writeFileSync(c,JSON.stringify(n,null,2)+`
3757
+ `,"utf-8");}catch{}(t.dependencies?.length||t.devDependencies?.length)&&(console.log(""),console.log(d__default.default.bold("Install dependencies:")),t.dependencies?.length&&console.log(d__default.default.cyan(` npm install ${t.dependencies.join(" ")}`)),t.devDependencies?.length&&console.log(d__default.default.cyan(` npm install -D ${t.devDependencies.join(" ")}`))),console.log(""),console.log(d__default.default.bold.green("Project scaffolded successfully!")),console.log(""),console.log(d__default.default.bold(" Next steps:")),t.postInstructions.forEach(n=>{console.log(d__default.default.gray(` ${n}`));}),console.log(""),console.log(d__default.default.gray(" Get your project credentials at https://vaif.studio/app/security/api-keys")),console.log("");}var se={$schema:"https://vaif.studio/schemas/config.json",projectId:"",database:{url:"${DATABASE_URL}",schema:"public"},types:{output:"./src/types/database.ts"},api:{baseUrl:"https://api.vaif.studio"}};async function le(i){if(i.addFeatures){i.template||(console.log(d__default.default.red(`
3758
+ --add-features requires --template to know which template to use.`)),console.log(d__default.default.gray("Example: vaif init --template react-spa --add-features functions,storage")),process.exit(1));let e=i.addFeatures.split(",").map(r=>r.trim());await F(i.template,{force:i.force,features:e,addOnly:true});return}let a=H__default.default("Initializing VAIF configuration...").start(),t=w__default.default.resolve("vaif.config.json");y__default.default.existsSync(t)&&!i.force&&(a.fail("vaif.config.json already exists"),console.log(d__default.default.yellow(`
3759
+ Use --force to overwrite existing configuration.`)),process.exit(1));try{if(y__default.default.writeFileSync(t,JSON.stringify(se,null,2),"utf-8"),a.succeed("Created vaif.config.json"),i.template){let e=i.features?i.features.split(",").map(r=>r.trim()):void 0;await F(i.template,{force:i.force,features:e});}else {let e=w__default.default.resolve(".env.example");if(y__default.default.existsSync(e)||(y__default.default.writeFileSync(e,`# VAIF Configuration
3686
3760
  DATABASE_URL=postgresql://user:password@localhost:5432/database
3687
3761
  VAIF_API_KEY=your-api-key
3688
- `,"utf-8"),console.log(p__default.default.gray("Created .env.example"))),i.typescript){let r=w__default.default.resolve("src/types");v__default.default.existsSync(r)||(v__default.default.mkdirSync(r,{recursive:!0}),console.log(p__default.default.gray("Created src/types directory")));}console.log(""),console.log(p__default.default.green("VAIF initialized successfully!")),console.log(""),console.log(p__default.default.gray("Next steps:")),console.log(p__default.default.gray(" 1. Update vaif.config.json with your project ID")),console.log(p__default.default.gray(" 2. Set DATABASE_URL in your environment")),console.log(p__default.default.gray(" 3. Run: npx vaif generate")),console.log("");}}catch(e){a.fail("Failed to initialize"),e instanceof Error&&console.error(p__default.default.red(`
3762
+ `,"utf-8"),console.log(d__default.default.gray("Created .env.example"))),i.typescript){let r=w__default.default.resolve("src/types");y__default.default.existsSync(r)||(y__default.default.mkdirSync(r,{recursive:!0}),console.log(d__default.default.gray("Created src/types directory")));}console.log(""),console.log(d__default.default.green("VAIF initialized successfully!")),console.log(""),console.log(d__default.default.gray("Next steps:")),console.log(d__default.default.gray(" 1. Update vaif.config.json with your project ID")),console.log(d__default.default.gray(" 2. Set DATABASE_URL in your environment")),console.log(d__default.default.gray(" 3. Run: npx vaif generate")),console.log("");}}catch(e){a.fail("Failed to initialize"),e instanceof Error&&console.error(d__default.default.red(`
3689
3763
  Error: ${e.message}`)),process.exit(1);}}async function Ze(i){let{connectionString:a,schema:t="public"}=i,e=new G__default.default.Client({connectionString:a});await e.connect();try{let r=await e.query(`
3690
3764
  SELECT table_name, table_type
3691
3765
  FROM information_schema.tables
@@ -3716,9 +3790,9 @@ Error: ${e.message}`)),process.exit(1);}}async function Ze(i){let{connectionStri
3716
3790
  JOIN pg_namespace n ON n.oid = t.typnamespace
3717
3791
  WHERE n.nspname = $1
3718
3792
  ORDER BY t.typname, e.enumsortorder
3719
- `,[t]),l=new Map;for(let s of r.rows)l.set(s.table_name,[]);for(let s of o.rows){let m=l.get(s.table_name);m&&m.push(s);}let c=new Map;for(let s of u.rows){let m=c.get(s.enum_name)||[];m.push(s.enum_value),c.set(s.enum_name,m);}let n=pe(l,c);return W__default.default.format(n,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100})}finally{await e.end();}}var R={smallint:"number",integer:"number",bigint:"string",int2:"number",int4:"number",int8:"string",decimal:"string",numeric:"string",real:"number",float4:"number",float8:"number","double precision":"number",money:"string",boolean:"boolean",bool:"boolean",text:"string",varchar:"string",char:"string",character:"string","character varying":"string",name:"string",citext:"string",date:"string",time:"string",timetz:"string",timestamp:"string",timestamptz:"string","timestamp without time zone":"string","timestamp with time zone":"string",interval:"string",bytea:"Buffer",uuid:"string",json:"unknown",jsonb:"unknown",inet:"string",cidr:"string",macaddr:"string",point:"{ x: number; y: number }",ARRAY:"unknown[]"};function de(i,a){let{data_type:t,udt_name:e,is_nullable:r}=i;if(a.has(e)){let l=a.get(e).map(c=>`"${c}"`).join(" | ");return r==="YES"?`(${l}) | null`:l}if(t==="ARRAY"){let u=e.replace(/^_/,"");if(a.has(u)){let n=a.get(u).map(s=>`"${s}"`).join(" | ");return r==="YES"?`(${n})[] | null`:`(${n})[]`}let l=R[u]||"unknown";return r==="YES"?`${l}[] | null`:`${l}[]`}let o=R[t]||R[e]||"unknown";return r==="YES"&&(o=`${o} | null`),o}function C(i){return i.split(/[_\-\s]+/).map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join("")}function pe(i,a){let t=["/**"," * Auto-generated TypeScript types from database schema"," * Generated by @vaiftech/cli",` * Generated at: ${new Date().toISOString()}`," * "," * DO NOT EDIT MANUALLY - changes will be overwritten"," */",""];if(a.size>0){t.push("// ============ ENUMS ============"),t.push("");for(let[r,o]of a){let u=C(r),l=o.map(c=>` | "${c}"`).join(`
3793
+ `,[t]),l=new Map;for(let s of r.rows)l.set(s.table_name,[]);for(let s of o.rows){let m=l.get(s.table_name);m&&m.push(s);}let c=new Map;for(let s of u.rows){let m=c.get(s.enum_name)||[];m.push(s.enum_value),c.set(s.enum_name,m);}let n=de(l,c);return W__default.default.format(n,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100})}finally{await e.end();}}var R={smallint:"number",integer:"number",bigint:"string",int2:"number",int4:"number",int8:"string",decimal:"string",numeric:"string",real:"number",float4:"number",float8:"number","double precision":"number",money:"string",boolean:"boolean",bool:"boolean",text:"string",varchar:"string",char:"string",character:"string","character varying":"string",name:"string",citext:"string",date:"string",time:"string",timetz:"string",timestamp:"string",timestamptz:"string","timestamp without time zone":"string","timestamp with time zone":"string",interval:"string",bytea:"Buffer",uuid:"string",json:"unknown",jsonb:"unknown",inet:"string",cidr:"string",macaddr:"string",point:"{ x: number; y: number }",ARRAY:"unknown[]"};function pe(i,a){let{data_type:t,udt_name:e,is_nullable:r}=i;if(a.has(e)){let l=a.get(e).map(c=>`"${c}"`).join(" | ");return r==="YES"?`(${l}) | null`:l}if(t==="ARRAY"){let u=e.replace(/^_/,"");if(a.has(u)){let n=a.get(u).map(s=>`"${s}"`).join(" | ");return r==="YES"?`(${n})[] | null`:`(${n})[]`}let l=R[u]||"unknown";return r==="YES"?`${l}[] | null`:`${l}[]`}let o=R[t]||R[e]||"unknown";return r==="YES"&&(o=`${o} | null`),o}function C(i){return i.split(/[_\-\s]+/).map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join("")}function de(i,a){let t=["/**"," * Auto-generated TypeScript types from database schema"," * Generated by @vaiftech/cli",` * Generated at: ${new Date().toISOString()}`," * "," * DO NOT EDIT MANUALLY - changes will be overwritten"," */",""];if(a.size>0){t.push("// ============ ENUMS ============"),t.push("");for(let[r,o]of a){let u=C(r),l=o.map(c=>` | "${c}"`).join(`
3720
3794
  `);t.push(`export type ${u} =
3721
- ${l};`),t.push("");}}t.push("// ============ TABLES ============"),t.push("");let e=[];for(let[r,o]of i){e.push(r);let u=C(r),l=[],c=[],n=[];for(let s of o){let m=de(s,a),d=s.column_name,g=s.column_default!==null||s.is_identity==="YES",y=s.is_nullable==="YES";l.push(` ${d}: ${m};`),g||s.column_name==="id"?c.push(` ${d}?: ${m.replace(" | null","")} | null;`):y?c.push(` ${d}?: ${m};`):c.push(` ${d}: ${m.replace(" | null","")};`),n.push(` ${d}?: ${m.replace(" | null","")} | null;`);}t.push(`export interface ${u} {
3795
+ ${l};`),t.push("");}}t.push("// ============ TABLES ============"),t.push("");let e=[];for(let[r,o]of i){e.push(r);let u=C(r),l=[],c=[],n=[];for(let s of o){let m=pe(s,a),p=s.column_name,g=s.column_default!==null||s.is_identity==="YES",v=s.is_nullable==="YES";l.push(` ${p}: ${m};`),g||s.column_name==="id"?c.push(` ${p}?: ${m.replace(" | null","")} | null;`):v?c.push(` ${p}?: ${m};`):c.push(` ${p}: ${m.replace(" | null","")};`),n.push(` ${p}?: ${m.replace(" | null","")} | null;`);}t.push(`export interface ${u} {
3722
3796
  ${l.join(`
3723
3797
  `)}
3724
3798
  }`),t.push(""),t.push(`export interface ${u}Insert {
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export{f as generateTypes,h as initConfig,a as loadConfig}from'./chunk-M2UHM7B7.js';import T from'pg';import $ from'prettier';async function S(p){let{connectionString:a,schema:e="public"}=p,r=new T.Client({connectionString:a});await r.connect();try{let t=await r.query(`
1
+ export{f as generateTypes,h as initConfig,a as loadConfig}from'./chunk-WYTLXCHQ.js';import T from'pg';import $ from'prettier';async function S(p){let{connectionString:a,schema:e="public"}=p,r=new T.Client({connectionString:a});await r.connect();try{let t=await r.query(`
2
2
  SELECT table_name, table_type
3
3
  FROM information_schema.tables
4
4
  WHERE table_schema = $1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vaiftech/cli",
3
- "version": "1.7.3",
3
+ "version": "1.7.5",
4
4
  "description": "VAIF CLI - Type generation and development tools",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",