@vaiftech/cli 1.0.5 → 1.2.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/dist/cli.cjs CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';var commander=require('commander'),A=require('fs'),b=require('path'),he=require('pg'),G=require('ora'),g=require('chalk'),ve=require('prettier'),ye=require('dotenv'),Ae=require('os'),Ee=require('readline');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var A__default=/*#__PURE__*/_interopDefault(A);var b__default=/*#__PURE__*/_interopDefault(b);var he__default=/*#__PURE__*/_interopDefault(he);var G__default=/*#__PURE__*/_interopDefault(G);var g__default=/*#__PURE__*/_interopDefault(g);var ve__default=/*#__PURE__*/_interopDefault(ve);var ye__default=/*#__PURE__*/_interopDefault(ye);var Ae__default=/*#__PURE__*/_interopDefault(Ae);var Ee__default=/*#__PURE__*/_interopDefault(Ee);ye__default.default.config();async function j(o){let e=b__default.default.resolve(o);if(!A__default.default.existsSync(e))return null;try{let t=A__default.default.readFileSync(e,"utf-8"),n=JSON.parse(t);return n.database?.url&&(n.database.url=M(n.database.url)),n.api?.apiKey&&(n.api.apiKey=M(n.api.apiKey)),n}catch{throw new Error(`Failed to parse config file: ${o}`)}}function M(o){return o.replace(/\$\{([^}]+)\}/g,(e,t)=>process.env[t]||e)}async function we(o,e){let t=await o.query(`
2
+ 'use strict';var commander=require('commander'),T=require('fs'),v=require('path'),Oe=require('pg'),L=require('ora'),l=require('chalk'),Ue=require('prettier'),De=require('dotenv'),Je=require('os'),Ge=require('readline');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var T__default=/*#__PURE__*/_interopDefault(T);var v__default=/*#__PURE__*/_interopDefault(v);var Oe__default=/*#__PURE__*/_interopDefault(Oe);var L__default=/*#__PURE__*/_interopDefault(L);var l__default=/*#__PURE__*/_interopDefault(l);var Ue__default=/*#__PURE__*/_interopDefault(Ue);var De__default=/*#__PURE__*/_interopDefault(De);var Je__default=/*#__PURE__*/_interopDefault(Je);var Ge__default=/*#__PURE__*/_interopDefault(Ge);De__default.default.config();async function b(t){let e=v__default.default.resolve(t);if(!T__default.default.existsSync(e))return null;try{let o=T__default.default.readFileSync(e,"utf-8"),n=JSON.parse(o);return n.database?.url&&(n.database.url=X(n.database.url)),n.api?.apiKey&&(n.api.apiKey=X(n.api.apiKey)),n}catch{throw new Error(`Failed to parse config file: ${t}`)}}function X(t){return t.replace(/\$\{([^}]+)\}/g,(e,o)=>process.env[o]||e)}async function Le(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
6
6
  AND table_type = 'BASE TABLE'
7
7
  ORDER BY table_name
8
- `,[e]),n=await o.query(`
8
+ `,[e]),n=await t.query(`
9
9
  SELECT
10
10
  table_name,
11
11
  column_name,
@@ -20,7 +20,7 @@
20
20
  FROM information_schema.columns
21
21
  WHERE table_schema = $1
22
22
  ORDER BY table_name, ordinal_position
23
- `,[e]),s=await o.query(`
23
+ `,[e]),s=await t.query(`
24
24
  SELECT
25
25
  tc.constraint_name,
26
26
  tc.table_name,
@@ -36,7 +36,7 @@
36
36
  AND ccu.table_schema = tc.table_schema
37
37
  WHERE tc.constraint_type = 'FOREIGN KEY'
38
38
  AND tc.table_schema = $1
39
- `,[e]),i=await o.query(`
39
+ `,[e]),a=await t.query(`
40
40
  SELECT
41
41
  t.typname as enum_name,
42
42
  e.enumlabel as enum_value
@@ -45,45 +45,1142 @@
45
45
  JOIN pg_namespace n ON n.oid = t.typnamespace
46
46
  WHERE n.nspname = $1
47
47
  ORDER BY t.typname, e.enumsortorder
48
- `,[e]),r=new Map;for(let a of t.rows)r.set(a.table_name,[]);for(let a of n.rows){let u=r.get(a.table_name);u&&u.push(a);}let l=new Map;for(let a of i.rows){let u=l.get(a.enum_name)||[];u.push(a.enum_value),l.set(a.enum_name,u);}return {tables:r,enums:l,foreignKeys:s.rows}}var N={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 Ie(o,e){let{data_type:t,udt_name:n,is_nullable:s}=o;if(e.has(n)){let l=e.get(n).map(a=>`"${a}"`).join(" | ");return s==="YES"?`(${l}) | null`:l}if(t==="ARRAY"){let r=n.replace(/^_/,"");if(e.has(r)){let u=e.get(r).map(f=>`"${f}"`).join(" | ");return s==="YES"?`(${u})[] | null`:`(${u})[]`}let l=N[r]||"unknown";return s==="YES"?`${l}[] | null`:`${l}[]`}let i=N[t]||N[n]||"unknown";return s==="YES"&&(i=`${i} | null`),i}function O(o){return o.split(/[_\-\s]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function je(o,e){let t=O(o),n=e.map(s=>` | "${s}"`).join(`
49
- `);return `export type ${t} =
50
- ${n};`}function $e(o,e,t){let n=O(o),s=[],i=[],r=[];for(let f of e){let p=Ie(f,t),c=f.column_name,h=f.column_default!==null||f.is_identity==="YES",E=f.is_nullable==="YES";s.push(` ${c}: ${p};`),h||f.column_name==="id"?i.push(` ${c}?: ${p.replace(" | null","")} | null;`):E?i.push(` ${c}?: ${p};`):i.push(` ${c}: ${p.replace(" | null","")};`),r.push(` ${c}?: ${p.replace(" | null","")} | null;`);}let l=`export interface ${n} {
48
+ `,[e]),i=new Map;for(let c of o.rows)i.set(c.table_name,[]);for(let c of n.rows){let g=i.get(c.table_name);g&&g.push(c);}let r=new Map;for(let c of a.rows){let g=r.get(c.enum_name)||[];g.push(c.enum_value),r.set(c.enum_name,g);}return {tables:i,enums:r,foreignKeys:s.rows}}var Y={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 Ke(t,e){let{data_type:o,udt_name:n,is_nullable:s}=t;if(e.has(n)){let r=e.get(n).map(c=>`"${c}"`).join(" | ");return s==="YES"?`(${r}) | null`:r}if(o==="ARRAY"){let i=n.replace(/^_/,"");if(e.has(i)){let g=e.get(i).map(d=>`"${d}"`).join(" | ");return s==="YES"?`(${g})[] | null`:`(${g})[]`}let r=Y[i]||"unknown";return s==="YES"?`${r}[] | null`:`${r}[]`}let a=Y[o]||Y[n]||"unknown";return s==="YES"&&(a=`${a} | null`),a}function q(t){return t.split(/[_\-\s]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function Me(t,e){let o=q(t),n=e.map(s=>` | "${s}"`).join(`
49
+ `);return `export type ${o} =
50
+ ${n};`}function Be(t,e,o){let n=q(t),s=[],a=[],i=[];for(let d of e){let f=Ke(d,o),p=d.column_name,u=d.column_default!==null||d.is_identity==="YES",A=d.is_nullable==="YES";s.push(` ${p}: ${f};`),u||d.column_name==="id"?a.push(` ${p}?: ${f.replace(" | null","")} | null;`):A?a.push(` ${p}?: ${f};`):a.push(` ${p}: ${f.replace(" | null","")};`),i.push(` ${p}?: ${f.replace(" | null","")} | null;`);}let r=`export interface ${n} {
51
51
  ${s.join(`
52
52
  `)}
53
- }`,a=`export interface ${n}Insert {
54
- ${i.join(`
53
+ }`,c=`export interface ${n}Insert {
54
+ ${a.join(`
55
55
  `)}
56
- }`,u=`export interface ${n}Update {
57
- ${r.join(`
56
+ }`,g=`export interface ${n}Update {
57
+ ${i.join(`
58
58
  `)}
59
- }`;return {base:l,insert:a,update:u}}function Se(o,e,t){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,r]of e)n.push(je(i,r)),n.push("");}n.push("// ============ TABLES ============"),n.push("");let s=[];for(let[i,r]of o){let{base:l,insert:a,update:u}=$e(i,r,e);s.push(i),n.push(l),n.push(""),n.push(a),n.push(""),n.push(u),n.push("");}n.push("// ============ DATABASE SCHEMA ============"),n.push(""),n.push("export interface Database {");for(let i of s){let r=O(i);n.push(` ${i}: {`),n.push(` Row: ${r};`),n.push(` Insert: ${r}Insert;`),n.push(` Update: ${r}Update;`),n.push(" };");}return n.push("}"),n.push(""),n.push("export type TableName = keyof Database;"),n.push(""),n.push("// ============ HELPER TYPES ============"),n.push(""),n.push('export type Row<T extends TableName> = Database[T]["Row"];'),n.push('export type Insert<T extends TableName> = Database[T]["Insert"];'),n.push('export type Update<T extends TableName> = Database[T]["Update"];'),n.push(""),n.join(`
60
- `)}async function Y(o){let e=G__default.default("Loading configuration...").start();try{let t=await j(o.config),n=o.connection||t?.database?.url||process.env.DATABASE_URL;n||(e.fail("No database connection string provided"),console.log(g__default.default.yellow(`
61
- Provide a connection string via:`)),console.log(g__default.default.gray(" --connection <url>")),console.log(g__default.default.gray(" DATABASE_URL environment variable")),console.log(g__default.default.gray(" vaif.config.json database.url")),process.exit(1)),e.text="Connecting to database...";let s=new he__default.default.Client({connectionString:n});await s.connect(),e.text="Introspecting schema...";let{tables:i,enums:r,foreignKeys:l}=await we(s,o.schema);if(await s.end(),i.size===0){e.warn(`No tables found in schema "${o.schema}"`);return}e.text=`Generating types for ${i.size} tables...`;let a=Se(i,r,l),u=await ve__default.default.format(a,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100});if(o.dryRun){e.succeed("Generated types (dry run):"),console.log(""),console.log(g__default.default.gray("\u2500".repeat(60))),console.log(u),console.log(g__default.default.gray("\u2500".repeat(60)));return}let f=b__default.default.resolve(o.output),p=b__default.default.dirname(f);A__default.default.existsSync(p)||A__default.default.mkdirSync(p,{recursive:!0}),A__default.default.writeFileSync(f,u,"utf-8"),e.succeed(`Generated types for ${i.size} tables \u2192 ${g__default.default.cyan(o.output)}`),console.log(""),console.log(g__default.default.green("Generated:")),console.log(g__default.default.gray(` Tables: ${i.size}`)),console.log(g__default.default.gray(` Enums: ${r.size}`)),console.log(""),console.log(g__default.default.gray("Import in your code:")),console.log(g__default.default.cyan(` import type { Database, Row, Insert, Update } from "${o.output.replace(/\.ts$/,"")}";`));}catch(t){e.fail("Failed to generate types"),t instanceof Error&&(console.error(g__default.default.red(`
62
- Error: ${t.message}`)),t.message.includes("ECONNREFUSED")&&console.log(g__default.default.yellow(`
63
- Make sure your database is running and accessible.`))),process.exit(1);}}var _e={$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 J(o){let e=G__default.default("Initializing VAIF configuration...").start(),t=b__default.default.resolve("vaif.config.json");A__default.default.existsSync(t)&&!o.force&&(e.fail("vaif.config.json already exists"),console.log(g__default.default.yellow(`
64
- Use --force to overwrite existing configuration.`)),process.exit(1));try{A__default.default.writeFileSync(t,JSON.stringify(_e,null,2),"utf-8"),e.succeed("Created vaif.config.json");let n=b__default.default.resolve(".env.example");if(A__default.default.existsSync(n)||(A__default.default.writeFileSync(n,`# VAIF Configuration
59
+ }`;return {base:r,insert:c,update:g}}function Ye(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[a,i]of e)n.push(Me(a,i)),n.push("");}n.push("// ============ TABLES ============"),n.push("");let s=[];for(let[a,i]of t){let{base:r,insert:c,update:g}=Be(a,i,e);s.push(a),n.push(r),n.push(""),n.push(c),n.push(""),n.push(g),n.push("");}n.push("// ============ DATABASE SCHEMA ============"),n.push(""),n.push("export interface Database {");for(let a of s){let i=q(a);n.push(` ${a}: {`),n.push(` Row: ${i};`),n.push(` Insert: ${i}Insert;`),n.push(` Update: ${i}Update;`),n.push(" };");}return n.push("}"),n.push(""),n.push("export type TableName = keyof Database;"),n.push(""),n.push("// ============ HELPER TYPES ============"),n.push(""),n.push('export type Row<T extends TableName> = Database[T]["Row"];'),n.push('export type Insert<T extends TableName> = Database[T]["Insert"];'),n.push('export type Update<T extends TableName> = Database[T]["Update"];'),n.push(""),n.join(`
60
+ `)}async function Q(t){let e=L__default.default("Loading configuration...").start();try{let o=await b(t.config),n=t.connection||o?.database?.url||process.env.DATABASE_URL;n||(e.fail("No database connection string provided"),console.log(l__default.default.yellow(`
61
+ Provide a connection string via:`)),console.log(l__default.default.gray(" --connection <url>")),console.log(l__default.default.gray(" DATABASE_URL environment variable")),console.log(l__default.default.gray(" vaif.config.json database.url")),process.exit(1)),e.text="Connecting to database...";let s=new Oe__default.default.Client({connectionString:n});await s.connect(),e.text="Introspecting schema...";let{tables:a,enums:i,foreignKeys:r}=await Le(s,t.schema);if(await s.end(),a.size===0){e.warn(`No tables found in schema "${t.schema}"`);return}e.text=`Generating types for ${a.size} tables...`;let c=Ye(a,i,r),g=await Ue__default.default.format(c,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100});if(t.dryRun){e.succeed("Generated types (dry run):"),console.log(""),console.log(l__default.default.gray("\u2500".repeat(60))),console.log(g),console.log(l__default.default.gray("\u2500".repeat(60)));return}let d=v__default.default.resolve(t.output),f=v__default.default.dirname(d);T__default.default.existsSync(f)||T__default.default.mkdirSync(f,{recursive:!0}),T__default.default.writeFileSync(d,g,"utf-8"),e.succeed(`Generated types for ${a.size} tables \u2192 ${l__default.default.cyan(t.output)}`),console.log(""),console.log(l__default.default.green("Generated:")),console.log(l__default.default.gray(` Tables: ${a.size}`)),console.log(l__default.default.gray(` Enums: ${i.size}`)),console.log(""),console.log(l__default.default.gray("Import in your code:")),console.log(l__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(l__default.default.red(`
62
+ Error: ${o.message}`)),o.message.includes("ECONNREFUSED")&&console.log(l__default.default.yellow(`
63
+ Make sure your database is running and accessible.`))),process.exit(1);}}var ee={"nextjs-fullstack":{name:"Next.js Full-Stack",description:"Next.js app with server/client VAIF client, auth middleware, and React hooks",tag:"Next.js",files:[{path:"lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
64
+ import { createServerClient } from "@vaiftech/client/server";
65
+
66
+ // Browser client \u2013 safe to use in Client Components
67
+ export const vaif = createClient({
68
+ projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
69
+ apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
70
+ });
71
+
72
+ // Server client \u2013 use in Server Components, Route Handlers, Server Actions
73
+ export function createVaifServer() {
74
+ return createServerClient({
75
+ projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
76
+ secretKey: process.env.VAIF_SECRET_KEY!,
77
+ });
78
+ }
79
+ `},{path:".env.local.example",content:`# VAIF Configuration
80
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
81
+
82
+ NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
83
+ NEXT_PUBLIC_VAIF_API_KEY=your-anon-key
84
+ VAIF_SECRET_KEY=your-secret-key
85
+ `},{path:"middleware.ts",content:`import { NextResponse, type NextRequest } from "next/server";
86
+ import { createServerClient } from "@vaiftech/client/server";
87
+ import { authMiddleware } from "@vaiftech/auth/nextjs";
88
+
89
+ // Routes that require authentication
90
+ const protectedRoutes = ["/dashboard", "/settings", "/api/protected"];
91
+
92
+ export async function middleware(request: NextRequest) {
93
+ const { pathname } = request.nextUrl;
94
+
95
+ // Skip auth for public routes
96
+ const isProtected = protectedRoutes.some((route) => pathname.startsWith(route));
97
+ if (!isProtected) {
98
+ return NextResponse.next();
99
+ }
100
+
101
+ const vaif = createServerClient({
102
+ projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
103
+ secretKey: process.env.VAIF_SECRET_KEY!,
104
+ });
105
+
106
+ return authMiddleware(vaif, request, {
107
+ loginRedirect: "/login",
108
+ onUnauthenticated: () => {
109
+ const loginUrl = new URL("/login", request.url);
110
+ loginUrl.searchParams.set("redirect", pathname);
111
+ return NextResponse.redirect(loginUrl);
112
+ },
113
+ });
114
+ }
115
+
116
+ export const config = {
117
+ matcher: ["/dashboard/:path*", "/settings/:path*", "/api/protected/:path*"],
118
+ };
119
+ `}],dependencies:["@vaiftech/client","@vaiftech/auth","@vaiftech/react"],postInstructions:["Copy .env.local.example to .env.local and fill in your project credentials","Import { vaif } from '@/lib/vaif' in Client Components","Import { createVaifServer } from '@/lib/vaif' in Server Components","Run: npx vaif generate to generate TypeScript types from your schema"]},"react-spa":{name:"React SPA",description:"Single-page React app with Vite, VAIF client, and provider wrapper",tag:"React + Vite",files:[{path:"src/lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
120
+
121
+ export const vaif = createClient({
122
+ projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
123
+ apiKey: import.meta.env.VITE_VAIF_API_KEY,
124
+ });
125
+ `},{path:"src/providers/VaifProvider.tsx",content:`import { VaifProvider as Provider } from "@vaiftech/react";
126
+ import { vaif } from "../lib/vaif";
127
+ import type { ReactNode } from "react";
128
+
129
+ interface Props {
130
+ children: ReactNode;
131
+ }
132
+
133
+ export function VaifProvider({ children }: Props) {
134
+ return <Provider client={vaif}>{children}</Provider>;
135
+ }
136
+ `},{path:".env.example",content:`# VAIF Configuration
137
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
138
+
139
+ VITE_VAIF_PROJECT_ID=your-project-id
140
+ VITE_VAIF_API_KEY=your-anon-key
141
+ `}],dependencies:["@vaiftech/client","@vaiftech/react"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Wrap your <App /> with <VaifProvider> in main.tsx","Import { vaif } from './lib/vaif' to query your database","Run: npx vaif generate to generate TypeScript types"]},"ios-swift-app":{name:"iOS Swift App",description:"Swift client manager for iOS/macOS apps using Swift Package Manager",tag:"Swift / iOS",files:[{path:"VaifManager.swift",content:`import Foundation
142
+ import VaifClient
143
+
144
+ /// Singleton manager for the VAIF client.
145
+ /// Add your project ID and API key in the initialiser or load from a config file.
146
+ @MainActor
147
+ final class VaifManager: ObservableObject {
148
+ static let shared = VaifManager()
149
+
150
+ let client: VaifClient
151
+
152
+ @Published var isAuthenticated = false
153
+
154
+ private init() {
155
+ guard
156
+ let projectId = ProcessInfo.processInfo.environment["VAIF_PROJECT_ID"]
157
+ ?? Bundle.main.infoDictionary?["VAIF_PROJECT_ID"] as? String,
158
+ let apiKey = ProcessInfo.processInfo.environment["VAIF_API_KEY"]
159
+ ?? Bundle.main.infoDictionary?["VAIF_API_KEY"] as? String
160
+ else {
161
+ fatalError("VAIF_PROJECT_ID and VAIF_API_KEY must be set")
162
+ }
163
+
164
+ self.client = VaifClient(
165
+ projectId: projectId,
166
+ apiKey: apiKey
167
+ )
168
+ }
169
+
170
+ // MARK: - Auth helpers
171
+
172
+ func signIn(email: String, password: String) async throws {
173
+ try await client.auth.signIn(email: email, password: password)
174
+ isAuthenticated = true
175
+ }
176
+
177
+ func signOut() async throws {
178
+ try await client.auth.signOut()
179
+ isAuthenticated = false
180
+ }
181
+
182
+ // MARK: - Database helpers
183
+
184
+ func query<T: Decodable>(_ table: String, type: T.Type) async throws -> [T] {
185
+ return try await client.from(table).select().execute().value
186
+ }
187
+
188
+ func insert<T: Encodable>(_ table: String, values: T) async throws {
189
+ try await client.from(table).insert(values).execute()
190
+ }
191
+ }
192
+ `},{path:".env.example",content:`# VAIF Configuration
193
+ # Add these to your Xcode scheme environment variables or Info.plist
194
+
195
+ VAIF_PROJECT_ID=your-project-id
196
+ VAIF_API_KEY=your-anon-key
197
+ `},{path:"README-VAIF.md",content:`# VAIF Swift Setup
198
+
199
+ ## 1. Add the Swift Package
200
+
201
+ In Xcode: **File \u2192 Add Package Dependencies\u2026**
202
+
203
+ Enter the repository URL:
204
+ \`\`\`
205
+ https://github.com/vaif-technologies/vaif-swift
206
+ \`\`\`
207
+
208
+ Select the **VaifClient** library and add it to your target.
209
+
210
+ ## 2. Configure Environment
211
+
212
+ Add your project credentials to your Xcode scheme:
213
+
214
+ 1. Edit Scheme \u2192 Run \u2192 Arguments \u2192 Environment Variables
215
+ 2. Add \`VAIF_PROJECT_ID\` and \`VAIF_API_KEY\`
216
+
217
+ Or add them to **Info.plist**:
218
+ \`\`\`xml
219
+ <key>VAIF_PROJECT_ID</key>
220
+ <string>your-project-id</string>
221
+ <key>VAIF_API_KEY</key>
222
+ <string>your-anon-key</string>
223
+ \`\`\`
224
+
225
+ ## 3. Usage
226
+
227
+ \`\`\`swift
228
+ import SwiftUI
229
+
230
+ struct ContentView: View {
231
+ @StateObject private var vaif = VaifManager.shared
232
+
233
+ var body: some View {
234
+ // Use vaif.client to interact with your project
235
+ Text("Connected to VAIF")
236
+ }
237
+ }
238
+ \`\`\`
239
+
240
+ ## 4. Generate Types
241
+
242
+ Run the VAIF CLI to generate Swift models from your schema:
243
+
244
+ \`\`\`bash
245
+ npx @vaiftech/cli generate --output ./Models/Database.swift --lang swift
246
+ \`\`\`
247
+ `}],postInstructions:["Add the VaifClient Swift package from https://github.com/vaif-technologies/vaif-swift","Add VAIF_PROJECT_ID and VAIF_API_KEY to your Xcode scheme environment","See README-VAIF.md for full setup instructions"]},"expo-mobile-app":{name:"Expo Mobile App",description:"React Native / Expo app with VAIF client configured for mobile",tag:"Expo / React Native",files:[{path:"lib/vaif.ts",content:`import { createExpoClient } from "@vaiftech/sdk-expo";
248
+ import AsyncStorage from "@react-native-async-storage/async-storage";
249
+
250
+ export const vaif = createExpoClient({
251
+ projectId: process.env.EXPO_PUBLIC_VAIF_PROJECT_ID!,
252
+ apiKey: process.env.EXPO_PUBLIC_VAIF_API_KEY!,
253
+ storage: AsyncStorage,
254
+ // Realtime is enabled by default on the Expo client
255
+ realtime: {
256
+ enabled: true,
257
+ },
258
+ });
259
+ `},{path:"app.config.ts",content:`import { ExpoConfig, ConfigContext } from "expo/config";
260
+
261
+ export default ({ config }: ConfigContext): ExpoConfig => ({
262
+ ...config,
263
+ name: "my-vaif-app",
264
+ slug: "my-vaif-app",
265
+ extra: {
266
+ // These are available via process.env.EXPO_PUBLIC_* in SDK 49+
267
+ // Set them in .env and they will be embedded at build time
268
+ vaifProjectId: process.env.EXPO_PUBLIC_VAIF_PROJECT_ID,
269
+ vaifApiKey: process.env.EXPO_PUBLIC_VAIF_API_KEY,
270
+ },
271
+ });
272
+ `},{path:".env.example",content:`# VAIF Configuration
273
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
274
+
275
+ EXPO_PUBLIC_VAIF_PROJECT_ID=your-project-id
276
+ EXPO_PUBLIC_VAIF_API_KEY=your-anon-key
277
+ `}],dependencies:["@vaiftech/sdk-expo","@react-native-async-storage/async-storage"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Import { vaif } from './lib/vaif' in your screens","The Expo client persists auth tokens via AsyncStorage automatically","Run: npx vaif generate to generate TypeScript types"]},"flutter-app":{name:"Flutter App",description:"Dart/Flutter client setup with environment configuration",tag:"Flutter / Dart",files:[{path:"lib/vaif_client.dart",content:`import 'package:vaif_client/vaif_client.dart';
278
+ import 'package:flutter_dotenv/flutter_dotenv.dart';
279
+
280
+ /// Global VAIF client instance.
281
+ ///
282
+ /// Initialise by calling [initVaif] in your main() before runApp().
283
+ late final VaifClient vaif;
284
+
285
+ Future<void> initVaif() async {
286
+ await dotenv.load(fileName: '.env');
287
+
288
+ final projectId = dotenv.env['VAIF_PROJECT_ID'];
289
+ final apiKey = dotenv.env['VAIF_API_KEY'];
290
+
291
+ if (projectId == null || apiKey == null) {
292
+ throw Exception(
293
+ 'VAIF_PROJECT_ID and VAIF_API_KEY must be set in .env',
294
+ );
295
+ }
296
+
297
+ vaif = VaifClient(
298
+ projectId: projectId,
299
+ apiKey: apiKey,
300
+ // Enable realtime subscriptions
301
+ realtime: const RealtimeConfig(enabled: true),
302
+ );
303
+ }
304
+
305
+ /// Example: fetch rows from a table.
306
+ Future<List<Map<String, dynamic>>> fetchRows(String table) async {
307
+ final response = await vaif.from(table).select().execute();
308
+ return List<Map<String, dynamic>>.from(response.data);
309
+ }
310
+
311
+ /// Example: insert a row.
312
+ Future<void> insertRow(String table, Map<String, dynamic> values) async {
313
+ await vaif.from(table).insert(values).execute();
314
+ }
315
+
316
+ /// Example: subscribe to realtime changes.
317
+ void subscribeToTable(
318
+ String table,
319
+ void Function(Map<String, dynamic> payload) onEvent,
320
+ ) {
321
+ vaif.realtime.channel(table).on(
322
+ RealtimeListenTypes.postgresChanges,
323
+ ChannelFilter(event: '*', schema: 'public', table: table),
324
+ (payload, [ref]) => onEvent(payload),
325
+ ).subscribe();
326
+ }
327
+ `},{path:".env.example",content:`# VAIF Configuration
328
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
329
+
330
+ VAIF_PROJECT_ID=your-project-id
331
+ VAIF_API_KEY=your-anon-key
332
+ `},{path:"README-VAIF.md",content:`# VAIF Flutter Setup
333
+
334
+ ## 1. Add Dependencies
335
+
336
+ Add the following to your \`pubspec.yaml\`:
337
+
338
+ \`\`\`yaml
339
+ dependencies:
340
+ vaif_client: ^1.0.0
341
+ flutter_dotenv: ^5.1.0
342
+ \`\`\`
343
+
344
+ Then run:
345
+ \`\`\`bash
346
+ flutter pub get
347
+ \`\`\`
348
+
349
+ ## 2. Configure Environment
350
+
351
+ Copy \`.env.example\` to \`.env\` and fill in your credentials.
352
+
353
+ Add the \`.env\` file to your \`pubspec.yaml\` assets:
354
+
355
+ \`\`\`yaml
356
+ flutter:
357
+ assets:
358
+ - .env
359
+ \`\`\`
360
+
361
+ ## 3. Initialise in main.dart
362
+
363
+ \`\`\`dart
364
+ import 'package:flutter/material.dart';
365
+ import 'lib/vaif_client.dart';
366
+
367
+ void main() async {
368
+ WidgetsFlutterBinding.ensureInitialized();
369
+ await initVaif();
370
+ runApp(const MyApp());
371
+ }
372
+ \`\`\`
373
+
374
+ ## 4. Usage
375
+
376
+ \`\`\`dart
377
+ // Query data
378
+ final todos = await vaif.from('todos').select().execute();
379
+
380
+ // Insert data
381
+ await vaif.from('todos').insert({'title': 'Buy milk', 'done': false}).execute();
382
+
383
+ // Realtime subscription
384
+ vaif.realtime.channel('todos').on(
385
+ RealtimeListenTypes.postgresChanges,
386
+ ChannelFilter(event: '*', schema: 'public', table: 'todos'),
387
+ (payload, [ref]) {
388
+ print('Change: $payload');
389
+ },
390
+ ).subscribe();
391
+ \`\`\`
392
+ `}],postInstructions:["Add vaif_client and flutter_dotenv to your pubspec.yaml (see README-VAIF.md)","Copy .env.example to .env and fill in your project credentials","Call initVaif() in main() before runApp()","See README-VAIF.md for full setup instructions"]},"python-fastapi-backend":{name:"Python FastAPI Backend",description:"FastAPI backend with VAIF client, auth middleware, and type-safe queries",tag:"Python / FastAPI",files:[{path:"vaif_client.py",content:`"""VAIF client setup and auth middleware for FastAPI."""
393
+
394
+ import os
395
+ from functools import lru_cache
396
+ from typing import Optional
397
+
398
+ from dotenv import load_dotenv
399
+ from fastapi import Depends, HTTPException, Request, status
400
+ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
401
+ from vaif import Client, ServiceClient
402
+
403
+ load_dotenv()
404
+
405
+ VAIF_PROJECT_ID = os.environ["VAIF_PROJECT_ID"]
406
+ VAIF_API_KEY = os.environ["VAIF_API_KEY"]
407
+ VAIF_SECRET_KEY = os.environ["VAIF_SECRET_KEY"]
408
+
409
+
410
+ @lru_cache()
411
+ def get_vaif_client() -> Client:
412
+ """Public client using the anon key (respects Row Level Security)."""
413
+ return Client(
414
+ project_id=VAIF_PROJECT_ID,
415
+ api_key=VAIF_API_KEY,
416
+ )
417
+
418
+
419
+ @lru_cache()
420
+ def get_vaif_admin() -> ServiceClient:
421
+ """Admin/service client that bypasses RLS. Use with caution."""
422
+ return ServiceClient(
423
+ project_id=VAIF_PROJECT_ID,
424
+ secret_key=VAIF_SECRET_KEY,
425
+ )
426
+
427
+
428
+ # \u2500\u2500 Auth middleware \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
429
+
430
+ security = HTTPBearer(auto_error=False)
431
+
432
+
433
+ async def get_current_user(
434
+ request: Request,
435
+ credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
436
+ ):
437
+ """FastAPI dependency that validates VAIF auth tokens.
438
+
439
+ Usage:
440
+ @app.get("/protected")
441
+ async def protected_route(user=Depends(get_current_user)):
442
+ return {"user_id": user["id"]}
443
+ """
444
+ if credentials is None:
445
+ raise HTTPException(
446
+ status_code=status.HTTP_401_UNAUTHORIZED,
447
+ detail="Missing authorization header",
448
+ )
449
+
450
+ client = get_vaif_admin()
451
+ try:
452
+ user = await client.auth.get_user(credentials.credentials)
453
+ except Exception as exc:
454
+ raise HTTPException(
455
+ status_code=status.HTTP_401_UNAUTHORIZED,
456
+ detail=f"Invalid token: {exc}",
457
+ )
458
+
459
+ if user is None:
460
+ raise HTTPException(
461
+ status_code=status.HTTP_401_UNAUTHORIZED,
462
+ detail="Invalid or expired token",
463
+ )
464
+
465
+ return user
466
+
467
+
468
+ # \u2500\u2500 Convenience query helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
469
+
470
+
471
+ async def query_table(table: str, filters: Optional[dict] = None):
472
+ """Quick helper to query a table with optional filters."""
473
+ client = get_vaif_client()
474
+ q = client.from_(table).select("*")
475
+ if filters:
476
+ for key, value in filters.items():
477
+ q = q.eq(key, value)
478
+ return await q.execute()
479
+
480
+
481
+ async def insert_row(table: str, data: dict):
482
+ """Insert a single row and return the result."""
483
+ client = get_vaif_client()
484
+ return await client.from_(table).insert(data).execute()
485
+ `},{path:".env.example",content:`# VAIF Configuration
486
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
487
+
488
+ VAIF_PROJECT_ID=your-project-id
489
+ VAIF_API_KEY=your-anon-key
490
+ VAIF_SECRET_KEY=your-secret-key
491
+ `},{path:"requirements.txt",content:`vaif-client>=1.0.0
492
+ fastapi>=0.110.0
493
+ uvicorn[standard]>=0.27.0
494
+ python-dotenv>=1.0.0
495
+ `}],postInstructions:["Install dependencies: pip install -r requirements.txt","Copy .env.example to .env and fill in your project credentials","Use get_current_user as a FastAPI Depends() for protected routes","Run your server: uvicorn main:app --reload"]},"go-backend-api":{name:"Go Backend API",description:"Go backend with VAIF client initialisation and HTTP middleware",tag:"Go",files:[{path:"vaif/client.go",content:`package vaif
496
+
497
+ import (
498
+ "fmt"
499
+ "net/http"
500
+ "os"
501
+ "strings"
502
+
503
+ vaifclient "github.com/vaif-technologies/vaif-go"
504
+ )
505
+
506
+ // Client is the global VAIF client instance.
507
+ // Initialise by calling Init() at application start.
508
+ var Client *vaifclient.Client
509
+
510
+ // Init creates the VAIF client from environment variables.
511
+ // Call this in main() before starting your HTTP server.
512
+ func Init() error {
513
+ projectID := os.Getenv("VAIF_PROJECT_ID")
514
+ apiKey := os.Getenv("VAIF_API_KEY")
515
+ secretKey := os.Getenv("VAIF_SECRET_KEY")
516
+
517
+ if projectID == "" || apiKey == "" {
518
+ return fmt.Errorf("VAIF_PROJECT_ID and VAIF_API_KEY must be set")
519
+ }
520
+
521
+ var err error
522
+ Client, err = vaifclient.NewClient(vaifclient.Config{
523
+ ProjectID: projectID,
524
+ APIKey: apiKey,
525
+ SecretKey: secretKey,
526
+ })
527
+ if err != nil {
528
+ return fmt.Errorf("failed to create VAIF client: %w", err)
529
+ }
530
+
531
+ return nil
532
+ }
533
+
534
+ // AuthMiddleware validates the VAIF auth token from the Authorization header.
535
+ // It injects the authenticated user into the request context.
536
+ func AuthMiddleware(next http.Handler) http.Handler {
537
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
538
+ auth := r.Header.Get("Authorization")
539
+ if auth == "" {
540
+ http.Error(w, "missing authorization header", http.StatusUnauthorized)
541
+ return
542
+ }
543
+
544
+ token := strings.TrimPrefix(auth, "Bearer ")
545
+ if token == auth {
546
+ http.Error(w, "invalid authorization format", http.StatusUnauthorized)
547
+ return
548
+ }
549
+
550
+ user, err := Client.Auth.GetUser(r.Context(), token)
551
+ if err != nil {
552
+ http.Error(w, "invalid or expired token", http.StatusUnauthorized)
553
+ return
554
+ }
555
+
556
+ ctx := vaifclient.WithUser(r.Context(), user)
557
+ next.ServeHTTP(w, r.WithContext(ctx))
558
+ })
559
+ }
560
+ `},{path:".env.example",content:`# VAIF Configuration
561
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
562
+
563
+ VAIF_PROJECT_ID=your-project-id
564
+ VAIF_API_KEY=your-anon-key
565
+ VAIF_SECRET_KEY=your-secret-key
566
+ `},{path:"README-VAIF.md",content:`# VAIF Go Setup
567
+
568
+ ## 1. Install the Go Client
569
+
570
+ \`\`\`bash
571
+ go get github.com/vaif-technologies/vaif-go
572
+ \`\`\`
573
+
574
+ ## 2. Configure Environment
575
+
576
+ Copy \`.env.example\` to \`.env\` and fill in your credentials.
577
+
578
+ Use a library like [godotenv](https://github.com/joho/godotenv) to load the file:
579
+
580
+ \`\`\`bash
581
+ go get github.com/joho/godotenv
582
+ \`\`\`
583
+
584
+ ## 3. Initialise in main.go
585
+
586
+ \`\`\`go
587
+ package main
588
+
589
+ import (
590
+ "log"
591
+ "net/http"
592
+
593
+ "github.com/joho/godotenv"
594
+ "yourmodule/vaif"
595
+ )
596
+
597
+ func main() {
598
+ _ = godotenv.Load()
599
+
600
+ if err := vaif.Init(); err != nil {
601
+ log.Fatalf("Failed to initialise VAIF: %v", err)
602
+ }
603
+
604
+ mux := http.NewServeMux()
605
+
606
+ // Public routes
607
+ mux.HandleFunc("/health", healthHandler)
608
+
609
+ // Protected routes
610
+ protected := vaif.AuthMiddleware(http.HandlerFunc(protectedHandler))
611
+ mux.Handle("/api/data", protected)
612
+
613
+ log.Println("Server running on :8080")
614
+ log.Fatal(http.ListenAndServe(":8080", mux))
615
+ }
616
+
617
+ func healthHandler(w http.ResponseWriter, r *http.Request) {
618
+ w.Write([]byte("ok"))
619
+ }
620
+
621
+ func protectedHandler(w http.ResponseWriter, r *http.Request) {
622
+ w.Write([]byte("authenticated"))
623
+ }
624
+ \`\`\`
625
+
626
+ ## 4. Query Data
627
+
628
+ \`\`\`go
629
+ // Fetch rows
630
+ rows, err := vaif.Client.From("todos").Select("*").Execute(ctx)
631
+
632
+ // Insert a row
633
+ _, err := vaif.Client.From("todos").Insert(map[string]interface{}{
634
+ "title": "Buy milk",
635
+ "done": false,
636
+ }).Execute(ctx)
637
+ \`\`\`
638
+ `}],postInstructions:["Run: go get github.com/vaif-technologies/vaif-go","Copy .env.example to .env and fill in your project credentials","Call vaif.Init() in main() before starting your server","See README-VAIF.md for full setup instructions"]},"todo-app":{name:"Todo App",description:"Simple React todo app \u2013 great for learning VAIF basics",tag:"React Starter",files:[{path:"src/lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
639
+
640
+ export const vaif = createClient({
641
+ projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
642
+ apiKey: import.meta.env.VITE_VAIF_API_KEY,
643
+ });
644
+
645
+ // Typed helpers for the todos table
646
+ export interface Todo {
647
+ id: string;
648
+ title: string;
649
+ done: boolean;
650
+ created_at: string;
651
+ user_id?: string;
652
+ }
653
+
654
+ export async function getTodos(): Promise<Todo[]> {
655
+ const { data, error } = await vaif
656
+ .from("todos")
657
+ .select("*")
658
+ .order("created_at", { ascending: false });
659
+
660
+ if (error) throw error;
661
+ return data as Todo[];
662
+ }
663
+
664
+ export async function addTodo(title: string): Promise<Todo> {
665
+ const { data, error } = await vaif
666
+ .from("todos")
667
+ .insert({ title, done: false })
668
+ .select()
669
+ .single();
670
+
671
+ if (error) throw error;
672
+ return data as Todo;
673
+ }
674
+
675
+ export async function toggleTodo(id: string, done: boolean): Promise<void> {
676
+ const { error } = await vaif
677
+ .from("todos")
678
+ .update({ done })
679
+ .eq("id", id);
680
+
681
+ if (error) throw error;
682
+ }
683
+
684
+ export async function deleteTodo(id: string): Promise<void> {
685
+ const { error } = await vaif
686
+ .from("todos")
687
+ .delete()
688
+ .eq("id", id);
689
+
690
+ if (error) throw error;
691
+ }
692
+ `},{path:".env.example",content:`# VAIF Configuration
693
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
694
+
695
+ VITE_VAIF_PROJECT_ID=your-project-id
696
+ VITE_VAIF_API_KEY=your-anon-key
697
+ `}],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",files:[{path:"src/lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
698
+
699
+ export const vaif = createClient({
700
+ projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
701
+ apiKey: import.meta.env.VITE_VAIF_API_KEY,
702
+ realtime: {
703
+ enabled: true,
704
+ // Automatically reconnect on connection loss
705
+ reconnect: true,
706
+ reconnectInterval: 1000,
707
+ maxReconnectAttempts: 10,
708
+ },
709
+ });
710
+
711
+ export interface Message {
712
+ id: string;
713
+ content: string;
714
+ user_id: string;
715
+ username: string;
716
+ channel_id: string;
717
+ created_at: string;
718
+ }
719
+
720
+ export async function sendMessage(
721
+ channelId: string,
722
+ content: string,
723
+ userId: string,
724
+ username: string,
725
+ ): Promise<Message> {
726
+ const { data, error } = await vaif
727
+ .from("messages")
728
+ .insert({
729
+ content,
730
+ user_id: userId,
731
+ username,
732
+ channel_id: channelId,
733
+ })
734
+ .select()
735
+ .single();
736
+
737
+ if (error) throw error;
738
+ return data as Message;
739
+ }
740
+
741
+ export async function getMessages(channelId: string, limit = 50): Promise<Message[]> {
742
+ const { data, error } = await vaif
743
+ .from("messages")
744
+ .select("*")
745
+ .eq("channel_id", channelId)
746
+ .order("created_at", { ascending: true })
747
+ .limit(limit);
748
+
749
+ if (error) throw error;
750
+ return data as Message[];
751
+ }
752
+ `},{path:"src/hooks/useRealtimeMessages.ts",content:`import { useEffect, useState, useCallback } from "react";
753
+ import { vaif, type Message, getMessages } from "../lib/vaif";
754
+
755
+ interface UseRealtimeMessagesOptions {
756
+ channelId: string;
757
+ initialLimit?: number;
758
+ }
759
+
760
+ /**
761
+ * Hook that subscribes to realtime message changes on a channel.
762
+ *
763
+ * Usage:
764
+ * const { messages, isLoading, error } = useRealtimeMessages({
765
+ * channelId: "general",
766
+ * });
767
+ */
768
+ export function useRealtimeMessages({
769
+ channelId,
770
+ initialLimit = 50,
771
+ }: UseRealtimeMessagesOptions) {
772
+ const [messages, setMessages] = useState<Message[]>([]);
773
+ const [isLoading, setIsLoading] = useState(true);
774
+ const [error, setError] = useState<Error | null>(null);
775
+
776
+ // Load initial messages
777
+ useEffect(() => {
778
+ let cancelled = false;
779
+
780
+ async function load() {
781
+ try {
782
+ setIsLoading(true);
783
+ const data = await getMessages(channelId, initialLimit);
784
+ if (!cancelled) {
785
+ setMessages(data);
786
+ setError(null);
787
+ }
788
+ } catch (err) {
789
+ if (!cancelled) {
790
+ setError(err instanceof Error ? err : new Error(String(err)));
791
+ }
792
+ } finally {
793
+ if (!cancelled) setIsLoading(false);
794
+ }
795
+ }
796
+
797
+ load();
798
+ return () => { cancelled = true; };
799
+ }, [channelId, initialLimit]);
800
+
801
+ // Subscribe to realtime changes
802
+ useEffect(() => {
803
+ const subscription = vaif
804
+ .channel(\`messages:\${channelId}\`)
805
+ .on(
806
+ "postgres_changes",
807
+ {
808
+ event: "*",
809
+ schema: "public",
810
+ table: "messages",
811
+ filter: \`channel_id=eq.\${channelId}\`,
812
+ },
813
+ (payload) => {
814
+ if (payload.eventType === "INSERT") {
815
+ setMessages((prev) => [...prev, payload.new as Message]);
816
+ } else if (payload.eventType === "UPDATE") {
817
+ setMessages((prev) =>
818
+ prev.map((msg) =>
819
+ msg.id === (payload.new as Message).id
820
+ ? (payload.new as Message)
821
+ : msg,
822
+ ),
823
+ );
824
+ } else if (payload.eventType === "DELETE") {
825
+ setMessages((prev) =>
826
+ prev.filter((msg) => msg.id !== (payload.old as Message).id),
827
+ );
828
+ }
829
+ },
830
+ )
831
+ .subscribe();
832
+
833
+ return () => {
834
+ subscription.unsubscribe();
835
+ };
836
+ }, [channelId]);
837
+
838
+ const refresh = useCallback(async () => {
839
+ const data = await getMessages(channelId, initialLimit);
840
+ setMessages(data);
841
+ }, [channelId, initialLimit]);
842
+
843
+ return { messages, isLoading, error, refresh };
844
+ }
845
+ `},{path:".env.example",content:`# VAIF Configuration
846
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
847
+
848
+ VITE_VAIF_PROJECT_ID=your-project-id
849
+ VITE_VAIF_API_KEY=your-anon-key
850
+ `}],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",files:[{path:"lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
851
+ import { createServerClient } from "@vaiftech/client/server";
852
+
853
+ // Browser client \u2013 use in Client Components
854
+ export const vaif = createClient({
855
+ projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
856
+ apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
857
+ });
858
+
859
+ // Server client \u2013 use in Server Components, Route Handlers, Server Actions
860
+ export function createVaifServer() {
861
+ return createServerClient({
862
+ projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
863
+ secretKey: process.env.VAIF_SECRET_KEY!,
864
+ });
865
+ }
866
+ `},{path:"lib/auth.ts",content:`import { createVaifServer } from "./vaif";
867
+
868
+ // \u2500\u2500 User helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
869
+
870
+ export async function getCurrentUser() {
871
+ const vaif = createVaifServer();
872
+ const { data: { user }, error } = await vaif.auth.getUser();
873
+ if (error || !user) return null;
874
+ return user;
875
+ }
876
+
877
+ export async function requireUser() {
878
+ const user = await getCurrentUser();
879
+ if (!user) throw new Error("Unauthorized");
880
+ return user;
881
+ }
882
+
883
+ // \u2500\u2500 Team / Organisation helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
884
+
885
+ export interface Team {
886
+ id: string;
887
+ name: string;
888
+ slug: string;
889
+ owner_id: string;
890
+ created_at: string;
891
+ }
892
+
893
+ export interface TeamMember {
894
+ id: string;
895
+ team_id: string;
896
+ user_id: string;
897
+ role: "owner" | "admin" | "member" | "viewer";
898
+ joined_at: string;
899
+ }
900
+
901
+ export async function getUserTeams(userId: string): Promise<Team[]> {
902
+ const vaif = createVaifServer();
903
+
904
+ // Get team IDs the user belongs to
905
+ const { data: memberships, error: memberError } = await vaif
906
+ .from("team_members")
907
+ .select("team_id")
908
+ .eq("user_id", userId);
909
+
910
+ if (memberError) throw memberError;
911
+ if (!memberships?.length) return [];
912
+
913
+ const teamIds = memberships.map((m) => m.team_id);
914
+
915
+ const { data: teams, error: teamError } = await vaif
916
+ .from("teams")
917
+ .select("*")
918
+ .in("id", teamIds)
919
+ .order("name");
920
+
921
+ if (teamError) throw teamError;
922
+ return (teams ?? []) as Team[];
923
+ }
924
+
925
+ export async function getTeamMembers(teamId: string): Promise<TeamMember[]> {
926
+ const vaif = createVaifServer();
927
+
928
+ const { data, error } = await vaif
929
+ .from("team_members")
930
+ .select("*")
931
+ .eq("team_id", teamId)
932
+ .order("joined_at");
933
+
934
+ if (error) throw error;
935
+ return (data ?? []) as TeamMember[];
936
+ }
937
+
938
+ export async function createTeam(name: string, slug: string): Promise<Team> {
939
+ const user = await requireUser();
940
+ const vaif = createVaifServer();
941
+
942
+ const { data: team, error } = await vaif
943
+ .from("teams")
944
+ .insert({ name, slug, owner_id: user.id })
945
+ .select()
946
+ .single();
947
+
948
+ if (error) throw error;
949
+
950
+ // Add the creator as owner
951
+ await vaif.from("team_members").insert({
952
+ team_id: team.id,
953
+ user_id: user.id,
954
+ role: "owner",
955
+ });
956
+
957
+ return team as Team;
958
+ }
959
+
960
+ export async function inviteToTeam(
961
+ teamId: string,
962
+ email: string,
963
+ role: TeamMember["role"] = "member",
964
+ ): Promise<void> {
965
+ const vaif = createVaifServer();
966
+
967
+ // Look up user by email
968
+ const { data: users } = await vaif
969
+ .from("users")
970
+ .select("id")
971
+ .eq("email", email)
972
+ .limit(1);
973
+
974
+ if (!users?.length) {
975
+ throw new Error("User not found. They must create an account first.");
976
+ }
977
+
978
+ const { error } = await vaif.from("team_members").insert({
979
+ team_id: teamId,
980
+ user_id: users[0].id,
981
+ role,
982
+ });
983
+
984
+ if (error) throw error;
985
+ }
986
+
987
+ // \u2500\u2500 Role-based checks \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
988
+
989
+ export async function requireTeamRole(
990
+ teamId: string,
991
+ requiredRoles: TeamMember["role"][],
992
+ ): Promise<TeamMember> {
993
+ const user = await requireUser();
994
+ const vaif = createVaifServer();
995
+
996
+ const { data: member, error } = await vaif
997
+ .from("team_members")
998
+ .select("*")
999
+ .eq("team_id", teamId)
1000
+ .eq("user_id", user.id)
1001
+ .single();
1002
+
1003
+ if (error || !member) {
1004
+ throw new Error("Not a member of this team");
1005
+ }
1006
+
1007
+ if (!requiredRoles.includes(member.role)) {
1008
+ throw new Error(\`Requires one of: \${requiredRoles.join(", ")}\`);
1009
+ }
1010
+
1011
+ return member as TeamMember;
1012
+ }
1013
+ `},{path:".env.example",content:`# VAIF Configuration
1014
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
1015
+
1016
+ NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
1017
+ NEXT_PUBLIC_VAIF_API_KEY=your-anon-key
1018
+ VAIF_SECRET_KEY=your-secret-key
1019
+ `}],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",files:[{path:"lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
1020
+ import { createServerClient } from "@vaiftech/client/server";
1021
+
1022
+ // Browser client
1023
+ export const vaif = createClient({
1024
+ projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
1025
+ apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
1026
+ });
1027
+
1028
+ // Server client
1029
+ export function createVaifServer() {
1030
+ return createServerClient({
1031
+ projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
1032
+ secretKey: process.env.VAIF_SECRET_KEY!,
1033
+ });
1034
+ }
1035
+ `},{path:"lib/storage.ts",content:`import { createVaifServer } from "./vaif";
1036
+
1037
+ const PRODUCT_IMAGES_BUCKET = "product-images";
1038
+
1039
+ interface UploadResult {
1040
+ path: string;
1041
+ publicUrl: string;
1042
+ }
1043
+
1044
+ /**
1045
+ * Upload a product image to VAIF Storage.
1046
+ *
1047
+ * @param file - The file buffer or Blob to upload
1048
+ * @param productId - Product ID used to organise files in folders
1049
+ * @param fileName - Original filename (will be sanitised)
1050
+ * @returns The storage path and public URL
1051
+ */
1052
+ export async function uploadProductImage(
1053
+ file: Buffer | Blob,
1054
+ productId: string,
1055
+ fileName: string,
1056
+ ): Promise<UploadResult> {
1057
+ const vaif = createVaifServer();
1058
+
1059
+ // Sanitise filename and build path
1060
+ const sanitised = fileName.replace(/[^a-zA-Z0-9._-]/g, "_");
1061
+ const storagePath = \`\${productId}/\${Date.now()}-\${sanitised}\`;
1062
+
1063
+ const { data, error } = await vaif.storage
1064
+ .from(PRODUCT_IMAGES_BUCKET)
1065
+ .upload(storagePath, file, {
1066
+ contentType: getContentType(fileName),
1067
+ upsert: false,
1068
+ });
1069
+
1070
+ if (error) throw error;
1071
+
1072
+ const { data: urlData } = vaif.storage
1073
+ .from(PRODUCT_IMAGES_BUCKET)
1074
+ .getPublicUrl(data.path);
1075
+
1076
+ return {
1077
+ path: data.path,
1078
+ publicUrl: urlData.publicUrl,
1079
+ };
1080
+ }
1081
+
1082
+ /**
1083
+ * Delete a product image from storage.
1084
+ */
1085
+ export async function deleteProductImage(storagePath: string): Promise<void> {
1086
+ const vaif = createVaifServer();
1087
+
1088
+ const { error } = await vaif.storage
1089
+ .from(PRODUCT_IMAGES_BUCKET)
1090
+ .remove([storagePath]);
1091
+
1092
+ if (error) throw error;
1093
+ }
1094
+
1095
+ /**
1096
+ * Generate a signed URL for a private product image.
1097
+ *
1098
+ * @param storagePath - The path returned from uploadProductImage
1099
+ * @param expiresIn - Seconds until the URL expires (default: 1 hour)
1100
+ */
1101
+ export async function getSignedImageUrl(
1102
+ storagePath: string,
1103
+ expiresIn = 3600,
1104
+ ): Promise<string> {
1105
+ const vaif = createVaifServer();
1106
+
1107
+ const { data, error } = await vaif.storage
1108
+ .from(PRODUCT_IMAGES_BUCKET)
1109
+ .createSignedUrl(storagePath, expiresIn);
1110
+
1111
+ if (error) throw error;
1112
+ return data.signedUrl;
1113
+ }
1114
+
1115
+ /**
1116
+ * List all images for a product.
1117
+ */
1118
+ export async function listProductImages(productId: string) {
1119
+ const vaif = createVaifServer();
1120
+
1121
+ const { data, error } = await vaif.storage
1122
+ .from(PRODUCT_IMAGES_BUCKET)
1123
+ .list(productId, {
1124
+ sortBy: { column: "created_at", order: "desc" },
1125
+ });
1126
+
1127
+ if (error) throw error;
1128
+ return data;
1129
+ }
1130
+
1131
+ function getContentType(fileName: string): string {
1132
+ const ext = fileName.split(".").pop()?.toLowerCase();
1133
+ const mimeTypes: Record<string, string> = {
1134
+ jpg: "image/jpeg",
1135
+ jpeg: "image/jpeg",
1136
+ png: "image/png",
1137
+ gif: "image/gif",
1138
+ webp: "image/webp",
1139
+ svg: "image/svg+xml",
1140
+ avif: "image/avif",
1141
+ };
1142
+ return mimeTypes[ext ?? ""] ?? "application/octet-stream";
1143
+ }
1144
+ `},{path:".env.example",content:`# VAIF Configuration
1145
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
1146
+
1147
+ NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
1148
+ NEXT_PUBLIC_VAIF_API_KEY=your-anon-key
1149
+ VAIF_SECRET_KEY=your-secret-key
1150
+ `}],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 te(){console.log(""),console.log(l__default.default.bold("Available project templates")),console.log("");let t=26,e=22;console.log(` ${l__default.default.gray("Template".padEnd(t))}${l__default.default.gray("Stack".padEnd(e))}${l__default.default.gray("Description")}`),console.log(l__default.default.gray(" "+"-".repeat(t+e+40)));for(let[o,n]of Object.entries(ee))console.log(` ${l__default.default.cyan(o.padEnd(t))}${l__default.default.yellow(n.tag.padEnd(e))}${l__default.default.white(n.description)}`);console.log(""),console.log(l__default.default.gray("Usage:")),console.log(l__default.default.gray(" npx @vaiftech/cli init --template <name>")),console.log(l__default.default.gray(" npx @vaiftech/cli init -t nextjs-fullstack")),console.log("");}async function oe(t,e={}){let o=ee[t];o||(console.log(l__default.default.red(`
1151
+ Unknown template: ${t}`)),console.log(l__default.default.yellow(`Run 'vaif templates' to see available templates.
1152
+ `)),process.exit(1)),console.log(""),console.log(l__default.default.bold(`Scaffolding ${l__default.default.cyan(o.name)} template...`)),console.log("");let n=0,s=0;for(let a of o.files){let i=v__default.default.resolve(a.path),r=v__default.default.dirname(i);if(T__default.default.existsSync(r)||T__default.default.mkdirSync(r,{recursive:true}),T__default.default.existsSync(i)&&!e.force){console.log(l__default.default.yellow(` skip ${a.path} (already exists)`)),s++;continue}T__default.default.writeFileSync(i,a.content,"utf-8"),console.log(l__default.default.green(` create ${a.path}`)),n++;}console.log(""),n>0&&console.log(l__default.default.green(`Created ${n} file${n!==1?"s":""}.`)),s>0&&console.log(l__default.default.yellow(`Skipped ${s} file${s!==1?"s":""} (use --force to overwrite).`)),(o.dependencies?.length||o.devDependencies?.length)&&(console.log(""),console.log(l__default.default.bold("Install dependencies:")),o.dependencies?.length&&console.log(l__default.default.cyan(` npm install ${o.dependencies.join(" ")}`)),o.devDependencies?.length&&console.log(l__default.default.cyan(` npm install -D ${o.devDependencies.join(" ")}`))),o.postInstructions.length>0&&(console.log(""),console.log(l__default.default.bold("Next steps:")),o.postInstructions.forEach((a,i)=>{console.log(l__default.default.gray(` ${i+1}. ${a}`));})),console.log("");}var ze={$schema:"https://vaif.studio/schemas/config.json",projectId:"",database:{url:"${DATABASE_URL}",schema:"public"},types:{output:"./src/types/database.ts"},api:{baseUrl:"https://api.vaif.studio"}};async function ne(t){let e=L__default.default("Initializing VAIF configuration...").start(),o=v__default.default.resolve("vaif.config.json");T__default.default.existsSync(o)&&!t.force&&(e.fail("vaif.config.json already exists"),console.log(l__default.default.yellow(`
1153
+ Use --force to overwrite existing configuration.`)),process.exit(1));try{if(T__default.default.writeFileSync(o,JSON.stringify(ze,null,2),"utf-8"),e.succeed("Created vaif.config.json"),t.template)await oe(t.template,{force:t.force});else {let n=v__default.default.resolve(".env.example");if(T__default.default.existsSync(n)||(T__default.default.writeFileSync(n,`# VAIF Configuration
65
1154
  DATABASE_URL=postgresql://user:password@localhost:5432/database
66
1155
  VAIF_API_KEY=your-api-key
67
- `,"utf-8"),console.log(g__default.default.gray("Created .env.example"))),o.typescript){let s=b__default.default.resolve("src/types");A__default.default.existsSync(s)||(A__default.default.mkdirSync(s,{recursive:!0}),console.log(g__default.default.gray("Created src/types directory")));}console.log(""),console.log(g__default.default.green("VAIF initialized successfully!")),console.log(""),console.log(g__default.default.gray("Next steps:")),console.log(g__default.default.gray(" 1. Update vaif.config.json with your project ID")),console.log(g__default.default.gray(" 2. Set DATABASE_URL in your environment")),console.log(g__default.default.gray(" 3. Run: npx vaif generate")),console.log("");}catch(n){e.fail("Failed to initialize"),n instanceof Error&&console.error(g__default.default.red(`
68
- Error: ${n.message}`)),process.exit(1);}}var V=b__default.default.join(Ae__default.default.homedir(),".vaif"),F=b__default.default.join(V,"auth.json"),Fe=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ce(){A__default.default.existsSync(V)||A__default.default.mkdirSync(V,{recursive:true});}function Re(o){Ce(),A__default.default.writeFileSync(F,JSON.stringify(o,null,2),"utf-8"),A__default.default.chmodSync(F,384);}function S(){if(!A__default.default.existsSync(F))return null;try{let o=A__default.default.readFileSync(F,"utf-8");return JSON.parse(o)}catch{return null}}function De(o){let e=Ee__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(o,n=>{e.close(),t(n);});})}async function q(o){try{let e=await fetch(`${Fe}/v1/auth/me`,{headers:{Authorization:`Bearer ${o}`}});return e.ok?{valid:!0,email:(await e.json()).email}:{valid:!1}}catch{return {valid:false}}}async function H(o){let e=G__default.default();console.log(""),console.log(g__default.default.bold("Welcome to VAIF CLI")),console.log(g__default.default.gray("Authenticate to access your VAIF projects")),console.log("");let t=o.token;t||(console.log(g__default.default.gray("To get your API token:")),console.log(g__default.default.gray(" 1. Go to https://vaif.studio/settings/api-keys")),console.log(g__default.default.gray(" 2. Create a new API key or copy an existing one")),console.log(""),t=await De(g__default.default.cyan("Enter your API token: ")),(!t||t.trim()==="")&&(console.log(g__default.default.red(`
69
- No token provided. Login cancelled.`)),process.exit(1))),e.start("Validating token...");let{valid:n,email:s}=await q(t.trim());n||(e.fail("Invalid token"),console.log(g__default.default.red(`
70
- The provided token is invalid or expired.`)),console.log(g__default.default.gray("Please check your token and try again.")),process.exit(1));let i={token:t.trim(),email:s,projectId:o.projectId,expiresAt:new Date(Date.now()+720*60*60*1e3).toISOString()};Re(i),e.succeed("Logged in successfully"),console.log(""),s&&console.log(g__default.default.green(` Authenticated as: ${s}`)),console.log(g__default.default.gray(` Config saved to: ${F}`)),console.log(""),console.log(g__default.default.gray("You can now use VAIF CLI commands like:")),console.log(g__default.default.gray(" vaif pull - Pull remote schema")),console.log(g__default.default.gray(" vaif push - Push schema changes")),console.log(g__default.default.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function W(){A__default.default.existsSync(F)?(A__default.default.unlinkSync(F),console.log(g__default.default.green("Logged out successfully"))):console.log(g__default.default.yellow("Not currently logged in"));}async function Q(){let o=S();(!o||!o.token)&&(console.log(g__default.default.yellow("Not logged in")),console.log(g__default.default.gray("Run `vaif login` to authenticate")),process.exit(1));let e=G__default.default("Checking authentication...").start(),{valid:t,email:n}=await q(o.token);t||(e.fail("Session expired"),console.log(g__default.default.yellow(`
71
- Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Authenticated"),console.log(""),console.log(g__default.default.green(` Email: ${n||o.email||"Unknown"}`)),o.projectId&&console.log(g__default.default.green(` Project: ${o.projectId}`)),console.log("");}var Ne=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Oe(o,e,t="public"){let n=await fetch(`${Ne}/v1/projects/${e}/schema?schema=${t}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!n.ok){let s=await n.text();throw new Error(`Failed to fetch schema: ${s}`)}return n.json()}async function X(o){let e=G__default.default(),t=S();(!t||!t.token)&&(console.log(g__default.default.red("Not logged in")),console.log(g__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",s=null;e.start("Loading configuration...");try{s=await j(n);}catch(r){e.fail("Failed to load config"),console.log(g__default.default.red(`
72
- Error: ${r}`)),process.exit(1);}s||(e.fail("No configuration found"),console.log(g__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let i=o.projectId||s.projectId||t.projectId;i||(e.fail("No project ID specified"),console.log(g__default.default.yellow(`
73
- Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let r=o.schema||s.database?.schema||"public",l=await Oe(t.token,i,r);e.succeed("Schema fetched successfully");let a=o.output||b__default.default.resolve("vaif.schema.json"),u={$schema:"https://vaif.studio/schemas/schema.json",projectId:i,schema:r,pulledAt:new Date().toISOString(),...l};A__default.default.writeFileSync(a,JSON.stringify(u,null,2),"utf-8"),console.log(""),console.log(g__default.default.green(`Schema saved to: ${a}`)),console.log(""),console.log(g__default.default.gray("Schema summary:")),console.log(g__default.default.gray(` Tables: ${(l.tables||[]).length}`)),console.log(g__default.default.gray(` Enums: ${(l.enums||[]).length}`)),console.log(g__default.default.gray(` Functions: ${(l.functions||[]).length}`)),console.log(""),console.log(g__default.default.gray("Next steps:")),console.log(g__default.default.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(g__default.default.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(r){e.fail("Failed to fetch schema"),r instanceof Error&&console.log(g__default.default.red(`
74
- Error: ${r.message}`)),process.exit(1);}}var ee=process.env.VAIF_API_URL||"https://api.vaif.studio";function ze(o){let e=Ee__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(o,n=>{e.close(),t(n);});})}async function Me(o,e,t){let n=await fetch(`${ee}/v1/projects/${e}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!n.ok){let s=await n.text();throw new Error(`Failed to preview changes: ${s}`)}return n.json()}async function Be(o,e,t){let n=await fetch(`${ee}/v1/projects/${e}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!n.ok){let s=await n.text();throw new Error(`Failed to apply changes: ${s}`)}return n.json()}function Ye(o){if(console.log(""),console.log(g__default.default.bold("Schema Changes:")),console.log(""),o.added.length===0&&o.modified.length===0&&o.removed.length===0){console.log(g__default.default.gray(" No changes detected. Schema is up to date."));return}if(o.added.length>0){console.log(g__default.default.green.bold(" + Added:"));for(let e of o.added)console.log(g__default.default.green(` + ${e.type}: ${e.name}`));console.log("");}if(o.modified.length>0){console.log(g__default.default.yellow.bold(" ~ Modified:"));for(let e of o.modified){console.log(g__default.default.yellow(` ~ ${e.type}: ${e.name}`));for(let t of e.changes)console.log(g__default.default.gray(` ${t}`));}console.log("");}if(o.removed.length>0){console.log(g__default.default.red.bold(" - Removed:"));for(let e of o.removed)console.log(g__default.default.red(` - ${e.type}: ${e.name}`));console.log("");}}async function oe(o){let e=G__default.default(),t=S();(!t||!t.token)&&(console.log(g__default.default.red("Not logged in")),console.log(g__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",s=null;e.start("Loading configuration...");try{s=await j(n);}catch(a){e.fail("Failed to load config"),console.log(g__default.default.red(`
75
- Error: ${a}`)),process.exit(1);}s||(e.fail("No configuration found"),console.log(g__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let i=o.projectId||s.projectId||t.projectId;i||(e.fail("No project ID specified"),console.log(g__default.default.yellow(`
76
- Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let r=o.schema||b__default.default.resolve("vaif.schema.json");A__default.default.existsSync(r)||(e.fail("No local schema found"),console.log(g__default.default.yellow(`
77
- Expected schema file at: ${r}`)),console.log(g__default.default.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let l;try{let a=A__default.default.readFileSync(r,"utf-8");l=JSON.parse(a);}catch(a){e.fail("Failed to parse schema file"),a instanceof Error&&console.log(g__default.default.red(`
78
- Error: ${a.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:a,sql:u}=await Me(t.token,i,l);if(e.stop(),Ye(a),a.added.length===0&&a.modified.length===0&&a.removed.length===0){console.log("");return}if(u.length>0){console.log(g__default.default.bold("SQL Migrations:")),console.log("");for(let p of u)console.log(g__default.default.gray(` ${p}`));console.log("");}if(o.dryRun){console.log(g__default.default.yellow("Dry run mode - no changes applied.")),console.log(g__default.default.gray("Remove --dry-run to apply these changes."));return}if(!o.force){a.removed.length>0&&(console.log(g__default.default.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(g__default.default.red(" This action cannot be undone!")),console.log(""));let c=await ze(g__default.default.cyan("Apply these changes? [y/N] "));if(c.toLowerCase()!=="y"&&c.toLowerCase()!=="yes"){console.log(g__default.default.yellow(`
79
- Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let f=await Be(t.token,i,l);if(f.success){if(e.succeed("Schema changes applied successfully"),console.log(""),f.migrations.length>0){console.log(g__default.default.gray("Migrations applied:"));for(let p of f.migrations)console.log(g__default.default.gray(` - ${p}`));console.log("");}console.log(g__default.default.green("Your database schema is now up to date.")),console.log(g__default.default.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else e.fail("Failed to apply some changes");}catch(a){e.fail("Failed to push schema changes"),a instanceof Error&&console.log(g__default.default.red(`
80
- Error: ${a.message}`)),process.exit(1);}}var re=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Je(o,e,t){let n=await fetch(`${re}/v1/projects/${e}/functions`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({name:t.name,runtime:t.runtime,entrypoint:t.entrypoint,code:t.code,envId:t.envId})});if(!n.ok){let s=await n.text();throw new Error(`Failed to deploy function: ${s}`)}return n.json()}async function Ke(o,e,t){let n=new URL(`${re}/v1/projects/${e}/functions`);t&&n.searchParams.set("envId",t);let s=await fetch(n.toString(),{headers:{Authorization:`Bearer ${o}`}});if(!s.ok){let i=await s.text();throw new Error(`Failed to list functions: ${i}`)}return s.json()}function ne(o){switch(b__default.default.extname(o).toLowerCase()){case ".ts":return "typescript";case ".js":case ".mjs":return "nodejs";case ".py":return "python";case ".go":return "go";case ".rs":return "rust";default:return "nodejs"}}function te(o){let e=[],t=[".ts",".js",".mjs",".py",".go",".rs"];function n(s){if(!A__default.default.existsSync(s))return;let i=A__default.default.readdirSync(s,{withFileTypes:true});for(let r of i){let l=b__default.default.join(s,r.name);if(r.isDirectory())r.name!=="node_modules"&&!r.name.startsWith(".")&&n(l);else if(r.isFile()){let a=b__default.default.extname(r.name).toLowerCase();t.includes(a)&&(r.name==="index.ts"||r.name==="index.js"||r.name.includes("function")||r.name.includes("handler"))&&e.push(l);}}}return n(o),e}async function ie(o){let e=G__default.default(),t=S();(!t||!t.token)&&(console.log(g__default.default.red("Not logged in")),console.log(g__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",s=null;try{s=await j(n);}catch{}let i=o.projectId||s?.projectId||t.projectId;i||(console.log(g__default.default.red("No project ID specified")),console.log(g__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(g__default.default.bold("VAIF Functions Deploy")),console.log(""),e.start("Scanning for function files...");let r=b__default.default.resolve("functions"),l=b__default.default.resolve("src/functions"),a=[];if(o.entrypoint){let c=b__default.default.resolve(o.entrypoint);A__default.default.existsSync(c)||(e.fail(`File not found: ${o.entrypoint}`),process.exit(1)),a=[c];}else a=[...te(r),...te(l)];a.length===0&&(e.fail("No function files found"),console.log(g__default.default.yellow(`
81
- Place your functions in:`)),console.log(g__default.default.gray(" - ./functions/")),console.log(g__default.default.gray(" - ./src/functions/")),console.log(g__default.default.gray(`
82
- Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${a.length} function(s)`),o.name&&(a=a.filter(c=>b__default.default.basename(c,b__default.default.extname(c)).includes(o.name)),a.length===0&&(console.log(g__default.default.yellow(`
83
- No functions matching "${o.name}" found`)),process.exit(1))),console.log(""),console.log(g__default.default.gray("Functions to deploy:"));for(let c of a){let h=b__default.default.basename(b__default.default.dirname(c))||b__default.default.basename(c,b__default.default.extname(c)),E=o.runtime||ne(c);console.log(g__default.default.gray(` - ${h} (${E})`));}if(console.log(""),o.dryRun){console.log(g__default.default.yellow("Dry run mode - no functions deployed."));return}let u=[];for(let c of a){let h=b__default.default.basename(b__default.default.dirname(c))||b__default.default.basename(c,b__default.default.extname(c)),E=o.runtime||ne(c);e.start(`Deploying ${h}...`);try{let R=A__default.default.readFileSync(c,"utf-8"),D=await Je(t.token,i,{name:h,runtime:E,entrypoint:b__default.default.basename(c),code:R,envId:o.envId});e.succeed(`Deployed ${h} (v${D.version})`),u.push({name:h,success:!0,version:D.version});}catch(R){let D=R instanceof Error?R.message:"Unknown error";e.fail(`Failed to deploy ${h}`),u.push({name:h,success:false,error:D});}}console.log("");let f=u.filter(c=>c.success).length;if(u.filter(c=>!c.success).length===0)console.log(g__default.default.green(`\u2713 Successfully deployed ${f} function(s)`));else {console.log(g__default.default.yellow(`Deployed ${f}/${u.length} function(s)`)),console.log(""),console.log(g__default.default.red("Failed deployments:"));for(let c of u.filter(h=>!h.success))console.log(g__default.default.red(` - ${c.name}: ${c.error}`));}console.log("");}async function ae(o){let e=G__default.default(),t=S();(!t||!t.token)&&(console.log(g__default.default.red("Not logged in")),console.log(g__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",s=null;try{s=await j(n);}catch{}let i=o.projectId||s?.projectId||t.projectId;i||(console.log(g__default.default.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let r=await Ke(t.token,i,o.envId);if(e.stop(),r.length===0){console.log(g__default.default.yellow(`
84
- No functions found`)),console.log(g__default.default.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(g__default.default.bold(`Functions (${r.length}):`)),console.log(""),console.log(g__default.default.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"VERSION".padEnd(10)+"STATUS".padEnd(12)+"LAST DEPLOYED")),console.log(g__default.default.gray(" "+"-".repeat(80)));for(let l of r){let a=l.status==="active"?g__default.default.green:l.status==="deploying"?g__default.default.yellow:g__default.default.red;console.log(" "+l.name.padEnd(25)+l.runtime.padEnd(15)+`v${l.version}`.padEnd(10)+a(l.status.padEnd(12))+(l.lastDeployed?new Date(l.lastDeployed).toLocaleDateString():"-"));}console.log("");}catch(r){e.fail("Failed to fetch functions"),r instanceof Error&&console.log(g__default.default.red(`
85
- Error: ${r.message}`)),process.exit(1);}}var ge=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Ge(o,e,t,n,s){let i=await fetch(`${ge}/v1/projects/${e}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({table:t,records:n,truncate:s?.truncate??false})});if(!i.ok){let r=await i.text();throw new Error(`Failed to seed ${t}: ${r}`)}return i.json()}async function qe(o,e){let t=await fetch(`${ge}/v1/projects/${e}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!t.ok){let n=await t.text();throw new Error(`Failed to reset database: ${n}`)}return t.json()}function U(o){let e=[];if(!A__default.default.existsSync(o))return e;let t=A__default.default.readdirSync(o,{withFileTypes:true});for(let n of t)if(n.isFile()){let s=b__default.default.extname(n.name).toLowerCase();(s===".json"||s===".ts"||s===".js")&&e.push(b__default.default.join(o,n.name));}return e.sort()}async function ce(o){let e=b__default.default.extname(o).toLowerCase();if(e===".json"){let t=A__default.default.readFileSync(o,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?[{table:b__default.default.basename(o,e),data:n}]:n.table&&n.data?[n]:Object.entries(n).map(([s,i])=>({table:s,data:i}))}else if(e===".ts"||e===".js"){let t=await import(o),n=t.default||t;return typeof n=="function"?n():n}throw new Error(`Unsupported file format: ${e}`)}async function fe(o){let e=G__default.default(),t=S();(!t||!t.token)&&(console.log(g__default.default.red("Not logged in")),console.log(g__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",s=null;try{s=await j(n);}catch{}let i=o.projectId||s?.projectId||t.projectId;i||(console.log(g__default.default.red("No project ID specified")),console.log(g__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(g__default.default.bold("VAIF Database Seed")),console.log("");let r=[];if(o.file){let f=b__default.default.resolve(o.file);A__default.default.existsSync(f)||(console.log(g__default.default.red(`File not found: ${o.file}`)),process.exit(1)),r=[f];}else {let f=b__default.default.resolve("seeds"),p=b__default.default.resolve("prisma/seed"),c=b__default.default.resolve("db/seeds");r=[...U(f),...U(p),...U(c)];}r.length===0&&(console.log(g__default.default.yellow("No seed files found")),console.log(g__default.default.gray(`
86
- Place your seed files in one of these directories:`)),console.log(g__default.default.gray(" - ./seeds/")),console.log(g__default.default.gray(" - ./prisma/seed/")),console.log(g__default.default.gray(" - ./db/seeds/")),console.log(g__default.default.gray(`
87
- Or specify a file with --file`)),console.log(g__default.default.gray(`
88
- Example seed file (seeds/users.json):`)),console.log(g__default.default.gray(" [")),console.log(g__default.default.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(g__default.default.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(g__default.default.gray(" ]")),process.exit(1)),console.log(g__default.default.gray("Seed files found:"));for(let f of r)console.log(g__default.default.gray(` - ${b__default.default.relative(process.cwd(),f)}`));if(console.log(""),o.truncate&&(console.log(g__default.default.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),o.dryRun){console.log(g__default.default.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let f of r){e.start(`Loading ${b__default.default.basename(f)}...`);try{let p=await ce(f);e.stop();for(let c of p)o.table&&c.table!==o.table||(console.log(g__default.default.cyan(`Table: ${c.table}`)),console.log(g__default.default.gray(` Records: ${c.data.length}`)),c.data.length>0&&console.log(g__default.default.gray(` Sample: ${JSON.stringify(c.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(p){e.fail(`Failed to load ${b__default.default.basename(f)}`),p instanceof Error&&console.log(g__default.default.red(` Error: ${p.message}`));}}return}let l=[];for(let f of r){e.start(`Processing ${b__default.default.basename(f)}...`);try{let p=await ce(f);e.stop();for(let c of p)if(!(o.table&&c.table!==o.table)){if(c.data.length===0){console.log(g__default.default.gray(` Skipping ${c.table} (no records)`));continue}e.start(`Seeding ${c.table} (${c.data.length} records)...`);try{let h=await Ge(t.token,i,c.table,c.data,{truncate:o.truncate});e.succeed(`Seeded ${c.table}: ${h.inserted} records`),l.push({table:c.table,inserted:h.inserted});}catch(h){let E=h instanceof Error?h.message:"Unknown error";e.fail(`Failed to seed ${c.table}`),l.push({table:c.table,inserted:0,error:E});}}}catch(p){e.fail(`Failed to load ${b__default.default.basename(f)}`),p instanceof Error&&console.log(g__default.default.red(` Error: ${p.message}`));}}console.log("");let a=l.reduce((f,p)=>f+p.inserted,0),u=l.filter(f=>f.error).length;if(u===0)console.log(g__default.default.green(`\u2713 Successfully seeded ${a} records across ${l.length} table(s)`));else {console.log(g__default.default.yellow(`Seeded ${a} records with ${u} error(s)`)),console.log(""),console.log(g__default.default.red("Errors:"));for(let f of l.filter(p=>p.error))console.log(g__default.default.red(` - ${f.table}: ${f.error}`));}console.log("");}async function ue(o){let e=G__default.default(),t=S();(!t||!t.token)&&(console.log(g__default.default.red("Not logged in")),console.log(g__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",s=null;try{s=await j(n);}catch{}let i=o.projectId||s?.projectId||t.projectId;i||(console.log(g__default.default.red("No project ID specified")),process.exit(1)),console.log(""),console.log(g__default.default.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(g__default.default.red("This will:")),console.log(g__default.default.red(" - Drop all tables")),console.log(g__default.default.red(" - Delete all data")),console.log(g__default.default.red(" - Reset migrations")),console.log(""),console.log(g__default.default.red.bold("This action cannot be undone!")),console.log(""),o.force||(console.log(g__default.default.yellow("Use --force to confirm this action.")),process.exit(1)),e.start("Resetting database...");try{await qe(t.token,i),e.succeed("Database reset complete"),console.log(""),console.log(g__default.default.gray("Your database is now empty.")),console.log(g__default.default.gray("Run `vaif push` to apply your schema, then `vaif db seed` to seed data.")),console.log("");}catch(r){e.fail("Failed to reset database"),r instanceof Error&&console.log(g__default.default.red(`
89
- Error: ${r.message}`)),process.exit(1);}}commander.program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.0.2");commander.program.command("login").description("Authenticate with VAIF").option("-t, --token <token>","API token (will prompt if not provided)").option("-p, --project-id <id>","Default project ID").action(H);commander.program.command("logout").description("Log out and remove stored credentials").action(W);commander.program.command("whoami").description("Show current authenticated user").action(Q);commander.program.command("init").description("Initialize VAIF configuration in your project").option("--typescript","Setup for TypeScript project").option("-f, --force","Overwrite existing config").action(J);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(X);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(oe);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(Y);var pe=commander.program.command("functions").alias("fn").description("Manage serverless functions");pe.command("deploy").description("Deploy functions to your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID").option("-n, --name <name>","Function name filter").option("-r, --runtime <runtime>","Runtime (nodejs, typescript, python)").option("--entrypoint <file>","Specific entrypoint file").option("--dry-run","Preview deployment without deploying").action(ie);pe.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(ae);var de=commander.program.command("db").description("Database management commands");de.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(fe);de.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(ue);commander.program.parse(process.argv);process.argv.slice(2).length||commander.program.outputHelp();
1156
+ `,"utf-8"),console.log(l__default.default.gray("Created .env.example"))),t.typescript){let s=v__default.default.resolve("src/types");T__default.default.existsSync(s)||(T__default.default.mkdirSync(s,{recursive:!0}),console.log(l__default.default.gray("Created src/types directory")));}console.log(""),console.log(l__default.default.green("VAIF initialized successfully!")),console.log(""),console.log(l__default.default.gray("Next steps:")),console.log(l__default.default.gray(" 1. Update vaif.config.json with your project ID")),console.log(l__default.default.gray(" 2. Set DATABASE_URL in your environment")),console.log(l__default.default.gray(" 3. Run: npx vaif generate")),console.log("");}}catch(n){e.fail("Failed to initialize"),n instanceof Error&&console.error(l__default.default.red(`
1157
+ Error: ${n.message}`)),process.exit(1);}}var J=v__default.default.join(Je__default.default.homedir(),".vaif"),k=v__default.default.join(J,"auth.json"),He=process.env.VAIF_API_URL||"https://api.vaif.studio";function Xe(){T__default.default.existsSync(J)||T__default.default.mkdirSync(J,{recursive:true});}function We(t){Xe(),T__default.default.writeFileSync(k,JSON.stringify(t,null,2),"utf-8"),T__default.default.chmodSync(k,384);}function _(){if(!T__default.default.existsSync(k))return null;try{let t=T__default.default.readFileSync(k,"utf-8");return JSON.parse(t)}catch{return null}}function Qe(t){let e=Ge__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}async function se(t){try{let e=await fetch(`${He}/v1/auth/me`,{headers:{Authorization:`Bearer ${t}`}});return e.ok?{valid:!0,email:(await e.json()).email}:{valid:!1}}catch{return {valid:false}}}async function ae(t){let e=L__default.default();console.log(""),console.log(l__default.default.bold("Welcome to VAIF CLI")),console.log(l__default.default.gray("Authenticate to access your VAIF projects")),console.log("");let o=t.token;o||(console.log(l__default.default.gray("To get your API token:")),console.log(l__default.default.gray(" 1. Go to https://vaif.studio/settings/api-keys")),console.log(l__default.default.gray(" 2. Create a new API key or copy an existing one")),console.log(""),o=await Qe(l__default.default.cyan("Enter your API token: ")),(!o||o.trim()==="")&&(console.log(l__default.default.red(`
1158
+ No token provided. Login cancelled.`)),process.exit(1))),e.start("Validating token...");let{valid:n,email:s}=await se(o.trim());n||(e.fail("Invalid token"),console.log(l__default.default.red(`
1159
+ The provided token is invalid or expired.`)),console.log(l__default.default.gray("Please check your token and try again.")),process.exit(1));let a={token:o.trim(),email:s,projectId:t.projectId,expiresAt:new Date(Date.now()+720*60*60*1e3).toISOString()};We(a),e.succeed("Logged in successfully"),console.log(""),s&&console.log(l__default.default.green(` Authenticated as: ${s}`)),console.log(l__default.default.gray(` Config saved to: ${k}`)),console.log(""),console.log(l__default.default.gray("You can now use VAIF CLI commands like:")),console.log(l__default.default.gray(" vaif pull - Pull remote schema")),console.log(l__default.default.gray(" vaif push - Push schema changes")),console.log(l__default.default.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function ce(){T__default.default.existsSync(k)?(T__default.default.unlinkSync(k),console.log(l__default.default.green("Logged out successfully"))):console.log(l__default.default.yellow("Not currently logged in"));}async function le(){let t=_();(!t||!t.token)&&(console.log(l__default.default.yellow("Not logged in")),console.log(l__default.default.gray("Run `vaif login` to authenticate")),process.exit(1));let e=L__default.default("Checking authentication...").start(),{valid:o,email:n}=await se(t.token);o||(e.fail("Session expired"),console.log(l__default.default.yellow(`
1160
+ Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Authenticated"),console.log(""),console.log(l__default.default.green(` Email: ${n||t.email||"Unknown"}`)),t.projectId&&console.log(l__default.default.green(` Project: ${t.projectId}`)),console.log("");}var ot=process.env.VAIF_API_URL||"https://api.vaif.studio";async function nt(t,e,o="public"){let n=await fetch(`${ot}/v1/projects/${e}/schema?schema=${o}`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!n.ok){let s=await n.text();throw new Error(`Failed to fetch schema: ${s}`)}return n.json()}async function pe(t){let e=L__default.default(),o=_();(!o||!o.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",s=null;e.start("Loading configuration...");try{s=await b(n);}catch(i){e.fail("Failed to load config"),console.log(l__default.default.red(`
1161
+ Error: ${i}`)),process.exit(1);}s||(e.fail("No configuration found"),console.log(l__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let a=t.projectId||s.projectId||o.projectId;a||(e.fail("No project ID specified"),console.log(l__default.default.yellow(`
1162
+ Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let i=t.schema||s.database?.schema||"public",r=await nt(o.token,a,i);e.succeed("Schema fetched successfully");let c=t.output||v__default.default.resolve("vaif.schema.json"),g={$schema:"https://vaif.studio/schemas/schema.json",projectId:a,schema:i,pulledAt:new Date().toISOString(),...r};T__default.default.writeFileSync(c,JSON.stringify(g,null,2),"utf-8"),console.log(""),console.log(l__default.default.green(`Schema saved to: ${c}`)),console.log(""),console.log(l__default.default.gray("Schema summary:")),console.log(l__default.default.gray(` Tables: ${(r.tables||[]).length}`)),console.log(l__default.default.gray(` Enums: ${(r.enums||[]).length}`)),console.log(l__default.default.gray(` Functions: ${(r.functions||[]).length}`)),console.log(""),console.log(l__default.default.gray("Next steps:")),console.log(l__default.default.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(l__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(l__default.default.red(`
1163
+ Error: ${i.message}`)),process.exit(1);}}var ge=process.env.VAIF_API_URL||"https://api.vaif.studio";function at(t){let e=Ge__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}async function ct(t,e,o){let n=await fetch(`${ge}/v1/projects/${e}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!n.ok){let s=await n.text();throw new Error(`Failed to preview changes: ${s}`)}return n.json()}async function lt(t,e,o){let n=await fetch(`${ge}/v1/projects/${e}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!n.ok){let s=await n.text();throw new Error(`Failed to apply changes: ${s}`)}return n.json()}function pt(t){if(console.log(""),console.log(l__default.default.bold("Schema Changes:")),console.log(""),t.added.length===0&&t.modified.length===0&&t.removed.length===0){console.log(l__default.default.gray(" No changes detected. Schema is up to date."));return}if(t.added.length>0){console.log(l__default.default.green.bold(" + Added:"));for(let e of t.added)console.log(l__default.default.green(` + ${e.type}: ${e.name}`));console.log("");}if(t.modified.length>0){console.log(l__default.default.yellow.bold(" ~ Modified:"));for(let e of t.modified){console.log(l__default.default.yellow(` ~ ${e.type}: ${e.name}`));for(let o of e.changes)console.log(l__default.default.gray(` ${o}`));}console.log("");}if(t.removed.length>0){console.log(l__default.default.red.bold(" - Removed:"));for(let e of t.removed)console.log(l__default.default.red(` - ${e.type}: ${e.name}`));console.log("");}}async function de(t){let e=L__default.default(),o=_();(!o||!o.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",s=null;e.start("Loading configuration...");try{s=await b(n);}catch(c){e.fail("Failed to load config"),console.log(l__default.default.red(`
1164
+ Error: ${c}`)),process.exit(1);}s||(e.fail("No configuration found"),console.log(l__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let a=t.projectId||s.projectId||o.projectId;a||(e.fail("No project ID specified"),console.log(l__default.default.yellow(`
1165
+ Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=t.schema||v__default.default.resolve("vaif.schema.json");T__default.default.existsSync(i)||(e.fail("No local schema found"),console.log(l__default.default.yellow(`
1166
+ Expected schema file at: ${i}`)),console.log(l__default.default.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let r;try{let c=T__default.default.readFileSync(i,"utf-8");r=JSON.parse(c);}catch(c){e.fail("Failed to parse schema file"),c instanceof Error&&console.log(l__default.default.red(`
1167
+ Error: ${c.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:c,sql:g}=await ct(o.token,a,r);if(e.stop(),pt(c),c.added.length===0&&c.modified.length===0&&c.removed.length===0){console.log("");return}if(g.length>0){console.log(l__default.default.bold("SQL Migrations:")),console.log("");for(let f of g)console.log(l__default.default.gray(` ${f}`));console.log("");}if(t.dryRun){console.log(l__default.default.yellow("Dry run mode - no changes applied.")),console.log(l__default.default.gray("Remove --dry-run to apply these changes."));return}if(!t.force){c.removed.length>0&&(console.log(l__default.default.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(l__default.default.red(" This action cannot be undone!")),console.log(""));let p=await at(l__default.default.cyan("Apply these changes? [y/N] "));if(p.toLowerCase()!=="y"&&p.toLowerCase()!=="yes"){console.log(l__default.default.yellow(`
1168
+ Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let d=await lt(o.token,a,r);if(d.success){if(e.succeed("Schema changes applied successfully"),console.log(""),d.migrations.length>0){console.log(l__default.default.gray("Migrations applied:"));for(let f of d.migrations)console.log(l__default.default.gray(` - ${f}`));console.log("");}console.log(l__default.default.green("Your database schema is now up to date.")),console.log(l__default.default.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else e.fail("Failed to apply some changes");}catch(c){e.fail("Failed to push schema changes"),c instanceof Error&&console.log(l__default.default.red(`
1169
+ Error: ${c.message}`)),process.exit(1);}}var ye=process.env.VAIF_API_URL||"https://api.vaif.studio";async function ft(t,e,o){let n=await fetch(`${ye}/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 s=await n.text();throw new Error(`Failed to deploy function: ${s}`)}return n.json()}async function gt(t,e,o){let n=new URL(`${ye}/v1/projects/${e}/functions`);o&&n.searchParams.set("envId",o);let s=await fetch(n.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!s.ok){let a=await s.text();throw new Error(`Failed to list functions: ${a}`)}return s.json()}function ue(t){switch(v__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"];function n(s){if(!T__default.default.existsSync(s))return;let a=T__default.default.readdirSync(s,{withFileTypes:true});for(let i of a){let r=v__default.default.join(s,i.name);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&n(r);else if(i.isFile()){let c=v__default.default.extname(i.name).toLowerCase();o.includes(c)&&(i.name==="index.ts"||i.name==="index.js"||i.name.includes("function")||i.name.includes("handler"))&&e.push(r);}}}return n(t),e}async function ve(t){let e=L__default.default(),o=_();(!o||!o.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",s=null;try{s=await b(n);}catch{}let a=t.projectId||s?.projectId||o.projectId;a||(console.log(l__default.default.red("No project ID specified")),console.log(l__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(l__default.default.bold("VAIF Functions Deploy")),console.log(""),e.start("Scanning for function files...");let i=v__default.default.resolve("functions"),r=v__default.default.resolve("src/functions"),c=[];if(t.entrypoint){let p=v__default.default.resolve(t.entrypoint);T__default.default.existsSync(p)||(e.fail(`File not found: ${t.entrypoint}`),process.exit(1)),c=[p];}else c=[...me(i),...me(r)];c.length===0&&(e.fail("No function files found"),console.log(l__default.default.yellow(`
1170
+ Place your functions in:`)),console.log(l__default.default.gray(" - ./functions/")),console.log(l__default.default.gray(" - ./src/functions/")),console.log(l__default.default.gray(`
1171
+ Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${c.length} function(s)`),t.name&&(c=c.filter(p=>v__default.default.basename(p,v__default.default.extname(p)).includes(t.name)),c.length===0&&(console.log(l__default.default.yellow(`
1172
+ No functions matching "${t.name}" found`)),process.exit(1))),console.log(""),console.log(l__default.default.gray("Functions to deploy:"));for(let p of c){let u=v__default.default.basename(v__default.default.dirname(p))||v__default.default.basename(p,v__default.default.extname(p)),A=t.runtime||ue(p);console.log(l__default.default.gray(` - ${u} (${A})`));}if(console.log(""),t.dryRun){console.log(l__default.default.yellow("Dry run mode - no functions deployed."));return}let g=[];for(let p of c){let u=v__default.default.basename(v__default.default.dirname(p))||v__default.default.basename(p,v__default.default.extname(p)),A=t.runtime||ue(p);e.start(`Deploying ${u}...`);try{let R=T__default.default.readFileSync(p,"utf-8"),O=await ft(o.token,a,{name:u,runtime:A,entrypoint:v__default.default.basename(p),code:R,envId:t.envId});e.succeed(`Deployed ${u} (v${O.version})`),g.push({name:u,success:!0,version:O.version});}catch(R){let O=R instanceof Error?R.message:"Unknown error";e.fail(`Failed to deploy ${u}`),g.push({name:u,success:false,error:O});}}console.log("");let d=g.filter(p=>p.success).length;if(g.filter(p=>!p.success).length===0)console.log(l__default.default.green(`\u2713 Successfully deployed ${d} function(s)`));else {console.log(l__default.default.yellow(`Deployed ${d}/${g.length} function(s)`)),console.log(""),console.log(l__default.default.red("Failed deployments:"));for(let p of g.filter(u=>!u.success))console.log(l__default.default.red(` - ${p.name}: ${p.error}`));}console.log("");}async function Ie(t){let e=L__default.default(),o=_();(!o||!o.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",s=null;try{s=await b(n);}catch{}let a=t.projectId||s?.projectId||o.projectId;a||(console.log(l__default.default.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let i=await gt(o.token,a,t.envId);if(e.stop(),i.length===0){console.log(l__default.default.yellow(`
1173
+ No functions found`)),console.log(l__default.default.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(l__default.default.bold(`Functions (${i.length}):`)),console.log(""),console.log(l__default.default.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"VERSION".padEnd(10)+"STATUS".padEnd(12)+"LAST DEPLOYED")),console.log(l__default.default.gray(" "+"-".repeat(80)));for(let r of i){let c=r.status==="active"?l__default.default.green:r.status==="deploying"?l__default.default.yellow:l__default.default.red;console.log(" "+r.name.padEnd(25)+r.runtime.padEnd(15)+`v${r.version}`.padEnd(10)+c(r.status.padEnd(12))+(r.lastDeployed?new Date(r.lastDeployed).toLocaleDateString():"-"));}console.log("");}catch(i){e.fail("Failed to fetch functions"),i instanceof Error&&console.log(l__default.default.red(`
1174
+ Error: ${i.message}`)),process.exit(1);}}var K=process.env.VAIF_API_URL||"https://api.vaif.studio";async function dt(t,e,o,n,s){let a=await fetch(`${K}/v1/projects/${e}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({table:o,records:n,truncate:s?.truncate??false})});if(!a.ok){let i=await a.text();throw new Error(`Failed to seed ${o}: ${i}`)}return a.json()}async function ut(t,e){let o=await fetch(`${K}/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 G(t){let e=[];if(!T__default.default.existsSync(t))return e;let o=T__default.default.readdirSync(t,{withFileTypes:true});for(let n of o)if(n.isFile()){let s=v__default.default.extname(n.name).toLowerCase();(s===".json"||s===".ts"||s===".js")&&e.push(v__default.default.join(t,n.name));}return e.sort()}async function be(t){let e=v__default.default.extname(t).toLowerCase();if(e===".json"){let o=T__default.default.readFileSync(t,"utf-8"),n=JSON.parse(o);return Array.isArray(n)?[{table:v__default.default.basename(t,e),data:n}]:n.table&&n.data?[n]:Object.entries(n).map(([s,a])=>({table:s,data:a}))}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 _e(t){let e=L__default.default(),o=_();(!o||!o.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",s=null;try{s=await b(n);}catch{}let a=t.projectId||s?.projectId||o.projectId;a||(console.log(l__default.default.red("No project ID specified")),console.log(l__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(l__default.default.bold("VAIF Database Seed")),console.log("");let i=[];if(t.file){let d=v__default.default.resolve(t.file);T__default.default.existsSync(d)||(console.log(l__default.default.red(`File not found: ${t.file}`)),process.exit(1)),i=[d];}else {let d=v__default.default.resolve("seeds"),f=v__default.default.resolve("prisma/seed"),p=v__default.default.resolve("db/seeds");i=[...G(d),...G(f),...G(p)];}i.length===0&&(console.log(l__default.default.yellow("No seed files found")),console.log(l__default.default.gray(`
1175
+ Place your seed files in one of these directories:`)),console.log(l__default.default.gray(" - ./seeds/")),console.log(l__default.default.gray(" - ./prisma/seed/")),console.log(l__default.default.gray(" - ./db/seeds/")),console.log(l__default.default.gray(`
1176
+ Or specify a file with --file`)),console.log(l__default.default.gray(`
1177
+ Example seed file (seeds/users.json):`)),console.log(l__default.default.gray(" [")),console.log(l__default.default.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(l__default.default.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(l__default.default.gray(" ]")),process.exit(1)),console.log(l__default.default.gray("Seed files found:"));for(let d of i)console.log(l__default.default.gray(` - ${v__default.default.relative(process.cwd(),d)}`));if(console.log(""),t.truncate&&(console.log(l__default.default.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),t.dryRun){console.log(l__default.default.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let d of i){e.start(`Loading ${v__default.default.basename(d)}...`);try{let f=await be(d);e.stop();for(let p of f)t.table&&p.table!==t.table||(console.log(l__default.default.cyan(`Table: ${p.table}`)),console.log(l__default.default.gray(` Records: ${p.data.length}`)),p.data.length>0&&console.log(l__default.default.gray(` Sample: ${JSON.stringify(p.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(f){e.fail(`Failed to load ${v__default.default.basename(d)}`),f instanceof Error&&console.log(l__default.default.red(` Error: ${f.message}`));}}return}let r=[];for(let d of i){e.start(`Processing ${v__default.default.basename(d)}...`);try{let f=await be(d);e.stop();for(let p of f)if(!(t.table&&p.table!==t.table)){if(p.data.length===0){console.log(l__default.default.gray(` Skipping ${p.table} (no records)`));continue}e.start(`Seeding ${p.table} (${p.data.length} records)...`);try{let u=await dt(o.token,a,p.table,p.data,{truncate:t.truncate});e.succeed(`Seeded ${p.table}: ${u.inserted} records`),r.push({table:p.table,inserted:u.inserted});}catch(u){let A=u instanceof Error?u.message:"Unknown error";e.fail(`Failed to seed ${p.table}`),r.push({table:p.table,inserted:0,error:A});}}}catch(f){e.fail(`Failed to load ${v__default.default.basename(d)}`),f instanceof Error&&console.log(l__default.default.red(` Error: ${f.message}`));}}console.log("");let c=r.reduce((d,f)=>d+f.inserted,0),g=r.filter(d=>d.error).length;if(g===0)console.log(l__default.default.green(`\u2713 Successfully seeded ${c} records across ${r.length} table(s)`));else {console.log(l__default.default.yellow(`Seeded ${c} records with ${g} error(s)`)),console.log(""),console.log(l__default.default.red("Errors:"));for(let d of r.filter(f=>f.error))console.log(l__default.default.red(` - ${d.table}: ${d.error}`));}console.log("");}async function we(t){let e=L__default.default(),o=_();(!o||!o.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",s=null;try{s=await b(n);}catch{}let a=t.projectId||s?.projectId||o.projectId;a||(console.log(l__default.default.red("No project ID specified")),console.log(l__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=v__default.default.resolve(t.dir||"./drizzle");if(console.log(""),console.log(l__default.default.bold("VAIF Database Push")),console.log(""),!T__default.default.existsSync(i)){let f=v__default.default.resolve("./migrations");T__default.default.existsSync(f)?console.log(l__default.default.gray(`Using migrations from: ${f}`)):(console.log(l__default.default.red(`Migrations directory not found: ${i}`)),console.log(l__default.default.gray(`
1178
+ Expected one of:`)),console.log(l__default.default.gray(" - ./drizzle/")),console.log(l__default.default.gray(" - ./migrations/")),console.log(l__default.default.gray(`
1179
+ Or specify with: vaif db push --dir <path>`)),process.exit(1));}let r=[],c=T__default.default.readdirSync(i,{withFileTypes:true});for(let f of c)if(f.isFile()&&f.name.endsWith(".sql"))r.push(v__default.default.join(i,f.name));else if(f.isDirectory()){let p=T__default.default.readdirSync(v__default.default.join(i,f.name),{withFileTypes:true});for(let u of p)u.isFile()&&u.name.endsWith(".sql")&&r.push(v__default.default.join(i,f.name,u.name));}r.sort(),r.length===0&&(console.log(l__default.default.yellow("No SQL migration files found")),process.exit(1)),console.log(l__default.default.gray(`Found ${r.length} migration(s):`));for(let f of r)console.log(l__default.default.gray(` - ${v__default.default.relative(process.cwd(),f)}`));if(console.log(""),t.dryRun){console.log(l__default.default.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let f of r){let p=T__default.default.readFileSync(f,"utf-8");console.log(l__default.default.cyan(`--- ${v__default.default.basename(f)} ---`)),console.log(l__default.default.gray(p.slice(0,500))),p.length>500&&console.log(l__default.default.gray("...")),console.log("");}return}let g=0,d=0;for(let f of r){let p=T__default.default.readFileSync(f,"utf-8"),u=v__default.default.relative(process.cwd(),f);e.start(`Applying ${u}...`);try{let A=await fetch(`${K}/v1/projects/${a}/schema/execute`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:p})});if(!A.ok){let R=await A.text();throw new Error(R)}e.succeed(`Applied ${u}`),g++;}catch(A){let R=A instanceof Error?A.message:"Unknown error";e.fail(`Failed ${u}: ${R}`),d++;}}console.log(""),console.log(d===0?l__default.default.green(`Successfully applied ${g} migration(s)`):l__default.default.yellow(`Applied ${g}, failed ${d} migration(s)`)),console.log("");}async function Ae(t){let e=L__default.default(),o=_();(!o||!o.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",s=null;try{s=await b(n);}catch{}let a=t.projectId||s?.projectId||o.projectId;a||(console.log(l__default.default.red("No project ID specified")),console.log(l__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=v__default.default.resolve(t.output||"vaif.schema.json");console.log(""),console.log(l__default.default.bold("VAIF Database Pull")),console.log(""),e.start("Pulling schema from remote...");try{let r=await fetch(`${K}/v1/projects/${a}/schema`,{headers:{Authorization:`Bearer ${o.token}`}});if(!r.ok){let d=await r.text();throw new Error(`Failed to pull schema: ${d}`)}let c=await r.json();T__default.default.writeFileSync(i,JSON.stringify(c,null,2),"utf-8"),e.succeed(`Schema written to ${v__default.default.relative(process.cwd(),i)}`);let g=c.tables?.length??Object.keys(c).length;console.log(l__default.default.gray(` ${g} table(s) pulled`)),console.log("");}catch(r){e.fail("Failed to pull schema"),r instanceof Error&&console.log(l__default.default.red(`
1180
+ Error: ${r.message}`)),process.exit(1);}}async function Ee(t){let e=L__default.default(),o=_();(!o||!o.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",s=null;try{s=await b(n);}catch{}let a=t.projectId||s?.projectId||o.projectId;a||(console.log(l__default.default.red("No project ID specified")),process.exit(1)),console.log(""),console.log(l__default.default.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(l__default.default.red("This will:")),console.log(l__default.default.red(" - Drop all tables")),console.log(l__default.default.red(" - Delete all data")),console.log(l__default.default.red(" - Reset migrations")),console.log(""),console.log(l__default.default.red.bold("This action cannot be undone!")),console.log(""),t.force||(console.log(l__default.default.yellow("Use --force to confirm this action.")),process.exit(1)),e.start("Resetting database...");try{await ut(o.token,a),e.succeed("Database reset complete"),console.log(""),console.log(l__default.default.gray("Your database is now empty.")),console.log(l__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(l__default.default.red(`
1181
+ Error: ${i.message}`)),process.exit(1);}}var je=process.env.VAIF_API_URL||"https://api.vaif.studio";function Se(t,e,o){return t.projectId||e?.projectId||o.projectId||null}async function xe(t){let e=L__default.default(),o=_();(!o||!o.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",s=null;try{s=await b(n);}catch{}let a=Se(t,s,o);a||(console.log(l__default.default.red("No project ID specified")),console.log(l__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(l__default.default.bold("VAIF Generate API Key")),console.log(""),e.start("Generating API key...");try{let r=await fetch(`${je}/v1/projects/${a}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i})});if(!r.ok){let g=await r.text();throw new Error(`Failed to generate key: ${g}`)}let c=await r.json();e.succeed("API key generated"),console.log(""),console.log(l__default.default.green(` Name: ${c.name}`)),console.log(l__default.default.green(` Key: ${c.key}`)),console.log(""),console.log(l__default.default.yellow.bold(" Save this key now - it will not be shown again!")),console.log("");}catch(r){e.fail("Failed to generate API key"),r instanceof Error&&console.log(l__default.default.red(`
1182
+ Error: ${r.message}`)),process.exit(1);}}async function Ce(t){let e=L__default.default(),o=_();(!o||!o.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",s=null;try{s=await b(n);}catch{}let a=Se(t,s,o);a||(console.log(l__default.default.red("No project ID specified")),console.log(l__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(l__default.default.bold("VAIF API Keys")),console.log(""),e.start("Fetching API keys...");try{let i=await fetch(`${je}/v1/projects/${a}/api-keys`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let f=await i.text();throw new Error(`Failed to list keys: ${f}`)}let r=await i.json(),c=r.keys||r;if(e.stop(),!Array.isArray(c)||c.length===0){console.log(l__default.default.yellow("No API keys found")),console.log(l__default.default.gray(`
1183
+ Generate one with: vaif keys generate`));return}let g=Math.max(8,...c.map(f=>(f.name||"").length)),d=` ${"Name".padEnd(g)} ${"Key".padEnd(24)} Created`;console.log(l__default.default.gray(d)),console.log(l__default.default.gray(" "+"-".repeat(d.length-2)));for(let f of c){let p=(f.name||"unnamed").padEnd(g),u=f.maskedKey||f.prefix||`${(f.key||"").slice(0,12)}...`,A=f.createdAt?new Date(f.createdAt).toLocaleDateString():"N/A";console.log(` ${p} ${u.padEnd(24)} ${A}`);}console.log(""),console.log(l__default.default.gray(` ${c.length} key(s) total`)),console.log("");}catch(i){e.fail("Failed to list API keys"),i instanceof Error&&console.log(l__default.default.red(`
1184
+ Error: ${i.message}`)),process.exit(1);}}var Fe=process.env.VAIF_API_URL||"https://api.vaif.studio";function ht(t){try{let e=new URL(t);return e.password&&(e.password="****"),e.toString()}catch{return t.replace(/:[^@/]+@/,":****@")}}async function Te(t){let e=L__default.default(),o=_();(!o||!o.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",s=null;try{s=await b(n);}catch{}let a=t.projectId||s?.projectId||o.projectId;a||(console.log(l__default.default.red("No project ID specified")),console.log(l__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(`${Fe}/v1/projects/${a}`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let d=await i.text();throw new Error(`Failed to fetch project: ${d}`)}let r=await i.json();e.stop(),console.log(""),console.log(l__default.default.bold("VAIF Project Info")),console.log("");let c=16,g=(d,f)=>{console.log(` ${l__default.default.gray(d.padEnd(c))} ${f}`);};g("Name:",l__default.default.white(r.name||"N/A")),g("Project ID:",l__default.default.white(a)),g("Region:",l__default.default.white(r.region||"us-east-1")),g("Plan:",l__default.default.white(r.plan||r.tier||"free")),g("Created:",l__default.default.white(r.createdAt?new Date(r.createdAt).toLocaleDateString():"N/A")),console.log(""),g("API URL:",l__default.default.cyan(r.apiUrl||`${Fe}/v1`)),g("WS URL:",l__default.default.cyan(r.wsUrl||r.realtimeUrl||"N/A")),g("DB URL:",l__default.default.cyan(r.databaseUrl?ht(r.databaseUrl):"N/A")),g("Storage URL:",l__default.default.cyan(r.storageUrl||"N/A")),console.log("");}catch(i){e.fail("Failed to fetch project info"),i instanceof Error&&console.log(l__default.default.red(`
1185
+ Error: ${i.message}`)),process.exit(1);}}var vt=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Re(t){let e=L__default.default(),o=_();(!o||!o.token)&&(console.log(l__default.default.red("Not logged in")),console.log(l__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",s=null;try{s=await b(n);}catch{}let a=t.projectId||s?.projectId||o.projectId;a||(console.log(l__default.default.red("No project ID specified")),console.log(l__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(`${vt}/v1/projects/${a}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let A=await i.text();throw new Error(`Failed to fetch project status: ${A}`)}let r=await i.json();e.stop(),console.log(""),console.log(l__default.default.bold("VAIF Project Status")),console.log("");let c=22,g=(A,R)=>{console.log(` ${l__default.default.gray(A.padEnd(c))} ${R}`);};g("Project:",l__default.default.white(r.name||a)),g("Plan:",l__default.default.white(r.plan||r.tier||"free")),console.log(""),console.log(l__default.default.gray(" --- Resources ---")),console.log("");let d=r.tableCount??r.tables?.length??"N/A",f=r.functionCount??r.functions?.length??"N/A",p=r.bucketCount??r.storage?.buckets?.length??"N/A",u=r.activeConnections??r.connections??"N/A";g("Tables:",l__default.default.white(String(d))),g("Functions:",l__default.default.white(String(f))),g("Storage Buckets:",l__default.default.white(String(p))),g("Active Connections:",l__default.default.white(String(u))),r.usage&&(console.log(""),console.log(l__default.default.gray(" --- Usage ---")),console.log(""),r.usage.dbSize&&g("Database Size:",l__default.default.white(r.usage.dbSize)),r.usage.storageSize&&g("Storage Size:",l__default.default.white(r.usage.storageSize)),r.usage.bandwidth&&g("Bandwidth:",l__default.default.white(r.usage.bandwidth)),r.usage.functionInvocations!=null&&g("Function Invocations:",l__default.default.white(String(r.usage.functionInvocations)))),console.log("");}catch(i){e.fail("Failed to fetch project status"),i instanceof Error&&console.log(l__default.default.red(`
1186
+ Error: ${i.message}`)),process.exit(1);}}commander.program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.2.0");commander.program.command("login").description("Authenticate with VAIF").option("-t, --token <token>","API token (will prompt if not provided)").option("-p, --project-id <id>","Default project ID").action(ae);commander.program.command("logout").description("Log out and remove stored credentials").action(ce);commander.program.command("whoami").description("Show current authenticated user").action(le);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)").action(ne);commander.program.command("templates").alias("tpl").description("List available project templates").action(te);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(Te);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(Re);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(pe);commander.program.command("push").description("Push local schema changes to your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-s, --schema <path>","Schema file path","vaif.schema.json").option("-p, --project-id <id>","Project ID (overrides config)").option("--dry-run","Preview changes without applying").option("-f, --force","Apply changes without confirmation").action(de);commander.program.command("generate").alias("gen").description("Generate TypeScript types from your database schema").option("-c, --connection <url>","Database connection string").option("-o, --output <path>","Output file path","./src/types/database.ts").option("--schema <name>","Schema name","public").option("--config <path>","Config file path","vaif.config.json").option("--dry-run","Preview generated types without writing").action(Q);var Ve=commander.program.command("functions").alias("fn").description("Manage serverless functions");Ve.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(ve);Ve.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(Ie);var M=commander.program.command("db").description("Database management commands");M.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(we);M.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(Ae);M.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(_e);M.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(Ee);var $e=commander.program.command("keys").description("Manage API keys");$e.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(xe);$e.command("list").alias("ls").description("List API keys").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(Ce);commander.program.parse(process.argv);process.argv.slice(2).length||commander.program.outputHelp();