@vaiftech/cli 1.0.5 → 1.1.0

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 (3) hide show
  1. package/dist/cli.cjs +47 -39
  2. package/dist/cli.js +27 -19
  3. package/package.json +1 -1
package/dist/cli.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';var commander=require('commander'),A=require('fs'),b=require('path'),he=require('pg'),G=require('ora'),g=require('chalk'),ve=require('prettier'),ye=require('dotenv'),Ae=require('os'),Ee=require('readline');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var A__default=/*#__PURE__*/_interopDefault(A);var b__default=/*#__PURE__*/_interopDefault(b);var he__default=/*#__PURE__*/_interopDefault(he);var G__default=/*#__PURE__*/_interopDefault(G);var g__default=/*#__PURE__*/_interopDefault(g);var ve__default=/*#__PURE__*/_interopDefault(ve);var ye__default=/*#__PURE__*/_interopDefault(ye);var Ae__default=/*#__PURE__*/_interopDefault(Ae);var Ee__default=/*#__PURE__*/_interopDefault(Ee);ye__default.default.config();async function j(o){let e=b__default.default.resolve(o);if(!A__default.default.existsSync(e))return null;try{let t=A__default.default.readFileSync(e,"utf-8"),n=JSON.parse(t);return n.database?.url&&(n.database.url=M(n.database.url)),n.api?.apiKey&&(n.api.apiKey=M(n.api.apiKey)),n}catch{throw new Error(`Failed to parse config file: ${o}`)}}function M(o){return o.replace(/\$\{([^}]+)\}/g,(e,t)=>process.env[t]||e)}async function we(o,e){let t=await o.query(`
2
+ 'use strict';var commander=require('commander'),E=require('fs'),y=require('path'),_e=require('pg'),L=require('ora'),l=require('chalk'),De=require('prettier'),Ee=require('dotenv'),ze=require('os'),Be=require('readline');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var E__default=/*#__PURE__*/_interopDefault(E);var y__default=/*#__PURE__*/_interopDefault(y);var _e__default=/*#__PURE__*/_interopDefault(_e);var L__default=/*#__PURE__*/_interopDefault(L);var l__default=/*#__PURE__*/_interopDefault(l);var De__default=/*#__PURE__*/_interopDefault(De);var Ee__default=/*#__PURE__*/_interopDefault(Ee);var ze__default=/*#__PURE__*/_interopDefault(ze);var Be__default=/*#__PURE__*/_interopDefault(Be);Ee__default.default.config();async function b(o){let e=y__default.default.resolve(o);if(!E__default.default.existsSync(e))return null;try{let t=E__default.default.readFileSync(e,"utf-8"),n=JSON.parse(t);return n.database?.url&&(n.database.url=q(n.database.url)),n.api?.apiKey&&(n.api.apiKey=q(n.api.apiKey)),n}catch{throw new Error(`Failed to parse config file: ${o}`)}}function q(o){return o.replace(/\$\{([^}]+)\}/g,(e,t)=>process.env[t]||e)}async function Re(o,e){let t=await o.query(`
3
3
  SELECT table_name, table_type
4
4
  FROM information_schema.tables
5
5
  WHERE table_schema = $1
@@ -20,7 +20,7 @@
20
20
  FROM information_schema.columns
21
21
  WHERE table_schema = $1
22
22
  ORDER BY table_name, ordinal_position
23
- `,[e]),s=await o.query(`
23
+ `,[e]),r=await o.query(`
24
24
  SELECT
25
25
  tc.constraint_name,
26
26
  tc.table_name,
@@ -36,7 +36,7 @@
36
36
  AND ccu.table_schema = tc.table_schema
37
37
  WHERE tc.constraint_type = 'FOREIGN KEY'
38
38
  AND tc.table_schema = $1
39
- `,[e]),i=await o.query(`
39
+ `,[e]),a=await o.query(`
40
40
  SELECT
41
41
  t.typname as enum_name,
42
42
  e.enumlabel as enum_value
@@ -45,45 +45,53 @@
45
45
  JOIN pg_namespace n ON n.oid = t.typnamespace
46
46
  WHERE n.nspname = $1
47
47
  ORDER BY t.typname, e.enumsortorder
48
- `,[e]),r=new Map;for(let a of t.rows)r.set(a.table_name,[]);for(let a of n.rows){let u=r.get(a.table_name);u&&u.push(a);}let l=new Map;for(let a of i.rows){let u=l.get(a.enum_name)||[];u.push(a.enum_value),l.set(a.enum_name,u);}return {tables:r,enums:l,foreignKeys:s.rows}}var N={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 Ie(o,e){let{data_type:t,udt_name:n,is_nullable:s}=o;if(e.has(n)){let l=e.get(n).map(a=>`"${a}"`).join(" | ");return s==="YES"?`(${l}) | null`:l}if(t==="ARRAY"){let r=n.replace(/^_/,"");if(e.has(r)){let u=e.get(r).map(f=>`"${f}"`).join(" | ");return s==="YES"?`(${u})[] | null`:`(${u})[]`}let l=N[r]||"unknown";return s==="YES"?`${l}[] | null`:`${l}[]`}let i=N[t]||N[n]||"unknown";return s==="YES"&&(i=`${i} | null`),i}function O(o){return o.split(/[_\-\s]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function je(o,e){let t=O(o),n=e.map(s=>` | "${s}"`).join(`
48
+ `,[e]),i=new Map;for(let c of t.rows)i.set(c.table_name,[]);for(let c of n.rows){let p=i.get(c.table_name);p&&p.push(c);}let s=new Map;for(let c of a.rows){let p=s.get(c.enum_name)||[];p.push(c.enum_value),s.set(c.enum_name,p);}return {tables:i,enums:s,foreignKeys:r.rows}}var B={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 Ne(o,e){let{data_type:t,udt_name:n,is_nullable:r}=o;if(e.has(n)){let s=e.get(n).map(c=>`"${c}"`).join(" | ");return r==="YES"?`(${s}) | null`:s}if(t==="ARRAY"){let i=n.replace(/^_/,"");if(e.has(i)){let p=e.get(i).map(d=>`"${d}"`).join(" | ");return r==="YES"?`(${p})[] | null`:`(${p})[]`}let s=B[i]||"unknown";return r==="YES"?`${s}[] | null`:`${s}[]`}let a=B[t]||B[n]||"unknown";return r==="YES"&&(a=`${a} | null`),a}function K(o){return o.split(/[_\-\s]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function Te(o,e){let t=K(o),n=e.map(r=>` | "${r}"`).join(`
49
49
  `);return `export type ${t} =
50
- ${n};`}function $e(o,e,t){let n=O(o),s=[],i=[],r=[];for(let f of e){let p=Ie(f,t),c=f.column_name,h=f.column_default!==null||f.is_identity==="YES",E=f.is_nullable==="YES";s.push(` ${c}: ${p};`),h||f.column_name==="id"?i.push(` ${c}?: ${p.replace(" | null","")} | null;`):E?i.push(` ${c}?: ${p};`):i.push(` ${c}: ${p.replace(" | null","")};`),r.push(` ${c}?: ${p.replace(" | null","")} | null;`);}let l=`export interface ${n} {
51
- ${s.join(`
50
+ ${n};`}function Oe(o,e,t){let n=K(o),r=[],a=[],i=[];for(let d of e){let f=Ne(d,t),g=d.column_name,u=d.column_default!==null||d.is_identity==="YES",I=d.is_nullable==="YES";r.push(` ${g}: ${f};`),u||d.column_name==="id"?a.push(` ${g}?: ${f.replace(" | null","")} | null;`):I?a.push(` ${g}?: ${f};`):a.push(` ${g}: ${f.replace(" | null","")};`),i.push(` ${g}?: ${f.replace(" | null","")} | null;`);}let s=`export interface ${n} {
51
+ ${r.join(`
52
52
  `)}
53
- }`,a=`export interface ${n}Insert {
54
- ${i.join(`
53
+ }`,c=`export interface ${n}Insert {
54
+ ${a.join(`
55
55
  `)}
56
- }`,u=`export interface ${n}Update {
57
- ${r.join(`
56
+ }`,p=`export interface ${n}Update {
57
+ ${i.join(`
58
58
  `)}
59
- }`;return {base:l,insert:a,update:u}}function Se(o,e,t){let n=["/**"," * 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(e.size>0){n.push("// ============ ENUMS ============"),n.push("");for(let[i,r]of e)n.push(je(i,r)),n.push("");}n.push("// ============ TABLES ============"),n.push("");let s=[];for(let[i,r]of o){let{base:l,insert:a,update:u}=$e(i,r,e);s.push(i),n.push(l),n.push(""),n.push(a),n.push(""),n.push(u),n.push("");}n.push("// ============ DATABASE SCHEMA ============"),n.push(""),n.push("export interface Database {");for(let i of s){let r=O(i);n.push(` ${i}: {`),n.push(` Row: ${r};`),n.push(` Insert: ${r}Insert;`),n.push(` Update: ${r}Update;`),n.push(" };");}return n.push("}"),n.push(""),n.push("export type TableName = keyof Database;"),n.push(""),n.push("// ============ HELPER TYPES ============"),n.push(""),n.push('export type Row<T extends TableName> = Database[T]["Row"];'),n.push('export type Insert<T extends TableName> = Database[T]["Insert"];'),n.push('export type Update<T extends TableName> = Database[T]["Update"];'),n.push(""),n.join(`
60
- `)}async function Y(o){let e=G__default.default("Loading configuration...").start();try{let t=await j(o.config),n=o.connection||t?.database?.url||process.env.DATABASE_URL;n||(e.fail("No database connection string provided"),console.log(g__default.default.yellow(`
61
- Provide a connection string via:`)),console.log(g__default.default.gray(" --connection <url>")),console.log(g__default.default.gray(" DATABASE_URL environment variable")),console.log(g__default.default.gray(" vaif.config.json database.url")),process.exit(1)),e.text="Connecting to database...";let s=new he__default.default.Client({connectionString:n});await s.connect(),e.text="Introspecting schema...";let{tables:i,enums:r,foreignKeys:l}=await we(s,o.schema);if(await s.end(),i.size===0){e.warn(`No tables found in schema "${o.schema}"`);return}e.text=`Generating types for ${i.size} tables...`;let a=Se(i,r,l),u=await ve__default.default.format(a,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100});if(o.dryRun){e.succeed("Generated types (dry run):"),console.log(""),console.log(g__default.default.gray("\u2500".repeat(60))),console.log(u),console.log(g__default.default.gray("\u2500".repeat(60)));return}let f=b__default.default.resolve(o.output),p=b__default.default.dirname(f);A__default.default.existsSync(p)||A__default.default.mkdirSync(p,{recursive:!0}),A__default.default.writeFileSync(f,u,"utf-8"),e.succeed(`Generated types for ${i.size} tables \u2192 ${g__default.default.cyan(o.output)}`),console.log(""),console.log(g__default.default.green("Generated:")),console.log(g__default.default.gray(` Tables: ${i.size}`)),console.log(g__default.default.gray(` Enums: ${r.size}`)),console.log(""),console.log(g__default.default.gray("Import in your code:")),console.log(g__default.default.cyan(` import type { Database, Row, Insert, Update } from "${o.output.replace(/\.ts$/,"")}";`));}catch(t){e.fail("Failed to generate types"),t instanceof Error&&(console.error(g__default.default.red(`
62
- Error: ${t.message}`)),t.message.includes("ECONNREFUSED")&&console.log(g__default.default.yellow(`
63
- Make sure your database is running and accessible.`))),process.exit(1);}}var _e={$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 J(o){let e=G__default.default("Initializing VAIF configuration...").start(),t=b__default.default.resolve("vaif.config.json");A__default.default.existsSync(t)&&!o.force&&(e.fail("vaif.config.json already exists"),console.log(g__default.default.yellow(`
64
- Use --force to overwrite existing configuration.`)),process.exit(1));try{A__default.default.writeFileSync(t,JSON.stringify(_e,null,2),"utf-8"),e.succeed("Created vaif.config.json");let n=b__default.default.resolve(".env.example");if(A__default.default.existsSync(n)||(A__default.default.writeFileSync(n,`# VAIF Configuration
59
+ }`;return {base:s,insert:c,update:p}}function Le(o,e,t){let n=["/**"," * 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(e.size>0){n.push("// ============ ENUMS ============"),n.push("");for(let[a,i]of e)n.push(Te(a,i)),n.push("");}n.push("// ============ TABLES ============"),n.push("");let r=[];for(let[a,i]of o){let{base:s,insert:c,update:p}=Oe(a,i,e);r.push(a),n.push(s),n.push(""),n.push(c),n.push(""),n.push(p),n.push("");}n.push("// ============ DATABASE SCHEMA ============"),n.push(""),n.push("export interface Database {");for(let a of r){let i=K(a);n.push(` ${a}: {`),n.push(` Row: ${i};`),n.push(` Insert: ${i}Insert;`),n.push(` Update: ${i}Update;`),n.push(" };");}return n.push("}"),n.push(""),n.push("export type TableName = keyof Database;"),n.push(""),n.push("// ============ HELPER TYPES ============"),n.push(""),n.push('export type Row<T extends TableName> = Database[T]["Row"];'),n.push('export type Insert<T extends TableName> = Database[T]["Insert"];'),n.push('export type Update<T extends TableName> = Database[T]["Update"];'),n.push(""),n.join(`
60
+ `)}async function H(o){let e=L__default.default("Loading configuration...").start();try{let t=await b(o.config),n=o.connection||t?.database?.url||process.env.DATABASE_URL;n||(e.fail("No database connection string provided"),console.log(l__default.default.yellow(`
61
+ Provide a connection string via:`)),console.log(l__default.default.gray(" --connection <url>")),console.log(l__default.default.gray(" DATABASE_URL environment variable")),console.log(l__default.default.gray(" vaif.config.json database.url")),process.exit(1)),e.text="Connecting to database...";let r=new _e__default.default.Client({connectionString:n});await r.connect(),e.text="Introspecting schema...";let{tables:a,enums:i,foreignKeys:s}=await Re(r,o.schema);if(await r.end(),a.size===0){e.warn(`No tables found in schema "${o.schema}"`);return}e.text=`Generating types for ${a.size} tables...`;let c=Le(a,i,s),p=await De__default.default.format(c,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100});if(o.dryRun){e.succeed("Generated types (dry run):"),console.log(""),console.log(l__default.default.gray("\u2500".repeat(60))),console.log(p),console.log(l__default.default.gray("\u2500".repeat(60)));return}let d=y__default.default.resolve(o.output),f=y__default.default.dirname(d);E__default.default.existsSync(f)||E__default.default.mkdirSync(f,{recursive:!0}),E__default.default.writeFileSync(d,p,"utf-8"),e.succeed(`Generated types for ${a.size} tables \u2192 ${l__default.default.cyan(o.output)}`),console.log(""),console.log(l__default.default.green("Generated:")),console.log(l__default.default.gray(` Tables: ${a.size}`)),console.log(l__default.default.gray(` Enums: ${i.size}`)),console.log(""),console.log(l__default.default.gray("Import in your code:")),console.log(l__default.default.cyan(` import type { Database, Row, Insert, Update } from "${o.output.replace(/\.ts$/,"")}";`));}catch(t){e.fail("Failed to generate types"),t instanceof Error&&(console.error(l__default.default.red(`
62
+ Error: ${t.message}`)),t.message.includes("ECONNREFUSED")&&console.log(l__default.default.yellow(`
63
+ Make sure your database is running and accessible.`))),process.exit(1);}}var Ue={$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 Q(o){let e=L__default.default("Initializing VAIF configuration...").start(),t=y__default.default.resolve("vaif.config.json");E__default.default.existsSync(t)&&!o.force&&(e.fail("vaif.config.json already exists"),console.log(l__default.default.yellow(`
64
+ Use --force to overwrite existing configuration.`)),process.exit(1));try{E__default.default.writeFileSync(t,JSON.stringify(Ue,null,2),"utf-8"),e.succeed("Created vaif.config.json");let n=y__default.default.resolve(".env.example");if(E__default.default.existsSync(n)||(E__default.default.writeFileSync(n,`# VAIF Configuration
65
65
  DATABASE_URL=postgresql://user:password@localhost:5432/database
66
66
  VAIF_API_KEY=your-api-key
67
- `,"utf-8"),console.log(g__default.default.gray("Created .env.example"))),o.typescript){let s=b__default.default.resolve("src/types");A__default.default.existsSync(s)||(A__default.default.mkdirSync(s,{recursive:!0}),console.log(g__default.default.gray("Created src/types directory")));}console.log(""),console.log(g__default.default.green("VAIF initialized successfully!")),console.log(""),console.log(g__default.default.gray("Next steps:")),console.log(g__default.default.gray(" 1. Update vaif.config.json with your project ID")),console.log(g__default.default.gray(" 2. Set DATABASE_URL in your environment")),console.log(g__default.default.gray(" 3. Run: npx vaif generate")),console.log("");}catch(n){e.fail("Failed to initialize"),n instanceof Error&&console.error(g__default.default.red(`
68
- Error: ${n.message}`)),process.exit(1);}}var V=b__default.default.join(Ae__default.default.homedir(),".vaif"),F=b__default.default.join(V,"auth.json"),Fe=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ce(){A__default.default.existsSync(V)||A__default.default.mkdirSync(V,{recursive:true});}function Re(o){Ce(),A__default.default.writeFileSync(F,JSON.stringify(o,null,2),"utf-8"),A__default.default.chmodSync(F,384);}function S(){if(!A__default.default.existsSync(F))return null;try{let o=A__default.default.readFileSync(F,"utf-8");return JSON.parse(o)}catch{return null}}function De(o){let e=Ee__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(o,n=>{e.close(),t(n);});})}async function q(o){try{let e=await fetch(`${Fe}/v1/auth/me`,{headers:{Authorization:`Bearer ${o}`}});return e.ok?{valid:!0,email:(await e.json()).email}:{valid:!1}}catch{return {valid:false}}}async function H(o){let e=G__default.default();console.log(""),console.log(g__default.default.bold("Welcome to VAIF CLI")),console.log(g__default.default.gray("Authenticate to access your VAIF projects")),console.log("");let t=o.token;t||(console.log(g__default.default.gray("To get your API token:")),console.log(g__default.default.gray(" 1. Go to https://vaif.studio/settings/api-keys")),console.log(g__default.default.gray(" 2. Create a new API key or copy an existing one")),console.log(""),t=await De(g__default.default.cyan("Enter your API token: ")),(!t||t.trim()==="")&&(console.log(g__default.default.red(`
69
- No token provided. Login cancelled.`)),process.exit(1))),e.start("Validating token...");let{valid:n,email:s}=await q(t.trim());n||(e.fail("Invalid token"),console.log(g__default.default.red(`
70
- The provided token is invalid or expired.`)),console.log(g__default.default.gray("Please check your token and try again.")),process.exit(1));let i={token:t.trim(),email:s,projectId:o.projectId,expiresAt:new Date(Date.now()+720*60*60*1e3).toISOString()};Re(i),e.succeed("Logged in successfully"),console.log(""),s&&console.log(g__default.default.green(` Authenticated as: ${s}`)),console.log(g__default.default.gray(` Config saved to: ${F}`)),console.log(""),console.log(g__default.default.gray("You can now use VAIF CLI commands like:")),console.log(g__default.default.gray(" vaif pull - Pull remote schema")),console.log(g__default.default.gray(" vaif push - Push schema changes")),console.log(g__default.default.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function W(){A__default.default.existsSync(F)?(A__default.default.unlinkSync(F),console.log(g__default.default.green("Logged out successfully"))):console.log(g__default.default.yellow("Not currently logged in"));}async function Q(){let o=S();(!o||!o.token)&&(console.log(g__default.default.yellow("Not logged in")),console.log(g__default.default.gray("Run `vaif login` to authenticate")),process.exit(1));let e=G__default.default("Checking authentication...").start(),{valid:t,email:n}=await q(o.token);t||(e.fail("Session expired"),console.log(g__default.default.yellow(`
71
- Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Authenticated"),console.log(""),console.log(g__default.default.green(` Email: ${n||o.email||"Unknown"}`)),o.projectId&&console.log(g__default.default.green(` Project: ${o.projectId}`)),console.log("");}var Ne=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Oe(o,e,t="public"){let n=await fetch(`${Ne}/v1/projects/${e}/schema?schema=${t}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!n.ok){let s=await n.text();throw new Error(`Failed to fetch schema: ${s}`)}return n.json()}async function X(o){let e=G__default.default(),t=S();(!t||!t.token)&&(console.log(g__default.default.red("Not logged in")),console.log(g__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",s=null;e.start("Loading configuration...");try{s=await j(n);}catch(r){e.fail("Failed to load config"),console.log(g__default.default.red(`
72
- Error: ${r}`)),process.exit(1);}s||(e.fail("No configuration found"),console.log(g__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let i=o.projectId||s.projectId||t.projectId;i||(e.fail("No project ID specified"),console.log(g__default.default.yellow(`
73
- Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let r=o.schema||s.database?.schema||"public",l=await Oe(t.token,i,r);e.succeed("Schema fetched successfully");let a=o.output||b__default.default.resolve("vaif.schema.json"),u={$schema:"https://vaif.studio/schemas/schema.json",projectId:i,schema:r,pulledAt:new Date().toISOString(),...l};A__default.default.writeFileSync(a,JSON.stringify(u,null,2),"utf-8"),console.log(""),console.log(g__default.default.green(`Schema saved to: ${a}`)),console.log(""),console.log(g__default.default.gray("Schema summary:")),console.log(g__default.default.gray(` Tables: ${(l.tables||[]).length}`)),console.log(g__default.default.gray(` Enums: ${(l.enums||[]).length}`)),console.log(g__default.default.gray(` Functions: ${(l.functions||[]).length}`)),console.log(""),console.log(g__default.default.gray("Next steps:")),console.log(g__default.default.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(g__default.default.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(r){e.fail("Failed to fetch schema"),r instanceof Error&&console.log(g__default.default.red(`
74
- Error: ${r.message}`)),process.exit(1);}}var ee=process.env.VAIF_API_URL||"https://api.vaif.studio";function ze(o){let e=Ee__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(o,n=>{e.close(),t(n);});})}async function Me(o,e,t){let n=await fetch(`${ee}/v1/projects/${e}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!n.ok){let s=await n.text();throw new Error(`Failed to preview changes: ${s}`)}return n.json()}async function Be(o,e,t){let n=await fetch(`${ee}/v1/projects/${e}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!n.ok){let s=await n.text();throw new Error(`Failed to apply changes: ${s}`)}return n.json()}function Ye(o){if(console.log(""),console.log(g__default.default.bold("Schema Changes:")),console.log(""),o.added.length===0&&o.modified.length===0&&o.removed.length===0){console.log(g__default.default.gray(" No changes detected. Schema is up to date."));return}if(o.added.length>0){console.log(g__default.default.green.bold(" + Added:"));for(let e of o.added)console.log(g__default.default.green(` + ${e.type}: ${e.name}`));console.log("");}if(o.modified.length>0){console.log(g__default.default.yellow.bold(" ~ Modified:"));for(let e of o.modified){console.log(g__default.default.yellow(` ~ ${e.type}: ${e.name}`));for(let t of e.changes)console.log(g__default.default.gray(` ${t}`));}console.log("");}if(o.removed.length>0){console.log(g__default.default.red.bold(" - Removed:"));for(let e of o.removed)console.log(g__default.default.red(` - ${e.type}: ${e.name}`));console.log("");}}async function oe(o){let e=G__default.default(),t=S();(!t||!t.token)&&(console.log(g__default.default.red("Not logged in")),console.log(g__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",s=null;e.start("Loading configuration...");try{s=await j(n);}catch(a){e.fail("Failed to load config"),console.log(g__default.default.red(`
75
- Error: ${a}`)),process.exit(1);}s||(e.fail("No configuration found"),console.log(g__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let i=o.projectId||s.projectId||t.projectId;i||(e.fail("No project ID specified"),console.log(g__default.default.yellow(`
76
- Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let r=o.schema||b__default.default.resolve("vaif.schema.json");A__default.default.existsSync(r)||(e.fail("No local schema found"),console.log(g__default.default.yellow(`
77
- Expected schema file at: ${r}`)),console.log(g__default.default.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let l;try{let a=A__default.default.readFileSync(r,"utf-8");l=JSON.parse(a);}catch(a){e.fail("Failed to parse schema file"),a instanceof Error&&console.log(g__default.default.red(`
78
- Error: ${a.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:a,sql:u}=await Me(t.token,i,l);if(e.stop(),Ye(a),a.added.length===0&&a.modified.length===0&&a.removed.length===0){console.log("");return}if(u.length>0){console.log(g__default.default.bold("SQL Migrations:")),console.log("");for(let p of u)console.log(g__default.default.gray(` ${p}`));console.log("");}if(o.dryRun){console.log(g__default.default.yellow("Dry run mode - no changes applied.")),console.log(g__default.default.gray("Remove --dry-run to apply these changes."));return}if(!o.force){a.removed.length>0&&(console.log(g__default.default.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(g__default.default.red(" This action cannot be undone!")),console.log(""));let c=await ze(g__default.default.cyan("Apply these changes? [y/N] "));if(c.toLowerCase()!=="y"&&c.toLowerCase()!=="yes"){console.log(g__default.default.yellow(`
79
- Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let f=await Be(t.token,i,l);if(f.success){if(e.succeed("Schema changes applied successfully"),console.log(""),f.migrations.length>0){console.log(g__default.default.gray("Migrations applied:"));for(let p of f.migrations)console.log(g__default.default.gray(` - ${p}`));console.log("");}console.log(g__default.default.green("Your database schema is now up to date.")),console.log(g__default.default.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else e.fail("Failed to apply some changes");}catch(a){e.fail("Failed to push schema changes"),a instanceof Error&&console.log(g__default.default.red(`
80
- Error: ${a.message}`)),process.exit(1);}}var re=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Je(o,e,t){let n=await fetch(`${re}/v1/projects/${e}/functions`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({name:t.name,runtime:t.runtime,entrypoint:t.entrypoint,code:t.code,envId:t.envId})});if(!n.ok){let s=await n.text();throw new Error(`Failed to deploy function: ${s}`)}return n.json()}async function Ke(o,e,t){let n=new URL(`${re}/v1/projects/${e}/functions`);t&&n.searchParams.set("envId",t);let s=await fetch(n.toString(),{headers:{Authorization:`Bearer ${o}`}});if(!s.ok){let i=await s.text();throw new Error(`Failed to list functions: ${i}`)}return s.json()}function ne(o){switch(b__default.default.extname(o).toLowerCase()){case ".ts":return "typescript";case ".js":case ".mjs":return "nodejs";case ".py":return "python";case ".go":return "go";case ".rs":return "rust";default:return "nodejs"}}function te(o){let e=[],t=[".ts",".js",".mjs",".py",".go",".rs"];function n(s){if(!A__default.default.existsSync(s))return;let i=A__default.default.readdirSync(s,{withFileTypes:true});for(let r of i){let l=b__default.default.join(s,r.name);if(r.isDirectory())r.name!=="node_modules"&&!r.name.startsWith(".")&&n(l);else if(r.isFile()){let a=b__default.default.extname(r.name).toLowerCase();t.includes(a)&&(r.name==="index.ts"||r.name==="index.js"||r.name.includes("function")||r.name.includes("handler"))&&e.push(l);}}}return n(o),e}async function ie(o){let e=G__default.default(),t=S();(!t||!t.token)&&(console.log(g__default.default.red("Not logged in")),console.log(g__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",s=null;try{s=await j(n);}catch{}let i=o.projectId||s?.projectId||t.projectId;i||(console.log(g__default.default.red("No project ID specified")),console.log(g__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(g__default.default.bold("VAIF Functions Deploy")),console.log(""),e.start("Scanning for function files...");let r=b__default.default.resolve("functions"),l=b__default.default.resolve("src/functions"),a=[];if(o.entrypoint){let c=b__default.default.resolve(o.entrypoint);A__default.default.existsSync(c)||(e.fail(`File not found: ${o.entrypoint}`),process.exit(1)),a=[c];}else a=[...te(r),...te(l)];a.length===0&&(e.fail("No function files found"),console.log(g__default.default.yellow(`
81
- Place your functions in:`)),console.log(g__default.default.gray(" - ./functions/")),console.log(g__default.default.gray(" - ./src/functions/")),console.log(g__default.default.gray(`
82
- Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${a.length} function(s)`),o.name&&(a=a.filter(c=>b__default.default.basename(c,b__default.default.extname(c)).includes(o.name)),a.length===0&&(console.log(g__default.default.yellow(`
83
- No functions matching "${o.name}" found`)),process.exit(1))),console.log(""),console.log(g__default.default.gray("Functions to deploy:"));for(let c of a){let h=b__default.default.basename(b__default.default.dirname(c))||b__default.default.basename(c,b__default.default.extname(c)),E=o.runtime||ne(c);console.log(g__default.default.gray(` - ${h} (${E})`));}if(console.log(""),o.dryRun){console.log(g__default.default.yellow("Dry run mode - no functions deployed."));return}let u=[];for(let c of a){let h=b__default.default.basename(b__default.default.dirname(c))||b__default.default.basename(c,b__default.default.extname(c)),E=o.runtime||ne(c);e.start(`Deploying ${h}...`);try{let R=A__default.default.readFileSync(c,"utf-8"),D=await Je(t.token,i,{name:h,runtime:E,entrypoint:b__default.default.basename(c),code:R,envId:o.envId});e.succeed(`Deployed ${h} (v${D.version})`),u.push({name:h,success:!0,version:D.version});}catch(R){let D=R instanceof Error?R.message:"Unknown error";e.fail(`Failed to deploy ${h}`),u.push({name:h,success:false,error:D});}}console.log("");let f=u.filter(c=>c.success).length;if(u.filter(c=>!c.success).length===0)console.log(g__default.default.green(`\u2713 Successfully deployed ${f} function(s)`));else {console.log(g__default.default.yellow(`Deployed ${f}/${u.length} function(s)`)),console.log(""),console.log(g__default.default.red("Failed deployments:"));for(let c of u.filter(h=>!h.success))console.log(g__default.default.red(` - ${c.name}: ${c.error}`));}console.log("");}async function ae(o){let e=G__default.default(),t=S();(!t||!t.token)&&(console.log(g__default.default.red("Not logged in")),console.log(g__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",s=null;try{s=await j(n);}catch{}let i=o.projectId||s?.projectId||t.projectId;i||(console.log(g__default.default.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let r=await Ke(t.token,i,o.envId);if(e.stop(),r.length===0){console.log(g__default.default.yellow(`
84
- No functions found`)),console.log(g__default.default.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(g__default.default.bold(`Functions (${r.length}):`)),console.log(""),console.log(g__default.default.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"VERSION".padEnd(10)+"STATUS".padEnd(12)+"LAST DEPLOYED")),console.log(g__default.default.gray(" "+"-".repeat(80)));for(let l of r){let a=l.status==="active"?g__default.default.green:l.status==="deploying"?g__default.default.yellow:g__default.default.red;console.log(" "+l.name.padEnd(25)+l.runtime.padEnd(15)+`v${l.version}`.padEnd(10)+a(l.status.padEnd(12))+(l.lastDeployed?new Date(l.lastDeployed).toLocaleDateString():"-"));}console.log("");}catch(r){e.fail("Failed to fetch functions"),r instanceof Error&&console.log(g__default.default.red(`
85
- Error: ${r.message}`)),process.exit(1);}}var ge=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Ge(o,e,t,n,s){let i=await fetch(`${ge}/v1/projects/${e}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({table:t,records:n,truncate:s?.truncate??false})});if(!i.ok){let r=await i.text();throw new Error(`Failed to seed ${t}: ${r}`)}return i.json()}async function qe(o,e){let t=await fetch(`${ge}/v1/projects/${e}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!t.ok){let n=await t.text();throw new Error(`Failed to reset database: ${n}`)}return t.json()}function U(o){let e=[];if(!A__default.default.existsSync(o))return e;let t=A__default.default.readdirSync(o,{withFileTypes:true});for(let n of t)if(n.isFile()){let s=b__default.default.extname(n.name).toLowerCase();(s===".json"||s===".ts"||s===".js")&&e.push(b__default.default.join(o,n.name));}return e.sort()}async function ce(o){let e=b__default.default.extname(o).toLowerCase();if(e===".json"){let t=A__default.default.readFileSync(o,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?[{table:b__default.default.basename(o,e),data:n}]:n.table&&n.data?[n]:Object.entries(n).map(([s,i])=>({table:s,data:i}))}else if(e===".ts"||e===".js"){let t=await import(o),n=t.default||t;return typeof n=="function"?n():n}throw new Error(`Unsupported file format: ${e}`)}async function fe(o){let e=G__default.default(),t=S();(!t||!t.token)&&(console.log(g__default.default.red("Not logged in")),console.log(g__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",s=null;try{s=await j(n);}catch{}let i=o.projectId||s?.projectId||t.projectId;i||(console.log(g__default.default.red("No project ID specified")),console.log(g__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(g__default.default.bold("VAIF Database Seed")),console.log("");let r=[];if(o.file){let f=b__default.default.resolve(o.file);A__default.default.existsSync(f)||(console.log(g__default.default.red(`File not found: ${o.file}`)),process.exit(1)),r=[f];}else {let f=b__default.default.resolve("seeds"),p=b__default.default.resolve("prisma/seed"),c=b__default.default.resolve("db/seeds");r=[...U(f),...U(p),...U(c)];}r.length===0&&(console.log(g__default.default.yellow("No seed files found")),console.log(g__default.default.gray(`
86
- Place your seed files in one of these directories:`)),console.log(g__default.default.gray(" - ./seeds/")),console.log(g__default.default.gray(" - ./prisma/seed/")),console.log(g__default.default.gray(" - ./db/seeds/")),console.log(g__default.default.gray(`
87
- Or specify a file with --file`)),console.log(g__default.default.gray(`
88
- Example seed file (seeds/users.json):`)),console.log(g__default.default.gray(" [")),console.log(g__default.default.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(g__default.default.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(g__default.default.gray(" ]")),process.exit(1)),console.log(g__default.default.gray("Seed files found:"));for(let f of r)console.log(g__default.default.gray(` - ${b__default.default.relative(process.cwd(),f)}`));if(console.log(""),o.truncate&&(console.log(g__default.default.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),o.dryRun){console.log(g__default.default.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let f of r){e.start(`Loading ${b__default.default.basename(f)}...`);try{let p=await ce(f);e.stop();for(let c of p)o.table&&c.table!==o.table||(console.log(g__default.default.cyan(`Table: ${c.table}`)),console.log(g__default.default.gray(` Records: ${c.data.length}`)),c.data.length>0&&console.log(g__default.default.gray(` Sample: ${JSON.stringify(c.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(p){e.fail(`Failed to load ${b__default.default.basename(f)}`),p instanceof Error&&console.log(g__default.default.red(` Error: ${p.message}`));}}return}let l=[];for(let f of r){e.start(`Processing ${b__default.default.basename(f)}...`);try{let p=await ce(f);e.stop();for(let c of p)if(!(o.table&&c.table!==o.table)){if(c.data.length===0){console.log(g__default.default.gray(` Skipping ${c.table} (no records)`));continue}e.start(`Seeding ${c.table} (${c.data.length} records)...`);try{let h=await Ge(t.token,i,c.table,c.data,{truncate:o.truncate});e.succeed(`Seeded ${c.table}: ${h.inserted} records`),l.push({table:c.table,inserted:h.inserted});}catch(h){let E=h instanceof Error?h.message:"Unknown error";e.fail(`Failed to seed ${c.table}`),l.push({table:c.table,inserted:0,error:E});}}}catch(p){e.fail(`Failed to load ${b__default.default.basename(f)}`),p instanceof Error&&console.log(g__default.default.red(` Error: ${p.message}`));}}console.log("");let a=l.reduce((f,p)=>f+p.inserted,0),u=l.filter(f=>f.error).length;if(u===0)console.log(g__default.default.green(`\u2713 Successfully seeded ${a} records across ${l.length} table(s)`));else {console.log(g__default.default.yellow(`Seeded ${a} records with ${u} error(s)`)),console.log(""),console.log(g__default.default.red("Errors:"));for(let f of l.filter(p=>p.error))console.log(g__default.default.red(` - ${f.table}: ${f.error}`));}console.log("");}async function ue(o){let e=G__default.default(),t=S();(!t||!t.token)&&(console.log(g__default.default.red("Not logged in")),console.log(g__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",s=null;try{s=await j(n);}catch{}let i=o.projectId||s?.projectId||t.projectId;i||(console.log(g__default.default.red("No project ID specified")),process.exit(1)),console.log(""),console.log(g__default.default.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(g__default.default.red("This will:")),console.log(g__default.default.red(" - Drop all tables")),console.log(g__default.default.red(" - Delete all data")),console.log(g__default.default.red(" - Reset migrations")),console.log(""),console.log(g__default.default.red.bold("This action cannot be undone!")),console.log(""),o.force||(console.log(g__default.default.yellow("Use --force to confirm this action.")),process.exit(1)),e.start("Resetting database...");try{await qe(t.token,i),e.succeed("Database reset complete"),console.log(""),console.log(g__default.default.gray("Your database is now empty.")),console.log(g__default.default.gray("Run `vaif push` to apply your schema, then `vaif db seed` to seed data.")),console.log("");}catch(r){e.fail("Failed to reset database"),r instanceof Error&&console.log(g__default.default.red(`
89
- Error: ${r.message}`)),process.exit(1);}}commander.program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.0.2");commander.program.command("login").description("Authenticate with VAIF").option("-t, --token <token>","API token (will prompt if not provided)").option("-p, --project-id <id>","Default project ID").action(H);commander.program.command("logout").description("Log out and remove stored credentials").action(W);commander.program.command("whoami").description("Show current authenticated user").action(Q);commander.program.command("init").description("Initialize VAIF configuration in your project").option("--typescript","Setup for TypeScript project").option("-f, --force","Overwrite existing config").action(J);commander.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(X);commander.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(oe);commander.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(Y);var pe=commander.program.command("functions").alias("fn").description("Manage serverless functions");pe.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(ie);pe.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(ae);var de=commander.program.command("db").description("Database management commands");de.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(fe);de.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(ue);commander.program.parse(process.argv);process.argv.slice(2).length||commander.program.outputHelp();
67
+ `,"utf-8"),console.log(l__default.default.gray("Created .env.example"))),o.typescript){let r=y__default.default.resolve("src/types");E__default.default.existsSync(r)||(E__default.default.mkdirSync(r,{recursive:!0}),console.log(l__default.default.gray("Created src/types directory")));}console.log(""),console.log(l__default.default.green("VAIF initialized successfully!")),console.log(""),console.log(l__default.default.gray("Next steps:")),console.log(l__default.default.gray(" 1. Update vaif.config.json with your project ID")),console.log(l__default.default.gray(" 2. Set DATABASE_URL in your environment")),console.log(l__default.default.gray(" 3. Run: npx vaif generate")),console.log("");}catch(n){e.fail("Failed to initialize"),n instanceof Error&&console.error(l__default.default.red(`
68
+ Error: ${n.message}`)),process.exit(1);}}var J=y__default.default.join(ze__default.default.homedir(),".vaif"),R=y__default.default.join(J,"auth.json"),Ke=process.env.VAIF_API_URL||"https://api.vaif.studio";function Me(){E__default.default.existsSync(J)||E__default.default.mkdirSync(J,{recursive:true});}function Je(o){Me(),E__default.default.writeFileSync(R,JSON.stringify(o,null,2),"utf-8"),E__default.default.chmodSync(R,384);}function j(){if(!E__default.default.existsSync(R))return null;try{let o=E__default.default.readFileSync(R,"utf-8");return JSON.parse(o)}catch{return null}}function Ye(o){let e=Be__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(o,n=>{e.close(),t(n);});})}async function ee(o){try{let e=await fetch(`${Ke}/v1/auth/me`,{headers:{Authorization:`Bearer ${o}`}});return e.ok?{valid:!0,email:(await e.json()).email}:{valid:!1}}catch{return {valid:false}}}async function oe(o){let e=L__default.default();console.log(""),console.log(l__default.default.bold("Welcome to VAIF CLI")),console.log(l__default.default.gray("Authenticate to access your VAIF projects")),console.log("");let t=o.token;t||(console.log(l__default.default.gray("To get your API token:")),console.log(l__default.default.gray(" 1. Go to https://vaif.studio/settings/api-keys")),console.log(l__default.default.gray(" 2. Create a new API key or copy an existing one")),console.log(""),t=await Ye(l__default.default.cyan("Enter your API token: ")),(!t||t.trim()==="")&&(console.log(l__default.default.red(`
69
+ No token provided. Login cancelled.`)),process.exit(1))),e.start("Validating token...");let{valid:n,email:r}=await ee(t.trim());n||(e.fail("Invalid token"),console.log(l__default.default.red(`
70
+ The provided token is invalid or expired.`)),console.log(l__default.default.gray("Please check your token and try again.")),process.exit(1));let a={token:t.trim(),email:r,projectId:o.projectId,expiresAt:new Date(Date.now()+720*60*60*1e3).toISOString()};Je(a),e.succeed("Logged in successfully"),console.log(""),r&&console.log(l__default.default.green(` Authenticated as: ${r}`)),console.log(l__default.default.gray(` Config saved to: ${R}`)),console.log(""),console.log(l__default.default.gray("You can now use VAIF CLI commands like:")),console.log(l__default.default.gray(" vaif pull - Pull remote schema")),console.log(l__default.default.gray(" vaif push - Push schema changes")),console.log(l__default.default.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function ne(){E__default.default.existsSync(R)?(E__default.default.unlinkSync(R),console.log(l__default.default.green("Logged out successfully"))):console.log(l__default.default.yellow("Not currently logged in"));}async function te(){let o=j();(!o||!o.token)&&(console.log(l__default.default.yellow("Not logged in")),console.log(l__default.default.gray("Run `vaif login` to authenticate")),process.exit(1));let e=L__default.default("Checking authentication...").start(),{valid:t,email:n}=await ee(o.token);t||(e.fail("Session expired"),console.log(l__default.default.yellow(`
71
+ Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Authenticated"),console.log(""),console.log(l__default.default.green(` Email: ${n||o.email||"Unknown"}`)),o.projectId&&console.log(l__default.default.green(` Project: ${o.projectId}`)),console.log("");}var He=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Qe(o,e,t="public"){let n=await fetch(`${He}/v1/projects/${e}/schema?schema=${t}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!n.ok){let r=await n.text();throw new Error(`Failed to fetch schema: ${r}`)}return n.json()}async function se(o){let e=L__default.default(),t=j();(!t||!t.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await b(n);}catch(i){e.fail("Failed to load config"),console.log(l__default.default.red(`
72
+ Error: ${i}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(l__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let a=o.projectId||r.projectId||t.projectId;a||(e.fail("No project ID specified"),console.log(l__default.default.yellow(`
73
+ Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let i=o.schema||r.database?.schema||"public",s=await Qe(t.token,a,i);e.succeed("Schema fetched successfully");let c=o.output||y__default.default.resolve("vaif.schema.json"),p={$schema:"https://vaif.studio/schemas/schema.json",projectId:a,schema:i,pulledAt:new Date().toISOString(),...s};E__default.default.writeFileSync(c,JSON.stringify(p,null,2),"utf-8"),console.log(""),console.log(l__default.default.green(`Schema saved to: ${c}`)),console.log(""),console.log(l__default.default.gray("Schema summary:")),console.log(l__default.default.gray(` Tables: ${(s.tables||[]).length}`)),console.log(l__default.default.gray(` Enums: ${(s.enums||[]).length}`)),console.log(l__default.default.gray(` Functions: ${(s.functions||[]).length}`)),console.log(""),console.log(l__default.default.gray("Next steps:")),console.log(l__default.default.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(l__default.default.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(i){e.fail("Failed to fetch schema"),i instanceof Error&&console.log(l__default.default.red(`
74
+ Error: ${i.message}`)),process.exit(1);}}var re=process.env.VAIF_API_URL||"https://api.vaif.studio";function oo(o){let e=Be__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(o,n=>{e.close(),t(n);});})}async function no(o,e,t){let n=await fetch(`${re}/v1/projects/${e}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!n.ok){let r=await n.text();throw new Error(`Failed to preview changes: ${r}`)}return n.json()}async function to(o,e,t){let n=await fetch(`${re}/v1/projects/${e}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!n.ok){let r=await n.text();throw new Error(`Failed to apply changes: ${r}`)}return n.json()}function so(o){if(console.log(""),console.log(l__default.default.bold("Schema Changes:")),console.log(""),o.added.length===0&&o.modified.length===0&&o.removed.length===0){console.log(l__default.default.gray(" No changes detected. Schema is up to date."));return}if(o.added.length>0){console.log(l__default.default.green.bold(" + Added:"));for(let e of o.added)console.log(l__default.default.green(` + ${e.type}: ${e.name}`));console.log("");}if(o.modified.length>0){console.log(l__default.default.yellow.bold(" ~ Modified:"));for(let e of o.modified){console.log(l__default.default.yellow(` ~ ${e.type}: ${e.name}`));for(let t of e.changes)console.log(l__default.default.gray(` ${t}`));}console.log("");}if(o.removed.length>0){console.log(l__default.default.red.bold(" - Removed:"));for(let e of o.removed)console.log(l__default.default.red(` - ${e.type}: ${e.name}`));console.log("");}}async function ae(o){let e=L__default.default(),t=j();(!t||!t.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await b(n);}catch(c){e.fail("Failed to load config"),console.log(l__default.default.red(`
75
+ Error: ${c}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(l__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let a=o.projectId||r.projectId||t.projectId;a||(e.fail("No project ID specified"),console.log(l__default.default.yellow(`
76
+ Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=o.schema||y__default.default.resolve("vaif.schema.json");E__default.default.existsSync(i)||(e.fail("No local schema found"),console.log(l__default.default.yellow(`
77
+ Expected schema file at: ${i}`)),console.log(l__default.default.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let s;try{let c=E__default.default.readFileSync(i,"utf-8");s=JSON.parse(c);}catch(c){e.fail("Failed to parse schema file"),c instanceof Error&&console.log(l__default.default.red(`
78
+ Error: ${c.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:c,sql:p}=await no(t.token,a,s);if(e.stop(),so(c),c.added.length===0&&c.modified.length===0&&c.removed.length===0){console.log("");return}if(p.length>0){console.log(l__default.default.bold("SQL Migrations:")),console.log("");for(let f of p)console.log(l__default.default.gray(` ${f}`));console.log("");}if(o.dryRun){console.log(l__default.default.yellow("Dry run mode - no changes applied.")),console.log(l__default.default.gray("Remove --dry-run to apply these changes."));return}if(!o.force){c.removed.length>0&&(console.log(l__default.default.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(l__default.default.red(" This action cannot be undone!")),console.log(""));let g=await oo(l__default.default.cyan("Apply these changes? [y/N] "));if(g.toLowerCase()!=="y"&&g.toLowerCase()!=="yes"){console.log(l__default.default.yellow(`
79
+ Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let d=await to(t.token,a,s);if(d.success){if(e.succeed("Schema changes applied successfully"),console.log(""),d.migrations.length>0){console.log(l__default.default.gray("Migrations applied:"));for(let f of d.migrations)console.log(l__default.default.gray(` - ${f}`));console.log("");}console.log(l__default.default.green("Your database schema is now up to date.")),console.log(l__default.default.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else e.fail("Failed to apply some changes");}catch(c){e.fail("Failed to push schema changes"),c instanceof Error&&console.log(l__default.default.red(`
80
+ Error: ${c.message}`)),process.exit(1);}}var fe=process.env.VAIF_API_URL||"https://api.vaif.studio";async function io(o,e,t){let n=await fetch(`${fe}/v1/projects/${e}/functions`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({name:t.name,runtime:t.runtime,entrypoint:t.entrypoint,code:t.code,envId:t.envId})});if(!n.ok){let r=await n.text();throw new Error(`Failed to deploy function: ${r}`)}return n.json()}async function ro(o,e,t){let n=new URL(`${fe}/v1/projects/${e}/functions`);t&&n.searchParams.set("envId",t);let r=await fetch(n.toString(),{headers:{Authorization:`Bearer ${o}`}});if(!r.ok){let a=await r.text();throw new Error(`Failed to list functions: ${a}`)}return r.json()}function ce(o){switch(y__default.default.extname(o).toLowerCase()){case ".ts":return "typescript";case ".js":case ".mjs":return "nodejs";case ".py":return "python";case ".go":return "go";case ".rs":return "rust";default:return "nodejs"}}function le(o){let e=[],t=[".ts",".js",".mjs",".py",".go",".rs"];function n(r){if(!E__default.default.existsSync(r))return;let a=E__default.default.readdirSync(r,{withFileTypes:true});for(let i of a){let s=y__default.default.join(r,i.name);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&n(s);else if(i.isFile()){let c=y__default.default.extname(i.name).toLowerCase();t.includes(c)&&(i.name==="index.ts"||i.name==="index.js"||i.name.includes("function")||i.name.includes("handler"))&&e.push(s);}}}return n(o),e}async function pe(o){let e=L__default.default(),t=j();(!t||!t.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=o.projectId||r?.projectId||t.projectId;a||(console.log(l__default.default.red("No project ID specified")),console.log(l__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(l__default.default.bold("VAIF Functions Deploy")),console.log(""),e.start("Scanning for function files...");let i=y__default.default.resolve("functions"),s=y__default.default.resolve("src/functions"),c=[];if(o.entrypoint){let g=y__default.default.resolve(o.entrypoint);E__default.default.existsSync(g)||(e.fail(`File not found: ${o.entrypoint}`),process.exit(1)),c=[g];}else c=[...le(i),...le(s)];c.length===0&&(e.fail("No function files found"),console.log(l__default.default.yellow(`
81
+ Place your functions in:`)),console.log(l__default.default.gray(" - ./functions/")),console.log(l__default.default.gray(" - ./src/functions/")),console.log(l__default.default.gray(`
82
+ Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${c.length} function(s)`),o.name&&(c=c.filter(g=>y__default.default.basename(g,y__default.default.extname(g)).includes(o.name)),c.length===0&&(console.log(l__default.default.yellow(`
83
+ No functions matching "${o.name}" found`)),process.exit(1))),console.log(""),console.log(l__default.default.gray("Functions to deploy:"));for(let g of c){let u=y__default.default.basename(y__default.default.dirname(g))||y__default.default.basename(g,y__default.default.extname(g)),I=o.runtime||ce(g);console.log(l__default.default.gray(` - ${u} (${I})`));}if(console.log(""),o.dryRun){console.log(l__default.default.yellow("Dry run mode - no functions deployed."));return}let p=[];for(let g of c){let u=y__default.default.basename(y__default.default.dirname(g))||y__default.default.basename(g,y__default.default.extname(g)),I=o.runtime||ce(g);e.start(`Deploying ${u}...`);try{let _=E__default.default.readFileSync(g,"utf-8"),T=await io(t.token,a,{name:u,runtime:I,entrypoint:y__default.default.basename(g),code:_,envId:o.envId});e.succeed(`Deployed ${u} (v${T.version})`),p.push({name:u,success:!0,version:T.version});}catch(_){let T=_ instanceof Error?_.message:"Unknown error";e.fail(`Failed to deploy ${u}`),p.push({name:u,success:false,error:T});}}console.log("");let d=p.filter(g=>g.success).length;if(p.filter(g=>!g.success).length===0)console.log(l__default.default.green(`\u2713 Successfully deployed ${d} function(s)`));else {console.log(l__default.default.yellow(`Deployed ${d}/${p.length} function(s)`)),console.log(""),console.log(l__default.default.red("Failed deployments:"));for(let g of p.filter(u=>!u.success))console.log(l__default.default.red(` - ${g.name}: ${g.error}`));}console.log("");}async function de(o){let e=L__default.default(),t=j();(!t||!t.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=o.projectId||r?.projectId||t.projectId;a||(console.log(l__default.default.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let i=await ro(t.token,a,o.envId);if(e.stop(),i.length===0){console.log(l__default.default.yellow(`
84
+ No functions found`)),console.log(l__default.default.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(l__default.default.bold(`Functions (${i.length}):`)),console.log(""),console.log(l__default.default.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"VERSION".padEnd(10)+"STATUS".padEnd(12)+"LAST DEPLOYED")),console.log(l__default.default.gray(" "+"-".repeat(80)));for(let s of i){let c=s.status==="active"?l__default.default.green:s.status==="deploying"?l__default.default.yellow:l__default.default.red;console.log(" "+s.name.padEnd(25)+s.runtime.padEnd(15)+`v${s.version}`.padEnd(10)+c(s.status.padEnd(12))+(s.lastDeployed?new Date(s.lastDeployed).toLocaleDateString():"-"));}console.log("");}catch(i){e.fail("Failed to fetch functions"),i instanceof Error&&console.log(l__default.default.red(`
85
+ Error: ${i.message}`)),process.exit(1);}}var V=process.env.VAIF_API_URL||"https://api.vaif.studio";async function ao(o,e,t,n,r){let a=await fetch(`${V}/v1/projects/${e}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({table:t,records:n,truncate:r?.truncate??false})});if(!a.ok){let i=await a.text();throw new Error(`Failed to seed ${t}: ${i}`)}return a.json()}async function co(o,e){let t=await fetch(`${V}/v1/projects/${e}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!t.ok){let n=await t.text();throw new Error(`Failed to reset database: ${n}`)}return t.json()}function Y(o){let e=[];if(!E__default.default.existsSync(o))return e;let t=E__default.default.readdirSync(o,{withFileTypes:true});for(let n of t)if(n.isFile()){let r=y__default.default.extname(n.name).toLowerCase();(r===".json"||r===".ts"||r===".js")&&e.push(y__default.default.join(o,n.name));}return e.sort()}async function ue(o){let e=y__default.default.extname(o).toLowerCase();if(e===".json"){let t=E__default.default.readFileSync(o,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?[{table:y__default.default.basename(o,e),data:n}]:n.table&&n.data?[n]:Object.entries(n).map(([r,a])=>({table:r,data:a}))}else if(e===".ts"||e===".js"){let t=await import(o),n=t.default||t;return typeof n=="function"?n():n}throw new Error(`Unsupported file format: ${e}`)}async function me(o){let e=L__default.default(),t=j();(!t||!t.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=o.projectId||r?.projectId||t.projectId;a||(console.log(l__default.default.red("No project ID specified")),console.log(l__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(l__default.default.bold("VAIF Database Seed")),console.log("");let i=[];if(o.file){let d=y__default.default.resolve(o.file);E__default.default.existsSync(d)||(console.log(l__default.default.red(`File not found: ${o.file}`)),process.exit(1)),i=[d];}else {let d=y__default.default.resolve("seeds"),f=y__default.default.resolve("prisma/seed"),g=y__default.default.resolve("db/seeds");i=[...Y(d),...Y(f),...Y(g)];}i.length===0&&(console.log(l__default.default.yellow("No seed files found")),console.log(l__default.default.gray(`
86
+ Place your seed files in one of these directories:`)),console.log(l__default.default.gray(" - ./seeds/")),console.log(l__default.default.gray(" - ./prisma/seed/")),console.log(l__default.default.gray(" - ./db/seeds/")),console.log(l__default.default.gray(`
87
+ Or specify a file with --file`)),console.log(l__default.default.gray(`
88
+ Example seed file (seeds/users.json):`)),console.log(l__default.default.gray(" [")),console.log(l__default.default.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(l__default.default.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(l__default.default.gray(" ]")),process.exit(1)),console.log(l__default.default.gray("Seed files found:"));for(let d of i)console.log(l__default.default.gray(` - ${y__default.default.relative(process.cwd(),d)}`));if(console.log(""),o.truncate&&(console.log(l__default.default.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),o.dryRun){console.log(l__default.default.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let d of i){e.start(`Loading ${y__default.default.basename(d)}...`);try{let f=await ue(d);e.stop();for(let g of f)o.table&&g.table!==o.table||(console.log(l__default.default.cyan(`Table: ${g.table}`)),console.log(l__default.default.gray(` Records: ${g.data.length}`)),g.data.length>0&&console.log(l__default.default.gray(` Sample: ${JSON.stringify(g.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(f){e.fail(`Failed to load ${y__default.default.basename(d)}`),f instanceof Error&&console.log(l__default.default.red(` Error: ${f.message}`));}}return}let s=[];for(let d of i){e.start(`Processing ${y__default.default.basename(d)}...`);try{let f=await ue(d);e.stop();for(let g of f)if(!(o.table&&g.table!==o.table)){if(g.data.length===0){console.log(l__default.default.gray(` Skipping ${g.table} (no records)`));continue}e.start(`Seeding ${g.table} (${g.data.length} records)...`);try{let u=await ao(t.token,a,g.table,g.data,{truncate:o.truncate});e.succeed(`Seeded ${g.table}: ${u.inserted} records`),s.push({table:g.table,inserted:u.inserted});}catch(u){let I=u instanceof Error?u.message:"Unknown error";e.fail(`Failed to seed ${g.table}`),s.push({table:g.table,inserted:0,error:I});}}}catch(f){e.fail(`Failed to load ${y__default.default.basename(d)}`),f instanceof Error&&console.log(l__default.default.red(` Error: ${f.message}`));}}console.log("");let c=s.reduce((d,f)=>d+f.inserted,0),p=s.filter(d=>d.error).length;if(p===0)console.log(l__default.default.green(`\u2713 Successfully seeded ${c} records across ${s.length} table(s)`));else {console.log(l__default.default.yellow(`Seeded ${c} records with ${p} error(s)`)),console.log(""),console.log(l__default.default.red("Errors:"));for(let d of s.filter(f=>f.error))console.log(l__default.default.red(` - ${d.table}: ${d.error}`));}console.log("");}async function he(o){let e=L__default.default(),t=j();(!t||!t.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=o.projectId||r?.projectId||t.projectId;a||(console.log(l__default.default.red("No project ID specified")),console.log(l__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=y__default.default.resolve(o.dir||"./drizzle");if(console.log(""),console.log(l__default.default.bold("VAIF Database Push")),console.log(""),!E__default.default.existsSync(i)){let f=y__default.default.resolve("./migrations");E__default.default.existsSync(f)?console.log(l__default.default.gray(`Using migrations from: ${f}`)):(console.log(l__default.default.red(`Migrations directory not found: ${i}`)),console.log(l__default.default.gray(`
89
+ Expected one of:`)),console.log(l__default.default.gray(" - ./drizzle/")),console.log(l__default.default.gray(" - ./migrations/")),console.log(l__default.default.gray(`
90
+ Or specify with: vaif db push --dir <path>`)),process.exit(1));}let s=[],c=E__default.default.readdirSync(i,{withFileTypes:true});for(let f of c)if(f.isFile()&&f.name.endsWith(".sql"))s.push(y__default.default.join(i,f.name));else if(f.isDirectory()){let g=E__default.default.readdirSync(y__default.default.join(i,f.name),{withFileTypes:true});for(let u of g)u.isFile()&&u.name.endsWith(".sql")&&s.push(y__default.default.join(i,f.name,u.name));}s.sort(),s.length===0&&(console.log(l__default.default.yellow("No SQL migration files found")),process.exit(1)),console.log(l__default.default.gray(`Found ${s.length} migration(s):`));for(let f of s)console.log(l__default.default.gray(` - ${y__default.default.relative(process.cwd(),f)}`));if(console.log(""),o.dryRun){console.log(l__default.default.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let f of s){let g=E__default.default.readFileSync(f,"utf-8");console.log(l__default.default.cyan(`--- ${y__default.default.basename(f)} ---`)),console.log(l__default.default.gray(g.slice(0,500))),g.length>500&&console.log(l__default.default.gray("...")),console.log("");}return}let p=0,d=0;for(let f of s){let g=E__default.default.readFileSync(f,"utf-8"),u=y__default.default.relative(process.cwd(),f);e.start(`Applying ${u}...`);try{let I=await fetch(`${V}/v1/projects/${a}/schema/execute`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:g})});if(!I.ok){let _=await I.text();throw new Error(_)}e.succeed(`Applied ${u}`),p++;}catch(I){let _=I instanceof Error?I.message:"Unknown error";e.fail(`Failed ${u}: ${_}`),d++;}}console.log(""),console.log(d===0?l__default.default.green(`Successfully applied ${p} migration(s)`):l__default.default.yellow(`Applied ${p}, failed ${d} migration(s)`)),console.log("");}async function ye(o){let e=L__default.default(),t=j();(!t||!t.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=o.projectId||r?.projectId||t.projectId;a||(console.log(l__default.default.red("No project ID specified")),console.log(l__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=y__default.default.resolve(o.output||"vaif.schema.json");console.log(""),console.log(l__default.default.bold("VAIF Database Pull")),console.log(""),e.start("Pulling schema from remote...");try{let s=await fetch(`${V}/v1/projects/${a}/schema`,{headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok){let d=await s.text();throw new Error(`Failed to pull schema: ${d}`)}let c=await s.json();E__default.default.writeFileSync(i,JSON.stringify(c,null,2),"utf-8"),e.succeed(`Schema written to ${y__default.default.relative(process.cwd(),i)}`);let p=c.tables?.length??Object.keys(c).length;console.log(l__default.default.gray(` ${p} table(s) pulled`)),console.log("");}catch(s){e.fail("Failed to pull schema"),s instanceof Error&&console.log(l__default.default.red(`
91
+ Error: ${s.message}`)),process.exit(1);}}async function we(o){let e=L__default.default(),t=j();(!t||!t.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=o.projectId||r?.projectId||t.projectId;a||(console.log(l__default.default.red("No project ID specified")),process.exit(1)),console.log(""),console.log(l__default.default.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(l__default.default.red("This will:")),console.log(l__default.default.red(" - Drop all tables")),console.log(l__default.default.red(" - Delete all data")),console.log(l__default.default.red(" - Reset migrations")),console.log(""),console.log(l__default.default.red.bold("This action cannot be undone!")),console.log(""),o.force||(console.log(l__default.default.yellow("Use --force to confirm this action.")),process.exit(1)),e.start("Resetting database...");try{await co(t.token,a),e.succeed("Database reset complete"),console.log(""),console.log(l__default.default.gray("Your database is now empty.")),console.log(l__default.default.gray("Run `vaif push` to apply your schema, then `vaif db seed` to seed data.")),console.log("");}catch(i){e.fail("Failed to reset database"),i instanceof Error&&console.log(l__default.default.red(`
92
+ Error: ${i.message}`)),process.exit(1);}}var je=process.env.VAIF_API_URL||"https://api.vaif.studio";function ve(o,e,t){return o.projectId||e?.projectId||t.projectId||null}async function Ie(o){let e=L__default.default(),t=j();(!t||!t.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=ve(o,r,t);a||(console.log(l__default.default.red("No project ID specified")),console.log(l__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=o.name||`cli-key-${Date.now()}`;console.log(""),console.log(l__default.default.bold("VAIF Generate API Key")),console.log(""),e.start("Generating API key...");try{let s=await fetch(`${je}/v1/projects/${a}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i})});if(!s.ok){let p=await s.text();throw new Error(`Failed to generate key: ${p}`)}let c=await s.json();e.succeed("API key generated"),console.log(""),console.log(l__default.default.green(` Name: ${c.name}`)),console.log(l__default.default.green(` Key: ${c.key}`)),console.log(""),console.log(l__default.default.yellow.bold(" Save this key now - it will not be shown again!")),console.log("");}catch(s){e.fail("Failed to generate API key"),s instanceof Error&&console.log(l__default.default.red(`
93
+ Error: ${s.message}`)),process.exit(1);}}async function $e(o){let e=L__default.default(),t=j();(!t||!t.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=ve(o,r,t);a||(console.log(l__default.default.red("No project ID specified")),console.log(l__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(l__default.default.bold("VAIF API Keys")),console.log(""),e.start("Fetching API keys...");try{let i=await fetch(`${je}/v1/projects/${a}/api-keys`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let f=await i.text();throw new Error(`Failed to list keys: ${f}`)}let s=await i.json(),c=s.keys||s;if(e.stop(),!Array.isArray(c)||c.length===0){console.log(l__default.default.yellow("No API keys found")),console.log(l__default.default.gray(`
94
+ Generate one with: vaif keys generate`));return}let p=Math.max(8,...c.map(f=>(f.name||"").length)),d=` ${"Name".padEnd(p)} ${"Key".padEnd(24)} Created`;console.log(l__default.default.gray(d)),console.log(l__default.default.gray(" "+"-".repeat(d.length-2)));for(let f of c){let g=(f.name||"unnamed").padEnd(p),u=f.maskedKey||f.prefix||`${(f.key||"").slice(0,12)}...`,I=f.createdAt?new Date(f.createdAt).toLocaleDateString():"N/A";console.log(` ${g} ${u.padEnd(24)} ${I}`);}console.log(""),console.log(l__default.default.gray(` ${c.length} key(s) total`)),console.log("");}catch(i){e.fail("Failed to list API keys"),i instanceof Error&&console.log(l__default.default.red(`
95
+ Error: ${i.message}`)),process.exit(1);}}var Se=process.env.VAIF_API_URL||"https://api.vaif.studio";function go(o){try{let e=new URL(o);return e.password&&(e.password="****"),e.toString()}catch{return o.replace(/:[^@/]+@/,":****@")}}async function Ae(o){let e=L__default.default(),t=j();(!t||!t.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=o.projectId||r?.projectId||t.projectId;a||(console.log(l__default.default.red("No project ID specified")),console.log(l__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),e.start("Fetching project info...");try{let i=await fetch(`${Se}/v1/projects/${a}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let d=await i.text();throw new Error(`Failed to fetch project: ${d}`)}let s=await i.json();e.stop(),console.log(""),console.log(l__default.default.bold("VAIF Project Info")),console.log("");let c=16,p=(d,f)=>{console.log(` ${l__default.default.gray(d.padEnd(c))} ${f}`);};p("Name:",l__default.default.white(s.name||"N/A")),p("Project ID:",l__default.default.white(a)),p("Region:",l__default.default.white(s.region||"us-east-1")),p("Plan:",l__default.default.white(s.plan||s.tier||"free")),p("Created:",l__default.default.white(s.createdAt?new Date(s.createdAt).toLocaleDateString():"N/A")),console.log(""),p("API URL:",l__default.default.cyan(s.apiUrl||`${Se}/v1`)),p("WS URL:",l__default.default.cyan(s.wsUrl||s.realtimeUrl||"N/A")),p("DB URL:",l__default.default.cyan(s.databaseUrl?go(s.databaseUrl):"N/A")),p("Storage URL:",l__default.default.cyan(s.storageUrl||"N/A")),console.log("");}catch(i){e.fail("Failed to fetch project info"),i instanceof Error&&console.log(l__default.default.red(`
96
+ Error: ${i.message}`)),process.exit(1);}}var po=process.env.VAIF_API_URL||"https://api.vaif.studio";async function xe(o){let e=L__default.default(),t=j();(!t||!t.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=o.projectId||r?.projectId||t.projectId;a||(console.log(l__default.default.red("No project ID specified")),console.log(l__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),e.start("Fetching project status...");try{let i=await fetch(`${po}/v1/projects/${a}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let I=await i.text();throw new Error(`Failed to fetch project status: ${I}`)}let s=await i.json();e.stop(),console.log(""),console.log(l__default.default.bold("VAIF Project Status")),console.log("");let c=22,p=(I,_)=>{console.log(` ${l__default.default.gray(I.padEnd(c))} ${_}`);};p("Project:",l__default.default.white(s.name||a)),p("Plan:",l__default.default.white(s.plan||s.tier||"free")),console.log(""),console.log(l__default.default.gray(" --- Resources ---")),console.log("");let d=s.tableCount??s.tables?.length??"N/A",f=s.functionCount??s.functions?.length??"N/A",g=s.bucketCount??s.storage?.buckets?.length??"N/A",u=s.activeConnections??s.connections??"N/A";p("Tables:",l__default.default.white(String(d))),p("Functions:",l__default.default.white(String(f))),p("Storage Buckets:",l__default.default.white(String(g))),p("Active Connections:",l__default.default.white(String(u))),s.usage&&(console.log(""),console.log(l__default.default.gray(" --- Usage ---")),console.log(""),s.usage.dbSize&&p("Database Size:",l__default.default.white(s.usage.dbSize)),s.usage.storageSize&&p("Storage Size:",l__default.default.white(s.usage.storageSize)),s.usage.bandwidth&&p("Bandwidth:",l__default.default.white(s.usage.bandwidth)),s.usage.functionInvocations!=null&&p("Function Invocations:",l__default.default.white(String(s.usage.functionInvocations)))),console.log("");}catch(i){e.fail("Failed to fetch project status"),i instanceof Error&&console.log(l__default.default.red(`
97
+ Error: ${i.message}`)),process.exit(1);}}commander.program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.1.0");commander.program.command("login").description("Authenticate with VAIF").option("-t, --token <token>","API token (will prompt if not provided)").option("-p, --project-id <id>","Default project ID").action(oe);commander.program.command("logout").description("Log out and remove stored credentials").action(ne);commander.program.command("whoami").description("Show current authenticated user").action(te);commander.program.command("init").description("Initialize VAIF configuration in your project").option("--typescript","Setup for TypeScript project").option("-f, --force","Overwrite existing config").action(Q);commander.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(Ae);commander.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(xe);commander.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(se);commander.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);commander.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(H);var Pe=commander.program.command("functions").alias("fn").description("Manage serverless functions");Pe.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(pe);Pe.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(de);var U=commander.program.command("db").description("Database management commands");U.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);U.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);U.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);U.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 Fe=commander.program.command("keys").description("Manage API keys");Fe.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(Ie);Fe.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($e);commander.program.parse(process.argv);process.argv.slice(2).length||commander.program.outputHelp();
package/dist/cli.js CHANGED
@@ -1,23 +1,31 @@
1
1
  #!/usr/bin/env node
2
- import {c,b,a}from'./chunk-7YZZOG47.js';import {program}from'commander';import S from'fs';import h from'path';import re from'os';import V from'ora';import r from'chalk';import ce from'readline';var R=h.join(re.homedir(),".vaif"),x=h.join(R,"auth.json"),ae=process.env.VAIF_API_URL||"https://api.vaif.studio";function le(){S.existsSync(R)||S.mkdirSync(R,{recursive:true});}function ge(e){le(),S.writeFileSync(x,JSON.stringify(e,null,2),"utf-8"),S.chmodSync(x,384);}function I(){if(!S.existsSync(x))return null;try{let e=S.readFileSync(x,"utf-8");return JSON.parse(e)}catch{return null}}function fe(e){let o=ce.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{o.question(e,t=>{o.close(),n(t);});})}async function _(e){try{let o=await fetch(`${ae}/v1/auth/me`,{headers:{Authorization:`Bearer ${e}`}});return o.ok?{valid:!0,email:(await o.json()).email}:{valid:!1}}catch{return {valid:false}}}async function U(e){let o=V();console.log(""),console.log(r.bold("Welcome to VAIF CLI")),console.log(r.gray("Authenticate to access your VAIF projects")),console.log("");let n=e.token;n||(console.log(r.gray("To get your API token:")),console.log(r.gray(" 1. Go to https://vaif.studio/settings/api-keys")),console.log(r.gray(" 2. Create a new API key or copy an existing one")),console.log(""),n=await fe(r.cyan("Enter your API token: ")),(!n||n.trim()==="")&&(console.log(r.red(`
3
- No token provided. Login cancelled.`)),process.exit(1))),o.start("Validating token...");let{valid:t,email:s}=await _(n.trim());t||(o.fail("Invalid token"),console.log(r.red(`
4
- The provided token is invalid or expired.`)),console.log(r.gray("Please check your token and try again.")),process.exit(1));let l={token:n.trim(),email:s,projectId:e.projectId,expiresAt:new Date(Date.now()+720*60*60*1e3).toISOString()};ge(l),o.succeed("Logged in successfully"),console.log(""),s&&console.log(r.green(` Authenticated as: ${s}`)),console.log(r.gray(` Config saved to: ${x}`)),console.log(""),console.log(r.gray("You can now use VAIF CLI commands like:")),console.log(r.gray(" vaif pull - Pull remote schema")),console.log(r.gray(" vaif push - Push schema changes")),console.log(r.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function J(){S.existsSync(x)?(S.unlinkSync(x),console.log(r.green("Logged out successfully"))):console.log(r.yellow("Not currently logged in"));}async function z(){let e=I();(!e||!e.token)&&(console.log(r.yellow("Not logged in")),console.log(r.gray("Run `vaif login` to authenticate")),process.exit(1));let o=V("Checking authentication...").start(),{valid:n,email:t}=await _(e.token);n||(o.fail("Session expired"),console.log(r.yellow(`
5
- Your session has expired. Please login again.`)),process.exit(1)),o.succeed("Authenticated"),console.log(""),console.log(r.green(` Email: ${t||e.email||"Unknown"}`)),e.projectId&&console.log(r.green(` Project: ${e.projectId}`)),console.log("");}var me=process.env.VAIF_API_URL||"https://api.vaif.studio";async function he(e,o,n="public"){let t=await fetch(`${me}/v1/projects/${o}/schema?schema=${n}`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!t.ok){let s=await t.text();throw new Error(`Failed to fetch schema: ${s}`)}return t.json()}async function B(e){let o=V(),n=I();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let t=e.config||"vaif.config.json",s=null;o.start("Loading configuration...");try{s=await a(t);}catch(c){o.fail("Failed to load config"),console.log(r.red(`
6
- Error: ${c}`)),process.exit(1);}s||(o.fail("No configuration found"),console.log(r.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let l=e.projectId||s.projectId||n.projectId;l||(o.fail("No project ID specified"),console.log(r.yellow(`
7
- Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),o.text="Fetching remote schema...";try{let c=e.schema||s.database?.schema||"public",f=await he(n.token,l,c);o.succeed("Schema fetched successfully");let a=e.output||h.resolve("vaif.schema.json"),v={$schema:"https://vaif.studio/schemas/schema.json",projectId:l,schema:c,pulledAt:new Date().toISOString(),...f};S.writeFileSync(a,JSON.stringify(v,null,2),"utf-8"),console.log(""),console.log(r.green(`Schema saved to: ${a}`)),console.log(""),console.log(r.gray("Schema summary:")),console.log(r.gray(` Tables: ${(f.tables||[]).length}`)),console.log(r.gray(` Enums: ${(f.enums||[]).length}`)),console.log(r.gray(` Functions: ${(f.functions||[]).length}`)),console.log(""),console.log(r.gray("Next steps:")),console.log(r.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(r.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(c){o.fail("Failed to fetch schema"),c instanceof Error&&console.log(r.red(`
8
- Error: ${c.message}`)),process.exit(1);}}var q=process.env.VAIF_API_URL||"https://api.vaif.studio";function je(e){let o=ce.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{o.question(e,t=>{o.close(),n(t);});})}async function be(e,o,n){let t=await fetch(`${q}/v1/projects/${o}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:n})});if(!t.ok){let s=await t.text();throw new Error(`Failed to preview changes: ${s}`)}return t.json()}async function Ie(e,o,n){let t=await fetch(`${q}/v1/projects/${o}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:n})});if(!t.ok){let s=await t.text();throw new Error(`Failed to apply changes: ${s}`)}return t.json()}function $e(e){if(console.log(""),console.log(r.bold("Schema Changes:")),console.log(""),e.added.length===0&&e.modified.length===0&&e.removed.length===0){console.log(r.gray(" No changes detected. Schema is up to date."));return}if(e.added.length>0){console.log(r.green.bold(" + Added:"));for(let o of e.added)console.log(r.green(` + ${o.type}: ${o.name}`));console.log("");}if(e.modified.length>0){console.log(r.yellow.bold(" ~ Modified:"));for(let o of e.modified){console.log(r.yellow(` ~ ${o.type}: ${o.name}`));for(let n of o.changes)console.log(r.gray(` ${n}`));}console.log("");}if(e.removed.length>0){console.log(r.red.bold(" - Removed:"));for(let o of e.removed)console.log(r.red(` - ${o.type}: ${o.name}`));console.log("");}}async function Y(e){let o=V(),n=I();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let t=e.config||"vaif.config.json",s=null;o.start("Loading configuration...");try{s=await a(t);}catch(a){o.fail("Failed to load config"),console.log(r.red(`
9
- Error: ${a}`)),process.exit(1);}s||(o.fail("No configuration found"),console.log(r.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let l=e.projectId||s.projectId||n.projectId;l||(o.fail("No project ID specified"),console.log(r.yellow(`
10
- Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let c=e.schema||h.resolve("vaif.schema.json");S.existsSync(c)||(o.fail("No local schema found"),console.log(r.yellow(`
11
- Expected schema file at: ${c}`)),console.log(r.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let f;try{let a=S.readFileSync(c,"utf-8");f=JSON.parse(a);}catch(a){o.fail("Failed to parse schema file"),a instanceof Error&&console.log(r.red(`
12
- Error: ${a.message}`)),process.exit(1);}o.text="Calculating schema changes...";try{let{diff:a,sql:v}=await be(n.token,l,f);if(o.stop(),$e(a),a.added.length===0&&a.modified.length===0&&a.removed.length===0){console.log("");return}if(v.length>0){console.log(r.bold("SQL Migrations:")),console.log("");for(let m of v)console.log(r.gray(` ${m}`));console.log("");}if(e.dryRun){console.log(r.yellow("Dry run mode - no changes applied.")),console.log(r.gray("Remove --dry-run to apply these changes."));return}if(!e.force){a.removed.length>0&&(console.log(r.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(r.red(" This action cannot be undone!")),console.log(""));let i=await je(r.cyan("Apply these changes? [y/N] "));if(i.toLowerCase()!=="y"&&i.toLowerCase()!=="yes"){console.log(r.yellow(`
13
- Cancelled. No changes applied.`));return}}o.start("Applying schema changes...");let p=await Ie(n.token,l,f);if(p.success){if(o.succeed("Schema changes applied successfully"),console.log(""),p.migrations.length>0){console.log(r.gray("Migrations applied:"));for(let m of p.migrations)console.log(r.gray(` - ${m}`));console.log("");}console.log(r.green("Your database schema is now up to date.")),console.log(r.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else o.fail("Failed to apply some changes");}catch(a){o.fail("Failed to push schema changes"),a instanceof Error&&console.log(r.red(`
14
- Error: ${a.message}`)),process.exit(1);}}var Q=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Se(e,o,n){let t=await fetch(`${Q}/v1/projects/${o}/functions`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({name:n.name,runtime:n.runtime,entrypoint:n.entrypoint,code:n.code,envId:n.envId})});if(!t.ok){let s=await t.text();throw new Error(`Failed to deploy function: ${s}`)}return t.json()}async function xe(e,o,n){let t=new URL(`${Q}/v1/projects/${o}/functions`);n&&t.searchParams.set("envId",n);let s=await fetch(t.toString(),{headers:{Authorization:`Bearer ${e}`}});if(!s.ok){let l=await s.text();throw new Error(`Failed to list functions: ${l}`)}return s.json()}function G(e){switch(h.extname(e).toLowerCase()){case ".ts":return "typescript";case ".js":case ".mjs":return "nodejs";case ".py":return "python";case ".go":return "go";case ".rs":return "rust";default:return "nodejs"}}function W(e){let o=[],n=[".ts",".js",".mjs",".py",".go",".rs"];function t(s){if(!S.existsSync(s))return;let l=S.readdirSync(s,{withFileTypes:true});for(let c of l){let f=h.join(s,c.name);if(c.isDirectory())c.name!=="node_modules"&&!c.name.startsWith(".")&&t(f);else if(c.isFile()){let a=h.extname(c.name).toLowerCase();n.includes(a)&&(c.name==="index.ts"||c.name==="index.js"||c.name.includes("function")||c.name.includes("handler"))&&o.push(f);}}}return t(e),o}async function K(e){let o=V(),n=I();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let t=e.config||"vaif.config.json",s=null;try{s=await a(t);}catch{}let l=e.projectId||s?.projectId||n.projectId;l||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(r.bold("VAIF Functions Deploy")),console.log(""),o.start("Scanning for function files...");let c=h.resolve("functions"),f=h.resolve("src/functions"),a$1=[];if(e.entrypoint){let i=h.resolve(e.entrypoint);S.existsSync(i)||(o.fail(`File not found: ${e.entrypoint}`),process.exit(1)),a$1=[i];}else a$1=[...W(c),...W(f)];a$1.length===0&&(o.fail("No function files found"),console.log(r.yellow(`
2
+ import {c,b,a}from'./chunk-7YZZOG47.js';import {program}from'commander';import k from'fs';import y from'path';import Io from'os';import V from'ora';import r from'chalk';import bo from'readline';var U=y.join(Io.homedir(),".vaif"),N=y.join(U,"auth.json"),$o=process.env.VAIF_API_URL||"https://api.vaif.studio";function So(){k.existsSync(U)||k.mkdirSync(U,{recursive:true});}function Ao(e){So(),k.writeFileSync(N,JSON.stringify(e,null,2),"utf-8"),k.chmodSync(N,384);}function w(){if(!k.existsSync(N))return null;try{let e=k.readFileSync(N,"utf-8");return JSON.parse(e)}catch{return null}}function Po(e){let o=bo.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{o.question(e,s=>{o.close(),n(s);});})}async function q(e){try{let o=await fetch(`${$o}/v1/auth/me`,{headers:{Authorization:`Bearer ${e}`}});return o.ok?{valid:!0,email:(await o.json()).email}:{valid:!1}}catch{return {valid:false}}}async function G(e){let o=V();console.log(""),console.log(r.bold("Welcome to VAIF CLI")),console.log(r.gray("Authenticate to access your VAIF projects")),console.log("");let n=e.token;n||(console.log(r.gray("To get your API token:")),console.log(r.gray(" 1. Go to https://vaif.studio/settings/api-keys")),console.log(r.gray(" 2. Create a new API key or copy an existing one")),console.log(""),n=await Po(r.cyan("Enter your API token: ")),(!n||n.trim()==="")&&(console.log(r.red(`
3
+ No token provided. Login cancelled.`)),process.exit(1))),o.start("Validating token...");let{valid:s,email:c}=await q(n.trim());s||(o.fail("Invalid token"),console.log(r.red(`
4
+ The provided token is invalid or expired.`)),console.log(r.gray("Please check your token and try again.")),process.exit(1));let f={token:n.trim(),email:c,projectId:e.projectId,expiresAt:new Date(Date.now()+720*60*60*1e3).toISOString()};Ao(f),o.succeed("Logged in successfully"),console.log(""),c&&console.log(r.green(` Authenticated as: ${c}`)),console.log(r.gray(` Config saved to: ${N}`)),console.log(""),console.log(r.gray("You can now use VAIF CLI commands like:")),console.log(r.gray(" vaif pull - Pull remote schema")),console.log(r.gray(" vaif push - Push schema changes")),console.log(r.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function M(){k.existsSync(N)?(k.unlinkSync(N),console.log(r.green("Logged out successfully"))):console.log(r.yellow("Not currently logged in"));}async function W(){let e=w();(!e||!e.token)&&(console.log(r.yellow("Not logged in")),console.log(r.gray("Run `vaif login` to authenticate")),process.exit(1));let o=V("Checking authentication...").start(),{valid:n,email:s}=await q(e.token);n||(o.fail("Session expired"),console.log(r.yellow(`
5
+ Your session has expired. Please login again.`)),process.exit(1)),o.succeed("Authenticated"),console.log(""),console.log(r.green(` Email: ${s||e.email||"Unknown"}`)),e.projectId&&console.log(r.green(` Project: ${e.projectId}`)),console.log("");}var Co=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Do(e,o,n="public"){let s=await fetch(`${Co}/v1/projects/${o}/schema?schema=${n}`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!s.ok){let c=await s.text();throw new Error(`Failed to fetch schema: ${c}`)}return s.json()}async function Y(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;o.start("Loading configuration...");try{c=await a(s);}catch(i){o.fail("Failed to load config"),console.log(r.red(`
6
+ Error: ${i}`)),process.exit(1);}c||(o.fail("No configuration found"),console.log(r.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let f=e.projectId||c.projectId||n.projectId;f||(o.fail("No project ID specified"),console.log(r.yellow(`
7
+ Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),o.text="Fetching remote schema...";try{let i=e.schema||c.database?.schema||"public",t=await Do(n.token,f,i);o.succeed("Schema fetched successfully");let l=e.output||y.resolve("vaif.schema.json"),d={$schema:"https://vaif.studio/schemas/schema.json",projectId:f,schema:i,pulledAt:new Date().toISOString(),...t};k.writeFileSync(l,JSON.stringify(d,null,2),"utf-8"),console.log(""),console.log(r.green(`Schema saved to: ${l}`)),console.log(""),console.log(r.gray("Schema summary:")),console.log(r.gray(` Tables: ${(t.tables||[]).length}`)),console.log(r.gray(` Enums: ${(t.enums||[]).length}`)),console.log(r.gray(` Functions: ${(t.functions||[]).length}`)),console.log(""),console.log(r.gray("Next steps:")),console.log(r.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(r.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(i){o.fail("Failed to fetch schema"),i instanceof Error&&console.log(r.red(`
8
+ Error: ${i.message}`)),process.exit(1);}}var Q=process.env.VAIF_API_URL||"https://api.vaif.studio";function Oo(e){let o=bo.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{o.question(e,s=>{o.close(),n(s);});})}async function Vo(e,o,n){let s=await fetch(`${Q}/v1/projects/${o}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:n})});if(!s.ok){let c=await s.text();throw new Error(`Failed to preview changes: ${c}`)}return s.json()}async function Lo(e,o,n){let s=await fetch(`${Q}/v1/projects/${o}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:n})});if(!s.ok){let c=await s.text();throw new Error(`Failed to apply changes: ${c}`)}return s.json()}function To(e){if(console.log(""),console.log(r.bold("Schema Changes:")),console.log(""),e.added.length===0&&e.modified.length===0&&e.removed.length===0){console.log(r.gray(" No changes detected. Schema is up to date."));return}if(e.added.length>0){console.log(r.green.bold(" + Added:"));for(let o of e.added)console.log(r.green(` + ${o.type}: ${o.name}`));console.log("");}if(e.modified.length>0){console.log(r.yellow.bold(" ~ Modified:"));for(let o of e.modified){console.log(r.yellow(` ~ ${o.type}: ${o.name}`));for(let n of o.changes)console.log(r.gray(` ${n}`));}console.log("");}if(e.removed.length>0){console.log(r.red.bold(" - Removed:"));for(let o of e.removed)console.log(r.red(` - ${o.type}: ${o.name}`));console.log("");}}async function X(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;o.start("Loading configuration...");try{c=await a(s);}catch(l){o.fail("Failed to load config"),console.log(r.red(`
9
+ Error: ${l}`)),process.exit(1);}c||(o.fail("No configuration found"),console.log(r.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let f=e.projectId||c.projectId||n.projectId;f||(o.fail("No project ID specified"),console.log(r.yellow(`
10
+ Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=e.schema||y.resolve("vaif.schema.json");k.existsSync(i)||(o.fail("No local schema found"),console.log(r.yellow(`
11
+ Expected schema file at: ${i}`)),console.log(r.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let t;try{let l=k.readFileSync(i,"utf-8");t=JSON.parse(l);}catch(l){o.fail("Failed to parse schema file"),l instanceof Error&&console.log(r.red(`
12
+ Error: ${l.message}`)),process.exit(1);}o.text="Calculating schema changes...";try{let{diff:l,sql:d}=await Vo(n.token,f,t);if(o.stop(),To(l),l.added.length===0&&l.modified.length===0&&l.removed.length===0){console.log("");return}if(d.length>0){console.log(r.bold("SQL Migrations:")),console.log("");for(let g of d)console.log(r.gray(` ${g}`));console.log("");}if(e.dryRun){console.log(r.yellow("Dry run mode - no changes applied.")),console.log(r.gray("Remove --dry-run to apply these changes."));return}if(!e.force){l.removed.length>0&&(console.log(r.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(r.red(" This action cannot be undone!")),console.log(""));let a=await Oo(r.cyan("Apply these changes? [y/N] "));if(a.toLowerCase()!=="y"&&a.toLowerCase()!=="yes"){console.log(r.yellow(`
13
+ Cancelled. No changes applied.`));return}}o.start("Applying schema changes...");let p=await Lo(n.token,f,t);if(p.success){if(o.succeed("Schema changes applied successfully"),console.log(""),p.migrations.length>0){console.log(r.gray("Migrations applied:"));for(let g of p.migrations)console.log(r.gray(` - ${g}`));console.log("");}console.log(r.green("Your database schema is now up to date.")),console.log(r.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else o.fail("Failed to apply some changes");}catch(l){o.fail("Failed to push schema changes"),l instanceof Error&&console.log(r.red(`
14
+ Error: ${l.message}`)),process.exit(1);}}var no=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Uo(e,o,n){let s=await fetch(`${no}/v1/projects/${o}/functions`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({name:n.name,runtime:n.runtime,entrypoint:n.entrypoint,code:n.code,envId:n.envId})});if(!s.ok){let c=await s.text();throw new Error(`Failed to deploy function: ${c}`)}return s.json()}async function _o(e,o,n){let s=new URL(`${no}/v1/projects/${o}/functions`);n&&s.searchParams.set("envId",n);let c=await fetch(s.toString(),{headers:{Authorization:`Bearer ${e}`}});if(!c.ok){let f=await c.text();throw new Error(`Failed to list functions: ${f}`)}return c.json()}function Z(e){switch(y.extname(e).toLowerCase()){case ".ts":return "typescript";case ".js":case ".mjs":return "nodejs";case ".py":return "python";case ".go":return "go";case ".rs":return "rust";default:return "nodejs"}}function oo(e){let o=[],n=[".ts",".js",".mjs",".py",".go",".rs"];function s(c){if(!k.existsSync(c))return;let f=k.readdirSync(c,{withFileTypes:true});for(let i of f){let t=y.join(c,i.name);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&s(t);else if(i.isFile()){let l=y.extname(i.name).toLowerCase();n.includes(l)&&(i.name==="index.ts"||i.name==="index.js"||i.name.includes("function")||i.name.includes("handler"))&&o.push(t);}}}return s(e),o}async function to(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=e.projectId||c?.projectId||n.projectId;f||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(r.bold("VAIF Functions Deploy")),console.log(""),o.start("Scanning for function files...");let i=y.resolve("functions"),t=y.resolve("src/functions"),l=[];if(e.entrypoint){let a=y.resolve(e.entrypoint);k.existsSync(a)||(o.fail(`File not found: ${e.entrypoint}`),process.exit(1)),l=[a];}else l=[...oo(i),...oo(t)];l.length===0&&(o.fail("No function files found"),console.log(r.yellow(`
15
15
  Place your functions in:`)),console.log(r.gray(" - ./functions/")),console.log(r.gray(" - ./src/functions/")),console.log(r.gray(`
16
- Or specify an entrypoint with --entrypoint`)),process.exit(1)),o.succeed(`Found ${a$1.length} function(s)`),e.name&&(a$1=a$1.filter(i=>h.basename(i,h.extname(i)).includes(e.name)),a$1.length===0&&(console.log(r.yellow(`
17
- No functions matching "${e.name}" found`)),process.exit(1))),console.log(""),console.log(r.gray("Functions to deploy:"));for(let i of a$1){let y=h.basename(h.dirname(i))||h.basename(i,h.extname(i)),F=e.runtime||G(i);console.log(r.gray(` - ${y} (${F})`));}if(console.log(""),e.dryRun){console.log(r.yellow("Dry run mode - no functions deployed."));return}let v=[];for(let i of a$1){let y=h.basename(h.dirname(i))||h.basename(i,h.extname(i)),F=e.runtime||G(i);o.start(`Deploying ${y}...`);try{let k=S.readFileSync(i,"utf-8"),C=await Se(n.token,l,{name:y,runtime:F,entrypoint:h.basename(i),code:k,envId:e.envId});o.succeed(`Deployed ${y} (v${C.version})`),v.push({name:y,success:!0,version:C.version});}catch(k){let C=k instanceof Error?k.message:"Unknown error";o.fail(`Failed to deploy ${y}`),v.push({name:y,success:false,error:C});}}console.log("");let p=v.filter(i=>i.success).length;if(v.filter(i=>!i.success).length===0)console.log(r.green(`\u2713 Successfully deployed ${p} function(s)`));else {console.log(r.yellow(`Deployed ${p}/${v.length} function(s)`)),console.log(""),console.log(r.red("Failed deployments:"));for(let i of v.filter(y=>!y.success))console.log(r.red(` - ${i.name}: ${i.error}`));}console.log("");}async function X(e){let o=V(),n=I();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let t=e.config||"vaif.config.json",s=null;try{s=await a(t);}catch{}let l=e.projectId||s?.projectId||n.projectId;l||(console.log(r.red("No project ID specified")),process.exit(1)),o.start("Fetching functions...");try{let c=await xe(n.token,l,e.envId);if(o.stop(),c.length===0){console.log(r.yellow(`
18
- No functions found`)),console.log(r.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(r.bold(`Functions (${c.length}):`)),console.log(""),console.log(r.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"VERSION".padEnd(10)+"STATUS".padEnd(12)+"LAST DEPLOYED")),console.log(r.gray(" "+"-".repeat(80)));for(let f of c){let a=f.status==="active"?r.green:f.status==="deploying"?r.yellow:r.red;console.log(" "+f.name.padEnd(25)+f.runtime.padEnd(15)+`v${f.version}`.padEnd(10)+a(f.status.padEnd(12))+(f.lastDeployed?new Date(f.lastDeployed).toLocaleDateString():"-"));}console.log("");}catch(c){o.fail("Failed to fetch functions"),c instanceof Error&&console.log(r.red(`
19
- Error: ${c.message}`)),process.exit(1);}}var oe=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Fe(e,o,n,t,s){let l=await fetch(`${oe}/v1/projects/${o}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({table:n,records:t,truncate:s?.truncate??false})});if(!l.ok){let c=await l.text();throw new Error(`Failed to seed ${n}: ${c}`)}return l.json()}async function Ae(e,o){let n=await fetch(`${oe}/v1/projects/${o}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!n.ok){let t=await n.text();throw new Error(`Failed to reset database: ${t}`)}return n.json()}function N(e){let o=[];if(!S.existsSync(e))return o;let n=S.readdirSync(e,{withFileTypes:true});for(let t of n)if(t.isFile()){let s=h.extname(t.name).toLowerCase();(s===".json"||s===".ts"||s===".js")&&o.push(h.join(e,t.name));}return o.sort()}async function Z(e){let o=h.extname(e).toLowerCase();if(o===".json"){let n=S.readFileSync(e,"utf-8"),t=JSON.parse(n);return Array.isArray(t)?[{table:h.basename(e,o),data:t}]:t.table&&t.data?[t]:Object.entries(t).map(([s,l])=>({table:s,data:l}))}else if(o===".ts"||o===".js"){let n=await import(e),t=n.default||n;return typeof t=="function"?t():t}throw new Error(`Unsupported file format: ${o}`)}async function ne(e){let o=V(),n=I();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let t=e.config||"vaif.config.json",s=null;try{s=await a(t);}catch{}let l=e.projectId||s?.projectId||n.projectId;l||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(r.bold("VAIF Database Seed")),console.log("");let c=[];if(e.file){let p=h.resolve(e.file);S.existsSync(p)||(console.log(r.red(`File not found: ${e.file}`)),process.exit(1)),c=[p];}else {let p=h.resolve("seeds"),m=h.resolve("prisma/seed"),i=h.resolve("db/seeds");c=[...N(p),...N(m),...N(i)];}c.length===0&&(console.log(r.yellow("No seed files found")),console.log(r.gray(`
16
+ Or specify an entrypoint with --entrypoint`)),process.exit(1)),o.succeed(`Found ${l.length} function(s)`),e.name&&(l=l.filter(a=>y.basename(a,y.extname(a)).includes(e.name)),l.length===0&&(console.log(r.yellow(`
17
+ No functions matching "${e.name}" found`)),process.exit(1))),console.log(""),console.log(r.gray("Functions to deploy:"));for(let a of l){let h=y.basename(y.dirname(a))||y.basename(a,y.extname(a)),$=e.runtime||Z(a);console.log(r.gray(` - ${h} (${$})`));}if(console.log(""),e.dryRun){console.log(r.yellow("Dry run mode - no functions deployed."));return}let d=[];for(let a of l){let h=y.basename(y.dirname(a))||y.basename(a,y.extname(a)),$=e.runtime||Z(a);o.start(`Deploying ${h}...`);try{let F=k.readFileSync(a,"utf-8"),R=await Uo(n.token,f,{name:h,runtime:$,entrypoint:y.basename(a),code:F,envId:e.envId});o.succeed(`Deployed ${h} (v${R.version})`),d.push({name:h,success:!0,version:R.version});}catch(F){let R=F instanceof Error?F.message:"Unknown error";o.fail(`Failed to deploy ${h}`),d.push({name:h,success:false,error:R});}}console.log("");let p=d.filter(a=>a.success).length;if(d.filter(a=>!a.success).length===0)console.log(r.green(`\u2713 Successfully deployed ${p} function(s)`));else {console.log(r.yellow(`Deployed ${p}/${d.length} function(s)`)),console.log(""),console.log(r.red("Failed deployments:"));for(let a of d.filter(h=>!h.success))console.log(r.red(` - ${a.name}: ${a.error}`));}console.log("");}async function io(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=e.projectId||c?.projectId||n.projectId;f||(console.log(r.red("No project ID specified")),process.exit(1)),o.start("Fetching functions...");try{let i=await _o(n.token,f,e.envId);if(o.stop(),i.length===0){console.log(r.yellow(`
18
+ No functions found`)),console.log(r.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(r.bold(`Functions (${i.length}):`)),console.log(""),console.log(r.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"VERSION".padEnd(10)+"STATUS".padEnd(12)+"LAST DEPLOYED")),console.log(r.gray(" "+"-".repeat(80)));for(let t of i){let l=t.status==="active"?r.green:t.status==="deploying"?r.yellow:r.red;console.log(" "+t.name.padEnd(25)+t.runtime.padEnd(15)+`v${t.version}`.padEnd(10)+l(t.status.padEnd(12))+(t.lastDeployed?new Date(t.lastDeployed).toLocaleDateString():"-"));}console.log("");}catch(i){o.fail("Failed to fetch functions"),i instanceof Error&&console.log(r.red(`
19
+ Error: ${i.message}`)),process.exit(1);}}var L=process.env.VAIF_API_URL||"https://api.vaif.studio";async function zo(e,o,n,s,c){let f=await fetch(`${L}/v1/projects/${o}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({table:n,records:s,truncate:c?.truncate??false})});if(!f.ok){let i=await f.text();throw new Error(`Failed to seed ${n}: ${i}`)}return f.json()}async function Bo(e,o){let n=await fetch(`${L}/v1/projects/${o}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!n.ok){let s=await n.text();throw new Error(`Failed to reset database: ${s}`)}return n.json()}function _(e){let o=[];if(!k.existsSync(e))return o;let n=k.readdirSync(e,{withFileTypes:true});for(let s of n)if(s.isFile()){let c=y.extname(s.name).toLowerCase();(c===".json"||c===".ts"||c===".js")&&o.push(y.join(e,s.name));}return o.sort()}async function so(e){let o=y.extname(e).toLowerCase();if(o===".json"){let n=k.readFileSync(e,"utf-8"),s=JSON.parse(n);return Array.isArray(s)?[{table:y.basename(e,o),data:s}]:s.table&&s.data?[s]:Object.entries(s).map(([c,f])=>({table:c,data:f}))}else if(o===".ts"||o===".js"){let n=await import(e),s=n.default||n;return typeof s=="function"?s():s}throw new Error(`Unsupported file format: ${o}`)}async function ro(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=e.projectId||c?.projectId||n.projectId;f||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(r.bold("VAIF Database Seed")),console.log("");let i=[];if(e.file){let p=y.resolve(e.file);k.existsSync(p)||(console.log(r.red(`File not found: ${e.file}`)),process.exit(1)),i=[p];}else {let p=y.resolve("seeds"),g=y.resolve("prisma/seed"),a=y.resolve("db/seeds");i=[..._(p),..._(g),..._(a)];}i.length===0&&(console.log(r.yellow("No seed files found")),console.log(r.gray(`
20
20
  Place your seed files in one of these directories:`)),console.log(r.gray(" - ./seeds/")),console.log(r.gray(" - ./prisma/seed/")),console.log(r.gray(" - ./db/seeds/")),console.log(r.gray(`
21
21
  Or specify a file with --file`)),console.log(r.gray(`
22
- Example seed file (seeds/users.json):`)),console.log(r.gray(" [")),console.log(r.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(r.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(r.gray(" ]")),process.exit(1)),console.log(r.gray("Seed files found:"));for(let p of c)console.log(r.gray(` - ${h.relative(process.cwd(),p)}`));if(console.log(""),e.truncate&&(console.log(r.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),e.dryRun){console.log(r.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let p of c){o.start(`Loading ${h.basename(p)}...`);try{let m=await Z(p);o.stop();for(let i of m)e.table&&i.table!==e.table||(console.log(r.cyan(`Table: ${i.table}`)),console.log(r.gray(` Records: ${i.data.length}`)),i.data.length>0&&console.log(r.gray(` Sample: ${JSON.stringify(i.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(m){o.fail(`Failed to load ${h.basename(p)}`),m instanceof Error&&console.log(r.red(` Error: ${m.message}`));}}return}let f=[];for(let p of c){o.start(`Processing ${h.basename(p)}...`);try{let m=await Z(p);o.stop();for(let i of m)if(!(e.table&&i.table!==e.table)){if(i.data.length===0){console.log(r.gray(` Skipping ${i.table} (no records)`));continue}o.start(`Seeding ${i.table} (${i.data.length} records)...`);try{let y=await Fe(n.token,l,i.table,i.data,{truncate:e.truncate});o.succeed(`Seeded ${i.table}: ${y.inserted} records`),f.push({table:i.table,inserted:y.inserted});}catch(y){let F=y instanceof Error?y.message:"Unknown error";o.fail(`Failed to seed ${i.table}`),f.push({table:i.table,inserted:0,error:F});}}}catch(m){o.fail(`Failed to load ${h.basename(p)}`),m instanceof Error&&console.log(r.red(` Error: ${m.message}`));}}console.log("");let a$1=f.reduce((p,m)=>p+m.inserted,0),v=f.filter(p=>p.error).length;if(v===0)console.log(r.green(`\u2713 Successfully seeded ${a$1} records across ${f.length} table(s)`));else {console.log(r.yellow(`Seeded ${a$1} records with ${v} error(s)`)),console.log(""),console.log(r.red("Errors:"));for(let p of f.filter(m=>m.error))console.log(r.red(` - ${p.table}: ${p.error}`));}console.log("");}async function te(e){let o=V(),n=I();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let t=e.config||"vaif.config.json",s=null;try{s=await a(t);}catch{}let l=e.projectId||s?.projectId||n.projectId;l||(console.log(r.red("No project ID specified")),process.exit(1)),console.log(""),console.log(r.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(r.red("This will:")),console.log(r.red(" - Drop all tables")),console.log(r.red(" - Delete all data")),console.log(r.red(" - Reset migrations")),console.log(""),console.log(r.red.bold("This action cannot be undone!")),console.log(""),e.force||(console.log(r.yellow("Use --force to confirm this action.")),process.exit(1)),o.start("Resetting database...");try{await Ae(n.token,l),o.succeed("Database reset complete"),console.log(""),console.log(r.gray("Your database is now empty.")),console.log(r.gray("Run `vaif push` to apply your schema, then `vaif db seed` to seed data.")),console.log("");}catch(c){o.fail("Failed to reset database"),c instanceof Error&&console.log(r.red(`
23
- Error: ${c.message}`)),process.exit(1);}}program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.0.2");program.command("login").description("Authenticate with VAIF").option("-t, --token <token>","API token (will prompt if not provided)").option("-p, --project-id <id>","Default project ID").action(U);program.command("logout").description("Log out and remove stored credentials").action(J);program.command("whoami").description("Show current authenticated user").action(z);program.command("init").description("Initialize VAIF configuration in your project").option("--typescript","Setup for TypeScript project").option("-f, --force","Overwrite existing config").action(c);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(B);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(Y);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(b);var se=program.command("functions").alias("fn").description("Manage serverless functions");se.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(K);se.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(X);var ie=program.command("db").description("Database management commands");ie.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(ne);ie.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(te);program.parse(process.argv);process.argv.slice(2).length||program.outputHelp();
22
+ Example seed file (seeds/users.json):`)),console.log(r.gray(" [")),console.log(r.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(r.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(r.gray(" ]")),process.exit(1)),console.log(r.gray("Seed files found:"));for(let p of i)console.log(r.gray(` - ${y.relative(process.cwd(),p)}`));if(console.log(""),e.truncate&&(console.log(r.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),e.dryRun){console.log(r.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let p of i){o.start(`Loading ${y.basename(p)}...`);try{let g=await so(p);o.stop();for(let a of g)e.table&&a.table!==e.table||(console.log(r.cyan(`Table: ${a.table}`)),console.log(r.gray(` Records: ${a.data.length}`)),a.data.length>0&&console.log(r.gray(` Sample: ${JSON.stringify(a.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(g){o.fail(`Failed to load ${y.basename(p)}`),g instanceof Error&&console.log(r.red(` Error: ${g.message}`));}}return}let t=[];for(let p of i){o.start(`Processing ${y.basename(p)}...`);try{let g=await so(p);o.stop();for(let a of g)if(!(e.table&&a.table!==e.table)){if(a.data.length===0){console.log(r.gray(` Skipping ${a.table} (no records)`));continue}o.start(`Seeding ${a.table} (${a.data.length} records)...`);try{let h=await zo(n.token,f,a.table,a.data,{truncate:e.truncate});o.succeed(`Seeded ${a.table}: ${h.inserted} records`),t.push({table:a.table,inserted:h.inserted});}catch(h){let $=h instanceof Error?h.message:"Unknown error";o.fail(`Failed to seed ${a.table}`),t.push({table:a.table,inserted:0,error:$});}}}catch(g){o.fail(`Failed to load ${y.basename(p)}`),g instanceof Error&&console.log(r.red(` Error: ${g.message}`));}}console.log("");let l=t.reduce((p,g)=>p+g.inserted,0),d=t.filter(p=>p.error).length;if(d===0)console.log(r.green(`\u2713 Successfully seeded ${l} records across ${t.length} table(s)`));else {console.log(r.yellow(`Seeded ${l} records with ${d} error(s)`)),console.log(""),console.log(r.red("Errors:"));for(let p of t.filter(g=>g.error))console.log(r.red(` - ${p.table}: ${p.error}`));}console.log("");}async function co(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=e.projectId||c?.projectId||n.projectId;f||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=y.resolve(e.dir||"./drizzle");if(console.log(""),console.log(r.bold("VAIF Database Push")),console.log(""),!k.existsSync(i)){let g=y.resolve("./migrations");k.existsSync(g)?console.log(r.gray(`Using migrations from: ${g}`)):(console.log(r.red(`Migrations directory not found: ${i}`)),console.log(r.gray(`
23
+ Expected one of:`)),console.log(r.gray(" - ./drizzle/")),console.log(r.gray(" - ./migrations/")),console.log(r.gray(`
24
+ Or specify with: vaif db push --dir <path>`)),process.exit(1));}let t=[],l=k.readdirSync(i,{withFileTypes:true});for(let g of l)if(g.isFile()&&g.name.endsWith(".sql"))t.push(y.join(i,g.name));else if(g.isDirectory()){let a=k.readdirSync(y.join(i,g.name),{withFileTypes:true});for(let h of a)h.isFile()&&h.name.endsWith(".sql")&&t.push(y.join(i,g.name,h.name));}t.sort(),t.length===0&&(console.log(r.yellow("No SQL migration files found")),process.exit(1)),console.log(r.gray(`Found ${t.length} migration(s):`));for(let g of t)console.log(r.gray(` - ${y.relative(process.cwd(),g)}`));if(console.log(""),e.dryRun){console.log(r.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let g of t){let a=k.readFileSync(g,"utf-8");console.log(r.cyan(`--- ${y.basename(g)} ---`)),console.log(r.gray(a.slice(0,500))),a.length>500&&console.log(r.gray("...")),console.log("");}return}let d=0,p=0;for(let g of t){let a=k.readFileSync(g,"utf-8"),h=y.relative(process.cwd(),g);o.start(`Applying ${h}...`);try{let $=await fetch(`${L}/v1/projects/${f}/schema/execute`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:a})});if(!$.ok){let F=await $.text();throw new Error(F)}o.succeed(`Applied ${h}`),d++;}catch($){let F=$ instanceof Error?$.message:"Unknown error";o.fail(`Failed ${h}: ${F}`),p++;}}console.log(""),console.log(p===0?r.green(`Successfully applied ${d} migration(s)`):r.yellow(`Applied ${d}, failed ${p} migration(s)`)),console.log("");}async function ao(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=e.projectId||c?.projectId||n.projectId;f||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=y.resolve(e.output||"vaif.schema.json");console.log(""),console.log(r.bold("VAIF Database Pull")),console.log(""),o.start("Pulling schema from remote...");try{let t=await fetch(`${L}/v1/projects/${f}/schema`,{headers:{Authorization:`Bearer ${n.token}`}});if(!t.ok){let p=await t.text();throw new Error(`Failed to pull schema: ${p}`)}let l=await t.json();k.writeFileSync(i,JSON.stringify(l,null,2),"utf-8"),o.succeed(`Schema written to ${y.relative(process.cwd(),i)}`);let d=l.tables?.length??Object.keys(l).length;console.log(r.gray(` ${d} table(s) pulled`)),console.log("");}catch(t){o.fail("Failed to pull schema"),t instanceof Error&&console.log(r.red(`
25
+ Error: ${t.message}`)),process.exit(1);}}async function lo(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=e.projectId||c?.projectId||n.projectId;f||(console.log(r.red("No project ID specified")),process.exit(1)),console.log(""),console.log(r.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(r.red("This will:")),console.log(r.red(" - Drop all tables")),console.log(r.red(" - Delete all data")),console.log(r.red(" - Reset migrations")),console.log(""),console.log(r.red.bold("This action cannot be undone!")),console.log(""),e.force||(console.log(r.yellow("Use --force to confirm this action.")),process.exit(1)),o.start("Resetting database...");try{await Bo(n.token,f),o.succeed("Database reset complete"),console.log(""),console.log(r.gray("Your database is now empty.")),console.log(r.gray("Run `vaif push` to apply your schema, then `vaif db seed` to seed data.")),console.log("");}catch(i){o.fail("Failed to reset database"),i instanceof Error&&console.log(r.red(`
26
+ Error: ${i.message}`)),process.exit(1);}}var fo=process.env.VAIF_API_URL||"https://api.vaif.studio";function po(e,o,n){return e.projectId||o?.projectId||n.projectId||null}async function uo(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=po(e,c,n);f||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=e.name||`cli-key-${Date.now()}`;console.log(""),console.log(r.bold("VAIF Generate API Key")),console.log(""),o.start("Generating API key...");try{let t=await fetch(`${fo}/v1/projects/${f}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i})});if(!t.ok){let d=await t.text();throw new Error(`Failed to generate key: ${d}`)}let l=await t.json();o.succeed("API key generated"),console.log(""),console.log(r.green(` Name: ${l.name}`)),console.log(r.green(` Key: ${l.key}`)),console.log(""),console.log(r.yellow.bold(" Save this key now - it will not be shown again!")),console.log("");}catch(t){o.fail("Failed to generate API key"),t instanceof Error&&console.log(r.red(`
27
+ Error: ${t.message}`)),process.exit(1);}}async function mo(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=po(e,c,n);f||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(r.bold("VAIF API Keys")),console.log(""),o.start("Fetching API keys...");try{let i=await fetch(`${fo}/v1/projects/${f}/api-keys`,{headers:{Authorization:`Bearer ${n.token}`}});if(!i.ok){let g=await i.text();throw new Error(`Failed to list keys: ${g}`)}let t=await i.json(),l=t.keys||t;if(o.stop(),!Array.isArray(l)||l.length===0){console.log(r.yellow("No API keys found")),console.log(r.gray(`
28
+ Generate one with: vaif keys generate`));return}let d=Math.max(8,...l.map(g=>(g.name||"").length)),p=` ${"Name".padEnd(d)} ${"Key".padEnd(24)} Created`;console.log(r.gray(p)),console.log(r.gray(" "+"-".repeat(p.length-2)));for(let g of l){let a=(g.name||"unnamed").padEnd(d),h=g.maskedKey||g.prefix||`${(g.key||"").slice(0,12)}...`,$=g.createdAt?new Date(g.createdAt).toLocaleDateString():"N/A";console.log(` ${a} ${h.padEnd(24)} ${$}`);}console.log(""),console.log(r.gray(` ${l.length} key(s) total`)),console.log("");}catch(i){o.fail("Failed to list API keys"),i instanceof Error&&console.log(r.red(`
29
+ Error: ${i.message}`)),process.exit(1);}}var ho=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ko(e){try{let o=new URL(e);return o.password&&(o.password="****"),o.toString()}catch{return e.replace(/:[^@/]+@/,":****@")}}async function yo(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=e.projectId||c?.projectId||n.projectId;f||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),o.start("Fetching project info...");try{let i=await fetch(`${ho}/v1/projects/${f}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!i.ok){let p=await i.text();throw new Error(`Failed to fetch project: ${p}`)}let t=await i.json();o.stop(),console.log(""),console.log(r.bold("VAIF Project Info")),console.log("");let l=16,d=(p,g)=>{console.log(` ${r.gray(p.padEnd(l))} ${g}`);};d("Name:",r.white(t.name||"N/A")),d("Project ID:",r.white(f)),d("Region:",r.white(t.region||"us-east-1")),d("Plan:",r.white(t.plan||t.tier||"free")),d("Created:",r.white(t.createdAt?new Date(t.createdAt).toLocaleDateString():"N/A")),console.log(""),d("API URL:",r.cyan(t.apiUrl||`${ho}/v1`)),d("WS URL:",r.cyan(t.wsUrl||t.realtimeUrl||"N/A")),d("DB URL:",r.cyan(t.databaseUrl?Ko(t.databaseUrl):"N/A")),d("Storage URL:",r.cyan(t.storageUrl||"N/A")),console.log("");}catch(i){o.fail("Failed to fetch project info"),i instanceof Error&&console.log(r.red(`
30
+ Error: ${i.message}`)),process.exit(1);}}var Go=process.env.VAIF_API_URL||"https://api.vaif.studio";async function jo(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=e.projectId||c?.projectId||n.projectId;f||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),o.start("Fetching project status...");try{let i=await fetch(`${Go}/v1/projects/${f}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${n.token}`}});if(!i.ok){let $=await i.text();throw new Error(`Failed to fetch project status: ${$}`)}let t=await i.json();o.stop(),console.log(""),console.log(r.bold("VAIF Project Status")),console.log("");let l=22,d=($,F)=>{console.log(` ${r.gray($.padEnd(l))} ${F}`);};d("Project:",r.white(t.name||f)),d("Plan:",r.white(t.plan||t.tier||"free")),console.log(""),console.log(r.gray(" --- Resources ---")),console.log("");let p=t.tableCount??t.tables?.length??"N/A",g=t.functionCount??t.functions?.length??"N/A",a=t.bucketCount??t.storage?.buckets?.length??"N/A",h=t.activeConnections??t.connections??"N/A";d("Tables:",r.white(String(p))),d("Functions:",r.white(String(g))),d("Storage Buckets:",r.white(String(a))),d("Active Connections:",r.white(String(h))),t.usage&&(console.log(""),console.log(r.gray(" --- Usage ---")),console.log(""),t.usage.dbSize&&d("Database Size:",r.white(t.usage.dbSize)),t.usage.storageSize&&d("Storage Size:",r.white(t.usage.storageSize)),t.usage.bandwidth&&d("Bandwidth:",r.white(t.usage.bandwidth)),t.usage.functionInvocations!=null&&d("Function Invocations:",r.white(String(t.usage.functionInvocations)))),console.log("");}catch(i){o.fail("Failed to fetch project status"),i instanceof Error&&console.log(r.red(`
31
+ Error: ${i.message}`)),process.exit(1);}}program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.1.0");program.command("login").description("Authenticate with VAIF").option("-t, --token <token>","API token (will prompt if not provided)").option("-p, --project-id <id>","Default project ID").action(G);program.command("logout").description("Log out and remove stored credentials").action(M);program.command("whoami").description("Show current authenticated user").action(W);program.command("init").description("Initialize VAIF configuration in your project").option("--typescript","Setup for TypeScript project").option("-f, --force","Overwrite existing config").action(c);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(yo);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(jo);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(Y);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(X);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(b);var wo=program.command("functions").alias("fn").description("Manage serverless functions");wo.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(to);wo.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(io);var T=program.command("db").description("Database management commands");T.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(co);T.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(ao);T.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(ro);T.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(lo);var vo=program.command("keys").description("Manage API keys");vo.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(uo);vo.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(mo);program.parse(process.argv);process.argv.slice(2).length||program.outputHelp();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vaiftech/cli",
3
- "version": "1.0.5",
3
+ "version": "1.1.0",
4
4
  "description": "VAIF CLI - Type generation and development tools",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",