@vaiftech/cli 1.6.0 → 1.6.1
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 +5 -1
- package/dist/{chunk-UQZPP43V.js → chunk-RBCJFCBE.js} +30 -28
- package/dist/cli.cjs +49 -47
- package/dist/cli.js +27 -27
- package/dist/index.cjs +22 -20
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/cli.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';var commander=require('commander'),N=require('fs'),A=require('path'),et=require('pg'),q=require('ora'),f=require('chalk'),ot=require('prettier'),Ze=require('dotenv'),pe=require('readline'),pt=require('os'),child_process=require('child_process');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var N__default=/*#__PURE__*/_interopDefault(N);var A__default=/*#__PURE__*/_interopDefault(A);var et__default=/*#__PURE__*/_interopDefault(et);var q__default=/*#__PURE__*/_interopDefault(q);var f__default=/*#__PURE__*/_interopDefault(f);var ot__default=/*#__PURE__*/_interopDefault(ot);var Ze__default=/*#__PURE__*/_interopDefault(Ze);var pe__default=/*#__PURE__*/_interopDefault(pe);var pt__default=/*#__PURE__*/_interopDefault(pt);Ze__default.default.config();async function I(t){let e=A__default.default.resolve(t);if(!N__default.default.existsSync(e))return null;try{let o=N__default.default.readFileSync(e,"utf-8"),n=JSON.parse(o);return n.database?.url&&(n.database.url=le(n.database.url)),n.api?.apiKey&&(n.api.apiKey=le(n.api.apiKey)),n}catch{throw new Error(`Failed to parse config file: ${t}`)}}function le(t){return t.replace(/\$\{([^}]+)\}/g,(e,o)=>process.env[o]||e)}async function nt(t,e){let o=await t.query(`
|
|
2
|
+
'use strict';require('dotenv/config');var commander=require('commander'),N=require('fs'),A=require('path'),et=require('pg'),q=require('ora'),f=require('chalk'),ot=require('prettier'),Ze=require('dotenv'),pe=require('readline'),pt=require('os'),child_process=require('child_process');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var N__default=/*#__PURE__*/_interopDefault(N);var A__default=/*#__PURE__*/_interopDefault(A);var et__default=/*#__PURE__*/_interopDefault(et);var q__default=/*#__PURE__*/_interopDefault(q);var f__default=/*#__PURE__*/_interopDefault(f);var ot__default=/*#__PURE__*/_interopDefault(ot);var Ze__default=/*#__PURE__*/_interopDefault(Ze);var pe__default=/*#__PURE__*/_interopDefault(pe);var pt__default=/*#__PURE__*/_interopDefault(pt);Ze__default.default.config();async function I(t){let e=A__default.default.resolve(t);if(!N__default.default.existsSync(e))return null;try{let o=N__default.default.readFileSync(e,"utf-8"),n=JSON.parse(o);return n.database?.url&&(n.database.url=le(n.database.url)),n.api?.apiKey&&(n.api.apiKey=le(n.api.apiKey)),n}catch{throw new Error(`Failed to parse config file: ${t}`)}}function le(t){return t.replace(/\$\{([^}]+)\}/g,(e,o)=>process.env[o]||e)}async function nt(t,e){let o=await t.query(`
|
|
3
3
|
SELECT table_name, table_type
|
|
4
4
|
FROM information_schema.tables
|
|
5
5
|
WHERE table_schema = $1
|
|
@@ -82,6 +82,7 @@ Make sure your database is running and accessible.`))),process.exit(1);}}var O=[
|
|
|
82
82
|
"@types/node": "^22.0.0",
|
|
83
83
|
"@types/react": "^19.0.0",
|
|
84
84
|
"@types/react-dom": "^19.0.0",
|
|
85
|
+
"drizzle-kit": "^0.30.0",
|
|
85
86
|
"typescript": "^5.7.0"
|
|
86
87
|
}
|
|
87
88
|
}
|
|
@@ -151,18 +152,17 @@ body {
|
|
|
151
152
|
-webkit-font-smoothing: antialiased;
|
|
152
153
|
-moz-osx-font-smoothing: grayscale;
|
|
153
154
|
}
|
|
154
|
-
`},{path:"lib/vaif.ts",content:`import {
|
|
155
|
-
import { createServerClient } from "@vaiftech/client/server";
|
|
155
|
+
`},{path:"lib/vaif.ts",content:`import { createVaifClient } from "@vaiftech/client";
|
|
156
156
|
|
|
157
157
|
// Browser client \u2013 safe to use in Client Components
|
|
158
|
-
export const vaif =
|
|
158
|
+
export const vaif = createVaifClient({
|
|
159
159
|
projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
|
|
160
160
|
apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
|
|
161
161
|
});
|
|
162
162
|
|
|
163
163
|
// Server client \u2013 use in Server Components, Route Handlers, Server Actions
|
|
164
164
|
export function createVaifServer() {
|
|
165
|
-
return
|
|
165
|
+
return createVaifClient({
|
|
166
166
|
projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
|
|
167
167
|
secretKey: process.env.VAIF_SECRET_KEY!,
|
|
168
168
|
});
|
|
@@ -275,7 +275,7 @@ A full-stack Next.js application powered by [VAIF Studio](https://vaif.studio),
|
|
|
275
275
|
|
|
276
276
|
Full documentation is available at <https://docs.vaif.studio>.
|
|
277
277
|
`}],featureFiles:{auth:[{path:"middleware.ts",content:`import { NextResponse, type NextRequest } from "next/server";
|
|
278
|
-
import {
|
|
278
|
+
import { createVaifClient } from "@vaiftech/client";
|
|
279
279
|
import { authMiddleware } from "@vaiftech/auth/nextjs";
|
|
280
280
|
|
|
281
281
|
const protectedRoutes = ["/dashboard", "/settings", "/api/protected"];
|
|
@@ -285,7 +285,7 @@ export async function middleware(request: NextRequest) {
|
|
|
285
285
|
const isProtected = protectedRoutes.some((route) => pathname.startsWith(route));
|
|
286
286
|
if (!isProtected) return NextResponse.next();
|
|
287
287
|
|
|
288
|
-
const vaif =
|
|
288
|
+
const vaif = createVaifClient({
|
|
289
289
|
projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
|
|
290
290
|
secretKey: process.env.VAIF_SECRET_KEY!,
|
|
291
291
|
});
|
|
@@ -553,9 +553,11 @@ export const posts = pgTable("posts", {
|
|
|
553
553
|
"react-router-dom": "^7.0.0"
|
|
554
554
|
},
|
|
555
555
|
"devDependencies": {
|
|
556
|
+
"@types/node": "^22.0.0",
|
|
556
557
|
"@types/react": "^19.0.0",
|
|
557
558
|
"@types/react-dom": "^19.0.0",
|
|
558
559
|
"@vitejs/plugin-react": "^4.4.0",
|
|
560
|
+
"drizzle-kit": "^0.30.0",
|
|
559
561
|
"typescript": "^5.7.0",
|
|
560
562
|
"vite": "^6.0.0"
|
|
561
563
|
}
|
|
@@ -643,9 +645,9 @@ function Home() {
|
|
|
643
645
|
</div>
|
|
644
646
|
);
|
|
645
647
|
}
|
|
646
|
-
`},{path:"src/lib/vaif.ts",content:`import {
|
|
648
|
+
`},{path:"src/lib/vaif.ts",content:`import { createVaifClient } from "@vaiftech/client";
|
|
647
649
|
|
|
648
|
-
export const vaif =
|
|
650
|
+
export const vaif = createVaifClient({
|
|
649
651
|
projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
|
|
650
652
|
apiKey: import.meta.env.VITE_VAIF_API_KEY,
|
|
651
653
|
});
|
|
@@ -1270,7 +1272,9 @@ Full documentation is available at <https://docs.vaif.studio>.
|
|
|
1270
1272
|
"react-native": "~0.76.0"
|
|
1271
1273
|
},
|
|
1272
1274
|
"devDependencies": {
|
|
1275
|
+
"@types/node": "^22.0.0",
|
|
1273
1276
|
"@types/react": "^19.0.0",
|
|
1277
|
+
"drizzle-kit": "^0.30.0",
|
|
1274
1278
|
"typescript": "^5.7.0"
|
|
1275
1279
|
}
|
|
1276
1280
|
}
|
|
@@ -2594,9 +2598,9 @@ func HelloHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
2594
2598
|
Message: fmt.Sprintf("Hello, %s!", req.Name),
|
|
2595
2599
|
})
|
|
2596
2600
|
}
|
|
2597
|
-
`}]},postInstructions:["go mod tidy","# Copy .env.example to .env and add your VAIF credentials","go run main.go"]},"todo-app":{name:"Todo App",description:"Simple React todo app \u2013 great for learning VAIF basics",tag:"React Starter",defaultFeatures:["database"],files:[{path:"src/lib/vaif.ts",content:`import {
|
|
2601
|
+
`}]},postInstructions:["go mod tidy","# Copy .env.example to .env and add your VAIF credentials","go run main.go"]},"todo-app":{name:"Todo App",description:"Simple React todo app \u2013 great for learning VAIF basics",tag:"React Starter",defaultFeatures:["database"],files:[{path:"src/lib/vaif.ts",content:`import { createVaifClient } from "@vaiftech/client";
|
|
2598
2602
|
|
|
2599
|
-
export const vaif =
|
|
2603
|
+
export const vaif = createVaifClient({
|
|
2600
2604
|
projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
|
|
2601
2605
|
apiKey: import.meta.env.VITE_VAIF_API_KEY,
|
|
2602
2606
|
});
|
|
@@ -2785,9 +2789,9 @@ export const posts = pgTable("posts", {
|
|
|
2785
2789
|
|
|
2786
2790
|
return Response.json({ message: \`Hello, \${name}!\` });
|
|
2787
2791
|
}
|
|
2788
|
-
`}]},dependencies:["@vaiftech/client","@vaiftech/react"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Create a 'todos' table in your VAIF dashboard with columns: id (uuid), title (text), done (boolean), created_at (timestamptz)","Import helpers from './lib/vaif' in your components","Run: npx vaif generate to generate TypeScript types"]},"realtime-chat":{name:"Realtime Chat",description:"React chat app with VAIF realtime subscriptions for live messaging",tag:"React + Realtime",defaultFeatures:["database","realtime","auth"],files:[{path:"src/lib/vaif.ts",content:`import {
|
|
2792
|
+
`}]},dependencies:["@vaiftech/client","@vaiftech/react"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Create a 'todos' table in your VAIF dashboard with columns: id (uuid), title (text), done (boolean), created_at (timestamptz)","Import helpers from './lib/vaif' in your components","Run: npx vaif generate to generate TypeScript types"]},"realtime-chat":{name:"Realtime Chat",description:"React chat app with VAIF realtime subscriptions for live messaging",tag:"React + Realtime",defaultFeatures:["database","realtime","auth"],files:[{path:"src/lib/vaif.ts",content:`import { createVaifClient } from "@vaiftech/client";
|
|
2789
2793
|
|
|
2790
|
-
export const vaif =
|
|
2794
|
+
export const vaif = createVaifClient({
|
|
2791
2795
|
projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
|
|
2792
2796
|
apiKey: import.meta.env.VITE_VAIF_API_KEY,
|
|
2793
2797
|
realtime: {
|
|
@@ -3084,18 +3088,17 @@ export const posts = pgTable("posts", {
|
|
|
3084
3088
|
|
|
3085
3089
|
return Response.json({ message: \`Hello, \${name}!\` });
|
|
3086
3090
|
}
|
|
3087
|
-
`}]},dependencies:["@vaiftech/client","@vaiftech/react"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Create a 'messages' table with columns: id (uuid), content (text), user_id (text), username (text), channel_id (text), created_at (timestamptz)","Enable Realtime on the messages table in your VAIF dashboard","Use the useRealtimeMessages hook in your components","Run: npx vaif generate to generate TypeScript types"]},"saas-starter":{name:"SaaS Starter",description:"Full SaaS starter with VAIF auth, team/org support, and server-side helpers",tag:"Next.js SaaS",defaultFeatures:["database","auth","functions"],files:[{path:"lib/vaif.ts",content:`import {
|
|
3088
|
-
import { createServerClient } from "@vaiftech/client/server";
|
|
3091
|
+
`}]},dependencies:["@vaiftech/client","@vaiftech/react"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Create a 'messages' table with columns: id (uuid), content (text), user_id (text), username (text), channel_id (text), created_at (timestamptz)","Enable Realtime on the messages table in your VAIF dashboard","Use the useRealtimeMessages hook in your components","Run: npx vaif generate to generate TypeScript types"]},"saas-starter":{name:"SaaS Starter",description:"Full SaaS starter with VAIF auth, team/org support, and server-side helpers",tag:"Next.js SaaS",defaultFeatures:["database","auth","functions"],files:[{path:"lib/vaif.ts",content:`import { createVaifClient } from "@vaiftech/client";
|
|
3089
3092
|
|
|
3090
3093
|
// Browser client \u2013 use in Client Components
|
|
3091
|
-
export const vaif =
|
|
3094
|
+
export const vaif = createVaifClient({
|
|
3092
3095
|
projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
|
|
3093
3096
|
apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
|
|
3094
3097
|
});
|
|
3095
3098
|
|
|
3096
3099
|
// Server client \u2013 use in Server Components, Route Handlers, Server Actions
|
|
3097
3100
|
export function createVaifServer() {
|
|
3098
|
-
return
|
|
3101
|
+
return createVaifClient({
|
|
3099
3102
|
projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
|
|
3100
3103
|
secretKey: process.env.VAIF_SECRET_KEY!,
|
|
3101
3104
|
});
|
|
@@ -3395,18 +3398,17 @@ export const posts = pgTable("posts", {
|
|
|
3395
3398
|
|
|
3396
3399
|
return Response.json({ message: \`Hello, \${name}!\` });
|
|
3397
3400
|
}
|
|
3398
|
-
`}]},dependencies:["@vaiftech/client","@vaiftech/auth","@vaiftech/react"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create 'teams' and 'team_members' tables in your VAIF dashboard","Import auth helpers from '@/lib/auth' in your Server Components/Actions","Use requireUser() for authenticated routes and requireTeamRole() for role checks","Run: npx vaif generate to generate TypeScript types"]},"ecommerce-api":{name:"E-commerce API",description:"API-first e-commerce setup with VAIF storage for product images",tag:"Next.js E-commerce",defaultFeatures:["database","auth","storage"],files:[{path:"lib/vaif.ts",content:`import {
|
|
3399
|
-
import { createServerClient } from "@vaiftech/client/server";
|
|
3401
|
+
`}]},dependencies:["@vaiftech/client","@vaiftech/auth","@vaiftech/react"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create 'teams' and 'team_members' tables in your VAIF dashboard","Import auth helpers from '@/lib/auth' in your Server Components/Actions","Use requireUser() for authenticated routes and requireTeamRole() for role checks","Run: npx vaif generate to generate TypeScript types"]},"ecommerce-api":{name:"E-commerce API",description:"API-first e-commerce setup with VAIF storage for product images",tag:"Next.js E-commerce",defaultFeatures:["database","auth","storage"],files:[{path:"lib/vaif.ts",content:`import { createVaifClient } from "@vaiftech/client";
|
|
3400
3402
|
|
|
3401
3403
|
// Browser client
|
|
3402
|
-
export const vaif =
|
|
3404
|
+
export const vaif = createVaifClient({
|
|
3403
3405
|
projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
|
|
3404
3406
|
apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
|
|
3405
3407
|
});
|
|
3406
3408
|
|
|
3407
3409
|
// Server client
|
|
3408
3410
|
export function createVaifServer() {
|
|
3409
|
-
return
|
|
3411
|
+
return createVaifClient({
|
|
3410
3412
|
projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
|
|
3411
3413
|
secretKey: process.env.VAIF_SECRET_KEY!,
|
|
3412
3414
|
});
|
|
@@ -3669,51 +3671,51 @@ export const posts = pgTable("posts", {
|
|
|
3669
3671
|
`}]},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 fe(){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(ue))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 lt(t){if(!process.stdin.isTTY||!process.stdout.isTTY)return t;let e=new Set(t.map(n=>O.findIndex(r=>r.name===n)).filter(n=>n>=0)),o=0;return new Promise(n=>{let r=pe__default.default.createInterface({input:process.stdin,output:process.stdout});pe__default.default.emitKeypressEvents(process.stdin,r),process.stdin.setRawMode&&process.stdin.setRawMode(true);function l(){let a=O.length+2;process.stdout.write(`\x1B[${a}A`),i();}function i(){console.log(f__default.default.bold(`
|
|
3670
3672
|
? Which VAIF features do you want to include?`)),O.forEach((a,s)=>{let c=e.has(s)?f__default.default.green("[x]"):"[ ]",d=s===o?f__default.default.cyan("> "):" ";console.log(`${d}${c} ${a.label} ${f__default.default.gray(`(${a.description})`)}`);}),console.log(f__default.default.gray(" (up/down to move, space to toggle, enter to confirm)"));}i(),process.stdin.on("keypress",(a,s)=>{if(s.name==="up"&&o>0)o--,l();else if(s.name==="down"&&o<O.length-1)o++,l();else if(s.name==="space")e.has(o)?e.delete(o):e.add(o),l();else if(s.name==="return"){process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close();let c=[...e].sort().map(d=>O[d].name);n(c.length>0?c:t);}else s.name==="c"&&s.ctrl&&(process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close(),process.exit(0));});})}async function ge(t,e={}){let o=ue[t];o||(console.log(f__default.default.red(`
|
|
3671
3673
|
Unknown template: ${t}`)),console.log(f__default.default.yellow(`Run 'vaif templates' to see available templates.
|
|
3672
|
-
`)),process.exit(1));let n;e.features&&e.features.length>0?n=e.features.filter(c=>O.some(d=>d.name===c)):o.featureFiles&&Object.keys(o.featureFiles).length>0?n=await lt(o.defaultFeatures??["database","auth"]):n=o.defaultFeatures??[],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=[...o.files];if(o.featureFiles)for(let c of n){let d=o.featureFiles[c];d&&r.push(...d);}let l=0,i=0;for(let c of r){let d=A__default.default.resolve(c.path),u=A__default.default.dirname(d);if(N__default.default.existsSync(u)||N__default.default.mkdirSync(u,{recursive:true}),c.path==="package.json"&&N__default.default.existsSync(d)&&!e.force)try{let p=JSON.parse(N__default.default.readFileSync(d,"utf-8")),g=JSON.parse(c.content),b=C=>{if(!C)return {};let $={};for(let[Xe,
|
|
3674
|
+
`)),process.exit(1));let n;e.features&&e.features.length>0?n=e.features.filter(c=>O.some(d=>d.name===c)):o.featureFiles&&Object.keys(o.featureFiles).length>0?n=await lt(o.defaultFeatures??["database","auth"]):n=o.defaultFeatures??[],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=[...o.files];if(o.featureFiles)for(let c of n){let d=o.featureFiles[c];d&&r.push(...d);}let l=0,i=0;for(let c of r){let d=A__default.default.resolve(c.path),u=A__default.default.dirname(d);if(N__default.default.existsSync(u)||N__default.default.mkdirSync(u,{recursive:true}),c.path==="package.json"&&N__default.default.existsSync(d)&&!e.force)try{let p=JSON.parse(N__default.default.readFileSync(d,"utf-8")),g=JSON.parse(c.content),b=C=>{if(!C)return {};let $={};for(let[Xe,z]of Object.entries(C))!z.startsWith("workspace:")&&!z.startsWith("link:")&&!z.startsWith("file:")&&($[Xe]=z);return $};p.dependencies={...b(p.dependencies),...g.dependencies||{}},p.devDependencies={...b(p.devDependencies),...g.devDependencies||{}},g.scripts&&(p.scripts={...p.scripts||{},...g.scripts}),N__default.default.writeFileSync(d,JSON.stringify(p,null,2)+`
|
|
3673
3675
|
`,"utf-8"),console.log(f__default.default.green(` merge ${c.path} (added dependencies)`)),l++;continue}catch{}if(N__default.default.existsSync(d)&&!e.force){console.log(f__default.default.yellow(` skip ${c.path} (already exists)`)),i++;continue}N__default.default.writeFileSync(d,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":""}.`)),i>0&&console.log(f__default.default.yellow(`Skipped ${i} file${i!==1?"s":""} (use --force to overwrite).`));let a={auth:{"@vaiftech/auth":"^1.0.0"},database:{},realtime:{},storage:{},functions:{}},s=A__default.default.resolve("package.json");if(N__default.default.existsSync(s)&&n.length>0)try{let c=JSON.parse(N__default.default.readFileSync(s,"utf-8")),d=!1;for(let u of n){let p=a[u];if(p)for(let[g,b]of Object.entries(p))c.dependencies?.[g]||(c.dependencies=c.dependencies||{},c.dependencies[g]=b,d=!0);}d&&N__default.default.writeFileSync(s,JSON.stringify(c,null,2)+`
|
|
3674
3676
|
`,"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 dt={$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 me(t){let e=q__default.default("Initializing VAIF configuration...").start(),o=A__default.default.resolve("vaif.config.json");N__default.default.existsSync(o)&&!t.force&&(e.fail("vaif.config.json already exists"),console.log(f__default.default.yellow(`
|
|
3675
3677
|
Use --force to overwrite existing configuration.`)),process.exit(1));try{if(N__default.default.writeFileSync(o,JSON.stringify(dt,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 ge(t.template,{force:t.force,features:n});}else {let n=A__default.default.resolve(".env.example");if(N__default.default.existsSync(n)||(N__default.default.writeFileSync(n,`# VAIF Configuration
|
|
3676
3678
|
DATABASE_URL=postgresql://user:password@localhost:5432/database
|
|
3677
3679
|
VAIF_API_KEY=your-api-key
|
|
3678
3680
|
`,"utf-8"),console.log(f__default.default.gray("Created .env.example"))),t.typescript){let r=A__default.default.resolve("src/types");N__default.default.existsSync(r)||(N__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(`
|
|
3679
|
-
Error: ${n.message}`)),process.exit(1);}}var ae=A__default.default.join(pt__default.default.homedir(),".vaif"),
|
|
3681
|
+
Error: ${n.message}`)),process.exit(1);}}var ae=A__default.default.join(pt__default.default.homedir(),".vaif"),k=A__default.default.join(ae,"auth.json"),K=process.env.VAIF_API_URL||"https://api.vaif.studio";function ft(){N__default.default.existsSync(ae)||N__default.default.mkdirSync(ae,{recursive:true});}function ve(t){ft(),N__default.default.writeFileSync(k,JSON.stringify(t,null,2),"utf-8"),N__default.default.chmodSync(k,384);}function w(){if(!N__default.default.existsSync(k))return null;try{let t=N__default.default.readFileSync(k,"utf-8");return JSON.parse(t)}catch{return null}}function gt(t){let e=pe__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}function mt(t){return new Promise(e=>{let o=pe__default.default.createInterface({input:process.stdin,output:process.stdout});process.stdin;let r=process.stdout.write.bind(process.stdout),l=false;process.stdout.write=((...i)=>l?true:r(...i)),o.question(t,i=>{l=false,process.stdout.write=r,console.log(""),o.close(),e(i);}),l=true;})}function ht(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 yt(t){return new Promise(e=>setTimeout(e,t))}async function vt(t){try{let e=await fetch(`${K}/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 bt(t){let e=q__default.default();e.start("Setting up authentication...");let o,n;try{let a=await fetch(`${K}/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(`
|
|
3680
3682
|
Could not connect to VAIF API. Please try again later.`)),process.exit(1));let s=await a.json();o=s.code,n=s.url;}catch{e.fail("Failed to connect to VAIF API"),console.log(f__default.default.red(`
|
|
3681
|
-
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(""),ht(n),e.start("Waiting for browser authentication...");let r=12e4,l=2e3,i=Date.now();for(;Date.now()-i<r;){await yt(l);try{let a=await fetch(`${
|
|
3682
|
-
The authentication session expired. Please try again.`)),process.exit(1));continue}let s=await a.json();if(s.ok&&s.accessToken){let c={token:s.accessToken,email:s.user?.email,projectId:t,expiresAt:new Date(Date.now()+s.expiresIn*1e3).toISOString()};ve(c),e.succeed("Logged in successfully"),console.log(""),s.user?.email&&console.log(f__default.default.green(` Authenticated as: ${s.user.email}`)),console.log(f__default.default.gray(` Config saved to: ${
|
|
3683
|
+
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(""),ht(n),e.start("Waiting for browser authentication...");let r=12e4,l=2e3,i=Date.now();for(;Date.now()-i<r;){await yt(l);try{let a=await fetch(`${K}/auth/cli/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:o})});if(!a.ok){let c=await a.json();(c.error==="ExpiredCode"||c.error==="InvalidCode")&&(e.fail("Authentication expired"),console.log(f__default.default.red(`
|
|
3684
|
+
The authentication session expired. Please try again.`)),process.exit(1));continue}let s=await a.json();if(s.ok&&s.accessToken){let c={token:s.accessToken,email:s.user?.email,projectId:t,expiresAt:new Date(Date.now()+s.expiresIn*1e3).toISOString()};ve(c),e.succeed("Logged in successfully"),console.log(""),s.user?.email&&console.log(f__default.default.green(` Authenticated as: ${s.user.email}`)),console.log(f__default.default.gray(` Config saved to: ${k}`)),console.log("");return}}catch{}}e.fail("Authentication timed out"),console.log(f__default.default.red(`
|
|
3683
3685
|
Timed out waiting for browser authentication.`)),console.log(f__default.default.gray("Try again or use: vaif login --email")),process.exit(1);}async function It(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 gt(f__default.default.cyan(" Email: "));(!e||e.trim()==="")&&(console.log(f__default.default.red(`
|
|
3684
3686
|
No email provided. Login cancelled.`)),process.exit(1));let o=await mt(f__default.default.cyan(" Password: "));(!o||o.trim()==="")&&(console.log(f__default.default.red(`
|
|
3685
|
-
No password provided. Login cancelled.`)),process.exit(1));let n=q__default.default("Authenticating...").start();try{let r=await fetch(`${
|
|
3686
|
-
${l.message||"Invalid email or password."}`)),process.exit(1));let i={token:l.accessToken,email:l.user?.email,projectId:t,expiresAt:new Date(Date.now()+l.expiresIn*1e3).toISOString()};ve(i),n.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: ${
|
|
3687
|
-
Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function be(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 It(t.projectId):await bt(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 Ie(){N__default.default.existsSync(
|
|
3688
|
-
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 Et=process.env.VAIF_API_URL||"https://api.vaif.studio";async function
|
|
3689
|
-
Error: ${i}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(f__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let l=t.projectId||r.projectId||o.projectId;l||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
|
|
3690
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let i=t.schema||r.database?.schema||"public",a=await
|
|
3691
|
-
Error: ${i.message}`)),process.exit(1);}}var Ee=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ft(t){let e=pe__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}async function jt(t,e,o){let n=await fetch(`${Ee}/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 Ct(t,e,o){let n=await fetch(`${Ee}/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 Rt(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
|
|
3692
|
-
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 l=t.projectId||r.projectId||o.projectId;l||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
|
|
3687
|
+
No password provided. Login cancelled.`)),process.exit(1));let n=q__default.default("Authenticating...").start();try{let r=await fetch(`${K}/auth/cli/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e.trim(),password:o})}),l=await r.json();(!r.ok||!l.ok)&&(n.fail("Login failed"),console.log(f__default.default.red(`
|
|
3688
|
+
${l.message||"Invalid email or password."}`)),process.exit(1));let i={token:l.accessToken,email:l.user?.email,projectId:t,expiresAt:new Date(Date.now()+l.expiresIn*1e3).toISOString()};ve(i),n.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("");}catch{n.fail("Failed to connect to VAIF API"),console.log(f__default.default.red(`
|
|
3689
|
+
Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function be(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 It(t.projectId):await bt(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 Ie(){N__default.default.existsSync(k)?(N__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 Ae(){let t=w();(!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 vt(t.token);o||(e.fail("Session expired"),console.log(f__default.default.yellow(`
|
|
3690
|
+
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 Et=process.env.VAIF_API_URL||"https://api.vaif.studio";async function _t(t,e,o="public"){let n=await fetch(`${Et}/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 we(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await I(n);}catch(i){e.fail("Failed to load config"),console.log(f__default.default.red(`
|
|
3691
|
+
Error: ${i}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(f__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let l=t.projectId||r.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
|
|
3692
|
+
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let i=t.schema||r.database?.schema||"public",a=await _t(o.token,l,i);e.succeed("Schema fetched successfully");let s=t.output||A__default.default.resolve("vaif.schema.json"),c={$schema:"https://vaif.studio/schemas/schema.json",projectId:l,schema:i,pulledAt:new Date().toISOString(),...a};N__default.default.writeFileSync(s,JSON.stringify(c,null,2),"utf-8"),console.log(""),console.log(f__default.default.green(`Schema saved to: ${s}`)),console.log(""),console.log(f__default.default.gray("Schema summary:")),console.log(f__default.default.gray(` Tables: ${(a.tables||[]).length}`)),console.log(f__default.default.gray(` Enums: ${(a.enums||[]).length}`)),console.log(f__default.default.gray(` Functions: ${(a.functions||[]).length}`)),console.log(""),console.log(f__default.default.gray("Next steps:")),console.log(f__default.default.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(f__default.default.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(i){e.fail("Failed to fetch schema"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3693
|
+
Error: ${i.message}`)),process.exit(1);}}var Ee=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ft(t){let e=pe__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}async function jt(t,e,o){let n=await fetch(`${Ee}/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 Ct(t,e,o){let n=await fetch(`${Ee}/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 Rt(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=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await I(n);}catch(s){e.fail("Failed to load config"),console.log(f__default.default.red(`
|
|
3694
|
+
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 l=t.projectId||r.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
|
|
3693
3695
|
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=t.schema||A__default.default.resolve("vaif.schema.json");N__default.default.existsSync(i)||(e.fail("No local schema found"),console.log(f__default.default.yellow(`
|
|
3694
3696
|
Expected schema file at: ${i}`)),console.log(f__default.default.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let a;try{let s=N__default.default.readFileSync(i,"utf-8");a=JSON.parse(s);}catch(s){e.fail("Failed to parse schema file"),s instanceof Error&&console.log(f__default.default.red(`
|
|
3695
3697
|
Error: ${s.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:s,sql:c}=await jt(o.token,l,a);if(e.stop(),Rt(s),s.added.length===0&&s.modified.length===0&&s.removed.length===0){console.log("");return}if(c.length>0){console.log(f__default.default.bold("SQL Migrations:")),console.log("");for(let u of c)console.log(f__default.default.gray(` ${u}`));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){s.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 p=await Ft(f__default.default.cyan("Apply these changes? [y/N] "));if(p.toLowerCase()!=="y"&&p.toLowerCase()!=="yes"){console.log(f__default.default.yellow(`
|
|
3696
3698
|
Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let d=await Ct(o.token,l,a);if(d.success){if(e.succeed("Schema changes applied successfully"),console.log(""),d.migrations.length>0){console.log(f__default.default.gray("Migrations applied:"));for(let u of d.migrations)console.log(f__default.default.gray(` - ${u}`));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(s){e.fail("Failed to push schema changes"),s instanceof Error&&console.log(f__default.default.red(`
|
|
3697
|
-
Error: ${s.message}`)),process.exit(1);}}var Fe=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Nt(t,e,o){let n=await fetch(`${Fe}/v1/projects/${e}/functions`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({name:o.name,runtime:o.runtime,entrypoint:o.entrypoint,code:o.code,envId:o.envId})});if(!n.ok){let r=await n.text();throw new Error(`Failed to deploy function: ${r}`)}return n.json()}async function Dt(t,e,o){let n=new URL(`${Fe}/v1/projects/${e}/functions`);o&&n.searchParams.set("envId",o);let r=await fetch(n.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!r.ok){let l=await r.text();throw new Error(`Failed to list functions: ${l}`)}return r.json()}function
|
|
3699
|
+
Error: ${s.message}`)),process.exit(1);}}var Fe=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Nt(t,e,o){let n=await fetch(`${Fe}/v1/projects/${e}/functions`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({name:o.name,runtime:o.runtime,entrypoint:o.entrypoint,code:o.code,envId:o.envId})});if(!n.ok){let r=await n.text();throw new Error(`Failed to deploy function: ${r}`)}return n.json()}async function Dt(t,e,o){let n=new URL(`${Fe}/v1/projects/${e}/functions`);o&&n.searchParams.set("envId",o);let r=await fetch(n.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!r.ok){let l=await r.text();throw new Error(`Failed to list functions: ${l}`)}return r.json()}function xe(t){switch(A__default.default.extname(t).toLowerCase()){case ".ts":return "typescript";case ".js":case ".mjs":return "nodejs";case ".py":return "python";case ".go":return "go";case ".rs":return "rust";default:return "nodejs"}}function Te(t){let e=[],o=[".ts",".js",".mjs",".py",".go",".rs"];function n(r){if(!N__default.default.existsSync(r))return;let l=N__default.default.readdirSync(r,{withFileTypes:true});for(let i of l){let a=A__default.default.join(r,i.name);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&n(a);else if(i.isFile()){let s=A__default.default.extname(i.name).toLowerCase();o.includes(s)&&(i.name==="index.ts"||i.name==="index.js"||i.name.includes("function")||i.name.includes("handler"))&&e.push(a);}}}return n(t),e}async function je(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF Functions Deploy")),console.log(""),e.start("Scanning for function files...");let i=A__default.default.resolve("functions"),a=A__default.default.resolve("src/functions"),s=[];if(t.entrypoint){let p=A__default.default.resolve(t.entrypoint);N__default.default.existsSync(p)||(e.fail(`File not found: ${t.entrypoint}`),process.exit(1)),s=[p];}else s=[...Te(i),...Te(a)];s.length===0&&(e.fail("No function files found"),console.log(f__default.default.yellow(`
|
|
3698
3700
|
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(`
|
|
3699
3701
|
Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${s.length} function(s)`),t.name&&(s=s.filter(p=>A__default.default.basename(p,A__default.default.extname(p)).includes(t.name)),s.length===0&&(console.log(f__default.default.yellow(`
|
|
3700
|
-
No functions matching "${t.name}" found`)),process.exit(1))),console.log(""),console.log(f__default.default.gray("Functions to deploy:"));for(let p of s){let g=A__default.default.basename(A__default.default.dirname(p))||A__default.default.basename(p,A__default.default.extname(p)),b=t.runtime||
|
|
3702
|
+
No functions matching "${t.name}" found`)),process.exit(1))),console.log(""),console.log(f__default.default.gray("Functions to deploy:"));for(let p of s){let g=A__default.default.basename(A__default.default.dirname(p))||A__default.default.basename(p,A__default.default.extname(p)),b=t.runtime||xe(p);console.log(f__default.default.gray(` - ${g} (${b})`));}if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no functions deployed."));return}let c=[];for(let p of s){let g=A__default.default.basename(A__default.default.dirname(p))||A__default.default.basename(p,A__default.default.extname(p)),b=t.runtime||xe(p);e.start(`Deploying ${g}...`);try{let C=N__default.default.readFileSync(p,"utf-8"),$=await Nt(o.token,l,{name:g,runtime:b,entrypoint:A__default.default.basename(p),code:C,envId:t.envId});e.succeed(`Deployed ${g} (v${$.version})`),c.push({name:g,success:!0,version:$.version});}catch(C){let $=C instanceof Error?C.message:"Unknown error";e.fail(`Failed to deploy ${g}`),c.push({name:g,success:false,error:$});}}console.log("");let d=c.filter(p=>p.success).length;if(c.filter(p=>!p.success).length===0)console.log(f__default.default.green(`\u2713 Successfully deployed ${d} function(s)`));else {console.log(f__default.default.yellow(`Deployed ${d}/${c.length} function(s)`)),console.log(""),console.log(f__default.default.red("Failed deployments:"));for(let p of c.filter(g=>!g.success))console.log(f__default.default.red(` - ${p.name}: ${p.error}`));}console.log("");}async function Ce(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let i=await Dt(o.token,l,t.envId);if(e.stop(),i.length===0){console.log(f__default.default.yellow(`
|
|
3701
3703
|
No functions found`)),console.log(f__default.default.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(f__default.default.bold(`Functions (${i.length}):`)),console.log(""),console.log(f__default.default.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"VERSION".padEnd(10)+"STATUS".padEnd(12)+"LAST DEPLOYED")),console.log(f__default.default.gray(" "+"-".repeat(80)));for(let a of i){let s=a.status==="active"?f__default.default.green:a.status==="deploying"?f__default.default.yellow:f__default.default.red;console.log(" "+a.name.padEnd(25)+a.runtime.padEnd(15)+`v${a.version}`.padEnd(10)+s(a.status.padEnd(12))+(a.lastDeployed?new Date(a.lastDeployed).toLocaleDateString():"-"));}console.log("");}catch(i){e.fail("Failed to fetch functions"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3702
|
-
Error: ${i.message}`)),process.exit(1);}}var Y=process.env.VAIF_API_URL||"https://api.vaif.studio";async function
|
|
3704
|
+
Error: ${i.message}`)),process.exit(1);}}var Y=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Vt(t,e,o,n,r){let l=await fetch(`${Y}/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(!l.ok){let i=await l.text();throw new Error(`Failed to seed ${o}: ${i}`)}return l.json()}async function Lt(t,e){let o=await fetch(`${Y}/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 re(t){let e=[];if(!N__default.default.existsSync(t))return e;let o=N__default.default.readdirSync(t,{withFileTypes:true});for(let n of o)if(n.isFile()){let r=A__default.default.extname(n.name).toLowerCase();(r===".json"||r===".ts"||r===".js")&&e.push(A__default.default.join(t,n.name));}return e.sort()}async function Re(t){let e=A__default.default.extname(t).toLowerCase();if(e===".json"){let o=N__default.default.readFileSync(t,"utf-8"),n=JSON.parse(o);return Array.isArray(n)?[{table:A__default.default.basename(t,e),data:n}]:n.table&&n.data?[n]:Object.entries(n).map(([r,l])=>({table:r,data:l}))}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 Ne(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF Database Seed")),console.log("");let i=[];if(t.file){let d=A__default.default.resolve(t.file);N__default.default.existsSync(d)||(console.log(f__default.default.red(`File not found: ${t.file}`)),process.exit(1)),i=[d];}else {let d=A__default.default.resolve("seeds"),u=A__default.default.resolve("prisma/seed"),p=A__default.default.resolve("db/seeds");i=[...re(d),...re(u),...re(p)];}i.length===0&&(console.log(f__default.default.yellow("No seed files found")),console.log(f__default.default.gray(`
|
|
3703
3705
|
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(`
|
|
3704
3706
|
Or specify a file with --file`)),console.log(f__default.default.gray(`
|
|
3705
|
-
Example seed file (seeds/users.json):`)),console.log(f__default.default.gray(" [")),console.log(f__default.default.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(f__default.default.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(f__default.default.gray(" ]")),process.exit(1)),console.log(f__default.default.gray("Seed files found:"));for(let d of i)console.log(f__default.default.gray(` - ${A__default.default.relative(process.cwd(),d)}`));if(console.log(""),t.truncate&&(console.log(f__default.default.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let d of i){e.start(`Loading ${A__default.default.basename(d)}...`);try{let u=await Re(d);e.stop();for(let p of u)t.table&&p.table!==t.table||(console.log(f__default.default.cyan(`Table: ${p.table}`)),console.log(f__default.default.gray(` Records: ${p.data.length}`)),p.data.length>0&&console.log(f__default.default.gray(` Sample: ${JSON.stringify(p.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(u){e.fail(`Failed to load ${A__default.default.basename(d)}`),u instanceof Error&&console.log(f__default.default.red(` Error: ${u.message}`));}}return}let a=[];for(let d of i){e.start(`Processing ${A__default.default.basename(d)}...`);try{let u=await Re(d);e.stop();for(let p of u)if(!(t.table&&p.table!==t.table)){if(p.data.length===0){console.log(f__default.default.gray(` Skipping ${p.table} (no records)`));continue}e.start(`Seeding ${p.table} (${p.data.length} records)...`);try{let g=await
|
|
3707
|
+
Example seed file (seeds/users.json):`)),console.log(f__default.default.gray(" [")),console.log(f__default.default.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(f__default.default.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(f__default.default.gray(" ]")),process.exit(1)),console.log(f__default.default.gray("Seed files found:"));for(let d of i)console.log(f__default.default.gray(` - ${A__default.default.relative(process.cwd(),d)}`));if(console.log(""),t.truncate&&(console.log(f__default.default.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let d of i){e.start(`Loading ${A__default.default.basename(d)}...`);try{let u=await Re(d);e.stop();for(let p of u)t.table&&p.table!==t.table||(console.log(f__default.default.cyan(`Table: ${p.table}`)),console.log(f__default.default.gray(` Records: ${p.data.length}`)),p.data.length>0&&console.log(f__default.default.gray(` Sample: ${JSON.stringify(p.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(u){e.fail(`Failed to load ${A__default.default.basename(d)}`),u instanceof Error&&console.log(f__default.default.red(` Error: ${u.message}`));}}return}let a=[];for(let d of i){e.start(`Processing ${A__default.default.basename(d)}...`);try{let u=await Re(d);e.stop();for(let p of u)if(!(t.table&&p.table!==t.table)){if(p.data.length===0){console.log(f__default.default.gray(` Skipping ${p.table} (no records)`));continue}e.start(`Seeding ${p.table} (${p.data.length} records)...`);try{let g=await Vt(o.token,l,p.table,p.data,{truncate:t.truncate});e.succeed(`Seeded ${p.table}: ${g.inserted} records`),a.push({table:p.table,inserted:g.inserted});}catch(g){let b=g instanceof Error?g.message:"Unknown error";e.fail(`Failed to seed ${p.table}`),a.push({table:p.table,inserted:0,error:b});}}}catch(u){e.fail(`Failed to load ${A__default.default.basename(d)}`),u instanceof Error&&console.log(f__default.default.red(` Error: ${u.message}`));}}console.log("");let s=a.reduce((d,u)=>d+u.inserted,0),c=a.filter(d=>d.error).length;if(c===0)console.log(f__default.default.green(`\u2713 Successfully seeded ${s} records across ${a.length} table(s)`));else {console.log(f__default.default.yellow(`Seeded ${s} records with ${c} error(s)`)),console.log(""),console.log(f__default.default.red("Errors:"));for(let d of a.filter(u=>u.error))console.log(f__default.default.red(` - ${d.table}: ${d.error}`));}console.log("");}async function De(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=A__default.default.resolve(t.dir||"./drizzle");if(console.log(""),console.log(f__default.default.bold("VAIF Database Push")),console.log(""),!N__default.default.existsSync(i)){let u=A__default.default.resolve("./migrations");N__default.default.existsSync(u)?console.log(f__default.default.gray(`Using migrations from: ${u}`)):(console.log(f__default.default.red(`Migrations directory not found: ${i}`)),console.log(f__default.default.gray(`
|
|
3706
3708
|
Expected one of:`)),console.log(f__default.default.gray(" - ./drizzle/")),console.log(f__default.default.gray(" - ./migrations/")),console.log(f__default.default.gray(`
|
|
3707
|
-
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let a=[],s=N__default.default.readdirSync(i,{withFileTypes:true});for(let u of s)if(u.isFile()&&u.name.endsWith(".sql"))a.push(A__default.default.join(i,u.name));else if(u.isDirectory()){let p=N__default.default.readdirSync(A__default.default.join(i,u.name),{withFileTypes:true});for(let g of p)g.isFile()&&g.name.endsWith(".sql")&&a.push(A__default.default.join(i,u.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 u of a)console.log(f__default.default.gray(` - ${A__default.default.relative(process.cwd(),u)}`));if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let u of a){let p=N__default.default.readFileSync(u,"utf-8");console.log(f__default.default.cyan(`--- ${A__default.default.basename(u)} ---`)),console.log(f__default.default.gray(p.slice(0,500))),p.length>500&&console.log(f__default.default.gray("...")),console.log("");}return}let c=0,d=0;for(let u of a){let p=N__default.default.readFileSync(u,"utf-8"),g=A__default.default.relative(process.cwd(),u);e.start(`Applying ${g}...`);try{let b=await fetch(`${Y}/v1/projects/${l}/schema/execute`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:p})});if(!b.ok){let C=await b.text();throw new Error(C)}e.succeed(`Applied ${g}`),c++;}catch(b){let C=b instanceof Error?b.message:"Unknown error";e.fail(`Failed ${g}: ${C}`),d++;}}console.log(""),console.log(d===0?f__default.default.green(`Successfully applied ${c} migration(s)`):f__default.default.yellow(`Applied ${c}, failed ${d} migration(s)`)),console.log("");}async function
|
|
3708
|
-
Error: ${a.message}`)),process.exit(1);}}async function
|
|
3709
|
-
Error: ${i.message}`)),process.exit(1);}}var Ue=process.env.VAIF_API_URL||"https://api.vaif.studio";function $e(t,e,o){return t.projectId||e?.projectId||o.projectId||null}async function Oe(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=$e(t,r,o);l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=t.name||`cli-key-${Date.now()}`;console.log(""),console.log(f__default.default.bold("VAIF Generate API Key")),console.log(""),e.start("Generating API key...");try{let a=await fetch(`${Ue}/v1/projects/${l}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i})});if(!a.ok){let c=await a.text();throw new Error(`Failed to generate key: ${c}`)}let s=await a.json();e.succeed("API key generated"),console.log(""),console.log(f__default.default.green(` Name: ${s.name}`)),console.log(f__default.default.green(` Key: ${s.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(`
|
|
3709
|
+
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let a=[],s=N__default.default.readdirSync(i,{withFileTypes:true});for(let u of s)if(u.isFile()&&u.name.endsWith(".sql"))a.push(A__default.default.join(i,u.name));else if(u.isDirectory()){let p=N__default.default.readdirSync(A__default.default.join(i,u.name),{withFileTypes:true});for(let g of p)g.isFile()&&g.name.endsWith(".sql")&&a.push(A__default.default.join(i,u.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 u of a)console.log(f__default.default.gray(` - ${A__default.default.relative(process.cwd(),u)}`));if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let u of a){let p=N__default.default.readFileSync(u,"utf-8");console.log(f__default.default.cyan(`--- ${A__default.default.basename(u)} ---`)),console.log(f__default.default.gray(p.slice(0,500))),p.length>500&&console.log(f__default.default.gray("...")),console.log("");}return}let c=0,d=0;for(let u of a){let p=N__default.default.readFileSync(u,"utf-8"),g=A__default.default.relative(process.cwd(),u);e.start(`Applying ${g}...`);try{let b=await fetch(`${Y}/v1/projects/${l}/schema/execute`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:p})});if(!b.ok){let C=await b.text();throw new Error(C)}e.succeed(`Applied ${g}`),c++;}catch(b){let C=b instanceof Error?b.message:"Unknown error";e.fail(`Failed ${g}: ${C}`),d++;}}console.log(""),console.log(d===0?f__default.default.green(`Successfully applied ${c} migration(s)`):f__default.default.yellow(`Applied ${c}, failed ${d} migration(s)`)),console.log("");}async function Ve(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=A__default.default.resolve(t.output||"vaif.schema.json");console.log(""),console.log(f__default.default.bold("VAIF Database Pull")),console.log(""),e.start("Pulling schema from remote...");try{let a=await fetch(`${Y}/v1/projects/${l}/schema`,{headers:{Authorization:`Bearer ${o.token}`}});if(!a.ok){let d=await a.text();throw new Error(`Failed to pull schema: ${d}`)}let s=await a.json();N__default.default.writeFileSync(i,JSON.stringify(s,null,2),"utf-8"),e.succeed(`Schema written to ${A__default.default.relative(process.cwd(),i)}`);let c=s.tables?.length??Object.keys(s).length;console.log(f__default.default.gray(` ${c} table(s) pulled`)),console.log("");}catch(a){e.fail("Failed to pull schema"),a instanceof Error&&console.log(f__default.default.red(`
|
|
3710
|
+
Error: ${a.message}`)),process.exit(1);}}async function Le(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(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 Lt(o.token,l),e.succeed("Database reset complete"),console.log(""),console.log(f__default.default.gray("Your database is now empty.")),console.log(f__default.default.gray("Run `vaif push` to apply your schema, then `vaif db seed` to seed data.")),console.log("");}catch(i){e.fail("Failed to reset database"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3711
|
+
Error: ${i.message}`)),process.exit(1);}}var Ue=process.env.VAIF_API_URL||"https://api.vaif.studio";function $e(t,e,o){return t.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||o.projectId||null}async function Oe(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=$e(t,r,o);l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=t.name||`cli-key-${Date.now()}`;console.log(""),console.log(f__default.default.bold("VAIF Generate API Key")),console.log(""),e.start("Generating API key...");try{let a=await fetch(`${Ue}/v1/projects/${l}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i})});if(!a.ok){let c=await a.text();throw new Error(`Failed to generate key: ${c}`)}let s=await a.json();e.succeed("API key generated"),console.log(""),console.log(f__default.default.green(` Name: ${s.name}`)),console.log(f__default.default.green(` Key: ${s.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(`
|
|
3710
3712
|
Error: ${a.message}`)),process.exit(1);}}async function Me(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=$e(t,r,o);l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF API Keys")),console.log(""),e.start("Fetching API keys...");try{let i=await fetch(`${Ue}/v1/projects/${l}/api-keys`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let u=await i.text();throw new Error(`Failed to list keys: ${u}`)}let a=await i.json(),s=a.keys||a;if(e.stop(),!Array.isArray(s)||s.length===0){console.log(f__default.default.yellow("No API keys found")),console.log(f__default.default.gray(`
|
|
3711
3713
|
Generate one with: vaif keys generate`));return}let c=Math.max(8,...s.map(u=>(u.name||"").length)),d=` ${"Name".padEnd(c)} ${"Key".padEnd(24)} Created`;console.log(f__default.default.gray(d)),console.log(f__default.default.gray(" "+"-".repeat(d.length-2)));for(let u of s){let p=(u.name||"unnamed").padEnd(c),g=u.maskedKey||u.prefix||`${(u.key||"").slice(0,12)}...`,b=u.createdAt?new Date(u.createdAt).toLocaleDateString():"N/A";console.log(` ${p} ${g.padEnd(24)} ${b}`);}console.log(""),console.log(f__default.default.gray(` ${s.length} key(s) total`)),console.log("");}catch(i){e.fail("Failed to list API keys"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3712
|
-
Error: ${i.message}`)),process.exit(1);}}var U=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ut(t,e,o){return t.projectId||e?.projectId||o.projectId||null}function
|
|
3713
|
-
Error: ${s.message}`)),process.exit(1);}}async function
|
|
3714
|
+
Error: ${i.message}`)),process.exit(1);}}var U=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ut(t,e,o){return t.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||o.projectId||null}function G(){let t=w();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 H(t){try{return await I(t||"vaif.config.json")}catch{return null}}function W(t,e,o){let n=Ut(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 ze(t,e,o){let n=q__default.default(),r=G(),l=await H(o.config),i=W(o,l,r),a=e;if(o.fromFile)try{a=N__default.default.readFileSync(o.fromFile,"utf-8");}catch(s){console.log(f__default.default.red(`Failed to read file: ${o.fromFile}`)),s instanceof Error&&console.log(f__default.default.gray(s.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 s=new URL(`${U}/functions/secrets/project/${i}`);o.envId&&s.searchParams.set("envId",o.envId);let c=await fetch(s.toString(),{headers:{Authorization:`Bearer ${r.token}`}});if(!c.ok)throw new Error(`Failed to check existing secrets: ${await c.text()}`);let u=(await c.json()).find(p=>p.key===t);if(u){n.text=`Updating secret "${t}"...`;let p=await fetch(`${U}/functions/secrets/${u.id}`,{method:"PUT",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({value:a})});if(!p.ok)throw new Error(`Failed to update secret: ${await p.text()}`);n.succeed(`Updated secret "${t}"`);}else {n.text=`Creating secret "${t}"...`;let p=await fetch(`${U}/functions/secrets`,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:i,envId:o.envId,key:t,value:a})});if(!p.ok)throw new Error(`Failed to create secret: ${await p.text()}`);n.succeed(`Created secret "${t}"`);}console.log("");}catch(s){n.fail("Failed to set secret"),s instanceof Error&&console.log(f__default.default.red(`
|
|
3715
|
+
Error: ${s.message}`)),process.exit(1);}}async function Ke(t){let e=q__default.default(),o=G(),n=await H(t.config),r=W(t,n,o);console.log(""),console.log(f__default.default.bold("VAIF Secrets")),console.log(""),e.start("Fetching secrets...");try{let l=new URL(`${U}/functions/secrets/project/${r}`);t.envId&&l.searchParams.set("envId",t.envId);let i=await fetch(l.toString(),{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok)throw new Error(`Failed to list secrets: ${await i.text()}`);let a=await i.json();if(e.stop(),a.length===0){console.log(f__default.default.yellow("No secrets found")),console.log(f__default.default.gray(`
|
|
3714
3716
|
Create one with: vaif secrets set <name> <value>`));return}let s=Math.max(8,...a.map(d=>d.key.length)),c=` ${"Name".padEnd(s)} Created`;console.log(f__default.default.gray(c)),console.log(f__default.default.gray(" "+"-".repeat(c.length-2)));for(let d of a){let u=d.key.padEnd(s),p=d.createdAt?new Date(d.createdAt).toLocaleDateString():"N/A";console.log(` ${u} ${p}`);}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(l){e.fail("Failed to list secrets"),l instanceof Error&&console.log(f__default.default.red(`
|
|
3715
|
-
Error: ${l.message}`)),process.exit(1);}}async function Be(t,e){let o=q__default.default(),n=
|
|
3716
|
-
Error: ${i.message}`)),process.exit(1);}}async function qe(t,e){let o=q__default.default(),n=
|
|
3717
|
-
Error: ${i.message}`)),process.exit(1);}}var Ye=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ot(t){try{let e=new URL(t);return e.password&&(e.password="****"),e.toString()}catch{return t.replace(/:[^@/]+@/,":****@")}}async function
|
|
3718
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
3719
|
-
Error: ${i.message}`)),process.exit(1);}}commander.program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.6.
|
|
3717
|
+
Error: ${l.message}`)),process.exit(1);}}async function Be(t,e){let o=q__default.default(),n=G(),r=await H(e.config),l=W(e,r,n);console.log(""),o.start("Fetching secret...");try{let i=new URL(`${U}/functions/secrets/project/${l}`);e.envId&&i.searchParams.set("envId",e.envId);let a=await fetch(i.toString(),{headers:{Authorization:`Bearer ${n.token}`}});if(!a.ok)throw new Error(`Failed to fetch secrets: ${await a.text()}`);let c=(await a.json()).find(p=>p.key===t);c||(o.fail(`Secret "${t}" not found`),process.exit(1));let d=await fetch(`${U}/functions/secrets/${c.id}/value`,{headers:{Authorization:`Bearer ${n.token}`}});if(!d.ok)throw new Error(`Failed to get secret value: ${await d.text()}`);let u=await d.json();o.stop(),console.log(u.value);}catch(i){o.fail("Failed to get secret"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3718
|
+
Error: ${i.message}`)),process.exit(1);}}async function qe(t,e){let o=q__default.default(),n=G(),r=await H(e.config),l=W(e,r,n);console.log(""),console.log(f__default.default.bold("VAIF Delete Secret")),console.log(""),o.start("Finding secret...");try{let i=new URL(`${U}/functions/secrets/project/${l}`);e.envId&&i.searchParams.set("envId",e.envId);let a=await fetch(i.toString(),{headers:{Authorization:`Bearer ${n.token}`}});if(!a.ok)throw new Error(`Failed to fetch secrets: ${await a.text()}`);let c=(await a.json()).find(u=>u.key===t);c||(o.fail(`Secret "${t}" not found`),process.exit(1)),o.text=`Deleting secret "${t}"...`;let d=await fetch(`${U}/functions/secrets/${c.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}});if(!d.ok)throw new Error(`Failed to delete secret: ${await d.text()}`);o.succeed(`Deleted secret "${t}"`),console.log("");}catch(i){o.fail("Failed to delete secret"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3719
|
+
Error: ${i.message}`)),process.exit(1);}}var Ye=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ot(t){try{let e=new URL(t);return e.password&&(e.password="****"),e.toString()}catch{return t.replace(/:[^@/]+@/,":****@")}}async function Je(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),e.start("Fetching project info...");try{let i=await fetch(`${Ye}/v1/projects/${l}`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let d=await i.text();throw new Error(`Failed to fetch project: ${d}`)}let a=await i.json();e.stop(),console.log(""),console.log(f__default.default.bold("VAIF Project Info")),console.log("");let s=16,c=(d,u)=>{console.log(` ${f__default.default.gray(d.padEnd(s))} ${u}`);};c("Name:",f__default.default.white(a.name||"N/A")),c("Project ID:",f__default.default.white(l)),c("Region:",f__default.default.white(a.region||"us-east-1")),c("Plan:",f__default.default.white(a.plan||a.tier||"free")),c("Created:",f__default.default.white(a.createdAt?new Date(a.createdAt).toLocaleDateString():"N/A")),console.log(""),c("API URL:",f__default.default.cyan(a.apiUrl||`${Ye}/v1`)),c("WS URL:",f__default.default.cyan(a.wsUrl||a.realtimeUrl||"N/A")),c("DB URL:",f__default.default.cyan(a.databaseUrl?Ot(a.databaseUrl):"N/A")),c("Storage URL:",f__default.default.cyan(a.storageUrl||"N/A")),console.log("");}catch(i){e.fail("Failed to fetch project info"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3720
|
+
Error: ${i.message}`)),process.exit(1);}}var zt=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Ge(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),e.start("Fetching project status...");try{let i=await fetch(`${zt}/v1/projects/${l}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let b=await i.text();throw new Error(`Failed to fetch project status: ${b}`)}let a=await i.json();e.stop(),console.log(""),console.log(f__default.default.bold("VAIF Project Status")),console.log("");let s=22,c=(b,C)=>{console.log(` ${f__default.default.gray(b.padEnd(s))} ${C}`);};c("Project:",f__default.default.white(a.name||l)),c("Plan:",f__default.default.white(a.plan||a.tier||"free")),console.log(""),console.log(f__default.default.gray(" --- Resources ---")),console.log("");let d=a.tableCount??a.tables?.length??"N/A",u=a.functionCount??a.functions?.length??"N/A",p=a.bucketCount??a.storage?.buckets?.length??"N/A",g=a.activeConnections??a.connections??"N/A";c("Tables:",f__default.default.white(String(d))),c("Functions:",f__default.default.white(String(u))),c("Storage Buckets:",f__default.default.white(String(p))),c("Active Connections:",f__default.default.white(String(g))),a.usage&&(console.log(""),console.log(f__default.default.gray(" --- Usage ---")),console.log(""),a.usage.dbSize&&c("Database Size:",f__default.default.white(a.usage.dbSize)),a.usage.storageSize&&c("Storage Size:",f__default.default.white(a.usage.storageSize)),a.usage.bandwidth&&c("Bandwidth:",f__default.default.white(a.usage.bandwidth)),a.usage.functionInvocations!=null&&c("Function Invocations:",f__default.default.white(String(a.usage.functionInvocations)))),console.log("");}catch(i){e.fail("Failed to fetch project status"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3721
|
+
Error: ${i.message}`)),process.exit(1);}}commander.program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.6.1");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(be);commander.program.command("logout").description("Log out and remove stored credentials").action(Ie);commander.program.command("whoami").description("Show current authenticated user").action(Ae);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").action(me);commander.program.command("templates").alias("tpl").description("List available project templates").action(fe);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(Je);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(Ge);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(we);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(de);var He=commander.program.command("functions").alias("fn").description("Manage serverless functions");He.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(je);He.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(Ce);var X=commander.program.command("db").description("Database management commands");X.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(De);X.command("pull").description("Pull schema from VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-o, --output <path>","Output file","vaif.schema.json").action(Ve);X.command("seed").description("Seed your database with test data").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --file <path>","Specific seed file").option("-t, --table <name>","Seed specific table only").option("--truncate","Truncate tables before seeding").option("--dry-run","Preview seeding without inserting data").action(Ne);X.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(Le);var We=commander.program.command("keys").description("Manage API keys");We.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(Oe);We.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(Me);var Q=commander.program.command("secrets").alias("sec").description("Manage function secrets");Q.command("set <name> [value]").description("Create or update a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").option("--from-file <path>","Read secret value from a file").action(ze);Q.command("list").alias("ls").description("List all secrets (names only)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Ke);Q.command("get <name>").description("Reveal a secret value").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Be);Q.command("delete <name>").description("Delete a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(qe);commander.program.parse(process.argv);process.argv.slice(2).length||commander.program.outputHelp();
|