@vaiftech/cli 1.7.5 → 1.8.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 +29 -1
- package/dist/{chunk-WYTLXCHQ.js → chunk-T7GOLIY4.js} +52 -35
- package/dist/cli.cjs +271 -61
- package/dist/cli.js +225 -32
- package/dist/index.cjs +55 -38
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/cli.cjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';require('dotenv/config');var commander=require('commander'),f=require('chalk'),
|
|
3
|
-
Could not connect to VAIF API. Please try again later.`)),process.exit(1));let
|
|
4
|
-
Could not connect to VAIF API.`)),console.log(f__default.default.gray("Check your internet connection or try: vaif login --email")),process.exit(1);}e.stop(),console.log(f__default.default.cyan(" Opening browser for authentication...")),console.log(""),console.log(f__default.default.gray(" If the browser doesn't open, visit this URL:")),console.log(f__default.default.white(` ${n}`)),console.log(""),
|
|
5
|
-
The authentication session expired. Please try again.`)),process.exit(1));continue}let
|
|
6
|
-
Timed out waiting for browser authentication.`)),console.log(f__default.default.gray("Try again or use: vaif login --email")),process.exit(1);}async function
|
|
7
|
-
No email provided. Login cancelled.`)),process.exit(1));let o=await
|
|
8
|
-
No password provided. Login cancelled.`)),process.exit(1));let n=
|
|
9
|
-
${
|
|
10
|
-
Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function
|
|
11
|
-
Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Authenticated"),console.log(""),console.log(f__default.default.green(` Email: ${n||t.email||"Unknown"}`)),t.projectId&&console.log(f__default.default.green(` Project: ${t.projectId}`)),console.log("");}var
|
|
2
|
+
'use strict';require('dotenv/config');var commander=require('commander'),f=require('chalk'),U=require('fs'),S=require('path'),xt=require('pg'),Q=require('ora'),Pt=require('prettier'),mt=require('dotenv'),ht=require('os'),child_process=require('child_process'),Ee=require('readline');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var f__default=/*#__PURE__*/_interopDefault(f);var U__default=/*#__PURE__*/_interopDefault(U);var S__default=/*#__PURE__*/_interopDefault(S);var xt__default=/*#__PURE__*/_interopDefault(xt);var Q__default=/*#__PURE__*/_interopDefault(Q);var Pt__default=/*#__PURE__*/_interopDefault(Pt);var mt__default=/*#__PURE__*/_interopDefault(mt);var ht__default=/*#__PURE__*/_interopDefault(ht);var Ee__default=/*#__PURE__*/_interopDefault(Ee);mt__default.default.config();async function A(t){let e=S__default.default.resolve(t);if(!U__default.default.existsSync(e))return null;try{let o=U__default.default.readFileSync(e,"utf-8"),n=JSON.parse(o);return n.database?.url&&(n.database.url=Se(n.database.url)),n.api?.apiKey&&(n.api.apiKey=Se(n.api.apiKey)),n}catch{throw new Error(`Failed to parse config file: ${t}`)}}function Se(t){return t.replace(/\$\{([^}]+)\}/g,(e,o)=>process.env[o]||e)}var se=S__default.default.join(ht__default.default.homedir(),".vaif"),K=S__default.default.join(se,"auth.json"),H=process.env.VAIF_API_URL||"https://api.vaif.studio";function vt(){U__default.default.existsSync(se)||U__default.default.mkdirSync(se,{recursive:true});}function xe(t){vt(),U__default.default.writeFileSync(K,JSON.stringify(t,null,2),"utf-8"),U__default.default.chmodSync(K,384);}function I(){if(!U__default.default.existsSync(K))return null;try{let t=U__default.default.readFileSync(K,"utf-8");return JSON.parse(t)}catch{return null}}function bt(t){let e=Ee__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}function It(t){return new Promise(e=>{let o=Ee__default.default.createInterface({input:process.stdin,output:process.stdout});process.stdin;let r=process.stdout.write.bind(process.stdout),i=false;process.stdout.write=((...s)=>i?true:r(...s)),o.question(t,s=>{i=false,process.stdout.write=r,console.log(""),o.close(),e(s);}),i=true;})}function At(t){let e=process.platform,o;e==="darwin"?o=`open "${t}"`:e==="win32"?o=`start "" "${t}"`:o=`xdg-open "${t}"`,child_process.exec(o,n=>{});}function wt(t){return new Promise(e=>setTimeout(e,t))}async function St(t){try{let e=await fetch(`${H}/auth/me`,{headers:{Authorization:`Bearer ${t}`}});if(e.ok){let o=await e.json();return {valid:!0,email:o.user?.email||o.email}}return {valid:!1}}catch{return {valid:false}}}async function _t(t){let e=Q__default.default();e.start("Setting up authentication...");let o,n;try{let a=await fetch(`${H}/auth/cli/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});a.ok||(e.fail("Failed to initiate authentication"),console.log(f__default.default.red(`
|
|
3
|
+
Could not connect to VAIF API. Please try again later.`)),process.exit(1));let l=await a.json();o=l.code,n=l.url;}catch{e.fail("Failed to connect to VAIF API"),console.log(f__default.default.red(`
|
|
4
|
+
Could not connect to VAIF API.`)),console.log(f__default.default.gray("Check your internet connection or try: vaif login --email")),process.exit(1);}e.stop(),console.log(f__default.default.cyan(" Opening browser for authentication...")),console.log(""),console.log(f__default.default.gray(" If the browser doesn't open, visit this URL:")),console.log(f__default.default.white(` ${n}`)),console.log(""),At(n),e.start("Waiting for browser authentication...");let r=12e4,i=2e3,s=Date.now();for(;Date.now()-s<r;){await wt(i);try{let a=await fetch(`${H}/auth/cli/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:o})});if(!a.ok){let d=await a.json();(d.error==="ExpiredCode"||d.error==="InvalidCode")&&(e.fail("Authentication expired"),console.log(f__default.default.red(`
|
|
5
|
+
The authentication session expired. Please try again.`)),process.exit(1));continue}let l=await a.json();if(l.ok&&l.accessToken){let d={token:l.accessToken,email:l.user?.email,projectId:t,expiresAt:new Date(Date.now()+l.expiresIn*1e3).toISOString()};xe(d),e.succeed("Logged in successfully"),console.log(""),l.user?.email&&console.log(f__default.default.green(` Authenticated as: ${l.user.email}`)),console.log(f__default.default.gray(` Config saved to: ${K}`)),console.log("");return}}catch{}}e.fail("Authentication timed out"),console.log(f__default.default.red(`
|
|
6
|
+
Timed out waiting for browser authentication.`)),console.log(f__default.default.gray("Try again or use: vaif login --email")),process.exit(1);}async function Et(t){console.log(""),console.log(f__default.default.bold("VAIF CLI Login")),console.log(f__default.default.gray("Enter your VAIF account credentials")),console.log("");let e=await bt(f__default.default.cyan(" Email: "));(!e||e.trim()==="")&&(console.log(f__default.default.red(`
|
|
7
|
+
No email provided. Login cancelled.`)),process.exit(1));let o=await It(f__default.default.cyan(" Password: "));(!o||o.trim()==="")&&(console.log(f__default.default.red(`
|
|
8
|
+
No password provided. Login cancelled.`)),process.exit(1));let n=Q__default.default("Authenticating...").start();try{let r=await fetch(`${H}/auth/cli/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e.trim(),password:o})}),i=await r.json();(!r.ok||!i.ok)&&(n.fail("Login failed"),console.log(f__default.default.red(`
|
|
9
|
+
${i.message||"Invalid email or password."}`)),process.exit(1));let s={token:i.accessToken,email:i.user?.email,projectId:t,expiresAt:new Date(Date.now()+i.expiresIn*1e3).toISOString()};xe(s),n.succeed("Logged in successfully"),console.log(""),i.user?.email&&console.log(f__default.default.green(` Authenticated as: ${i.user.email}`)),console.log(f__default.default.gray(` Config saved to: ${K}`)),console.log("");}catch{n.fail("Failed to connect to VAIF API"),console.log(f__default.default.red(`
|
|
10
|
+
Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function Te(t){console.log(""),console.log(f__default.default.bold("Welcome to VAIF CLI")),console.log(f__default.default.gray("Authenticate to access your VAIF projects")),console.log(""),t.email?await Et(t.projectId):await _t(t.projectId),console.log(f__default.default.gray("You can now use VAIF CLI commands like:")),console.log(f__default.default.gray(" vaif pull - Pull remote schema")),console.log(f__default.default.gray(" vaif push - Push schema changes")),console.log(f__default.default.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function Pe(){U__default.default.existsSync(K)?(U__default.default.unlinkSync(K),console.log(f__default.default.green("Logged out successfully"))):console.log(f__default.default.yellow("Not currently logged in"));}async function Fe(){let t=I();(!t||!t.token)&&(console.log(f__default.default.yellow("Not logged in")),console.log(f__default.default.gray("Run `vaif login` to authenticate")),process.exit(1));let e=Q__default.default("Checking authentication...").start(),{valid:o,email:n}=await St(t.token);o||(e.fail("Session expired"),console.log(f__default.default.yellow(`
|
|
11
|
+
Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Authenticated"),console.log(""),console.log(f__default.default.green(` Email: ${n||t.email||"Unknown"}`)),t.projectId&&console.log(f__default.default.green(` Project: ${t.projectId}`)),console.log("");}var Ft=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Ct(t,e){let o=await fetch(`${Ft}/schema-engine/introspect/${e}`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!o.ok){let a=await o.text();throw new Error(`API introspection failed: ${a}`)}let n=await o.json();if(!n.ok||!n.schemaExists)throw new Error("Project schema does not exist yet. Push a migration first with `vaif db push`.");let r=new Map,i=[];for(let a of n.tables){let l=a.columns.map(d=>({column_name:d.name,data_type:d.type,is_nullable:d.nullable?"YES":"NO",column_default:d.default,udt_name:d.type,is_identity:d.primaryKey&&d.default?.includes("gen_random_uuid")?"YES":"NO",character_maximum_length:null,numeric_precision:null,numeric_scale:null}));r.set(a.name,l);for(let d of a.foreignKeys)i.push({constraint_name:d.constraintName,table_name:a.name,column_name:d.columnName,foreign_table_name:d.refTable,foreign_column_name:d.refColumn});}return {tables:r,enums:new Map,foreignKeys:i}}async function jt(t,e){let o=await t.query(`
|
|
12
12
|
SELECT table_name, table_type
|
|
13
13
|
FROM information_schema.tables
|
|
14
14
|
WHERE table_schema = $1
|
|
@@ -29,7 +29,7 @@ Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Aut
|
|
|
29
29
|
FROM information_schema.columns
|
|
30
30
|
WHERE table_schema = $1
|
|
31
31
|
ORDER BY table_name, ordinal_position
|
|
32
|
-
`,[e]),
|
|
32
|
+
`,[e]),r=await t.query(`
|
|
33
33
|
SELECT
|
|
34
34
|
tc.constraint_name,
|
|
35
35
|
tc.table_name,
|
|
@@ -45,7 +45,7 @@ Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Aut
|
|
|
45
45
|
AND ccu.table_schema = tc.table_schema
|
|
46
46
|
WHERE tc.constraint_type = 'FOREIGN KEY'
|
|
47
47
|
AND tc.table_schema = $1
|
|
48
|
-
`,[e]),
|
|
48
|
+
`,[e]),i=await t.query(`
|
|
49
49
|
SELECT
|
|
50
50
|
t.typname as enum_name,
|
|
51
51
|
e.enumlabel as enum_value
|
|
@@ -54,24 +54,24 @@ Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Aut
|
|
|
54
54
|
JOIN pg_namespace n ON n.oid = t.typnamespace
|
|
55
55
|
WHERE n.nspname = $1
|
|
56
56
|
ORDER BY t.typname, e.enumsortorder
|
|
57
|
-
`,[e]),
|
|
57
|
+
`,[e]),s=new Map;for(let l of o.rows)s.set(l.table_name,[]);for(let l of n.rows){let d=s.get(l.table_name);d&&d.push(l);}let a=new Map;for(let l of i.rows){let d=a.get(l.enum_name)||[];d.push(l.enum_value),a.set(l.enum_name,d);}return {tables:s,enums:a,foreignKeys:r.rows}}var ce={smallint:"number",integer:"number",bigint:"string",int2:"number",int4:"number",int8:"string",decimal:"string",numeric:"string",real:"number",float4:"number",float8:"number","double precision":"number",money:"string",boolean:"boolean",bool:"boolean",text:"string",varchar:"string",char:"string",character:"string","character varying":"string",name:"string",citext:"string",date:"string",time:"string",timetz:"string","time without time zone":"string","time with time zone":"string",timestamp:"string",timestamptz:"string","timestamp without time zone":"string","timestamp with time zone":"string",interval:"string",bytea:"Buffer",uuid:"string",json:"unknown",jsonb:"unknown",inet:"string",cidr:"string",macaddr:"string",macaddr8:"string",point:"{ x: number; y: number }",line:"string",lseg:"string",box:"string",path:"string",polygon:"string",circle:"string",ARRAY:"unknown[]"};function Rt(t,e){let{data_type:o,udt_name:n,is_nullable:r}=t;if(e.has(n)){let a=e.get(n).map(l=>`"${l}"`).join(" | ");return r==="YES"?`(${a}) | null`:a}if(o==="ARRAY"){let s=n.replace(/^_/,"");if(e.has(s)){let d=e.get(s).map(u=>`"${u}"`).join(" | ");return r==="YES"?`(${d})[] | null`:`(${d})[]`}let a=ce[s]||"unknown";return r==="YES"?`${a}[] | null`:`${a}[]`}let i=ce[o]||ce[n]||"unknown";return r==="YES"&&(i=`${i} | null`),i}function de(t){return t.split(/[_\-\s]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function Vt(t,e){let o=de(t),n=e.map(r=>` | "${r}"`).join(`
|
|
58
58
|
`);return `export type ${o} =
|
|
59
|
-
${n};`}function
|
|
60
|
-
${s.join(`
|
|
61
|
-
`)}
|
|
62
|
-
}`,c=`export interface ${n}Insert {
|
|
59
|
+
${n};`}function kt(t,e,o){let n=de(t),r=[],i=[],s=[];for(let u of e){let p=Rt(u,o),c=u.column_name,g=u.column_default!==null||u.is_identity==="YES",h=u.is_nullable==="YES";r.push(` ${c}: ${p};`),g||u.column_name==="id"?i.push(` ${c}?: ${p.replace(" | null","")} | null;`):h?i.push(` ${c}?: ${p};`):i.push(` ${c}: ${p.replace(" | null","")};`),s.push(` ${c}?: ${p.replace(" | null","")} | null;`);}let a=`export interface ${n} {
|
|
63
60
|
${r.join(`
|
|
64
61
|
`)}
|
|
65
|
-
}`,l=`export interface ${n}
|
|
62
|
+
}`,l=`export interface ${n}Insert {
|
|
66
63
|
${i.join(`
|
|
67
64
|
`)}
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
65
|
+
}`,d=`export interface ${n}Update {
|
|
66
|
+
${s.join(`
|
|
67
|
+
`)}
|
|
68
|
+
}`;return {base:a,insert:l,update:d}}function Lt(t,e,o){let n=["/**"," * Auto-generated TypeScript types from database schema"," * Generated by @vaiftech/cli",` * Generated at: ${new Date().toISOString()}`," * "," * DO NOT EDIT MANUALLY - changes will be overwritten"," */",""];if(e.size>0){n.push("// ============ ENUMS ============"),n.push("");for(let[i,s]of e)n.push(Vt(i,s)),n.push("");}n.push("// ============ TABLES ============"),n.push("");let r=[];for(let[i,s]of t){let{base:a,insert:l,update:d}=kt(i,s,e);r.push(i),n.push(a),n.push(""),n.push(l),n.push(""),n.push(d),n.push("");}n.push("// ============ DATABASE SCHEMA ============"),n.push(""),n.push("export interface Database {");for(let i of r){let s=de(i);n.push(` ${i}: {`),n.push(` Row: ${s};`),n.push(` Insert: ${s}Insert;`),n.push(` Update: ${s}Update;`),n.push(" };");}return n.push("}"),n.push(""),n.push("export type TableName = keyof Database;"),n.push(""),n.push("// ============ HELPER TYPES ============"),n.push(""),n.push('export type Row<T extends TableName> = Database[T]["Row"];'),n.push('export type Insert<T extends TableName> = Database[T]["Insert"];'),n.push('export type Update<T extends TableName> = Database[T]["Update"];'),n.push(""),n.join(`
|
|
69
|
+
`)}async function je(t){let e=Q__default.default("Loading configuration...").start();try{let o=await A(t.config),n=t.connection||o?.database?.url||process.env.DATABASE_URL,r=n&&!n.includes("${"),i,s,a;if(r){e.text="Connecting to database...";let c=new xt__default.default.Client({connectionString:n});await c.connect(),e.text="Introspecting schema...",{tables:i,enums:s,foreignKeys:a}=await jt(c,t.schema),await c.end();}else {let c=I();(!c||!c.token)&&(e.fail("No database connection and not logged in"),console.log(f__default.default.yellow(`
|
|
70
|
+
Either:`)),console.log(f__default.default.gray(" 1. Run `vaif login` to authenticate (no DATABASE_URL needed)")),console.log(f__default.default.gray(" 2. Set DATABASE_URL in your .env file")),console.log(f__default.default.gray(" 3. Pass --connection postgresql://user:pass@host:5432/db")),process.exit(1));let g=o?.projectId||process.env.VAIF_PROJECT_ID||c.projectId;g||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
|
|
71
|
+
Set projectId in vaif.config.json or use VAIF_PROJECT_ID env var.`)),process.exit(1)),e.text="Introspecting schema via API...",{tables:i,enums:s,foreignKeys:a}=await Ct(c.token,g);}if(i.size===0){e.warn("No tables found"),console.log(f__default.default.yellow(`
|
|
72
|
+
Push a migration first: vaif db push`));return}e.text=`Generating types for ${i.size} tables...`;let l=Lt(i,s,a),d=await Pt__default.default.format(l,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100});if(t.dryRun){e.succeed("Generated types (dry run):"),console.log(""),console.log(f__default.default.gray("\u2500".repeat(60))),console.log(d),console.log(f__default.default.gray("\u2500".repeat(60)));return}let u=S__default.default.resolve(t.output),p=S__default.default.dirname(u);U__default.default.existsSync(p)||U__default.default.mkdirSync(p,{recursive:!0}),U__default.default.writeFileSync(u,d,"utf-8"),e.succeed(`Generated types for ${i.size} tables \u2192 ${f__default.default.cyan(t.output)}`),console.log(""),console.log(f__default.default.green("Generated:")),console.log(f__default.default.gray(` Tables: ${i.size}`)),console.log(f__default.default.gray(` Enums: ${s.size}`)),console.log(""),console.log(f__default.default.gray("Import in your code:")),console.log(f__default.default.cyan(` import type { Database, Row, Insert, Update } from "${t.output.replace(/\.ts$/,"")}";`));}catch(o){e.fail("Failed to generate types"),o instanceof Error&&(console.error(f__default.default.red(`
|
|
73
73
|
Error: ${o.message}`)),o.message.includes("ECONNREFUSED")&&console.log(f__default.default.yellow(`
|
|
74
|
-
Make sure your database is running and accessible.`))),process.exit(1);}}var
|
|
74
|
+
Make sure your database is running and accessible.`))),process.exit(1);}}var q=[{name:"database",label:"Database",description:"CRUD queries, type-safe operations"},{name:"auth",label:"Authentication",description:"login, signup, OAuth, sessions"},{name:"realtime",label:"Realtime",description:"live subscriptions, presence"},{name:"storage",label:"Storage",description:"file uploads, signed URLs"},{name:"functions",label:"Functions",description:"serverless function calls"}],Ve={"nextjs-fullstack":{name:"Next.js Full-Stack",description:"Next.js app with server/client VAIF client, auth middleware, and React hooks",tag:"Next.js",defaultFeatures:["database","auth"],files:[{path:"package.json",content:`{
|
|
75
75
|
"name": "my-vaif-app",
|
|
76
76
|
"private": true,
|
|
77
77
|
"version": "0.1.0",
|
|
@@ -168,6 +168,7 @@ body {
|
|
|
168
168
|
// Browser client \u2013 safe to use in Client Components
|
|
169
169
|
export const vaif = createVaifClient({
|
|
170
170
|
baseUrl: process.env.NEXT_PUBLIC_VAIF_API_URL || 'https://api.vaif.studio',
|
|
171
|
+
projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID,
|
|
171
172
|
apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
|
|
172
173
|
});
|
|
173
174
|
|
|
@@ -175,6 +176,7 @@ export const vaif = createVaifClient({
|
|
|
175
176
|
export function createVaifServer() {
|
|
176
177
|
return createVaifClient({
|
|
177
178
|
baseUrl: process.env.NEXT_PUBLIC_VAIF_API_URL || 'https://api.vaif.studio',
|
|
179
|
+
projectId: process.env.VAIF_PROJECT_ID,
|
|
178
180
|
apiKey: process.env.VAIF_SECRET_KEY!,
|
|
179
181
|
});
|
|
180
182
|
}
|
|
@@ -182,6 +184,7 @@ export function createVaifServer() {
|
|
|
182
184
|
# Get these values from https://vaif.studio/app/security/api-keys \u2192 Project Settings \u2192 API Keys
|
|
183
185
|
|
|
184
186
|
NEXT_PUBLIC_VAIF_API_URL=https://api.vaif.studio
|
|
187
|
+
NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
|
|
185
188
|
NEXT_PUBLIC_VAIF_API_KEY=your-api-key
|
|
186
189
|
VAIF_SECRET_KEY=your-secret-key
|
|
187
190
|
|
|
@@ -315,6 +318,7 @@ export async function middleware(request: NextRequest) {
|
|
|
315
318
|
|
|
316
319
|
const vaif = createVaifClient({
|
|
317
320
|
baseUrl: process.env.NEXT_PUBLIC_VAIF_API_URL || 'https://api.vaif.studio',
|
|
321
|
+
projectId: process.env.VAIF_PROJECT_ID,
|
|
318
322
|
apiKey: process.env.VAIF_SECRET_KEY!,
|
|
319
323
|
});
|
|
320
324
|
|
|
@@ -677,12 +681,14 @@ function Home() {
|
|
|
677
681
|
|
|
678
682
|
export const vaif = createVaifClient({
|
|
679
683
|
baseUrl: import.meta.env.VITE_VAIF_API_URL || 'https://api.vaif.studio',
|
|
684
|
+
projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
|
|
680
685
|
apiKey: import.meta.env.VITE_VAIF_API_KEY,
|
|
681
686
|
});
|
|
682
687
|
`},{path:"src/vite-env.d.ts",content:`/// <reference types="vite/client" />
|
|
683
688
|
|
|
684
689
|
interface ImportMetaEnv {
|
|
685
690
|
readonly VITE_VAIF_API_URL: string;
|
|
691
|
+
readonly VITE_VAIF_PROJECT_ID: string;
|
|
686
692
|
readonly VITE_VAIF_API_KEY: string;
|
|
687
693
|
}
|
|
688
694
|
|
|
@@ -693,6 +699,7 @@ interface ImportMeta {
|
|
|
693
699
|
# Get these values from https://vaif.studio/app/security/api-keys
|
|
694
700
|
|
|
695
701
|
VITE_VAIF_API_URL=https://api.vaif.studio
|
|
702
|
+
VITE_VAIF_PROJECT_ID=your-project-id
|
|
696
703
|
VITE_VAIF_API_KEY=your-api-key
|
|
697
704
|
`},{path:".gitignore",content:`node_modules
|
|
698
705
|
dist
|
|
@@ -2693,6 +2700,7 @@ func HelloHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
2693
2700
|
|
|
2694
2701
|
export const vaif = createVaifClient({
|
|
2695
2702
|
baseUrl: import.meta.env.VITE_VAIF_API_URL || 'https://api.vaif.studio',
|
|
2703
|
+
projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
|
|
2696
2704
|
apiKey: import.meta.env.VITE_VAIF_API_KEY,
|
|
2697
2705
|
});
|
|
2698
2706
|
|
|
@@ -2747,6 +2755,7 @@ export async function deleteTodo(id: string): Promise<void> {
|
|
|
2747
2755
|
# Get these values from https://vaif.studio/app/security/api-keys
|
|
2748
2756
|
|
|
2749
2757
|
VITE_VAIF_API_URL=https://api.vaif.studio
|
|
2758
|
+
VITE_VAIF_PROJECT_ID=your-project-id
|
|
2750
2759
|
VITE_VAIF_API_KEY=your-api-key
|
|
2751
2760
|
`},{path:"README.md",content:`# Todo App \u2014 VAIF Starter
|
|
2752
2761
|
|
|
@@ -2884,6 +2893,7 @@ export const posts = pgTable("posts", {
|
|
|
2884
2893
|
|
|
2885
2894
|
export const vaif = createVaifClient({
|
|
2886
2895
|
baseUrl: import.meta.env.VITE_VAIF_API_URL || 'https://api.vaif.studio',
|
|
2896
|
+
projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
|
|
2887
2897
|
apiKey: import.meta.env.VITE_VAIF_API_KEY,
|
|
2888
2898
|
});
|
|
2889
2899
|
|
|
@@ -3025,6 +3035,7 @@ export function useRealtimeMessages({
|
|
|
3025
3035
|
# Get these values from https://vaif.studio/app/security/api-keys
|
|
3026
3036
|
|
|
3027
3037
|
VITE_VAIF_API_URL=https://api.vaif.studio
|
|
3038
|
+
VITE_VAIF_PROJECT_ID=your-project-id
|
|
3028
3039
|
VITE_VAIF_API_KEY=your-api-key
|
|
3029
3040
|
`},{path:"README.md",content:`# Realtime Chat \u2014 VAIF Starter
|
|
3030
3041
|
|
|
@@ -3177,6 +3188,7 @@ export const posts = pgTable("posts", {
|
|
|
3177
3188
|
// Browser client \u2013 use in Client Components
|
|
3178
3189
|
export const vaif = createVaifClient({
|
|
3179
3190
|
baseUrl: process.env.NEXT_PUBLIC_VAIF_API_URL || 'https://api.vaif.studio',
|
|
3191
|
+
projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID,
|
|
3180
3192
|
apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
|
|
3181
3193
|
});
|
|
3182
3194
|
|
|
@@ -3184,6 +3196,7 @@ export const vaif = createVaifClient({
|
|
|
3184
3196
|
export function createVaifServer() {
|
|
3185
3197
|
return createVaifClient({
|
|
3186
3198
|
baseUrl: process.env.NEXT_PUBLIC_VAIF_API_URL || 'https://api.vaif.studio',
|
|
3199
|
+
projectId: process.env.VAIF_PROJECT_ID,
|
|
3187
3200
|
apiKey: process.env.VAIF_SECRET_KEY!,
|
|
3188
3201
|
});
|
|
3189
3202
|
}
|
|
@@ -3338,6 +3351,7 @@ export async function requireTeamRole(
|
|
|
3338
3351
|
# Get these values from https://vaif.studio/app/security/api-keys \u2192 Project Settings \u2192 API Keys
|
|
3339
3352
|
|
|
3340
3353
|
NEXT_PUBLIC_VAIF_API_URL=https://api.vaif.studio
|
|
3354
|
+
NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
|
|
3341
3355
|
NEXT_PUBLIC_VAIF_API_KEY=your-api-key
|
|
3342
3356
|
VAIF_SECRET_KEY=your-secret-key
|
|
3343
3357
|
|
|
@@ -3490,6 +3504,7 @@ export const posts = pgTable("posts", {
|
|
|
3490
3504
|
// Browser client
|
|
3491
3505
|
export const vaif = createVaifClient({
|
|
3492
3506
|
baseUrl: process.env.NEXT_PUBLIC_VAIF_API_URL || 'https://api.vaif.studio',
|
|
3507
|
+
projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID,
|
|
3493
3508
|
apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
|
|
3494
3509
|
});
|
|
3495
3510
|
|
|
@@ -3497,6 +3512,7 @@ export const vaif = createVaifClient({
|
|
|
3497
3512
|
export function createVaifServer() {
|
|
3498
3513
|
return createVaifClient({
|
|
3499
3514
|
baseUrl: process.env.NEXT_PUBLIC_VAIF_API_URL || 'https://api.vaif.studio',
|
|
3515
|
+
projectId: process.env.VAIF_PROJECT_ID,
|
|
3500
3516
|
apiKey: process.env.VAIF_SECRET_KEY!,
|
|
3501
3517
|
});
|
|
3502
3518
|
}
|
|
@@ -3613,6 +3629,7 @@ function getContentType(fileName: string): string {
|
|
|
3613
3629
|
# Get these values from https://vaif.studio/app/security/api-keys \u2192 Project Settings \u2192 API Keys
|
|
3614
3630
|
|
|
3615
3631
|
NEXT_PUBLIC_VAIF_API_URL=https://api.vaif.studio
|
|
3632
|
+
NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
|
|
3616
3633
|
NEXT_PUBLIC_VAIF_API_KEY=your-api-key
|
|
3617
3634
|
VAIF_SECRET_KEY=your-secret-key
|
|
3618
3635
|
|
|
@@ -3758,47 +3775,240 @@ export const posts = pgTable("posts", {
|
|
|
3758
3775
|
|
|
3759
3776
|
return Response.json({ message: \`Hello, \${name}!\` });
|
|
3760
3777
|
}
|
|
3761
|
-
`}]},dependencies:["@vaiftech/client","@vaiftech/auth"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create a 'product-images' storage bucket in your VAIF dashboard","Import storage helpers from '@/lib/storage' in your API routes","Use uploadProductImage() in your product creation flow","Run: npx vaif generate to generate TypeScript types"]}};function
|
|
3762
|
-
? Which VAIF features do you want to include?`)),
|
|
3778
|
+
`}]},dependencies:["@vaiftech/client","@vaiftech/auth"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create a 'product-images' storage bucket in your VAIF dashboard","Import storage helpers from '@/lib/storage' in your API routes","Use uploadProductImage() in your product creation flow","Run: npx vaif generate to generate TypeScript types"]}};function ke(){console.log(""),console.log(f__default.default.bold("Available project templates")),console.log("");let t=26,e=22;console.log(` ${f__default.default.gray("Template".padEnd(t))}${f__default.default.gray("Stack".padEnd(e))}${f__default.default.gray("Description")}`),console.log(f__default.default.gray(" "+"-".repeat(t+e+40)));for(let[o,n]of Object.entries(Ve))console.log(` ${f__default.default.cyan(o.padEnd(t))}${f__default.default.yellow(n.tag.padEnd(e))}${f__default.default.white(n.description)}`);console.log(""),console.log(f__default.default.gray("Usage:")),console.log(f__default.default.gray(" npx @vaiftech/cli init --template <name>")),console.log(f__default.default.gray(" npx @vaiftech/cli init -t nextjs-fullstack")),console.log(f__default.default.gray(" npx @vaiftech/cli init -t react-spa --features auth,database,realtime")),console.log(""),console.log(f__default.default.gray("Available features: auth, database, realtime, storage, functions")),console.log("");}async function Nt(t){if(!process.stdin.isTTY||!process.stdout.isTTY)return t;let e=new Set(t.map(n=>q.findIndex(r=>r.name===n)).filter(n=>n>=0)),o=0;return new Promise(n=>{let r=Ee__default.default.createInterface({input:process.stdin,output:process.stdout});Ee__default.default.emitKeypressEvents(process.stdin,r),process.stdin.setRawMode&&process.stdin.setRawMode(true);function i(){let a=q.length+2;process.stdout.write(`\x1B[${a}A`),s();}function s(){console.log(f__default.default.bold(`
|
|
3779
|
+
? Which VAIF features do you want to include?`)),q.forEach((a,l)=>{let d=e.has(l)?f__default.default.green("[x]"):"[ ]",u=l===o?f__default.default.cyan("> "):" ";console.log(`${u}${d} ${a.label} ${f__default.default.gray(`(${a.description})`)}`);}),console.log(f__default.default.gray(" (up/down to move, space to toggle, enter to confirm)"));}s(),process.stdin.on("keypress",(a,l)=>{if(l.name==="up"&&o>0)o--,i();else if(l.name==="down"&&o<q.length-1)o++,i();else if(l.name==="space")e.has(o)?e.delete(o):e.add(o),i();else if(l.name==="return"){process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close();let d=[...e].sort().map(u=>q[u].name);n(d.length>0?d:t);}else l.name==="c"&&l.ctrl&&(process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close(),process.exit(0));});})}async function ue(t,e={}){let o=Ve[t];o||(console.log(f__default.default.red(`
|
|
3763
3780
|
Unknown template: ${t}`)),console.log(f__default.default.yellow(`Run 'vaif templates' to see available templates.
|
|
3764
|
-
`)),process.exit(1));let n;e.features&&e.features.length>0?n=e.features.filter(
|
|
3765
|
-
No features specified.`)),console.log(f__default.default.yellow("Usage: vaif init --template <name> --add-features <features>")),console.log(f__default.default.gray("Available features: auth, database, realtime, storage, functions")),process.exit(1)):o.featureFiles&&Object.keys(o.featureFiles).length>0?n=await
|
|
3766
|
-
`,"utf-8"),console.log(f__default.default.green(` merge ${
|
|
3767
|
-
`,"utf-8");}catch{}(o.dependencies?.length||o.devDependencies?.length)&&(console.log(""),console.log(f__default.default.bold("Install dependencies:")),o.dependencies?.length&&console.log(f__default.default.cyan(` npm install ${o.dependencies.join(" ")}`)),o.devDependencies?.length&&console.log(f__default.default.cyan(` npm install -D ${o.devDependencies.join(" ")}`))),console.log(""),console.log(f__default.default.bold.green("Project scaffolded successfully!")),console.log(""),console.log(f__default.default.bold(" Next steps:")),o.postInstructions.forEach(
|
|
3768
|
-
--add-features requires --template to know which template to use.`)),console.log(f__default.default.gray("Example: vaif init --template react-spa --add-features functions,storage")),process.exit(1));let n=t.addFeatures.split(",").map(
|
|
3769
|
-
Use --force to overwrite existing configuration.`)),process.exit(1));try{if(
|
|
3781
|
+
`)),process.exit(1));let n;e.features&&e.features.length>0?n=e.features.filter(c=>q.some(g=>g.name===c)):e.addOnly?(console.log(f__default.default.red(`
|
|
3782
|
+
No features specified.`)),console.log(f__default.default.yellow("Usage: vaif init --template <name> --add-features <features>")),console.log(f__default.default.gray("Available features: auth, database, realtime, storage, functions")),process.exit(1)):o.featureFiles&&Object.keys(o.featureFiles).length>0?n=await Nt(o.defaultFeatures??["database","auth"]):n=o.defaultFeatures??[],e.addOnly?(console.log(""),console.log(f__default.default.bold(`Adding features to ${f__default.default.cyan(o.name)} project...`)),console.log(f__default.default.gray(` Features: ${n.join(", ")}`)),console.log("")):(console.log(""),console.log(f__default.default.bold(`Scaffolding ${f__default.default.cyan(o.name)} template...`)),n.length>0&&console.log(f__default.default.gray(` Features: ${n.join(", ")}`)),console.log(""));let r=e.addOnly?[]:[...o.files],i=new Set,s=[];if(o.featureFiles)for(let c of n){let g=o.featureFiles[c];if(g)for(let h of g)i.add(h.path),s.push(h);}let a=r.filter(c=>!i.has(c.path)).concat(s),l=0,d=0;for(let c of a){let g=S__default.default.resolve(c.path),h=S__default.default.dirname(g);if(U__default.default.existsSync(h)||U__default.default.mkdirSync(h,{recursive:true}),c.path==="package.json"&&U__default.default.existsSync(g)&&!e.force)try{let E=JSON.parse(U__default.default.readFileSync(g,"utf-8")),N=JSON.parse(c.content),$=Ie=>{if(!Ie)return {};let Ae={};for(let[ft,W]of Object.entries(Ie))!W.startsWith("workspace:")&&!W.startsWith("link:")&&!W.startsWith("file:")&&(Ae[ft]=W);return Ae};E.dependencies={...$(E.dependencies),...N.dependencies||{}},E.devDependencies={...$(E.devDependencies),...N.devDependencies||{}},N.scripts&&(E.scripts={...E.scripts||{},...N.scripts}),U__default.default.writeFileSync(g,JSON.stringify(E,null,2)+`
|
|
3783
|
+
`,"utf-8"),console.log(f__default.default.green(` merge ${c.path} (added dependencies)`)),l++;continue}catch{}if(U__default.default.existsSync(g)&&!e.force){console.log(f__default.default.yellow(` skip ${c.path} (already exists)`)),d++;continue}U__default.default.writeFileSync(g,c.content,"utf-8"),console.log(f__default.default.green(` create ${c.path}`)),l++;}console.log(""),l>0&&console.log(f__default.default.green(`Created ${l} file${l!==1?"s":""}.`)),d>0&&console.log(f__default.default.yellow(`Skipped ${d} file${d!==1?"s":""} (use --force to overwrite).`));let u={auth:{"@vaiftech/auth":"^1.0.0"},database:{},realtime:{},storage:{},functions:{}},p=S__default.default.resolve("package.json");if(U__default.default.existsSync(p)&&n.length>0)try{let c=JSON.parse(U__default.default.readFileSync(p,"utf-8")),g=!1;for(let h of n){let E=u[h];if(E)for(let[N,$]of Object.entries(E))c.dependencies?.[N]||(c.dependencies=c.dependencies||{},c.dependencies[N]=$,g=!0);}g&&U__default.default.writeFileSync(p,JSON.stringify(c,null,2)+`
|
|
3784
|
+
`,"utf-8");}catch{}(o.dependencies?.length||o.devDependencies?.length)&&(console.log(""),console.log(f__default.default.bold("Install dependencies:")),o.dependencies?.length&&console.log(f__default.default.cyan(` npm install ${o.dependencies.join(" ")}`)),o.devDependencies?.length&&console.log(f__default.default.cyan(` npm install -D ${o.devDependencies.join(" ")}`))),console.log(""),console.log(f__default.default.bold.green("Project scaffolded successfully!")),console.log(""),console.log(f__default.default.bold(" Next steps:")),o.postInstructions.forEach(c=>{console.log(f__default.default.gray(` ${c}`));}),console.log(""),console.log(f__default.default.gray(" Get your project credentials at https://vaif.studio/app/security/api-keys")),console.log("");}var Ut={$schema:"https://vaif.studio/schemas/config.json",projectId:"",database:{url:"${DATABASE_URL}",schema:"public"},types:{output:"./src/types/database.ts"},api:{baseUrl:"https://api.vaif.studio"}};async function Le(t){if(t.addFeatures){t.template||(console.log(f__default.default.red(`
|
|
3785
|
+
--add-features requires --template to know which template to use.`)),console.log(f__default.default.gray("Example: vaif init --template react-spa --add-features functions,storage")),process.exit(1));let n=t.addFeatures.split(",").map(r=>r.trim());await ue(t.template,{force:t.force,features:n,addOnly:true});return}let e=Q__default.default("Initializing VAIF configuration...").start(),o=S__default.default.resolve("vaif.config.json");U__default.default.existsSync(o)&&!t.force&&(e.fail("vaif.config.json already exists"),console.log(f__default.default.yellow(`
|
|
3786
|
+
Use --force to overwrite existing configuration.`)),process.exit(1));try{if(U__default.default.writeFileSync(o,JSON.stringify(Ut,null,2),"utf-8"),e.succeed("Created vaif.config.json"),t.template){let n=t.features?t.features.split(",").map(r=>r.trim()):void 0;await ue(t.template,{force:t.force,features:n});}else {let n=S__default.default.resolve(".env.example");if(U__default.default.existsSync(n)||(U__default.default.writeFileSync(n,`# VAIF Configuration
|
|
3770
3787
|
DATABASE_URL=postgresql://user:password@localhost:5432/database
|
|
3771
3788
|
VAIF_API_KEY=your-api-key
|
|
3772
|
-
`,"utf-8"),console.log(f__default.default.gray("Created .env.example"))),t.typescript){let
|
|
3773
|
-
Error: ${n.message}`)),process.exit(1);}}var
|
|
3774
|
-
Error: ${
|
|
3775
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let
|
|
3776
|
-
Error: ${
|
|
3777
|
-
Error: ${
|
|
3778
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let
|
|
3779
|
-
Expected schema file at: ${
|
|
3780
|
-
Error: ${
|
|
3781
|
-
Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let
|
|
3782
|
-
Error: ${
|
|
3789
|
+
`,"utf-8"),console.log(f__default.default.gray("Created .env.example"))),t.typescript){let r=S__default.default.resolve("src/types");U__default.default.existsSync(r)||(U__default.default.mkdirSync(r,{recursive:!0}),console.log(f__default.default.gray("Created src/types directory")));}console.log(""),console.log(f__default.default.green("VAIF initialized successfully!")),console.log(""),console.log(f__default.default.gray("Next steps:")),console.log(f__default.default.gray(" 1. Update vaif.config.json with your project ID")),console.log(f__default.default.gray(" 2. Set DATABASE_URL in your environment")),console.log(f__default.default.gray(" 3. Run: npx vaif generate")),console.log("");}}catch(n){e.fail("Failed to initialize"),n instanceof Error&&console.error(f__default.default.red(`
|
|
3790
|
+
Error: ${n.message}`)),process.exit(1);}}var Kt=process.env.VAIF_API_URL||"https://api.vaif.studio";async function zt(t,e,o="public"){let n=await fetch(`${Kt}/v1/projects/${e}/schema?schema=${o}`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!n.ok){let r=await n.text();throw new Error(`Failed to fetch schema: ${r}`)}return n.json()}async function Ne(t){let e=Q__default.default(),o=I();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await A(n);}catch(s){e.fail("Failed to load config"),console.log(f__default.default.red(`
|
|
3791
|
+
Error: ${s}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(f__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let i=t.projectId||r.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
|
|
3792
|
+
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let s=t.schema||r.database?.schema||"public",a=await zt(o.token,i,s);e.succeed("Schema fetched successfully");let l=t.output||S__default.default.resolve("vaif.schema.json"),d={$schema:"https://vaif.studio/schemas/schema.json",projectId:i,schema:s,pulledAt:new Date().toISOString(),...a};U__default.default.writeFileSync(l,JSON.stringify(d,null,2),"utf-8"),console.log(""),console.log(f__default.default.green(`Schema saved to: ${l}`)),console.log(""),console.log(f__default.default.gray("Schema summary:")),console.log(f__default.default.gray(` Tables: ${(a.tables||[]).length}`)),console.log(f__default.default.gray(` Enums: ${(a.enums||[]).length}`)),console.log(f__default.default.gray(` Functions: ${(a.functions||[]).length}`)),console.log(""),console.log(f__default.default.gray("Next steps:")),console.log(f__default.default.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(f__default.default.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(s){e.fail("Failed to fetch schema"),s instanceof Error&&console.log(f__default.default.red(`
|
|
3793
|
+
Error: ${s.message}`)),process.exit(1);}}var Ue=process.env.VAIF_API_URL||"https://api.vaif.studio";function Jt(t){let e=Ee__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}async function Gt(t,e,o){let n=await fetch(`${Ue}/v1/projects/${e}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!n.ok){let r=await n.text();throw new Error(`Failed to preview changes: ${r}`)}return n.json()}async function Wt(t,e,o){let n=await fetch(`${Ue}/v1/projects/${e}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!n.ok){let r=await n.text();throw new Error(`Failed to apply changes: ${r}`)}return n.json()}function Ht(t){if(console.log(""),console.log(f__default.default.bold("Schema Changes:")),console.log(""),t.added.length===0&&t.modified.length===0&&t.removed.length===0){console.log(f__default.default.gray(" No changes detected. Schema is up to date."));return}if(t.added.length>0){console.log(f__default.default.green.bold(" + Added:"));for(let e of t.added)console.log(f__default.default.green(` + ${e.type}: ${e.name}`));console.log("");}if(t.modified.length>0){console.log(f__default.default.yellow.bold(" ~ Modified:"));for(let e of t.modified){console.log(f__default.default.yellow(` ~ ${e.type}: ${e.name}`));for(let o of e.changes)console.log(f__default.default.gray(` ${o}`));}console.log("");}if(t.removed.length>0){console.log(f__default.default.red.bold(" - Removed:"));for(let e of t.removed)console.log(f__default.default.red(` - ${e.type}: ${e.name}`));console.log("");}}async function $e(t){let e=Q__default.default(),o=I();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await A(n);}catch(l){e.fail("Failed to load config"),console.log(f__default.default.red(`
|
|
3794
|
+
Error: ${l}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(f__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let i=t.projectId||r.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
|
|
3795
|
+
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let s=t.schema||S__default.default.resolve("vaif.schema.json");U__default.default.existsSync(s)||(e.fail("No local schema found"),console.log(f__default.default.yellow(`
|
|
3796
|
+
Expected schema file at: ${s}`)),console.log(f__default.default.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let a;try{let l=U__default.default.readFileSync(s,"utf-8");a=JSON.parse(l);}catch(l){e.fail("Failed to parse schema file"),l instanceof Error&&console.log(f__default.default.red(`
|
|
3797
|
+
Error: ${l.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:l,sql:d}=await Gt(o.token,i,a);if(e.stop(),Ht(l),l.added.length===0&&l.modified.length===0&&l.removed.length===0){console.log("");return}if(d.length>0){console.log(f__default.default.bold("SQL Migrations:")),console.log("");for(let p of d)console.log(f__default.default.gray(` ${p}`));console.log("");}if(t.dryRun){console.log(f__default.default.yellow("Dry run mode - no changes applied.")),console.log(f__default.default.gray("Remove --dry-run to apply these changes."));return}if(!t.force){l.removed.length>0&&(console.log(f__default.default.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(f__default.default.red(" This action cannot be undone!")),console.log(""));let c=await Jt(f__default.default.cyan("Apply these changes? [y/N] "));if(c.toLowerCase()!=="y"&&c.toLowerCase()!=="yes"){console.log(f__default.default.yellow(`
|
|
3798
|
+
Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let u=await Wt(o.token,i,a);if(u.success){if(e.succeed("Schema changes applied successfully"),console.log(""),u.migrations.length>0){console.log(f__default.default.gray("Migrations applied:"));for(let p of u.migrations)console.log(f__default.default.gray(` - ${p}`));console.log("");}console.log(f__default.default.green("Your database schema is now up to date.")),console.log(f__default.default.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else e.fail("Failed to apply some changes");}catch(l){e.fail("Failed to push schema changes"),l instanceof Error&&console.log(f__default.default.red(`
|
|
3799
|
+
Error: ${l.message}`)),process.exit(1);}}var X=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Xt(t,e,o,n){let r=new URL(`${X}/functions/project/${e}`);n&&r.searchParams.set("envId",n);let i=await fetch(r.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!i.ok)return null;let s=await i.json(),a=s.functions||s;return Array.isArray(a)&&a.find(l=>l.name===o)||null}async function Qt(t,e,o){let n=await fetch(`${X}/functions/`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:e,name:o.name,runtime:o.runtime,entrypoint:o.entrypoint,envId:o.envId})});if(!n.ok){let r=await n.text();throw new Error(`Failed to create function: ${r}`)}return n.json()}async function Zt(t,e,o){let n=await fetch(`${X}/functions/${e}/source`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({sourceCode:o})});if(!n.ok){let r=await n.text();throw new Error(`Failed to deploy source: ${r}`)}}async function eo(t,e,o){let n=new URL(`${X}/functions/project/${e}`);o&&n.searchParams.set("envId",o);let r=await fetch(n.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!r.ok){let s=await r.text();throw new Error(`Failed to list functions: ${s}`)}let i=await r.json();return i.functions||i}function Oe(t){switch(S__default.default.extname(t).toLowerCase()){case ".ts":return "typescript";case ".js":case ".mjs":return "nodejs";case ".py":return "python";case ".go":return "go";case ".rs":return "rust";default:return "nodejs"}}function Me(t){let e=[],o=[".ts",".js",".mjs",".py",".go",".rs"],n=["drizzle.config.ts","tsconfig.json","package.json"];if(!U__default.default.existsSync(t))return e;let r=U__default.default.readdirSync(t,{withFileTypes:true});for(let i of r){let s=S__default.default.join(t,i.name);if(i.isDirectory()){if(i.name!=="node_modules"&&!i.name.startsWith(".")){let a=U__default.default.readdirSync(s,{withFileTypes:true});for(let l of a)if(l.isFile()){let d=S__default.default.extname(l.name).toLowerCase();if(o.includes(d)){e.push(S__default.default.join(s,l.name));break}}}}else if(i.isFile()){let a=S__default.default.extname(i.name).toLowerCase();o.includes(a)&&!n.includes(i.name)&&e.push(s);}}return e}async function ze(t){let e=Q__default.default(),o=I();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let i=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF Functions Deploy")),console.log(""),e.start("Scanning for function files...");let s=S__default.default.resolve("functions"),a=S__default.default.resolve("src/functions"),l=[];if(t.entrypoint){let c=S__default.default.resolve(t.entrypoint);U__default.default.existsSync(c)||(e.fail(`File not found: ${t.entrypoint}`),process.exit(1)),l=[c];}else l=[...Me(s),...Me(a)];l.length===0&&(e.fail("No function files found"),console.log(f__default.default.yellow(`
|
|
3783
3800
|
Place your functions in:`)),console.log(f__default.default.gray(" - ./functions/")),console.log(f__default.default.gray(" - ./src/functions/")),console.log(f__default.default.gray(`
|
|
3784
|
-
Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${
|
|
3785
|
-
No functions matching "${t.name}" found`)),process.exit(1))),console.log(""),console.log(f__default.default.gray("Functions to deploy:"));for(let
|
|
3786
|
-
No functions found`)),console.log(f__default.default.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(f__default.default.bold(`Functions (${
|
|
3787
|
-
Error: ${
|
|
3801
|
+
Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${l.length} function(s)`),t.name&&(l=l.filter(c=>S__default.default.basename(c,S__default.default.extname(c)).includes(t.name)),l.length===0&&(console.log(f__default.default.yellow(`
|
|
3802
|
+
No functions matching "${t.name}" found`)),process.exit(1))),console.log(""),console.log(f__default.default.gray("Functions to deploy:"));for(let c of l){let g=S__default.default.basename(S__default.default.dirname(c)),h=g==="functions"||g==="src"?S__default.default.basename(c,S__default.default.extname(c)):g,E=t.runtime||Oe(c);console.log(f__default.default.gray(` - ${h} (${E})`));}if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no functions deployed."));return}let d=[];for(let c of l){let g=S__default.default.basename(S__default.default.dirname(c)),h=g==="functions"||g==="src"?S__default.default.basename(c,S__default.default.extname(c)):g,E=t.runtime||Oe(c);e.start(`Deploying ${h}...`);try{let N=U__default.default.readFileSync(c,"utf-8"),$=await Xt(o.token,i,h,t.envId);$||(e.text=`Creating ${h}...`,$=await Qt(o.token,i,{name:h,runtime:E,entrypoint:S__default.default.basename(c),envId:t.envId})),e.text=`Deploying ${h}...`,await Zt(o.token,$.id,N),e.succeed(`Deployed ${h}`),d.push({name:h,success:!0});}catch(N){let $=N instanceof Error?N.message:"Unknown error";e.fail(`Failed to deploy ${h}`),d.push({name:h,success:false,error:$});}}console.log("");let u=d.filter(c=>c.success).length;if(d.filter(c=>!c.success).length===0)console.log(f__default.default.green(`\u2713 Successfully deployed ${u} function(s)`));else {console.log(f__default.default.yellow(`Deployed ${u}/${d.length} function(s)`)),console.log(""),console.log(f__default.default.red("Failed deployments:"));for(let c of d.filter(g=>!g.success))console.log(f__default.default.red(` - ${c.name}: ${c.error}`));}console.log("");}async function Be(t){let e=Q__default.default(),o=I();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let i=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(console.log(f__default.default.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let s=await eo(o.token,i,t.envId);if(e.stop(),s.length===0){console.log(f__default.default.yellow(`
|
|
3803
|
+
No functions found`)),console.log(f__default.default.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(f__default.default.bold(`Functions (${s.length}):`)),console.log(""),console.log(f__default.default.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"STATUS".padEnd(12)+"INVOCATIONS".padEnd(14)+"LAST DEPLOYED")),console.log(f__default.default.gray(" "+"-".repeat(80)));for(let a of s){let l=a.deployStatus==="deployed"?f__default.default.green:a.deployStatus==="deploying"?f__default.default.yellow:a.deployStatus==="failed"?f__default.default.red:f__default.default.gray;console.log(" "+a.name.padEnd(25)+a.runtime.padEnd(15)+l(a.deployStatus.padEnd(12))+String(a.invocationCount??0).padEnd(14)+(a.deployedAt?new Date(a.deployedAt).toLocaleDateString():"-"));}console.log("");}catch(s){e.fail("Failed to fetch functions"),s instanceof Error&&console.log(f__default.default.red(`
|
|
3804
|
+
Error: ${s.message}`)),process.exit(1);}}var Z=process.env.VAIF_API_URL||"https://api.vaif.studio";async function to(t,e,o,n,r){let i=await fetch(`${Z}/v1/projects/${e}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({table:o,records:n,truncate:r?.truncate??false})});if(!i.ok){let s=await i.text();throw new Error(`Failed to seed ${o}: ${s}`)}return i.json()}async function oo(t,e){let o=await fetch(`${Z}/v1/projects/${e}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!o.ok){let n=await o.text();throw new Error(`Failed to reset database: ${n}`)}return o.json()}function ge(t){let e=[];if(!U__default.default.existsSync(t))return e;let o=U__default.default.readdirSync(t,{withFileTypes:true});for(let n of o)if(n.isFile()){let r=S__default.default.extname(n.name).toLowerCase();(r===".json"||r===".ts"||r===".js")&&e.push(S__default.default.join(t,n.name));}return e.sort()}async function qe(t){let e=S__default.default.extname(t).toLowerCase();if(e===".json"){let o=U__default.default.readFileSync(t,"utf-8"),n=JSON.parse(o);return Array.isArray(n)?[{table:S__default.default.basename(t,e),data:n}]:n.table&&n.data?[n]:Object.entries(n).map(([r,i])=>({table:r,data:i}))}else if(e===".ts"||e===".js"){let o=await import(t),n=o.default||o;return typeof n=="function"?n():n}throw new Error(`Unsupported file format: ${e}`)}async function Ye(t){let e=Q__default.default(),o=I();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let i=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF Database Seed")),console.log("");let s=[];if(t.file){let u=S__default.default.resolve(t.file);U__default.default.existsSync(u)||(console.log(f__default.default.red(`File not found: ${t.file}`)),process.exit(1)),s=[u];}else {let u=S__default.default.resolve("seeds"),p=S__default.default.resolve("prisma/seed"),c=S__default.default.resolve("db/seeds");s=[...ge(u),...ge(p),...ge(c)];}s.length===0&&(console.log(f__default.default.yellow("No seed files found")),console.log(f__default.default.gray(`
|
|
3788
3805
|
Place your seed files in one of these directories:`)),console.log(f__default.default.gray(" - ./seeds/")),console.log(f__default.default.gray(" - ./prisma/seed/")),console.log(f__default.default.gray(" - ./db/seeds/")),console.log(f__default.default.gray(`
|
|
3789
3806
|
Or specify a file with --file`)),console.log(f__default.default.gray(`
|
|
3790
|
-
Example seed file (seeds/users.json):`)),console.log(f__default.default.gray(" [")),console.log(f__default.default.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(f__default.default.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(f__default.default.gray(" ]")),process.exit(1)),console.log(f__default.default.gray("Seed files found:"));for(let
|
|
3807
|
+
Example seed file (seeds/users.json):`)),console.log(f__default.default.gray(" [")),console.log(f__default.default.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(f__default.default.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(f__default.default.gray(" ]")),process.exit(1)),console.log(f__default.default.gray("Seed files found:"));for(let u of s)console.log(f__default.default.gray(` - ${S__default.default.relative(process.cwd(),u)}`));if(console.log(""),t.truncate&&(console.log(f__default.default.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let u of s){e.start(`Loading ${S__default.default.basename(u)}...`);try{let p=await qe(u);e.stop();for(let c of p)t.table&&c.table!==t.table||(console.log(f__default.default.cyan(`Table: ${c.table}`)),console.log(f__default.default.gray(` Records: ${c.data.length}`)),c.data.length>0&&console.log(f__default.default.gray(` Sample: ${JSON.stringify(c.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(p){e.fail(`Failed to load ${S__default.default.basename(u)}`),p instanceof Error&&console.log(f__default.default.red(` Error: ${p.message}`));}}return}let a=[];for(let u of s){e.start(`Processing ${S__default.default.basename(u)}...`);try{let p=await qe(u);e.stop();for(let c of p)if(!(t.table&&c.table!==t.table)){if(c.data.length===0){console.log(f__default.default.gray(` Skipping ${c.table} (no records)`));continue}e.start(`Seeding ${c.table} (${c.data.length} records)...`);try{let g=await to(o.token,i,c.table,c.data,{truncate:t.truncate});e.succeed(`Seeded ${c.table}: ${g.inserted} records`),a.push({table:c.table,inserted:g.inserted});}catch(g){let h=g instanceof Error?g.message:"Unknown error";e.fail(`Failed to seed ${c.table}`),a.push({table:c.table,inserted:0,error:h});}}}catch(p){e.fail(`Failed to load ${S__default.default.basename(u)}`),p instanceof Error&&console.log(f__default.default.red(` Error: ${p.message}`));}}console.log("");let l=a.reduce((u,p)=>u+p.inserted,0),d=a.filter(u=>u.error).length;if(d===0)console.log(f__default.default.green(`\u2713 Successfully seeded ${l} records across ${a.length} table(s)`));else {console.log(f__default.default.yellow(`Seeded ${l} records with ${d} error(s)`)),console.log(""),console.log(f__default.default.red("Errors:"));for(let u of a.filter(p=>p.error))console.log(f__default.default.red(` - ${u.table}: ${u.error}`));}console.log("");}async function Je(t){let e=Q__default.default(),o=I();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let i=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let s=S__default.default.resolve(t.dir||"./drizzle");if(console.log(""),console.log(f__default.default.bold("VAIF Database Push")),console.log(""),!U__default.default.existsSync(s)){let p=S__default.default.resolve("./migrations");U__default.default.existsSync(p)?console.log(f__default.default.gray(`Using migrations from: ${p}`)):(console.log(f__default.default.red(`Migrations directory not found: ${s}`)),console.log(f__default.default.gray(`
|
|
3791
3808
|
Expected one of:`)),console.log(f__default.default.gray(" - ./drizzle/")),console.log(f__default.default.gray(" - ./migrations/")),console.log(f__default.default.gray(`
|
|
3792
|
-
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let a=[],
|
|
3793
|
-
Error: ${a.message}`)),process.exit(1);}}async function
|
|
3794
|
-
Error: ${
|
|
3795
|
-
Error: ${a.message}`)),process.exit(1);}}async function
|
|
3796
|
-
Generate one with: vaif keys generate`));return}let
|
|
3797
|
-
Error: ${
|
|
3798
|
-
Error: ${
|
|
3799
|
-
Create one with: vaif secrets set <name> <value>`));return}let
|
|
3800
|
-
Error: ${
|
|
3801
|
-
Error: ${
|
|
3802
|
-
Error: ${
|
|
3803
|
-
Error: ${
|
|
3804
|
-
Error: ${
|
|
3809
|
+
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let a=[],l=U__default.default.readdirSync(s,{withFileTypes:true});for(let p of l)if(p.isFile()&&p.name.endsWith(".sql"))a.push(S__default.default.join(s,p.name));else if(p.isDirectory()){let c=U__default.default.readdirSync(S__default.default.join(s,p.name),{withFileTypes:true});for(let g of c)g.isFile()&&g.name.endsWith(".sql")&&a.push(S__default.default.join(s,p.name,g.name));}a.sort(),a.length===0&&(console.log(f__default.default.yellow("No SQL migration files found")),process.exit(1)),console.log(f__default.default.gray(`Found ${a.length} migration(s):`));for(let p of a)console.log(f__default.default.gray(` - ${S__default.default.relative(process.cwd(),p)}`));if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let p of a){let c=U__default.default.readFileSync(p,"utf-8");console.log(f__default.default.cyan(`--- ${S__default.default.basename(p)} ---`)),console.log(f__default.default.gray(c.slice(0,500))),c.length>500&&console.log(f__default.default.gray("...")),console.log("");}return}let d=0,u=0;for(let p of a){let c=U__default.default.readFileSync(p,"utf-8"),g=S__default.default.relative(process.cwd(),p);e.start(`Applying ${g}...`);try{let h=await fetch(`${Z}/schema-engine/query/${i}`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:c})});if(!h.ok){let E=await h.text();throw new Error(E)}e.succeed(`Applied ${g}`),d++;}catch(h){let E=h instanceof Error?h.message:"Unknown error";e.fail(`Failed ${g}: ${E}`),u++;}}console.log(""),console.log(u===0?f__default.default.green(`Successfully applied ${d} migration(s)`):f__default.default.yellow(`Applied ${d}, failed ${u} migration(s)`)),console.log("");}async function Ge(t){let e=Q__default.default(),o=I();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let i=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let s=S__default.default.resolve(t.output||"vaif.schema.json");console.log(""),console.log(f__default.default.bold("VAIF Database Pull")),console.log(""),e.start("Pulling schema from remote...");try{let a=await fetch(`${Z}/schema-engine/introspect/${i}`,{headers:{Authorization:`Bearer ${o.token}`}});if(!a.ok){let u=await a.text();throw new Error(`Failed to pull schema: ${u}`)}let l=await a.json();U__default.default.writeFileSync(s,JSON.stringify(l,null,2),"utf-8"),e.succeed(`Schema written to ${S__default.default.relative(process.cwd(),s)}`);let d=l.tables?.length??Object.keys(l).length;console.log(f__default.default.gray(` ${d} table(s) pulled`)),console.log("");}catch(a){e.fail("Failed to pull schema"),a instanceof Error&&console.log(f__default.default.red(`
|
|
3810
|
+
Error: ${a.message}`)),process.exit(1);}}async function We(t){let e=Q__default.default(),o=I();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let i=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(console.log(f__default.default.red("No project ID specified")),process.exit(1)),console.log(""),console.log(f__default.default.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(f__default.default.red("This will:")),console.log(f__default.default.red(" - Drop all tables")),console.log(f__default.default.red(" - Delete all data")),console.log(f__default.default.red(" - Reset migrations")),console.log(""),console.log(f__default.default.red.bold("This action cannot be undone!")),console.log(""),t.force||(console.log(f__default.default.yellow("Use --force to confirm this action.")),process.exit(1)),e.start("Resetting database...");try{await oo(o.token,i),e.succeed("Database reset complete"),console.log(""),console.log(f__default.default.gray("Your database is now empty.")),console.log(f__default.default.gray("Run `vaif push` to apply your schema, then `vaif db seed` to seed data.")),console.log("");}catch(s){e.fail("Failed to reset database"),s instanceof Error&&console.log(f__default.default.red(`
|
|
3811
|
+
Error: ${s.message}`)),process.exit(1);}}var Xe=process.env.VAIF_API_URL||"https://api.vaif.studio";function Qe(t,e,o){return t.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||o.projectId||null}async function Ze(t){let e=Q__default.default(),o=I();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let i=Qe(t,r,o);i||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let s=t.name||`cli-key-${Date.now()}`;console.log(""),console.log(f__default.default.bold("VAIF Generate API Key")),console.log(""),e.start("Generating API key...");try{let a=await fetch(`${Xe}/v1/projects/${i}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:s})});if(!a.ok){let d=await a.text();throw new Error(`Failed to generate key: ${d}`)}let l=await a.json();e.succeed("API key generated"),console.log(""),console.log(f__default.default.green(` Name: ${l.name}`)),console.log(f__default.default.green(` Key: ${l.key}`)),console.log(""),console.log(f__default.default.yellow.bold(" Save this key now - it will not be shown again!")),console.log("");}catch(a){e.fail("Failed to generate API key"),a instanceof Error&&console.log(f__default.default.red(`
|
|
3812
|
+
Error: ${a.message}`)),process.exit(1);}}async function et(t){let e=Q__default.default(),o=I();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let i=Qe(t,r,o);i||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF API Keys")),console.log(""),e.start("Fetching API keys...");try{let s=await fetch(`${Xe}/v1/projects/${i}/api-keys`,{headers:{Authorization:`Bearer ${o.token}`}});if(!s.ok){let p=await s.text();throw new Error(`Failed to list keys: ${p}`)}let a=await s.json(),l=a.keys||a;if(e.stop(),!Array.isArray(l)||l.length===0){console.log(f__default.default.yellow("No API keys found")),console.log(f__default.default.gray(`
|
|
3813
|
+
Generate one with: vaif keys generate`));return}let d=Math.max(8,...l.map(p=>(p.name||"").length)),u=` ${"Name".padEnd(d)} ${"Key".padEnd(24)} Created`;console.log(f__default.default.gray(u)),console.log(f__default.default.gray(" "+"-".repeat(u.length-2)));for(let p of l){let c=(p.name||"unnamed").padEnd(d),g=p.maskedKey||p.prefix||`${(p.key||"").slice(0,12)}...`,h=p.createdAt?new Date(p.createdAt).toLocaleDateString():"N/A";console.log(` ${c} ${g.padEnd(24)} ${h}`);}console.log(""),console.log(f__default.default.gray(` ${l.length} key(s) total`)),console.log("");}catch(s){e.fail("Failed to list API keys"),s instanceof Error&&console.log(f__default.default.red(`
|
|
3814
|
+
Error: ${s.message}`)),process.exit(1);}}var z=process.env.VAIF_API_URL||"https://api.vaif.studio";function ao(t,e,o){return t.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||o.projectId||null}function te(){let t=I();return (!t||!t.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1)),t}async function oe(t){try{return await A(t||"vaif.config.json")}catch{return null}}function ne(t,e,o){let n=ao(t,e,o);return n||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),n}async function tt(t,e,o){let n=Q__default.default(),r=te(),i=await oe(o.config),s=ne(o,i,r),a=e;if(o.fromFile)try{a=U__default.default.readFileSync(o.fromFile,"utf-8");}catch(l){console.log(f__default.default.red(`Failed to read file: ${o.fromFile}`)),l instanceof Error&&console.log(f__default.default.gray(l.message)),process.exit(1);}a||(console.log(f__default.default.red("No value provided")),console.log(f__default.default.gray("Provide a value as argument or use --from-file <path>")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF Set Secret")),console.log(""),n.start("Checking for existing secret...");try{let l=new URL(`${z}/functions/secrets/project/${s}`);o.envId&&l.searchParams.set("envId",o.envId);let d=await fetch(l.toString(),{headers:{Authorization:`Bearer ${r.token}`}});if(!d.ok)throw new Error(`Failed to check existing secrets: ${await d.text()}`);let p=(await d.json()).find(c=>c.key===t);if(p){n.text=`Updating secret "${t}"...`;let c=await fetch(`${z}/functions/secrets/${p.id}`,{method:"PUT",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({value:a})});if(!c.ok)throw new Error(`Failed to update secret: ${await c.text()}`);n.succeed(`Updated secret "${t}"`);}else {n.text=`Creating secret "${t}"...`;let c=await fetch(`${z}/functions/secrets`,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:s,envId:o.envId,key:t,value:a})});if(!c.ok)throw new Error(`Failed to create secret: ${await c.text()}`);n.succeed(`Created secret "${t}"`);}console.log("");}catch(l){n.fail("Failed to set secret"),l instanceof Error&&console.log(f__default.default.red(`
|
|
3815
|
+
Error: ${l.message}`)),process.exit(1);}}async function ot(t){let e=Q__default.default(),o=te(),n=await oe(t.config),r=ne(t,n,o);console.log(""),console.log(f__default.default.bold("VAIF Secrets")),console.log(""),e.start("Fetching secrets...");try{let i=new URL(`${z}/functions/secrets/project/${r}`);t.envId&&i.searchParams.set("envId",t.envId);let s=await fetch(i.toString(),{headers:{Authorization:`Bearer ${o.token}`}});if(!s.ok)throw new Error(`Failed to list secrets: ${await s.text()}`);let a=await s.json();if(e.stop(),a.length===0){console.log(f__default.default.yellow("No secrets found")),console.log(f__default.default.gray(`
|
|
3816
|
+
Create one with: vaif secrets set <name> <value>`));return}let l=Math.max(8,...a.map(u=>u.key.length)),d=` ${"Name".padEnd(l)} Created`;console.log(f__default.default.gray(d)),console.log(f__default.default.gray(" "+"-".repeat(d.length-2)));for(let u of a){let p=u.key.padEnd(l),c=u.createdAt?new Date(u.createdAt).toLocaleDateString():"N/A";console.log(` ${p} ${c}`);}console.log(""),console.log(f__default.default.gray(` ${a.length} secret(s) total`)),console.log(f__default.default.gray(" Values are hidden. Use `vaif secrets get <name>` to reveal.")),console.log("");}catch(i){e.fail("Failed to list secrets"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3817
|
+
Error: ${i.message}`)),process.exit(1);}}async function nt(t,e){let o=Q__default.default(),n=te(),r=await oe(e.config),i=ne(e,r,n);console.log(""),o.start("Fetching secret...");try{let s=new URL(`${z}/functions/secrets/project/${i}`);e.envId&&s.searchParams.set("envId",e.envId);let a=await fetch(s.toString(),{headers:{Authorization:`Bearer ${n.token}`}});if(!a.ok)throw new Error(`Failed to fetch secrets: ${await a.text()}`);let d=(await a.json()).find(c=>c.key===t);d||(o.fail(`Secret "${t}" not found`),process.exit(1));let u=await fetch(`${z}/functions/secrets/${d.id}/value`,{headers:{Authorization:`Bearer ${n.token}`}});if(!u.ok)throw new Error(`Failed to get secret value: ${await u.text()}`);let p=await u.json();o.stop(),console.log(p.value);}catch(s){o.fail("Failed to get secret"),s instanceof Error&&console.log(f__default.default.red(`
|
|
3818
|
+
Error: ${s.message}`)),process.exit(1);}}async function at(t,e){let o=Q__default.default(),n=te(),r=await oe(e.config),i=ne(e,r,n);console.log(""),console.log(f__default.default.bold("VAIF Delete Secret")),console.log(""),o.start("Finding secret...");try{let s=new URL(`${z}/functions/secrets/project/${i}`);e.envId&&s.searchParams.set("envId",e.envId);let a=await fetch(s.toString(),{headers:{Authorization:`Bearer ${n.token}`}});if(!a.ok)throw new Error(`Failed to fetch secrets: ${await a.text()}`);let d=(await a.json()).find(p=>p.key===t);d||(o.fail(`Secret "${t}" not found`),process.exit(1)),o.text=`Deleting secret "${t}"...`;let u=await fetch(`${z}/functions/secrets/${d.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}});if(!u.ok)throw new Error(`Failed to delete secret: ${await u.text()}`);o.succeed(`Deleted secret "${t}"`),console.log("");}catch(s){o.fail("Failed to delete secret"),s instanceof Error&&console.log(f__default.default.red(`
|
|
3819
|
+
Error: ${s.message}`)),process.exit(1);}}var it=process.env.VAIF_API_URL||"https://api.vaif.studio";function so(t){try{let e=new URL(t);return e.password&&(e.password="****"),e.toString()}catch{return t.replace(/:[^@/]+@/,":****@")}}async function st(t){let e=Q__default.default(),o=I();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let i=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),e.start("Fetching project info...");try{let s=await fetch(`${it}/v1/projects/${i}`,{headers:{Authorization:`Bearer ${o.token}`}});if(!s.ok){let u=await s.text();throw new Error(`Failed to fetch project: ${u}`)}let a=await s.json();e.stop(),console.log(""),console.log(f__default.default.bold("VAIF Project Info")),console.log("");let l=16,d=(u,p)=>{console.log(` ${f__default.default.gray(u.padEnd(l))} ${p}`);};d("Name:",f__default.default.white(a.name||"N/A")),d("Project ID:",f__default.default.white(i)),d("Region:",f__default.default.white(a.region||"us-east-1")),d("Plan:",f__default.default.white(a.plan||a.tier||"free")),d("Created:",f__default.default.white(a.createdAt?new Date(a.createdAt).toLocaleDateString():"N/A")),console.log(""),d("API URL:",f__default.default.cyan(a.apiUrl||`${it}/v1`)),d("WS URL:",f__default.default.cyan(a.wsUrl||a.realtimeUrl||"N/A")),d("DB URL:",f__default.default.cyan(a.databaseUrl?so(a.databaseUrl):"N/A")),d("Storage URL:",f__default.default.cyan(a.storageUrl||"N/A")),console.log("");}catch(s){e.fail("Failed to fetch project info"),s instanceof Error&&console.log(f__default.default.red(`
|
|
3820
|
+
Error: ${s.message}`)),process.exit(1);}}var lo=process.env.VAIF_API_URL||"https://api.vaif.studio";async function rt(t){let e=Q__default.default(),o=I();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let i=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;i||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),e.start("Fetching project status...");try{let s=await fetch(`${lo}/v1/projects/${i}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${o.token}`}});if(!s.ok){let h=await s.text();throw new Error(`Failed to fetch project status: ${h}`)}let a=await s.json();e.stop(),console.log(""),console.log(f__default.default.bold("VAIF Project Status")),console.log("");let l=22,d=(h,E)=>{console.log(` ${f__default.default.gray(h.padEnd(l))} ${E}`);};d("Project:",f__default.default.white(a.name||i)),d("Plan:",f__default.default.white(a.plan||a.tier||"free")),console.log(""),console.log(f__default.default.gray(" --- Resources ---")),console.log("");let u=a.tableCount??a.tables?.length??"N/A",p=a.functionCount??a.functions?.length??"N/A",c=a.bucketCount??a.storage?.buckets?.length??"N/A",g=a.activeConnections??a.connections??"N/A";d("Tables:",f__default.default.white(String(u))),d("Functions:",f__default.default.white(String(p))),d("Storage Buckets:",f__default.default.white(String(c))),d("Active Connections:",f__default.default.white(String(g))),a.usage&&(console.log(""),console.log(f__default.default.gray(" --- Usage ---")),console.log(""),a.usage.dbSize&&d("Database Size:",f__default.default.white(a.usage.dbSize)),a.usage.storageSize&&d("Storage Size:",f__default.default.white(a.usage.storageSize)),a.usage.bandwidth&&d("Bandwidth:",f__default.default.white(a.usage.bandwidth)),a.usage.functionInvocations!=null&&d("Function Invocations:",f__default.default.white(String(a.usage.functionInvocations)))),console.log("");}catch(s){e.fail("Failed to fetch project status"),s instanceof Error&&console.log(f__default.default.red(`
|
|
3821
|
+
Error: ${s.message}`)),process.exit(1);}}var G=process.env.VAIF_API_URL||"https://api.vaif.studio";function po(t,e,o){return t.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||o.projectId||null}function uo(t){if(!t||t.length===0)return "*No tables found. Create tables in the VAIF Studio dashboard.*";let e="";for(let o of t){e+=`### \`${o.name}\`
|
|
3822
|
+
|
|
3823
|
+
`,e+=`| Column | Type | Nullable | Default | Constraints |
|
|
3824
|
+
`,e+=`|--------|------|----------|---------|-------------|
|
|
3825
|
+
`;for(let n of o.columns){let r=[];n.isPrimaryKey&&r.push("PK"),n.nullable||r.push("NOT NULL");let i=o.foreignKeys?.find(s=>s.column===n.name);i&&r.push(`FK \u2192 ${i.foreignTable}.${i.foreignColumn}`),e+=`| ${n.name} | ${n.type} | ${n.nullable?"yes":"no"} | ${n.defaultValue||"-"} | ${r.join(", ")||"-"} |
|
|
3826
|
+
`;}e+=`
|
|
3827
|
+
`;}return e}function fo(t,e,o){let n=t.slice(0,3);if(n.length===0)return "";let r="";for(let i of n){let s=i.columns.filter(l=>!l.isPrimaryKey&&l.name!=="created_at"&&l.name!=="updated_at"),a=s.slice(0,3).map(l=>` ${l.name}: ${go(l)}`).join(`,
|
|
3828
|
+
`);r+=`### \`${i.name}\`
|
|
3829
|
+
|
|
3830
|
+
`,r+="```typescript\n",r+=`// Select all
|
|
3831
|
+
const ${i.name} = await vaif.from("${i.name}").select();
|
|
3832
|
+
|
|
3833
|
+
`,r+=`// Select with filter
|
|
3834
|
+
const filtered = await vaif.from("${i.name}").select().eq("${s[0]?.name||"id"}", value);
|
|
3835
|
+
|
|
3836
|
+
`,r+=`// Insert
|
|
3837
|
+
const created = await vaif.from("${i.name}").insert({
|
|
3838
|
+
${a}
|
|
3839
|
+
});
|
|
3840
|
+
|
|
3841
|
+
`,r+=`// Update
|
|
3842
|
+
await vaif.from("${i.name}").update(recordId, {
|
|
3843
|
+
${s[0]?.name||"name"}: newValue
|
|
3844
|
+
});
|
|
3845
|
+
|
|
3846
|
+
`,r+=`// Delete
|
|
3847
|
+
await vaif.from("${i.name}").delete(recordId);
|
|
3848
|
+
`,r+="```\n\n";}return r}function go(t){let e=t.type.toLowerCase();return e.includes("uuid")?'"crypto.randomUUID()"':e.includes("int")||e.includes("serial")?"42":e.includes("bool")?"true":e.includes("timestamp")||e.includes("date")?'"new Date().toISOString()"':e.includes("json")?"{}":e.includes("float")||e.includes("numeric")||e.includes("decimal")||e.includes("double")?"3.14":`"example_${t.name}"`}function mo(t){let{projectId:e,apiKey:o,apiUrl:n,projectName:r,schema:i}=t,s=uo(i.tables),a=fo(i.tables);return `# VAIF Studio Backend
|
|
3849
|
+
|
|
3850
|
+
This project uses **VAIF Studio** as its backend. Project: **${r}** (\`${e}\`).
|
|
3851
|
+
|
|
3852
|
+
## SDK Setup
|
|
3853
|
+
|
|
3854
|
+
\`\`\`bash
|
|
3855
|
+
npm install @vaiftech/client
|
|
3856
|
+
\`\`\`
|
|
3857
|
+
|
|
3858
|
+
\`\`\`typescript
|
|
3859
|
+
import { createVaifClient } from "@vaiftech/client";
|
|
3860
|
+
|
|
3861
|
+
const vaif = createVaifClient({
|
|
3862
|
+
baseUrl: "${n}",
|
|
3863
|
+
projectId: "${e}",
|
|
3864
|
+
apiKey: "${o}",
|
|
3865
|
+
});
|
|
3866
|
+
\`\`\`
|
|
3867
|
+
|
|
3868
|
+
## Database Schema
|
|
3869
|
+
|
|
3870
|
+
${s}
|
|
3871
|
+
|
|
3872
|
+
## CRUD Examples
|
|
3873
|
+
|
|
3874
|
+
${a}
|
|
3875
|
+
|
|
3876
|
+
## Authentication
|
|
3877
|
+
|
|
3878
|
+
\`\`\`typescript
|
|
3879
|
+
import { createAuthClient } from "@vaiftech/auth";
|
|
3880
|
+
|
|
3881
|
+
const auth = createAuthClient({
|
|
3882
|
+
url: "${n}",
|
|
3883
|
+
apiKey: "${o}",
|
|
3884
|
+
});
|
|
3885
|
+
|
|
3886
|
+
// Sign up
|
|
3887
|
+
const { user, session } = await auth.signUp({
|
|
3888
|
+
email: "user@example.com",
|
|
3889
|
+
password: "securePassword123",
|
|
3890
|
+
});
|
|
3891
|
+
|
|
3892
|
+
// Sign in with password
|
|
3893
|
+
const { session } = await auth.signInWithPassword({
|
|
3894
|
+
email: "user@example.com",
|
|
3895
|
+
password: "securePassword123",
|
|
3896
|
+
});
|
|
3897
|
+
|
|
3898
|
+
// Sign in with OAuth
|
|
3899
|
+
await auth.signInWithOAuth({ provider: "google" });
|
|
3900
|
+
|
|
3901
|
+
// Session management
|
|
3902
|
+
const currentSession = await auth.getSession();
|
|
3903
|
+
await auth.signOut();
|
|
3904
|
+
|
|
3905
|
+
// Listen for auth state changes
|
|
3906
|
+
auth.onAuthStateChange((event) => {
|
|
3907
|
+
console.log("Auth event:", event.event, event.session);
|
|
3908
|
+
});
|
|
3909
|
+
\`\`\`
|
|
3910
|
+
|
|
3911
|
+
## Storage
|
|
3912
|
+
|
|
3913
|
+
\`\`\`typescript
|
|
3914
|
+
// Upload a file
|
|
3915
|
+
const { url } = await vaif.storage.upload("avatars", file, {
|
|
3916
|
+
contentType: "image/png",
|
|
3917
|
+
});
|
|
3918
|
+
|
|
3919
|
+
// Download a file
|
|
3920
|
+
const blob = await vaif.storage.download("avatars", "photo.png");
|
|
3921
|
+
|
|
3922
|
+
// Create a signed URL (expiring)
|
|
3923
|
+
const { signedUrl } = await vaif.storage.createSignedUrl("avatars", "photo.png", {
|
|
3924
|
+
expiresIn: 3600,
|
|
3925
|
+
});
|
|
3926
|
+
|
|
3927
|
+
// List files in a bucket
|
|
3928
|
+
const files = await vaif.storage.list("avatars", { limit: 100 });
|
|
3929
|
+
\`\`\`
|
|
3930
|
+
|
|
3931
|
+
## Functions
|
|
3932
|
+
|
|
3933
|
+
\`\`\`typescript
|
|
3934
|
+
// Invoke a serverless function
|
|
3935
|
+
const result = await vaif.functions.invoke("send-welcome-email", {
|
|
3936
|
+
body: { userId: "user_123", template: "welcome" },
|
|
3937
|
+
});
|
|
3938
|
+
\`\`\`
|
|
3939
|
+
|
|
3940
|
+
## Realtime
|
|
3941
|
+
|
|
3942
|
+
\`\`\`typescript
|
|
3943
|
+
// Subscribe to a channel
|
|
3944
|
+
const channel = vaif.realtime.channel("my-channel");
|
|
3945
|
+
|
|
3946
|
+
// Listen for postgres changes
|
|
3947
|
+
channel.on("postgres_changes", {
|
|
3948
|
+
event: "INSERT",
|
|
3949
|
+
schema: "public",
|
|
3950
|
+
table: "messages",
|
|
3951
|
+
}, (payload) => {
|
|
3952
|
+
console.log("New message:", payload.new);
|
|
3953
|
+
});
|
|
3954
|
+
|
|
3955
|
+
// Listen for UPDATE events
|
|
3956
|
+
channel.on("postgres_changes", {
|
|
3957
|
+
event: "UPDATE",
|
|
3958
|
+
schema: "public",
|
|
3959
|
+
table: "messages",
|
|
3960
|
+
}, (payload) => {
|
|
3961
|
+
console.log("Updated:", payload.new, "was:", payload.old);
|
|
3962
|
+
});
|
|
3963
|
+
|
|
3964
|
+
// Listen for DELETE events
|
|
3965
|
+
channel.on("postgres_changes", {
|
|
3966
|
+
event: "DELETE",
|
|
3967
|
+
schema: "public",
|
|
3968
|
+
table: "messages",
|
|
3969
|
+
}, (payload) => {
|
|
3970
|
+
console.log("Deleted:", payload.old);
|
|
3971
|
+
});
|
|
3972
|
+
|
|
3973
|
+
// Subscribe to start receiving events
|
|
3974
|
+
channel.subscribe();
|
|
3975
|
+
|
|
3976
|
+
// Unsubscribe when done
|
|
3977
|
+
channel.unsubscribe();
|
|
3978
|
+
\`\`\`
|
|
3979
|
+
|
|
3980
|
+
## API Reference Notes
|
|
3981
|
+
|
|
3982
|
+
### Filter Syntax
|
|
3983
|
+
|
|
3984
|
+
The SDK supports these filter operators:
|
|
3985
|
+
|
|
3986
|
+
| Operator | Description | Example |
|
|
3987
|
+
|----------|-------------|---------|
|
|
3988
|
+
| \`eq\` | Equal | \`.eq("status", "active")\` |
|
|
3989
|
+
| \`neq\` | Not equal | \`.neq("status", "deleted")\` |
|
|
3990
|
+
| \`gt\` | Greater than | \`.gt("age", 18)\` |
|
|
3991
|
+
| \`lt\` | Less than | \`.lt("price", 100)\` |
|
|
3992
|
+
| \`gte\` | Greater than or equal | \`.gte("score", 90)\` |
|
|
3993
|
+
| \`lte\` | Less than or equal | \`.lte("count", 10)\` |
|
|
3994
|
+
| \`in\` | In array | \`.in("role", ["admin", "editor"])\` |
|
|
3995
|
+
| \`like\` | Pattern match (case-sensitive) | \`.like("name", "%john%")\` |
|
|
3996
|
+
| \`ilike\` | Pattern match (case-insensitive) | \`.ilike("name", "%john%")\` |
|
|
3997
|
+
| \`is\` | IS comparison (null, true, false) | \`.is("deleted_at", null)\` |
|
|
3998
|
+
|
|
3999
|
+
### Pagination
|
|
4000
|
+
|
|
4001
|
+
\`\`\`typescript
|
|
4002
|
+
// Default: limit 20, offset 0
|
|
4003
|
+
const page1 = await vaif.from("posts").select().limit(20).offset(0);
|
|
4004
|
+
const page2 = await vaif.from("posts").select().limit(20).offset(20);
|
|
4005
|
+
\`\`\`
|
|
4006
|
+
|
|
4007
|
+
### Auth Headers
|
|
4008
|
+
|
|
4009
|
+
All authenticated requests require:
|
|
4010
|
+
- \`Authorization: Bearer <jwt_token>\` \u2014 for user-scoped requests
|
|
4011
|
+
- \`x-api-key: <api_key>\` \u2014 for server-side / service-role requests
|
|
4012
|
+
- \`x-project-id: ${e}\` \u2014 identifies the project
|
|
4013
|
+
`}async function ct(t){let e=Q__default.default(),o=I();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let i=po(t,r,o);i||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let s=S__default.default.resolve(t.outputDir||".");console.log(""),console.log(f__default.default.bold("VAIF Claude Code Setup")),console.log(f__default.default.gray(` Project: ${i}`)),console.log(""),e.start("Fetching database schema...");let a={tables:[]};try{let p=await fetch(`${G}/schema-engine/introspect/${i}`,{headers:{Authorization:`Bearer ${o.token}`}});p.ok?(a=await p.json(),e.succeed(`Fetched schema (${a.tables?.length||0} tables)`)):e.warn("Could not fetch schema \u2014 continuing without it");}catch{e.warn("Could not fetch schema \u2014 continuing without it");}e.start("Fetching project info...");let l=i,d=G;try{let p=await fetch(`${G}/v1/projects/${i}`,{headers:{Authorization:`Bearer ${o.token}`}});if(p.ok){let c=await p.json();l=c.name||i,d=c.apiUrl||G,e.succeed(`Project: ${l}`);}else e.warn("Could not fetch project info \u2014 using defaults");}catch{e.warn("Could not fetch project info \u2014 using defaults");}let u=t.apiKey||r?.api?.apiKey||"";if(!u){e.start("Generating API key for Claude Code...");try{let p=`claude-code-${Date.now()}`,c=await fetch(`${G}/v1/projects/${i}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:p})});c.ok?(u=(await c.json()).key,e.succeed(`Generated API key: ${p}`)):(e.fail("Could not auto-generate API key"),console.log(f__default.default.yellow(" Pass one with --api-key or generate via `vaif keys generate`")),process.exit(1));}catch{e.fail("Could not auto-generate API key"),console.log(f__default.default.yellow(" Pass one with --api-key or generate via `vaif keys generate`")),process.exit(1);}}if(!t.skipMcp){e.start("Writing .mcp.json...");let p={mcpServers:{"vaif-studio":{command:"npx",args:["@vaiftech/mcp"],env:{VAIF_API_KEY:u,VAIF_PROJECT_ID:i,VAIF_API_URL:d,VAIF_AUTH_TOKEN:o.token}}}},c=S__default.default.join(s,".mcp.json");U__default.default.writeFileSync(c,JSON.stringify(p,null,2)+`
|
|
4014
|
+
`,"utf-8"),e.succeed(`Written ${f__default.default.cyan(".mcp.json")}`);}if(!t.skipClaudeMd){e.start("Writing CLAUDE.md...");let p=mo({projectId:i,apiKey:u,apiUrl:d,projectName:l,schema:a}),c=S__default.default.join(s,"CLAUDE.md");U__default.default.writeFileSync(c,p,"utf-8"),e.succeed(`Written ${f__default.default.cyan("CLAUDE.md")}`);}console.log(""),console.log(f__default.default.green.bold(" Claude Code integration configured!")),console.log(""),t.skipMcp||console.log(f__default.default.gray(" MCP Server: ")+f__default.default.white(".mcp.json")),t.skipClaudeMd||console.log(f__default.default.gray(" Context: ")+f__default.default.white("CLAUDE.md")),console.log(""),console.log(f__default.default.bold(" Next steps:")),console.log(f__default.default.gray(" 1. Open this project in Claude Code")),console.log(f__default.default.gray(" 2. The MCP server auto-connects to your VAIF project")),console.log(f__default.default.gray(" 3. Ask Claude to query, modify, or build against your schema")),console.log("");}var dt="1.8.0",he=f__default.default.hex("#00f0ff"),ye=f__default.default.hex("#7b61ff"),ve=f__default.default.hex("#ff3dff"),be=f__default.default.hex("#00ff9d"),w=f__default.default.hex("#555570"),B=f__default.default.hex("#00f0ff");function ho(){console.log(""),console.log(he(" \u2566 \u2566")+ye("\u2554\u2550\u2557\u2566")+ve("\u2554\u2550\u2557 ")+be("\u2554\u2550\u2557\u2566 \u2566")),console.log(he(" \u255A\u2557\u2554\u255D")+ye("\u2560\u2550\u2563\u2551")+ve("\u2560\u2563 ")+be("\u2551 \u2551 \u2551")),console.log(he(" \u255A\u255D ")+ye("\u2569 \u2569\u2569")+ve("\u255A ")+be("\u255A\u2550\u255D\u2569\u2550\u255D\u2569")),console.log(""),console.log(w(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(B(" VAIF Studio CLI")+w(` v${dt}`)),console.log(w(" Build full-stack apps at lightning speed")),console.log(w(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(""),console.log(f__default.default.bold(" Quick Start")),console.log(w(" $ ")+B("vaif login")+w(" Authenticate")),console.log(w(" $ ")+B("vaif init -t react-spa")+w(" Scaffold project")),console.log(w(" $ ")+B("vaif db push")+w(" Push migrations")),console.log(w(" $ ")+B("vaif generate")+w(" Generate types")),console.log(w(" $ ")+B("vaif functions deploy")+w(" Deploy functions")),console.log(""),console.log(f__default.default.bold(" Categories")),console.log(w(" auth ")+f__default.default.white("login, logout, whoami")),console.log(w(" project ")+f__default.default.white("init, templates, info, status")),console.log(w(" schema ")+f__default.default.white("pull, push, generate")),console.log(w(" database ")+f__default.default.white("db push, db pull, db seed, db reset")),console.log(w(" deploy ")+f__default.default.white("functions deploy, functions list")),console.log(w(" security ")+f__default.default.white("keys, secrets")),console.log(w(" ai ")+f__default.default.white("claude-setup")),console.log(""),console.log(w(" Run ")+B("vaif <command> --help")+w(" for details")),console.log(w(" Docs: ")+f__default.default.underline("https://docs.vaif.studio")),console.log("");}commander.program.name("vaif").description("VAIF CLI - Type generation and development tools").version(dt);commander.program.command("login").description("Authenticate with VAIF (opens browser)").option("-e, --email","Login with email/password instead of browser").option("-p, --project-id <id>","Default project ID").action(Te);commander.program.command("logout").description("Log out and remove stored credentials").action(Pe);commander.program.command("whoami").description("Show current authenticated user").action(Fe);commander.program.command("init").description("Initialize VAIF configuration in your project").option("--typescript","Setup for TypeScript project").option("-f, --force","Overwrite existing config").option("-t, --template <name>","Scaffold from a template (run vaif templates for list)").option("--features <features>","Comma-separated features to include: auth,database,realtime,storage,functions").option("--add-features <features>","Add features to an existing project (requires --template)").action(Le);commander.program.command("templates").alias("tpl").description("List available project templates").action(ke);commander.program.command("info").description("Show project information (name, region, URLs)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(st);commander.program.command("status").description("Show project status (tables, functions, storage, connections)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(rt);commander.program.command("pull").description("Pull database schema from your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-o, --output <path>","Output file path","vaif.schema.json").option("-s, --schema <name>","Schema name","public").option("-p, --project-id <id>","Project ID (overrides config)").action(Ne);commander.program.command("push").description("Push local schema changes to your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-s, --schema <path>","Schema file path","vaif.schema.json").option("-p, --project-id <id>","Project ID (overrides config)").option("--dry-run","Preview changes without applying").option("-f, --force","Apply changes without confirmation").action($e);commander.program.command("generate").alias("gen").description("Generate TypeScript types from your database schema").option("-c, --connection <url>","Database connection string").option("-o, --output <path>","Output file path","./src/types/database.ts").option("--schema <name>","Schema name","public").option("--config <path>","Config file path","vaif.config.json").option("--dry-run","Preview generated types without writing").action(je);var pt=commander.program.command("functions").alias("fn").description("Manage serverless functions");pt.command("deploy").description("Deploy functions to your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID").option("-n, --name <name>","Function name filter").option("-r, --runtime <runtime>","Runtime (nodejs, typescript, python)").option("--entrypoint <file>","Specific entrypoint file").option("--dry-run","Preview deployment without deploying").action(ze);pt.command("list").alias("ls").description("List deployed functions").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID").action(Be);var ae=commander.program.command("db").description("Database management commands");ae.command("push").description("Push local Drizzle migrations to VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-d, --dir <path>","Migrations directory","./drizzle").option("--dry-run","Preview without applying").action(Je);ae.command("pull").description("Pull schema from VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-o, --output <path>","Output file","vaif.schema.json").action(Ge);ae.command("seed").description("Seed your database with test data").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --file <path>","Specific seed file").option("-t, --table <name>","Seed specific table only").option("--truncate","Truncate tables before seeding").option("--dry-run","Preview seeding without inserting data").action(Ye);ae.command("reset").description("Reset database (drop all tables and data)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --force","Confirm reset (required)").action(We);var ut=commander.program.command("keys").description("Manage API keys");ut.command("generate").description("Generate a new API key").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-n, --name <name>","Key name").action(Ze);ut.command("list").alias("ls").description("List API keys").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(et);var ie=commander.program.command("secrets").alias("sec").description("Manage function secrets");ie.command("set <name> [value]").description("Create or update a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").option("--from-file <path>","Read secret value from a file").action(tt);ie.command("list").alias("ls").description("List all secrets (names only)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(ot);ie.command("get <name>").description("Reveal a secret value").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(nt);ie.command("delete <name>").description("Delete a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(at);commander.program.command("claude-setup").description("Configure Claude Code integration (MCP server + CLAUDE.md)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID").option("-k, --api-key <key>","API key for MCP server").option("--skip-mcp","Skip generating .mcp.json").option("--skip-claude-md","Skip generating CLAUDE.md").option("-o, --output-dir <dir>","Output directory",".").action(ct);process.argv.slice(2).length||(ho(),process.exit(0));commander.program.parse(process.argv);
|