@vaiftech/cli 1.6.6 → 1.7.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.
- package/README.md +1 -1
- package/dist/cli.cjs +46 -46
- package/dist/cli.js +30 -30
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
[](https://www.npmjs.com/package/@vaiftech/cli)
|
|
4
4
|
[](https://opensource.org/licenses/MIT)
|
|
5
5
|
|
|
6
|
-
Command-line tools for [VAIF Studio](https://vaif.studio) (v1.
|
|
6
|
+
Command-line tools for [VAIF Studio](https://vaif.studio) (v1.7.0) — scaffold full projects from templates with feature selection, browser-based authentication, manage schemas, deploy functions, generate TypeScript types, and more.
|
|
7
7
|
|
|
8
8
|
## Installation
|
|
9
9
|
|
package/dist/cli.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';require('dotenv/config');var commander=require('commander'),
|
|
2
|
+
'use strict';require('dotenv/config');var commander=require('commander'),f=require('chalk'),L=require('fs'),A=require('path'),lt=require('pg'),H=require('ora'),dt=require('prettier'),st=require('dotenv'),Ae=require('readline'),bt=require('os'),child_process=require('child_process');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var f__default=/*#__PURE__*/_interopDefault(f);var L__default=/*#__PURE__*/_interopDefault(L);var A__default=/*#__PURE__*/_interopDefault(A);var lt__default=/*#__PURE__*/_interopDefault(lt);var H__default=/*#__PURE__*/_interopDefault(H);var dt__default=/*#__PURE__*/_interopDefault(dt);var st__default=/*#__PURE__*/_interopDefault(st);var Ae__default=/*#__PURE__*/_interopDefault(Ae);var bt__default=/*#__PURE__*/_interopDefault(bt);st__default.default.config();async function I(t){let e=A__default.default.resolve(t);if(!L__default.default.existsSync(e))return null;try{let o=L__default.default.readFileSync(e,"utf-8"),n=JSON.parse(o);return n.database?.url&&(n.database.url=ve(n.database.url)),n.api?.apiKey&&(n.api.apiKey=ve(n.api.apiKey)),n}catch{throw new Error(`Failed to parse config file: ${t}`)}}function ve(t){return t.replace(/\$\{([^}]+)\}/g,(e,o)=>process.env[o]||e)}async function ut(t,e){let o=await t.query(`
|
|
3
3
|
SELECT table_name, table_type
|
|
4
4
|
FROM information_schema.tables
|
|
5
5
|
WHERE table_schema = $1
|
|
@@ -45,9 +45,9 @@
|
|
|
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]),i=new Map;for(let l of o.rows)i.set(l.table_name,[]);for(let l of n.rows){let c=i.get(l.table_name);c&&c.push(l);}let a=new Map;for(let l of s.rows){let c=a.get(l.enum_name)||[];c.push(l.enum_value),a.set(l.enum_name,c);}return {tables:i,enums:a,foreignKeys:r.rows}}var
|
|
48
|
+
`,[e]),i=new Map;for(let l of o.rows)i.set(l.table_name,[]);for(let l of n.rows){let c=i.get(l.table_name);c&&c.push(l);}let a=new Map;for(let l of s.rows){let c=a.get(l.enum_name)||[];c.push(l.enum_value),a.set(l.enum_name,c);}return {tables:i,enums:a,foreignKeys:r.rows}}var ie={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 pt(t,e){let{data_type:o,udt_name:n,is_nullable:r}=t;if(e.has(n)){let a=e.get(n).map(l=>`"${l}"`).join(" | ");return r==="YES"?`(${a}) | null`:a}if(o==="ARRAY"){let i=n.replace(/^_/,"");if(e.has(i)){let c=e.get(i).map(d=>`"${d}"`).join(" | ");return r==="YES"?`(${c})[] | null`:`(${c})[]`}let a=ie[i]||"unknown";return r==="YES"?`${a}[] | null`:`${a}[]`}let s=ie[o]||ie[n]||"unknown";return r==="YES"&&(s=`${s} | null`),s}function re(t){return t.split(/[_\-\s]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function ft(t,e){let o=re(t),n=e.map(r=>` | "${r}"`).join(`
|
|
49
49
|
`);return `export type ${o} =
|
|
50
|
-
${n};`}function
|
|
50
|
+
${n};`}function gt(t,e,o){let n=re(t),r=[],s=[],i=[];for(let d of e){let p=pt(d,o),u=d.column_name,m=d.column_default!==null||d.is_identity==="YES",y=d.is_nullable==="YES";r.push(` ${u}: ${p};`),m||d.column_name==="id"?s.push(` ${u}?: ${p.replace(" | null","")} | null;`):y?s.push(` ${u}?: ${p};`):s.push(` ${u}: ${p.replace(" | null","")};`),i.push(` ${u}?: ${p.replace(" | null","")} | null;`);}let a=`export interface ${n} {
|
|
51
51
|
${r.join(`
|
|
52
52
|
`)}
|
|
53
53
|
}`,l=`export interface ${n}Insert {
|
|
@@ -56,11 +56,11 @@ ${s.join(`
|
|
|
56
56
|
}`,c=`export interface ${n}Update {
|
|
57
57
|
${i.join(`
|
|
58
58
|
`)}
|
|
59
|
-
}`;return {base:a,insert:l,update:c}}function
|
|
60
|
-
`)}async function
|
|
61
|
-
Provide a connection string via:`)),console.log(f__default.default.gray(" --connection <url>")),console.log(f__default.default.gray(" DATABASE_URL environment variable")),console.log(f__default.default.gray(" vaif.config.json database.url")),process.exit(1)),e.text="Connecting to database...";let r=new
|
|
59
|
+
}`;return {base:a,insert:l,update:c}}function mt(t,e,o){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[s,i]of e)n.push(ft(s,i)),n.push("");}n.push("// ============ TABLES ============"),n.push("");let r=[];for(let[s,i]of t){let{base:a,insert:l,update:c}=gt(s,i,e);r.push(s),n.push(a),n.push(""),n.push(l),n.push(""),n.push(c),n.push("");}n.push("// ============ DATABASE SCHEMA ============"),n.push(""),n.push("export interface Database {");for(let s of r){let i=re(s);n.push(` ${s}: {`),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 Ie(t){let e=H__default.default("Loading configuration...").start();try{let o=await I(t.config),n=t.connection||o?.database?.url||process.env.DATABASE_URL;n||(e.fail("No database connection string provided"),console.log(f__default.default.yellow(`
|
|
61
|
+
Provide a connection string via:`)),console.log(f__default.default.gray(" --connection <url>")),console.log(f__default.default.gray(" DATABASE_URL environment variable")),console.log(f__default.default.gray(" vaif.config.json database.url")),process.exit(1)),e.text="Connecting to database...";let r=new lt__default.default.Client({connectionString:n});await r.connect(),e.text="Introspecting schema...";let{tables:s,enums:i,foreignKeys:a}=await ut(r,t.schema);if(await r.end(),s.size===0){e.warn(`No tables found in schema "${t.schema}"`);return}e.text=`Generating types for ${s.size} tables...`;let l=mt(s,i,a),c=await dt__default.default.format(l,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100});if(t.dryRun){e.succeed("Generated types (dry run):"),console.log(""),console.log(f__default.default.gray("\u2500".repeat(60))),console.log(c),console.log(f__default.default.gray("\u2500".repeat(60)));return}let d=A__default.default.resolve(t.output),p=A__default.default.dirname(d);L__default.default.existsSync(p)||L__default.default.mkdirSync(p,{recursive:!0}),L__default.default.writeFileSync(d,c,"utf-8"),e.succeed(`Generated types for ${s.size} tables \u2192 ${f__default.default.cyan(t.output)}`),console.log(""),console.log(f__default.default.green("Generated:")),console.log(f__default.default.gray(` Tables: ${s.size}`)),console.log(f__default.default.gray(` Enums: ${i.size}`)),console.log(""),console.log(f__default.default.gray("Import in your code:")),console.log(f__default.default.cyan(` import type { Database, Row, Insert, Update } from "${t.output.replace(/\.ts$/,"")}";`));}catch(o){e.fail("Failed to generate types"),o instanceof Error&&(console.error(f__default.default.red(`
|
|
62
62
|
Error: ${o.message}`)),o.message.includes("ECONNREFUSED")&&console.log(f__default.default.yellow(`
|
|
63
|
-
Make sure your database is running and accessible.`))),process.exit(1);}}var
|
|
63
|
+
Make sure your database is running and accessible.`))),process.exit(1);}}var B=[{name:"database",label:"Database",description:"CRUD queries, type-safe operations"},{name:"auth",label:"Authentication",description:"login, signup, OAuth, sessions"},{name:"realtime",label:"Realtime",description:"live subscriptions, presence"},{name:"storage",label:"Storage",description:"file uploads, signed URLs"},{name:"functions",label:"Functions",description:"serverless function calls"}],we={"nextjs-fullstack":{name:"Next.js Full-Stack",description:"Next.js app with server/client VAIF client, auth middleware, and React hooks",tag:"Next.js",defaultFeatures:["database","auth"],files:[{path:"package.json",content:`{
|
|
64
64
|
"name": "my-vaif-app",
|
|
65
65
|
"private": true,
|
|
66
66
|
"version": "0.1.0",
|
|
@@ -3689,56 +3689,56 @@ export const posts = pgTable("posts", {
|
|
|
3689
3689
|
|
|
3690
3690
|
return Response.json({ message: \`Hello, \${name}!\` });
|
|
3691
3691
|
}
|
|
3692
|
-
`}]},dependencies:["@vaiftech/client","@vaiftech/auth"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create a 'product-images' storage bucket in your VAIF dashboard","Import storage helpers from '@/lib/storage' in your API routes","Use uploadProductImage() in your product creation flow","Run: npx vaif generate to generate TypeScript types"]}};function
|
|
3693
|
-
? Which VAIF features do you want to include?`)),
|
|
3692
|
+
`}]},dependencies:["@vaiftech/client","@vaiftech/auth"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create a 'product-images' storage bucket in your VAIF dashboard","Import storage helpers from '@/lib/storage' in your API routes","Use uploadProductImage() in your product creation flow","Run: npx vaif generate to generate TypeScript types"]}};function Se(){console.log(""),console.log(f__default.default.bold("Available project templates")),console.log("");let t=26,e=22;console.log(` ${f__default.default.gray("Template".padEnd(t))}${f__default.default.gray("Stack".padEnd(e))}${f__default.default.gray("Description")}`),console.log(f__default.default.gray(" "+"-".repeat(t+e+40)));for(let[o,n]of Object.entries(we))console.log(` ${f__default.default.cyan(o.padEnd(t))}${f__default.default.yellow(n.tag.padEnd(e))}${f__default.default.white(n.description)}`);console.log(""),console.log(f__default.default.gray("Usage:")),console.log(f__default.default.gray(" npx @vaiftech/cli init --template <name>")),console.log(f__default.default.gray(" npx @vaiftech/cli init -t nextjs-fullstack")),console.log(f__default.default.gray(" npx @vaiftech/cli init -t react-spa --features auth,database,realtime")),console.log(""),console.log(f__default.default.gray("Available features: auth, database, realtime, storage, functions")),console.log("");}async function ht(t){if(!process.stdin.isTTY||!process.stdout.isTTY)return t;let e=new Set(t.map(n=>B.findIndex(r=>r.name===n)).filter(n=>n>=0)),o=0;return new Promise(n=>{let r=Ae__default.default.createInterface({input:process.stdin,output:process.stdout});Ae__default.default.emitKeypressEvents(process.stdin,r),process.stdin.setRawMode&&process.stdin.setRawMode(true);function s(){let a=B.length+2;process.stdout.write(`\x1B[${a}A`),i();}function i(){console.log(f__default.default.bold(`
|
|
3693
|
+
? Which VAIF features do you want to include?`)),B.forEach((a,l)=>{let c=e.has(l)?f__default.default.green("[x]"):"[ ]",d=l===o?f__default.default.cyan("> "):" ";console.log(`${d}${c} ${a.label} ${f__default.default.gray(`(${a.description})`)}`);}),console.log(f__default.default.gray(" (up/down to move, space to toggle, enter to confirm)"));}i(),process.stdin.on("keypress",(a,l)=>{if(l.name==="up"&&o>0)o--,s();else if(l.name==="down"&&o<B.length-1)o++,s();else if(l.name==="space")e.has(o)?e.delete(o):e.add(o),s();else if(l.name==="return"){process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close();let c=[...e].sort().map(d=>B[d].name);n(c.length>0?c:t);}else l.name==="c"&&l.ctrl&&(process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close(),process.exit(0));});})}async function le(t,e={}){let o=we[t];o||(console.log(f__default.default.red(`
|
|
3694
3694
|
Unknown template: ${t}`)),console.log(f__default.default.yellow(`Run 'vaif templates' to see available templates.
|
|
3695
|
-
`)),process.exit(1));let n;e.features&&e.features.length>0?n=e.features.filter(c=>
|
|
3696
|
-
No features specified.`)),console.log(f__default.default.yellow("Usage: vaif init --template <name> --add-features <features>")),console.log(f__default.default.gray("Available features: auth, database, realtime, storage, functions")),process.exit(1)):o.featureFiles&&Object.keys(o.featureFiles).length>0?n=await
|
|
3697
|
-
`,"utf-8"),console.log(f__default.default.green(` merge ${c.path} (added dependencies)`)),s++;continue}catch{}if(
|
|
3698
|
-
`,"utf-8");}catch{}(o.dependencies?.length||o.devDependencies?.length)&&(console.log(""),console.log(f__default.default.bold("Install dependencies:")),o.dependencies?.length&&console.log(f__default.default.cyan(` npm install ${o.dependencies.join(" ")}`)),o.devDependencies?.length&&console.log(f__default.default.cyan(` npm install -D ${o.devDependencies.join(" ")}`))),console.log(""),console.log(f__default.default.bold.green("Project scaffolded successfully!")),console.log(""),console.log(f__default.default.bold(" Next steps:")),o.postInstructions.forEach(c=>{console.log(f__default.default.gray(` ${c}`));}),console.log(""),console.log(f__default.default.gray(" Get your project credentials at https://vaif.studio/app/security/api-keys")),console.log("");}var
|
|
3699
|
-
--add-features requires --template to know which template to use.`)),console.log(f__default.default.gray("Example: vaif init --template react-spa --add-features functions,storage")),process.exit(1));let n=t.addFeatures.split(",").map(r=>r.trim());await
|
|
3700
|
-
Use --force to overwrite existing configuration.`)),process.exit(1));try{if(
|
|
3695
|
+
`)),process.exit(1));let n;e.features&&e.features.length>0?n=e.features.filter(c=>B.some(d=>d.name===c)):e.addOnly?(console.log(f__default.default.red(`
|
|
3696
|
+
No features specified.`)),console.log(f__default.default.yellow("Usage: vaif init --template <name> --add-features <features>")),console.log(f__default.default.gray("Available features: auth, database, realtime, storage, functions")),process.exit(1)):o.featureFiles&&Object.keys(o.featureFiles).length>0?n=await ht(o.defaultFeatures??["database","auth"]):n=o.defaultFeatures??[],e.addOnly?(console.log(""),console.log(f__default.default.bold(`Adding features to ${f__default.default.cyan(o.name)} project...`)),console.log(f__default.default.gray(` Features: ${n.join(", ")}`)),console.log("")):(console.log(""),console.log(f__default.default.bold(`Scaffolding ${f__default.default.cyan(o.name)} template...`)),n.length>0&&console.log(f__default.default.gray(` Features: ${n.join(", ")}`)),console.log(""));let r=e.addOnly?[]:[...o.files];if(o.featureFiles)for(let c of n){let d=o.featureFiles[c];d&&r.push(...d);}let s=0,i=0;for(let c of r){let d=A__default.default.resolve(c.path),p=A__default.default.dirname(d);if(L__default.default.existsSync(p)||L__default.default.mkdirSync(p,{recursive:true}),c.path==="package.json"&&L__default.default.existsSync(d)&&!e.force)try{let u=JSON.parse(L__default.default.readFileSync(d,"utf-8")),m=JSON.parse(c.content),y=D=>{if(!D)return {};let M={};for(let[z,J]of Object.entries(D))!J.startsWith("workspace:")&&!J.startsWith("link:")&&!J.startsWith("file:")&&(M[z]=J);return M};u.dependencies={...y(u.dependencies),...m.dependencies||{}},u.devDependencies={...y(u.devDependencies),...m.devDependencies||{}},m.scripts&&(u.scripts={...u.scripts||{},...m.scripts}),L__default.default.writeFileSync(d,JSON.stringify(u,null,2)+`
|
|
3697
|
+
`,"utf-8"),console.log(f__default.default.green(` merge ${c.path} (added dependencies)`)),s++;continue}catch{}if(L__default.default.existsSync(d)&&!e.force){console.log(f__default.default.yellow(` skip ${c.path} (already exists)`)),i++;continue}L__default.default.writeFileSync(d,c.content,"utf-8"),console.log(f__default.default.green(` create ${c.path}`)),s++;}console.log(""),s>0&&console.log(f__default.default.green(`Created ${s} file${s!==1?"s":""}.`)),i>0&&console.log(f__default.default.yellow(`Skipped ${i} file${i!==1?"s":""} (use --force to overwrite).`));let a={auth:{"@vaiftech/auth":"^1.0.0"},database:{},realtime:{},storage:{},functions:{}},l=A__default.default.resolve("package.json");if(L__default.default.existsSync(l)&&n.length>0)try{let c=JSON.parse(L__default.default.readFileSync(l,"utf-8")),d=!1;for(let p of n){let u=a[p];if(u)for(let[m,y]of Object.entries(u))c.dependencies?.[m]||(c.dependencies=c.dependencies||{},c.dependencies[m]=y,d=!0);}d&&L__default.default.writeFileSync(l,JSON.stringify(c,null,2)+`
|
|
3698
|
+
`,"utf-8");}catch{}(o.dependencies?.length||o.devDependencies?.length)&&(console.log(""),console.log(f__default.default.bold("Install dependencies:")),o.dependencies?.length&&console.log(f__default.default.cyan(` npm install ${o.dependencies.join(" ")}`)),o.devDependencies?.length&&console.log(f__default.default.cyan(` npm install -D ${o.devDependencies.join(" ")}`))),console.log(""),console.log(f__default.default.bold.green("Project scaffolded successfully!")),console.log(""),console.log(f__default.default.bold(" Next steps:")),o.postInstructions.forEach(c=>{console.log(f__default.default.gray(` ${c}`));}),console.log(""),console.log(f__default.default.gray(" Get your project credentials at https://vaif.studio/app/security/api-keys")),console.log("");}var vt={$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 Ee(t){if(t.addFeatures){t.template||(console.log(f__default.default.red(`
|
|
3699
|
+
--add-features requires --template to know which template to use.`)),console.log(f__default.default.gray("Example: vaif init --template react-spa --add-features functions,storage")),process.exit(1));let n=t.addFeatures.split(",").map(r=>r.trim());await le(t.template,{force:t.force,features:n,addOnly:true});return}let e=H__default.default("Initializing VAIF configuration...").start(),o=A__default.default.resolve("vaif.config.json");L__default.default.existsSync(o)&&!t.force&&(e.fail("vaif.config.json already exists"),console.log(f__default.default.yellow(`
|
|
3700
|
+
Use --force to overwrite existing configuration.`)),process.exit(1));try{if(L__default.default.writeFileSync(o,JSON.stringify(vt,null,2),"utf-8"),e.succeed("Created vaif.config.json"),t.template){let n=t.features?t.features.split(",").map(r=>r.trim()):void 0;await le(t.template,{force:t.force,features:n});}else {let n=A__default.default.resolve(".env.example");if(L__default.default.existsSync(n)||(L__default.default.writeFileSync(n,`# VAIF Configuration
|
|
3701
3701
|
DATABASE_URL=postgresql://user:password@localhost:5432/database
|
|
3702
3702
|
VAIF_API_KEY=your-api-key
|
|
3703
|
-
`,"utf-8"),console.log(f__default.default.gray("Created .env.example"))),t.typescript){let r=A__default.default.resolve("src/types");
|
|
3704
|
-
Error: ${n.message}`)),process.exit(1);}}var
|
|
3703
|
+
`,"utf-8"),console.log(f__default.default.gray("Created .env.example"))),t.typescript){let r=A__default.default.resolve("src/types");L__default.default.existsSync(r)||(L__default.default.mkdirSync(r,{recursive:!0}),console.log(f__default.default.gray("Created src/types directory")));}console.log(""),console.log(f__default.default.green("VAIF initialized successfully!")),console.log(""),console.log(f__default.default.gray("Next steps:")),console.log(f__default.default.gray(" 1. Update vaif.config.json with your project ID")),console.log(f__default.default.gray(" 2. Set DATABASE_URL in your environment")),console.log(f__default.default.gray(" 3. Run: npx vaif generate")),console.log("");}}catch(n){e.fail("Failed to initialize"),n instanceof Error&&console.error(f__default.default.red(`
|
|
3704
|
+
Error: ${n.message}`)),process.exit(1);}}var de=A__default.default.join(bt__default.default.homedir(),".vaif"),$=A__default.default.join(de,"auth.json"),G=process.env.VAIF_API_URL||"https://api.vaif.studio";function At(){L__default.default.existsSync(de)||L__default.default.mkdirSync(de,{recursive:true});}function Te(t){At(),L__default.default.writeFileSync($,JSON.stringify(t,null,2),"utf-8"),L__default.default.chmodSync($,384);}function S(){if(!L__default.default.existsSync($))return null;try{let t=L__default.default.readFileSync($,"utf-8");return JSON.parse(t)}catch{return null}}function wt(t){let e=Ae__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}function St(t){return new Promise(e=>{let o=Ae__default.default.createInterface({input:process.stdin,output:process.stdout});process.stdin;let r=process.stdout.write.bind(process.stdout),s=false;process.stdout.write=((...i)=>s?true:r(...i)),o.question(t,i=>{s=false,process.stdout.write=r,console.log(""),o.close(),e(i);}),s=true;})}function Et(t){let e=process.platform,o;e==="darwin"?o=`open "${t}"`:e==="win32"?o=`start "" "${t}"`:o=`xdg-open "${t}"`,child_process.exec(o,n=>{});}function xt(t){return new Promise(e=>setTimeout(e,t))}async function _t(t){try{let e=await fetch(`${G}/auth/me`,{headers:{Authorization:`Bearer ${t}`}});if(e.ok){let o=await e.json();return {valid:!0,email:o.user?.email||o.email}}return {valid:!1}}catch{return {valid:false}}}async function Tt(t){let e=H__default.default();e.start("Setting up authentication...");let o,n;try{let a=await fetch(`${G}/auth/cli/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});a.ok||(e.fail("Failed to initiate authentication"),console.log(f__default.default.red(`
|
|
3705
3705
|
Could not connect to VAIF API. Please try again later.`)),process.exit(1));let l=await a.json();o=l.code,n=l.url;}catch{e.fail("Failed to connect to VAIF API"),console.log(f__default.default.red(`
|
|
3706
|
-
Could not connect to VAIF API.`)),console.log(f__default.default.gray("Check your internet connection or try: vaif login --email")),process.exit(1);}e.stop(),console.log(f__default.default.cyan(" Opening browser for authentication...")),console.log(""),console.log(f__default.default.gray(" If the browser doesn't open, visit this URL:")),console.log(f__default.default.white(` ${n}`)),console.log(""),
|
|
3707
|
-
The authentication session expired. Please try again.`)),process.exit(1));continue}let l=await a.json();if(l.ok&&l.accessToken){let c={token:l.accessToken,email:l.user?.email,projectId:t,expiresAt:new Date(Date.now()+l.expiresIn*1e3).toISOString()};
|
|
3708
|
-
Timed out waiting for browser authentication.`)),console.log(f__default.default.gray("Try again or use: vaif login --email")),process.exit(1);}async function
|
|
3709
|
-
No email provided. Login cancelled.`)),process.exit(1));let o=await
|
|
3710
|
-
No password provided. Login cancelled.`)),process.exit(1));let n=
|
|
3711
|
-
${s.message||"Invalid email or password."}`)),process.exit(1));let i={token:s.accessToken,email:s.user?.email,projectId:t,expiresAt:new Date(Date.now()+s.expiresIn*1e3).toISOString()};
|
|
3712
|
-
Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function
|
|
3713
|
-
Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Authenticated"),console.log(""),console.log(f__default.default.green(` Email: ${n||t.email||"Unknown"}`)),t.projectId&&console.log(f__default.default.green(` Project: ${t.projectId}`)),console.log("");}var
|
|
3706
|
+
Could not connect to VAIF API.`)),console.log(f__default.default.gray("Check your internet connection or try: vaif login --email")),process.exit(1);}e.stop(),console.log(f__default.default.cyan(" Opening browser for authentication...")),console.log(""),console.log(f__default.default.gray(" If the browser doesn't open, visit this URL:")),console.log(f__default.default.white(` ${n}`)),console.log(""),Et(n),e.start("Waiting for browser authentication...");let r=12e4,s=2e3,i=Date.now();for(;Date.now()-i<r;){await xt(s);try{let a=await fetch(`${G}/auth/cli/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:o})});if(!a.ok){let c=await a.json();(c.error==="ExpiredCode"||c.error==="InvalidCode")&&(e.fail("Authentication expired"),console.log(f__default.default.red(`
|
|
3707
|
+
The authentication session expired. Please try again.`)),process.exit(1));continue}let l=await a.json();if(l.ok&&l.accessToken){let c={token:l.accessToken,email:l.user?.email,projectId:t,expiresAt:new Date(Date.now()+l.expiresIn*1e3).toISOString()};Te(c),e.succeed("Logged in successfully"),console.log(""),l.user?.email&&console.log(f__default.default.green(` Authenticated as: ${l.user.email}`)),console.log(f__default.default.gray(` Config saved to: ${$}`)),console.log("");return}}catch{}}e.fail("Authentication timed out"),console.log(f__default.default.red(`
|
|
3708
|
+
Timed out waiting for browser authentication.`)),console.log(f__default.default.gray("Try again or use: vaif login --email")),process.exit(1);}async function Ft(t){console.log(""),console.log(f__default.default.bold("VAIF CLI Login")),console.log(f__default.default.gray("Enter your VAIF account credentials")),console.log("");let e=await wt(f__default.default.cyan(" Email: "));(!e||e.trim()==="")&&(console.log(f__default.default.red(`
|
|
3709
|
+
No email provided. Login cancelled.`)),process.exit(1));let o=await St(f__default.default.cyan(" Password: "));(!o||o.trim()==="")&&(console.log(f__default.default.red(`
|
|
3710
|
+
No password provided. Login cancelled.`)),process.exit(1));let n=H__default.default("Authenticating...").start();try{let r=await fetch(`${G}/auth/cli/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e.trim(),password:o})}),s=await r.json();(!r.ok||!s.ok)&&(n.fail("Login failed"),console.log(f__default.default.red(`
|
|
3711
|
+
${s.message||"Invalid email or password."}`)),process.exit(1));let i={token:s.accessToken,email:s.user?.email,projectId:t,expiresAt:new Date(Date.now()+s.expiresIn*1e3).toISOString()};Te(i),n.succeed("Logged in successfully"),console.log(""),s.user?.email&&console.log(f__default.default.green(` Authenticated as: ${s.user.email}`)),console.log(f__default.default.gray(` Config saved to: ${$}`)),console.log("");}catch{n.fail("Failed to connect to VAIF API"),console.log(f__default.default.red(`
|
|
3712
|
+
Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function Fe(t){console.log(""),console.log(f__default.default.bold("Welcome to VAIF CLI")),console.log(f__default.default.gray("Authenticate to access your VAIF projects")),console.log(""),t.email?await Ft(t.projectId):await Tt(t.projectId),console.log(f__default.default.gray("You can now use VAIF CLI commands like:")),console.log(f__default.default.gray(" vaif pull - Pull remote schema")),console.log(f__default.default.gray(" vaif push - Push schema changes")),console.log(f__default.default.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function Pe(){L__default.default.existsSync($)?(L__default.default.unlinkSync($),console.log(f__default.default.green("Logged out successfully"))):console.log(f__default.default.yellow("Not currently logged in"));}async function je(){let t=S();(!t||!t.token)&&(console.log(f__default.default.yellow("Not logged in")),console.log(f__default.default.gray("Run `vaif login` to authenticate")),process.exit(1));let e=H__default.default("Checking authentication...").start(),{valid:o,email:n}=await _t(t.token);o||(e.fail("Session expired"),console.log(f__default.default.yellow(`
|
|
3713
|
+
Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Authenticated"),console.log(""),console.log(f__default.default.green(` Email: ${n||t.email||"Unknown"}`)),t.projectId&&console.log(f__default.default.green(` Project: ${t.projectId}`)),console.log("");}var Rt=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Nt(t,e,o="public"){let n=await fetch(`${Rt}/v1/projects/${e}/schema?schema=${o}`,{headers:{Authorization:`Bearer ${t}`,"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 Ce(t){let e=H__default.default(),o=S();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await I(n);}catch(i){e.fail("Failed to load config"),console.log(f__default.default.red(`
|
|
3714
3714
|
Error: ${i}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(f__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let s=t.projectId||r.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
|
|
3715
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let i=t.schema||r.database?.schema||"public",a=await
|
|
3716
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
3715
|
+
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let i=t.schema||r.database?.schema||"public",a=await Nt(o.token,s,i);e.succeed("Schema fetched successfully");let l=t.output||A__default.default.resolve("vaif.schema.json"),c={$schema:"https://vaif.studio/schemas/schema.json",projectId:s,schema:i,pulledAt:new Date().toISOString(),...a};L__default.default.writeFileSync(l,JSON.stringify(c,null,2),"utf-8"),console.log(""),console.log(f__default.default.green(`Schema saved to: ${l}`)),console.log(""),console.log(f__default.default.gray("Schema summary:")),console.log(f__default.default.gray(` Tables: ${(a.tables||[]).length}`)),console.log(f__default.default.gray(` Enums: ${(a.enums||[]).length}`)),console.log(f__default.default.gray(` Functions: ${(a.functions||[]).length}`)),console.log(""),console.log(f__default.default.gray("Next steps:")),console.log(f__default.default.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(f__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(f__default.default.red(`
|
|
3716
|
+
Error: ${i.message}`)),process.exit(1);}}var Ne=process.env.VAIF_API_URL||"https://api.vaif.studio";function kt(t){let e=Ae__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}async function Ut(t,e,o){let n=await fetch(`${Ne}/v1/projects/${e}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!n.ok){let r=await n.text();throw new Error(`Failed to preview changes: ${r}`)}return n.json()}async function $t(t,e,o){let n=await fetch(`${Ne}/v1/projects/${e}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!n.ok){let r=await n.text();throw new Error(`Failed to apply changes: ${r}`)}return n.json()}function Ot(t){if(console.log(""),console.log(f__default.default.bold("Schema Changes:")),console.log(""),t.added.length===0&&t.modified.length===0&&t.removed.length===0){console.log(f__default.default.gray(" No changes detected. Schema is up to date."));return}if(t.added.length>0){console.log(f__default.default.green.bold(" + Added:"));for(let e of t.added)console.log(f__default.default.green(` + ${e.type}: ${e.name}`));console.log("");}if(t.modified.length>0){console.log(f__default.default.yellow.bold(" ~ Modified:"));for(let e of t.modified){console.log(f__default.default.yellow(` ~ ${e.type}: ${e.name}`));for(let o of e.changes)console.log(f__default.default.gray(` ${o}`));}console.log("");}if(t.removed.length>0){console.log(f__default.default.red.bold(" - Removed:"));for(let e of t.removed)console.log(f__default.default.red(` - ${e.type}: ${e.name}`));console.log("");}}async function De(t){let e=H__default.default(),o=S();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await I(n);}catch(l){e.fail("Failed to load config"),console.log(f__default.default.red(`
|
|
3717
3717
|
Error: ${l}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(f__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let s=t.projectId||r.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
|
|
3718
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=t.schema||A__default.default.resolve("vaif.schema.json");
|
|
3719
|
-
Expected schema file at: ${i}`)),console.log(f__default.default.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let a;try{let l=
|
|
3720
|
-
Error: ${l.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:l,sql:c}=await
|
|
3721
|
-
Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let d=await
|
|
3722
|
-
Error: ${l.message}`)),process.exit(1);}}var
|
|
3718
|
+
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=t.schema||A__default.default.resolve("vaif.schema.json");L__default.default.existsSync(i)||(e.fail("No local schema found"),console.log(f__default.default.yellow(`
|
|
3719
|
+
Expected schema file at: ${i}`)),console.log(f__default.default.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let a;try{let l=L__default.default.readFileSync(i,"utf-8");a=JSON.parse(l);}catch(l){e.fail("Failed to parse schema file"),l instanceof Error&&console.log(f__default.default.red(`
|
|
3720
|
+
Error: ${l.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:l,sql:c}=await Ut(o.token,s,a);if(e.stop(),Ot(l),l.added.length===0&&l.modified.length===0&&l.removed.length===0){console.log("");return}if(c.length>0){console.log(f__default.default.bold("SQL Migrations:")),console.log("");for(let p of c)console.log(f__default.default.gray(` ${p}`));console.log("");}if(t.dryRun){console.log(f__default.default.yellow("Dry run mode - no changes applied.")),console.log(f__default.default.gray("Remove --dry-run to apply these changes."));return}if(!t.force){l.removed.length>0&&(console.log(f__default.default.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(f__default.default.red(" This action cannot be undone!")),console.log(""));let u=await kt(f__default.default.cyan("Apply these changes? [y/N] "));if(u.toLowerCase()!=="y"&&u.toLowerCase()!=="yes"){console.log(f__default.default.yellow(`
|
|
3721
|
+
Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let d=await $t(o.token,s,a);if(d.success){if(e.succeed("Schema changes applied successfully"),console.log(""),d.migrations.length>0){console.log(f__default.default.gray("Migrations applied:"));for(let p of d.migrations)console.log(f__default.default.gray(` - ${p}`));console.log("");}console.log(f__default.default.green("Your database schema is now up to date.")),console.log(f__default.default.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else e.fail("Failed to apply some changes");}catch(l){e.fail("Failed to push schema changes"),l instanceof Error&&console.log(f__default.default.red(`
|
|
3722
|
+
Error: ${l.message}`)),process.exit(1);}}var W=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Mt(t,e,o,n){let r=new URL(`${W}/functions/project/${e}`);n&&r.searchParams.set("envId",n);let s=await fetch(r.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!s.ok)return null;let i=await s.json(),a=i.functions||i;return Array.isArray(a)&&a.find(l=>l.name===o)||null}async function zt(t,e,o){let n=await fetch(`${W}/functions/`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:e,name:o.name,runtime:o.runtime,entrypoint:o.entrypoint,envId:o.envId})});if(!n.ok){let r=await n.text();throw new Error(`Failed to create function: ${r}`)}return n.json()}async function Kt(t,e,o){let n=await fetch(`${W}/functions/${e}/source`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({sourceCode:o})});if(!n.ok){let r=await n.text();throw new Error(`Failed to deploy source: ${r}`)}}async function Bt(t,e,o){let n=new URL(`${W}/functions/project/${e}`);o&&n.searchParams.set("envId",o);let r=await fetch(n.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!r.ok){let i=await r.text();throw new Error(`Failed to list functions: ${i}`)}let s=await r.json();return s.functions||s}function Ve(t){switch(A__default.default.extname(t).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(t){let e=[],o=[".ts",".js",".mjs",".py",".go",".rs"],n=["drizzle.config.ts","tsconfig.json","package.json"];if(!L__default.default.existsSync(t))return e;let r=L__default.default.readdirSync(t,{withFileTypes:true});for(let s of r){let i=A__default.default.join(t,s.name);if(s.isDirectory()){if(s.name!=="node_modules"&&!s.name.startsWith(".")){let a=L__default.default.readdirSync(i,{withFileTypes:true});for(let l of a)if(l.isFile()){let c=A__default.default.extname(l.name).toLowerCase();if(o.includes(c)){e.push(A__default.default.join(i,l.name));break}}}}else if(s.isFile()){let a=A__default.default.extname(s.name).toLowerCase();o.includes(a)&&!n.includes(s.name)&&e.push(i);}}return e}async function Ue(t){let e=H__default.default(),o=S();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF Functions Deploy")),console.log(""),e.start("Scanning for function files...");let i=A__default.default.resolve("functions"),a=A__default.default.resolve("src/functions"),l=[];if(t.entrypoint){let u=A__default.default.resolve(t.entrypoint);L__default.default.existsSync(u)||(e.fail(`File not found: ${t.entrypoint}`),process.exit(1)),l=[u];}else l=[...Le(i),...Le(a)];l.length===0&&(e.fail("No function files found"),console.log(f__default.default.yellow(`
|
|
3723
3723
|
Place your functions in:`)),console.log(f__default.default.gray(" - ./functions/")),console.log(f__default.default.gray(" - ./src/functions/")),console.log(f__default.default.gray(`
|
|
3724
3724
|
Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${l.length} function(s)`),t.name&&(l=l.filter(u=>A__default.default.basename(u,A__default.default.extname(u)).includes(t.name)),l.length===0&&(console.log(f__default.default.yellow(`
|
|
3725
|
-
No functions matching "${t.name}" found`)),process.exit(1))),console.log(""),console.log(f__default.default.gray("Functions to deploy:"));for(let u of l){let m=A__default.default.basename(A__default.default.dirname(u)),y=m==="functions"||m==="src"?A__default.default.basename(u,A__default.default.extname(u)):m,
|
|
3725
|
+
No functions matching "${t.name}" found`)),process.exit(1))),console.log(""),console.log(f__default.default.gray("Functions to deploy:"));for(let u of l){let m=A__default.default.basename(A__default.default.dirname(u)),y=m==="functions"||m==="src"?A__default.default.basename(u,A__default.default.extname(u)):m,D=t.runtime||Ve(u);console.log(f__default.default.gray(` - ${y} (${D})`));}if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no functions deployed."));return}let c=[];for(let u of l){let m=A__default.default.basename(A__default.default.dirname(u)),y=m==="functions"||m==="src"?A__default.default.basename(u,A__default.default.extname(u)):m,D=t.runtime||Ve(u);e.start(`Deploying ${y}...`);try{let M=L__default.default.readFileSync(u,"utf-8"),z=await Mt(o.token,s,y,t.envId);z||(e.text=`Creating ${y}...`,z=await zt(o.token,s,{name:y,runtime:D,entrypoint:A__default.default.basename(u),envId:t.envId})),e.text=`Deploying ${y}...`,await Kt(o.token,z.id,M),e.succeed(`Deployed ${y}`),c.push({name:y,success:!0});}catch(M){let z=M instanceof Error?M.message:"Unknown error";e.fail(`Failed to deploy ${y}`),c.push({name:y,success:false,error:z});}}console.log("");let d=c.filter(u=>u.success).length;if(c.filter(u=>!u.success).length===0)console.log(f__default.default.green(`\u2713 Successfully deployed ${d} function(s)`));else {console.log(f__default.default.yellow(`Deployed ${d}/${c.length} function(s)`)),console.log(""),console.log(f__default.default.red("Failed deployments:"));for(let u of c.filter(m=>!m.success))console.log(f__default.default.red(` - ${u.name}: ${u.error}`));}console.log("");}async function $e(t){let e=H__default.default(),o=S();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(console.log(f__default.default.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let i=await Bt(o.token,s,t.envId);if(e.stop(),i.length===0){console.log(f__default.default.yellow(`
|
|
3726
3726
|
No functions found`)),console.log(f__default.default.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(f__default.default.bold(`Functions (${i.length}):`)),console.log(""),console.log(f__default.default.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"STATUS".padEnd(12)+"INVOCATIONS".padEnd(14)+"LAST DEPLOYED")),console.log(f__default.default.gray(" "+"-".repeat(80)));for(let a of i){let l=a.deployStatus==="deployed"?f__default.default.green:a.deployStatus==="deploying"?f__default.default.yellow:a.deployStatus==="failed"?f__default.default.red:f__default.default.gray;console.log(" "+a.name.padEnd(25)+a.runtime.padEnd(15)+l(a.deployStatus.padEnd(12))+String(a.invocationCount??0).padEnd(14)+(a.deployedAt?new Date(a.deployedAt).toLocaleDateString():"-"));}console.log("");}catch(i){e.fail("Failed to fetch functions"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3727
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
3727
|
+
Error: ${i.message}`)),process.exit(1);}}var X=process.env.VAIF_API_URL||"https://api.vaif.studio";async function qt(t,e,o,n,r){let s=await fetch(`${X}/v1/projects/${e}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({table:o,records:n,truncate:r?.truncate??false})});if(!s.ok){let i=await s.text();throw new Error(`Failed to seed ${o}: ${i}`)}return s.json()}async function Yt(t,e){let o=await fetch(`${X}/v1/projects/${e}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!o.ok){let n=await o.text();throw new Error(`Failed to reset database: ${n}`)}return o.json()}function pe(t){let e=[];if(!L__default.default.existsSync(t))return e;let o=L__default.default.readdirSync(t,{withFileTypes:true});for(let n of o)if(n.isFile()){let r=A__default.default.extname(n.name).toLowerCase();(r===".json"||r===".ts"||r===".js")&&e.push(A__default.default.join(t,n.name));}return e.sort()}async function Oe(t){let e=A__default.default.extname(t).toLowerCase();if(e===".json"){let o=L__default.default.readFileSync(t,"utf-8"),n=JSON.parse(o);return Array.isArray(n)?[{table:A__default.default.basename(t,e),data:n}]:n.table&&n.data?[n]:Object.entries(n).map(([r,s])=>({table:r,data:s}))}else if(e===".ts"||e===".js"){let o=await import(t),n=o.default||o;return typeof n=="function"?n():n}throw new Error(`Unsupported file format: ${e}`)}async function Me(t){let e=H__default.default(),o=S();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF Database Seed")),console.log("");let i=[];if(t.file){let d=A__default.default.resolve(t.file);L__default.default.existsSync(d)||(console.log(f__default.default.red(`File not found: ${t.file}`)),process.exit(1)),i=[d];}else {let d=A__default.default.resolve("seeds"),p=A__default.default.resolve("prisma/seed"),u=A__default.default.resolve("db/seeds");i=[...pe(d),...pe(p),...pe(u)];}i.length===0&&(console.log(f__default.default.yellow("No seed files found")),console.log(f__default.default.gray(`
|
|
3728
3728
|
Place your seed files in one of these directories:`)),console.log(f__default.default.gray(" - ./seeds/")),console.log(f__default.default.gray(" - ./prisma/seed/")),console.log(f__default.default.gray(" - ./db/seeds/")),console.log(f__default.default.gray(`
|
|
3729
3729
|
Or specify a file with --file`)),console.log(f__default.default.gray(`
|
|
3730
|
-
Example seed file (seeds/users.json):`)),console.log(f__default.default.gray(" [")),console.log(f__default.default.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(f__default.default.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(f__default.default.gray(" ]")),process.exit(1)),console.log(f__default.default.gray("Seed files found:"));for(let d of i)console.log(f__default.default.gray(` - ${A__default.default.relative(process.cwd(),d)}`));if(console.log(""),t.truncate&&(console.log(f__default.default.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let d of i){e.start(`Loading ${A__default.default.basename(d)}...`);try{let p=await
|
|
3730
|
+
Example seed file (seeds/users.json):`)),console.log(f__default.default.gray(" [")),console.log(f__default.default.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(f__default.default.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(f__default.default.gray(" ]")),process.exit(1)),console.log(f__default.default.gray("Seed files found:"));for(let d of i)console.log(f__default.default.gray(` - ${A__default.default.relative(process.cwd(),d)}`));if(console.log(""),t.truncate&&(console.log(f__default.default.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let d of i){e.start(`Loading ${A__default.default.basename(d)}...`);try{let p=await Oe(d);e.stop();for(let u of p)t.table&&u.table!==t.table||(console.log(f__default.default.cyan(`Table: ${u.table}`)),console.log(f__default.default.gray(` Records: ${u.data.length}`)),u.data.length>0&&console.log(f__default.default.gray(` Sample: ${JSON.stringify(u.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(p){e.fail(`Failed to load ${A__default.default.basename(d)}`),p instanceof Error&&console.log(f__default.default.red(` Error: ${p.message}`));}}return}let a=[];for(let d of i){e.start(`Processing ${A__default.default.basename(d)}...`);try{let p=await Oe(d);e.stop();for(let u of p)if(!(t.table&&u.table!==t.table)){if(u.data.length===0){console.log(f__default.default.gray(` Skipping ${u.table} (no records)`));continue}e.start(`Seeding ${u.table} (${u.data.length} records)...`);try{let m=await qt(o.token,s,u.table,u.data,{truncate:t.truncate});e.succeed(`Seeded ${u.table}: ${m.inserted} records`),a.push({table:u.table,inserted:m.inserted});}catch(m){let y=m instanceof Error?m.message:"Unknown error";e.fail(`Failed to seed ${u.table}`),a.push({table:u.table,inserted:0,error:y});}}}catch(p){e.fail(`Failed to load ${A__default.default.basename(d)}`),p instanceof Error&&console.log(f__default.default.red(` Error: ${p.message}`));}}console.log("");let l=a.reduce((d,p)=>d+p.inserted,0),c=a.filter(d=>d.error).length;if(c===0)console.log(f__default.default.green(`\u2713 Successfully seeded ${l} records across ${a.length} table(s)`));else {console.log(f__default.default.yellow(`Seeded ${l} records with ${c} error(s)`)),console.log(""),console.log(f__default.default.red("Errors:"));for(let d of a.filter(p=>p.error))console.log(f__default.default.red(` - ${d.table}: ${d.error}`));}console.log("");}async function ze(t){let e=H__default.default(),o=S();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=A__default.default.resolve(t.dir||"./drizzle");if(console.log(""),console.log(f__default.default.bold("VAIF Database Push")),console.log(""),!L__default.default.existsSync(i)){let p=A__default.default.resolve("./migrations");L__default.default.existsSync(p)?console.log(f__default.default.gray(`Using migrations from: ${p}`)):(console.log(f__default.default.red(`Migrations directory not found: ${i}`)),console.log(f__default.default.gray(`
|
|
3731
3731
|
Expected one of:`)),console.log(f__default.default.gray(" - ./drizzle/")),console.log(f__default.default.gray(" - ./migrations/")),console.log(f__default.default.gray(`
|
|
3732
|
-
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let a=[],l=
|
|
3733
|
-
Error: ${a.message}`)),process.exit(1);}}async function
|
|
3734
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
3735
|
-
Error: ${a.message}`)),process.exit(1);}}async function
|
|
3732
|
+
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let a=[],l=L__default.default.readdirSync(i,{withFileTypes:true});for(let p of l)if(p.isFile()&&p.name.endsWith(".sql"))a.push(A__default.default.join(i,p.name));else if(p.isDirectory()){let u=L__default.default.readdirSync(A__default.default.join(i,p.name),{withFileTypes:true});for(let m of u)m.isFile()&&m.name.endsWith(".sql")&&a.push(A__default.default.join(i,p.name,m.name));}a.sort(),a.length===0&&(console.log(f__default.default.yellow("No SQL migration files found")),process.exit(1)),console.log(f__default.default.gray(`Found ${a.length} migration(s):`));for(let p of a)console.log(f__default.default.gray(` - ${A__default.default.relative(process.cwd(),p)}`));if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let p of a){let u=L__default.default.readFileSync(p,"utf-8");console.log(f__default.default.cyan(`--- ${A__default.default.basename(p)} ---`)),console.log(f__default.default.gray(u.slice(0,500))),u.length>500&&console.log(f__default.default.gray("...")),console.log("");}return}let c=0,d=0;for(let p of a){let u=L__default.default.readFileSync(p,"utf-8"),m=A__default.default.relative(process.cwd(),p);e.start(`Applying ${m}...`);try{let y=await fetch(`${X}/schema-engine/query/${s}`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:u})});if(!y.ok){let D=await y.text();throw new Error(D)}e.succeed(`Applied ${m}`),c++;}catch(y){let D=y instanceof Error?y.message:"Unknown error";e.fail(`Failed ${m}: ${D}`),d++;}}console.log(""),console.log(d===0?f__default.default.green(`Successfully applied ${c} migration(s)`):f__default.default.yellow(`Applied ${c}, failed ${d} migration(s)`)),console.log("");}async function Ke(t){let e=H__default.default(),o=S();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=A__default.default.resolve(t.output||"vaif.schema.json");console.log(""),console.log(f__default.default.bold("VAIF Database Pull")),console.log(""),e.start("Pulling schema from remote...");try{let a=await fetch(`${X}/schema-engine/introspect/${s}`,{headers:{Authorization:`Bearer ${o.token}`}});if(!a.ok){let d=await a.text();throw new Error(`Failed to pull schema: ${d}`)}let l=await a.json();L__default.default.writeFileSync(i,JSON.stringify(l,null,2),"utf-8"),e.succeed(`Schema written to ${A__default.default.relative(process.cwd(),i)}`);let c=l.tables?.length??Object.keys(l).length;console.log(f__default.default.gray(` ${c} table(s) pulled`)),console.log("");}catch(a){e.fail("Failed to pull schema"),a instanceof Error&&console.log(f__default.default.red(`
|
|
3733
|
+
Error: ${a.message}`)),process.exit(1);}}async function Be(t){let e=H__default.default(),o=S();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(console.log(f__default.default.red("No project ID specified")),process.exit(1)),console.log(""),console.log(f__default.default.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(f__default.default.red("This will:")),console.log(f__default.default.red(" - Drop all tables")),console.log(f__default.default.red(" - Delete all data")),console.log(f__default.default.red(" - Reset migrations")),console.log(""),console.log(f__default.default.red.bold("This action cannot be undone!")),console.log(""),t.force||(console.log(f__default.default.yellow("Use --force to confirm this action.")),process.exit(1)),e.start("Resetting database...");try{await Yt(o.token,s),e.succeed("Database reset complete"),console.log(""),console.log(f__default.default.gray("Your database is now empty.")),console.log(f__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(f__default.default.red(`
|
|
3734
|
+
Error: ${i.message}`)),process.exit(1);}}var Ye=process.env.VAIF_API_URL||"https://api.vaif.studio";function Je(t,e,o){return t.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||o.projectId||null}async function Ge(t){let e=H__default.default(),o=S();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=Je(t,r,o);s||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=t.name||`cli-key-${Date.now()}`;console.log(""),console.log(f__default.default.bold("VAIF Generate API Key")),console.log(""),e.start("Generating API key...");try{let a=await fetch(`${Ye}/v1/projects/${s}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i})});if(!a.ok){let c=await a.text();throw new Error(`Failed to generate key: ${c}`)}let l=await a.json();e.succeed("API key generated"),console.log(""),console.log(f__default.default.green(` Name: ${l.name}`)),console.log(f__default.default.green(` Key: ${l.key}`)),console.log(""),console.log(f__default.default.yellow.bold(" Save this key now - it will not be shown again!")),console.log("");}catch(a){e.fail("Failed to generate API key"),a instanceof Error&&console.log(f__default.default.red(`
|
|
3735
|
+
Error: ${a.message}`)),process.exit(1);}}async function We(t){let e=H__default.default(),o=S();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=Je(t,r,o);s||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF API Keys")),console.log(""),e.start("Fetching API keys...");try{let i=await fetch(`${Ye}/v1/projects/${s}/api-keys`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let p=await i.text();throw new Error(`Failed to list keys: ${p}`)}let a=await i.json(),l=a.keys||a;if(e.stop(),!Array.isArray(l)||l.length===0){console.log(f__default.default.yellow("No API keys found")),console.log(f__default.default.gray(`
|
|
3736
3736
|
Generate one with: vaif keys generate`));return}let c=Math.max(8,...l.map(p=>(p.name||"").length)),d=` ${"Name".padEnd(c)} ${"Key".padEnd(24)} Created`;console.log(f__default.default.gray(d)),console.log(f__default.default.gray(" "+"-".repeat(d.length-2)));for(let p of l){let u=(p.name||"unnamed").padEnd(c),m=p.maskedKey||p.prefix||`${(p.key||"").slice(0,12)}...`,y=p.createdAt?new Date(p.createdAt).toLocaleDateString():"N/A";console.log(` ${u} ${m.padEnd(24)} ${y}`);}console.log(""),console.log(f__default.default.gray(` ${l.length} key(s) total`)),console.log("");}catch(i){e.fail("Failed to list API keys"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3737
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
3738
|
-
Error: ${l.message}`)),process.exit(1);}}async function
|
|
3737
|
+
Error: ${i.message}`)),process.exit(1);}}var O=process.env.VAIF_API_URL||"https://api.vaif.studio";function Gt(t,e,o){return t.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||o.projectId||null}function Z(){let t=S();return (!t||!t.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1)),t}async function ee(t){try{return await I(t||"vaif.config.json")}catch{return null}}function te(t,e,o){let n=Gt(t,e,o);return n||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),n}async function He(t,e,o){let n=H__default.default(),r=Z(),s=await ee(o.config),i=te(o,s,r),a=e;if(o.fromFile)try{a=L__default.default.readFileSync(o.fromFile,"utf-8");}catch(l){console.log(f__default.default.red(`Failed to read file: ${o.fromFile}`)),l instanceof Error&&console.log(f__default.default.gray(l.message)),process.exit(1);}a||(console.log(f__default.default.red("No value provided")),console.log(f__default.default.gray("Provide a value as argument or use --from-file <path>")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF Set Secret")),console.log(""),n.start("Checking for existing secret...");try{let l=new URL(`${O}/functions/secrets/project/${i}`);o.envId&&l.searchParams.set("envId",o.envId);let c=await fetch(l.toString(),{headers:{Authorization:`Bearer ${r.token}`}});if(!c.ok)throw new Error(`Failed to check existing secrets: ${await c.text()}`);let p=(await c.json()).find(u=>u.key===t);if(p){n.text=`Updating secret "${t}"...`;let u=await fetch(`${O}/functions/secrets/${p.id}`,{method:"PUT",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({value:a})});if(!u.ok)throw new Error(`Failed to update secret: ${await u.text()}`);n.succeed(`Updated secret "${t}"`);}else {n.text=`Creating secret "${t}"...`;let u=await fetch(`${O}/functions/secrets`,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:i,envId:o.envId,key:t,value:a})});if(!u.ok)throw new Error(`Failed to create secret: ${await u.text()}`);n.succeed(`Created secret "${t}"`);}console.log("");}catch(l){n.fail("Failed to set secret"),l instanceof Error&&console.log(f__default.default.red(`
|
|
3738
|
+
Error: ${l.message}`)),process.exit(1);}}async function Xe(t){let e=H__default.default(),o=Z(),n=await ee(t.config),r=te(t,n,o);console.log(""),console.log(f__default.default.bold("VAIF Secrets")),console.log(""),e.start("Fetching secrets...");try{let s=new URL(`${O}/functions/secrets/project/${r}`);t.envId&&s.searchParams.set("envId",t.envId);let i=await fetch(s.toString(),{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok)throw new Error(`Failed to list secrets: ${await i.text()}`);let a=await i.json();if(e.stop(),a.length===0){console.log(f__default.default.yellow("No secrets found")),console.log(f__default.default.gray(`
|
|
3739
3739
|
Create one with: vaif secrets set <name> <value>`));return}let l=Math.max(8,...a.map(d=>d.key.length)),c=` ${"Name".padEnd(l)} Created`;console.log(f__default.default.gray(c)),console.log(f__default.default.gray(" "+"-".repeat(c.length-2)));for(let d of a){let p=d.key.padEnd(l),u=d.createdAt?new Date(d.createdAt).toLocaleDateString():"N/A";console.log(` ${p} ${u}`);}console.log(""),console.log(f__default.default.gray(` ${a.length} secret(s) total`)),console.log(f__default.default.gray(" Values are hidden. Use `vaif secrets get <name>` to reveal.")),console.log("");}catch(s){e.fail("Failed to list secrets"),s instanceof Error&&console.log(f__default.default.red(`
|
|
3740
|
-
Error: ${s.message}`)),process.exit(1);}}async function
|
|
3741
|
-
Error: ${i.message}`)),process.exit(1);}}async function
|
|
3742
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
3743
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
3744
|
-
Error: ${i.message}`)),process.exit(1);}}commander.program.name("vaif").description("VAIF CLI - Type generation and development tools").version(
|
|
3740
|
+
Error: ${s.message}`)),process.exit(1);}}async function Qe(t,e){let o=H__default.default(),n=Z(),r=await ee(e.config),s=te(e,r,n);console.log(""),o.start("Fetching secret...");try{let i=new URL(`${O}/functions/secrets/project/${s}`);e.envId&&i.searchParams.set("envId",e.envId);let a=await fetch(i.toString(),{headers:{Authorization:`Bearer ${n.token}`}});if(!a.ok)throw new Error(`Failed to fetch secrets: ${await a.text()}`);let c=(await a.json()).find(u=>u.key===t);c||(o.fail(`Secret "${t}" not found`),process.exit(1));let d=await fetch(`${O}/functions/secrets/${c.id}/value`,{headers:{Authorization:`Bearer ${n.token}`}});if(!d.ok)throw new Error(`Failed to get secret value: ${await d.text()}`);let p=await d.json();o.stop(),console.log(p.value);}catch(i){o.fail("Failed to get secret"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3741
|
+
Error: ${i.message}`)),process.exit(1);}}async function Ze(t,e){let o=H__default.default(),n=Z(),r=await ee(e.config),s=te(e,r,n);console.log(""),console.log(f__default.default.bold("VAIF Delete Secret")),console.log(""),o.start("Finding secret...");try{let i=new URL(`${O}/functions/secrets/project/${s}`);e.envId&&i.searchParams.set("envId",e.envId);let a=await fetch(i.toString(),{headers:{Authorization:`Bearer ${n.token}`}});if(!a.ok)throw new Error(`Failed to fetch secrets: ${await a.text()}`);let c=(await a.json()).find(p=>p.key===t);c||(o.fail(`Secret "${t}" not found`),process.exit(1)),o.text=`Deleting secret "${t}"...`;let d=await fetch(`${O}/functions/secrets/${c.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}});if(!d.ok)throw new Error(`Failed to delete secret: ${await d.text()}`);o.succeed(`Deleted secret "${t}"`),console.log("");}catch(i){o.fail("Failed to delete secret"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3742
|
+
Error: ${i.message}`)),process.exit(1);}}var et=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ht(t){try{let e=new URL(t);return e.password&&(e.password="****"),e.toString()}catch{return t.replace(/:[^@/]+@/,":****@")}}async function tt(t){let e=H__default.default(),o=S();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(console.log(f__default.default.red("No project ID specified")),console.log(f__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(`${et}/v1/projects/${s}`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let d=await i.text();throw new Error(`Failed to fetch project: ${d}`)}let a=await i.json();e.stop(),console.log(""),console.log(f__default.default.bold("VAIF Project Info")),console.log("");let l=16,c=(d,p)=>{console.log(` ${f__default.default.gray(d.padEnd(l))} ${p}`);};c("Name:",f__default.default.white(a.name||"N/A")),c("Project ID:",f__default.default.white(s)),c("Region:",f__default.default.white(a.region||"us-east-1")),c("Plan:",f__default.default.white(a.plan||a.tier||"free")),c("Created:",f__default.default.white(a.createdAt?new Date(a.createdAt).toLocaleDateString():"N/A")),console.log(""),c("API URL:",f__default.default.cyan(a.apiUrl||`${et}/v1`)),c("WS URL:",f__default.default.cyan(a.wsUrl||a.realtimeUrl||"N/A")),c("DB URL:",f__default.default.cyan(a.databaseUrl?Ht(a.databaseUrl):"N/A")),c("Storage URL:",f__default.default.cyan(a.storageUrl||"N/A")),console.log("");}catch(i){e.fail("Failed to fetch project info"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3743
|
+
Error: ${i.message}`)),process.exit(1);}}var Qt=process.env.VAIF_API_URL||"https://api.vaif.studio";async function ot(t){let e=H__default.default(),o=S();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(console.log(f__default.default.red("No project ID specified")),console.log(f__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(`${Qt}/v1/projects/${s}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let y=await i.text();throw new Error(`Failed to fetch project status: ${y}`)}let a=await i.json();e.stop(),console.log(""),console.log(f__default.default.bold("VAIF Project Status")),console.log("");let l=22,c=(y,D)=>{console.log(` ${f__default.default.gray(y.padEnd(l))} ${D}`);};c("Project:",f__default.default.white(a.name||s)),c("Plan:",f__default.default.white(a.plan||a.tier||"free")),console.log(""),console.log(f__default.default.gray(" --- Resources ---")),console.log("");let d=a.tableCount??a.tables?.length??"N/A",p=a.functionCount??a.functions?.length??"N/A",u=a.bucketCount??a.storage?.buckets?.length??"N/A",m=a.activeConnections??a.connections??"N/A";c("Tables:",f__default.default.white(String(d))),c("Functions:",f__default.default.white(String(p))),c("Storage Buckets:",f__default.default.white(String(u))),c("Active Connections:",f__default.default.white(String(m))),a.usage&&(console.log(""),console.log(f__default.default.gray(" --- Usage ---")),console.log(""),a.usage.dbSize&&c("Database Size:",f__default.default.white(a.usage.dbSize)),a.usage.storageSize&&c("Storage Size:",f__default.default.white(a.usage.storageSize)),a.usage.bandwidth&&c("Bandwidth:",f__default.default.white(a.usage.bandwidth)),a.usage.functionInvocations!=null&&c("Function Invocations:",f__default.default.white(String(a.usage.functionInvocations)))),console.log("");}catch(i){e.fail("Failed to fetch project status"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3744
|
+
Error: ${i.message}`)),process.exit(1);}}var nt="1.7.0",fe=f__default.default.hex("#00f0ff"),ge=f__default.default.hex("#7b61ff"),me=f__default.default.hex("#ff3dff"),he=f__default.default.hex("#00ff9d"),w=f__default.default.hex("#555570"),K=f__default.default.hex("#00f0ff");function Zt(){console.log(""),console.log(fe(" \u2566 \u2566")+ge("\u2554\u2550\u2557\u2566")+me("\u2554\u2550\u2557 ")+he("\u2554\u2550\u2557\u2566 \u2566")),console.log(fe(" \u255A\u2557\u2554\u255D")+ge("\u2560\u2550\u2563\u2551")+me("\u2560\u2563 ")+he("\u2551 \u2551 \u2551")),console.log(fe(" \u255A\u255D ")+ge("\u2569 \u2569\u2569")+me("\u255A ")+he("\u255A\u2550\u255D\u2569\u2550\u255D\u2569")),console.log(""),console.log(w(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(K(" VAIF Studio CLI")+w(` v${nt}`)),console.log(w(" Build full-stack apps at lightning speed")),console.log(w(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(""),console.log(f__default.default.bold(" Quick Start")),console.log(w(" $ ")+K("vaif login")+w(" Authenticate")),console.log(w(" $ ")+K("vaif init -t react-spa")+w(" Scaffold project")),console.log(w(" $ ")+K("vaif db push")+w(" Push migrations")),console.log(w(" $ ")+K("vaif generate")+w(" Generate types")),console.log(w(" $ ")+K("vaif functions deploy")+w(" Deploy functions")),console.log(""),console.log(f__default.default.bold(" Categories")),console.log(w(" auth ")+f__default.default.white("login, logout, whoami")),console.log(w(" project ")+f__default.default.white("init, templates, info, status")),console.log(w(" schema ")+f__default.default.white("pull, push, generate")),console.log(w(" database ")+f__default.default.white("db push, db pull, db seed, db reset")),console.log(w(" deploy ")+f__default.default.white("functions deploy, functions list")),console.log(w(" security ")+f__default.default.white("keys, secrets")),console.log(""),console.log(w(" Run ")+K("vaif <command> --help")+w(" for details")),console.log(w(" Docs: ")+f__default.default.underline("https://docs.vaif.studio")),console.log("");}commander.program.name("vaif").description("VAIF CLI - Type generation and development tools").version(nt);commander.program.command("login").description("Authenticate with VAIF (opens browser)").option("-e, --email","Login with email/password instead of browser").option("-p, --project-id <id>","Default project ID").action(Fe);commander.program.command("logout").description("Log out and remove stored credentials").action(Pe);commander.program.command("whoami").description("Show current authenticated user").action(je);commander.program.command("init").description("Initialize VAIF configuration in your project").option("--typescript","Setup for TypeScript project").option("-f, --force","Overwrite existing config").option("-t, --template <name>","Scaffold from a template (run vaif templates for list)").option("--features <features>","Comma-separated features to include: auth,database,realtime,storage,functions").option("--add-features <features>","Add features to an existing project (requires --template)").action(Ee);commander.program.command("templates").alias("tpl").description("List available project templates").action(Se);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(tt);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(ot);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(Ce);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(De);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(Ie);var at=commander.program.command("functions").alias("fn").description("Manage serverless functions");at.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(Ue);at.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($e);var oe=commander.program.command("db").description("Database management commands");oe.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(ze);oe.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(Ke);oe.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);oe.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(Be);var it=commander.program.command("keys").description("Manage API keys");it.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(Ge);it.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(We);var ne=commander.program.command("secrets").alias("sec").description("Manage function secrets");ne.command("set <name> [value]").description("Create or update a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").option("--from-file <path>","Read secret value from a file").action(He);ne.command("list").alias("ls").description("List all secrets (names only)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Xe);ne.command("get <name>").description("Reveal a secret value").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Qe);ne.command("delete <name>").description("Delete a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Ze);process.argv.slice(2).length||(Zt(),process.exit(0));commander.program.parse(process.argv);
|
package/dist/cli.js
CHANGED
|
@@ -1,42 +1,42 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {d,c,b,a}from'./chunk-OB2QEQ2L.js';import'dotenv/config';import {program}from'commander';import
|
|
2
|
+
import {d,c,b,a}from'./chunk-OB2QEQ2L.js';import'dotenv/config';import {program}from'commander';import l from'chalk';import D from'fs';import j from'path';import Be from'os';import {exec}from'child_process';import M from'ora';import le from'readline';var X=j.join(Be.homedir(),".vaif"),V=j.join(X,"auth.json"),J=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ke(){D.existsSync(X)||D.mkdirSync(X,{recursive:true});}function ge(e){Ke(),D.writeFileSync(V,JSON.stringify(e,null,2),"utf-8"),D.chmodSync(V,384);}function I(){if(!D.existsSync(V))return null;try{let e=D.readFileSync(V,"utf-8");return JSON.parse(e)}catch{return null}}function qe(e){let o=le.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{o.question(e,s=>{o.close(),t(s);});})}function We(e){return new Promise(o=>{let t=le.createInterface({input:process.stdin,output:process.stdout});process.stdin;let c=process.stdout.write.bind(process.stdout),r=false;process.stdout.write=((...i)=>r?true:c(...i)),t.question(e,i=>{r=false,process.stdout.write=c,console.log(""),t.close(),o(i);}),r=true;})}function Ge(e){let o=process.platform,t;o==="darwin"?t=`open "${e}"`:o==="win32"?t=`start "" "${e}"`:t=`xdg-open "${e}"`,exec(t,s=>{});}function Ye(e){return new Promise(o=>setTimeout(o,e))}async function Qe(e){try{let o=await fetch(`${J}/auth/me`,{headers:{Authorization:`Bearer ${e}`}});if(o.ok){let t=await o.json();return {valid:!0,email:t.user?.email||t.email}}return {valid:!1}}catch{return {valid:false}}}async function He(e){let o=M();o.start("Setting up authentication...");let t,s;try{let n=await fetch(`${J}/auth/cli/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});n.ok||(o.fail("Failed to initiate authentication"),console.log(l.red(`
|
|
3
3
|
Could not connect to VAIF API. Please try again later.`)),process.exit(1));let a=await n.json();t=a.code,s=a.url;}catch{o.fail("Failed to connect to VAIF API"),console.log(l.red(`
|
|
4
|
-
Could not connect to VAIF API.`)),console.log(l.gray("Check your internet connection or try: vaif login --email")),process.exit(1);}o.stop(),console.log(l.cyan(" Opening browser for authentication...")),console.log(""),console.log(l.gray(" If the browser doesn't open, visit this URL:")),console.log(l.white(` ${s}`)),console.log(""),
|
|
5
|
-
The authentication session expired. Please try again.`)),process.exit(1));continue}let a=await n.json();if(a.ok&&a.accessToken){let f={token:a.accessToken,email:a.user?.email,projectId:e,expiresAt:new Date(Date.now()+a.expiresIn*1e3).toISOString()};
|
|
6
|
-
Timed out waiting for browser authentication.`)),console.log(l.gray("Try again or use: vaif login --email")),process.exit(1);}async function
|
|
7
|
-
No email provided. Login cancelled.`)),process.exit(1));let t=await
|
|
8
|
-
No password provided. Login cancelled.`)),process.exit(1));let s=
|
|
9
|
-
${r.message||"Invalid email or password."}`)),process.exit(1));let i={token:r.accessToken,email:r.user?.email,projectId:e,expiresAt:new Date(Date.now()+r.expiresIn*1e3).toISOString()};
|
|
10
|
-
Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function
|
|
11
|
-
Your session has expired. Please login again.`)),process.exit(1)),o.succeed("Authenticated"),console.log(""),console.log(l.green(` Email: ${s||e.email||"Unknown"}`)),e.projectId&&console.log(l.green(` Project: ${e.projectId}`)),console.log("");}var
|
|
4
|
+
Could not connect to VAIF API.`)),console.log(l.gray("Check your internet connection or try: vaif login --email")),process.exit(1);}o.stop(),console.log(l.cyan(" Opening browser for authentication...")),console.log(""),console.log(l.gray(" If the browser doesn't open, visit this URL:")),console.log(l.white(` ${s}`)),console.log(""),Ge(s),o.start("Waiting for browser authentication...");let c=12e4,r=2e3,i=Date.now();for(;Date.now()-i<c;){await Ye(r);try{let n=await fetch(`${J}/auth/cli/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok){let f=await n.json();(f.error==="ExpiredCode"||f.error==="InvalidCode")&&(o.fail("Authentication expired"),console.log(l.red(`
|
|
5
|
+
The authentication session expired. Please try again.`)),process.exit(1));continue}let a=await n.json();if(a.ok&&a.accessToken){let f={token:a.accessToken,email:a.user?.email,projectId:e,expiresAt:new Date(Date.now()+a.expiresIn*1e3).toISOString()};ge(f),o.succeed("Logged in successfully"),console.log(""),a.user?.email&&console.log(l.green(` Authenticated as: ${a.user.email}`)),console.log(l.gray(` Config saved to: ${V}`)),console.log("");return}}catch{}}o.fail("Authentication timed out"),console.log(l.red(`
|
|
6
|
+
Timed out waiting for browser authentication.`)),console.log(l.gray("Try again or use: vaif login --email")),process.exit(1);}async function Xe(e){console.log(""),console.log(l.bold("VAIF CLI Login")),console.log(l.gray("Enter your VAIF account credentials")),console.log("");let o=await qe(l.cyan(" Email: "));(!o||o.trim()==="")&&(console.log(l.red(`
|
|
7
|
+
No email provided. Login cancelled.`)),process.exit(1));let t=await We(l.cyan(" Password: "));(!t||t.trim()==="")&&(console.log(l.red(`
|
|
8
|
+
No password provided. Login cancelled.`)),process.exit(1));let s=M("Authenticating...").start();try{let c=await fetch(`${J}/auth/cli/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:o.trim(),password:t})}),r=await c.json();(!c.ok||!r.ok)&&(s.fail("Login failed"),console.log(l.red(`
|
|
9
|
+
${r.message||"Invalid email or password."}`)),process.exit(1));let i={token:r.accessToken,email:r.user?.email,projectId:e,expiresAt:new Date(Date.now()+r.expiresIn*1e3).toISOString()};ge(i),s.succeed("Logged in successfully"),console.log(""),r.user?.email&&console.log(l.green(` Authenticated as: ${r.user.email}`)),console.log(l.gray(` Config saved to: ${V}`)),console.log("");}catch{s.fail("Failed to connect to VAIF API"),console.log(l.red(`
|
|
10
|
+
Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function fe(e){console.log(""),console.log(l.bold("Welcome to VAIF CLI")),console.log(l.gray("Authenticate to access your VAIF projects")),console.log(""),e.email?await Xe(e.projectId):await He(e.projectId),console.log(l.gray("You can now use VAIF CLI commands like:")),console.log(l.gray(" vaif pull - Pull remote schema")),console.log(l.gray(" vaif push - Push schema changes")),console.log(l.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function de(){D.existsSync(V)?(D.unlinkSync(V),console.log(l.green("Logged out successfully"))):console.log(l.yellow("Not currently logged in"));}async function pe(){let e=I();(!e||!e.token)&&(console.log(l.yellow("Not logged in")),console.log(l.gray("Run `vaif login` to authenticate")),process.exit(1));let o=M("Checking authentication...").start(),{valid:t,email:s}=await Qe(e.token);t||(o.fail("Session expired"),console.log(l.yellow(`
|
|
11
|
+
Your session has expired. Please login again.`)),process.exit(1)),o.succeed("Authenticated"),console.log(""),console.log(l.green(` Email: ${s||e.email||"Unknown"}`)),e.projectId&&console.log(l.green(` Project: ${e.projectId}`)),console.log("");}var to=process.env.VAIF_API_URL||"https://api.vaif.studio";async function no(e,o,t="public"){let s=await fetch(`${to}/v1/projects/${o}/schema?schema=${t}`,{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 ue(e){let o=M(),t=I();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.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(l.red(`
|
|
12
12
|
Error: ${i}`)),process.exit(1);}c||(o.fail("No configuration found"),console.log(l.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let r=e.projectId||c.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(o.fail("No project ID specified"),console.log(l.yellow(`
|
|
13
|
-
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",n=await
|
|
14
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
13
|
+
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",n=await no(t.token,r,i);o.succeed("Schema fetched successfully");let a=e.output||j.resolve("vaif.schema.json"),f={$schema:"https://vaif.studio/schemas/schema.json",projectId:r,schema:i,pulledAt:new Date().toISOString(),...n};D.writeFileSync(a,JSON.stringify(f,null,2),"utf-8"),console.log(""),console.log(l.green(`Schema saved to: ${a}`)),console.log(""),console.log(l.gray("Schema summary:")),console.log(l.gray(` Tables: ${(n.tables||[]).length}`)),console.log(l.gray(` Enums: ${(n.enums||[]).length}`)),console.log(l.gray(` Functions: ${(n.functions||[]).length}`)),console.log(""),console.log(l.gray("Next steps:")),console.log(l.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(l.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(i){o.fail("Failed to fetch schema"),i instanceof Error&&console.log(l.red(`
|
|
14
|
+
Error: ${i.message}`)),process.exit(1);}}var he=process.env.VAIF_API_URL||"https://api.vaif.studio";function co(e){let o=le.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{o.question(e,s=>{o.close(),t(s);});})}async function ao(e,o,t){let s=await fetch(`${he}/v1/projects/${o}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!s.ok){let c=await s.text();throw new Error(`Failed to preview changes: ${c}`)}return s.json()}async function lo(e,o,t){let s=await fetch(`${he}/v1/projects/${o}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!s.ok){let c=await s.text();throw new Error(`Failed to apply changes: ${c}`)}return s.json()}function go(e){if(console.log(""),console.log(l.bold("Schema Changes:")),console.log(""),e.added.length===0&&e.modified.length===0&&e.removed.length===0){console.log(l.gray(" No changes detected. Schema is up to date."));return}if(e.added.length>0){console.log(l.green.bold(" + Added:"));for(let o of e.added)console.log(l.green(` + ${o.type}: ${o.name}`));console.log("");}if(e.modified.length>0){console.log(l.yellow.bold(" ~ Modified:"));for(let o of e.modified){console.log(l.yellow(` ~ ${o.type}: ${o.name}`));for(let t of o.changes)console.log(l.gray(` ${t}`));}console.log("");}if(e.removed.length>0){console.log(l.red.bold(" - Removed:"));for(let o of e.removed)console.log(l.red(` - ${o.type}: ${o.name}`));console.log("");}}async function ye(e){let o=M(),t=I();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.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(a){o.fail("Failed to load config"),console.log(l.red(`
|
|
15
15
|
Error: ${a}`)),process.exit(1);}c||(o.fail("No configuration found"),console.log(l.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let r=e.projectId||c.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(o.fail("No project ID specified"),console.log(l.yellow(`
|
|
16
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=e.schema||j.resolve("vaif.schema.json");
|
|
17
|
-
Expected schema file at: ${i}`)),console.log(l.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let n;try{let a=
|
|
18
|
-
Error: ${a.message}`)),process.exit(1);}o.text="Calculating schema changes...";try{let{diff:a,sql:f}=await
|
|
19
|
-
Cancelled. No changes applied.`));return}}o.start("Applying schema changes...");let p=await
|
|
20
|
-
Error: ${a.message}`)),process.exit(1);}}var
|
|
16
|
+
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=e.schema||j.resolve("vaif.schema.json");D.existsSync(i)||(o.fail("No local schema found"),console.log(l.yellow(`
|
|
17
|
+
Expected schema file at: ${i}`)),console.log(l.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let n;try{let a=D.readFileSync(i,"utf-8");n=JSON.parse(a);}catch(a){o.fail("Failed to parse schema file"),a instanceof Error&&console.log(l.red(`
|
|
18
|
+
Error: ${a.message}`)),process.exit(1);}o.text="Calculating schema changes...";try{let{diff:a,sql:f}=await ao(t.token,r,n);if(o.stop(),go(a),a.added.length===0&&a.modified.length===0&&a.removed.length===0){console.log("");return}if(f.length>0){console.log(l.bold("SQL Migrations:")),console.log("");for(let d of f)console.log(l.gray(` ${d}`));console.log("");}if(e.dryRun){console.log(l.yellow("Dry run mode - no changes applied.")),console.log(l.gray("Remove --dry-run to apply these changes."));return}if(!e.force){a.removed.length>0&&(console.log(l.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(l.red(" This action cannot be undone!")),console.log(""));let g=await co(l.cyan("Apply these changes? [y/N] "));if(g.toLowerCase()!=="y"&&g.toLowerCase()!=="yes"){console.log(l.yellow(`
|
|
19
|
+
Cancelled. No changes applied.`));return}}o.start("Applying schema changes...");let p=await lo(t.token,r,n);if(p.success){if(o.succeed("Schema changes applied successfully"),console.log(""),p.migrations.length>0){console.log(l.gray("Migrations applied:"));for(let d of p.migrations)console.log(l.gray(` - ${d}`));console.log("");}console.log(l.green("Your database schema is now up to date.")),console.log(l.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(l.red(`
|
|
20
|
+
Error: ${a.message}`)),process.exit(1);}}var B=process.env.VAIF_API_URL||"https://api.vaif.studio";async function fo(e,o,t,s){let c=new URL(`${B}/functions/project/${o}`);s&&c.searchParams.set("envId",s);let r=await fetch(c.toString(),{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)return null;let i=await r.json(),n=i.functions||i;return Array.isArray(n)&&n.find(a=>a.name===t)||null}async function po(e,o,t){let s=await fetch(`${B}/functions/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:o,name:t.name,runtime:t.runtime,entrypoint:t.entrypoint,envId:t.envId})});if(!s.ok){let c=await s.text();throw new Error(`Failed to create function: ${c}`)}return s.json()}async function uo(e,o,t){let s=await fetch(`${B}/functions/${o}/source`,{method:"PUT",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({sourceCode:t})});if(!s.ok){let c=await s.text();throw new Error(`Failed to deploy source: ${c}`)}}async function mo(e,o,t){let s=new URL(`${B}/functions/project/${o}`);t&&s.searchParams.set("envId",t);let c=await fetch(s.toString(),{headers:{Authorization:`Bearer ${e}`}});if(!c.ok){let i=await c.text();throw new Error(`Failed to list functions: ${i}`)}let r=await c.json();return r.functions||r}function we(e){switch(j.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 je(e){let o=[],t=[".ts",".js",".mjs",".py",".go",".rs"],s=["drizzle.config.ts","tsconfig.json","package.json"];if(!D.existsSync(e))return o;let c=D.readdirSync(e,{withFileTypes:true});for(let r of c){let i=j.join(e,r.name);if(r.isDirectory()){if(r.name!=="node_modules"&&!r.name.startsWith(".")){let n=D.readdirSync(i,{withFileTypes:true});for(let a of n)if(a.isFile()){let f=j.extname(a.name).toLowerCase();if(t.includes(f)){o.push(j.join(i,a.name));break}}}}else if(r.isFile()){let n=j.extname(r.name).toLowerCase();t.includes(n)&&!s.includes(r.name)&&o.push(i);}}return o}async function Ie(e){let o=M(),t=I();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.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 r=e.projectId||c?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(l.bold("VAIF Functions Deploy")),console.log(""),o.start("Scanning for function files...");let i=j.resolve("functions"),n=j.resolve("src/functions"),a$1=[];if(e.entrypoint){let g=j.resolve(e.entrypoint);D.existsSync(g)||(o.fail(`File not found: ${e.entrypoint}`),process.exit(1)),a$1=[g];}else a$1=[...je(i),...je(n)];a$1.length===0&&(o.fail("No function files found"),console.log(l.yellow(`
|
|
21
21
|
Place your functions in:`)),console.log(l.gray(" - ./functions/")),console.log(l.gray(" - ./src/functions/")),console.log(l.gray(`
|
|
22
22
|
Or specify an entrypoint with --entrypoint`)),process.exit(1)),o.succeed(`Found ${a$1.length} function(s)`),e.name&&(a$1=a$1.filter(g=>j.basename(g,j.extname(g)).includes(e.name)),a$1.length===0&&(console.log(l.yellow(`
|
|
23
|
-
No functions matching "${e.name}" found`)),process.exit(1))),console.log(""),console.log(l.gray("Functions to deploy:"));for(let g of a$1){let y=j.basename(j.dirname(g)),w=y==="functions"||y==="src"?j.basename(g,j.extname(g)):y,
|
|
23
|
+
No functions matching "${e.name}" found`)),process.exit(1))),console.log(""),console.log(l.gray("Functions to deploy:"));for(let g of a$1){let y=j.basename(j.dirname(g)),w=y==="functions"||y==="src"?j.basename(g,j.extname(g)):y,E=e.runtime||we(g);console.log(l.gray(` - ${w} (${E})`));}if(console.log(""),e.dryRun){console.log(l.yellow("Dry run mode - no functions deployed."));return}let f=[];for(let g of a$1){let y=j.basename(j.dirname(g)),w=y==="functions"||y==="src"?j.basename(g,j.extname(g)):y,E=e.runtime||we(g);o.start(`Deploying ${w}...`);try{let z=D.readFileSync(g,"utf-8"),_=await fo(t.token,r,w,e.envId);_||(o.text=`Creating ${w}...`,_=await po(t.token,r,{name:w,runtime:E,entrypoint:j.basename(g),envId:e.envId})),o.text=`Deploying ${w}...`,await uo(t.token,_.id,z),o.succeed(`Deployed ${w}`),f.push({name:w,success:!0});}catch(z){let _=z instanceof Error?z.message:"Unknown error";o.fail(`Failed to deploy ${w}`),f.push({name:w,success:false,error:_});}}console.log("");let p=f.filter(g=>g.success).length;if(f.filter(g=>!g.success).length===0)console.log(l.green(`\u2713 Successfully deployed ${p} function(s)`));else {console.log(l.yellow(`Deployed ${p}/${f.length} function(s)`)),console.log(""),console.log(l.red("Failed deployments:"));for(let g of f.filter(y=>!y.success))console.log(l.red(` - ${g.name}: ${g.error}`));}console.log("");}async function $e(e){let o=M(),t=I();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.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 r=e.projectId||c?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(l.red("No project ID specified")),process.exit(1)),o.start("Fetching functions...");try{let i=await mo(t.token,r,e.envId);if(o.stop(),i.length===0){console.log(l.yellow(`
|
|
24
24
|
No functions found`)),console.log(l.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(l.bold(`Functions (${i.length}):`)),console.log(""),console.log(l.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"STATUS".padEnd(12)+"INVOCATIONS".padEnd(14)+"LAST DEPLOYED")),console.log(l.gray(" "+"-".repeat(80)));for(let n of i){let a=n.deployStatus==="deployed"?l.green:n.deployStatus==="deploying"?l.yellow:n.deployStatus==="failed"?l.red:l.gray;console.log(" "+n.name.padEnd(25)+n.runtime.padEnd(15)+a(n.deployStatus.padEnd(12))+String(n.invocationCount??0).padEnd(14)+(n.deployedAt?new Date(n.deployedAt).toLocaleDateString():"-"));}console.log("");}catch(i){o.fail("Failed to fetch functions"),i instanceof Error&&console.log(l.red(`
|
|
25
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
25
|
+
Error: ${i.message}`)),process.exit(1);}}var K=process.env.VAIF_API_URL||"https://api.vaif.studio";async function ho(e,o,t,s,c){let r=await fetch(`${K}/v1/projects/${o}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({table:t,records:s,truncate:c?.truncate??false})});if(!r.ok){let i=await r.text();throw new Error(`Failed to seed ${t}: ${i}`)}return r.json()}async function yo(e,o){let t=await fetch(`${K}/v1/projects/${o}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!t.ok){let s=await t.text();throw new Error(`Failed to reset database: ${s}`)}return t.json()}function ee(e){let o=[];if(!D.existsSync(e))return o;let t=D.readdirSync(e,{withFileTypes:true});for(let s of t)if(s.isFile()){let c=j.extname(s.name).toLowerCase();(c===".json"||c===".ts"||c===".js")&&o.push(j.join(e,s.name));}return o.sort()}async function be(e){let o=j.extname(e).toLowerCase();if(o===".json"){let t=D.readFileSync(e,"utf-8"),s=JSON.parse(t);return Array.isArray(s)?[{table:j.basename(e,o),data:s}]:s.table&&s.data?[s]:Object.entries(s).map(([c,r])=>({table:c,data:r}))}else if(o===".ts"||o===".js"){let t=await import(e),s=t.default||t;return typeof s=="function"?s():s}throw new Error(`Unsupported file format: ${o}`)}async function Se(e){let o=M(),t=I();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.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 r=e.projectId||c?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(l.bold("VAIF Database Seed")),console.log("");let i=[];if(e.file){let p=j.resolve(e.file);D.existsSync(p)||(console.log(l.red(`File not found: ${e.file}`)),process.exit(1)),i=[p];}else {let p=j.resolve("seeds"),d=j.resolve("prisma/seed"),g=j.resolve("db/seeds");i=[...ee(p),...ee(d),...ee(g)];}i.length===0&&(console.log(l.yellow("No seed files found")),console.log(l.gray(`
|
|
26
26
|
Place your seed files in one of these directories:`)),console.log(l.gray(" - ./seeds/")),console.log(l.gray(" - ./prisma/seed/")),console.log(l.gray(" - ./db/seeds/")),console.log(l.gray(`
|
|
27
27
|
Or specify a file with --file`)),console.log(l.gray(`
|
|
28
|
-
Example seed file (seeds/users.json):`)),console.log(l.gray(" [")),console.log(l.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(l.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(l.gray(" ]")),process.exit(1)),console.log(l.gray("Seed files found:"));for(let p of i)console.log(l.gray(` - ${j.relative(process.cwd(),p)}`));if(console.log(""),e.truncate&&(console.log(l.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),e.dryRun){console.log(l.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let p of i){o.start(`Loading ${j.basename(p)}...`);try{let d=await
|
|
28
|
+
Example seed file (seeds/users.json):`)),console.log(l.gray(" [")),console.log(l.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(l.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(l.gray(" ]")),process.exit(1)),console.log(l.gray("Seed files found:"));for(let p of i)console.log(l.gray(` - ${j.relative(process.cwd(),p)}`));if(console.log(""),e.truncate&&(console.log(l.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),e.dryRun){console.log(l.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let p of i){o.start(`Loading ${j.basename(p)}...`);try{let d=await be(p);o.stop();for(let g of d)e.table&&g.table!==e.table||(console.log(l.cyan(`Table: ${g.table}`)),console.log(l.gray(` Records: ${g.data.length}`)),g.data.length>0&&console.log(l.gray(` Sample: ${JSON.stringify(g.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(d){o.fail(`Failed to load ${j.basename(p)}`),d instanceof Error&&console.log(l.red(` Error: ${d.message}`));}}return}let n=[];for(let p of i){o.start(`Processing ${j.basename(p)}...`);try{let d=await be(p);o.stop();for(let g of d)if(!(e.table&&g.table!==e.table)){if(g.data.length===0){console.log(l.gray(` Skipping ${g.table} (no records)`));continue}o.start(`Seeding ${g.table} (${g.data.length} records)...`);try{let y=await ho(t.token,r,g.table,g.data,{truncate:e.truncate});o.succeed(`Seeded ${g.table}: ${y.inserted} records`),n.push({table:g.table,inserted:y.inserted});}catch(y){let w=y instanceof Error?y.message:"Unknown error";o.fail(`Failed to seed ${g.table}`),n.push({table:g.table,inserted:0,error:w});}}}catch(d){o.fail(`Failed to load ${j.basename(p)}`),d instanceof Error&&console.log(l.red(` Error: ${d.message}`));}}console.log("");let a$1=n.reduce((p,d)=>p+d.inserted,0),f=n.filter(p=>p.error).length;if(f===0)console.log(l.green(`\u2713 Successfully seeded ${a$1} records across ${n.length} table(s)`));else {console.log(l.yellow(`Seeded ${a$1} records with ${f} error(s)`)),console.log(""),console.log(l.red("Errors:"));for(let p of n.filter(d=>d.error))console.log(l.red(` - ${p.table}: ${p.error}`));}console.log("");}async function Ae(e){let o=M(),t=I();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.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 r=e.projectId||c?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=j.resolve(e.dir||"./drizzle");if(console.log(""),console.log(l.bold("VAIF Database Push")),console.log(""),!D.existsSync(i)){let d=j.resolve("./migrations");D.existsSync(d)?console.log(l.gray(`Using migrations from: ${d}`)):(console.log(l.red(`Migrations directory not found: ${i}`)),console.log(l.gray(`
|
|
29
29
|
Expected one of:`)),console.log(l.gray(" - ./drizzle/")),console.log(l.gray(" - ./migrations/")),console.log(l.gray(`
|
|
30
|
-
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let n=[],a$1=
|
|
31
|
-
Error: ${n.message}`)),process.exit(1);}}async function
|
|
32
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
33
|
-
Error: ${n.message}`)),process.exit(1);}}async function
|
|
30
|
+
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let n=[],a$1=D.readdirSync(i,{withFileTypes:true});for(let d of a$1)if(d.isFile()&&d.name.endsWith(".sql"))n.push(j.join(i,d.name));else if(d.isDirectory()){let g=D.readdirSync(j.join(i,d.name),{withFileTypes:true});for(let y of g)y.isFile()&&y.name.endsWith(".sql")&&n.push(j.join(i,d.name,y.name));}n.sort(),n.length===0&&(console.log(l.yellow("No SQL migration files found")),process.exit(1)),console.log(l.gray(`Found ${n.length} migration(s):`));for(let d of n)console.log(l.gray(` - ${j.relative(process.cwd(),d)}`));if(console.log(""),e.dryRun){console.log(l.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let d of n){let g=D.readFileSync(d,"utf-8");console.log(l.cyan(`--- ${j.basename(d)} ---`)),console.log(l.gray(g.slice(0,500))),g.length>500&&console.log(l.gray("...")),console.log("");}return}let f=0,p=0;for(let d of n){let g=D.readFileSync(d,"utf-8"),y=j.relative(process.cwd(),d);o.start(`Applying ${y}...`);try{let w=await fetch(`${K}/schema-engine/query/${r}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:g})});if(!w.ok){let E=await w.text();throw new Error(E)}o.succeed(`Applied ${y}`),f++;}catch(w){let E=w instanceof Error?w.message:"Unknown error";o.fail(`Failed ${y}: ${E}`),p++;}}console.log(""),console.log(p===0?l.green(`Successfully applied ${f} migration(s)`):l.yellow(`Applied ${f}, failed ${p} migration(s)`)),console.log("");}async function Pe(e){let o=M(),t=I();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.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 r=e.projectId||c?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=j.resolve(e.output||"vaif.schema.json");console.log(""),console.log(l.bold("VAIF Database Pull")),console.log(""),o.start("Pulling schema from remote...");try{let n=await fetch(`${K}/schema-engine/introspect/${r}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok){let p=await n.text();throw new Error(`Failed to pull schema: ${p}`)}let a=await n.json();D.writeFileSync(i,JSON.stringify(a,null,2),"utf-8"),o.succeed(`Schema written to ${j.relative(process.cwd(),i)}`);let f=a.tables?.length??Object.keys(a).length;console.log(l.gray(` ${f} table(s) pulled`)),console.log("");}catch(n){o.fail("Failed to pull schema"),n instanceof Error&&console.log(l.red(`
|
|
31
|
+
Error: ${n.message}`)),process.exit(1);}}async function xe(e){let o=M(),t=I();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.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 r=e.projectId||c?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(l.red("No project ID specified")),process.exit(1)),console.log(""),console.log(l.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(l.red("This will:")),console.log(l.red(" - Drop all tables")),console.log(l.red(" - Delete all data")),console.log(l.red(" - Reset migrations")),console.log(""),console.log(l.red.bold("This action cannot be undone!")),console.log(""),e.force||(console.log(l.yellow("Use --force to confirm this action.")),process.exit(1)),o.start("Resetting database...");try{await yo(t.token,r),o.succeed("Database reset complete"),console.log(""),console.log(l.gray("Your database is now empty.")),console.log(l.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(l.red(`
|
|
32
|
+
Error: ${i.message}`)),process.exit(1);}}var ke=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ce(e,o,t){return e.projectId||o?.projectId||process.env.VAIF_PROJECT_ID||t.projectId||null}async function De(e){let o=M(),t=I();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.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 r=Ce(e,c,t);r||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=e.name||`cli-key-${Date.now()}`;console.log(""),console.log(l.bold("VAIF Generate API Key")),console.log(""),o.start("Generating API key...");try{let n=await fetch(`${ke}/v1/projects/${r}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i})});if(!n.ok){let f=await n.text();throw new Error(`Failed to generate key: ${f}`)}let a=await n.json();o.succeed("API key generated"),console.log(""),console.log(l.green(` Name: ${a.name}`)),console.log(l.green(` Key: ${a.key}`)),console.log(""),console.log(l.yellow.bold(" Save this key now - it will not be shown again!")),console.log("");}catch(n){o.fail("Failed to generate API key"),n instanceof Error&&console.log(l.red(`
|
|
33
|
+
Error: ${n.message}`)),process.exit(1);}}async function Ee(e){let o=M(),t=I();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.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 r=Ce(e,c,t);r||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(l.bold("VAIF API Keys")),console.log(""),o.start("Fetching API keys...");try{let i=await fetch(`${ke}/v1/projects/${r}/api-keys`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let d=await i.text();throw new Error(`Failed to list keys: ${d}`)}let n=await i.json(),a=n.keys||n;if(o.stop(),!Array.isArray(a)||a.length===0){console.log(l.yellow("No API keys found")),console.log(l.gray(`
|
|
34
34
|
Generate one with: vaif keys generate`));return}let f=Math.max(8,...a.map(d=>(d.name||"").length)),p=` ${"Name".padEnd(f)} ${"Key".padEnd(24)} Created`;console.log(l.gray(p)),console.log(l.gray(" "+"-".repeat(p.length-2)));for(let d of a){let g=(d.name||"unnamed").padEnd(f),y=d.maskedKey||d.prefix||`${(d.key||"").slice(0,12)}...`,w=d.createdAt?new Date(d.createdAt).toLocaleDateString():"N/A";console.log(` ${g} ${y.padEnd(24)} ${w}`);}console.log(""),console.log(l.gray(` ${a.length} key(s) total`)),console.log("");}catch(i){o.fail("Failed to list API keys"),i instanceof Error&&console.log(l.red(`
|
|
35
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
36
|
-
Error: ${a.message}`)),process.exit(1);}}async function
|
|
35
|
+
Error: ${i.message}`)),process.exit(1);}}var T=process.env.VAIF_API_URL||"https://api.vaif.studio";function jo(e,o,t){return e.projectId||o?.projectId||process.env.VAIF_PROJECT_ID||t.projectId||null}function W(){let e=I();return (!e||!e.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1)),e}async function G(e){try{return await a(e||"vaif.config.json")}catch{return null}}function Y(e,o,t){let s=jo(e,o,t);return s||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),s}async function Re(e,o,t){let s=M(),c=W(),r=await G(t.config),i=Y(t,r,c),n=o;if(t.fromFile)try{n=D.readFileSync(t.fromFile,"utf-8");}catch(a){console.log(l.red(`Failed to read file: ${t.fromFile}`)),a instanceof Error&&console.log(l.gray(a.message)),process.exit(1);}n||(console.log(l.red("No value provided")),console.log(l.gray("Provide a value as argument or use --from-file <path>")),process.exit(1)),console.log(""),console.log(l.bold("VAIF Set Secret")),console.log(""),s.start("Checking for existing secret...");try{let a=new URL(`${T}/functions/secrets/project/${i}`);t.envId&&a.searchParams.set("envId",t.envId);let f=await fetch(a.toString(),{headers:{Authorization:`Bearer ${c.token}`}});if(!f.ok)throw new Error(`Failed to check existing secrets: ${await f.text()}`);let d=(await f.json()).find(g=>g.key===e);if(d){s.text=`Updating secret "${e}"...`;let g=await fetch(`${T}/functions/secrets/${d.id}`,{method:"PUT",headers:{Authorization:`Bearer ${c.token}`,"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!g.ok)throw new Error(`Failed to update secret: ${await g.text()}`);s.succeed(`Updated secret "${e}"`);}else {s.text=`Creating secret "${e}"...`;let g=await fetch(`${T}/functions/secrets`,{method:"POST",headers:{Authorization:`Bearer ${c.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:i,envId:t.envId,key:e,value:n})});if(!g.ok)throw new Error(`Failed to create secret: ${await g.text()}`);s.succeed(`Created secret "${e}"`);}console.log("");}catch(a){s.fail("Failed to set secret"),a instanceof Error&&console.log(l.red(`
|
|
36
|
+
Error: ${a.message}`)),process.exit(1);}}async function Oe(e){let o=M(),t=W(),s=await G(e.config),c=Y(e,s,t);console.log(""),console.log(l.bold("VAIF Secrets")),console.log(""),o.start("Fetching secrets...");try{let r=new URL(`${T}/functions/secrets/project/${c}`);e.envId&&r.searchParams.set("envId",e.envId);let i=await fetch(r.toString(),{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok)throw new Error(`Failed to list secrets: ${await i.text()}`);let n=await i.json();if(o.stop(),n.length===0){console.log(l.yellow("No secrets found")),console.log(l.gray(`
|
|
37
37
|
Create one with: vaif secrets set <name> <value>`));return}let a=Math.max(8,...n.map(p=>p.key.length)),f=` ${"Name".padEnd(a)} Created`;console.log(l.gray(f)),console.log(l.gray(" "+"-".repeat(f.length-2)));for(let p of n){let d=p.key.padEnd(a),g=p.createdAt?new Date(p.createdAt).toLocaleDateString():"N/A";console.log(` ${d} ${g}`);}console.log(""),console.log(l.gray(` ${n.length} secret(s) total`)),console.log(l.gray(" Values are hidden. Use `vaif secrets get <name>` to reveal.")),console.log("");}catch(r){o.fail("Failed to list secrets"),r instanceof Error&&console.log(l.red(`
|
|
38
|
-
Error: ${r.message}`)),process.exit(1);}}async function
|
|
39
|
-
Error: ${i.message}`)),process.exit(1);}}async function
|
|
40
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
41
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
42
|
-
Error: ${i.message}`)),process.exit(1);}}program.name("vaif").description("VAIF CLI - Type generation and development tools").version(
|
|
38
|
+
Error: ${r.message}`)),process.exit(1);}}async function Ne(e,o){let t=M(),s=W(),c=await G(o.config),r=Y(o,c,s);console.log(""),t.start("Fetching secret...");try{let i=new URL(`${T}/functions/secrets/project/${r}`);o.envId&&i.searchParams.set("envId",o.envId);let n=await fetch(i.toString(),{headers:{Authorization:`Bearer ${s.token}`}});if(!n.ok)throw new Error(`Failed to fetch secrets: ${await n.text()}`);let f=(await n.json()).find(g=>g.key===e);f||(t.fail(`Secret "${e}" not found`),process.exit(1));let p=await fetch(`${T}/functions/secrets/${f.id}/value`,{headers:{Authorization:`Bearer ${s.token}`}});if(!p.ok)throw new Error(`Failed to get secret value: ${await p.text()}`);let d=await p.json();t.stop(),console.log(d.value);}catch(i){t.fail("Failed to get secret"),i instanceof Error&&console.log(l.red(`
|
|
39
|
+
Error: ${i.message}`)),process.exit(1);}}async function Ve(e,o){let t=M(),s=W(),c=await G(o.config),r=Y(o,c,s);console.log(""),console.log(l.bold("VAIF Delete Secret")),console.log(""),t.start("Finding secret...");try{let i=new URL(`${T}/functions/secrets/project/${r}`);o.envId&&i.searchParams.set("envId",o.envId);let n=await fetch(i.toString(),{headers:{Authorization:`Bearer ${s.token}`}});if(!n.ok)throw new Error(`Failed to fetch secrets: ${await n.text()}`);let f=(await n.json()).find(d=>d.key===e);f||(t.fail(`Secret "${e}" not found`),process.exit(1)),t.text=`Deleting secret "${e}"...`;let p=await fetch(`${T}/functions/secrets/${f.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${s.token}`}});if(!p.ok)throw new Error(`Failed to delete secret: ${await p.text()}`);t.succeed(`Deleted secret "${e}"`),console.log("");}catch(i){t.fail("Failed to delete secret"),i instanceof Error&&console.log(l.red(`
|
|
40
|
+
Error: ${i.message}`)),process.exit(1);}}var Te=process.env.VAIF_API_URL||"https://api.vaif.studio";function Io(e){try{let o=new URL(e);return o.password&&(o.password="****"),o.toString()}catch{return e.replace(/:[^@/]+@/,":****@")}}async function Le(e){let o=M(),t=I();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.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 r=e.projectId||c?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),o.start("Fetching project info...");try{let i=await fetch(`${Te}/v1/projects/${r}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let p=await i.text();throw new Error(`Failed to fetch project: ${p}`)}let n=await i.json();o.stop(),console.log(""),console.log(l.bold("VAIF Project Info")),console.log("");let a=16,f=(p,d)=>{console.log(` ${l.gray(p.padEnd(a))} ${d}`);};f("Name:",l.white(n.name||"N/A")),f("Project ID:",l.white(r)),f("Region:",l.white(n.region||"us-east-1")),f("Plan:",l.white(n.plan||n.tier||"free")),f("Created:",l.white(n.createdAt?new Date(n.createdAt).toLocaleDateString():"N/A")),console.log(""),f("API URL:",l.cyan(n.apiUrl||`${Te}/v1`)),f("WS URL:",l.cyan(n.wsUrl||n.realtimeUrl||"N/A")),f("DB URL:",l.cyan(n.databaseUrl?Io(n.databaseUrl):"N/A")),f("Storage URL:",l.cyan(n.storageUrl||"N/A")),console.log("");}catch(i){o.fail("Failed to fetch project info"),i instanceof Error&&console.log(l.red(`
|
|
41
|
+
Error: ${i.message}`)),process.exit(1);}}var bo=process.env.VAIF_API_URL||"https://api.vaif.studio";async function _e(e){let o=M(),t=I();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.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 r=e.projectId||c?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),o.start("Fetching project status...");try{let i=await fetch(`${bo}/v1/projects/${r}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let w=await i.text();throw new Error(`Failed to fetch project status: ${w}`)}let n=await i.json();o.stop(),console.log(""),console.log(l.bold("VAIF Project Status")),console.log("");let a=22,f=(w,E)=>{console.log(` ${l.gray(w.padEnd(a))} ${E}`);};f("Project:",l.white(n.name||r)),f("Plan:",l.white(n.plan||n.tier||"free")),console.log(""),console.log(l.gray(" --- Resources ---")),console.log("");let p=n.tableCount??n.tables?.length??"N/A",d=n.functionCount??n.functions?.length??"N/A",g=n.bucketCount??n.storage?.buckets?.length??"N/A",y=n.activeConnections??n.connections??"N/A";f("Tables:",l.white(String(p))),f("Functions:",l.white(String(d))),f("Storage Buckets:",l.white(String(g))),f("Active Connections:",l.white(String(y))),n.usage&&(console.log(""),console.log(l.gray(" --- Usage ---")),console.log(""),n.usage.dbSize&&f("Database Size:",l.white(n.usage.dbSize)),n.usage.storageSize&&f("Storage Size:",l.white(n.usage.storageSize)),n.usage.bandwidth&&f("Bandwidth:",l.white(n.usage.bandwidth)),n.usage.functionInvocations!=null&&f("Function Invocations:",l.white(String(n.usage.functionInvocations)))),console.log("");}catch(i){o.fail("Failed to fetch project status"),i instanceof Error&&console.log(l.red(`
|
|
42
|
+
Error: ${i.message}`)),process.exit(1);}}var Ue="1.7.0",oe=l.hex("#00f0ff"),te=l.hex("#7b61ff"),ne=l.hex("#ff3dff"),se=l.hex("#00ff9d"),v=l.hex("#555570"),L=l.hex("#00f0ff");function So(){console.log(""),console.log(oe(" \u2566 \u2566")+te("\u2554\u2550\u2557\u2566")+ne("\u2554\u2550\u2557 ")+se("\u2554\u2550\u2557\u2566 \u2566")),console.log(oe(" \u255A\u2557\u2554\u255D")+te("\u2560\u2550\u2563\u2551")+ne("\u2560\u2563 ")+se("\u2551 \u2551 \u2551")),console.log(oe(" \u255A\u255D ")+te("\u2569 \u2569\u2569")+ne("\u255A ")+se("\u255A\u2550\u255D\u2569\u2550\u255D\u2569")),console.log(""),console.log(v(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(L(" VAIF Studio CLI")+v(` v${Ue}`)),console.log(v(" Build full-stack apps at lightning speed")),console.log(v(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(""),console.log(l.bold(" Quick Start")),console.log(v(" $ ")+L("vaif login")+v(" Authenticate")),console.log(v(" $ ")+L("vaif init -t react-spa")+v(" Scaffold project")),console.log(v(" $ ")+L("vaif db push")+v(" Push migrations")),console.log(v(" $ ")+L("vaif generate")+v(" Generate types")),console.log(v(" $ ")+L("vaif functions deploy")+v(" Deploy functions")),console.log(""),console.log(l.bold(" Categories")),console.log(v(" auth ")+l.white("login, logout, whoami")),console.log(v(" project ")+l.white("init, templates, info, status")),console.log(v(" schema ")+l.white("pull, push, generate")),console.log(v(" database ")+l.white("db push, db pull, db seed, db reset")),console.log(v(" deploy ")+l.white("functions deploy, functions list")),console.log(v(" security ")+l.white("keys, secrets")),console.log(""),console.log(v(" Run ")+L("vaif <command> --help")+v(" for details")),console.log(v(" Docs: ")+l.underline("https://docs.vaif.studio")),console.log("");}program.name("vaif").description("VAIF CLI - Type generation and development tools").version(Ue);program.command("login").description("Authenticate with VAIF (opens browser)").option("-e, --email","Login with email/password instead of browser").option("-p, --project-id <id>","Default project ID").action(fe);program.command("logout").description("Log out and remove stored credentials").action(de);program.command("whoami").description("Show current authenticated user").action(pe);program.command("init").description("Initialize VAIF configuration in your project").option("--typescript","Setup for TypeScript project").option("-f, --force","Overwrite existing config").option("-t, --template <name>","Scaffold from a template (run vaif templates for list)").option("--features <features>","Comma-separated features to include: auth,database,realtime,storage,functions").option("--add-features <features>","Add features to an existing project (requires --template)").action(d);program.command("templates").alias("tpl").description("List available project templates").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(Le);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(_e);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(ue);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(ye);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 ze=program.command("functions").alias("fn").description("Manage serverless functions");ze.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);ze.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($e);var Q=program.command("db").description("Database management commands");Q.command("push").description("Push local Drizzle migrations to VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-d, --dir <path>","Migrations directory","./drizzle").option("--dry-run","Preview without applying").action(Ae);Q.command("pull").description("Pull schema from VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-o, --output <path>","Output file","vaif.schema.json").action(Pe);Q.command("seed").description("Seed your database with test data").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --file <path>","Specific seed file").option("-t, --table <name>","Seed specific table only").option("--truncate","Truncate tables before seeding").option("--dry-run","Preview seeding without inserting data").action(Se);Q.command("reset").description("Reset database (drop all tables and data)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --force","Confirm reset (required)").action(xe);var Je=program.command("keys").description("Manage API keys");Je.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(De);Je.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(Ee);var H=program.command("secrets").alias("sec").description("Manage function secrets");H.command("set <name> [value]").description("Create or update a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").option("--from-file <path>","Read secret value from a file").action(Re);H.command("list").alias("ls").description("List all secrets (names only)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Oe);H.command("get <name>").description("Reveal a secret value").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Ne);H.command("delete <name>").description("Delete a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Ve);process.argv.slice(2).length||(So(),process.exit(0));program.parse(process.argv);
|