@vaiftech/cli 1.9.9 → 1.10.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 +57 -1
- package/dist/{chunk-KHEM3PLW.js → chunk-6Y62OF5M.js} +1378 -38
- package/dist/cli.cjs +869 -126
- package/dist/cli.js +80 -677
- package/dist/index.cjs +1380 -40
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/package.json +3 -3
package/dist/cli.js
CHANGED
|
@@ -1,682 +1,85 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {c,d,e,
|
|
3
|
-
Error: ${
|
|
4
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),
|
|
5
|
-
Error: ${
|
|
6
|
-
Error: ${
|
|
7
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let
|
|
8
|
-
Expected schema file at: ${
|
|
9
|
-
Error: ${
|
|
10
|
-
Cancelled. No changes applied.`));return}}
|
|
11
|
-
Error: ${
|
|
2
|
+
import {c,d,e,i,g,f as f$1,h,b,a}from'./chunk-6Y62OF5M.js';import'dotenv/config';import {createRequire}from'module';import {program}from'commander';import f from'chalk';import b$1 from'fs';import j from'path';import J from'ora';import Qe from'readline';var We=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Ye(e,t,o="public"){let s=await fetch(`${We}/projects/${t}/schema?schema=${o}`,{headers:{Authorization:`Bearer ${e}`,"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 de(e){let t=J(),o=b();(!o||!o.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",r=null;t.start("Loading configuration...");try{r=await a(s);}catch(c){t.fail("Failed to load config"),console.log(f.red(`
|
|
3
|
+
Error: ${c}`)),process.exit(1);}r||(t.fail("No configuration found"),console.log(f.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let i=e.projectId||r.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(t.fail("No project ID specified"),console.log(f.yellow(`
|
|
4
|
+
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),t.text="Fetching remote schema...";try{let c=e.schema||r.database?.schema||"public",n=await Ye(o.token,i,c);t.succeed("Schema fetched successfully");let a=e.output||j.resolve("vaif.schema.json"),l={$schema:"https://vaif.studio/schemas/schema.json",projectId:i,schema:c,pulledAt:new Date().toISOString(),...n};b$1.writeFileSync(a,JSON.stringify(l,null,2),"utf-8"),console.log(""),console.log(f.green(`Schema saved to: ${a}`)),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(c){t.fail("Failed to fetch schema"),c instanceof Error&&console.log(f.red(`
|
|
5
|
+
Error: ${c.message}`)),process.exit(1);}}var pe=process.env.VAIF_API_URL||"https://api.vaif.studio";function Xe(e){let t=Qe.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{t.question(e,s=>{t.close(),o(s);});})}async function Ze(e,t,o){let s=await fetch(`${pe}/projects/${t}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!s.ok){let r=await s.text();throw new Error(`Failed to preview changes: ${r}`)}return s.json()}async function eo(e,t,o){let s=await fetch(`${pe}/projects/${t}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!s.ok){let r=await s.text();throw new Error(`Failed to apply changes: ${r}`)}return s.json()}function oo(e){if(console.log(""),console.log(f.bold("Schema Changes:")),console.log(""),e.added.length===0&&e.modified.length===0&&e.removed.length===0){console.log(f.gray(" No changes detected. Schema is up to date."));return}if(e.added.length>0){console.log(f.green.bold(" + Added:"));for(let t of e.added)console.log(f.green(` + ${t.type}: ${t.name}`));console.log("");}if(e.modified.length>0){console.log(f.yellow.bold(" ~ Modified:"));for(let t of e.modified){console.log(f.yellow(` ~ ${t.type}: ${t.name}`));for(let o of t.changes)console.log(f.gray(` ${o}`));}console.log("");}if(e.removed.length>0){console.log(f.red.bold(" - Removed:"));for(let t of e.removed)console.log(f.red(` - ${t.type}: ${t.name}`));console.log("");}}async function me(e){let t=J(),o=b();(!o||!o.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",r=null;t.start("Loading configuration...");try{r=await a(s);}catch(a){t.fail("Failed to load config"),console.log(f.red(`
|
|
6
|
+
Error: ${a}`)),process.exit(1);}r||(t.fail("No configuration found"),console.log(f.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let i=e.projectId||r.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(t.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 c=e.schema||j.resolve("vaif.schema.json");b$1.existsSync(c)||(t.fail("No local schema found"),console.log(f.yellow(`
|
|
8
|
+
Expected schema file at: ${c}`)),console.log(f.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let n;try{let a=b$1.readFileSync(c,"utf-8");n=JSON.parse(a);}catch(a){t.fail("Failed to parse schema file"),a instanceof Error&&console.log(f.red(`
|
|
9
|
+
Error: ${a.message}`)),process.exit(1);}t.text="Calculating schema changes...";try{let{diff:a,sql:l}=await Ze(o.token,i,n);if(t.stop(),oo(a),a.added.length===0&&a.modified.length===0&&a.removed.length===0){console.log("");return}if(l.length>0){console.log(f.bold("SQL Migrations:")),console.log("");for(let d of l)console.log(f.gray(` ${d}`));console.log("");}if(e.dryRun){console.log(f.yellow("Dry run mode - no changes applied.")),console.log(f.gray("Remove --dry-run to apply these changes."));return}if(!e.force){a.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 g=await Xe(f.cyan("Apply these changes? [y/N] "));if(g.toLowerCase()!=="y"&&g.toLowerCase()!=="yes"){console.log(f.yellow(`
|
|
10
|
+
Cancelled. No changes applied.`));return}}t.start("Applying schema changes...");let u=await eo(o.token,i,n);if(u.success){if(t.succeed("Schema changes applied successfully"),console.log(""),u.migrations.length>0){console.log(f.gray("Migrations applied:"));for(let d of u.migrations)console.log(f.gray(` - ${d}`));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 t.fail("Failed to apply some changes");}catch(a){t.fail("Failed to push schema changes"),a instanceof Error&&console.log(f.red(`
|
|
11
|
+
Error: ${a.message}`)),process.exit(1);}}var z=process.env.VAIF_API_URL||"https://api.vaif.studio";async function to(e,t,o,s){let r=new URL(`${z}/functions/project/${t}`);s&&r.searchParams.set("envId",s);let i=await fetch(r.toString(),{headers:{Authorization:`Bearer ${e}`}});if(!i.ok)return null;let c=await i.json(),n=c.functions||c;return Array.isArray(n)&&n.find(a=>a.name===o)||null}async function no(e,t,o){let s=await fetch(`${z}/functions/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:t,name:o.name,runtime:o.runtime,entrypoint:o.entrypoint,envId:o.envId})});if(!s.ok){let r=await s.text();throw new Error(`Failed to create function: ${r}`)}return s.json()}async function so(e,t,o){let s=await fetch(`${z}/functions/${t}/source`,{method:"PUT",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({sourceCode:o})});if(!s.ok){let r=await s.text();throw new Error(`Failed to deploy source: ${r}`)}}async function io(e,t,o){let s=new URL(`${z}/functions/project/${t}`);o&&s.searchParams.set("envId",o);let r=await fetch(s.toString(),{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){let c=await r.text();throw new Error(`Failed to list functions: ${c}`)}let i=await r.json();return i.functions||i}function he(e){switch(j.extname(e).toLowerCase()){case ".ts":return "typescript";case ".js":case ".mjs":return "nodejs";case ".py":return "python";case ".go":return "go";case ".rs":return "rust";default:return "nodejs"}}function ye(e){let t=[],o=[".ts",".js",".mjs",".py",".go",".rs"],s=["drizzle.config.ts","tsconfig.json","package.json"];if(!b$1.existsSync(e))return t;let r=b$1.readdirSync(e,{withFileTypes:true});for(let i of r){let c=j.join(e,i.name);if(i.isDirectory()){if(i.name!=="node_modules"&&!i.name.startsWith(".")){let n=b$1.readdirSync(c,{withFileTypes:true});for(let a of n)if(a.isFile()){let l=j.extname(a.name).toLowerCase();if(o.includes(l)){t.push(j.join(c,a.name));break}}}}else if(i.isFile()){let n=j.extname(i.name).toLowerCase();o.includes(n)&&!s.includes(i.name)&&t.push(c);}}return t}async function we(e){let t=J(),o=b();(!o||!o.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let i=e.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(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(""),t.start("Scanning for function files...");let c=j.resolve("functions"),n=j.resolve("src/functions"),a$1=[];if(e.entrypoint){let g=j.resolve(e.entrypoint);b$1.existsSync(g)||(t.fail(`File not found: ${e.entrypoint}`),process.exit(1)),a$1=[g];}else a$1=[...ye(c),...ye(n)];a$1.length===0&&(t.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
|
-
Or specify an entrypoint with --entrypoint`)),process.exit(1)),
|
|
14
|
-
No functions matching "${
|
|
15
|
-
No functions found`)),console.log(f.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(f.bold(`Functions (${
|
|
16
|
-
Error: ${
|
|
13
|
+
Or specify an entrypoint with --entrypoint`)),process.exit(1)),t.succeed(`Found ${a$1.length} function(s)`),e.name&&(a$1=a$1.filter(g=>j.basename(g,j.extname(g)).includes(e.name)),a$1.length===0&&(console.log(f.yellow(`
|
|
14
|
+
No functions matching "${e.name}" found`)),process.exit(1))),console.log(""),console.log(f.gray("Functions to deploy:"));for(let g of a$1){let m=j.basename(j.dirname(g)),w=m==="functions"||m==="src"?j.basename(g,j.extname(g)):m,D=e.runtime||he(g);console.log(f.gray(` - ${w} (${D})`));}if(console.log(""),e.dryRun){console.log(f.yellow("Dry run mode - no functions deployed."));return}let l=[];for(let g of a$1){let m=j.basename(j.dirname(g)),w=m==="functions"||m==="src"?j.basename(g,j.extname(g)):m,D=e.runtime||he(g);t.start(`Deploying ${w}...`);try{let L=b$1.readFileSync(g,"utf-8"),_=await to(o.token,i,w,e.envId);_||(t.text=`Creating ${w}...`,_=await no(o.token,i,{name:w,runtime:D,entrypoint:j.basename(g),envId:e.envId})),t.text=`Deploying ${w}...`,await so(o.token,_.id,L),t.succeed(`Deployed ${w}`),l.push({name:w,success:!0});}catch(L){let _=L instanceof Error?L.message:"Unknown error";t.fail(`Failed to deploy ${w}`),l.push({name:w,success:false,error:_});}}console.log("");let u=l.filter(g=>g.success).length;if(l.filter(g=>!g.success).length===0)console.log(f.green(`\u2713 Successfully deployed ${u} function(s)`));else {console.log(f.yellow(`Deployed ${u}/${l.length} function(s)`)),console.log(""),console.log(f.red("Failed deployments:"));for(let g of l.filter(m=>!m.success))console.log(f.red(` - ${g.name}: ${g.error}`));}console.log("");}async function je(e){let t=J(),o=b();(!o||!o.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let i=e.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(console.log(f.red("No project ID specified")),process.exit(1)),t.start("Fetching functions...");try{let c=await io(o.token,i,e.envId);if(t.stop(),c.length===0){console.log(f.yellow(`
|
|
15
|
+
No functions found`)),console.log(f.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(f.bold(`Functions (${c.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 c){let a=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)+a(n.deployStatus.padEnd(12))+String(n.invocationCount??0).padEnd(14)+(n.deployedAt?new Date(n.deployedAt).toLocaleDateString():"-"));}console.log("");}catch(c){t.fail("Failed to fetch functions"),c instanceof Error&&console.log(f.red(`
|
|
16
|
+
Error: ${c.message}`)),process.exit(1);}}var K=process.env.VAIF_API_URL||"https://api.vaif.studio";async function ro(e,t,o,s,r){let i=await fetch(`${K}/projects/${t}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({table:o,records:s,truncate:r?.truncate??false})});if(!i.ok){let c=await i.text();throw new Error(`Failed to seed ${o}: ${c}`)}return i.json()}async function co(e,t){let o=await fetch(`${K}/projects/${t}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!o.ok){let s=await o.text();throw new Error(`Failed to reset database: ${s}`)}return o.json()}function X(e){let t=[];if(!b$1.existsSync(e))return t;let o=b$1.readdirSync(e,{withFileTypes:true});for(let s of o)if(s.isFile()){let r=j.extname(s.name).toLowerCase();(r===".json"||r===".ts"||r===".js")&&t.push(j.join(e,s.name));}return t.sort()}async function ve(e){let t=j.extname(e).toLowerCase();if(t===".json"){let o=b$1.readFileSync(e,"utf-8"),s=JSON.parse(o);return Array.isArray(s)?[{table:j.basename(e,t),data:s}]:s.table&&s.data?[s]:Object.entries(s).map(([r,i])=>({table:r,data:i}))}else if(t===".ts"||t===".js"){let o=await import(e),s=o.default||o;return typeof s=="function"?s():s}throw new Error(`Unsupported file format: ${t}`)}async function Ie(e){let t=J(),o=b();(!o||!o.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let i=e.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(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 c=[];if(e.file){let u=j.resolve(e.file);b$1.existsSync(u)||(console.log(f.red(`File not found: ${e.file}`)),process.exit(1)),c=[u];}else {let u=j.resolve("seeds"),d=j.resolve("prisma/seed"),g=j.resolve("db/seeds");c=[...X(u),...X(d),...X(g)];}c.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
|
|
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 u of c)console.log(f.gray(` - ${j.relative(process.cwd(),u)}`));if(console.log(""),e.truncate&&(console.log(f.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),e.dryRun){console.log(f.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let u of c){t.start(`Loading ${j.basename(u)}...`);try{let d=await ve(u);t.stop();for(let g of d)e.table&&g.table!==e.table||(console.log(f.cyan(`Table: ${g.table}`)),console.log(f.gray(` Records: ${g.data.length}`)),g.data.length>0&&console.log(f.gray(` Sample: ${JSON.stringify(g.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(d){t.fail(`Failed to load ${j.basename(u)}`),d instanceof Error&&console.log(f.red(` Error: ${d.message}`));}}return}let n=[];for(let u of c){t.start(`Processing ${j.basename(u)}...`);try{let d=await ve(u);t.stop();for(let g of d)if(!(e.table&&g.table!==e.table)){if(g.data.length===0){console.log(f.gray(` Skipping ${g.table} (no records)`));continue}t.start(`Seeding ${g.table} (${g.data.length} records)...`);try{let m=await ro(o.token,i,g.table,g.data,{truncate:e.truncate});t.succeed(`Seeded ${g.table}: ${m.inserted} records`),n.push({table:g.table,inserted:m.inserted});}catch(m){let w=m instanceof Error?m.message:"Unknown error";t.fail(`Failed to seed ${g.table}`),n.push({table:g.table,inserted:0,error:w});}}}catch(d){t.fail(`Failed to load ${j.basename(u)}`),d instanceof Error&&console.log(f.red(` Error: ${d.message}`));}}console.log("");let a$1=n.reduce((u,d)=>u+d.inserted,0),l=n.filter(u=>u.error).length;if(l===0)console.log(f.green(`\u2713 Successfully seeded ${a$1} records across ${n.length} table(s)`));else {console.log(f.yellow(`Seeded ${a$1} records with ${l} error(s)`)),console.log(""),console.log(f.red("Errors:"));for(let u of n.filter(d=>d.error))console.log(f.red(` - ${u.table}: ${u.error}`));}console.log("");}async function $e(e){let t=J(),o=b();(!o||!o.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let i=e.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(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 c=j.resolve(e.dir||"./drizzle");if(console.log(""),console.log(f.bold("VAIF Database Push")),console.log(""),!b$1.existsSync(c)){let d=j.resolve("./migrations");b$1.existsSync(d)?console.log(f.gray(`Using migrations from: ${d}`)):(console.log(f.red(`Migrations directory not found: ${c}`)),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
|
|
22
|
-
Error: ${
|
|
23
|
-
Error: ${
|
|
24
|
-
Error: ${
|
|
25
|
-
Generate one with: vaif keys generate`));return}let
|
|
26
|
-
Error: ${
|
|
27
|
-
Error: ${
|
|
28
|
-
Create one with: vaif secrets set <name> <value>`));return}let
|
|
29
|
-
Error: ${
|
|
30
|
-
Error: ${
|
|
31
|
-
Error: ${
|
|
32
|
-
Error: ${
|
|
33
|
-
Error: ${
|
|
34
|
-
`)
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
${
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
`,
|
|
73
|
-
`,
|
|
74
|
-
`,
|
|
75
|
-
`,
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
\`\`\`typescript
|
|
86
|
-
import { createVaifClient } from "@vaiftech/client";
|
|
87
|
-
|
|
88
|
-
const vaif = createVaifClient({
|
|
89
|
-
baseUrl: "${n}",
|
|
90
|
-
projectId: "${e}",
|
|
91
|
-
apiKey: "${t}",
|
|
92
|
-
});
|
|
93
|
-
\`\`\`
|
|
94
|
-
|
|
95
|
-
## Database Schema
|
|
96
|
-
|
|
97
|
-
${r}
|
|
98
|
-
|
|
99
|
-
## CRUD Examples
|
|
100
|
-
|
|
101
|
-
${s}
|
|
102
|
-
|
|
103
|
-
## Authentication (End-User Auth)
|
|
104
|
-
|
|
105
|
-
VAIF provides **project-scoped** authentication for your app's end-users. All auth routes are scoped to your project ID.
|
|
106
|
-
|
|
107
|
-
### API Routes
|
|
108
|
-
|
|
109
|
-
| Route | Method | Auth | Description |
|
|
110
|
-
|-------|--------|------|-------------|
|
|
111
|
-
| \`/projects/${e}/auth/signup\` | POST | None (public) | Register a new user |
|
|
112
|
-
| \`/projects/${e}/auth/login\` | POST | None (public) | Login with email/password |
|
|
113
|
-
| \`/projects/${e}/auth/refresh\` | POST | Cookie | Refresh access token |
|
|
114
|
-
|
|
115
|
-
### Signup
|
|
116
|
-
|
|
117
|
-
\`\`\`typescript
|
|
118
|
-
const res = await fetch("${n}/projects/${e}/auth/signup", {
|
|
119
|
-
method: "POST",
|
|
120
|
-
headers: { "Content-Type": "application/json" },
|
|
121
|
-
body: JSON.stringify({
|
|
122
|
-
email: "user@example.com",
|
|
123
|
-
password: "securePassword123",
|
|
124
|
-
metadata: { displayName: "Jane Doe" }, // optional
|
|
125
|
-
}),
|
|
126
|
-
});
|
|
127
|
-
const { accessToken, expiresIn, user } = await res.json();
|
|
128
|
-
// accessToken: JWT with { sub: userId, email, projectId, type: "project_user" }
|
|
129
|
-
\`\`\`
|
|
130
|
-
|
|
131
|
-
### Login
|
|
132
|
-
|
|
133
|
-
\`\`\`typescript
|
|
134
|
-
const res = await fetch("${n}/projects/${e}/auth/login", {
|
|
135
|
-
method: "POST",
|
|
136
|
-
headers: { "Content-Type": "application/json" },
|
|
137
|
-
body: JSON.stringify({
|
|
138
|
-
email: "user@example.com",
|
|
139
|
-
password: "securePassword123",
|
|
140
|
-
}),
|
|
141
|
-
});
|
|
142
|
-
const { accessToken, expiresIn, user } = await res.json();
|
|
143
|
-
\`\`\`
|
|
144
|
-
|
|
145
|
-
### Token Refresh
|
|
146
|
-
|
|
147
|
-
\`\`\`typescript
|
|
148
|
-
// Refresh token is stored as httpOnly cookie (project_refresh_token)
|
|
149
|
-
// and sent automatically with same-origin requests
|
|
150
|
-
const res = await fetch("${n}/projects/${e}/auth/refresh", {
|
|
151
|
-
method: "POST",
|
|
152
|
-
credentials: "include", // sends the httpOnly cookie
|
|
153
|
-
});
|
|
154
|
-
const { accessToken, expiresIn, user } = await res.json();
|
|
155
|
-
\`\`\`
|
|
156
|
-
|
|
157
|
-
### Using Auth in Your App
|
|
158
|
-
|
|
159
|
-
\`\`\`typescript
|
|
160
|
-
// Store the access token and use it for authenticated requests
|
|
161
|
-
const headers = {
|
|
162
|
-
Authorization: \\\`Bearer \\\${accessToken}\\\`,
|
|
163
|
-
"x-vaif-key": "${t}",
|
|
164
|
-
};
|
|
165
|
-
|
|
166
|
-
// The JWT contains: { sub: userId, email, projectId, type: "project_user" }
|
|
167
|
-
// Use this with RLS to scope data to the current user
|
|
168
|
-
\`\`\`
|
|
169
|
-
|
|
170
|
-
> **Important**: Auth routes are at \`/projects/{projectId}/auth/*\`, NOT \`/auth/*\`. The \`/auth/*\` routes are for VAIF Studio platform accounts, not your app's end-users.
|
|
171
|
-
|
|
172
|
-
## Storage
|
|
173
|
-
|
|
174
|
-
\`\`\`typescript
|
|
175
|
-
// Upload a file
|
|
176
|
-
const { url } = await vaif.storage.upload("avatars", file, {
|
|
177
|
-
contentType: "image/png",
|
|
178
|
-
});
|
|
179
|
-
|
|
180
|
-
// Download a file
|
|
181
|
-
const blob = await vaif.storage.download("avatars", "photo.png");
|
|
182
|
-
|
|
183
|
-
// Create a signed URL (expiring)
|
|
184
|
-
const { signedUrl } = await vaif.storage.createSignedUrl("avatars", "photo.png", {
|
|
185
|
-
expiresIn: 3600,
|
|
186
|
-
});
|
|
187
|
-
|
|
188
|
-
// List files in a bucket
|
|
189
|
-
const files = await vaif.storage.list("avatars", { limit: 100 });
|
|
190
|
-
\`\`\`
|
|
191
|
-
|
|
192
|
-
## Functions
|
|
193
|
-
|
|
194
|
-
\`\`\`typescript
|
|
195
|
-
// Invoke a serverless function
|
|
196
|
-
const result = await vaif.functions.invoke("send_welcome_email", {
|
|
197
|
-
body: { userId: "user_123", template: "welcome" },
|
|
198
|
-
});
|
|
199
|
-
\`\`\`
|
|
200
|
-
|
|
201
|
-
> **Function naming**: Names must be alphanumeric and underscores only (\`^[a-zA-Z0-9_]+$\`). Use \`send_email\` not \`send-email\`.
|
|
202
|
-
|
|
203
|
-
## Realtime
|
|
204
|
-
|
|
205
|
-
\`\`\`typescript
|
|
206
|
-
// Subscribe to a channel
|
|
207
|
-
const channel = vaif.realtime.channel("my-channel");
|
|
208
|
-
|
|
209
|
-
// Listen for postgres changes
|
|
210
|
-
channel.on("postgres_changes", {
|
|
211
|
-
event: "INSERT",
|
|
212
|
-
schema: "public",
|
|
213
|
-
table: "messages",
|
|
214
|
-
}, (payload) => {
|
|
215
|
-
console.log("New message:", payload.new);
|
|
216
|
-
});
|
|
217
|
-
|
|
218
|
-
// Listen for UPDATE events
|
|
219
|
-
channel.on("postgres_changes", {
|
|
220
|
-
event: "UPDATE",
|
|
221
|
-
schema: "public",
|
|
222
|
-
table: "messages",
|
|
223
|
-
}, (payload) => {
|
|
224
|
-
console.log("Updated:", payload.new, "was:", payload.old);
|
|
225
|
-
});
|
|
226
|
-
|
|
227
|
-
// Listen for DELETE events
|
|
228
|
-
channel.on("postgres_changes", {
|
|
229
|
-
event: "DELETE",
|
|
230
|
-
schema: "public",
|
|
231
|
-
table: "messages",
|
|
232
|
-
}, (payload) => {
|
|
233
|
-
console.log("Deleted:", payload.old);
|
|
234
|
-
});
|
|
235
|
-
|
|
236
|
-
// Subscribe to start receiving events
|
|
237
|
-
channel.subscribe();
|
|
238
|
-
|
|
239
|
-
// Unsubscribe when done
|
|
240
|
-
channel.unsubscribe();
|
|
241
|
-
\`\`\`
|
|
242
|
-
|
|
243
|
-
## Row-Level Security (RLS)
|
|
244
|
-
|
|
245
|
-
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.
|
|
246
|
-
|
|
247
|
-
\`\`\`typescript
|
|
248
|
-
// SDK: pass RLS context to scope queries to the current user
|
|
249
|
-
const posts = await vaif.from("posts").select({
|
|
250
|
-
headers: { "x-vaif-rls": \`user_id:\${currentUser.id}\` },
|
|
251
|
-
});
|
|
252
|
-
|
|
253
|
-
// Multiple RLS fields (e.g., multi-tenant + user scoping)
|
|
254
|
-
const data = await vaif.from("documents").select({
|
|
255
|
-
headers: { "x-vaif-rls": \`org_id:\${orgId},user_id:\${userId}\` },
|
|
256
|
-
});
|
|
257
|
-
\`\`\`
|
|
258
|
-
|
|
259
|
-
**How it works:**
|
|
260
|
-
- On **SELECT / UPDATE / DELETE**: RLS fields are added as WHERE conditions (e.g., \`WHERE user_id = $1\`)
|
|
261
|
-
- On **INSERT**: RLS fields are auto-populated into the record if not already provided
|
|
262
|
-
- This enables multi-tenant data isolation without database-level RLS policies
|
|
263
|
-
|
|
264
|
-
## Realtime Setup
|
|
265
|
-
|
|
266
|
-
Enable realtime on your tables, then subscribe to live changes:
|
|
267
|
-
|
|
268
|
-
\`\`\`typescript
|
|
269
|
-
// 1. Enable realtime on tables via API
|
|
270
|
-
await fetch("${n}/realtime/install", {
|
|
271
|
-
method: "POST",
|
|
272
|
-
headers: {
|
|
273
|
-
Authorization: \`Bearer \${token}\`,
|
|
274
|
-
"Content-Type": "application/json",
|
|
275
|
-
},
|
|
276
|
-
body: JSON.stringify({
|
|
277
|
-
projectId: "${e}",
|
|
278
|
-
tables: ["messages", "notifications"],
|
|
279
|
-
}),
|
|
280
|
-
});
|
|
281
|
-
|
|
282
|
-
// 2. Subscribe to changes via SDK
|
|
283
|
-
const channel = vaif.realtime.channel("chat-room");
|
|
284
|
-
|
|
285
|
-
channel.on("postgres_changes", {
|
|
286
|
-
event: "*", // INSERT, UPDATE, DELETE, or * for all
|
|
287
|
-
schema: "public",
|
|
288
|
-
table: "messages",
|
|
289
|
-
}, (payload) => {
|
|
290
|
-
console.log("Change:", payload.eventType, payload.new);
|
|
291
|
-
});
|
|
292
|
-
|
|
293
|
-
channel.subscribe();
|
|
294
|
-
|
|
295
|
-
// 3. Presence: track who's online
|
|
296
|
-
channel.on("presence", { event: "sync" }, () => {
|
|
297
|
-
const state = channel.presenceState();
|
|
298
|
-
console.log("Online users:", Object.keys(state));
|
|
299
|
-
});
|
|
300
|
-
channel.track({ user_id: currentUser.id, status: "online" });
|
|
301
|
-
|
|
302
|
-
// 4. Broadcast: send ephemeral messages (typing indicators, cursors)
|
|
303
|
-
channel.send({
|
|
304
|
-
type: "broadcast",
|
|
305
|
-
event: "typing",
|
|
306
|
-
payload: { userId: currentUser.id },
|
|
307
|
-
});
|
|
308
|
-
|
|
309
|
-
// Cleanup
|
|
310
|
-
channel.unsubscribe();
|
|
311
|
-
\`\`\`
|
|
312
|
-
|
|
313
|
-
## Storage Policies
|
|
314
|
-
|
|
315
|
-
Control who can access storage buckets with RLS-style policies:
|
|
316
|
-
|
|
317
|
-
\`\`\`typescript
|
|
318
|
-
// Create a policy: only the uploader can read their own files
|
|
319
|
-
await fetch("${n}/storage/buckets/\${bucketId}/policies", {
|
|
320
|
-
method: "POST",
|
|
321
|
-
headers: {
|
|
322
|
-
Authorization: \`Bearer \${token}\`,
|
|
323
|
-
"Content-Type": "application/json",
|
|
324
|
-
},
|
|
325
|
-
body: JSON.stringify({
|
|
326
|
-
name: "owner_read",
|
|
327
|
-
operation: "SELECT", // SELECT | INSERT | UPDATE | DELETE | ALL
|
|
328
|
-
definition: "auth.uid() = owner_id",
|
|
329
|
-
}),
|
|
330
|
-
});
|
|
331
|
-
|
|
332
|
-
// Create a policy: authenticated users can upload
|
|
333
|
-
await fetch("${n}/storage/buckets/\${bucketId}/policies", {
|
|
334
|
-
method: "POST",
|
|
335
|
-
headers: {
|
|
336
|
-
Authorization: \`Bearer \${token}\`,
|
|
337
|
-
"Content-Type": "application/json",
|
|
338
|
-
},
|
|
339
|
-
body: JSON.stringify({
|
|
340
|
-
name: "auth_insert",
|
|
341
|
-
operation: "INSERT",
|
|
342
|
-
definition: "auth.uid() IS NOT NULL",
|
|
343
|
-
}),
|
|
344
|
-
});
|
|
345
|
-
\`\`\`
|
|
346
|
-
|
|
347
|
-
## Edge Function Deployment
|
|
348
|
-
|
|
349
|
-
Create and deploy serverless functions:
|
|
350
|
-
|
|
351
|
-
\`\`\`typescript
|
|
352
|
-
// 1. Create a function
|
|
353
|
-
const fn = await fetch("${n}/functions", {
|
|
354
|
-
method: "POST",
|
|
355
|
-
headers: {
|
|
356
|
-
Authorization: \`Bearer \${token}\`,
|
|
357
|
-
"Content-Type": "application/json",
|
|
358
|
-
},
|
|
359
|
-
body: JSON.stringify({
|
|
360
|
-
projectId: "${e}",
|
|
361
|
-
name: "send_welcome_email",
|
|
362
|
-
runtime: "nodejs20", // nodejs20 (default)
|
|
363
|
-
entrypoint: "index.ts", // default
|
|
364
|
-
timeoutMs: 10000, // 1000\u201330000ms, default 10000
|
|
365
|
-
}),
|
|
366
|
-
});
|
|
367
|
-
|
|
368
|
-
// 2. Deploy source code
|
|
369
|
-
await fetch(\`${n}/functions/\${fn.id}/source\`, {
|
|
370
|
-
method: "PUT",
|
|
371
|
-
headers: {
|
|
372
|
-
Authorization: \`Bearer \${token}\`,
|
|
373
|
-
"Content-Type": "application/json",
|
|
374
|
-
},
|
|
375
|
-
body: JSON.stringify({
|
|
376
|
-
sourceCode: \`
|
|
377
|
-
export default async function handler(req, ctx) {
|
|
378
|
-
const { userId } = req.body;
|
|
379
|
-
// ctx.secrets contains your encrypted secrets
|
|
380
|
-
const apiKey = ctx.secrets.SENDGRID_KEY;
|
|
381
|
-
return { status: "sent", userId };
|
|
382
|
-
}
|
|
383
|
-
\`,
|
|
384
|
-
}),
|
|
385
|
-
});
|
|
386
|
-
|
|
387
|
-
// 3. Invoke the function
|
|
388
|
-
const result = await vaif.functions.invoke("send_welcome_email", {
|
|
389
|
-
body: { userId: "user_123" },
|
|
390
|
-
});
|
|
391
|
-
\`\`\`
|
|
392
|
-
|
|
393
|
-
### Authenticated Context in Functions
|
|
394
|
-
|
|
395
|
-
Access the caller's verified identity via \\\`vaif.auth\\\`:
|
|
396
|
-
|
|
397
|
-
\`\`\`typescript
|
|
398
|
-
export default async function handler(req) {
|
|
399
|
-
const auth = vaif.auth;
|
|
400
|
-
// auth.type = 'user' | 'api_key' | 'function'
|
|
401
|
-
// auth.userId \u2014 User ID (for user/function types)
|
|
402
|
-
// auth.email \u2014 User email (for user type)
|
|
403
|
-
// auth.projectId \u2014 Always present
|
|
404
|
-
// auth.scopes \u2014 API key scopes (for api_key type)
|
|
405
|
-
|
|
406
|
-
if (!auth || auth.type !== 'user') {
|
|
407
|
-
return { statusCode: 401, body: { error: 'Unauthorized' } };
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
return { body: { message: "Hello " + auth.email } };
|
|
411
|
-
}
|
|
412
|
-
\`\`\`
|
|
413
|
-
|
|
414
|
-
### Function-to-Function Invocation
|
|
415
|
-
|
|
416
|
-
Call other functions from within a handler:
|
|
417
|
-
|
|
418
|
-
\`\`\`typescript
|
|
419
|
-
export default async function handler(req) {
|
|
420
|
-
const result = await vaif.invoke("send_email", {
|
|
421
|
-
to: "user@example.com",
|
|
422
|
-
subject: "Hello",
|
|
423
|
-
});
|
|
424
|
-
return { statusCode: 200, body: result };
|
|
425
|
-
}
|
|
426
|
-
\`\`\`
|
|
427
|
-
|
|
428
|
-
### Database Triggers
|
|
429
|
-
|
|
430
|
-
Fire functions automatically on insert/update/delete events. Configure triggers via the API:
|
|
431
|
-
|
|
432
|
-
\`\`\`
|
|
433
|
-
POST /functions/\\\${functionId}/triggers
|
|
434
|
-
{ "event": "db.insert", "tableName": "orders", "enabled": true }
|
|
435
|
-
\`\`\`
|
|
436
|
-
|
|
437
|
-
## API Key Management
|
|
438
|
-
|
|
439
|
-
API keys are project-scoped and used for data-plane authentication (CRUD, storage, functions).
|
|
440
|
-
|
|
441
|
-
\`\`\`typescript
|
|
442
|
-
// Create a new API key
|
|
443
|
-
const { key } = await fetch("${n}/projects/${e}/api-keys", {
|
|
444
|
-
method: "POST",
|
|
445
|
-
headers: {
|
|
446
|
-
Authorization: \`Bearer \${token}\`,
|
|
447
|
-
"Content-Type": "application/json",
|
|
448
|
-
},
|
|
449
|
-
body: JSON.stringify({ name: "production-frontend" }),
|
|
450
|
-
}).then(r => r.json());
|
|
451
|
-
|
|
452
|
-
// List keys
|
|
453
|
-
const keys = await fetch("${n}/projects/${e}/api-keys", {
|
|
454
|
-
headers: { Authorization: \`Bearer \${token}\` },
|
|
455
|
-
}).then(r => r.json());
|
|
456
|
-
|
|
457
|
-
// Rotate a key (generates new secret, old key stops working)
|
|
458
|
-
await fetch(\`${n}/projects/${e}/api-keys/\${keyId}/rotate\`, {
|
|
459
|
-
method: "POST",
|
|
460
|
-
headers: { Authorization: \`Bearer \${token}\` },
|
|
461
|
-
});
|
|
462
|
-
|
|
463
|
-
// Revoke a key
|
|
464
|
-
await fetch(\`${n}/projects/${e}/api-keys/\${keyId}/revoke\`, {
|
|
465
|
-
method: "POST",
|
|
466
|
-
headers: { Authorization: \`Bearer \${token}\` },
|
|
467
|
-
});
|
|
468
|
-
\`\`\`
|
|
469
|
-
|
|
470
|
-
## Secrets & Environment Variables
|
|
471
|
-
|
|
472
|
-
Secrets are encrypted at rest and injected into function invocations at runtime.
|
|
473
|
-
|
|
474
|
-
\`\`\`typescript
|
|
475
|
-
// Set a secret (via API)
|
|
476
|
-
await fetch("${n}/functions/secrets", {
|
|
477
|
-
method: "POST",
|
|
478
|
-
headers: {
|
|
479
|
-
Authorization: \`Bearer \${token}\`,
|
|
480
|
-
"Content-Type": "application/json",
|
|
481
|
-
},
|
|
482
|
-
body: JSON.stringify({
|
|
483
|
-
projectId: "${e}",
|
|
484
|
-
key: "STRIPE_SECRET_KEY",
|
|
485
|
-
value: "sk_live_...",
|
|
486
|
-
}),
|
|
487
|
-
});
|
|
488
|
-
|
|
489
|
-
// Or use the CLI
|
|
490
|
-
// vaif secrets set STRIPE_SECRET_KEY sk_live_...
|
|
491
|
-
// vaif secrets list
|
|
492
|
-
// vaif secrets delete STRIPE_SECRET_KEY
|
|
493
|
-
\`\`\`
|
|
494
|
-
|
|
495
|
-
**Accessing secrets in functions:**
|
|
496
|
-
|
|
497
|
-
\`\`\`typescript
|
|
498
|
-
export default async function handler(req, ctx) {
|
|
499
|
-
const stripe = new Stripe(ctx.secrets.STRIPE_SECRET_KEY);
|
|
500
|
-
// ...
|
|
501
|
-
}
|
|
502
|
-
\`\`\`
|
|
503
|
-
|
|
504
|
-
## API Reference Notes
|
|
505
|
-
|
|
506
|
-
### Filter Syntax
|
|
507
|
-
|
|
508
|
-
The SDK supports these filter operators:
|
|
509
|
-
|
|
510
|
-
| Operator | Description | Example |
|
|
511
|
-
|----------|-------------|---------|
|
|
512
|
-
| \`eq\` | Equal | \`.eq("status", "active")\` |
|
|
513
|
-
| \`neq\` | Not equal | \`.neq("status", "deleted")\` |
|
|
514
|
-
| \`gt\` | Greater than | \`.gt("age", 18)\` |
|
|
515
|
-
| \`lt\` | Less than | \`.lt("price", 100)\` |
|
|
516
|
-
| \`gte\` | Greater than or equal | \`.gte("score", 90)\` |
|
|
517
|
-
| \`lte\` | Less than or equal | \`.lte("count", 10)\` |
|
|
518
|
-
| \`in\` | In array | \`.in("role", ["admin", "editor"])\` |
|
|
519
|
-
| \`like\` | Pattern match (case-sensitive) | \`.like("name", "%john%")\` |
|
|
520
|
-
| \`ilike\` | Pattern match (case-insensitive) | \`.ilike("name", "%john%")\` |
|
|
521
|
-
| \`is\` | IS comparison (null, true, false) | \`.is("deleted_at", null)\` |
|
|
522
|
-
|
|
523
|
-
### JSONB Subkey Filters
|
|
524
|
-
|
|
525
|
-
Filter on nested JSONB fields using arrow notation:
|
|
526
|
-
|
|
527
|
-
| Filter | SQL Generated |
|
|
528
|
-
|--------|--------------|
|
|
529
|
-
| \\\`filter[metadata->status]=active\\\` | \\\`metadata->>'status' = 'active'\\\` |
|
|
530
|
-
| \\\`filter[config->theme.ilike]=%dark%\\\` | \\\`config->>'theme' ILIKE '%dark%'\\\` |
|
|
531
|
-
| \\\`filter[data->user->role]=admin\\\` | \\\`data->'user'->>'role' = 'admin'\\\` |
|
|
532
|
-
|
|
533
|
-
All standard operators work with JSONB paths. The last segment uses \\\`->>\\\` (text extraction).
|
|
534
|
-
|
|
535
|
-
### Compound Filters (AND + OR)
|
|
536
|
-
|
|
537
|
-
Combine AND and OR conditions:
|
|
538
|
-
|
|
539
|
-
\`\`\`
|
|
540
|
-
?filter[status]=active&or_filter[role]=admin&or_filter[role]=moderator
|
|
541
|
-
\`\`\`
|
|
542
|
-
|
|
543
|
-
This generates: \\\`WHERE status = 'active' AND (role = 'admin' OR role = 'moderator')\\\`
|
|
544
|
-
|
|
545
|
-
### Full-Text Search
|
|
546
|
-
|
|
547
|
-
\`\`\`typescript
|
|
548
|
-
const results = await fetch("${n}/generated/posts/search", {
|
|
549
|
-
method: "POST",
|
|
550
|
-
headers: { "x-vaif-key": "${t}", "Content-Type": "application/json" },
|
|
551
|
-
body: JSON.stringify({
|
|
552
|
-
query: "search term",
|
|
553
|
-
columns: ["title", "body"],
|
|
554
|
-
limit: 20,
|
|
555
|
-
}),
|
|
556
|
-
});
|
|
557
|
-
// Results ranked by ts_rank score
|
|
558
|
-
\`\`\`
|
|
559
|
-
|
|
560
|
-
### Aggregation
|
|
561
|
-
|
|
562
|
-
\`\`\`typescript
|
|
563
|
-
const stats = await fetch("${n}/generated/orders/aggregate", {
|
|
564
|
-
method: "POST",
|
|
565
|
-
headers: { "x-vaif-key": "${t}", "Content-Type": "application/json" },
|
|
566
|
-
body: JSON.stringify({
|
|
567
|
-
aggregates: [
|
|
568
|
-
{ fn: "count", column: "*" },
|
|
569
|
-
{ fn: "sum", column: "total" },
|
|
570
|
-
{ fn: "avg", column: "total" },
|
|
571
|
-
],
|
|
572
|
-
groupBy: ["status"],
|
|
573
|
-
}),
|
|
574
|
-
});
|
|
575
|
-
\`\`\`
|
|
576
|
-
|
|
577
|
-
### Joins (Foreign Key Includes)
|
|
578
|
-
|
|
579
|
-
Include related rows by specifying foreign key columns:
|
|
580
|
-
|
|
581
|
-
\`\`\`
|
|
582
|
-
GET /generated/posts?include=author_id&include=category_id
|
|
583
|
-
\`\`\`
|
|
584
|
-
|
|
585
|
-
Returns posts with \\\`author_id_included\\\` and \\\`category_id_included\\\` objects containing the related rows.
|
|
586
|
-
|
|
587
|
-
### Upsert
|
|
588
|
-
|
|
589
|
-
Insert or update on conflict:
|
|
590
|
-
|
|
591
|
-
\`\`\`typescript
|
|
592
|
-
const result = await fetch("${n}/generated/users", {
|
|
593
|
-
method: "POST",
|
|
594
|
-
headers: { "x-vaif-key": "${t}", "Content-Type": "application/json" },
|
|
595
|
-
body: JSON.stringify({
|
|
596
|
-
email: "alice@example.com",
|
|
597
|
-
name: "Alice",
|
|
598
|
-
_upsert: true,
|
|
599
|
-
_conflictColumns: ["email"],
|
|
600
|
-
}),
|
|
601
|
-
});
|
|
602
|
-
\`\`\`
|
|
603
|
-
|
|
604
|
-
### Pagination
|
|
605
|
-
|
|
606
|
-
\`\`\`typescript
|
|
607
|
-
// Default: limit 20, offset 0
|
|
608
|
-
const page1 = await vaif.from("posts").select().limit(20).offset(0);
|
|
609
|
-
const page2 = await vaif.from("posts").select().limit(20).offset(20);
|
|
610
|
-
\`\`\`
|
|
611
|
-
|
|
612
|
-
### REST API Response Format
|
|
613
|
-
|
|
614
|
-
When calling the REST API directly (without the SDK), all data-plane responses are wrapped:
|
|
615
|
-
|
|
616
|
-
\`\`\`typescript
|
|
617
|
-
// GET /generated/{table} \u2192 list
|
|
618
|
-
{ data: [...], count: 5 }
|
|
619
|
-
|
|
620
|
-
// GET /generated/{table}/{id} \u2192 single record
|
|
621
|
-
{ data: { id: "...", ... } }
|
|
622
|
-
|
|
623
|
-
// POST /generated/{table} \u2192 created record
|
|
624
|
-
{ data: { id: "...", ... } }
|
|
625
|
-
|
|
626
|
-
// PATCH /generated/{table}/{id} \u2192 updated record
|
|
627
|
-
{ data: { id: "...", ... } }
|
|
628
|
-
|
|
629
|
-
// DELETE /generated/{table}/{id}
|
|
630
|
-
{ ok: true }
|
|
631
|
-
|
|
632
|
-
// Error responses
|
|
633
|
-
{ error: "NotFound", message: "...", requestId: "..." }
|
|
634
|
-
\`\`\`
|
|
635
|
-
|
|
636
|
-
The SDK unwraps these automatically, but if you use \`fetch()\` directly, access the data via \`response.data\`.
|
|
637
|
-
|
|
638
|
-
### Numeric/Decimal Column Serialization
|
|
639
|
-
|
|
640
|
-
PostgreSQL \`numeric\` and \`decimal\` columns serialize to **JSON strings** (to preserve arbitrary precision). This is standard behavior. Any column typed as \`numeric\` or \`decimal\` will arrive as \`"3.14"\` not \`3.14\`.
|
|
641
|
-
|
|
642
|
-
\`\`\`typescript
|
|
643
|
-
// Wrong \u2014 value is a string, comparison may fail
|
|
644
|
-
if (item.price > 10.0) { ... }
|
|
645
|
-
|
|
646
|
-
// Correct \u2014 parse before arithmetic
|
|
647
|
-
if (parseFloat(item.price) > 10.0) { ... }
|
|
648
|
-
\`\`\`
|
|
649
|
-
|
|
650
|
-
### Auth Headers
|
|
651
|
-
|
|
652
|
-
VAIF uses **two auth modes** \u2014 choose the right one for each operation:
|
|
653
|
-
|
|
654
|
-
| Auth Mode | Header | Used For |
|
|
655
|
-
|-----------|--------|----------|
|
|
656
|
-
| **API Key** | \`x-vaif-key: vaif_xxx\` | Data-plane: CRUD (\`/generated/*\`), storage uploads/downloads, function invocation |
|
|
657
|
-
| **JWT Token** | \`Authorization: Bearer <jwt>\` | Control-plane: schema introspection, project management, function CRUD, bucket creation |
|
|
658
|
-
|
|
659
|
-
> **Important**: API keys do NOT work for control-plane endpoints (creating functions, managing buckets, schema changes). Those require a JWT session token. The MCP server handles this automatically by using both auth modes.
|
|
660
|
-
|
|
661
|
-
### MCP Tools (via .mcp.json)
|
|
662
|
-
|
|
663
|
-
The \`.mcp.json\` file configures an MCP server that gives Claude Code direct access to your VAIF project. Available tools:
|
|
664
|
-
|
|
665
|
-
| Tool | What it does |
|
|
666
|
-
|------|-------------|
|
|
667
|
-
| \`list_tables\`, \`describe_table\` | Inspect database schema |
|
|
668
|
-
| \`get_schema\` | Full schema as JSON |
|
|
669
|
-
| \`create_tables\` | Create or update tables declaratively |
|
|
670
|
-
| \`query_rows\` | Query with filters, JSONB paths, pagination |
|
|
671
|
-
| \`insert_row\`, \`update_row\`, \`delete_row\` | CRUD operations on any table |
|
|
672
|
-
| \`list_functions\`, \`deploy_function\`, \`invoke_function\` | Function management |
|
|
673
|
-
| \`get_function_logs\` | Execution history with status filters |
|
|
674
|
-
| \`set_secret\`, \`list_secrets\`, \`delete_secret\` | Function secrets |
|
|
675
|
-
| \`list_buckets\`, \`list_files\`, \`get_signed_url\` | Storage operations |
|
|
676
|
-
| \`enable_realtime\`, \`realtime_status\` | Realtime subscriptions |
|
|
677
|
-
|
|
678
|
-
> **Note**: MCP tools are only available to the main Claude Code session, not to spawned sub-agents (Task tool). The main session should handle all VAIF backend operations directly.
|
|
679
|
-
`}async function Oe(o){let e=J(),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 n=o.config||"vaif.config.json",i=null;try{i=await a(n);}catch{}let a$1=po(o,i,t);a$1||(console.log(f.yellow(`No project ID specified \u2014 fetching your projects...
|
|
680
|
-
`)),a$1=await uo(t.token),a$1||(console.log(f.gray(`
|
|
681
|
-
Tip: pass --project-id <id> or set projectId in vaif.config.json`)),process.exit(1)));let r=b$1.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 s={tables:[]};try{let d=await fetch(`${N}/schema-engine/introspect/${a$1}`,{headers:{Authorization:`Bearer ${t.token}`}});d.ok?(s=await d.json(),e.succeed(`Fetched schema (${s.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,g=N;try{let d=await fetch(`${N}/projects/${a$1}`,{headers:{Authorization:`Bearer ${t.token}`}});if(d.ok){let l=await d.json(),u=l.project||l;c=u.name||a$1,g=u.apiUrl||N,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||i?.api?.apiKey||"";if(!p){e.start("Generating API key for Claude Code...");try{let d=`claude-code-${Date.now()}`,l=await fetch(`${N}/projects/${a$1}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:d,scopes:["crud","realtime","functions","storage"]})});if(l.ok){let u=await l.json();p=u.apiKey||u.key,e.succeed(`Generated API key: ${d}`);}else 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 d={mcpServers:{"vaif-studio":{command:"npx",args:["@vaiftech/mcp"],env:{VAIF_API_KEY:p,VAIF_PROJECT_ID:a$1,VAIF_API_URL:g,VAIF_AUTH_TOKEN:t.token}}}},l=b$1.join(r,".mcp.json");F.writeFileSync(l,JSON.stringify(d,null,2)+`
|
|
682
|
-
`,"utf-8"),e.succeed(`Written ${f.cyan(".mcp.json")}`);}if(!o.skipClaudeMd){e.start("Writing CLAUDE.md...");let d=wo({projectId:a$1,apiKey:p,apiUrl:g,projectName:c,schema:s}),l=b$1.join(r,"CLAUDE.md");F.writeFileSync(l,d,"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 vo=createRequire(import.meta.url),{version:Ne}=vo("../package.json"),X=f.hex("#00f0ff"),Z=f.hex("#7b61ff"),ee=f.hex("#ff3dff"),oe=f.hex("#00ff9d"),j=f.hex("#555570"),O=f.hex("#00f0ff");function Io(){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(j(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(O(" VAIF Studio CLI")+j(` v${Ne}`)),console.log(j(" Build full-stack apps at lightning speed")),console.log(j(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(""),console.log(f.bold(" Quick Start")),console.log(j(" $ ")+O("vaif login")+j(" Authenticate")),console.log(j(" $ ")+O("vaif init -t react-spa")+j(" Scaffold project")),console.log(j(" $ ")+O("vaif db push")+j(" Push migrations")),console.log(j(" $ ")+O("vaif generate")+j(" Generate types")),console.log(j(" $ ")+O("vaif functions deploy")+j(" Deploy functions")),console.log(""),console.log(f.bold(" Categories")),console.log(j(" auth ")+f.white("login, logout, whoami")),console.log(j(" project ")+f.white("init, templates, info, status")),console.log(j(" schema ")+f.white("pull, push, generate")),console.log(j(" database ")+f.white("db push, db pull, db seed, db reset")),console.log(j(" deploy ")+f.white("functions deploy, functions list")),console.log(j(" security ")+f.white("keys, secrets")),console.log(j(" ai ")+f.white("claude-setup")),console.log(""),console.log(j(" Run ")+O("vaif <command> --help")+j(" for details")),console.log(j(" 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(Te);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(De);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 Le=program.command("functions").alias("fn").description("Manage serverless functions");Le.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);Le.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 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(ke);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(Ae);var H=program.command("secrets").alias("sec").description("Manage function secrets");H.command("set <name> [value]").description("Create or update a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").option("--from-file <path>","Read secret value from a file").action(Pe);H.command("list").alias("ls").description("List all secrets (names only)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Ce);H.command("get <name>").description("Reveal a secret value").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Ee);H.command("delete <name>").description("Delete a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(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||(Io(),process.exit(0));program.parse(process.argv);
|
|
21
|
+
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let n=[],a$1=b$1.readdirSync(c,{withFileTypes:true});for(let d of a$1)if(d.isFile()&&d.name.endsWith(".sql"))n.push(j.join(c,d.name));else if(d.isDirectory()){let g=b$1.readdirSync(j.join(c,d.name),{withFileTypes:true});for(let m of g)m.isFile()&&m.name.endsWith(".sql")&&n.push(j.join(c,d.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 d of n)console.log(f.gray(` - ${j.relative(process.cwd(),d)}`));if(console.log(""),e.dryRun){console.log(f.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let d of n){let g=b$1.readFileSync(d,"utf-8");console.log(f.cyan(`--- ${j.basename(d)} ---`)),console.log(f.gray(g.slice(0,500))),g.length>500&&console.log(f.gray("...")),console.log("");}return}let l=0,u=0;for(let d of n){let g=b$1.readFileSync(d,"utf-8"),m=j.relative(process.cwd(),d);t.start(`Applying ${m}...`);try{let w=await fetch(`${K}/schema-engine/query/${i}`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:g})});if(!w.ok){let D=await w.text();throw new Error(D)}t.succeed(`Applied ${m}`),l++;}catch(w){let D=w instanceof Error?w.message:"Unknown error";t.fail(`Failed ${m}: ${D}`),u++;}}console.log(""),console.log(u===0?f.green(`Successfully applied ${l} migration(s)`):f.yellow(`Applied ${l}, failed ${u} migration(s)`)),console.log("");}async function Se(e){let t=J(),o=b();(!o||!o.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let i=e.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(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 c=j.resolve(e.output||"vaif.schema.json");console.log(""),console.log(f.bold("VAIF Database Pull")),console.log(""),t.start("Pulling schema from remote...");try{let n=await fetch(`${K}/schema-engine/introspect/${i}`,{headers:{Authorization:`Bearer ${o.token}`}});if(!n.ok){let u=await n.text();throw new Error(`Failed to pull schema: ${u}`)}let a=await n.json();b$1.writeFileSync(c,JSON.stringify(a,null,2),"utf-8"),t.succeed(`Schema written to ${j.relative(process.cwd(),c)}`);let l=a.tables?.length??Object.keys(a).length;console.log(f.gray(` ${l} table(s) pulled`)),console.log("");}catch(n){t.fail("Failed to pull schema"),n instanceof Error&&console.log(f.red(`
|
|
22
|
+
Error: ${n.message}`)),process.exit(1);}}async function xe(e){let t=J(),o=b();(!o||!o.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let i=e.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(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(""),e.force||(console.log(f.yellow("Use --force to confirm this action.")),process.exit(1)),t.start("Resetting database...");try{await co(o.token,i),t.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(c){t.fail("Failed to reset database"),c instanceof Error&&console.log(f.red(`
|
|
23
|
+
Error: ${c.message}`)),process.exit(1);}}var Fe=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ae(e,t,o){return e.projectId||t?.projectId||process.env.VAIF_PROJECT_ID||o.projectId||null}async function ke(e){let t=J(),o=b();(!o||!o.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let i=Ae(e,r,o);i||(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 c=e.name||`cli-key-${Date.now()}`;console.log(""),console.log(f.bold("VAIF Generate API Key")),console.log(""),t.start("Generating API key...");try{let n=await fetch(`${Fe}/projects/${i}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:c})});if(!n.ok){let l=await n.text();throw new Error(`Failed to generate key: ${l}`)}let a=await n.json();t.succeed("API key generated"),console.log(""),console.log(f.green(` Name: ${a.name}`)),console.log(f.green(` Key: ${a.key}`)),console.log(""),console.log(f.yellow.bold(" Save this key now - it will not be shown again!")),console.log("");}catch(n){t.fail("Failed to generate API key"),n instanceof Error&&console.log(f.red(`
|
|
24
|
+
Error: ${n.message}`)),process.exit(1);}}async function Ce(e){let t=J(),o=b();(!o||!o.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let i=Ae(e,r,o);i||(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(""),t.start("Fetching API keys...");try{let c=await fetch(`${Fe}/projects/${i}/api-keys`,{headers:{Authorization:`Bearer ${o.token}`}});if(!c.ok){let d=await c.text();throw new Error(`Failed to list keys: ${d}`)}let n=await c.json(),a=n.keys||n;if(t.stop(),!Array.isArray(a)||a.length===0){console.log(f.yellow("No API keys found")),console.log(f.gray(`
|
|
25
|
+
Generate one with: vaif keys generate`));return}let l=Math.max(8,...a.map(d=>(d.name||"").length)),u=` ${"Name".padEnd(l)} ${"Key".padEnd(24)} Created`;console.log(f.gray(u)),console.log(f.gray(" "+"-".repeat(u.length-2)));for(let d of a){let g=(d.name||"unnamed").padEnd(l),m=d.maskedKey||d.prefix||`${(d.key||"").slice(0,12)}...`,w=d.createdAt?new Date(d.createdAt).toLocaleDateString():"N/A";console.log(` ${g} ${m.padEnd(24)} ${w}`);}console.log(""),console.log(f.gray(` ${a.length} key(s) total`)),console.log("");}catch(c){t.fail("Failed to list API keys"),c instanceof Error&&console.log(f.red(`
|
|
26
|
+
Error: ${c.message}`)),process.exit(1);}}var V=process.env.VAIF_API_URL||"https://api.vaif.studio";function lo(e,t,o){return e.projectId||t?.projectId||process.env.VAIF_PROJECT_ID||o.projectId||null}function W(){let e=b();return (!e||!e.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1)),e}async function Y(e){try{return await a(e||"vaif.config.json")}catch{return null}}function G(e,t,o){let s=lo(e,t,o);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 Ee(e,t,o){let s=J(),r=W(),i=await Y(o.config),c=G(o,i,r),n=t;if(o.fromFile)try{n=b$1.readFileSync(o.fromFile,"utf-8");}catch(a){console.log(f.red(`Failed to read file: ${o.fromFile}`)),a instanceof Error&&console.log(f.gray(a.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 a=new URL(`${V}/functions/secrets/project/${c}`);o.envId&&a.searchParams.set("envId",o.envId);let l=await fetch(a.toString(),{headers:{Authorization:`Bearer ${r.token}`}});if(!l.ok)throw new Error(`Failed to check existing secrets: ${await l.text()}`);let d=(await l.json()).find(g=>g.key===e);if(d){s.text=`Updating secret "${e}"...`;let g=await fetch(`${V}/functions/secrets/${d.id}`,{method:"PUT",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!g.ok)throw new Error(`Failed to update secret: ${await g.text()}`);s.succeed(`Updated secret "${e}"`);}else {s.text=`Creating secret "${e}"...`;let g=await fetch(`${V}/functions/secrets`,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:c,envId:o.envId,key:e,value:n})});if(!g.ok)throw new Error(`Failed to create secret: ${await g.text()}`);s.succeed(`Created secret "${e}"`);}console.log("");}catch(a){s.fail("Failed to set secret"),a instanceof Error&&console.log(f.red(`
|
|
27
|
+
Error: ${a.message}`)),process.exit(1);}}async function Re(e){let t=J(),o=W(),s=await Y(e.config),r=G(e,s,o);console.log(""),console.log(f.bold("VAIF Secrets")),console.log(""),t.start("Fetching secrets...");try{let i=new URL(`${V}/functions/secrets/project/${r}`);e.envId&&i.searchParams.set("envId",e.envId);let c=await fetch(i.toString(),{headers:{Authorization:`Bearer ${o.token}`}});if(!c.ok)throw new Error(`Failed to list secrets: ${await c.text()}`);let n=await c.json();if(t.stop(),n.length===0){console.log(f.yellow("No secrets found")),console.log(f.gray(`
|
|
28
|
+
Create one with: vaif secrets set <name> <value>`));return}let a=Math.max(8,...n.map(u=>u.key.length)),l=` ${"Name".padEnd(a)} Created`;console.log(f.gray(l)),console.log(f.gray(" "+"-".repeat(l.length-2)));for(let u of n){let d=u.key.padEnd(a),g=u.createdAt?new Date(u.createdAt).toLocaleDateString():"N/A";console.log(` ${d} ${g}`);}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(i){t.fail("Failed to list secrets"),i instanceof Error&&console.log(f.red(`
|
|
29
|
+
Error: ${i.message}`)),process.exit(1);}}async function De(e,t){let o=J(),s=W(),r=await Y(t.config),i=G(t,r,s);console.log(""),o.start("Fetching secret...");try{let c=new URL(`${V}/functions/secrets/project/${i}`);t.envId&&c.searchParams.set("envId",t.envId);let n=await fetch(c.toString(),{headers:{Authorization:`Bearer ${s.token}`}});if(!n.ok)throw new Error(`Failed to fetch secrets: ${await n.text()}`);let l=(await n.json()).find(g=>g.key===e);l||(o.fail(`Secret "${e}" not found`),process.exit(1));let u=await fetch(`${V}/functions/secrets/${l.id}/value`,{headers:{Authorization:`Bearer ${s.token}`}});if(!u.ok)throw new Error(`Failed to get secret value: ${await u.text()}`);let d=await u.json();o.stop(),console.log(d.value);}catch(c){o.fail("Failed to get secret"),c instanceof Error&&console.log(f.red(`
|
|
30
|
+
Error: ${c.message}`)),process.exit(1);}}async function Ne(e,t){let o=J(),s=W(),r=await Y(t.config),i=G(t,r,s);console.log(""),console.log(f.bold("VAIF Delete Secret")),console.log(""),o.start("Finding secret...");try{let c=new URL(`${V}/functions/secrets/project/${i}`);t.envId&&c.searchParams.set("envId",t.envId);let n=await fetch(c.toString(),{headers:{Authorization:`Bearer ${s.token}`}});if(!n.ok)throw new Error(`Failed to fetch secrets: ${await n.text()}`);let l=(await n.json()).find(d=>d.key===e);l||(o.fail(`Secret "${e}" not found`),process.exit(1)),o.text=`Deleting secret "${e}"...`;let u=await fetch(`${V}/functions/secrets/${l.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${s.token}`}});if(!u.ok)throw new Error(`Failed to delete secret: ${await u.text()}`);o.succeed(`Deleted secret "${e}"`),console.log("");}catch(c){o.fail("Failed to delete secret"),c instanceof Error&&console.log(f.red(`
|
|
31
|
+
Error: ${c.message}`)),process.exit(1);}}var Te=process.env.VAIF_API_URL||"https://api.vaif.studio";function fo(e){try{let t=new URL(e);return t.password&&(t.password="****"),t.toString()}catch{return e.replace(/:[^@/]+@/,":****@")}}async function Oe(e){let t=J(),o=b();(!o||!o.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let i=e.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(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)),t.start("Fetching project info...");try{let c=await fetch(`${Te}/projects/${i}`,{headers:{Authorization:`Bearer ${o.token}`}});if(!c.ok){let u=await c.text();throw new Error(`Failed to fetch project: ${u}`)}let n=await c.json();t.stop(),console.log(""),console.log(f.bold("VAIF Project Info")),console.log("");let a=16,l=(u,d)=>{console.log(` ${f.gray(u.padEnd(a))} ${d}`);};l("Name:",f.white(n.name||"N/A")),l("Project ID:",f.white(i)),l("Region:",f.white(n.region||"us-east-1")),l("Plan:",f.white(n.plan||n.tier||"free")),l("Created:",f.white(n.createdAt?new Date(n.createdAt).toLocaleDateString():"N/A")),console.log(""),l("API URL:",f.cyan(n.apiUrl||`${Te}/v1`)),l("WS URL:",f.cyan(n.wsUrl||n.realtimeUrl||"N/A")),l("DB URL:",f.cyan(n.databaseUrl?fo(n.databaseUrl):"N/A")),l("Storage URL:",f.cyan(n.storageUrl||"N/A")),console.log("");}catch(c){t.fail("Failed to fetch project info"),c instanceof Error&&console.log(f.red(`
|
|
32
|
+
Error: ${c.message}`)),process.exit(1);}}var po=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Ve(e){let t=J(),o=b();(!o||!o.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let i=e.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(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)),t.start("Fetching project status...");try{let c=await fetch(`${po}/projects/${i}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${o.token}`}});if(!c.ok){let w=await c.text();throw new Error(`Failed to fetch project status: ${w}`)}let n=await c.json();t.stop(),console.log(""),console.log(f.bold("VAIF Project Status")),console.log("");let a=22,l=(w,D)=>{console.log(` ${f.gray(w.padEnd(a))} ${D}`);};l("Project:",f.white(n.name||i)),l("Plan:",f.white(n.plan||n.tier||"free")),console.log(""),console.log(f.gray(" --- Resources ---")),console.log("");let u=n.tableCount??n.tables?.length??"N/A",d=n.functionCount??n.functions?.length??"N/A",g=n.bucketCount??n.storage?.buckets?.length??"N/A",m=n.activeConnections??n.connections??"N/A";l("Tables:",f.white(String(u))),l("Functions:",f.white(String(d))),l("Storage Buckets:",f.white(String(g))),l("Active Connections:",f.white(String(m))),n.usage&&(console.log(""),console.log(f.gray(" --- Usage ---")),console.log(""),n.usage.dbSize&&l("Database Size:",f.white(n.usage.dbSize)),n.usage.storageSize&&l("Storage Size:",f.white(n.usage.storageSize)),n.usage.bandwidth&&l("Bandwidth:",f.white(n.usage.bandwidth)),n.usage.functionInvocations!=null&&l("Function Invocations:",f.white(String(n.usage.functionInvocations)))),console.log("");}catch(c){t.fail("Failed to fetch project status"),c instanceof Error&&console.log(f.red(`
|
|
33
|
+
Error: ${c.message}`)),process.exit(1);}}function mo(e){let t=[j.join(e,".env.local"),j.join(e,".env")],o={};for(let r of t)if(b$1.existsSync(r)){let i=b$1.readFileSync(r,"utf-8");for(let c of i.split(`
|
|
34
|
+
`)){let n=c.match(/^([^#=]+)=(.*)$/);if(!n)continue;let[,a,l]=n,u=a.trim(),d=l.trim().replace(/^["']|["']$/g,"");if(u==="SUPABASE_URL"||u==="NEXT_PUBLIC_SUPABASE_URL"){o.api={...o.api,url:d};let g=d.match(/https:\/\/([^.]+)\.supabase\./);g&&(o.projectId=g[1]);}(u==="SUPABASE_ANON_KEY"||u==="NEXT_PUBLIC_SUPABASE_ANON_KEY")&&(o.api={...o.api,anonKey:d}),u==="SUPABASE_SERVICE_ROLE_KEY"&&(o.api={...o.api,serviceKey:d});}break}let s=j.join(e,"supabase","config.toml");if(b$1.existsSync(s)){let i=b$1.readFileSync(s,"utf-8").match(/project_id\s*=\s*"([^"]+)"/);i&&(o.projectId=i[1]);}return o.projectId||o.api?.url?o:null}function ho(e){let t=j.join(e,"supabase","migrations"),o=new Map;if(!b$1.existsSync(t))return [];let s=b$1.readdirSync(t).filter(r=>r.endsWith(".sql")).sort();for(let r of s){let i=b$1.readFileSync(j.join(t,r),"utf-8");yo(i,o),bo(i,o);}return Array.from(o.values())}function yo(e,t){let o=/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:public\.)?(\w+)\s*\(([\s\S]*?)\);/gi,s;for(;(s=o.exec(e))!==null;){let i=s[1],c=s[2];if(["schema_migrations","_prisma_migrations","supabase_migrations"].includes(i))continue;let n=[],a=c.split(`,
|
|
35
|
+
`).map(l=>l.trim()).filter(Boolean);for(let l of a){if(/^\s*(PRIMARY\s+KEY|FOREIGN\s+KEY|UNIQUE|CHECK|CONSTRAINT)/i.test(l))continue;let u=l.match(/^(\w+)\s+(\w+(?:\([^)]*\))?(?:\[\])?)\s*(.*)/i);if(!u)continue;let[,d,g,m]=u,w=/PRIMARY\s+KEY/i.test(m),D=/UNIQUE/i.test(m),L=!/NOT\s+NULL/i.test(m)&&!w,_=m.match(/DEFAULT\s+(.+?)(?:\s+|$)/i),B=m.match(/REFERENCES\s+(?:public\.)?(\w+)\s*\((\w+)\)(?:\s+ON\s+DELETE\s+(\w+))?/i);n.push({name:d,type:wo(g),nullable:L,isPrimaryKey:w,isUnique:D,defaultValue:_?.[1],references:B?{table:B[1],column:B[2],onDelete:B[3]?.toUpperCase()}:void 0});}n.length>0&&t.set(i,{name:i,columns:n,indexes:[],rlsPolicies:[]});}let r=/CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?(\w+)\s+ON\s+(?:public\.)?(\w+)\s*\(([^)]+)\)/gi;for(;(s=r.exec(e))!==null;){let[,i,c,n]=s,a=t.get(c);a&&(a.indexes=a.indexes||[],a.indexes.push({name:i,columns:n.split(",").map(l=>l.trim()),unique:/UNIQUE/i.test(s[0])}));}}function bo(e,t){let o=/CREATE\s+POLICY\s+"([^"]+)"\s+ON\s+(?:public\.)?(\w+)\s+(?:FOR\s+(\w+)\s+)?(?:USING\s+\((.+?)\)|WITH\s+CHECK\s+\((.+?)\))/gi,s;for(;(s=o.exec(e))!==null;){let[,r,i,c,n,a]=s,l=t.get(i);l&&(l.rlsPolicies=l.rlsPolicies||[],l.rlsPolicies.push({name:r,command:c||"ALL",definition:(n||a||"").replace(/auth\.uid\(\)/g,"vaif.auth_uid()")}));}}function wo(e){let t=e.toLowerCase();return t.includes("serial")?"integer":t.includes("bigserial")?"bigint":e}function jo(e){let t=j.join(e,"supabase","config.toml"),o=[];if(b$1.existsSync(t)){let s=b$1.readFileSync(t,"utf-8"),r=/\[storage\.buckets\.(\w+)\]/g,i;for(;(i=r.exec(s))!==null;){let c=i[1],n=s.slice(i.index),a=/public\s*=\s*true/i.test(n.split(/\[/)[0]);o.push({name:c,public:a});}}return o}function vo(e){let t=j.join(e,"supabase","functions"),o=[];if(!b$1.existsSync(t))return [];let s=b$1.readdirSync(t,{withFileTypes:true});for(let r of s){if(!r.isDirectory()||r.name.startsWith("_"))continue;let i=j.join(t,r.name,"index.ts"),c=b$1.existsSync(i);o.push({name:r.name.replace(/-/g,"_"),runtime:"nodejs20",entrypoint:"index.ts",sourceHint:c?`Source found at supabase/functions/${r.name}/index.ts \u2014 convert Deno imports to Node.js`:void 0});}return o}function Io(e){let t=[],o=ho(e);o.length===0&&t.push("No migration files found in supabase/migrations/. Add your schema SQL files or export with: supabase db dump --schema public > supabase/migrations/schema.sql");let s=jo(e),r=vo(e);r.length>0&&t.push("Supabase Edge Functions use Deno runtime. VAIF functions use Node.js by default. You will need to convert Deno-specific imports (e.g., std/http/server) to Node.js equivalents.");let i=[],c=j.join(e,"supabase","config.toml");if(b$1.existsSync(c)){let n=b$1.readFileSync(c,"utf-8");n.includes("[auth.external.google]")&&i.push("google"),n.includes("[auth.external.github]")&&i.push("github"),n.includes("[auth.external.apple]")&&i.push("apple"),n.includes("[auth.external.azure]")&&i.push("microsoft"),(n.includes("[auth.sms]")||n.includes("[auth.external.phone]"))&&i.push("phone");}return {source:"supabase",tables:o,buckets:s,functions:r,authProviders:i,warnings:t}}function Ue(e){let t=j.join(e,"firebase.json"),o={};if(b$1.existsSync(t))try{let i=JSON.parse(b$1.readFileSync(t,"utf-8"));i.projectId&&(o.projectId=i.projectId);}catch{}let s=j.join(e,".firebaserc");if(b$1.existsSync(s))try{let c=JSON.parse(b$1.readFileSync(s,"utf-8")).projects?.default;c&&(o.projectId=c);}catch{}let r=j.join(e,".env");if(b$1.existsSync(r)){let i=b$1.readFileSync(r,"utf-8");for(let c of i.split(`
|
|
36
|
+
`)){let n=c.match(/^([^#=]+)=(.*)$/);if(!n)continue;let[,a,l]=n;a.trim().includes("STORAGE_BUCKET")&&(o.storageBucket=l.trim().replace(/^["']|["']$/g,""));}}return o.projectId?o:null}function $o(e){let t=j.join(e,"firestore.rules"),o=[];if(!b$1.existsSync(t))return [];let s=b$1.readFileSync(t,"utf-8"),r=/match\s+\/([a-zA-Z_]\w*)\s*\/\{(\w+)\}/g,i,c=new Set;for(;(i=r.exec(s))!==null;){let n=i[1];c.has(n)||(c.add(n),!n.startsWith("_")&&o.push({name:n,columns:[{name:"id",type:"uuid",nullable:false,isPrimaryKey:true,defaultValue:"gen_random_uuid()"},{name:"created_at",type:"timestamptz",nullable:false,defaultValue:"now()"},{name:"updated_at",type:"timestamptz",nullable:false,defaultValue:"now()"},{name:"data",type:"jsonb",nullable:true,defaultValue:"'{}'"}],indexes:[],rlsPolicies:[]}));}return o}function So(e){let t=j.join(e,"functions"),o=[];if(!b$1.existsSync(t))return [];let r=[j.join(t,"src","index.ts"),j.join(t,"index.ts"),j.join(t,"src","index.js"),j.join(t,"index.js")].find(a=>b$1.existsSync(a));if(!r)return [];let i=b$1.readFileSync(r,"utf-8"),c=/(?:exports\.(\w+)\s*=|export\s+(?:const|function)\s+(\w+))/g,n;for(;(n=c.exec(i))!==null;){let a=(n[1]||n[2]).replace(/-/g,"_");o.push({name:a,runtime:"nodejs20",entrypoint:"index.ts",sourceHint:`Exported from ${j.relative(e,r)} \u2014 needs manual conversion from Firebase Functions SDK to VAIF handler format`});}return o}function xo(e,t){let o=[];t.storageBucket&&o.push({name:"default",public:false});let s=j.join(e,"storage.rules");if(b$1.existsSync(s)){let r=b$1.readFileSync(s,"utf-8"),i=/match\s+\/([a-zA-Z]\w*)\s*\/\{/g,c;for(;(c=i.exec(r))!==null;){let n=c[1];n!=="b"&&!o.find(a=>a.name===n)&&o.push({name:n,public:false});}}return o}function Po(e){let t=[],o=Ue(e)||{},s=$o(e);s.length===0?t.push("No firestore.rules found. Add your Firestore rules file or manually specify your collection structure."):t.push("Firestore collections were detected from firestore.rules. Each collection is mapped to a table with a JSONB 'data' column. You should replace the 'data' column with specific typed columns matching your document structure. See docs/migration/from-firebase.md for schema design patterns.");let r=So(e);r.length>0&&t.push("Firebase Cloud Functions use the Firebase Admin SDK and trigger patterns (auth.user().onCreate, firestore.document().onWrite). VAIF functions use a simpler handler(req, ctx) pattern. Each function needs manual conversion.");let i=xo(e,o),c=["email"],n=j.join(e,"firebase.json");if(b$1.existsSync(n))try{let a=JSON.parse(b$1.readFileSync(n,"utf-8"));a.auth?.providers&&c.push(...a.auth.providers.filter(l=>l!=="email"));}catch{}return {source:"firebase",tables:s,buckets:i,functions:r,authProviders:c,warnings:t}}function Fo(e){if(console.log(""),console.log(f.bold.cyan(` Migration Plan (from ${e.source})`)),console.log(f.gray(" \u2500".repeat(30))),console.log(""),e.tables.length>0){console.log(f.bold(` \u{1F4E6} Tables (${e.tables.length})`));for(let t of e.tables){let o=t.columns.length,s=t.columns.filter(c=>c.references).length,r=t.rlsPolicies?.length||0,i=[`${o} columns`];s>0&&i.push(`${s} foreign keys`),r>0&&i.push(`${r} RLS policies`),console.log(f.white(` ${t.name}`)+f.gray(` \u2014 ${i.join(", ")}`));}console.log("");}if(e.buckets.length>0){console.log(f.bold(` \u{1F5C4}\uFE0F Storage Buckets (${e.buckets.length})`));for(let t of e.buckets)console.log(f.white(` ${t.name}`)+f.gray(` \u2014 ${t.public?"public":"private"}`));console.log("");}if(e.functions.length>0){console.log(f.bold(` \u26A1 Functions (${e.functions.length})`));for(let t of e.functions)console.log(f.white(` ${t.name}`)+f.gray(` \u2014 ${t.runtime}`)),t.sourceHint&&console.log(f.yellow(` \u26A0 ${t.sourceHint}`));console.log("");}if(e.authProviders.length>0&&(console.log(f.bold(` \u{1F510} Auth Providers (${e.authProviders.length})`)),console.log(f.white(` ${e.authProviders.join(", ")}`)),console.log("")),e.warnings.length>0){console.log(f.bold.yellow(" \u26A0 Warnings"));for(let t of e.warnings)console.log(f.yellow(` \u2022 ${t}`));console.log("");}}function _e(e,t){let o=`# VAIF Migration Plan
|
|
37
|
+
|
|
38
|
+
`;if(o+=`**Source:** ${e.source}
|
|
39
|
+
`,o+=`**Generated:** ${new Date().toISOString()}
|
|
40
|
+
|
|
41
|
+
`,e.tables.length>0){o+=`## Tables (${e.tables.length})
|
|
42
|
+
|
|
43
|
+
`;for(let r of e.tables){o+=`### ${r.name}
|
|
44
|
+
|
|
45
|
+
`,o+=`| Column | Type | Nullable | Default | Constraints |
|
|
46
|
+
`,o+=`|--------|------|----------|---------|-------------|
|
|
47
|
+
`;for(let i of r.columns){let c=[];i.isPrimaryKey&&c.push("PK"),i.isUnique&&c.push("UNIQUE"),i.references&&c.push(`FK \u2192 ${i.references.table}.${i.references.column}`),o+=`| ${i.name} | ${i.type} | ${i.nullable?"yes":"no"} | ${i.defaultValue||"-"} | ${c.join(", ")||"-"} |
|
|
48
|
+
`;}if(o+=`
|
|
49
|
+
`,r.rlsPolicies&&r.rlsPolicies.length>0){o+=`**RLS Policies:**
|
|
50
|
+
`;for(let i of r.rlsPolicies)o+=`- \`${i.name}\` (${i.command}): \`${i.definition}\`
|
|
51
|
+
`;o+=`
|
|
52
|
+
`;}}}if(e.buckets.length>0){o+=`## Storage Buckets (${e.buckets.length})
|
|
53
|
+
|
|
54
|
+
`;for(let r of e.buckets)o+=`- **${r.name}** \u2014 ${r.public?"public":"private"}
|
|
55
|
+
`;o+=`
|
|
56
|
+
`;}if(e.functions.length>0){o+=`## Functions (${e.functions.length})
|
|
57
|
+
|
|
58
|
+
`;for(let r of e.functions)o+=`- **${r.name}** \u2014 ${r.runtime}
|
|
59
|
+
`,r.sourceHint&&(o+=` - \u26A0 ${r.sourceHint}
|
|
60
|
+
`);o+=`
|
|
61
|
+
`;}if(e.authProviders.length>0&&(o+=`## Auth Providers
|
|
62
|
+
|
|
63
|
+
`,o+=e.authProviders.map(r=>`- ${r}`).join(`
|
|
64
|
+
`)+`
|
|
65
|
+
|
|
66
|
+
`),e.warnings.length>0){o+=`## Warnings
|
|
67
|
+
|
|
68
|
+
`;for(let r of e.warnings)o+=`- \u26A0 ${r}
|
|
69
|
+
`;o+=`
|
|
70
|
+
`;}o+=`## Next Steps
|
|
71
|
+
|
|
72
|
+
`,o+=`1. Review the tables above and adjust column types as needed
|
|
73
|
+
`,o+=`2. Run \`vaif migrate --from ${e.source}\` without \`--dry-run\` to execute
|
|
74
|
+
`,o+=`3. Verify tables were created in the VAIF dashboard
|
|
75
|
+
`,o+=`4. Migrate your data using the export/import scripts in docs/migration/from-${e.source}.md
|
|
76
|
+
`,o+="5. Update your application code to use `@vaiftech/client`\n";let s=j.join(t,"vaif-migration-plan.md");return b$1.writeFileSync(s,o,"utf-8"),s}var ee=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Ao(e,t,o){if(e.tables.length>0){let s=J(`Creating ${e.tables.length} tables...`).start();try{let r=e.tables.map(c=>({name:c.name,columns:c.columns.map(n=>({name:n.name,type:n.type,nullable:n.nullable,primaryKey:n.isPrimaryKey||!1,unique:n.isUnique||!1,default:n.defaultValue,references:n.references?{table:n.references.table,column:n.references.column,onDelete:n.references.onDelete||"SET NULL"}:void 0})),indexes:c.indexes})),i=await fetch(`${ee}/schema-engine/${t}/tables`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({tables:r})});if(i.ok)s.succeed(`Created ${e.tables.length} tables`);else {let c=await i.text();s.fail(`Failed to create tables: ${c}`);}}catch(r){s.fail(`Failed to create tables: ${r instanceof Error?r.message:String(r)}`);}}for(let s of e.buckets){let r=J(`Creating bucket: ${s.name}...`).start();try{let i=await fetch(`${ee}/storage/buckets`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","x-project-id":t},body:JSON.stringify({name:s.name,public:s.public,fileSizeLimit:s.fileSizeLimit,allowedMimeTypes:s.allowedMimeTypes})});if(i.ok)r.succeed(`Created bucket: ${s.name}`);else {let c=await i.text();r.warn(`Bucket ${s.name}: ${c}`);}}catch(i){r.warn(`Bucket ${s.name}: ${i instanceof Error?i.message:String(i)}`);}}for(let s of e.functions){let r=J(`Creating function: ${s.name}...`).start();try{let i=await fetch(`${ee}/functions`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:t,name:s.name,runtime:s.runtime,entrypoint:s.entrypoint})});if(i.ok)r.succeed(`Created function stub: ${s.name}`);else {let c=await i.text();r.warn(`Function ${s.name}: ${c}`);}}catch(i){r.warn(`Function ${s.name}: ${i instanceof Error?i.message:String(i)}`);}}}async function Le(e){let t=e.outputDir?j.resolve(e.outputDir):process.cwd(),o=e.from;console.log(""),console.log(f.bold(` Analyzing ${o} project...`));let s;if(o==="supabase"?(mo(t)||(console.log(f.yellow(`
|
|
77
|
+
No Supabase configuration found.`)),console.log(f.gray(" Expected: .env with SUPABASE_URL, or supabase/config.toml")),console.log(f.gray(` Make sure you're in a Supabase project directory.
|
|
78
|
+
`)),process.exit(1)),s=Io(t)):o==="firebase"?(Ue(t)||(console.log(f.yellow(`
|
|
79
|
+
No Firebase configuration found.`)),console.log(f.gray(" Expected: firebase.json or .firebaserc in project root")),console.log(f.gray(` Make sure you're in a Firebase project directory.
|
|
80
|
+
`)),process.exit(1)),s=Po(t)):(console.log(f.red(`
|
|
81
|
+
Unknown source: "${o}"`)),console.log(f.gray(` Supported: supabase, firebase
|
|
82
|
+
`)),process.exit(1)),Fo(s),e.dryRun){let n=_e(s,t);console.log(f.green(` \u2713 Migration plan written to ${f.cyan(j.relative(process.cwd(),n))}`)),console.log(f.gray(` Review the plan, then run without --dry-run to execute.
|
|
83
|
+
`));return}let r=b();(!r||!r.token)&&(console.log(f.red(" Not logged in. Run `vaif login` first.")),process.exit(1));let i=e.projectId;if(!i)try{i=(await a(e.config||"vaif.config.json")).projectId;}catch{}i||(i=process.env.VAIF_PROJECT_ID),i||(console.log(f.red(" No VAIF project ID specified.")),console.log(f.gray(` Pass --project-id <id>, set in vaif.config.json, or set VAIF_PROJECT_ID env var.
|
|
84
|
+
`)),process.exit(1)),console.log(f.bold(` Executing migration to VAIF project: ${i}
|
|
85
|
+
`)),await Ao(s,i,r.token);let c=_e(s,t);console.log(""),console.log(f.green.bold(" \u2713 Migration complete!")),console.log(f.gray(` Plan saved to ${j.relative(process.cwd(),c)}`)),console.log(""),console.log(f.bold(" Next steps:")),console.log(f.gray(" 1. Verify tables in the VAIF dashboard")),console.log(f.gray(" 2. Migrate data using scripts in docs/migration/from-"+o+".md")),console.log(f.gray(" 3. Update your app code to use @vaiftech/client")),console.log(f.gray(" 4. Run `vaif claude-setup` to configure AI tools for your project\n"));}var Co=createRequire(import.meta.url),{version:Me}=Co("../package.json"),oe=f.hex("#00f0ff"),te=f.hex("#7b61ff"),ne=f.hex("#ff3dff"),se=f.hex("#00ff9d"),v=f.hex("#555570"),U=f.hex("#00f0ff");function Eo(){console.log(""),console.log(oe(" \u2566 \u2566")+te("\u2554\u2550\u2557\u2566")+ne("\u2554\u2550\u2557 ")+se("\u2554\u2550\u2557\u2566 \u2566")),console.log(oe(" \u255A\u2557\u2554\u255D")+te("\u2560\u2550\u2563\u2551")+ne("\u2560\u2563 ")+se("\u2551 \u2551 \u2551")),console.log(oe(" \u255A\u255D ")+te("\u2569 \u2569\u2569")+ne("\u255A ")+se("\u255A\u2550\u255D\u2569\u2550\u255D\u2569")),console.log(""),console.log(v(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(U(" VAIF Studio CLI")+v(` v${Me}`)),console.log(v(" Build full-stack apps at lightning speed")),console.log(v(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(""),console.log(f.bold(" Quick Start")),console.log(v(" $ ")+U("vaif login")+v(" Authenticate")),console.log(v(" $ ")+U("vaif init -t react-spa")+v(" Scaffold project")),console.log(v(" $ ")+U("vaif db push")+v(" Push migrations")),console.log(v(" $ ")+U("vaif generate")+v(" Generate types")),console.log(v(" $ ")+U("vaif functions deploy")+v(" Deploy functions")),console.log(""),console.log(f.bold(" Categories")),console.log(v(" auth ")+f.white("login, logout, whoami")),console.log(v(" project ")+f.white("init, templates, info, status")),console.log(v(" schema ")+f.white("pull, push, generate")),console.log(v(" database ")+f.white("db push, db pull, db seed, db reset")),console.log(v(" deploy ")+f.white("functions deploy, functions list")),console.log(v(" security ")+f.white("keys, secrets")),console.log(v(" migrate ")+f.white("migrate --from supabase|firebase")),console.log(v(" ai ")+f.white("claude-setup, init --claude")),console.log(""),console.log(v(" Run ")+U("vaif <command> --help")+v(" for details")),console.log(v(" Docs: ")+f.underline("https://docs.vaif.studio")),console.log("");}program.name("vaif").description("VAIF CLI - Type generation and development tools").version(Me);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)").option("--claude [type]","Generate CLAUDE.md for AI assistants (types: base, saas, mobile, ecommerce). Omit type to auto-detect or use live project data.").action(i);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(Oe);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(Ve);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(de);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(me);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 Be=program.command("functions").alias("fn").description("Manage serverless functions");Be.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(we);Be.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(je);var H=program.command("db").description("Database management commands");H.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($e);H.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(Se);H.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(Ie);H.command("reset").description("Reset database (drop all tables and data)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --force","Confirm reset (required)").action(xe);var ze=program.command("keys").description("Manage API keys");ze.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(ke);ze.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(Ce);var Q=program.command("secrets").alias("sec").description("Manage function secrets");Q.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(Ee);Q.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(Re);Q.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(De);Q.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(Ne);program.command("migrate").description("Migrate from Supabase or Firebase to VAIF Studio").requiredOption("--from <platform>","Source platform: supabase or firebase").option("--dry-run","Show migration plan without executing").option("-c, --config <path>","VAIF config file path","vaif.config.json").option("-p, --project-id <id>","Target VAIF project ID").option("-o, --output-dir <dir>","Source project directory to analyze",".").action(Le);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(h);process.argv.slice(2).length||(Eo(),process.exit(0));program.parse(process.argv);
|