@vaiftech/cli 1.8.1 → 1.9.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 +2 -2
- package/dist/cli.cjs +235 -18
- package/dist/cli.js +241 -24
- 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.9.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
|
|
|
@@ -280,7 +280,7 @@ vaif claude-setup -o ./my-app # Custom output directory
|
|
|
280
280
|
**Generated files:**
|
|
281
281
|
|
|
282
282
|
- **`.mcp.json`** — Configures the `@vaiftech/mcp` server so Claude Code can query your database, manage schema, upload files, invoke functions, and more.
|
|
283
|
-
- **`CLAUDE.md`** — Gives Claude full context about your project: SDK setup with your actual API key, complete database schema with types and constraints, CRUD examples using your real table names, auth/storage/realtime/functions usage patterns, and filter/pagination reference.
|
|
283
|
+
- **`CLAUDE.md`** — Gives Claude full context about your project: SDK setup with your actual API key, complete database schema with types and constraints, CRUD examples using your real table names, auth/storage/realtime/functions usage patterns, row-level security (RLS), storage policies, edge function deployment, API key management, secrets management, and filter/pagination reference.
|
|
284
284
|
|
|
285
285
|
## Configuration
|
|
286
286
|
|
package/dist/cli.cjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';require('dotenv/config');var commander=require('commander'),f=require('chalk'),U=require('fs'),S=require('path'),xt=require('pg'),Q=require('ora'),Pt=require('prettier'),mt=require('dotenv'),ht=require('os'),child_process=require('child_process'),Ee=require('readline');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var f__default=/*#__PURE__*/_interopDefault(f);var U__default=/*#__PURE__*/_interopDefault(U);var S__default=/*#__PURE__*/_interopDefault(S);var xt__default=/*#__PURE__*/_interopDefault(xt);var Q__default=/*#__PURE__*/_interopDefault(Q);var Pt__default=/*#__PURE__*/_interopDefault(Pt);var mt__default=/*#__PURE__*/_interopDefault(mt);var ht__default=/*#__PURE__*/_interopDefault(ht);var Ee__default=/*#__PURE__*/_interopDefault(Ee);mt__default.default.config();async function A(t){let e=S__default.default.resolve(t);if(!U__default.default.existsSync(e))return null;try{let o=U__default.default.readFileSync(e,"utf-8"),n=JSON.parse(o);return n.database?.url&&(n.database.url=Se(n.database.url)),n.api?.apiKey&&(n.api.apiKey=Se(n.api.apiKey)),n}catch{throw new Error(`Failed to parse config file: ${t}`)}}function Se(t){return t.replace(/\$\{([^}]+)\}/g,(e,o)=>process.env[o]||e)}var se=S__default.default.join(ht__default.default.homedir(),".vaif"),
|
|
2
|
+
'use strict';require('dotenv/config');var commander=require('commander'),f=require('chalk'),U=require('fs'),S=require('path'),xt=require('pg'),Q=require('ora'),Pt=require('prettier'),mt=require('dotenv'),ht=require('os'),child_process=require('child_process'),Ee=require('readline');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var f__default=/*#__PURE__*/_interopDefault(f);var U__default=/*#__PURE__*/_interopDefault(U);var S__default=/*#__PURE__*/_interopDefault(S);var xt__default=/*#__PURE__*/_interopDefault(xt);var Q__default=/*#__PURE__*/_interopDefault(Q);var Pt__default=/*#__PURE__*/_interopDefault(Pt);var mt__default=/*#__PURE__*/_interopDefault(mt);var ht__default=/*#__PURE__*/_interopDefault(ht);var Ee__default=/*#__PURE__*/_interopDefault(Ee);mt__default.default.config();async function A(t){let e=S__default.default.resolve(t);if(!U__default.default.existsSync(e))return null;try{let o=U__default.default.readFileSync(e,"utf-8"),n=JSON.parse(o);return n.database?.url&&(n.database.url=Se(n.database.url)),n.api?.apiKey&&(n.api.apiKey=Se(n.api.apiKey)),n}catch{throw new Error(`Failed to parse config file: ${t}`)}}function Se(t){return t.replace(/\$\{([^}]+)\}/g,(e,o)=>process.env[o]||e)}var se=S__default.default.join(ht__default.default.homedir(),".vaif"),M=S__default.default.join(se,"auth.json"),H=process.env.VAIF_API_URL||"https://api.vaif.studio";function vt(){U__default.default.existsSync(se)||U__default.default.mkdirSync(se,{recursive:true});}function xe(t){vt(),U__default.default.writeFileSync(M,JSON.stringify(t,null,2),"utf-8"),U__default.default.chmodSync(M,384);}function I(){if(!U__default.default.existsSync(M))return null;try{let t=U__default.default.readFileSync(M,"utf-8");return JSON.parse(t)}catch{return null}}function bt(t){let e=Ee__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}function It(t){return new Promise(e=>{let o=Ee__default.default.createInterface({input:process.stdin,output:process.stdout});process.stdin;let r=process.stdout.write.bind(process.stdout),i=false;process.stdout.write=((...s)=>i?true:r(...s)),o.question(t,s=>{i=false,process.stdout.write=r,console.log(""),o.close(),e(s);}),i=true;})}function At(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 wt(t){return new Promise(e=>setTimeout(e,t))}async function St(t){try{let e=await fetch(`${H}/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 _t(t){let e=Q__default.default();e.start("Setting up authentication...");let o,n;try{let a=await fetch(`${H}/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(`
|
|
3
3
|
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(`
|
|
4
4
|
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(""),At(n),e.start("Waiting for browser authentication...");let r=12e4,i=2e3,s=Date.now();for(;Date.now()-s<r;){await wt(i);try{let a=await fetch(`${H}/auth/cli/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:o})});if(!a.ok){let d=await a.json();(d.error==="ExpiredCode"||d.error==="InvalidCode")&&(e.fail("Authentication expired"),console.log(f__default.default.red(`
|
|
5
|
-
The authentication session expired. Please try again.`)),process.exit(1));continue}let l=await a.json();if(l.ok&&l.accessToken){let d={token:l.accessToken,email:l.user?.email,projectId:t,expiresAt:new Date(Date.now()+l.expiresIn*1e3).toISOString()};xe(d),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: ${
|
|
5
|
+
The authentication session expired. Please try again.`)),process.exit(1));continue}let l=await a.json();if(l.ok&&l.accessToken){let d={token:l.accessToken,email:l.user?.email,projectId:t,expiresAt:new Date(Date.now()+l.expiresIn*1e3).toISOString()};xe(d),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: ${M}`)),console.log("");return}}catch{}}e.fail("Authentication timed out"),console.log(f__default.default.red(`
|
|
6
6
|
Timed out waiting for browser authentication.`)),console.log(f__default.default.gray("Try again or use: vaif login --email")),process.exit(1);}async function Et(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 bt(f__default.default.cyan(" Email: "));(!e||e.trim()==="")&&(console.log(f__default.default.red(`
|
|
7
7
|
No email provided. Login cancelled.`)),process.exit(1));let o=await It(f__default.default.cyan(" Password: "));(!o||o.trim()==="")&&(console.log(f__default.default.red(`
|
|
8
8
|
No password provided. Login cancelled.`)),process.exit(1));let n=Q__default.default("Authenticating...").start();try{let r=await fetch(`${H}/auth/cli/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e.trim(),password:o})}),i=await r.json();(!r.ok||!i.ok)&&(n.fail("Login failed"),console.log(f__default.default.red(`
|
|
9
|
-
${i.message||"Invalid email or password."}`)),process.exit(1));let s={token:i.accessToken,email:i.user?.email,projectId:t,expiresAt:new Date(Date.now()+i.expiresIn*1e3).toISOString()};xe(s),n.succeed("Logged in successfully"),console.log(""),i.user?.email&&console.log(f__default.default.green(` Authenticated as: ${i.user.email}`)),console.log(f__default.default.gray(` Config saved to: ${
|
|
10
|
-
Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function Te(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 Et(t.projectId):await _t(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(){U__default.default.existsSync(
|
|
9
|
+
${i.message||"Invalid email or password."}`)),process.exit(1));let s={token:i.accessToken,email:i.user?.email,projectId:t,expiresAt:new Date(Date.now()+i.expiresIn*1e3).toISOString()};xe(s),n.succeed("Logged in successfully"),console.log(""),i.user?.email&&console.log(f__default.default.green(` Authenticated as: ${i.user.email}`)),console.log(f__default.default.gray(` Config saved to: ${M}`)),console.log("");}catch{n.fail("Failed to connect to VAIF API"),console.log(f__default.default.red(`
|
|
10
|
+
Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function Te(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 Et(t.projectId):await _t(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(){U__default.default.existsSync(M)?(U__default.default.unlinkSync(M),console.log(f__default.default.green("Logged out successfully"))):console.log(f__default.default.yellow("Not currently logged in"));}async function Fe(){let t=I();(!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=Q__default.default("Checking authentication...").start(),{valid:o,email:n}=await St(t.token);o||(e.fail("Session expired"),console.log(f__default.default.yellow(`
|
|
11
11
|
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 Ft=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Ct(t,e){let o=await fetch(`${Ft}/schema-engine/introspect/${e}`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!o.ok){let a=await o.text();throw new Error(`API introspection failed: ${a}`)}let n=await o.json();if(!n.ok||!n.schemaExists)throw new Error("Project schema does not exist yet. Push a migration first with `vaif db push`.");let r=new Map,i=[];for(let a of n.tables){let l=a.columns.map(d=>({column_name:d.name,data_type:d.type,is_nullable:d.nullable?"YES":"NO",column_default:d.default,udt_name:d.type,is_identity:d.primaryKey&&d.default?.includes("gen_random_uuid")?"YES":"NO",character_maximum_length:null,numeric_precision:null,numeric_scale:null}));r.set(a.name,l);for(let d of a.foreignKeys)i.push({constraint_name:d.constraintName,table_name:a.name,column_name:d.columnName,foreign_table_name:d.refTable,foreign_column_name:d.refColumn});}return {tables:r,enums:new Map,foreignKeys:i}}async function jt(t,e){let o=await t.query(`
|
|
12
12
|
SELECT table_name, table_type
|
|
13
13
|
FROM information_schema.tables
|
|
@@ -54,9 +54,9 @@ Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Aut
|
|
|
54
54
|
JOIN pg_namespace n ON n.oid = t.typnamespace
|
|
55
55
|
WHERE n.nspname = $1
|
|
56
56
|
ORDER BY t.typname, e.enumsortorder
|
|
57
|
-
`,[e]),s=new Map;for(let l of o.rows)s.set(l.table_name,[]);for(let l of n.rows){let d=s.get(l.table_name);d&&d.push(l);}let a=new Map;for(let l of i.rows){let d=a.get(l.enum_name)||[];d.push(l.enum_value),a.set(l.enum_name,d);}return {tables:s,enums:a,foreignKeys:r.rows}}var ce={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 Rt(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 s=n.replace(/^_/,"");if(e.has(s)){let d=e.get(s).map(u=>`"${u}"`).join(" | ");return r==="YES"?`(${d})[] | null`:`(${d})[]`}let a=ce[s]||"unknown";return r==="YES"?`${a}[] | null`:`${a}[]`}let i=ce[o]||ce[n]||"unknown";return r==="YES"&&(i=`${i} | null`),i}function de(t){return t.split(/[_\-\s]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function
|
|
57
|
+
`,[e]),s=new Map;for(let l of o.rows)s.set(l.table_name,[]);for(let l of n.rows){let d=s.get(l.table_name);d&&d.push(l);}let a=new Map;for(let l of i.rows){let d=a.get(l.enum_name)||[];d.push(l.enum_value),a.set(l.enum_name,d);}return {tables:s,enums:a,foreignKeys:r.rows}}var ce={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 Rt(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 s=n.replace(/^_/,"");if(e.has(s)){let d=e.get(s).map(u=>`"${u}"`).join(" | ");return r==="YES"?`(${d})[] | null`:`(${d})[]`}let a=ce[s]||"unknown";return r==="YES"?`${a}[] | null`:`${a}[]`}let i=ce[o]||ce[n]||"unknown";return r==="YES"&&(i=`${i} | null`),i}function de(t){return t.split(/[_\-\s]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function kt(t,e){let o=de(t),n=e.map(r=>` | "${r}"`).join(`
|
|
58
58
|
`);return `export type ${o} =
|
|
59
|
-
${n};`}function
|
|
59
|
+
${n};`}function Lt(t,e,o){let n=de(t),r=[],i=[],s=[];for(let u of e){let p=Rt(u,o),c=u.column_name,g=u.column_default!==null||u.is_identity==="YES",h=u.is_nullable==="YES";r.push(` ${c}: ${p};`),g||u.column_name==="id"?i.push(` ${c}?: ${p.replace(" | null","")} | null;`):h?i.push(` ${c}?: ${p};`):i.push(` ${c}: ${p.replace(" | null","")};`),s.push(` ${c}?: ${p.replace(" | null","")} | null;`);}let a=`export interface ${n} {
|
|
60
60
|
${r.join(`
|
|
61
61
|
`)}
|
|
62
62
|
}`,l=`export interface ${n}Insert {
|
|
@@ -65,13 +65,13 @@ ${i.join(`
|
|
|
65
65
|
}`,d=`export interface ${n}Update {
|
|
66
66
|
${s.join(`
|
|
67
67
|
`)}
|
|
68
|
-
}`;return {base:a,insert:l,update:d}}function
|
|
68
|
+
}`;return {base:a,insert:l,update:d}}function Nt(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[i,s]of e)n.push(kt(i,s)),n.push("");}n.push("// ============ TABLES ============"),n.push("");let r=[];for(let[i,s]of t){let{base:a,insert:l,update:d}=Lt(i,s,e);r.push(i),n.push(a),n.push(""),n.push(l),n.push(""),n.push(d),n.push("");}n.push("// ============ DATABASE SCHEMA ============"),n.push(""),n.push("export interface Database {");for(let i of r){let s=de(i);n.push(` ${i}: {`),n.push(` Row: ${s};`),n.push(` Insert: ${s}Insert;`),n.push(` Update: ${s}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(`
|
|
69
69
|
`)}async function je(t){let e=Q__default.default("Loading configuration...").start();try{let o=await A(t.config),n=t.connection||o?.database?.url||process.env.DATABASE_URL,r=n&&!n.includes("${"),i,s,a;if(r){e.text="Connecting to database...";let c=new xt__default.default.Client({connectionString:n});await c.connect(),e.text="Introspecting schema...",{tables:i,enums:s,foreignKeys:a}=await jt(c,t.schema),await c.end();}else {let c=I();(!c||!c.token)&&(e.fail("No database connection and not logged in"),console.log(f__default.default.yellow(`
|
|
70
70
|
Either:`)),console.log(f__default.default.gray(" 1. Run `vaif login` to authenticate (no DATABASE_URL needed)")),console.log(f__default.default.gray(" 2. Set DATABASE_URL in your .env file")),console.log(f__default.default.gray(" 3. Pass --connection postgresql://user:pass@host:5432/db")),process.exit(1));let g=o?.projectId||process.env.VAIF_PROJECT_ID||c.projectId;g||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
|
|
71
71
|
Set projectId in vaif.config.json or use VAIF_PROJECT_ID env var.`)),process.exit(1)),e.text="Introspecting schema via API...",{tables:i,enums:s,foreignKeys:a}=await Ct(c.token,g);}if(i.size===0){e.warn("No tables found"),console.log(f__default.default.yellow(`
|
|
72
|
-
Push a migration first: vaif db push`));return}e.text=`Generating types for ${i.size} tables...`;let l=
|
|
72
|
+
Push a migration first: vaif db push`));return}e.text=`Generating types for ${i.size} tables...`;let l=Nt(i,s,a),d=await Pt__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(d),console.log(f__default.default.gray("\u2500".repeat(60)));return}let u=S__default.default.resolve(t.output),p=S__default.default.dirname(u);U__default.default.existsSync(p)||U__default.default.mkdirSync(p,{recursive:!0}),U__default.default.writeFileSync(u,d,"utf-8"),e.succeed(`Generated types for ${i.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: ${i.size}`)),console.log(f__default.default.gray(` Enums: ${s.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(`
|
|
73
73
|
Error: ${o.message}`)),o.message.includes("ECONNREFUSED")&&console.log(f__default.default.yellow(`
|
|
74
|
-
Make sure your database is running and accessible.`))),process.exit(1);}}var q=[{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"}],
|
|
74
|
+
Make sure your database is running and accessible.`))),process.exit(1);}}var q=[{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"}],ke={"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:`{
|
|
75
75
|
"name": "my-vaif-app",
|
|
76
76
|
"private": true,
|
|
77
77
|
"version": "0.1.0",
|
|
@@ -3775,19 +3775,19 @@ export const posts = pgTable("posts", {
|
|
|
3775
3775
|
|
|
3776
3776
|
return Response.json({ message: \`Hello, \${name}!\` });
|
|
3777
3777
|
}
|
|
3778
|
-
`}]},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
|
|
3779
|
-
? Which VAIF features do you want to include?`)),q.forEach((a,l)=>{let d=e.has(l)?f__default.default.green("[x]"):"[ ]",u=l===o?f__default.default.cyan("> "):" ";console.log(`${u}${d} ${a.label} ${f__default.default.gray(`(${a.description})`)}`);}),console.log(f__default.default.gray(" (up/down to move, space to toggle, enter to confirm)"));}s(),process.stdin.on("keypress",(a,l)=>{if(l.name==="up"&&o>0)o--,i();else if(l.name==="down"&&o<q.length-1)o++,i();else if(l.name==="space")e.has(o)?e.delete(o):e.add(o),i();else if(l.name==="return"){process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close();let d=[...e].sort().map(u=>q[u].name);n(d.length>0?d:t);}else l.name==="c"&&l.ctrl&&(process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close(),process.exit(0));});})}async function ue(t,e={}){let o=
|
|
3778
|
+
`}]},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 Le(){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(ke))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 Vt(t){if(!process.stdin.isTTY||!process.stdout.isTTY)return t;let e=new Set(t.map(n=>q.findIndex(r=>r.name===n)).filter(n=>n>=0)),o=0;return new Promise(n=>{let r=Ee__default.default.createInterface({input:process.stdin,output:process.stdout});Ee__default.default.emitKeypressEvents(process.stdin,r),process.stdin.setRawMode&&process.stdin.setRawMode(true);function i(){let a=q.length+2;process.stdout.write(`\x1B[${a}A`),s();}function s(){console.log(f__default.default.bold(`
|
|
3779
|
+
? Which VAIF features do you want to include?`)),q.forEach((a,l)=>{let d=e.has(l)?f__default.default.green("[x]"):"[ ]",u=l===o?f__default.default.cyan("> "):" ";console.log(`${u}${d} ${a.label} ${f__default.default.gray(`(${a.description})`)}`);}),console.log(f__default.default.gray(" (up/down to move, space to toggle, enter to confirm)"));}s(),process.stdin.on("keypress",(a,l)=>{if(l.name==="up"&&o>0)o--,i();else if(l.name==="down"&&o<q.length-1)o++,i();else if(l.name==="space")e.has(o)?e.delete(o):e.add(o),i();else if(l.name==="return"){process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close();let d=[...e].sort().map(u=>q[u].name);n(d.length>0?d:t);}else l.name==="c"&&l.ctrl&&(process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close(),process.exit(0));});})}async function ue(t,e={}){let o=ke[t];o||(console.log(f__default.default.red(`
|
|
3780
3780
|
Unknown template: ${t}`)),console.log(f__default.default.yellow(`Run 'vaif templates' to see available templates.
|
|
3781
3781
|
`)),process.exit(1));let n;e.features&&e.features.length>0?n=e.features.filter(c=>q.some(g=>g.name===c)):e.addOnly?(console.log(f__default.default.red(`
|
|
3782
|
-
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
|
|
3783
|
-
`,"utf-8"),console.log(f__default.default.green(` merge ${c.path} (added dependencies)`)),l++;continue}catch{}if(U__default.default.existsSync(g)&&!e.force){console.log(f__default.default.yellow(` skip ${c.path} (already exists)`)),d++;continue}U__default.default.writeFileSync(g,c.content,"utf-8"),console.log(f__default.default.green(` create ${c.path}`)),l++;}console.log(""),l>0&&console.log(f__default.default.green(`Created ${l} file${l!==1?"s":""}.`)),d>0&&console.log(f__default.default.yellow(`Skipped ${d} file${d!==1?"s":""} (use --force to overwrite).`));let u={auth:{"@vaiftech/auth":"^1.0.0"},database:{},realtime:{},storage:{},functions:{}},p=S__default.default.resolve("package.json");if(U__default.default.existsSync(p)&&n.length>0)try{let c=JSON.parse(U__default.default.readFileSync(p,"utf-8")),g=!1;for(let h of n){let E=u[h];if(E)for(let[
|
|
3784
|
-
`,"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 Ut={$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
|
|
3782
|
+
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 Vt(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],i=new Set,s=[];if(o.featureFiles)for(let c of n){let g=o.featureFiles[c];if(g)for(let h of g)i.add(h.path),s.push(h);}let a=r.filter(c=>!i.has(c.path)).concat(s),l=0,d=0;for(let c of a){let g=S__default.default.resolve(c.path),h=S__default.default.dirname(g);if(U__default.default.existsSync(h)||U__default.default.mkdirSync(h,{recursive:true}),c.path==="package.json"&&U__default.default.existsSync(g)&&!e.force)try{let E=JSON.parse(U__default.default.readFileSync(g,"utf-8")),V=JSON.parse(c.content),$=Ie=>{if(!Ie)return {};let Ae={};for(let[ft,W]of Object.entries(Ie))!W.startsWith("workspace:")&&!W.startsWith("link:")&&!W.startsWith("file:")&&(Ae[ft]=W);return Ae};E.dependencies={...$(E.dependencies),...V.dependencies||{}},E.devDependencies={...$(E.devDependencies),...V.devDependencies||{}},V.scripts&&(E.scripts={...E.scripts||{},...V.scripts}),U__default.default.writeFileSync(g,JSON.stringify(E,null,2)+`
|
|
3783
|
+
`,"utf-8"),console.log(f__default.default.green(` merge ${c.path} (added dependencies)`)),l++;continue}catch{}if(U__default.default.existsSync(g)&&!e.force){console.log(f__default.default.yellow(` skip ${c.path} (already exists)`)),d++;continue}U__default.default.writeFileSync(g,c.content,"utf-8"),console.log(f__default.default.green(` create ${c.path}`)),l++;}console.log(""),l>0&&console.log(f__default.default.green(`Created ${l} file${l!==1?"s":""}.`)),d>0&&console.log(f__default.default.yellow(`Skipped ${d} file${d!==1?"s":""} (use --force to overwrite).`));let u={auth:{"@vaiftech/auth":"^1.0.0"},database:{},realtime:{},storage:{},functions:{}},p=S__default.default.resolve("package.json");if(U__default.default.existsSync(p)&&n.length>0)try{let c=JSON.parse(U__default.default.readFileSync(p,"utf-8")),g=!1;for(let h of n){let E=u[h];if(E)for(let[V,$]of Object.entries(E))c.dependencies?.[V]||(c.dependencies=c.dependencies||{},c.dependencies[V]=$,g=!0);}g&&U__default.default.writeFileSync(p,JSON.stringify(c,null,2)+`
|
|
3784
|
+
`,"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 Ut={$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 Ne(t){if(t.addFeatures){t.template||(console.log(f__default.default.red(`
|
|
3785
3785
|
--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 ue(t.template,{force:t.force,features:n,addOnly:true});return}let e=Q__default.default("Initializing VAIF configuration...").start(),o=S__default.default.resolve("vaif.config.json");U__default.default.existsSync(o)&&!t.force&&(e.fail("vaif.config.json already exists"),console.log(f__default.default.yellow(`
|
|
3786
3786
|
Use --force to overwrite existing configuration.`)),process.exit(1));try{if(U__default.default.writeFileSync(o,JSON.stringify(Ut,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 ue(t.template,{force:t.force,features:n});}else {let n=S__default.default.resolve(".env.example");if(U__default.default.existsSync(n)||(U__default.default.writeFileSync(n,`# VAIF Configuration
|
|
3787
3787
|
DATABASE_URL=postgresql://user:password@localhost:5432/database
|
|
3788
3788
|
VAIF_API_KEY=your-api-key
|
|
3789
3789
|
`,"utf-8"),console.log(f__default.default.gray("Created .env.example"))),t.typescript){let r=S__default.default.resolve("src/types");U__default.default.existsSync(r)||(U__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(`
|
|
3790
|
-
Error: ${n.message}`)),process.exit(1);}}var
|
|
3790
|
+
Error: ${n.message}`)),process.exit(1);}}var Mt=process.env.VAIF_API_URL||"https://api.vaif.studio";async function zt(t,e,o="public"){let n=await fetch(`${Mt}/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 Ve(t){let e=Q__default.default(),o=I();(!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 A(n);}catch(s){e.fail("Failed to load config"),console.log(f__default.default.red(`
|
|
3791
3791
|
Error: ${s}`)),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 i=t.projectId||r.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
|
|
3792
3792
|
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let s=t.schema||r.database?.schema||"public",a=await zt(o.token,i,s);e.succeed("Schema fetched successfully");let l=t.output||S__default.default.resolve("vaif.schema.json"),d={$schema:"https://vaif.studio/schemas/schema.json",projectId:i,schema:s,pulledAt:new Date().toISOString(),...a};U__default.default.writeFileSync(l,JSON.stringify(d,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(s){e.fail("Failed to fetch schema"),s instanceof Error&&console.log(f__default.default.red(`
|
|
3793
3793
|
Error: ${s.message}`)),process.exit(1);}}var Ue=process.env.VAIF_API_URL||"https://api.vaif.studio";function Jt(t){let e=Ee__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}async function Gt(t,e,o){let n=await fetch(`${Ue}/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 Wt(t,e,o){let n=await fetch(`${Ue}/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 Ht(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 $e(t){let e=Q__default.default(),o=I();(!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 A(n);}catch(l){e.fail("Failed to load config"),console.log(f__default.default.red(`
|
|
@@ -3796,10 +3796,10 @@ Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));
|
|
|
3796
3796
|
Expected schema file at: ${s}`)),console.log(f__default.default.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let a;try{let l=U__default.default.readFileSync(s,"utf-8");a=JSON.parse(l);}catch(l){e.fail("Failed to parse schema file"),l instanceof Error&&console.log(f__default.default.red(`
|
|
3797
3797
|
Error: ${l.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:l,sql:d}=await Gt(o.token,i,a);if(e.stop(),Ht(l),l.added.length===0&&l.modified.length===0&&l.removed.length===0){console.log("");return}if(d.length>0){console.log(f__default.default.bold("SQL Migrations:")),console.log("");for(let p of d)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 c=await Jt(f__default.default.cyan("Apply these changes? [y/N] "));if(c.toLowerCase()!=="y"&&c.toLowerCase()!=="yes"){console.log(f__default.default.yellow(`
|
|
3798
3798
|
Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let u=await Wt(o.token,i,a);if(u.success){if(e.succeed("Schema changes applied successfully"),console.log(""),u.migrations.length>0){console.log(f__default.default.gray("Migrations applied:"));for(let p of u.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(`
|
|
3799
|
-
Error: ${l.message}`)),process.exit(1);}}var X=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Xt(t,e,o,n){let r=new URL(`${X}/functions/project/${e}`);n&&r.searchParams.set("envId",n);let i=await fetch(r.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!i.ok)return null;let s=await i.json(),a=s.functions||s;return Array.isArray(a)&&a.find(l=>l.name===o)||null}async function Qt(t,e,o){let n=await fetch(`${X}/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 Zt(t,e,o){let n=await fetch(`${X}/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 eo(t,e,o){let n=new URL(`${X}/functions/project/${e}`);o&&n.searchParams.set("envId",o);let r=await fetch(n.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!r.ok){let s=await r.text();throw new Error(`Failed to list functions: ${s}`)}let i=await r.json();return i.functions||i}function Oe(t){switch(S__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
|
|
3799
|
+
Error: ${l.message}`)),process.exit(1);}}var X=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Xt(t,e,o,n){let r=new URL(`${X}/functions/project/${e}`);n&&r.searchParams.set("envId",n);let i=await fetch(r.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!i.ok)return null;let s=await i.json(),a=s.functions||s;return Array.isArray(a)&&a.find(l=>l.name===o)||null}async function Qt(t,e,o){let n=await fetch(`${X}/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 Zt(t,e,o){let n=await fetch(`${X}/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 eo(t,e,o){let n=new URL(`${X}/functions/project/${e}`);o&&n.searchParams.set("envId",o);let r=await fetch(n.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!r.ok){let s=await r.text();throw new Error(`Failed to list functions: ${s}`)}let i=await r.json();return i.functions||i}function Oe(t){switch(S__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 Ke(t){let e=[],o=[".ts",".js",".mjs",".py",".go",".rs"],n=["drizzle.config.ts","tsconfig.json","package.json"];if(!U__default.default.existsSync(t))return e;let r=U__default.default.readdirSync(t,{withFileTypes:true});for(let i of r){let s=S__default.default.join(t,i.name);if(i.isDirectory()){if(i.name!=="node_modules"&&!i.name.startsWith(".")){let a=U__default.default.readdirSync(s,{withFileTypes:true});for(let l of a)if(l.isFile()){let d=S__default.default.extname(l.name).toLowerCase();if(o.includes(d)){e.push(S__default.default.join(s,l.name));break}}}}else if(i.isFile()){let a=S__default.default.extname(i.name).toLowerCase();o.includes(a)&&!n.includes(i.name)&&e.push(s);}}return e}async function ze(t){let e=Q__default.default(),o=I();(!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 A(n);}catch{}let i=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(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 s=S__default.default.resolve("functions"),a=S__default.default.resolve("src/functions"),l=[];if(t.entrypoint){let c=S__default.default.resolve(t.entrypoint);U__default.default.existsSync(c)||(e.fail(`File not found: ${t.entrypoint}`),process.exit(1)),l=[c];}else l=[...Ke(s),...Ke(a)];l.length===0&&(e.fail("No function files found"),console.log(f__default.default.yellow(`
|
|
3800
3800
|
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(`
|
|
3801
3801
|
Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${l.length} function(s)`),t.name&&(l=l.filter(c=>S__default.default.basename(c,S__default.default.extname(c)).includes(t.name)),l.length===0&&(console.log(f__default.default.yellow(`
|
|
3802
|
-
No functions matching "${t.name}" found`)),process.exit(1))),console.log(""),console.log(f__default.default.gray("Functions to deploy:"));for(let c of l){let g=S__default.default.basename(S__default.default.dirname(c)),h=g==="functions"||g==="src"?S__default.default.basename(c,S__default.default.extname(c)):g,E=t.runtime||Oe(c);console.log(f__default.default.gray(` - ${h} (${E})`));}if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no functions deployed."));return}let d=[];for(let c of l){let g=S__default.default.basename(S__default.default.dirname(c)),h=g==="functions"||g==="src"?S__default.default.basename(c,S__default.default.extname(c)):g,E=t.runtime||Oe(c);e.start(`Deploying ${h}...`);try{let
|
|
3802
|
+
No functions matching "${t.name}" found`)),process.exit(1))),console.log(""),console.log(f__default.default.gray("Functions to deploy:"));for(let c of l){let g=S__default.default.basename(S__default.default.dirname(c)),h=g==="functions"||g==="src"?S__default.default.basename(c,S__default.default.extname(c)):g,E=t.runtime||Oe(c);console.log(f__default.default.gray(` - ${h} (${E})`));}if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no functions deployed."));return}let d=[];for(let c of l){let g=S__default.default.basename(S__default.default.dirname(c)),h=g==="functions"||g==="src"?S__default.default.basename(c,S__default.default.extname(c)):g,E=t.runtime||Oe(c);e.start(`Deploying ${h}...`);try{let V=U__default.default.readFileSync(c,"utf-8"),$=await Xt(o.token,i,h,t.envId);$||(e.text=`Creating ${h}...`,$=await Qt(o.token,i,{name:h,runtime:E,entrypoint:S__default.default.basename(c),envId:t.envId})),e.text=`Deploying ${h}...`,await Zt(o.token,$.id,V),e.succeed(`Deployed ${h}`),d.push({name:h,success:!0});}catch(V){let $=V instanceof Error?V.message:"Unknown error";e.fail(`Failed to deploy ${h}`),d.push({name:h,success:false,error:$});}}console.log("");let u=d.filter(c=>c.success).length;if(d.filter(c=>!c.success).length===0)console.log(f__default.default.green(`\u2713 Successfully deployed ${u} function(s)`));else {console.log(f__default.default.yellow(`Deployed ${u}/${d.length} function(s)`)),console.log(""),console.log(f__default.default.red("Failed deployments:"));for(let c of d.filter(g=>!g.success))console.log(f__default.default.red(` - ${c.name}: ${c.error}`));}console.log("");}async function Be(t){let e=Q__default.default(),o=I();(!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 A(n);}catch{}let i=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(console.log(f__default.default.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let s=await eo(o.token,i,t.envId);if(e.stop(),s.length===0){console.log(f__default.default.yellow(`
|
|
3803
3803
|
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 (${s.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 s){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(s){e.fail("Failed to fetch functions"),s instanceof Error&&console.log(f__default.default.red(`
|
|
3804
3804
|
Error: ${s.message}`)),process.exit(1);}}var Z=process.env.VAIF_API_URL||"https://api.vaif.studio";async function to(t,e,o,n,r){let i=await fetch(`${Z}/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(!i.ok){let s=await i.text();throw new Error(`Failed to seed ${o}: ${s}`)}return i.json()}async function oo(t,e){let o=await fetch(`${Z}/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 ge(t){let e=[];if(!U__default.default.existsSync(t))return e;let o=U__default.default.readdirSync(t,{withFileTypes:true});for(let n of o)if(n.isFile()){let r=S__default.default.extname(n.name).toLowerCase();(r===".json"||r===".ts"||r===".js")&&e.push(S__default.default.join(t,n.name));}return e.sort()}async function qe(t){let e=S__default.default.extname(t).toLowerCase();if(e===".json"){let o=U__default.default.readFileSync(t,"utf-8"),n=JSON.parse(o);return Array.isArray(n)?[{table:S__default.default.basename(t,e),data:n}]:n.table&&n.data?[n]:Object.entries(n).map(([r,i])=>({table:r,data:i}))}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 Ye(t){let e=Q__default.default(),o=I();(!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 A(n);}catch{}let i=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(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 s=[];if(t.file){let u=S__default.default.resolve(t.file);U__default.default.existsSync(u)||(console.log(f__default.default.red(`File not found: ${t.file}`)),process.exit(1)),s=[u];}else {let u=S__default.default.resolve("seeds"),p=S__default.default.resolve("prisma/seed"),c=S__default.default.resolve("db/seeds");s=[...ge(u),...ge(p),...ge(c)];}s.length===0&&(console.log(f__default.default.yellow("No seed files found")),console.log(f__default.default.gray(`
|
|
3805
3805
|
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(`
|
|
@@ -3977,6 +3977,223 @@ channel.subscribe();
|
|
|
3977
3977
|
channel.unsubscribe();
|
|
3978
3978
|
\`\`\`
|
|
3979
3979
|
|
|
3980
|
+
## Row-Level Security (RLS)
|
|
3981
|
+
|
|
3982
|
+
Filter data per-user by sending the \`X-VAIF-RLS\` header with your requests. The header format is \`field:value\`, comma-separated for multiple fields.
|
|
3983
|
+
|
|
3984
|
+
\`\`\`typescript
|
|
3985
|
+
// SDK: pass RLS context to scope queries to the current user
|
|
3986
|
+
const posts = await vaif.from("posts").select({
|
|
3987
|
+
headers: { "x-vaif-rls": \`user_id:\${currentUser.id}\` },
|
|
3988
|
+
});
|
|
3989
|
+
|
|
3990
|
+
// Multiple RLS fields (e.g., multi-tenant + user scoping)
|
|
3991
|
+
const data = await vaif.from("documents").select({
|
|
3992
|
+
headers: { "x-vaif-rls": \`org_id:\${orgId},user_id:\${userId}\` },
|
|
3993
|
+
});
|
|
3994
|
+
\`\`\`
|
|
3995
|
+
|
|
3996
|
+
**How it works:**
|
|
3997
|
+
- On **SELECT / UPDATE / DELETE**: RLS fields are added as WHERE conditions (e.g., \`WHERE user_id = $1\`)
|
|
3998
|
+
- On **INSERT**: RLS fields are auto-populated into the record if not already provided
|
|
3999
|
+
- This enables multi-tenant data isolation without database-level RLS policies
|
|
4000
|
+
|
|
4001
|
+
## Realtime Setup
|
|
4002
|
+
|
|
4003
|
+
Enable realtime on your tables, then subscribe to live changes:
|
|
4004
|
+
|
|
4005
|
+
\`\`\`typescript
|
|
4006
|
+
// 1. Enable realtime on tables via API
|
|
4007
|
+
await fetch("${n}/realtime/install", {
|
|
4008
|
+
method: "POST",
|
|
4009
|
+
headers: {
|
|
4010
|
+
Authorization: \`Bearer \${token}\`,
|
|
4011
|
+
"Content-Type": "application/json",
|
|
4012
|
+
},
|
|
4013
|
+
body: JSON.stringify({
|
|
4014
|
+
projectId: "${e}",
|
|
4015
|
+
tables: ["messages", "notifications"],
|
|
4016
|
+
}),
|
|
4017
|
+
});
|
|
4018
|
+
|
|
4019
|
+
// 2. Subscribe to changes via SDK
|
|
4020
|
+
const channel = vaif.realtime.channel("chat-room");
|
|
4021
|
+
|
|
4022
|
+
channel.on("postgres_changes", {
|
|
4023
|
+
event: "*", // INSERT, UPDATE, DELETE, or * for all
|
|
4024
|
+
schema: "public",
|
|
4025
|
+
table: "messages",
|
|
4026
|
+
}, (payload) => {
|
|
4027
|
+
console.log("Change:", payload.eventType, payload.new);
|
|
4028
|
+
});
|
|
4029
|
+
|
|
4030
|
+
channel.subscribe();
|
|
4031
|
+
|
|
4032
|
+
// 3. Presence: track who's online
|
|
4033
|
+
channel.on("presence", { event: "sync" }, () => {
|
|
4034
|
+
const state = channel.presenceState();
|
|
4035
|
+
console.log("Online users:", Object.keys(state));
|
|
4036
|
+
});
|
|
4037
|
+
channel.track({ user_id: currentUser.id, status: "online" });
|
|
4038
|
+
|
|
4039
|
+
// 4. Broadcast: send ephemeral messages (typing indicators, cursors)
|
|
4040
|
+
channel.send({
|
|
4041
|
+
type: "broadcast",
|
|
4042
|
+
event: "typing",
|
|
4043
|
+
payload: { userId: currentUser.id },
|
|
4044
|
+
});
|
|
4045
|
+
|
|
4046
|
+
// Cleanup
|
|
4047
|
+
channel.unsubscribe();
|
|
4048
|
+
\`\`\`
|
|
4049
|
+
|
|
4050
|
+
## Storage Policies
|
|
4051
|
+
|
|
4052
|
+
Control who can access storage buckets with RLS-style policies:
|
|
4053
|
+
|
|
4054
|
+
\`\`\`typescript
|
|
4055
|
+
// Create a policy: only the uploader can read their own files
|
|
4056
|
+
await fetch("${n}/storage/buckets/\${bucketId}/policies", {
|
|
4057
|
+
method: "POST",
|
|
4058
|
+
headers: {
|
|
4059
|
+
Authorization: \`Bearer \${token}\`,
|
|
4060
|
+
"Content-Type": "application/json",
|
|
4061
|
+
},
|
|
4062
|
+
body: JSON.stringify({
|
|
4063
|
+
name: "owner_read",
|
|
4064
|
+
operation: "SELECT", // SELECT | INSERT | UPDATE | DELETE | ALL
|
|
4065
|
+
definition: "auth.uid() = owner_id",
|
|
4066
|
+
}),
|
|
4067
|
+
});
|
|
4068
|
+
|
|
4069
|
+
// Create a policy: authenticated users can upload
|
|
4070
|
+
await fetch("${n}/storage/buckets/\${bucketId}/policies", {
|
|
4071
|
+
method: "POST",
|
|
4072
|
+
headers: {
|
|
4073
|
+
Authorization: \`Bearer \${token}\`,
|
|
4074
|
+
"Content-Type": "application/json",
|
|
4075
|
+
},
|
|
4076
|
+
body: JSON.stringify({
|
|
4077
|
+
name: "auth_insert",
|
|
4078
|
+
operation: "INSERT",
|
|
4079
|
+
definition: "auth.uid() IS NOT NULL",
|
|
4080
|
+
}),
|
|
4081
|
+
});
|
|
4082
|
+
\`\`\`
|
|
4083
|
+
|
|
4084
|
+
## Edge Function Deployment
|
|
4085
|
+
|
|
4086
|
+
Create and deploy serverless functions:
|
|
4087
|
+
|
|
4088
|
+
\`\`\`typescript
|
|
4089
|
+
// 1. Create a function
|
|
4090
|
+
const fn = await fetch("${n}/functions", {
|
|
4091
|
+
method: "POST",
|
|
4092
|
+
headers: {
|
|
4093
|
+
Authorization: \`Bearer \${token}\`,
|
|
4094
|
+
"Content-Type": "application/json",
|
|
4095
|
+
},
|
|
4096
|
+
body: JSON.stringify({
|
|
4097
|
+
projectId: "${e}",
|
|
4098
|
+
name: "send_welcome_email",
|
|
4099
|
+
runtime: "nodejs20", // nodejs20 (default)
|
|
4100
|
+
entrypoint: "index.ts", // default
|
|
4101
|
+
timeoutMs: 10000, // 1000\u201330000ms, default 10000
|
|
4102
|
+
}),
|
|
4103
|
+
});
|
|
4104
|
+
|
|
4105
|
+
// 2. Deploy source code
|
|
4106
|
+
await fetch(\`${n}/functions/\${fn.id}/source\`, {
|
|
4107
|
+
method: "PUT",
|
|
4108
|
+
headers: {
|
|
4109
|
+
Authorization: \`Bearer \${token}\`,
|
|
4110
|
+
"Content-Type": "application/json",
|
|
4111
|
+
},
|
|
4112
|
+
body: JSON.stringify({
|
|
4113
|
+
sourceCode: \`
|
|
4114
|
+
export default async function handler(req, ctx) {
|
|
4115
|
+
const { userId } = req.body;
|
|
4116
|
+
// ctx.secrets contains your encrypted secrets
|
|
4117
|
+
const apiKey = ctx.secrets.SENDGRID_KEY;
|
|
4118
|
+
return { status: "sent", userId };
|
|
4119
|
+
}
|
|
4120
|
+
\`,
|
|
4121
|
+
}),
|
|
4122
|
+
});
|
|
4123
|
+
|
|
4124
|
+
// 3. Invoke the function
|
|
4125
|
+
const result = await vaif.functions.invoke("send_welcome_email", {
|
|
4126
|
+
body: { userId: "user_123" },
|
|
4127
|
+
});
|
|
4128
|
+
\`\`\`
|
|
4129
|
+
|
|
4130
|
+
## API Key Management
|
|
4131
|
+
|
|
4132
|
+
API keys are project-scoped and used for data-plane authentication (CRUD, storage, functions).
|
|
4133
|
+
|
|
4134
|
+
\`\`\`typescript
|
|
4135
|
+
// Create a new API key
|
|
4136
|
+
const { key } = await fetch("${n}/projects/${e}/api-keys", {
|
|
4137
|
+
method: "POST",
|
|
4138
|
+
headers: {
|
|
4139
|
+
Authorization: \`Bearer \${token}\`,
|
|
4140
|
+
"Content-Type": "application/json",
|
|
4141
|
+
},
|
|
4142
|
+
body: JSON.stringify({ name: "production-frontend" }),
|
|
4143
|
+
}).then(r => r.json());
|
|
4144
|
+
|
|
4145
|
+
// List keys
|
|
4146
|
+
const keys = await fetch("${n}/projects/${e}/api-keys", {
|
|
4147
|
+
headers: { Authorization: \`Bearer \${token}\` },
|
|
4148
|
+
}).then(r => r.json());
|
|
4149
|
+
|
|
4150
|
+
// Rotate a key (generates new secret, old key stops working)
|
|
4151
|
+
await fetch(\`${n}/projects/${e}/api-keys/\${keyId}/rotate\`, {
|
|
4152
|
+
method: "POST",
|
|
4153
|
+
headers: { Authorization: \`Bearer \${token}\` },
|
|
4154
|
+
});
|
|
4155
|
+
|
|
4156
|
+
// Revoke a key
|
|
4157
|
+
await fetch(\`${n}/projects/${e}/api-keys/\${keyId}/revoke\`, {
|
|
4158
|
+
method: "POST",
|
|
4159
|
+
headers: { Authorization: \`Bearer \${token}\` },
|
|
4160
|
+
});
|
|
4161
|
+
\`\`\`
|
|
4162
|
+
|
|
4163
|
+
## Secrets & Environment Variables
|
|
4164
|
+
|
|
4165
|
+
Secrets are encrypted at rest and injected into function invocations at runtime.
|
|
4166
|
+
|
|
4167
|
+
\`\`\`typescript
|
|
4168
|
+
// Set a secret (via API)
|
|
4169
|
+
await fetch("${n}/functions/secrets", {
|
|
4170
|
+
method: "POST",
|
|
4171
|
+
headers: {
|
|
4172
|
+
Authorization: \`Bearer \${token}\`,
|
|
4173
|
+
"Content-Type": "application/json",
|
|
4174
|
+
},
|
|
4175
|
+
body: JSON.stringify({
|
|
4176
|
+
projectId: "${e}",
|
|
4177
|
+
key: "STRIPE_SECRET_KEY",
|
|
4178
|
+
value: "sk_live_...",
|
|
4179
|
+
}),
|
|
4180
|
+
});
|
|
4181
|
+
|
|
4182
|
+
// Or use the CLI
|
|
4183
|
+
// vaif secrets set STRIPE_SECRET_KEY sk_live_...
|
|
4184
|
+
// vaif secrets list
|
|
4185
|
+
// vaif secrets delete STRIPE_SECRET_KEY
|
|
4186
|
+
\`\`\`
|
|
4187
|
+
|
|
4188
|
+
**Accessing secrets in functions:**
|
|
4189
|
+
|
|
4190
|
+
\`\`\`typescript
|
|
4191
|
+
export default async function handler(req, ctx) {
|
|
4192
|
+
const stripe = new Stripe(ctx.secrets.STRIPE_SECRET_KEY);
|
|
4193
|
+
// ...
|
|
4194
|
+
}
|
|
4195
|
+
\`\`\`
|
|
4196
|
+
|
|
3980
4197
|
## API Reference Notes
|
|
3981
4198
|
|
|
3982
4199
|
### Filter Syntax
|
|
@@ -4011,4 +4228,4 @@ All authenticated requests require:
|
|
|
4011
4228
|
- \`x-api-key: <api_key>\` \u2014 for server-side / service-role requests
|
|
4012
4229
|
- \`x-project-id: ${e}\` \u2014 identifies the project
|
|
4013
4230
|
`}async function ct(t){let e=Q__default.default(),o=I();(!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 A(n);}catch{}let i=po(t,r,o);i||(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 s=S__default.default.resolve(t.outputDir||".");console.log(""),console.log(f__default.default.bold("VAIF Claude Code Setup")),console.log(f__default.default.gray(` Project: ${i}`)),console.log(""),e.start("Fetching database schema...");let a={tables:[]};try{let p=await fetch(`${G}/schema-engine/introspect/${i}`,{headers:{Authorization:`Bearer ${o.token}`}});p.ok?(a=await p.json(),e.succeed(`Fetched schema (${a.tables?.length||0} tables)`)):e.warn("Could not fetch schema \u2014 continuing without it");}catch{e.warn("Could not fetch schema \u2014 continuing without it");}e.start("Fetching project info...");let l=i,d=G;try{let p=await fetch(`${G}/projects/${i}`,{headers:{Authorization:`Bearer ${o.token}`}});if(p.ok){let c=await p.json();l=c.name||i,d=c.apiUrl||G,e.succeed(`Project: ${l}`);}else e.warn("Could not fetch project info \u2014 using defaults");}catch{e.warn("Could not fetch project info \u2014 using defaults");}let u=t.apiKey||r?.api?.apiKey||"";if(!u){e.start("Generating API key for Claude Code...");try{let p=`claude-code-${Date.now()}`,c=await fetch(`${G}/projects/${i}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:p})});c.ok?(u=(await c.json()).key,e.succeed(`Generated API key: ${p}`)):(e.fail("Could not auto-generate API key"),console.log(f__default.default.yellow(" Pass one with --api-key or generate via `vaif keys generate`")),process.exit(1));}catch{e.fail("Could not auto-generate API key"),console.log(f__default.default.yellow(" Pass one with --api-key or generate via `vaif keys generate`")),process.exit(1);}}if(!t.skipMcp){e.start("Writing .mcp.json...");let p={mcpServers:{"vaif-studio":{command:"npx",args:["@vaiftech/mcp"],env:{VAIF_API_KEY:u,VAIF_PROJECT_ID:i,VAIF_API_URL:d,VAIF_AUTH_TOKEN:o.token}}}},c=S__default.default.join(s,".mcp.json");U__default.default.writeFileSync(c,JSON.stringify(p,null,2)+`
|
|
4014
|
-
`,"utf-8"),e.succeed(`Written ${f__default.default.cyan(".mcp.json")}`);}if(!t.skipClaudeMd){e.start("Writing CLAUDE.md...");let p=mo({projectId:i,apiKey:u,apiUrl:d,projectName:l,schema:a}),c=S__default.default.join(s,"CLAUDE.md");U__default.default.writeFileSync(c,p,"utf-8"),e.succeed(`Written ${f__default.default.cyan("CLAUDE.md")}`);}console.log(""),console.log(f__default.default.green.bold(" Claude Code integration configured!")),console.log(""),t.skipMcp||console.log(f__default.default.gray(" MCP Server: ")+f__default.default.white(".mcp.json")),t.skipClaudeMd||console.log(f__default.default.gray(" Context: ")+f__default.default.white("CLAUDE.md")),console.log(""),console.log(f__default.default.bold(" Next steps:")),console.log(f__default.default.gray(" 1. Open this project in Claude Code")),console.log(f__default.default.gray(" 2. The MCP server auto-connects to your VAIF project")),console.log(f__default.default.gray(" 3. Ask Claude to query, modify, or build against your schema")),console.log("");}var dt="1.8.1",he=f__default.default.hex("#00f0ff"),ye=f__default.default.hex("#7b61ff"),ve=f__default.default.hex("#ff3dff"),be=f__default.default.hex("#00ff9d"),w=f__default.default.hex("#555570"),B=f__default.default.hex("#00f0ff");function ho(){console.log(""),console.log(he(" \u2566 \u2566")+ye("\u2554\u2550\u2557\u2566")+ve("\u2554\u2550\u2557 ")+be("\u2554\u2550\u2557\u2566 \u2566")),console.log(he(" \u255A\u2557\u2554\u255D")+ye("\u2560\u2550\u2563\u2551")+ve("\u2560\u2563 ")+be("\u2551 \u2551 \u2551")),console.log(he(" \u255A\u255D ")+ye("\u2569 \u2569\u2569")+ve("\u255A ")+be("\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(B(" VAIF Studio CLI")+w(` v${dt}`)),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(" $ ")+B("vaif login")+w(" Authenticate")),console.log(w(" $ ")+B("vaif init -t react-spa")+w(" Scaffold project")),console.log(w(" $ ")+B("vaif db push")+w(" Push migrations")),console.log(w(" $ ")+B("vaif generate")+w(" Generate types")),console.log(w(" $ ")+B("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(w(" ai ")+f__default.default.white("claude-setup")),console.log(""),console.log(w(" Run ")+B("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(dt);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(Te);commander.program.command("logout").description("Log out and remove stored credentials").action(Pe);commander.program.command("whoami").description("Show current authenticated user").action(Fe);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(Le);commander.program.command("templates").alias("tpl").description("List available project templates").action(ke);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(st);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(rt);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(Ne);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($e);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(je);var pt=commander.program.command("functions").alias("fn").description("Manage serverless functions");pt.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(ze);pt.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(Be);var ae=commander.program.command("db").description("Database management commands");ae.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(Je);ae.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(Ge);ae.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(Ye);ae.command("reset").description("Reset database (drop all tables and data)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --force","Confirm reset (required)").action(We);var ut=commander.program.command("keys").description("Manage API keys");ut.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(Ze);ut.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(et);var ie=commander.program.command("secrets").alias("sec").description("Manage function secrets");ie.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(tt);ie.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(ot);ie.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(nt);ie.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(at);commander.program.command("claude-setup").description("Configure Claude Code integration (MCP server + CLAUDE.md)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID").option("-k, --api-key <key>","API key for MCP server").option("--skip-mcp","Skip generating .mcp.json").option("--skip-claude-md","Skip generating CLAUDE.md").option("-o, --output-dir <dir>","Output directory",".").action(ct);process.argv.slice(2).length||(ho(),process.exit(0));commander.program.parse(process.argv);
|
|
4231
|
+
`,"utf-8"),e.succeed(`Written ${f__default.default.cyan(".mcp.json")}`);}if(!t.skipClaudeMd){e.start("Writing CLAUDE.md...");let p=mo({projectId:i,apiKey:u,apiUrl:d,projectName:l,schema:a}),c=S__default.default.join(s,"CLAUDE.md");U__default.default.writeFileSync(c,p,"utf-8"),e.succeed(`Written ${f__default.default.cyan("CLAUDE.md")}`);}console.log(""),console.log(f__default.default.green.bold(" Claude Code integration configured!")),console.log(""),t.skipMcp||console.log(f__default.default.gray(" MCP Server: ")+f__default.default.white(".mcp.json")),t.skipClaudeMd||console.log(f__default.default.gray(" Context: ")+f__default.default.white("CLAUDE.md")),console.log(""),console.log(f__default.default.bold(" Next steps:")),console.log(f__default.default.gray(" 1. Open this project in Claude Code")),console.log(f__default.default.gray(" 2. The MCP server auto-connects to your VAIF project")),console.log(f__default.default.gray(" 3. Ask Claude to query, modify, or build against your schema")),console.log("");}var dt="1.8.1",he=f__default.default.hex("#00f0ff"),ye=f__default.default.hex("#7b61ff"),ve=f__default.default.hex("#ff3dff"),be=f__default.default.hex("#00ff9d"),w=f__default.default.hex("#555570"),B=f__default.default.hex("#00f0ff");function ho(){console.log(""),console.log(he(" \u2566 \u2566")+ye("\u2554\u2550\u2557\u2566")+ve("\u2554\u2550\u2557 ")+be("\u2554\u2550\u2557\u2566 \u2566")),console.log(he(" \u255A\u2557\u2554\u255D")+ye("\u2560\u2550\u2563\u2551")+ve("\u2560\u2563 ")+be("\u2551 \u2551 \u2551")),console.log(he(" \u255A\u255D ")+ye("\u2569 \u2569\u2569")+ve("\u255A ")+be("\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(B(" VAIF Studio CLI")+w(` v${dt}`)),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(" $ ")+B("vaif login")+w(" Authenticate")),console.log(w(" $ ")+B("vaif init -t react-spa")+w(" Scaffold project")),console.log(w(" $ ")+B("vaif db push")+w(" Push migrations")),console.log(w(" $ ")+B("vaif generate")+w(" Generate types")),console.log(w(" $ ")+B("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(w(" ai ")+f__default.default.white("claude-setup")),console.log(""),console.log(w(" Run ")+B("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(dt);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(Te);commander.program.command("logout").description("Log out and remove stored credentials").action(Pe);commander.program.command("whoami").description("Show current authenticated user").action(Fe);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(Ne);commander.program.command("templates").alias("tpl").description("List available project templates").action(Le);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(st);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(rt);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(Ve);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($e);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(je);var pt=commander.program.command("functions").alias("fn").description("Manage serverless functions");pt.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(ze);pt.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(Be);var ae=commander.program.command("db").description("Database management commands");ae.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(Je);ae.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(Ge);ae.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(Ye);ae.command("reset").description("Reset database (drop all tables and data)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --force","Confirm reset (required)").action(We);var ut=commander.program.command("keys").description("Manage API keys");ut.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(Ze);ut.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(et);var ie=commander.program.command("secrets").alias("sec").description("Manage function secrets");ie.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(tt);ie.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(ot);ie.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(nt);ie.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(at);commander.program.command("claude-setup").description("Configure Claude Code integration (MCP server + CLAUDE.md)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID").option("-k, --api-key <key>","API key for MCP server").option("--skip-mcp","Skip generating .mcp.json").option("--skip-claude-md","Skip generating CLAUDE.md").option("-o, --output-dir <dir>","Output directory",".").action(ct);process.argv.slice(2).length||(ho(),process.exit(0));commander.program.parse(process.argv);
|
package/dist/cli.js
CHANGED
|
@@ -1,36 +1,36 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {c,d,e,h,g,f as f$1,b,a}from'./chunk-T7GOLIY4.js';import'dotenv/config';import {program}from'commander';import f from'chalk';import
|
|
2
|
+
import {c,d,e,h,g,f as f$1,b,a}from'./chunk-T7GOLIY4.js';import'dotenv/config';import {program}from'commander';import f from'chalk';import F from'fs';import I from'path';import K from'ora';import Me from'readline';var Ke=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Be(o,e,t="public"){let s=await fetch(`${Ke}/projects/${e}/schema?schema=${t}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!s.ok){let r=await s.text();throw new Error(`Failed to fetch schema: ${r}`)}return s.json()}async function ce(o){let e=K(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=o.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await a(s);}catch(i){e.fail("Failed to load config"),console.log(f.red(`
|
|
3
3
|
Error: ${i}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(f.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let a$1=o.projectId||r.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(e.fail("No project ID specified"),console.log(f.yellow(`
|
|
4
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let i=o.schema||r.database?.schema||"public",n=await Be(t.token,a$1,i);e.succeed("Schema fetched successfully");let c=o.output||I.resolve("vaif.schema.json"),d={$schema:"https://vaif.studio/schemas/schema.json",projectId:a$1,schema:i,pulledAt:new Date().toISOString(),...n};
|
|
5
|
-
Error: ${i.message}`)),process.exit(1);}}var ge=process.env.VAIF_API_URL||"https://api.vaif.studio";function We(o){let e=
|
|
4
|
+
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let i=o.schema||r.database?.schema||"public",n=await Be(t.token,a$1,i);e.succeed("Schema fetched successfully");let c=o.output||I.resolve("vaif.schema.json"),d={$schema:"https://vaif.studio/schemas/schema.json",projectId:a$1,schema:i,pulledAt:new Date().toISOString(),...n};F.writeFileSync(c,JSON.stringify(d,null,2),"utf-8"),console.log(""),console.log(f.green(`Schema saved to: ${c}`)),console.log(""),console.log(f.gray("Schema summary:")),console.log(f.gray(` Tables: ${(n.tables||[]).length}`)),console.log(f.gray(` Enums: ${(n.enums||[]).length}`)),console.log(f.gray(` Functions: ${(n.functions||[]).length}`)),console.log(""),console.log(f.gray("Next steps:")),console.log(f.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(f.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.red(`
|
|
5
|
+
Error: ${i.message}`)),process.exit(1);}}var ge=process.env.VAIF_API_URL||"https://api.vaif.studio";function We(o){let e=Me.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(o,s=>{e.close(),t(s);});})}async function Ge(o,e,t){let s=await fetch(`${ge}/projects/${e}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!s.ok){let r=await s.text();throw new Error(`Failed to preview changes: ${r}`)}return s.json()}async function Ye(o,e,t){let s=await fetch(`${ge}/projects/${e}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!s.ok){let r=await s.text();throw new Error(`Failed to apply changes: ${r}`)}return s.json()}function He(o){if(console.log(""),console.log(f.bold("Schema Changes:")),console.log(""),o.added.length===0&&o.modified.length===0&&o.removed.length===0){console.log(f.gray(" No changes detected. Schema is up to date."));return}if(o.added.length>0){console.log(f.green.bold(" + Added:"));for(let e of o.added)console.log(f.green(` + ${e.type}: ${e.name}`));console.log("");}if(o.modified.length>0){console.log(f.yellow.bold(" ~ Modified:"));for(let e of o.modified){console.log(f.yellow(` ~ ${e.type}: ${e.name}`));for(let t of e.changes)console.log(f.gray(` ${t}`));}console.log("");}if(o.removed.length>0){console.log(f.red.bold(" - Removed:"));for(let e of o.removed)console.log(f.red(` - ${e.type}: ${e.name}`));console.log("");}}async function fe(o){let e=K(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=o.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await a(s);}catch(c){e.fail("Failed to load config"),console.log(f.red(`
|
|
6
6
|
Error: ${c}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(f.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let a$1=o.projectId||r.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(e.fail("No project ID specified"),console.log(f.yellow(`
|
|
7
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=o.schema||I.resolve("vaif.schema.json");
|
|
8
|
-
Expected schema file at: ${i}`)),console.log(f.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let n;try{let c=
|
|
9
|
-
Error: ${c.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:c,sql:d}=await Ge(t.token,a$1,n);if(e.stop(),
|
|
7
|
+
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=o.schema||I.resolve("vaif.schema.json");F.existsSync(i)||(e.fail("No local schema found"),console.log(f.yellow(`
|
|
8
|
+
Expected schema file at: ${i}`)),console.log(f.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let n;try{let c=F.readFileSync(i,"utf-8");n=JSON.parse(c);}catch(c){e.fail("Failed to parse schema file"),c instanceof Error&&console.log(f.red(`
|
|
9
|
+
Error: ${c.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:c,sql:d}=await Ge(t.token,a$1,n);if(e.stop(),He(c),c.added.length===0&&c.modified.length===0&&c.removed.length===0){console.log("");return}if(d.length>0){console.log(f.bold("SQL Migrations:")),console.log("");for(let g of d)console.log(f.gray(` ${g}`));console.log("");}if(o.dryRun){console.log(f.yellow("Dry run mode - no changes applied.")),console.log(f.gray("Remove --dry-run to apply these changes."));return}if(!o.force){c.removed.length>0&&(console.log(f.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(f.red(" This action cannot be undone!")),console.log(""));let l=await We(f.cyan("Apply these changes? [y/N] "));if(l.toLowerCase()!=="y"&&l.toLowerCase()!=="yes"){console.log(f.yellow(`
|
|
10
10
|
Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let p=await Ye(t.token,a$1,n);if(p.success){if(e.succeed("Schema changes applied successfully"),console.log(""),p.migrations.length>0){console.log(f.gray("Migrations applied:"));for(let g of p.migrations)console.log(f.gray(` - ${g}`));console.log("");}console.log(f.green("Your database schema is now up to date.")),console.log(f.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else e.fail("Failed to apply some changes");}catch(c){e.fail("Failed to push schema changes"),c instanceof Error&&console.log(f.red(`
|
|
11
|
-
Error: ${c.message}`)),process.exit(1);}}var z=process.env.VAIF_API_URL||"https://api.vaif.studio";async function
|
|
11
|
+
Error: ${c.message}`)),process.exit(1);}}var z=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Qe(o,e,t,s){let r=new URL(`${z}/functions/project/${e}`);s&&r.searchParams.set("envId",s);let a=await fetch(r.toString(),{headers:{Authorization:`Bearer ${o}`}});if(!a.ok)return null;let i=await a.json(),n=i.functions||i;return Array.isArray(n)&&n.find(c=>c.name===t)||null}async function Xe(o,e,t){let s=await fetch(`${z}/functions/`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:e,name:t.name,runtime:t.runtime,entrypoint:t.entrypoint,envId:t.envId})});if(!s.ok){let r=await s.text();throw new Error(`Failed to create function: ${r}`)}return s.json()}async function Ze(o,e,t){let s=await fetch(`${z}/functions/${e}/source`,{method:"PUT",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({sourceCode:t})});if(!s.ok){let r=await s.text();throw new Error(`Failed to deploy source: ${r}`)}}async function eo(o,e,t){let s=new URL(`${z}/functions/project/${e}`);t&&s.searchParams.set("envId",t);let r=await fetch(s.toString(),{headers:{Authorization:`Bearer ${o}`}});if(!r.ok){let i=await r.text();throw new Error(`Failed to list functions: ${i}`)}let a=await r.json();return a.functions||a}function de(o){switch(I.extname(o).toLowerCase()){case ".ts":return "typescript";case ".js":case ".mjs":return "nodejs";case ".py":return "python";case ".go":return "go";case ".rs":return "rust";default:return "nodejs"}}function pe(o){let e=[],t=[".ts",".js",".mjs",".py",".go",".rs"],s=["drizzle.config.ts","tsconfig.json","package.json"];if(!F.existsSync(o))return e;let r=F.readdirSync(o,{withFileTypes:true});for(let a of r){let i=I.join(o,a.name);if(a.isDirectory()){if(a.name!=="node_modules"&&!a.name.startsWith(".")){let n=F.readdirSync(i,{withFileTypes:true});for(let c of n)if(c.isFile()){let d=I.extname(c.name).toLowerCase();if(t.includes(d)){e.push(I.join(i,c.name));break}}}}else if(a.isFile()){let n=I.extname(a.name).toLowerCase();t.includes(n)&&!s.includes(a.name)&&e.push(i);}}return e}async function he(o){let e=K(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=o.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f.bold("VAIF Functions Deploy")),console.log(""),e.start("Scanning for function files...");let i=I.resolve("functions"),n=I.resolve("src/functions"),c=[];if(o.entrypoint){let l=I.resolve(o.entrypoint);F.existsSync(l)||(e.fail(`File not found: ${o.entrypoint}`),process.exit(1)),c=[l];}else c=[...pe(i),...pe(n)];c.length===0&&(e.fail("No function files found"),console.log(f.yellow(`
|
|
12
12
|
Place your functions in:`)),console.log(f.gray(" - ./functions/")),console.log(f.gray(" - ./src/functions/")),console.log(f.gray(`
|
|
13
13
|
Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${c.length} function(s)`),o.name&&(c=c.filter(l=>I.basename(l,I.extname(l)).includes(o.name)),c.length===0&&(console.log(f.yellow(`
|
|
14
|
-
No functions matching "${o.name}" found`)),process.exit(1))),console.log(""),console.log(f.gray("Functions to deploy:"));for(let l of c){let
|
|
14
|
+
No functions matching "${o.name}" found`)),process.exit(1))),console.log(""),console.log(f.gray("Functions to deploy:"));for(let l of c){let m=I.basename(I.dirname(l)),y=m==="functions"||m==="src"?I.basename(l,I.extname(l)):m,D=o.runtime||de(l);console.log(f.gray(` - ${y} (${D})`));}if(console.log(""),o.dryRun){console.log(f.yellow("Dry run mode - no functions deployed."));return}let d=[];for(let l of c){let m=I.basename(I.dirname(l)),y=m==="functions"||m==="src"?I.basename(l,I.extname(l)):m,D=o.runtime||de(l);e.start(`Deploying ${y}...`);try{let U=F.readFileSync(l,"utf-8"),_=await Qe(t.token,a$1,y,o.envId);_||(e.text=`Creating ${y}...`,_=await Xe(t.token,a$1,{name:y,runtime:D,entrypoint:I.basename(l),envId:o.envId})),e.text=`Deploying ${y}...`,await Ze(t.token,_.id,U),e.succeed(`Deployed ${y}`),d.push({name:y,success:!0});}catch(U){let _=U instanceof Error?U.message:"Unknown error";e.fail(`Failed to deploy ${y}`),d.push({name:y,success:false,error:_});}}console.log("");let p=d.filter(l=>l.success).length;if(d.filter(l=>!l.success).length===0)console.log(f.green(`\u2713 Successfully deployed ${p} function(s)`));else {console.log(f.yellow(`Deployed ${p}/${d.length} function(s)`)),console.log(""),console.log(f.red("Failed deployments:"));for(let l of d.filter(m=>!m.success))console.log(f.red(` - ${l.name}: ${l.error}`));}console.log("");}async function me(o){let e=K(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=o.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(console.log(f.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let i=await eo(t.token,a$1,o.envId);if(e.stop(),i.length===0){console.log(f.yellow(`
|
|
15
15
|
No functions found`)),console.log(f.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(f.bold(`Functions (${i.length}):`)),console.log(""),console.log(f.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"STATUS".padEnd(12)+"INVOCATIONS".padEnd(14)+"LAST DEPLOYED")),console.log(f.gray(" "+"-".repeat(80)));for(let n of i){let c=n.deployStatus==="deployed"?f.green:n.deployStatus==="deploying"?f.yellow:n.deployStatus==="failed"?f.red:f.gray;console.log(" "+n.name.padEnd(25)+n.runtime.padEnd(15)+c(n.deployStatus.padEnd(12))+String(n.invocationCount??0).padEnd(14)+(n.deployedAt?new Date(n.deployedAt).toLocaleDateString():"-"));}console.log("");}catch(i){e.fail("Failed to fetch functions"),i instanceof Error&&console.log(f.red(`
|
|
16
|
-
Error: ${i.message}`)),process.exit(1);}}var B=process.env.VAIF_API_URL||"https://api.vaif.studio";async function oo(o,e,t,s,r){let a=await fetch(`${B}/projects/${e}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({table:t,records:s,truncate:r?.truncate??false})});if(!a.ok){let i=await a.text();throw new Error(`Failed to seed ${t}: ${i}`)}return a.json()}async function to(o,e){let t=await fetch(`${B}/projects/${e}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!t.ok){let s=await t.text();throw new Error(`Failed to reset database: ${s}`)}return t.json()}function
|
|
16
|
+
Error: ${i.message}`)),process.exit(1);}}var B=process.env.VAIF_API_URL||"https://api.vaif.studio";async function oo(o,e,t,s,r){let a=await fetch(`${B}/projects/${e}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({table:t,records:s,truncate:r?.truncate??false})});if(!a.ok){let i=await a.text();throw new Error(`Failed to seed ${t}: ${i}`)}return a.json()}async function to(o,e){let t=await fetch(`${B}/projects/${e}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!t.ok){let s=await t.text();throw new Error(`Failed to reset database: ${s}`)}return t.json()}function H(o){let e=[];if(!F.existsSync(o))return e;let t=F.readdirSync(o,{withFileTypes:true});for(let s of t)if(s.isFile()){let r=I.extname(s.name).toLowerCase();(r===".json"||r===".ts"||r===".js")&&e.push(I.join(o,s.name));}return e.sort()}async function ye(o){let e=I.extname(o).toLowerCase();if(e===".json"){let t=F.readFileSync(o,"utf-8"),s=JSON.parse(t);return Array.isArray(s)?[{table:I.basename(o,e),data:s}]:s.table&&s.data?[s]:Object.entries(s).map(([r,a])=>({table:r,data:a}))}else if(e===".ts"||e===".js"){let t=await import(o),s=t.default||t;return typeof s=="function"?s():s}throw new Error(`Unsupported file format: ${e}`)}async function we(o){let e=K(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=o.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f.bold("VAIF Database Seed")),console.log("");let i=[];if(o.file){let p=I.resolve(o.file);F.existsSync(p)||(console.log(f.red(`File not found: ${o.file}`)),process.exit(1)),i=[p];}else {let p=I.resolve("seeds"),g=I.resolve("prisma/seed"),l=I.resolve("db/seeds");i=[...H(p),...H(g),...H(l)];}i.length===0&&(console.log(f.yellow("No seed files found")),console.log(f.gray(`
|
|
17
17
|
Place your seed files in one of these directories:`)),console.log(f.gray(" - ./seeds/")),console.log(f.gray(" - ./prisma/seed/")),console.log(f.gray(" - ./db/seeds/")),console.log(f.gray(`
|
|
18
18
|
Or specify a file with --file`)),console.log(f.gray(`
|
|
19
|
-
Example seed file (seeds/users.json):`)),console.log(f.gray(" [")),console.log(f.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(f.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(f.gray(" ]")),process.exit(1)),console.log(f.gray("Seed files found:"));for(let p of i)console.log(f.gray(` - ${I.relative(process.cwd(),p)}`));if(console.log(""),o.truncate&&(console.log(f.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),o.dryRun){console.log(f.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let p of i){e.start(`Loading ${I.basename(p)}...`);try{let g=await ye(p);e.stop();for(let l of g)o.table&&l.table!==o.table||(console.log(f.cyan(`Table: ${l.table}`)),console.log(f.gray(` Records: ${l.data.length}`)),l.data.length>0&&console.log(f.gray(` Sample: ${JSON.stringify(l.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(g){e.fail(`Failed to load ${I.basename(p)}`),g instanceof Error&&console.log(f.red(` Error: ${g.message}`));}}return}let n=[];for(let p of i){e.start(`Processing ${I.basename(p)}...`);try{let g=await ye(p);e.stop();for(let l of g)if(!(o.table&&l.table!==o.table)){if(l.data.length===0){console.log(f.gray(` Skipping ${l.table} (no records)`));continue}e.start(`Seeding ${l.table} (${l.data.length} records)...`);try{let
|
|
19
|
+
Example seed file (seeds/users.json):`)),console.log(f.gray(" [")),console.log(f.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(f.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(f.gray(" ]")),process.exit(1)),console.log(f.gray("Seed files found:"));for(let p of i)console.log(f.gray(` - ${I.relative(process.cwd(),p)}`));if(console.log(""),o.truncate&&(console.log(f.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),o.dryRun){console.log(f.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let p of i){e.start(`Loading ${I.basename(p)}...`);try{let g=await ye(p);e.stop();for(let l of g)o.table&&l.table!==o.table||(console.log(f.cyan(`Table: ${l.table}`)),console.log(f.gray(` Records: ${l.data.length}`)),l.data.length>0&&console.log(f.gray(` Sample: ${JSON.stringify(l.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(g){e.fail(`Failed to load ${I.basename(p)}`),g instanceof Error&&console.log(f.red(` Error: ${g.message}`));}}return}let n=[];for(let p of i){e.start(`Processing ${I.basename(p)}...`);try{let g=await ye(p);e.stop();for(let l of g)if(!(o.table&&l.table!==o.table)){if(l.data.length===0){console.log(f.gray(` Skipping ${l.table} (no records)`));continue}e.start(`Seeding ${l.table} (${l.data.length} records)...`);try{let m=await oo(t.token,a$1,l.table,l.data,{truncate:o.truncate});e.succeed(`Seeded ${l.table}: ${m.inserted} records`),n.push({table:l.table,inserted:m.inserted});}catch(m){let y=m instanceof Error?m.message:"Unknown error";e.fail(`Failed to seed ${l.table}`),n.push({table:l.table,inserted:0,error:y});}}}catch(g){e.fail(`Failed to load ${I.basename(p)}`),g instanceof Error&&console.log(f.red(` Error: ${g.message}`));}}console.log("");let c=n.reduce((p,g)=>p+g.inserted,0),d=n.filter(p=>p.error).length;if(d===0)console.log(f.green(`\u2713 Successfully seeded ${c} records across ${n.length} table(s)`));else {console.log(f.yellow(`Seeded ${c} records with ${d} error(s)`)),console.log(""),console.log(f.red("Errors:"));for(let p of n.filter(g=>g.error))console.log(f.red(` - ${p.table}: ${p.error}`));}console.log("");}async function je(o){let e=K(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=o.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=I.resolve(o.dir||"./drizzle");if(console.log(""),console.log(f.bold("VAIF Database Push")),console.log(""),!F.existsSync(i)){let g=I.resolve("./migrations");F.existsSync(g)?console.log(f.gray(`Using migrations from: ${g}`)):(console.log(f.red(`Migrations directory not found: ${i}`)),console.log(f.gray(`
|
|
20
20
|
Expected one of:`)),console.log(f.gray(" - ./drizzle/")),console.log(f.gray(" - ./migrations/")),console.log(f.gray(`
|
|
21
|
-
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let n=[],c=
|
|
21
|
+
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let n=[],c=F.readdirSync(i,{withFileTypes:true});for(let g of c)if(g.isFile()&&g.name.endsWith(".sql"))n.push(I.join(i,g.name));else if(g.isDirectory()){let l=F.readdirSync(I.join(i,g.name),{withFileTypes:true});for(let m of l)m.isFile()&&m.name.endsWith(".sql")&&n.push(I.join(i,g.name,m.name));}n.sort(),n.length===0&&(console.log(f.yellow("No SQL migration files found")),process.exit(1)),console.log(f.gray(`Found ${n.length} migration(s):`));for(let g of n)console.log(f.gray(` - ${I.relative(process.cwd(),g)}`));if(console.log(""),o.dryRun){console.log(f.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let g of n){let l=F.readFileSync(g,"utf-8");console.log(f.cyan(`--- ${I.basename(g)} ---`)),console.log(f.gray(l.slice(0,500))),l.length>500&&console.log(f.gray("...")),console.log("");}return}let d=0,p=0;for(let g of n){let l=F.readFileSync(g,"utf-8"),m=I.relative(process.cwd(),g);e.start(`Applying ${m}...`);try{let y=await fetch(`${B}/schema-engine/query/${a$1}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:l})});if(!y.ok){let D=await y.text();throw new Error(D)}e.succeed(`Applied ${m}`),d++;}catch(y){let D=y instanceof Error?y.message:"Unknown error";e.fail(`Failed ${m}: ${D}`),p++;}}console.log(""),console.log(p===0?f.green(`Successfully applied ${d} migration(s)`):f.yellow(`Applied ${d}, failed ${p} migration(s)`)),console.log("");}async function ve(o){let e=K(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=o.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=I.resolve(o.output||"vaif.schema.json");console.log(""),console.log(f.bold("VAIF Database Pull")),console.log(""),e.start("Pulling schema from remote...");try{let n=await fetch(`${B}/schema-engine/introspect/${a$1}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok){let p=await n.text();throw new Error(`Failed to pull schema: ${p}`)}let c=await n.json();F.writeFileSync(i,JSON.stringify(c,null,2),"utf-8"),e.succeed(`Schema written to ${I.relative(process.cwd(),i)}`);let d=c.tables?.length??Object.keys(c).length;console.log(f.gray(` ${d} table(s) pulled`)),console.log("");}catch(n){e.fail("Failed to pull schema"),n instanceof Error&&console.log(f.red(`
|
|
22
22
|
Error: ${n.message}`)),process.exit(1);}}async function Ie(o){let e=K(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=o.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(console.log(f.red("No project ID specified")),process.exit(1)),console.log(""),console.log(f.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(f.red("This will:")),console.log(f.red(" - Drop all tables")),console.log(f.red(" - Delete all data")),console.log(f.red(" - Reset migrations")),console.log(""),console.log(f.red.bold("This action cannot be undone!")),console.log(""),o.force||(console.log(f.yellow("Use --force to confirm this action.")),process.exit(1)),e.start("Resetting database...");try{await to(t.token,a$1),e.succeed("Database reset complete"),console.log(""),console.log(f.gray("Your database is now empty.")),console.log(f.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.red(`
|
|
23
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
24
|
-
Error: ${n.message}`)),process.exit(1);}}async function
|
|
25
|
-
Generate one with: vaif keys generate`));return}let d=Math.max(8,...c.map(g=>(g.name||"").length)),p=` ${"Name".padEnd(d)} ${"Key".padEnd(24)} Created`;console.log(f.gray(p)),console.log(f.gray(" "+"-".repeat(p.length-2)));for(let g of c){let l=(g.name||"unnamed").padEnd(d),
|
|
26
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
27
|
-
Error: ${c.message}`)),process.exit(1);}}async function
|
|
23
|
+
Error: ${i.message}`)),process.exit(1);}}var Se=process.env.VAIF_API_URL||"https://api.vaif.studio";function be(o,e,t){return o.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||t.projectId||null}async function Ae(o){let e=K(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=be(o,r,t);a$1||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=o.name||`cli-key-${Date.now()}`;console.log(""),console.log(f.bold("VAIF Generate API Key")),console.log(""),e.start("Generating API key...");try{let n=await fetch(`${Se}/projects/${a$1}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i})});if(!n.ok){let d=await n.text();throw new Error(`Failed to generate key: ${d}`)}let c=await n.json();e.succeed("API key generated"),console.log(""),console.log(f.green(` Name: ${c.name}`)),console.log(f.green(` Key: ${c.key}`)),console.log(""),console.log(f.yellow.bold(" Save this key now - it will not be shown again!")),console.log("");}catch(n){e.fail("Failed to generate API key"),n instanceof Error&&console.log(f.red(`
|
|
24
|
+
Error: ${n.message}`)),process.exit(1);}}async function ke(o){let e=K(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=be(o,r,t);a$1||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f.bold("VAIF API Keys")),console.log(""),e.start("Fetching API keys...");try{let i=await fetch(`${Se}/projects/${a$1}/api-keys`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let g=await i.text();throw new Error(`Failed to list keys: ${g}`)}let n=await i.json(),c=n.keys||n;if(e.stop(),!Array.isArray(c)||c.length===0){console.log(f.yellow("No API keys found")),console.log(f.gray(`
|
|
25
|
+
Generate one with: vaif keys generate`));return}let d=Math.max(8,...c.map(g=>(g.name||"").length)),p=` ${"Name".padEnd(d)} ${"Key".padEnd(24)} Created`;console.log(f.gray(p)),console.log(f.gray(" "+"-".repeat(p.length-2)));for(let g of c){let l=(g.name||"unnamed").padEnd(d),m=g.maskedKey||g.prefix||`${(g.key||"").slice(0,12)}...`,y=g.createdAt?new Date(g.createdAt).toLocaleDateString():"N/A";console.log(` ${l} ${m.padEnd(24)} ${y}`);}console.log(""),console.log(f.gray(` ${c.length} key(s) total`)),console.log("");}catch(i){e.fail("Failed to list API keys"),i instanceof Error&&console.log(f.red(`
|
|
26
|
+
Error: ${i.message}`)),process.exit(1);}}var O=process.env.VAIF_API_URL||"https://api.vaif.studio";function so(o,e,t){return o.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||t.projectId||null}function q(){let o=b();return (!o||!o.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1)),o}async function M(o){try{return await a(o||"vaif.config.json")}catch{return null}}function W(o,e,t){let s=so(o,e,t);return s||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),s}async function Pe(o,e,t){let s=K(),r=q(),a=await M(t.config),i=W(t,a,r),n=e;if(t.fromFile)try{n=F.readFileSync(t.fromFile,"utf-8");}catch(c){console.log(f.red(`Failed to read file: ${t.fromFile}`)),c instanceof Error&&console.log(f.gray(c.message)),process.exit(1);}n||(console.log(f.red("No value provided")),console.log(f.gray("Provide a value as argument or use --from-file <path>")),process.exit(1)),console.log(""),console.log(f.bold("VAIF Set Secret")),console.log(""),s.start("Checking for existing secret...");try{let c=new URL(`${O}/functions/secrets/project/${i}`);t.envId&&c.searchParams.set("envId",t.envId);let d=await fetch(c.toString(),{headers:{Authorization:`Bearer ${r.token}`}});if(!d.ok)throw new Error(`Failed to check existing secrets: ${await d.text()}`);let g=(await d.json()).find(l=>l.key===o);if(g){s.text=`Updating secret "${o}"...`;let l=await fetch(`${O}/functions/secrets/${g.id}`,{method:"PUT",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!l.ok)throw new Error(`Failed to update secret: ${await l.text()}`);s.succeed(`Updated secret "${o}"`);}else {s.text=`Creating secret "${o}"...`;let l=await fetch(`${O}/functions/secrets`,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:i,envId:t.envId,key:o,value:n})});if(!l.ok)throw new Error(`Failed to create secret: ${await l.text()}`);s.succeed(`Created secret "${o}"`);}console.log("");}catch(c){s.fail("Failed to set secret"),c instanceof Error&&console.log(f.red(`
|
|
27
|
+
Error: ${c.message}`)),process.exit(1);}}async function Ce(o){let e=K(),t=q(),s=await M(o.config),r=W(o,s,t);console.log(""),console.log(f.bold("VAIF Secrets")),console.log(""),e.start("Fetching secrets...");try{let a=new URL(`${O}/functions/secrets/project/${r}`);o.envId&&a.searchParams.set("envId",o.envId);let i=await fetch(a.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(e.stop(),n.length===0){console.log(f.yellow("No secrets found")),console.log(f.gray(`
|
|
28
28
|
Create one with: vaif secrets set <name> <value>`));return}let c=Math.max(8,...n.map(p=>p.key.length)),d=` ${"Name".padEnd(c)} Created`;console.log(f.gray(d)),console.log(f.gray(" "+"-".repeat(d.length-2)));for(let p of n){let g=p.key.padEnd(c),l=p.createdAt?new Date(p.createdAt).toLocaleDateString():"N/A";console.log(` ${g} ${l}`);}console.log(""),console.log(f.gray(` ${n.length} secret(s) total`)),console.log(f.gray(" Values are hidden. Use `vaif secrets get <name>` to reveal.")),console.log("");}catch(a){e.fail("Failed to list secrets"),a instanceof Error&&console.log(f.red(`
|
|
29
|
-
Error: ${a.message}`)),process.exit(1);}}async function
|
|
30
|
-
Error: ${i.message}`)),process.exit(1);}}async function xe(o,e){let t=K(),s=
|
|
31
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
32
|
-
Error: ${i.message}`)),process.exit(1);}}var co=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Re(o){let e=K(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=o.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(console.log(f.red("No project ID specified")),console.log(f.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(`${co}/projects/${a$1}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let y=await i.text();throw new Error(`Failed to fetch project status: ${y}`)}let n=await i.json();e.stop(),console.log(""),console.log(f.bold("VAIF Project Status")),console.log("");let c=22,d=(y,
|
|
33
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
29
|
+
Error: ${a.message}`)),process.exit(1);}}async function Ee(o,e){let t=K(),s=q(),r=await M(e.config),a=W(e,r,s);console.log(""),t.start("Fetching secret...");try{let i=new URL(`${O}/functions/secrets/project/${a}`);e.envId&&i.searchParams.set("envId",e.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 d=(await n.json()).find(l=>l.key===o);d||(t.fail(`Secret "${o}" not found`),process.exit(1));let p=await fetch(`${O}/functions/secrets/${d.id}/value`,{headers:{Authorization:`Bearer ${s.token}`}});if(!p.ok)throw new Error(`Failed to get secret value: ${await p.text()}`);let g=await p.json();t.stop(),console.log(g.value);}catch(i){t.fail("Failed to get secret"),i instanceof Error&&console.log(f.red(`
|
|
30
|
+
Error: ${i.message}`)),process.exit(1);}}async function xe(o,e){let t=K(),s=q(),r=await M(e.config),a=W(e,r,s);console.log(""),console.log(f.bold("VAIF Delete Secret")),console.log(""),t.start("Finding secret...");try{let i=new URL(`${O}/functions/secrets/project/${a}`);e.envId&&i.searchParams.set("envId",e.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 d=(await n.json()).find(g=>g.key===o);d||(t.fail(`Secret "${o}" not found`),process.exit(1)),t.text=`Deleting secret "${o}"...`;let p=await fetch(`${O}/functions/secrets/${d.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 "${o}"`),console.log("");}catch(i){t.fail("Failed to delete secret"),i instanceof Error&&console.log(f.red(`
|
|
31
|
+
Error: ${i.message}`)),process.exit(1);}}var Fe=process.env.VAIF_API_URL||"https://api.vaif.studio";function ro(o){try{let e=new URL(o);return e.password&&(e.password="****"),e.toString()}catch{return o.replace(/:[^@/]+@/,":****@")}}async function De(o){let e=K(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=o.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(console.log(f.red("No project ID specified")),console.log(f.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(`${Fe}/projects/${a$1}`,{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();e.stop(),console.log(""),console.log(f.bold("VAIF Project Info")),console.log("");let c=16,d=(p,g)=>{console.log(` ${f.gray(p.padEnd(c))} ${g}`);};d("Name:",f.white(n.name||"N/A")),d("Project ID:",f.white(a$1)),d("Region:",f.white(n.region||"us-east-1")),d("Plan:",f.white(n.plan||n.tier||"free")),d("Created:",f.white(n.createdAt?new Date(n.createdAt).toLocaleDateString():"N/A")),console.log(""),d("API URL:",f.cyan(n.apiUrl||`${Fe}/v1`)),d("WS URL:",f.cyan(n.wsUrl||n.realtimeUrl||"N/A")),d("DB URL:",f.cyan(n.databaseUrl?ro(n.databaseUrl):"N/A")),d("Storage URL:",f.cyan(n.storageUrl||"N/A")),console.log("");}catch(i){e.fail("Failed to fetch project info"),i instanceof Error&&console.log(f.red(`
|
|
32
|
+
Error: ${i.message}`)),process.exit(1);}}var co=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Re(o){let e=K(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=o.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(console.log(f.red("No project ID specified")),console.log(f.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(`${co}/projects/${a$1}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let y=await i.text();throw new Error(`Failed to fetch project status: ${y}`)}let n=await i.json();e.stop(),console.log(""),console.log(f.bold("VAIF Project Status")),console.log("");let c=22,d=(y,D)=>{console.log(` ${f.gray(y.padEnd(c))} ${D}`);};d("Project:",f.white(n.name||a$1)),d("Plan:",f.white(n.plan||n.tier||"free")),console.log(""),console.log(f.gray(" --- Resources ---")),console.log("");let p=n.tableCount??n.tables?.length??"N/A",g=n.functionCount??n.functions?.length??"N/A",l=n.bucketCount??n.storage?.buckets?.length??"N/A",m=n.activeConnections??n.connections??"N/A";d("Tables:",f.white(String(p))),d("Functions:",f.white(String(g))),d("Storage Buckets:",f.white(String(l))),d("Active Connections:",f.white(String(m))),n.usage&&(console.log(""),console.log(f.gray(" --- Usage ---")),console.log(""),n.usage.dbSize&&d("Database Size:",f.white(n.usage.dbSize)),n.usage.storageSize&&d("Storage Size:",f.white(n.usage.storageSize)),n.usage.bandwidth&&d("Bandwidth:",f.white(n.usage.bandwidth)),n.usage.functionInvocations!=null&&d("Function Invocations:",f.white(String(n.usage.functionInvocations)))),console.log("");}catch(i){e.fail("Failed to fetch project status"),i instanceof Error&&console.log(f.red(`
|
|
33
|
+
Error: ${i.message}`)),process.exit(1);}}var V=process.env.VAIF_API_URL||"https://api.vaif.studio";function go(o,e,t){return o.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||t.projectId||null}function fo(o){if(!o||o.length===0)return "*No tables found. Create tables in the VAIF Studio dashboard.*";let e="";for(let t of o){e+=`### \`${t.name}\`
|
|
34
34
|
|
|
35
35
|
`,e+=`| Column | Type | Nullable | Default | Constraints |
|
|
36
36
|
`,e+=`|--------|------|----------|---------|-------------|
|
|
@@ -57,7 +57,7 @@ await vaif.from("${a.name}").update(recordId, {
|
|
|
57
57
|
|
|
58
58
|
`,r+=`// Delete
|
|
59
59
|
await vaif.from("${a.name}").delete(recordId);
|
|
60
|
-
`,r+="```\n\n";}return r}function uo(o){let e=o.type.toLowerCase();return e.includes("uuid")?'"crypto.randomUUID()"':e.includes("int")||e.includes("serial")?"42":e.includes("bool")?"true":e.includes("timestamp")||e.includes("date")?'"new Date().toISOString()"':e.includes("json")?"{}":e.includes("float")||e.includes("numeric")||e.includes("decimal")||e.includes("double")?"3.14":`"example_${o.name}"`}function
|
|
60
|
+
`,r+="```\n\n";}return r}function uo(o){let e=o.type.toLowerCase();return e.includes("uuid")?'"crypto.randomUUID()"':e.includes("int")||e.includes("serial")?"42":e.includes("bool")?"true":e.includes("timestamp")||e.includes("date")?'"new Date().toISOString()"':e.includes("json")?"{}":e.includes("float")||e.includes("numeric")||e.includes("decimal")||e.includes("double")?"3.14":`"example_${o.name}"`}function ho(o){let{projectId:e,apiKey:t,apiUrl:s,projectName:r,schema:a}=o,i=fo(a.tables),n=po(a.tables);return `# VAIF Studio Backend
|
|
61
61
|
|
|
62
62
|
This project uses **VAIF Studio** as its backend. Project: **${r}** (\`${e}\`).
|
|
63
63
|
|
|
@@ -189,6 +189,223 @@ channel.subscribe();
|
|
|
189
189
|
channel.unsubscribe();
|
|
190
190
|
\`\`\`
|
|
191
191
|
|
|
192
|
+
## Row-Level Security (RLS)
|
|
193
|
+
|
|
194
|
+
Filter data per-user by sending the \`X-VAIF-RLS\` header with your requests. The header format is \`field:value\`, comma-separated for multiple fields.
|
|
195
|
+
|
|
196
|
+
\`\`\`typescript
|
|
197
|
+
// SDK: pass RLS context to scope queries to the current user
|
|
198
|
+
const posts = await vaif.from("posts").select({
|
|
199
|
+
headers: { "x-vaif-rls": \`user_id:\${currentUser.id}\` },
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
// Multiple RLS fields (e.g., multi-tenant + user scoping)
|
|
203
|
+
const data = await vaif.from("documents").select({
|
|
204
|
+
headers: { "x-vaif-rls": \`org_id:\${orgId},user_id:\${userId}\` },
|
|
205
|
+
});
|
|
206
|
+
\`\`\`
|
|
207
|
+
|
|
208
|
+
**How it works:**
|
|
209
|
+
- On **SELECT / UPDATE / DELETE**: RLS fields are added as WHERE conditions (e.g., \`WHERE user_id = $1\`)
|
|
210
|
+
- On **INSERT**: RLS fields are auto-populated into the record if not already provided
|
|
211
|
+
- This enables multi-tenant data isolation without database-level RLS policies
|
|
212
|
+
|
|
213
|
+
## Realtime Setup
|
|
214
|
+
|
|
215
|
+
Enable realtime on your tables, then subscribe to live changes:
|
|
216
|
+
|
|
217
|
+
\`\`\`typescript
|
|
218
|
+
// 1. Enable realtime on tables via API
|
|
219
|
+
await fetch("${s}/realtime/install", {
|
|
220
|
+
method: "POST",
|
|
221
|
+
headers: {
|
|
222
|
+
Authorization: \`Bearer \${token}\`,
|
|
223
|
+
"Content-Type": "application/json",
|
|
224
|
+
},
|
|
225
|
+
body: JSON.stringify({
|
|
226
|
+
projectId: "${e}",
|
|
227
|
+
tables: ["messages", "notifications"],
|
|
228
|
+
}),
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
// 2. Subscribe to changes via SDK
|
|
232
|
+
const channel = vaif.realtime.channel("chat-room");
|
|
233
|
+
|
|
234
|
+
channel.on("postgres_changes", {
|
|
235
|
+
event: "*", // INSERT, UPDATE, DELETE, or * for all
|
|
236
|
+
schema: "public",
|
|
237
|
+
table: "messages",
|
|
238
|
+
}, (payload) => {
|
|
239
|
+
console.log("Change:", payload.eventType, payload.new);
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
channel.subscribe();
|
|
243
|
+
|
|
244
|
+
// 3. Presence: track who's online
|
|
245
|
+
channel.on("presence", { event: "sync" }, () => {
|
|
246
|
+
const state = channel.presenceState();
|
|
247
|
+
console.log("Online users:", Object.keys(state));
|
|
248
|
+
});
|
|
249
|
+
channel.track({ user_id: currentUser.id, status: "online" });
|
|
250
|
+
|
|
251
|
+
// 4. Broadcast: send ephemeral messages (typing indicators, cursors)
|
|
252
|
+
channel.send({
|
|
253
|
+
type: "broadcast",
|
|
254
|
+
event: "typing",
|
|
255
|
+
payload: { userId: currentUser.id },
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
// Cleanup
|
|
259
|
+
channel.unsubscribe();
|
|
260
|
+
\`\`\`
|
|
261
|
+
|
|
262
|
+
## Storage Policies
|
|
263
|
+
|
|
264
|
+
Control who can access storage buckets with RLS-style policies:
|
|
265
|
+
|
|
266
|
+
\`\`\`typescript
|
|
267
|
+
// Create a policy: only the uploader can read their own files
|
|
268
|
+
await fetch("${s}/storage/buckets/\${bucketId}/policies", {
|
|
269
|
+
method: "POST",
|
|
270
|
+
headers: {
|
|
271
|
+
Authorization: \`Bearer \${token}\`,
|
|
272
|
+
"Content-Type": "application/json",
|
|
273
|
+
},
|
|
274
|
+
body: JSON.stringify({
|
|
275
|
+
name: "owner_read",
|
|
276
|
+
operation: "SELECT", // SELECT | INSERT | UPDATE | DELETE | ALL
|
|
277
|
+
definition: "auth.uid() = owner_id",
|
|
278
|
+
}),
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
// Create a policy: authenticated users can upload
|
|
282
|
+
await fetch("${s}/storage/buckets/\${bucketId}/policies", {
|
|
283
|
+
method: "POST",
|
|
284
|
+
headers: {
|
|
285
|
+
Authorization: \`Bearer \${token}\`,
|
|
286
|
+
"Content-Type": "application/json",
|
|
287
|
+
},
|
|
288
|
+
body: JSON.stringify({
|
|
289
|
+
name: "auth_insert",
|
|
290
|
+
operation: "INSERT",
|
|
291
|
+
definition: "auth.uid() IS NOT NULL",
|
|
292
|
+
}),
|
|
293
|
+
});
|
|
294
|
+
\`\`\`
|
|
295
|
+
|
|
296
|
+
## Edge Function Deployment
|
|
297
|
+
|
|
298
|
+
Create and deploy serverless functions:
|
|
299
|
+
|
|
300
|
+
\`\`\`typescript
|
|
301
|
+
// 1. Create a function
|
|
302
|
+
const fn = await fetch("${s}/functions", {
|
|
303
|
+
method: "POST",
|
|
304
|
+
headers: {
|
|
305
|
+
Authorization: \`Bearer \${token}\`,
|
|
306
|
+
"Content-Type": "application/json",
|
|
307
|
+
},
|
|
308
|
+
body: JSON.stringify({
|
|
309
|
+
projectId: "${e}",
|
|
310
|
+
name: "send_welcome_email",
|
|
311
|
+
runtime: "nodejs20", // nodejs20 (default)
|
|
312
|
+
entrypoint: "index.ts", // default
|
|
313
|
+
timeoutMs: 10000, // 1000\u201330000ms, default 10000
|
|
314
|
+
}),
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
// 2. Deploy source code
|
|
318
|
+
await fetch(\`${s}/functions/\${fn.id}/source\`, {
|
|
319
|
+
method: "PUT",
|
|
320
|
+
headers: {
|
|
321
|
+
Authorization: \`Bearer \${token}\`,
|
|
322
|
+
"Content-Type": "application/json",
|
|
323
|
+
},
|
|
324
|
+
body: JSON.stringify({
|
|
325
|
+
sourceCode: \`
|
|
326
|
+
export default async function handler(req, ctx) {
|
|
327
|
+
const { userId } = req.body;
|
|
328
|
+
// ctx.secrets contains your encrypted secrets
|
|
329
|
+
const apiKey = ctx.secrets.SENDGRID_KEY;
|
|
330
|
+
return { status: "sent", userId };
|
|
331
|
+
}
|
|
332
|
+
\`,
|
|
333
|
+
}),
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
// 3. Invoke the function
|
|
337
|
+
const result = await vaif.functions.invoke("send_welcome_email", {
|
|
338
|
+
body: { userId: "user_123" },
|
|
339
|
+
});
|
|
340
|
+
\`\`\`
|
|
341
|
+
|
|
342
|
+
## API Key Management
|
|
343
|
+
|
|
344
|
+
API keys are project-scoped and used for data-plane authentication (CRUD, storage, functions).
|
|
345
|
+
|
|
346
|
+
\`\`\`typescript
|
|
347
|
+
// Create a new API key
|
|
348
|
+
const { key } = await fetch("${s}/projects/${e}/api-keys", {
|
|
349
|
+
method: "POST",
|
|
350
|
+
headers: {
|
|
351
|
+
Authorization: \`Bearer \${token}\`,
|
|
352
|
+
"Content-Type": "application/json",
|
|
353
|
+
},
|
|
354
|
+
body: JSON.stringify({ name: "production-frontend" }),
|
|
355
|
+
}).then(r => r.json());
|
|
356
|
+
|
|
357
|
+
// List keys
|
|
358
|
+
const keys = await fetch("${s}/projects/${e}/api-keys", {
|
|
359
|
+
headers: { Authorization: \`Bearer \${token}\` },
|
|
360
|
+
}).then(r => r.json());
|
|
361
|
+
|
|
362
|
+
// Rotate a key (generates new secret, old key stops working)
|
|
363
|
+
await fetch(\`${s}/projects/${e}/api-keys/\${keyId}/rotate\`, {
|
|
364
|
+
method: "POST",
|
|
365
|
+
headers: { Authorization: \`Bearer \${token}\` },
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
// Revoke a key
|
|
369
|
+
await fetch(\`${s}/projects/${e}/api-keys/\${keyId}/revoke\`, {
|
|
370
|
+
method: "POST",
|
|
371
|
+
headers: { Authorization: \`Bearer \${token}\` },
|
|
372
|
+
});
|
|
373
|
+
\`\`\`
|
|
374
|
+
|
|
375
|
+
## Secrets & Environment Variables
|
|
376
|
+
|
|
377
|
+
Secrets are encrypted at rest and injected into function invocations at runtime.
|
|
378
|
+
|
|
379
|
+
\`\`\`typescript
|
|
380
|
+
// Set a secret (via API)
|
|
381
|
+
await fetch("${s}/functions/secrets", {
|
|
382
|
+
method: "POST",
|
|
383
|
+
headers: {
|
|
384
|
+
Authorization: \`Bearer \${token}\`,
|
|
385
|
+
"Content-Type": "application/json",
|
|
386
|
+
},
|
|
387
|
+
body: JSON.stringify({
|
|
388
|
+
projectId: "${e}",
|
|
389
|
+
key: "STRIPE_SECRET_KEY",
|
|
390
|
+
value: "sk_live_...",
|
|
391
|
+
}),
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
// Or use the CLI
|
|
395
|
+
// vaif secrets set STRIPE_SECRET_KEY sk_live_...
|
|
396
|
+
// vaif secrets list
|
|
397
|
+
// vaif secrets delete STRIPE_SECRET_KEY
|
|
398
|
+
\`\`\`
|
|
399
|
+
|
|
400
|
+
**Accessing secrets in functions:**
|
|
401
|
+
|
|
402
|
+
\`\`\`typescript
|
|
403
|
+
export default async function handler(req, ctx) {
|
|
404
|
+
const stripe = new Stripe(ctx.secrets.STRIPE_SECRET_KEY);
|
|
405
|
+
// ...
|
|
406
|
+
}
|
|
407
|
+
\`\`\`
|
|
408
|
+
|
|
192
409
|
## API Reference Notes
|
|
193
410
|
|
|
194
411
|
### Filter Syntax
|
|
@@ -222,5 +439,5 @@ All authenticated requests require:
|
|
|
222
439
|
- \`Authorization: Bearer <jwt_token>\` \u2014 for user-scoped requests
|
|
223
440
|
- \`x-api-key: <api_key>\` \u2014 for server-side / service-role requests
|
|
224
441
|
- \`x-project-id: ${e}\` \u2014 identifies the project
|
|
225
|
-
`}async function
|
|
226
|
-
`,"utf-8"),e.succeed(`Written ${f.cyan(".mcp.json")}`);}if(!o.skipClaudeMd){e.start("Writing CLAUDE.md...");let g=mo({projectId:a$1,apiKey:p,apiUrl:d,projectName:c,schema:n}),l=I.join(i,"CLAUDE.md");D.writeFileSync(l,g,"utf-8"),e.succeed(`Written ${f.cyan("CLAUDE.md")}`);}console.log(""),console.log(f.green.bold(" Claude Code integration configured!")),console.log(""),o.skipMcp||console.log(f.gray(" MCP Server: ")+f.white(".mcp.json")),o.skipClaudeMd||console.log(f.gray(" Context: ")+f.white("CLAUDE.md")),console.log(""),console.log(f.bold(" Next steps:")),console.log(f.gray(" 1. Open this project in Claude Code")),console.log(f.gray(" 2. The MCP server auto-connects to your VAIF project")),console.log(f.gray(" 3. Ask Claude to query, modify, or build against your schema")),console.log("");}var Oe="1.8.1",X=f.hex("#00f0ff"),Z=f.hex("#7b61ff"),ee=f.hex("#ff3dff"),oe=f.hex("#00ff9d"),w=f.hex("#555570"),O=f.hex("#00f0ff");function ho(){console.log(""),console.log(X(" \u2566 \u2566")+Z("\u2554\u2550\u2557\u2566")+ee("\u2554\u2550\u2557 ")+oe("\u2554\u2550\u2557\u2566 \u2566")),console.log(X(" \u255A\u2557\u2554\u255D")+Z("\u2560\u2550\u2563\u2551")+ee("\u2560\u2563 ")+oe("\u2551 \u2551 \u2551")),console.log(X(" \u255A\u255D ")+Z("\u2569 \u2569\u2569")+ee("\u255A ")+oe("\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(O(" VAIF Studio CLI")+w(` v${Oe}`)),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.bold(" Quick Start")),console.log(w(" $ ")+O("vaif login")+w(" Authenticate")),console.log(w(" $ ")+O("vaif init -t react-spa")+w(" Scaffold project")),console.log(w(" $ ")+O("vaif db push")+w(" Push migrations")),console.log(w(" $ ")+O("vaif generate")+w(" Generate types")),console.log(w(" $ ")+O("vaif functions deploy")+w(" Deploy functions")),console.log(""),console.log(f.bold(" Categories")),console.log(w(" auth ")+f.white("login, logout, whoami")),console.log(w(" project ")+f.white("init, templates, info, status")),console.log(w(" schema ")+f.white("pull, push, generate")),console.log(w(" database ")+f.white("db push, db pull, db seed, db reset")),console.log(w(" deploy ")+f.white("functions deploy, functions list")),console.log(w(" security ")+f.white("keys, secrets")),console.log(w(" ai ")+f.white("claude-setup")),console.log(""),console.log(w(" Run ")+O("vaif <command> --help")+w(" for details")),console.log(w(" Docs: ")+f.underline("https://docs.vaif.studio")),console.log("");}program.name("vaif").description("VAIF CLI - Type generation and development tools").version(Oe);program.command("login").description("Authenticate with VAIF (opens browser)").option("-e, --email","Login with email/password instead of browser").option("-p, --project-id <id>","Default project ID").action(c);program.command("logout").description("Log out and remove stored credentials").action(d);program.command("whoami").description("Show current authenticated user").action(e);program.command("init").description("Initialize VAIF configuration in your project").option("--typescript","Setup for TypeScript project").option("-f, --force","Overwrite existing config").option("-t, --template <name>","Scaffold from a template (run vaif templates for list)").option("--features <features>","Comma-separated features to include: auth,database,realtime,storage,functions").option("--add-features <features>","Add features to an existing project (requires --template)").action(h);program.command("templates").alias("tpl").description("List available project templates").action(g);program.command("info").description("Show project information (name, region, URLs)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(Ee);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(Re);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);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(fe);program.command("generate").alias("gen").description("Generate TypeScript types from your database schema").option("-c, --connection <url>","Database connection string").option("-o, --output <path>","Output file path","./src/types/database.ts").option("--schema <name>","Schema name","public").option("--config <path>","Config file path","vaif.config.json").option("--dry-run","Preview generated types without writing").action(f$1);var Te=program.command("functions").alias("fn").description("Manage serverless functions");Te.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(me);Te.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(he);var G=program.command("db").description("Database management commands");G.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(je);G.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(ve);G.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(we);G.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(Ie);var Ue=program.command("keys").description("Manage API keys");Ue.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(Ae);Ue.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(Pe);var Y=program.command("secrets").alias("sec").description("Manage function secrets");Y.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(Ce);Y.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(ke);Y.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(Fe);Y.command("delete <name>").description("Delete a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(xe);program.command("claude-setup").description("Configure Claude Code integration (MCP server + CLAUDE.md)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID").option("-k, --api-key <key>","API key for MCP server").option("--skip-mcp","Skip generating .mcp.json").option("--skip-claude-md","Skip generating CLAUDE.md").option("-o, --output-dir <dir>","Output directory",".").action(Ve);process.argv.slice(2).length||(ho(),process.exit(0));program.parse(process.argv);
|
|
442
|
+
`}async function Oe(o){let e=K(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=go(o,r,t);a$1||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=I.resolve(o.outputDir||".");console.log(""),console.log(f.bold("VAIF Claude Code Setup")),console.log(f.gray(` Project: ${a$1}`)),console.log(""),e.start("Fetching database schema...");let n={tables:[]};try{let g=await fetch(`${V}/schema-engine/introspect/${a$1}`,{headers:{Authorization:`Bearer ${t.token}`}});g.ok?(n=await g.json(),e.succeed(`Fetched schema (${n.tables?.length||0} tables)`)):e.warn("Could not fetch schema \u2014 continuing without it");}catch{e.warn("Could not fetch schema \u2014 continuing without it");}e.start("Fetching project info...");let c=a$1,d=V;try{let g=await fetch(`${V}/projects/${a$1}`,{headers:{Authorization:`Bearer ${t.token}`}});if(g.ok){let l=await g.json();c=l.name||a$1,d=l.apiUrl||V,e.succeed(`Project: ${c}`);}else e.warn("Could not fetch project info \u2014 using defaults");}catch{e.warn("Could not fetch project info \u2014 using defaults");}let p=o.apiKey||r?.api?.apiKey||"";if(!p){e.start("Generating API key for Claude Code...");try{let g=`claude-code-${Date.now()}`,l=await fetch(`${V}/projects/${a$1}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:g})});l.ok?(p=(await l.json()).key,e.succeed(`Generated API key: ${g}`)):(e.fail("Could not auto-generate API key"),console.log(f.yellow(" Pass one with --api-key or generate via `vaif keys generate`")),process.exit(1));}catch{e.fail("Could not auto-generate API key"),console.log(f.yellow(" Pass one with --api-key or generate via `vaif keys generate`")),process.exit(1);}}if(!o.skipMcp){e.start("Writing .mcp.json...");let g={mcpServers:{"vaif-studio":{command:"npx",args:["@vaiftech/mcp"],env:{VAIF_API_KEY:p,VAIF_PROJECT_ID:a$1,VAIF_API_URL:d,VAIF_AUTH_TOKEN:t.token}}}},l=I.join(i,".mcp.json");F.writeFileSync(l,JSON.stringify(g,null,2)+`
|
|
443
|
+
`,"utf-8"),e.succeed(`Written ${f.cyan(".mcp.json")}`);}if(!o.skipClaudeMd){e.start("Writing CLAUDE.md...");let g=ho({projectId:a$1,apiKey:p,apiUrl:d,projectName:c,schema:n}),l=I.join(i,"CLAUDE.md");F.writeFileSync(l,g,"utf-8"),e.succeed(`Written ${f.cyan("CLAUDE.md")}`);}console.log(""),console.log(f.green.bold(" Claude Code integration configured!")),console.log(""),o.skipMcp||console.log(f.gray(" MCP Server: ")+f.white(".mcp.json")),o.skipClaudeMd||console.log(f.gray(" Context: ")+f.white("CLAUDE.md")),console.log(""),console.log(f.bold(" Next steps:")),console.log(f.gray(" 1. Open this project in Claude Code")),console.log(f.gray(" 2. The MCP server auto-connects to your VAIF project")),console.log(f.gray(" 3. Ask Claude to query, modify, or build against your schema")),console.log("");}var Ne="1.8.1",X=f.hex("#00f0ff"),Z=f.hex("#7b61ff"),ee=f.hex("#ff3dff"),oe=f.hex("#00ff9d"),w=f.hex("#555570"),N=f.hex("#00f0ff");function mo(){console.log(""),console.log(X(" \u2566 \u2566")+Z("\u2554\u2550\u2557\u2566")+ee("\u2554\u2550\u2557 ")+oe("\u2554\u2550\u2557\u2566 \u2566")),console.log(X(" \u255A\u2557\u2554\u255D")+Z("\u2560\u2550\u2563\u2551")+ee("\u2560\u2563 ")+oe("\u2551 \u2551 \u2551")),console.log(X(" \u255A\u255D ")+Z("\u2569 \u2569\u2569")+ee("\u255A ")+oe("\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(N(" VAIF Studio CLI")+w(` v${Ne}`)),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.bold(" Quick Start")),console.log(w(" $ ")+N("vaif login")+w(" Authenticate")),console.log(w(" $ ")+N("vaif init -t react-spa")+w(" Scaffold project")),console.log(w(" $ ")+N("vaif db push")+w(" Push migrations")),console.log(w(" $ ")+N("vaif generate")+w(" Generate types")),console.log(w(" $ ")+N("vaif functions deploy")+w(" Deploy functions")),console.log(""),console.log(f.bold(" Categories")),console.log(w(" auth ")+f.white("login, logout, whoami")),console.log(w(" project ")+f.white("init, templates, info, status")),console.log(w(" schema ")+f.white("pull, push, generate")),console.log(w(" database ")+f.white("db push, db pull, db seed, db reset")),console.log(w(" deploy ")+f.white("functions deploy, functions list")),console.log(w(" security ")+f.white("keys, secrets")),console.log(w(" ai ")+f.white("claude-setup")),console.log(""),console.log(w(" Run ")+N("vaif <command> --help")+w(" for details")),console.log(w(" Docs: ")+f.underline("https://docs.vaif.studio")),console.log("");}program.name("vaif").description("VAIF CLI - Type generation and development tools").version(Ne);program.command("login").description("Authenticate with VAIF (opens browser)").option("-e, --email","Login with email/password instead of browser").option("-p, --project-id <id>","Default project ID").action(c);program.command("logout").description("Log out and remove stored credentials").action(d);program.command("whoami").description("Show current authenticated user").action(e);program.command("init").description("Initialize VAIF configuration in your project").option("--typescript","Setup for TypeScript project").option("-f, --force","Overwrite existing config").option("-t, --template <name>","Scaffold from a template (run vaif templates for list)").option("--features <features>","Comma-separated features to include: auth,database,realtime,storage,functions").option("--add-features <features>","Add features to an existing project (requires --template)").action(h);program.command("templates").alias("tpl").description("List available project templates").action(g);program.command("info").description("Show project information (name, region, URLs)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(De);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(Re);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);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(fe);program.command("generate").alias("gen").description("Generate TypeScript types from your database schema").option("-c, --connection <url>","Database connection string").option("-o, --output <path>","Output file path","./src/types/database.ts").option("--schema <name>","Schema name","public").option("--config <path>","Config file path","vaif.config.json").option("--dry-run","Preview generated types without writing").action(f$1);var _e=program.command("functions").alias("fn").description("Manage serverless functions");_e.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(he);_e.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(me);var G=program.command("db").description("Database management commands");G.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(je);G.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(ve);G.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(we);G.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(Ie);var Le=program.command("keys").description("Manage API keys");Le.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(Ae);Le.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(ke);var Y=program.command("secrets").alias("sec").description("Manage function secrets");Y.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(Pe);Y.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(Ce);Y.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(Ee);Y.command("delete <name>").description("Delete a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(xe);program.command("claude-setup").description("Configure Claude Code integration (MCP server + CLAUDE.md)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID").option("-k, --api-key <key>","API key for MCP server").option("--skip-mcp","Skip generating .mcp.json").option("--skip-claude-md","Skip generating CLAUDE.md").option("-o, --output-dir <dir>","Output directory",".").action(Oe);process.argv.slice(2).length||(mo(),process.exit(0));program.parse(process.argv);
|