@vaiftech/cli 1.1.0 → 1.3.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'),E=require('fs'),y=require('path'),_e=require('pg'),L=require('ora'),l=require('chalk'),De=require('prettier'),Ee=require('dotenv'),ze=require('os'),Be=require('readline');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var E__default=/*#__PURE__*/_interopDefault(E);var y__default=/*#__PURE__*/_interopDefault(y);var _e__default=/*#__PURE__*/_interopDefault(_e);var L__default=/*#__PURE__*/_interopDefault(L);var l__default=/*#__PURE__*/_interopDefault(l);var De__default=/*#__PURE__*/_interopDefault(De);var Ee__default=/*#__PURE__*/_interopDefault(Ee);var ze__default=/*#__PURE__*/_interopDefault(ze);var Be__default=/*#__PURE__*/_interopDefault(Be);Ee__default.default.config();async function b(o){let e=y__default.default.resolve(o);if(!E__default.default.existsSync(e))return null;try{let t=E__default.default.readFileSync(e,"utf-8"),n=JSON.parse(t);return n.database?.url&&(n.database.url=q(n.database.url)),n.api?.apiKey&&(n.api.apiKey=q(n.api.apiKey)),n}catch{throw new Error(`Failed to parse config file: ${o}`)}}function q(o){return o.replace(/\$\{([^}]+)\}/g,(e,t)=>process.env[t]||e)}async function Re(o,e){let t=await o.query(`
2
+ 'use strict';var commander=require('commander'),j=require('fs'),b=require('path'),Me=require('pg'),K=require('ora'),d=require('chalk'),Be=require('prettier'),Oe=require('dotenv'),ne=require('readline'),Ze=require('os'),child_process=require('child_process');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var j__default=/*#__PURE__*/_interopDefault(j);var b__default=/*#__PURE__*/_interopDefault(b);var Me__default=/*#__PURE__*/_interopDefault(Me);var K__default=/*#__PURE__*/_interopDefault(K);var d__default=/*#__PURE__*/_interopDefault(d);var Be__default=/*#__PURE__*/_interopDefault(Be);var Oe__default=/*#__PURE__*/_interopDefault(Oe);var ne__default=/*#__PURE__*/_interopDefault(ne);var Ze__default=/*#__PURE__*/_interopDefault(Ze);Oe__default.default.config();async function I(t){let e=b__default.default.resolve(t);if(!j__default.default.existsSync(e))return null;try{let o=j__default.default.readFileSync(e,"utf-8"),n=JSON.parse(o);return n.database?.url&&(n.database.url=Q(n.database.url)),n.api?.apiKey&&(n.api.apiKey=Q(n.api.apiKey)),n}catch{throw new Error(`Failed to parse config file: ${t}`)}}function Q(t){return t.replace(/\$\{([^}]+)\}/g,(e,o)=>process.env[o]||e)}async function ze(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]),r=await o.query(`
23
+ `,[e]),i=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]),a=await o.query(`
39
+ `,[e]),l=await t.query(`
40
40
  SELECT
41
41
  t.typname as enum_name,
42
42
  e.enumlabel as enum_value
@@ -45,53 +45,2059 @@
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]),i=new Map;for(let c of t.rows)i.set(c.table_name,[]);for(let c of n.rows){let p=i.get(c.table_name);p&&p.push(c);}let s=new Map;for(let c of a.rows){let p=s.get(c.enum_name)||[];p.push(c.enum_value),s.set(c.enum_name,p);}return {tables:i,enums:s,foreignKeys:r.rows}}var B={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 Ne(o,e){let{data_type:t,udt_name:n,is_nullable:r}=o;if(e.has(n)){let s=e.get(n).map(c=>`"${c}"`).join(" | ");return r==="YES"?`(${s}) | null`:s}if(t==="ARRAY"){let i=n.replace(/^_/,"");if(e.has(i)){let p=e.get(i).map(d=>`"${d}"`).join(" | ");return r==="YES"?`(${p})[] | null`:`(${p})[]`}let s=B[i]||"unknown";return r==="YES"?`${s}[] | null`:`${s}[]`}let a=B[t]||B[n]||"unknown";return r==="YES"&&(a=`${a} | null`),a}function K(o){return o.split(/[_\-\s]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function Te(o,e){let t=K(o),n=e.map(r=>` | "${r}"`).join(`
49
- `);return `export type ${t} =
50
- ${n};`}function Oe(o,e,t){let n=K(o),r=[],a=[],i=[];for(let d of e){let f=Ne(d,t),g=d.column_name,u=d.column_default!==null||d.is_identity==="YES",I=d.is_nullable==="YES";r.push(` ${g}: ${f};`),u||d.column_name==="id"?a.push(` ${g}?: ${f.replace(" | null","")} | null;`):I?a.push(` ${g}?: ${f};`):a.push(` ${g}: ${f.replace(" | null","")};`),i.push(` ${g}?: ${f.replace(" | null","")} | null;`);}let s=`export interface ${n} {
51
- ${r.join(`
48
+ `,[e]),a=new Map;for(let s of o.rows)a.set(s.table_name,[]);for(let s of n.rows){let c=a.get(s.table_name);c&&c.push(s);}let r=new Map;for(let s of l.rows){let c=r.get(s.enum_name)||[];c.push(s.enum_value),r.set(s.enum_name,c);}return {tables:a,enums:r,foreignKeys:i.rows}}var q={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 Ye(t,e){let{data_type:o,udt_name:n,is_nullable:i}=t;if(e.has(n)){let r=e.get(n).map(s=>`"${s}"`).join(" | ");return i==="YES"?`(${r}) | null`:r}if(o==="ARRAY"){let a=n.replace(/^_/,"");if(e.has(a)){let c=e.get(a).map(f=>`"${f}"`).join(" | ");return i==="YES"?`(${c})[] | null`:`(${c})[]`}let r=q[a]||"unknown";return i==="YES"?`${r}[] | null`:`${r}[]`}let l=q[o]||q[n]||"unknown";return i==="YES"&&(l=`${l} | null`),l}function J(t){return t.split(/[_\-\s]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function qe(t,e){let o=J(t),n=e.map(i=>` | "${i}"`).join(`
49
+ `);return `export type ${o} =
50
+ ${n};`}function Je(t,e,o){let n=J(t),i=[],l=[],a=[];for(let f of e){let u=Ye(f,o),p=f.column_name,h=f.column_default!==null||f.is_identity==="YES",x=f.is_nullable==="YES";i.push(` ${p}: ${u};`),h||f.column_name==="id"?l.push(` ${p}?: ${u.replace(" | null","")} | null;`):x?l.push(` ${p}?: ${u};`):l.push(` ${p}: ${u.replace(" | null","")};`),a.push(` ${p}?: ${u.replace(" | null","")} | null;`);}let r=`export interface ${n} {
51
+ ${i.join(`
52
52
  `)}
53
- }`,c=`export interface ${n}Insert {
54
- ${a.join(`
53
+ }`,s=`export interface ${n}Insert {
54
+ ${l.join(`
55
55
  `)}
56
- }`,p=`export interface ${n}Update {
57
- ${i.join(`
56
+ }`,c=`export interface ${n}Update {
57
+ ${a.join(`
58
58
  `)}
59
- }`;return {base:s,insert:c,update:p}}function Le(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[a,i]of e)n.push(Te(a,i)),n.push("");}n.push("// ============ TABLES ============"),n.push("");let r=[];for(let[a,i]of o){let{base:s,insert:c,update:p}=Oe(a,i,e);r.push(a),n.push(s),n.push(""),n.push(c),n.push(""),n.push(p),n.push("");}n.push("// ============ DATABASE SCHEMA ============"),n.push(""),n.push("export interface Database {");for(let a of r){let i=K(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 H(o){let e=L__default.default("Loading configuration...").start();try{let t=await b(o.config),n=o.connection||t?.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 r=new _e__default.default.Client({connectionString:n});await r.connect(),e.text="Introspecting schema...";let{tables:a,enums:i,foreignKeys:s}=await Re(r,o.schema);if(await r.end(),a.size===0){e.warn(`No tables found in schema "${o.schema}"`);return}e.text=`Generating types for ${a.size} tables...`;let c=Le(a,i,s),p=await De__default.default.format(c,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100});if(o.dryRun){e.succeed("Generated types (dry run):"),console.log(""),console.log(l__default.default.gray("\u2500".repeat(60))),console.log(p),console.log(l__default.default.gray("\u2500".repeat(60)));return}let d=y__default.default.resolve(o.output),f=y__default.default.dirname(d);E__default.default.existsSync(f)||E__default.default.mkdirSync(f,{recursive:!0}),E__default.default.writeFileSync(d,p,"utf-8"),e.succeed(`Generated types for ${a.size} tables \u2192 ${l__default.default.cyan(o.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 "${o.output.replace(/\.ts$/,"")}";`));}catch(t){e.fail("Failed to generate types"),t instanceof Error&&(console.error(l__default.default.red(`
62
- Error: ${t.message}`)),t.message.includes("ECONNREFUSED")&&console.log(l__default.default.yellow(`
63
- Make sure your database is running and accessible.`))),process.exit(1);}}var Ue={$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 Q(o){let e=L__default.default("Initializing VAIF configuration...").start(),t=y__default.default.resolve("vaif.config.json");E__default.default.existsSync(t)&&!o.force&&(e.fail("vaif.config.json already exists"),console.log(l__default.default.yellow(`
64
- Use --force to overwrite existing configuration.`)),process.exit(1));try{E__default.default.writeFileSync(t,JSON.stringify(Ue,null,2),"utf-8"),e.succeed("Created vaif.config.json");let n=y__default.default.resolve(".env.example");if(E__default.default.existsSync(n)||(E__default.default.writeFileSync(n,`# VAIF Configuration
59
+ }`;return {base:r,insert:s,update:c}}function We(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[l,a]of e)n.push(qe(l,a)),n.push("");}n.push("// ============ TABLES ============"),n.push("");let i=[];for(let[l,a]of t){let{base:r,insert:s,update:c}=Je(l,a,e);i.push(l),n.push(r),n.push(""),n.push(s),n.push(""),n.push(c),n.push("");}n.push("// ============ DATABASE SCHEMA ============"),n.push(""),n.push("export interface Database {");for(let l of i){let a=J(l);n.push(` ${l}: {`),n.push(` Row: ${a};`),n.push(` Insert: ${a}Insert;`),n.push(` Update: ${a}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 te(t){let e=K__default.default("Loading configuration...").start();try{let o=await I(t.config),n=t.connection||o?.database?.url||process.env.DATABASE_URL;n||(e.fail("No database connection string provided"),console.log(d__default.default.yellow(`
61
+ Provide a connection string via:`)),console.log(d__default.default.gray(" --connection <url>")),console.log(d__default.default.gray(" DATABASE_URL environment variable")),console.log(d__default.default.gray(" vaif.config.json database.url")),process.exit(1)),e.text="Connecting to database...";let i=new Me__default.default.Client({connectionString:n});await i.connect(),e.text="Introspecting schema...";let{tables:l,enums:a,foreignKeys:r}=await ze(i,t.schema);if(await i.end(),l.size===0){e.warn(`No tables found in schema "${t.schema}"`);return}e.text=`Generating types for ${l.size} tables...`;let s=We(l,a,r),c=await Be__default.default.format(s,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100});if(t.dryRun){e.succeed("Generated types (dry run):"),console.log(""),console.log(d__default.default.gray("\u2500".repeat(60))),console.log(c),console.log(d__default.default.gray("\u2500".repeat(60)));return}let f=b__default.default.resolve(t.output),u=b__default.default.dirname(f);j__default.default.existsSync(u)||j__default.default.mkdirSync(u,{recursive:!0}),j__default.default.writeFileSync(f,c,"utf-8"),e.succeed(`Generated types for ${l.size} tables \u2192 ${d__default.default.cyan(t.output)}`),console.log(""),console.log(d__default.default.green("Generated:")),console.log(d__default.default.gray(` Tables: ${l.size}`)),console.log(d__default.default.gray(` Enums: ${a.size}`)),console.log(""),console.log(d__default.default.gray("Import in your code:")),console.log(d__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(d__default.default.red(`
62
+ Error: ${o.message}`)),o.message.includes("ECONNREFUSED")&&console.log(d__default.default.yellow(`
63
+ Make sure your database is running and accessible.`))),process.exit(1);}}var $=[{name:"database",label:"Database",description:"CRUD queries, type-safe operations"},{name:"auth",label:"Authentication",description:"login, signup, OAuth, sessions"},{name:"realtime",label:"Realtime",description:"live subscriptions, presence"},{name:"storage",label:"Storage",description:"file uploads, signed URLs"},{name:"functions",label:"Functions",description:"serverless function calls"}],re={"nextjs-fullstack":{name:"Next.js Full-Stack",description:"Next.js app with server/client VAIF client, auth middleware, and React hooks",tag:"Next.js",defaultFeatures:["database","auth"],files:[{path:"package.json",content:`{
64
+ "name": "my-vaif-app",
65
+ "private": true,
66
+ "version": "0.1.0",
67
+ "scripts": {
68
+ "dev": "next dev",
69
+ "build": "next build",
70
+ "start": "next start",
71
+ "lint": "next lint"
72
+ },
73
+ "dependencies": {
74
+ "@vaiftech/client": "^1.0.0",
75
+ "@vaiftech/auth": "^1.0.0",
76
+ "@vaiftech/react": "^1.0.0",
77
+ "next": "^15.0.0",
78
+ "react": "^19.0.0",
79
+ "react-dom": "^19.0.0"
80
+ },
81
+ "devDependencies": {
82
+ "@types/node": "^22.0.0",
83
+ "@types/react": "^19.0.0",
84
+ "@types/react-dom": "^19.0.0",
85
+ "typescript": "^5.7.0"
86
+ }
87
+ }
88
+ `},{path:"tsconfig.json",content:`{
89
+ "compilerOptions": {
90
+ "target": "ES2017",
91
+ "lib": ["dom", "dom.iterable", "esnext"],
92
+ "allowJs": true,
93
+ "skipLibCheck": true,
94
+ "strict": true,
95
+ "noEmit": true,
96
+ "esModuleInterop": true,
97
+ "module": "esnext",
98
+ "moduleResolution": "bundler",
99
+ "resolveJsonModule": true,
100
+ "isolatedModules": true,
101
+ "jsx": "preserve",
102
+ "incremental": true,
103
+ "plugins": [{ "name": "next" }],
104
+ "paths": { "@/*": ["./*"] }
105
+ },
106
+ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
107
+ "exclude": ["node_modules"]
108
+ }
109
+ `},{path:"next.config.ts",content:`import type { NextConfig } from "next";
110
+
111
+ const nextConfig: NextConfig = {};
112
+
113
+ export default nextConfig;
114
+ `},{path:"app/layout.tsx",content:`import type { Metadata } from "next";
115
+ import { VaifProvider } from "@vaiftech/react";
116
+ import { vaif } from "@/lib/vaif";
117
+ import "./globals.css";
118
+
119
+ export const metadata: Metadata = {
120
+ title: "My VAIF App",
121
+ description: "Built with VAIF Studio",
122
+ };
123
+
124
+ export default function RootLayout({ children }: { children: React.ReactNode }) {
125
+ return (
126
+ <html lang="en">
127
+ <body>
128
+ <VaifProvider client={vaif}>{children}</VaifProvider>
129
+ </body>
130
+ </html>
131
+ );
132
+ }
133
+ `},{path:"app/page.tsx",content:`export default function Home() {
134
+ return (
135
+ <main style={{ maxWidth: 600, margin: "80px auto", textAlign: "center" }}>
136
+ <h1>Welcome to VAIF</h1>
137
+ <p>Your Next.js app is ready. Start building!</p>
138
+ </main>
139
+ );
140
+ }
141
+ `},{path:"app/globals.css",content:`*,
142
+ *::before,
143
+ *::after {
144
+ box-sizing: border-box;
145
+ margin: 0;
146
+ padding: 0;
147
+ }
148
+
149
+ body {
150
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
151
+ -webkit-font-smoothing: antialiased;
152
+ -moz-osx-font-smoothing: grayscale;
153
+ }
154
+ `},{path:"lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
155
+ import { createServerClient } from "@vaiftech/client/server";
156
+
157
+ // Browser client \u2013 safe to use in Client Components
158
+ export const vaif = createClient({
159
+ projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
160
+ apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
161
+ });
162
+
163
+ // Server client \u2013 use in Server Components, Route Handlers, Server Actions
164
+ export function createVaifServer() {
165
+ return createServerClient({
166
+ projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
167
+ secretKey: process.env.VAIF_SECRET_KEY!,
168
+ });
169
+ }
170
+ `},{path:".env.local.example",content:`# VAIF Configuration
171
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
172
+
173
+ NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
174
+ NEXT_PUBLIC_VAIF_API_KEY=your-anon-key
175
+ VAIF_SECRET_KEY=your-secret-key
176
+ `},{path:".gitignore",content:`node_modules
177
+ .next
178
+ out
179
+ .env
180
+ .env.local
181
+ *.local
182
+ `}],featureFiles:{auth:[{path:"middleware.ts",content:`import { NextResponse, type NextRequest } from "next/server";
183
+ import { createServerClient } from "@vaiftech/client/server";
184
+ import { authMiddleware } from "@vaiftech/auth/nextjs";
185
+
186
+ const protectedRoutes = ["/dashboard", "/settings", "/api/protected"];
187
+
188
+ export async function middleware(request: NextRequest) {
189
+ const { pathname } = request.nextUrl;
190
+ const isProtected = protectedRoutes.some((route) => pathname.startsWith(route));
191
+ if (!isProtected) return NextResponse.next();
192
+
193
+ const vaif = createServerClient({
194
+ projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
195
+ secretKey: process.env.VAIF_SECRET_KEY!,
196
+ });
197
+
198
+ return authMiddleware(vaif, request, {
199
+ loginRedirect: "/login",
200
+ onUnauthenticated: () => {
201
+ const loginUrl = new URL("/login", request.url);
202
+ loginUrl.searchParams.set("redirect", pathname);
203
+ return NextResponse.redirect(loginUrl);
204
+ },
205
+ });
206
+ }
207
+
208
+ export const config = {
209
+ matcher: ["/dashboard/:path*", "/settings/:path*", "/api/protected/:path*"],
210
+ };
211
+ `},{path:"app/(auth)/login/page.tsx",content:`"use client";
212
+
213
+ import { useState } from "react";
214
+ import { useRouter } from "next/navigation";
215
+ import { vaif } from "@/lib/vaif";
216
+
217
+ export default function LoginPage() {
218
+ const router = useRouter();
219
+ const [email, setEmail] = useState("");
220
+ const [password, setPassword] = useState("");
221
+ const [error, setError] = useState<string | null>(null);
222
+ const [loading, setLoading] = useState(false);
223
+
224
+ async function handleSubmit(e: React.FormEvent) {
225
+ e.preventDefault();
226
+ setLoading(true);
227
+ setError(null);
228
+
229
+ const { error } = await vaif.auth.signInWithPassword({ email, password });
230
+ if (error) {
231
+ setError(error.message);
232
+ setLoading(false);
233
+ } else {
234
+ router.push("/dashboard");
235
+ }
236
+ }
237
+
238
+ return (
239
+ <div style={{ maxWidth: 400, margin: "80px auto" }}>
240
+ <h1>Log In</h1>
241
+ <form onSubmit={handleSubmit}>
242
+ <div style={{ marginBottom: 12 }}>
243
+ <label htmlFor="email">Email</label>
244
+ <input id="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} required style={{ display: "block", width: "100%", padding: 8 }} />
245
+ </div>
246
+ <div style={{ marginBottom: 12 }}>
247
+ <label htmlFor="password">Password</label>
248
+ <input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required style={{ display: "block", width: "100%", padding: 8 }} />
249
+ </div>
250
+ {error && <p style={{ color: "red" }}>{error}</p>}
251
+ <button type="submit" disabled={loading} style={{ padding: "8px 24px" }}>
252
+ {loading ? "Logging in..." : "Log In"}
253
+ </button>
254
+ </form>
255
+ </div>
256
+ );
257
+ }
258
+ `},{path:"app/(auth)/signup/page.tsx",content:`"use client";
259
+
260
+ import { useState } from "react";
261
+ import { useRouter } from "next/navigation";
262
+ import { vaif } from "@/lib/vaif";
263
+
264
+ export default function SignupPage() {
265
+ const router = useRouter();
266
+ const [email, setEmail] = useState("");
267
+ const [password, setPassword] = useState("");
268
+ const [error, setError] = useState<string | null>(null);
269
+ const [loading, setLoading] = useState(false);
270
+
271
+ async function handleSubmit(e: React.FormEvent) {
272
+ e.preventDefault();
273
+ setLoading(true);
274
+ setError(null);
275
+
276
+ const { error } = await vaif.auth.signUp({ email, password });
277
+ if (error) {
278
+ setError(error.message);
279
+ setLoading(false);
280
+ } else {
281
+ router.push("/");
282
+ }
283
+ }
284
+
285
+ return (
286
+ <div style={{ maxWidth: 400, margin: "80px auto" }}>
287
+ <h1>Sign Up</h1>
288
+ <form onSubmit={handleSubmit}>
289
+ <div style={{ marginBottom: 12 }}>
290
+ <label htmlFor="email">Email</label>
291
+ <input id="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} required style={{ display: "block", width: "100%", padding: 8 }} />
292
+ </div>
293
+ <div style={{ marginBottom: 12 }}>
294
+ <label htmlFor="password">Password</label>
295
+ <input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required minLength={8} style={{ display: "block", width: "100%", padding: 8 }} />
296
+ </div>
297
+ {error && <p style={{ color: "red" }}>{error}</p>}
298
+ <button type="submit" disabled={loading} style={{ padding: "8px 24px" }}>
299
+ {loading ? "Creating account..." : "Sign Up"}
300
+ </button>
301
+ </form>
302
+ </div>
303
+ );
304
+ }
305
+ `}],storage:[{path:"lib/storage.ts",content:`import { createVaifServer } from "./vaif";
306
+
307
+ export async function uploadFile(bucket: string, file: Buffer | Blob, filePath: string) {
308
+ const vaif = createVaifServer();
309
+ const { data, error } = await vaif.storage.from(bucket).upload(filePath, file);
310
+ if (error) throw error;
311
+ const { data: urlData } = vaif.storage.from(bucket).getPublicUrl(data.path);
312
+ return { path: data.path, publicUrl: urlData.publicUrl };
313
+ }
314
+
315
+ export async function getSignedUrl(bucket: string, filePath: string, expiresIn = 3600) {
316
+ const vaif = createVaifServer();
317
+ const { data, error } = await vaif.storage.from(bucket).createSignedUrl(filePath, expiresIn);
318
+ if (error) throw error;
319
+ return data.signedUrl;
320
+ }
321
+ `},{path:"app/api/upload/route.ts",content:`import { NextRequest, NextResponse } from "next/server";
322
+ import { uploadFile } from "@/lib/storage";
323
+
324
+ export async function POST(request: NextRequest) {
325
+ const formData = await request.formData();
326
+ const file = formData.get("file") as Blob | null;
327
+ if (!file) return NextResponse.json({ error: "No file provided" }, { status: 400 });
328
+
329
+ const fileName = (formData.get("fileName") as string) || "upload";
330
+ const bucket = (formData.get("bucket") as string) || "uploads";
331
+ const filePath = \`\${Date.now()}-\${fileName}\`;
332
+
333
+ const result = await uploadFile(bucket, file, filePath);
334
+ return NextResponse.json(result);
335
+ }
336
+ `}],realtime:[{path:"hooks/useRealtime.ts",content:`"use client";
337
+
338
+ import { useEffect, useState, useCallback } from "react";
339
+ import { vaif } from "@/lib/vaif";
340
+
341
+ interface UseRealtimeOptions<T> {
342
+ table: string;
343
+ schema?: string;
344
+ filter?: string;
345
+ initialData?: T[];
346
+ }
347
+
348
+ export function useRealtime<T extends { id: string }>({
349
+ table,
350
+ schema = "public",
351
+ filter,
352
+ initialData = [],
353
+ }: UseRealtimeOptions<T>) {
354
+ const [data, setData] = useState<T[]>(initialData);
355
+
356
+ useEffect(() => {
357
+ vaif.from(table).select("*").then(({ data: rows }) => {
358
+ if (rows) setData(rows as T[]);
359
+ });
360
+ }, [table]);
361
+
362
+ useEffect(() => {
363
+ const channelConfig: Record<string, string> = { event: "*", schema, table };
364
+ if (filter) channelConfig.filter = filter;
365
+
366
+ const channel = vaif
367
+ .channel(\`\${table}-changes\`)
368
+ .on("postgres_changes", channelConfig, (payload) => {
369
+ if (payload.eventType === "INSERT") {
370
+ setData((prev) => [...prev, payload.new as T]);
371
+ } else if (payload.eventType === "UPDATE") {
372
+ setData((prev) => prev.map((item) => (item.id === (payload.new as T).id ? (payload.new as T) : item)));
373
+ } else if (payload.eventType === "DELETE") {
374
+ setData((prev) => prev.filter((item) => item.id !== (payload.old as T).id));
375
+ }
376
+ })
377
+ .subscribe();
378
+
379
+ return () => { channel.unsubscribe(); };
380
+ }, [table, schema, filter]);
381
+
382
+ const refresh = useCallback(async () => {
383
+ const { data: rows } = await vaif.from(table).select("*");
384
+ if (rows) setData(rows as T[]);
385
+ }, [table]);
386
+
387
+ return { data, refresh };
388
+ }
389
+ `}]},dependencies:["@vaiftech/client","@vaiftech/auth","@vaiftech/react","next","react","react-dom"],devDependencies:["@types/node","@types/react","@types/react-dom","typescript"],postInstructions:["cd my-vaif-app","npm install","# Copy .env.local.example to .env.local and add your VAIF credentials","npm run dev"]},"react-spa":{name:"React SPA",description:"Single-page React app with Vite, VAIF client, and provider wrapper",tag:"React + Vite",defaultFeatures:["database","auth"],files:[{path:"package.json",content:`{
390
+ "name": "my-vaif-app",
391
+ "private": true,
392
+ "version": "0.1.0",
393
+ "type": "module",
394
+ "scripts": {
395
+ "dev": "vite",
396
+ "build": "tsc -b && vite build",
397
+ "preview": "vite preview"
398
+ },
399
+ "dependencies": {
400
+ "@vaiftech/client": "^1.0.0",
401
+ "@vaiftech/react": "^1.0.0",
402
+ "react": "^19.0.0",
403
+ "react-dom": "^19.0.0",
404
+ "react-router-dom": "^7.0.0"
405
+ },
406
+ "devDependencies": {
407
+ "@types/react": "^19.0.0",
408
+ "@types/react-dom": "^19.0.0",
409
+ "@vitejs/plugin-react": "^4.4.0",
410
+ "typescript": "^5.7.0",
411
+ "vite": "^6.0.0"
412
+ }
413
+ }
414
+ `},{path:"tsconfig.json",content:`{
415
+ "compilerOptions": {
416
+ "target": "ES2020",
417
+ "useDefineForClassFields": true,
418
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
419
+ "module": "ESNext",
420
+ "skipLibCheck": true,
421
+ "moduleResolution": "bundler",
422
+ "allowImportingTsExtensions": true,
423
+ "isolatedModules": true,
424
+ "moduleDetection": "force",
425
+ "noEmit": true,
426
+ "jsx": "react-jsx",
427
+ "strict": true,
428
+ "noUnusedLocals": true,
429
+ "noUnusedParameters": true,
430
+ "noFallthroughCasesInSwitch": true,
431
+ "noUncheckedSideEffectImports": true,
432
+ "paths": {
433
+ "@/*": ["./src/*"]
434
+ }
435
+ },
436
+ "include": ["src"]
437
+ }
438
+ `},{path:"vite.config.ts",content:`import { defineConfig } from "vite";
439
+ import react from "@vitejs/plugin-react";
440
+ import path from "path";
441
+
442
+ export default defineConfig({
443
+ plugins: [react()],
444
+ resolve: {
445
+ alias: {
446
+ "@": path.resolve(__dirname, "./src"),
447
+ },
448
+ },
449
+ });
450
+ `},{path:"index.html",content:`<!DOCTYPE html>
451
+ <html lang="en">
452
+ <head>
453
+ <meta charset="UTF-8" />
454
+ <link rel="icon" type="image/svg+xml" href="/vite.svg" />
455
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
456
+ <title>My VAIF App</title>
457
+ </head>
458
+ <body>
459
+ <div id="root"></div>
460
+ <script type="module" src="/src/main.tsx"></script>
461
+ </body>
462
+ </html>
463
+ `},{path:"src/main.tsx",content:`import React from "react";
464
+ import ReactDOM from "react-dom/client";
465
+ import { BrowserRouter } from "react-router-dom";
466
+ import { VaifProvider } from "@vaiftech/react";
467
+ import { vaif } from "./lib/vaif";
468
+ import App from "./App";
469
+
470
+ ReactDOM.createRoot(document.getElementById("root")!).render(
471
+ <React.StrictMode>
472
+ <BrowserRouter>
473
+ <VaifProvider client={vaif}>
474
+ <App />
475
+ </VaifProvider>
476
+ </BrowserRouter>
477
+ </React.StrictMode>,
478
+ );
479
+ `},{path:"src/App.tsx",content:`import { Routes, Route } from "react-router-dom";
480
+
481
+ export default function App() {
482
+ return (
483
+ <Routes>
484
+ <Route path="/" element={<Home />} />
485
+ </Routes>
486
+ );
487
+ }
488
+
489
+ function Home() {
490
+ return (
491
+ <div style={{ maxWidth: 600, margin: "80px auto", textAlign: "center" }}>
492
+ <h1>Welcome to VAIF</h1>
493
+ <p>Your app is ready. Start building!</p>
494
+ </div>
495
+ );
496
+ }
497
+ `},{path:"src/lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
498
+
499
+ export const vaif = createClient({
500
+ projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
501
+ apiKey: import.meta.env.VITE_VAIF_API_KEY,
502
+ });
503
+ `},{path:"src/vite-env.d.ts",content:`/// <reference types="vite/client" />
504
+
505
+ interface ImportMetaEnv {
506
+ readonly VITE_VAIF_PROJECT_ID: string;
507
+ readonly VITE_VAIF_API_KEY: string;
508
+ }
509
+
510
+ interface ImportMeta {
511
+ readonly env: ImportMetaEnv;
512
+ }
513
+ `},{path:".env.example",content:`# VAIF Configuration
514
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
515
+
516
+ VITE_VAIF_PROJECT_ID=your-project-id
517
+ VITE_VAIF_API_KEY=your-anon-key
518
+ `},{path:".gitignore",content:`node_modules
519
+ dist
520
+ .env
521
+ .env.local
522
+ *.local
523
+ `}],featureFiles:{auth:[{path:"src/pages/Login.tsx",content:`import { useState } from "react";
524
+ import { useNavigate } from "react-router-dom";
525
+ import { vaif } from "../lib/vaif";
526
+
527
+ export default function Login() {
528
+ const navigate = useNavigate();
529
+ const [email, setEmail] = useState("");
530
+ const [password, setPassword] = useState("");
531
+ const [error, setError] = useState<string | null>(null);
532
+ const [loading, setLoading] = useState(false);
533
+
534
+ async function handleSubmit(e: React.FormEvent) {
535
+ e.preventDefault();
536
+ setLoading(true);
537
+ setError(null);
538
+
539
+ const { error } = await vaif.auth.signInWithPassword({ email, password });
540
+ if (error) {
541
+ setError(error.message);
542
+ setLoading(false);
543
+ } else {
544
+ navigate("/");
545
+ }
546
+ }
547
+
548
+ return (
549
+ <div style={{ maxWidth: 400, margin: "80px auto" }}>
550
+ <h1>Log In</h1>
551
+ <form onSubmit={handleSubmit}>
552
+ <div style={{ marginBottom: 12 }}>
553
+ <label htmlFor="email">Email</label>
554
+ <input id="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} required style={{ display: "block", width: "100%", padding: 8 }} />
555
+ </div>
556
+ <div style={{ marginBottom: 12 }}>
557
+ <label htmlFor="password">Password</label>
558
+ <input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required style={{ display: "block", width: "100%", padding: 8 }} />
559
+ </div>
560
+ {error && <p style={{ color: "red" }}>{error}</p>}
561
+ <button type="submit" disabled={loading} style={{ padding: "8px 24px" }}>
562
+ {loading ? "Logging in..." : "Log In"}
563
+ </button>
564
+ </form>
565
+ </div>
566
+ );
567
+ }
568
+ `},{path:"src/pages/Signup.tsx",content:`import { useState } from "react";
569
+ import { useNavigate } from "react-router-dom";
570
+ import { vaif } from "../lib/vaif";
571
+
572
+ export default function Signup() {
573
+ const navigate = useNavigate();
574
+ const [email, setEmail] = useState("");
575
+ const [password, setPassword] = useState("");
576
+ const [error, setError] = useState<string | null>(null);
577
+ const [loading, setLoading] = useState(false);
578
+
579
+ async function handleSubmit(e: React.FormEvent) {
580
+ e.preventDefault();
581
+ setLoading(true);
582
+ setError(null);
583
+
584
+ const { error } = await vaif.auth.signUp({ email, password });
585
+ if (error) {
586
+ setError(error.message);
587
+ setLoading(false);
588
+ } else {
589
+ navigate("/");
590
+ }
591
+ }
592
+
593
+ return (
594
+ <div style={{ maxWidth: 400, margin: "80px auto" }}>
595
+ <h1>Sign Up</h1>
596
+ <form onSubmit={handleSubmit}>
597
+ <div style={{ marginBottom: 12 }}>
598
+ <label htmlFor="email">Email</label>
599
+ <input id="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} required style={{ display: "block", width: "100%", padding: 8 }} />
600
+ </div>
601
+ <div style={{ marginBottom: 12 }}>
602
+ <label htmlFor="password">Password</label>
603
+ <input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required minLength={8} style={{ display: "block", width: "100%", padding: 8 }} />
604
+ </div>
605
+ {error && <p style={{ color: "red" }}>{error}</p>}
606
+ <button type="submit" disabled={loading} style={{ padding: "8px 24px" }}>
607
+ {loading ? "Creating account..." : "Sign Up"}
608
+ </button>
609
+ </form>
610
+ </div>
611
+ );
612
+ }
613
+ `},{path:"src/components/AuthGuard.tsx",content:`import { useEffect, useState, type ReactNode } from "react";
614
+ import { useNavigate } from "react-router-dom";
615
+ import { vaif } from "../lib/vaif";
616
+
617
+ interface AuthGuardProps {
618
+ children: ReactNode;
619
+ fallback?: ReactNode;
620
+ }
621
+
622
+ export function AuthGuard({ children, fallback }: AuthGuardProps) {
623
+ const navigate = useNavigate();
624
+ const [loading, setLoading] = useState(true);
625
+ const [authenticated, setAuthenticated] = useState(false);
626
+
627
+ useEffect(() => {
628
+ vaif.auth.getSession().then(({ data }) => {
629
+ if (data.session) {
630
+ setAuthenticated(true);
631
+ } else {
632
+ navigate("/login");
633
+ }
634
+ setLoading(false);
635
+ });
636
+
637
+ const { data: { subscription } } = vaif.auth.onAuthStateChange((_event, session) => {
638
+ setAuthenticated(!!session);
639
+ if (!session) navigate("/login");
640
+ });
641
+
642
+ return () => subscription.unsubscribe();
643
+ }, [navigate]);
644
+
645
+ if (loading) return fallback ?? <div>Loading...</div>;
646
+ if (!authenticated) return null;
647
+ return <>{children}</>;
648
+ }
649
+ `}],storage:[{path:"src/hooks/useFileUpload.ts",content:`import { useState, useCallback } from "react";
650
+ import { vaif } from "../lib/vaif";
651
+
652
+ interface UploadResult {
653
+ path: string;
654
+ publicUrl: string;
655
+ }
656
+
657
+ interface UseFileUploadOptions {
658
+ bucket?: string;
659
+ folder?: string;
660
+ }
661
+
662
+ export function useFileUpload({ bucket = "uploads", folder = "" }: UseFileUploadOptions = {}) {
663
+ const [uploading, setUploading] = useState(false);
664
+ const [error, setError] = useState<string | null>(null);
665
+
666
+ const upload = useCallback(
667
+ async (file: File): Promise<UploadResult | null> => {
668
+ setUploading(true);
669
+ setError(null);
670
+
671
+ const filePath = folder
672
+ ? \`\${folder}/\${Date.now()}-\${file.name}\`
673
+ : \`\${Date.now()}-\${file.name}\`;
674
+
675
+ const { data, error: uploadError } = await vaif.storage
676
+ .from(bucket)
677
+ .upload(filePath, file);
678
+
679
+ if (uploadError) {
680
+ setError(uploadError.message);
681
+ setUploading(false);
682
+ return null;
683
+ }
684
+
685
+ const { data: urlData } = vaif.storage.from(bucket).getPublicUrl(data.path);
686
+
687
+ setUploading(false);
688
+ return { path: data.path, publicUrl: urlData.publicUrl };
689
+ },
690
+ [bucket, folder],
691
+ );
692
+
693
+ return { upload, uploading, error };
694
+ }
695
+ `}],realtime:[{path:"src/hooks/useRealtimeSubscription.ts",content:`import { useEffect, useState, useCallback } from "react";
696
+ import { vaif } from "../lib/vaif";
697
+
698
+ interface UseRealtimeOptions<T> {
699
+ table: string;
700
+ schema?: string;
701
+ filter?: string;
702
+ initialData?: T[];
703
+ }
704
+
705
+ export function useRealtimeSubscription<T extends { id: string }>({
706
+ table,
707
+ schema = "public",
708
+ filter,
709
+ initialData = [],
710
+ }: UseRealtimeOptions<T>) {
711
+ const [data, setData] = useState<T[]>(initialData);
712
+
713
+ useEffect(() => {
714
+ // Load initial data
715
+ let query = vaif.from(table).select("*");
716
+ query.then(({ data: rows }) => {
717
+ if (rows) setData(rows as T[]);
718
+ });
719
+ }, [table]);
720
+
721
+ useEffect(() => {
722
+ const channelConfig: Record<string, string> = {
723
+ event: "*",
724
+ schema,
725
+ table,
726
+ };
727
+ if (filter) channelConfig.filter = filter;
728
+
729
+ const channel = vaif
730
+ .channel(\`\${table}-changes\`)
731
+ .on("postgres_changes", channelConfig, (payload) => {
732
+ if (payload.eventType === "INSERT") {
733
+ setData((prev) => [...prev, payload.new as T]);
734
+ } else if (payload.eventType === "UPDATE") {
735
+ setData((prev) =>
736
+ prev.map((item) => (item.id === (payload.new as T).id ? (payload.new as T) : item)),
737
+ );
738
+ } else if (payload.eventType === "DELETE") {
739
+ setData((prev) => prev.filter((item) => item.id !== (payload.old as T).id));
740
+ }
741
+ })
742
+ .subscribe();
743
+
744
+ return () => {
745
+ channel.unsubscribe();
746
+ };
747
+ }, [table, schema, filter]);
748
+
749
+ const refresh = useCallback(async () => {
750
+ const { data: rows } = await vaif.from(table).select("*");
751
+ if (rows) setData(rows as T[]);
752
+ }, [table]);
753
+
754
+ return { data, refresh };
755
+ }
756
+ `}]},dependencies:["@vaiftech/client","@vaiftech/react","react","react-dom","react-router-dom"],devDependencies:["@types/react","@types/react-dom","@vitejs/plugin-react","typescript","vite"],postInstructions:["cd my-vaif-app","npm install","# Copy .env.example to .env and add your VAIF credentials","npm run dev"]},"ios-swift-app":{name:"iOS Swift App",description:"Swift client manager for iOS/macOS apps using Swift Package Manager",tag:"Swift / iOS",defaultFeatures:["database","auth"],files:[{path:"VaifManager.swift",content:`import Foundation
757
+ import VaifClient
758
+
759
+ /// Singleton manager for the VAIF client.
760
+ /// Add your project ID and API key in the initialiser or load from a config file.
761
+ @MainActor
762
+ final class VaifManager: ObservableObject {
763
+ static let shared = VaifManager()
764
+
765
+ let client: VaifClient
766
+
767
+ @Published var isAuthenticated = false
768
+
769
+ private init() {
770
+ guard
771
+ let projectId = ProcessInfo.processInfo.environment["VAIF_PROJECT_ID"]
772
+ ?? Bundle.main.infoDictionary?["VAIF_PROJECT_ID"] as? String,
773
+ let apiKey = ProcessInfo.processInfo.environment["VAIF_API_KEY"]
774
+ ?? Bundle.main.infoDictionary?["VAIF_API_KEY"] as? String
775
+ else {
776
+ fatalError("VAIF_PROJECT_ID and VAIF_API_KEY must be set")
777
+ }
778
+
779
+ self.client = VaifClient(
780
+ projectId: projectId,
781
+ apiKey: apiKey
782
+ )
783
+ }
784
+
785
+ // MARK: - Auth helpers
786
+
787
+ func signIn(email: String, password: String) async throws {
788
+ try await client.auth.signIn(email: email, password: password)
789
+ isAuthenticated = true
790
+ }
791
+
792
+ func signOut() async throws {
793
+ try await client.auth.signOut()
794
+ isAuthenticated = false
795
+ }
796
+
797
+ // MARK: - Database helpers
798
+
799
+ func query<T: Decodable>(_ table: String, type: T.Type) async throws -> [T] {
800
+ return try await client.from(table).select().execute().value
801
+ }
802
+
803
+ func insert<T: Encodable>(_ table: String, values: T) async throws {
804
+ try await client.from(table).insert(values).execute()
805
+ }
806
+ }
807
+ `},{path:".env.example",content:`# VAIF Configuration
808
+ # Add these to your Xcode scheme environment variables or Info.plist
809
+
810
+ VAIF_PROJECT_ID=your-project-id
811
+ VAIF_API_KEY=your-anon-key
812
+ `},{path:"README-VAIF.md",content:`# VAIF Swift Setup
813
+
814
+ ## 1. Add the Swift Package
815
+
816
+ In Xcode: **File \u2192 Add Package Dependencies\u2026**
817
+
818
+ Enter the repository URL:
819
+ \`\`\`
820
+ https://github.com/vaif-technologies/vaif-swift
821
+ \`\`\`
822
+
823
+ Select the **VaifClient** library and add it to your target.
824
+
825
+ ## 2. Configure Environment
826
+
827
+ Add your project credentials to your Xcode scheme:
828
+
829
+ 1. Edit Scheme \u2192 Run \u2192 Arguments \u2192 Environment Variables
830
+ 2. Add \`VAIF_PROJECT_ID\` and \`VAIF_API_KEY\`
831
+
832
+ Or add them to **Info.plist**:
833
+ \`\`\`xml
834
+ <key>VAIF_PROJECT_ID</key>
835
+ <string>your-project-id</string>
836
+ <key>VAIF_API_KEY</key>
837
+ <string>your-anon-key</string>
838
+ \`\`\`
839
+
840
+ ## 3. Usage
841
+
842
+ \`\`\`swift
843
+ import SwiftUI
844
+
845
+ struct ContentView: View {
846
+ @StateObject private var vaif = VaifManager.shared
847
+
848
+ var body: some View {
849
+ // Use vaif.client to interact with your project
850
+ Text("Connected to VAIF")
851
+ }
852
+ }
853
+ \`\`\`
854
+
855
+ ## 4. Generate Types
856
+
857
+ Run the VAIF CLI to generate Swift models from your schema:
858
+
859
+ \`\`\`bash
860
+ npx @vaiftech/cli generate --output ./Models/Database.swift --lang swift
861
+ \`\`\`
862
+ `}],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",defaultFeatures:["database","auth"],files:[{path:"package.json",content:`{
863
+ "name": "my-vaif-app",
864
+ "version": "0.1.0",
865
+ "main": "expo-router/entry",
866
+ "scripts": {
867
+ "start": "expo start",
868
+ "android": "expo start --android",
869
+ "ios": "expo start --ios",
870
+ "web": "expo start --web"
871
+ },
872
+ "dependencies": {
873
+ "@react-native-async-storage/async-storage": "^2.1.0",
874
+ "@vaiftech/sdk-expo": "^1.0.0",
875
+ "expo": "~52.0.0",
876
+ "expo-router": "~4.0.0",
877
+ "react": "^19.0.0",
878
+ "react-native": "~0.76.0"
879
+ },
880
+ "devDependencies": {
881
+ "@types/react": "^19.0.0",
882
+ "typescript": "^5.7.0"
883
+ }
884
+ }
885
+ `},{path:"app.json",content:`{
886
+ "expo": {
887
+ "name": "my-vaif-app",
888
+ "slug": "my-vaif-app",
889
+ "version": "1.0.0",
890
+ "scheme": "myvaifapp",
891
+ "platforms": ["ios", "android", "web"],
892
+ "newArchEnabled": true
893
+ }
894
+ }
895
+ `},{path:"app/_layout.tsx",content:`import { Stack } from "expo-router";
896
+ import { VaifProvider } from "@vaiftech/sdk-expo";
897
+ import { vaif } from "../lib/vaif";
898
+
899
+ export default function RootLayout() {
900
+ return (
901
+ <VaifProvider client={vaif}>
902
+ <Stack>
903
+ <Stack.Screen name="index" options={{ title: "Home" }} />
904
+ </Stack>
905
+ </VaifProvider>
906
+ );
907
+ }
908
+ `},{path:"app/index.tsx",content:`import { View, Text, StyleSheet } from "react-native";
909
+
910
+ export default function HomeScreen() {
911
+ return (
912
+ <View style={styles.container}>
913
+ <Text style={styles.title}>Welcome to VAIF</Text>
914
+ <Text style={styles.subtitle}>Your mobile app is ready. Start building!</Text>
915
+ </View>
916
+ );
917
+ }
918
+
919
+ const styles = StyleSheet.create({
920
+ container: { flex: 1, alignItems: "center", justifyContent: "center", padding: 24 },
921
+ title: { fontSize: 28, fontWeight: "bold", marginBottom: 8 },
922
+ subtitle: { fontSize: 16, color: "#666", textAlign: "center" },
923
+ });
924
+ `},{path:"lib/vaif.ts",content:`import { createExpoClient } from "@vaiftech/sdk-expo";
925
+ import AsyncStorage from "@react-native-async-storage/async-storage";
926
+
927
+ export const vaif = createExpoClient({
928
+ projectId: process.env.EXPO_PUBLIC_VAIF_PROJECT_ID!,
929
+ apiKey: process.env.EXPO_PUBLIC_VAIF_API_KEY!,
930
+ storage: AsyncStorage,
931
+ realtime: { enabled: true },
932
+ });
933
+ `},{path:".env.example",content:`# VAIF Configuration
934
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
935
+
936
+ EXPO_PUBLIC_VAIF_PROJECT_ID=your-project-id
937
+ EXPO_PUBLIC_VAIF_API_KEY=your-anon-key
938
+ `},{path:".gitignore",content:`node_modules
939
+ .expo
940
+ dist
941
+ .env
942
+ `}],featureFiles:{auth:[{path:"app/(auth)/login.tsx",content:`import { useState } from "react";
943
+ import { View, Text, TextInput, TouchableOpacity, StyleSheet, Alert } from "react-native";
944
+ import { useRouter } from "expo-router";
945
+ import { vaif } from "../../lib/vaif";
946
+
947
+ export default function LoginScreen() {
948
+ const router = useRouter();
949
+ const [email, setEmail] = useState("");
950
+ const [password, setPassword] = useState("");
951
+ const [loading, setLoading] = useState(false);
952
+
953
+ async function handleLogin() {
954
+ setLoading(true);
955
+ const { error } = await vaif.auth.signInWithPassword({ email, password });
956
+ setLoading(false);
957
+ if (error) Alert.alert("Error", error.message);
958
+ else router.replace("/");
959
+ }
960
+
961
+ return (
962
+ <View style={styles.container}>
963
+ <Text style={styles.title}>Log In</Text>
964
+ <TextInput style={styles.input} placeholder="Email" value={email} onChangeText={setEmail} autoCapitalize="none" keyboardType="email-address" />
965
+ <TextInput style={styles.input} placeholder="Password" value={password} onChangeText={setPassword} secureTextEntry />
966
+ <TouchableOpacity style={styles.button} onPress={handleLogin} disabled={loading}>
967
+ <Text style={styles.buttonText}>{loading ? "Logging in..." : "Log In"}</Text>
968
+ </TouchableOpacity>
969
+ </View>
970
+ );
971
+ }
972
+
973
+ const styles = StyleSheet.create({
974
+ container: { flex: 1, padding: 24, justifyContent: "center" },
975
+ title: { fontSize: 28, fontWeight: "bold", marginBottom: 24, textAlign: "center" },
976
+ input: { borderWidth: 1, borderColor: "#ccc", borderRadius: 8, padding: 12, marginBottom: 12, fontSize: 16 },
977
+ button: { backgroundColor: "#0070f3", borderRadius: 8, padding: 14, alignItems: "center" },
978
+ buttonText: { color: "#fff", fontSize: 16, fontWeight: "600" },
979
+ });
980
+ `},{path:"app/(auth)/signup.tsx",content:`import { useState } from "react";
981
+ import { View, Text, TextInput, TouchableOpacity, StyleSheet, Alert } from "react-native";
982
+ import { useRouter } from "expo-router";
983
+ import { vaif } from "../../lib/vaif";
984
+
985
+ export default function SignupScreen() {
986
+ const router = useRouter();
987
+ const [email, setEmail] = useState("");
988
+ const [password, setPassword] = useState("");
989
+ const [loading, setLoading] = useState(false);
990
+
991
+ async function handleSignup() {
992
+ setLoading(true);
993
+ const { error } = await vaif.auth.signUp({ email, password });
994
+ setLoading(false);
995
+ if (error) Alert.alert("Error", error.message);
996
+ else router.replace("/");
997
+ }
998
+
999
+ return (
1000
+ <View style={styles.container}>
1001
+ <Text style={styles.title}>Sign Up</Text>
1002
+ <TextInput style={styles.input} placeholder="Email" value={email} onChangeText={setEmail} autoCapitalize="none" keyboardType="email-address" />
1003
+ <TextInput style={styles.input} placeholder="Password" value={password} onChangeText={setPassword} secureTextEntry />
1004
+ <TouchableOpacity style={styles.button} onPress={handleSignup} disabled={loading}>
1005
+ <Text style={styles.buttonText}>{loading ? "Creating account..." : "Sign Up"}</Text>
1006
+ </TouchableOpacity>
1007
+ </View>
1008
+ );
1009
+ }
1010
+
1011
+ const styles = StyleSheet.create({
1012
+ container: { flex: 1, padding: 24, justifyContent: "center" },
1013
+ title: { fontSize: 28, fontWeight: "bold", marginBottom: 24, textAlign: "center" },
1014
+ input: { borderWidth: 1, borderColor: "#ccc", borderRadius: 8, padding: 12, marginBottom: 12, fontSize: 16 },
1015
+ button: { backgroundColor: "#0070f3", borderRadius: 8, padding: 14, alignItems: "center" },
1016
+ buttonText: { color: "#fff", fontSize: 16, fontWeight: "600" },
1017
+ });
1018
+ `}],storage:[{path:"hooks/useImagePicker.ts",content:`import { useState, useCallback } from "react";
1019
+ import * as ImagePicker from "expo-image-picker";
1020
+ import { vaif } from "../lib/vaif";
1021
+
1022
+ interface UploadResult {
1023
+ path: string;
1024
+ publicUrl: string;
1025
+ }
1026
+
1027
+ export function useImagePicker(bucket = "uploads") {
1028
+ const [uploading, setUploading] = useState(false);
1029
+ const [error, setError] = useState<string | null>(null);
1030
+
1031
+ const pickAndUpload = useCallback(async (): Promise<UploadResult | null> => {
1032
+ const result = await ImagePicker.launchImageLibraryAsync({
1033
+ mediaTypes: ImagePicker.MediaTypeOptions.Images,
1034
+ quality: 0.8,
1035
+ });
1036
+
1037
+ if (result.canceled || !result.assets[0]) return null;
1038
+
1039
+ setUploading(true);
1040
+ setError(null);
1041
+
1042
+ const asset = result.assets[0];
1043
+ const ext = asset.uri.split(".").pop() || "jpg";
1044
+ const filePath = \`\${Date.now()}.\${ext}\`;
1045
+
1046
+ const response = await fetch(asset.uri);
1047
+ const blob = await response.blob();
1048
+
1049
+ const { data, error: uploadError } = await vaif.storage
1050
+ .from(bucket)
1051
+ .upload(filePath, blob);
1052
+
1053
+ if (uploadError) {
1054
+ setError(uploadError.message);
1055
+ setUploading(false);
1056
+ return null;
1057
+ }
1058
+
1059
+ const { data: urlData } = vaif.storage.from(bucket).getPublicUrl(data.path);
1060
+ setUploading(false);
1061
+ return { path: data.path, publicUrl: urlData.publicUrl };
1062
+ }, [bucket]);
1063
+
1064
+ return { pickAndUpload, uploading, error };
1065
+ }
1066
+ `}],realtime:[{path:"hooks/useRealtimeMessages.ts",content:`import { useEffect, useState, useCallback } from "react";
1067
+ import { vaif } from "../lib/vaif";
1068
+
1069
+ interface Message {
1070
+ id: string;
1071
+ content: string;
1072
+ user_id: string;
1073
+ created_at: string;
1074
+ }
1075
+
1076
+ export function useRealtimeMessages(channelId: string) {
1077
+ const [messages, setMessages] = useState<Message[]>([]);
1078
+ const [loading, setLoading] = useState(true);
1079
+
1080
+ useEffect(() => {
1081
+ vaif.from("messages").select("*").eq("channel_id", channelId)
1082
+ .order("created_at", { ascending: true }).limit(50)
1083
+ .then(({ data }) => {
1084
+ if (data) setMessages(data as Message[]);
1085
+ setLoading(false);
1086
+ });
1087
+ }, [channelId]);
1088
+
1089
+ useEffect(() => {
1090
+ const channel = vaif
1091
+ .channel(\`messages:\${channelId}\`)
1092
+ .on("postgres_changes", { event: "INSERT", schema: "public", table: "messages", filter: \`channel_id=eq.\${channelId}\` }, (payload) => {
1093
+ setMessages((prev) => [...prev, payload.new as Message]);
1094
+ })
1095
+ .subscribe();
1096
+
1097
+ return () => { channel.unsubscribe(); };
1098
+ }, [channelId]);
1099
+
1100
+ const refresh = useCallback(async () => {
1101
+ const { data } = await vaif.from("messages").select("*").eq("channel_id", channelId).order("created_at", { ascending: true }).limit(50);
1102
+ if (data) setMessages(data as Message[]);
1103
+ }, [channelId]);
1104
+
1105
+ return { messages, loading, refresh };
1106
+ }
1107
+ `}]},dependencies:["@vaiftech/sdk-expo","@react-native-async-storage/async-storage","expo","expo-router","react","react-native"],postInstructions:["cd my-vaif-app","npm install","# Copy .env.example to .env and add your VAIF credentials","npx expo start"]},"flutter-app":{name:"Flutter App",description:"Dart/Flutter client setup with environment configuration",tag:"Flutter / Dart",defaultFeatures:["database","auth"],files:[{path:"lib/main.dart",content:`import 'package:flutter/material.dart';
1108
+ import 'vaif_client.dart';
1109
+
1110
+ void main() async {
1111
+ WidgetsFlutterBinding.ensureInitialized();
1112
+ await initVaif();
1113
+ runApp(const MyApp());
1114
+ }
1115
+
1116
+ class MyApp extends StatelessWidget {
1117
+ const MyApp({super.key});
1118
+
1119
+ @override
1120
+ Widget build(BuildContext context) {
1121
+ return MaterialApp(
1122
+ title: 'My VAIF App',
1123
+ theme: ThemeData(colorSchemeSeed: Colors.blue, useMaterial3: true),
1124
+ home: const HomeScreen(),
1125
+ );
1126
+ }
1127
+ }
1128
+
1129
+ class HomeScreen extends StatelessWidget {
1130
+ const HomeScreen({super.key});
1131
+
1132
+ @override
1133
+ Widget build(BuildContext context) {
1134
+ return Scaffold(
1135
+ appBar: AppBar(title: const Text('My VAIF App')),
1136
+ body: const Center(child: Text('Welcome to VAIF! Start building.')),
1137
+ );
1138
+ }
1139
+ }
1140
+ `},{path:"lib/vaif_client.dart",content:`import 'package:vaif_client/vaif_client.dart';
1141
+ import 'package:flutter_dotenv/flutter_dotenv.dart';
1142
+
1143
+ late final VaifClient vaif;
1144
+
1145
+ Future<void> initVaif() async {
1146
+ await dotenv.load(fileName: '.env');
1147
+
1148
+ final projectId = dotenv.env['VAIF_PROJECT_ID'];
1149
+ final apiKey = dotenv.env['VAIF_API_KEY'];
1150
+
1151
+ if (projectId == null || apiKey == null) {
1152
+ throw Exception('VAIF_PROJECT_ID and VAIF_API_KEY must be set in .env');
1153
+ }
1154
+
1155
+ vaif = VaifClient(
1156
+ projectId: projectId,
1157
+ apiKey: apiKey,
1158
+ realtime: const RealtimeConfig(enabled: true),
1159
+ );
1160
+ }
1161
+ `},{path:"pubspec.yaml",content:`name: my_vaif_app
1162
+ description: A Flutter app powered by VAIF.
1163
+ version: 0.1.0
1164
+ publish_to: 'none'
1165
+
1166
+ environment:
1167
+ sdk: ^3.5.0
1168
+
1169
+ dependencies:
1170
+ flutter:
1171
+ sdk: flutter
1172
+ vaif_client: ^1.0.0
1173
+ flutter_dotenv: ^5.1.0
1174
+
1175
+ dev_dependencies:
1176
+ flutter_test:
1177
+ sdk: flutter
1178
+ flutter_lints: ^5.0.0
1179
+
1180
+ flutter:
1181
+ uses-material-design: true
1182
+ assets:
1183
+ - .env
1184
+ `},{path:".env.example",content:`VAIF_PROJECT_ID=your-project-id
1185
+ VAIF_API_KEY=your-anon-key
1186
+ `},{path:".gitignore",content:`build/
1187
+ .dart_tool/
1188
+ .packages
1189
+ .env
1190
+ *.iml
1191
+ `}],featureFiles:{auth:[{path:"lib/screens/login_screen.dart",content:`import 'package:flutter/material.dart';
1192
+ import '../vaif_client.dart';
1193
+
1194
+ class LoginScreen extends StatefulWidget {
1195
+ const LoginScreen({super.key});
1196
+
1197
+ @override
1198
+ State<LoginScreen> createState() => _LoginScreenState();
1199
+ }
1200
+
1201
+ class _LoginScreenState extends State<LoginScreen> {
1202
+ final _emailController = TextEditingController();
1203
+ final _passwordController = TextEditingController();
1204
+ bool _loading = false;
1205
+ String? _error;
1206
+
1207
+ Future<void> _handleLogin() async {
1208
+ setState(() { _loading = true; _error = null; });
1209
+
1210
+ try {
1211
+ await vaif.auth.signInWithPassword(
1212
+ email: _emailController.text,
1213
+ password: _passwordController.text,
1214
+ );
1215
+ if (mounted) Navigator.of(context).pushReplacementNamed('/');
1216
+ } catch (e) {
1217
+ setState(() { _error = e.toString(); });
1218
+ } finally {
1219
+ if (mounted) setState(() { _loading = false; });
1220
+ }
1221
+ }
1222
+
1223
+ @override
1224
+ Widget build(BuildContext context) {
1225
+ return Scaffold(
1226
+ appBar: AppBar(title: const Text('Log In')),
1227
+ body: Padding(
1228
+ padding: const EdgeInsets.all(24),
1229
+ child: Column(
1230
+ mainAxisAlignment: MainAxisAlignment.center,
1231
+ children: [
1232
+ TextField(controller: _emailController, decoration: const InputDecoration(labelText: 'Email'), keyboardType: TextInputType.emailAddress),
1233
+ const SizedBox(height: 12),
1234
+ TextField(controller: _passwordController, decoration: const InputDecoration(labelText: 'Password'), obscureText: true),
1235
+ const SizedBox(height: 24),
1236
+ if (_error != null) Text(_error!, style: const TextStyle(color: Colors.red)),
1237
+ const SizedBox(height: 12),
1238
+ ElevatedButton(
1239
+ onPressed: _loading ? null : _handleLogin,
1240
+ child: Text(_loading ? 'Logging in...' : 'Log In'),
1241
+ ),
1242
+ ],
1243
+ ),
1244
+ ),
1245
+ );
1246
+ }
1247
+ }
1248
+ `}]},postInstructions:["flutter pub get","# Copy .env.example to .env and add your VAIF credentials","flutter run"]},"python-fastapi-backend":{name:"Python FastAPI Backend",description:"FastAPI backend with VAIF client, auth middleware, and type-safe queries",tag:"Python / FastAPI",defaultFeatures:["database","auth"],files:[{path:"main.py",content:`"""VAIF FastAPI application."""
1249
+
1250
+ from fastapi import FastAPI
1251
+ from fastapi.middleware.cors import CORSMiddleware
1252
+ from vaif_client import get_vaif_client
1253
+
1254
+ app = FastAPI(title="My VAIF API", version="0.1.0")
1255
+
1256
+ app.add_middleware(
1257
+ CORSMiddleware,
1258
+ allow_origins=["*"],
1259
+ allow_credentials=True,
1260
+ allow_methods=["*"],
1261
+ allow_headers=["*"],
1262
+ )
1263
+
1264
+
1265
+ @app.get("/")
1266
+ async def root():
1267
+ return {"status": "ok", "message": "VAIF API running"}
1268
+
1269
+
1270
+ @app.get("/health")
1271
+ async def health():
1272
+ return {"status": "healthy"}
1273
+
1274
+
1275
+ @app.get("/items")
1276
+ async def list_items():
1277
+ client = get_vaif_client()
1278
+ result = await client.from_("items").select("*").execute()
1279
+ return {"data": result.data}
1280
+ `},{path:"vaif_client.py",content:`"""VAIF client setup for FastAPI."""
1281
+
1282
+ import os
1283
+ from functools import lru_cache
1284
+
1285
+ from dotenv import load_dotenv
1286
+ from vaif import Client, ServiceClient
1287
+
1288
+ load_dotenv()
1289
+
1290
+ VAIF_PROJECT_ID = os.environ["VAIF_PROJECT_ID"]
1291
+ VAIF_API_KEY = os.environ["VAIF_API_KEY"]
1292
+ VAIF_SECRET_KEY = os.environ.get("VAIF_SECRET_KEY", "")
1293
+
1294
+
1295
+ @lru_cache()
1296
+ def get_vaif_client() -> Client:
1297
+ """Public client using the anon key (respects Row Level Security)."""
1298
+ return Client(project_id=VAIF_PROJECT_ID, api_key=VAIF_API_KEY)
1299
+
1300
+
1301
+ @lru_cache()
1302
+ def get_vaif_admin() -> ServiceClient:
1303
+ """Admin/service client that bypasses RLS. Use with caution."""
1304
+ return ServiceClient(project_id=VAIF_PROJECT_ID, secret_key=VAIF_SECRET_KEY)
1305
+ `},{path:"requirements.txt",content:`vaif-client>=1.0.0
1306
+ fastapi>=0.110.0
1307
+ uvicorn[standard]>=0.27.0
1308
+ python-dotenv>=1.0.0
1309
+ `},{path:".env.example",content:`# VAIF Configuration
1310
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
1311
+
1312
+ VAIF_PROJECT_ID=your-project-id
1313
+ VAIF_API_KEY=your-anon-key
1314
+ VAIF_SECRET_KEY=your-secret-key
1315
+ `},{path:".gitignore",content:`__pycache__
1316
+ *.pyc
1317
+ .env
1318
+ .venv
1319
+ venv
1320
+ `}],featureFiles:{auth:[{path:"middleware/auth.py",content:`"""VAIF auth middleware for FastAPI."""
1321
+
1322
+ from typing import Optional
1323
+
1324
+ from fastapi import Depends, HTTPException, status
1325
+ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
1326
+ from vaif_client import get_vaif_admin
1327
+
1328
+ security = HTTPBearer(auto_error=False)
1329
+
1330
+
1331
+ async def get_current_user(
1332
+ credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
1333
+ ):
1334
+ """FastAPI dependency that validates VAIF auth tokens.
1335
+
1336
+ Usage:
1337
+ @app.get("/protected")
1338
+ async def protected_route(user=Depends(get_current_user)):
1339
+ return {"user_id": user["id"]}
1340
+ """
1341
+ if credentials is None:
1342
+ raise HTTPException(
1343
+ status_code=status.HTTP_401_UNAUTHORIZED,
1344
+ detail="Missing authorization header",
1345
+ )
1346
+
1347
+ client = get_vaif_admin()
1348
+ try:
1349
+ user = await client.auth.get_user(credentials.credentials)
1350
+ except Exception as exc:
1351
+ raise HTTPException(
1352
+ status_code=status.HTTP_401_UNAUTHORIZED,
1353
+ detail=f"Invalid token: {exc}",
1354
+ )
1355
+
1356
+ if user is None:
1357
+ raise HTTPException(
1358
+ status_code=status.HTTP_401_UNAUTHORIZED,
1359
+ detail="Invalid or expired token",
1360
+ )
1361
+
1362
+ return user
1363
+ `},{path:"middleware/__init__.py",content:""}],storage:[{path:"routes/storage.py",content:`"""File upload routes using VAIF Storage."""
1364
+
1365
+ from fastapi import APIRouter, UploadFile, File
1366
+ from vaif_client import get_vaif_admin
1367
+
1368
+ router = APIRouter(prefix="/storage", tags=["storage"])
1369
+
1370
+ BUCKET = "uploads"
1371
+
1372
+
1373
+ @router.post("/upload")
1374
+ async def upload_file(file: UploadFile = File(...)):
1375
+ client = get_vaif_admin()
1376
+ file_path = f"{file.filename}"
1377
+ contents = await file.read()
1378
+
1379
+ result = await client.storage.from_(BUCKET).upload(file_path, contents)
1380
+ url_data = client.storage.from_(BUCKET).get_public_url(result.path)
1381
+
1382
+ return {"path": result.path, "public_url": url_data}
1383
+ `},{path:"routes/__init__.py",content:""}],functions:[{path:"routes/functions.py",content:`"""Invoke VAIF serverless functions."""
1384
+
1385
+ from fastapi import APIRouter
1386
+ from vaif_client import get_vaif_client
1387
+
1388
+ router = APIRouter(prefix="/functions", tags=["functions"])
1389
+
1390
+
1391
+ @router.post("/invoke/{function_name}")
1392
+ async def invoke_function(function_name: str, payload: dict = {}):
1393
+ client = get_vaif_client()
1394
+ result = await client.functions.invoke(function_name, body=payload)
1395
+ return {"data": result}
1396
+ `}]},postInstructions:["pip install -r requirements.txt","# Copy .env.example to .env and add your VAIF credentials","uvicorn main:app --reload"]},"go-backend-api":{name:"Go Backend API",description:"Go backend with VAIF client initialisation and HTTP middleware",tag:"Go",defaultFeatures:["database","auth"],files:[{path:"main.go",content:`package main
1397
+
1398
+ import (
1399
+ "encoding/json"
1400
+ "log"
1401
+ "net/http"
1402
+
1403
+ "github.com/joho/godotenv"
1404
+ "myapp/vaif"
1405
+ )
1406
+
1407
+ func main() {
1408
+ _ = godotenv.Load()
1409
+
1410
+ if err := vaif.Init(); err != nil {
1411
+ log.Fatalf("Failed to initialise VAIF: %v", err)
1412
+ }
1413
+
1414
+ mux := http.NewServeMux()
1415
+
1416
+ mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
1417
+ json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
1418
+ })
1419
+
1420
+ log.Println("Server running on :8080")
1421
+ log.Fatal(http.ListenAndServe(":8080", mux))
1422
+ }
1423
+ `},{path:"vaif/client.go",content:`package vaif
1424
+
1425
+ import (
1426
+ "fmt"
1427
+ "os"
1428
+
1429
+ vaifclient "github.com/vaif-technologies/vaif-go"
1430
+ )
1431
+
1432
+ var Client *vaifclient.Client
1433
+
1434
+ func Init() error {
1435
+ projectID := os.Getenv("VAIF_PROJECT_ID")
1436
+ apiKey := os.Getenv("VAIF_API_KEY")
1437
+ secretKey := os.Getenv("VAIF_SECRET_KEY")
1438
+
1439
+ if projectID == "" || apiKey == "" {
1440
+ return fmt.Errorf("VAIF_PROJECT_ID and VAIF_API_KEY must be set")
1441
+ }
1442
+
1443
+ var err error
1444
+ Client, err = vaifclient.NewClient(vaifclient.Config{
1445
+ ProjectID: projectID,
1446
+ APIKey: apiKey,
1447
+ SecretKey: secretKey,
1448
+ })
1449
+ if err != nil {
1450
+ return fmt.Errorf("failed to create VAIF client: %w", err)
1451
+ }
1452
+
1453
+ return nil
1454
+ }
1455
+ `},{path:"go.mod",content:`module myapp
1456
+
1457
+ go 1.22
1458
+
1459
+ require (
1460
+ github.com/joho/godotenv v1.5.1
1461
+ github.com/vaif-technologies/vaif-go v1.0.0
1462
+ )
1463
+ `},{path:".env.example",content:`# VAIF Configuration
1464
+ VAIF_PROJECT_ID=your-project-id
1465
+ VAIF_API_KEY=your-anon-key
1466
+ VAIF_SECRET_KEY=your-secret-key
1467
+ `},{path:".gitignore",content:`*.exe
1468
+ *.exe~
1469
+ *.dll
1470
+ *.so
1471
+ *.dylib
1472
+ .env
1473
+ `}],featureFiles:{auth:[{path:"middleware/auth.go",content:`package middleware
1474
+
1475
+ import (
1476
+ "net/http"
1477
+ "strings"
1478
+
1479
+ "myapp/vaif"
1480
+ vaifclient "github.com/vaif-technologies/vaif-go"
1481
+ )
1482
+
1483
+ func AuthMiddleware(next http.Handler) http.Handler {
1484
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1485
+ auth := r.Header.Get("Authorization")
1486
+ if auth == "" {
1487
+ http.Error(w, "missing authorization header", http.StatusUnauthorized)
1488
+ return
1489
+ }
1490
+
1491
+ token := strings.TrimPrefix(auth, "Bearer ")
1492
+ if token == auth {
1493
+ http.Error(w, "invalid authorization format", http.StatusUnauthorized)
1494
+ return
1495
+ }
1496
+
1497
+ user, err := vaif.Client.Auth.GetUser(r.Context(), token)
1498
+ if err != nil {
1499
+ http.Error(w, "invalid or expired token", http.StatusUnauthorized)
1500
+ return
1501
+ }
1502
+
1503
+ ctx := vaifclient.WithUser(r.Context(), user)
1504
+ next.ServeHTTP(w, r.WithContext(ctx))
1505
+ })
1506
+ }
1507
+ `}],storage:[{path:"handlers/storage.go",content:`package handlers
1508
+
1509
+ import (
1510
+ "encoding/json"
1511
+ "fmt"
1512
+ "io"
1513
+ "net/http"
1514
+ "time"
1515
+
1516
+ "myapp/vaif"
1517
+ )
1518
+
1519
+ func UploadHandler(w http.ResponseWriter, r *http.Request) {
1520
+ if r.Method != http.MethodPost {
1521
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
1522
+ return
1523
+ }
1524
+
1525
+ file, header, err := r.FormFile("file")
1526
+ if err != nil {
1527
+ http.Error(w, "invalid file", http.StatusBadRequest)
1528
+ return
1529
+ }
1530
+ defer file.Close()
1531
+
1532
+ data, err := io.ReadAll(file)
1533
+ if err != nil {
1534
+ http.Error(w, "failed to read file", http.StatusInternalServerError)
1535
+ return
1536
+ }
1537
+
1538
+ path := fmt.Sprintf("%d-%s", time.Now().Unix(), header.Filename)
1539
+ result, err := vaif.Client.Storage.From("uploads").Upload(r.Context(), path, data)
1540
+ if err != nil {
1541
+ http.Error(w, "upload failed", http.StatusInternalServerError)
1542
+ return
1543
+ }
1544
+
1545
+ w.Header().Set("Content-Type", "application/json")
1546
+ json.NewEncoder(w).Encode(result)
1547
+ }
1548
+ `}]},postInstructions:["go mod tidy","# Copy .env.example to .env and add your VAIF credentials","go run main.go"]},"todo-app":{name:"Todo App",description:"Simple React todo app \u2013 great for learning VAIF basics",tag:"React Starter",defaultFeatures:["database"],files:[{path:"src/lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
1549
+
1550
+ export const vaif = createClient({
1551
+ projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
1552
+ apiKey: import.meta.env.VITE_VAIF_API_KEY,
1553
+ });
1554
+
1555
+ // Typed helpers for the todos table
1556
+ export interface Todo {
1557
+ id: string;
1558
+ title: string;
1559
+ done: boolean;
1560
+ created_at: string;
1561
+ user_id?: string;
1562
+ }
1563
+
1564
+ export async function getTodos(): Promise<Todo[]> {
1565
+ const { data, error } = await vaif
1566
+ .from("todos")
1567
+ .select("*")
1568
+ .order("created_at", { ascending: false });
1569
+
1570
+ if (error) throw error;
1571
+ return data as Todo[];
1572
+ }
1573
+
1574
+ export async function addTodo(title: string): Promise<Todo> {
1575
+ const { data, error } = await vaif
1576
+ .from("todos")
1577
+ .insert({ title, done: false })
1578
+ .select()
1579
+ .single();
1580
+
1581
+ if (error) throw error;
1582
+ return data as Todo;
1583
+ }
1584
+
1585
+ export async function toggleTodo(id: string, done: boolean): Promise<void> {
1586
+ const { error } = await vaif
1587
+ .from("todos")
1588
+ .update({ done })
1589
+ .eq("id", id);
1590
+
1591
+ if (error) throw error;
1592
+ }
1593
+
1594
+ export async function deleteTodo(id: string): Promise<void> {
1595
+ const { error } = await vaif
1596
+ .from("todos")
1597
+ .delete()
1598
+ .eq("id", id);
1599
+
1600
+ if (error) throw error;
1601
+ }
1602
+ `},{path:".env.example",content:`# VAIF Configuration
1603
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
1604
+
1605
+ VITE_VAIF_PROJECT_ID=your-project-id
1606
+ VITE_VAIF_API_KEY=your-anon-key
1607
+ `}],dependencies:["@vaiftech/client","@vaiftech/react"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Create a 'todos' table in your VAIF dashboard with columns: id (uuid), title (text), done (boolean), created_at (timestamptz)","Import helpers from './lib/vaif' in your components","Run: npx vaif generate to generate TypeScript types"]},"realtime-chat":{name:"Realtime Chat",description:"React chat app with VAIF realtime subscriptions for live messaging",tag:"React + Realtime",defaultFeatures:["database","realtime","auth"],files:[{path:"src/lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
1608
+
1609
+ export const vaif = createClient({
1610
+ projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
1611
+ apiKey: import.meta.env.VITE_VAIF_API_KEY,
1612
+ realtime: {
1613
+ enabled: true,
1614
+ // Automatically reconnect on connection loss
1615
+ reconnect: true,
1616
+ reconnectInterval: 1000,
1617
+ maxReconnectAttempts: 10,
1618
+ },
1619
+ });
1620
+
1621
+ export interface Message {
1622
+ id: string;
1623
+ content: string;
1624
+ user_id: string;
1625
+ username: string;
1626
+ channel_id: string;
1627
+ created_at: string;
1628
+ }
1629
+
1630
+ export async function sendMessage(
1631
+ channelId: string,
1632
+ content: string,
1633
+ userId: string,
1634
+ username: string,
1635
+ ): Promise<Message> {
1636
+ const { data, error } = await vaif
1637
+ .from("messages")
1638
+ .insert({
1639
+ content,
1640
+ user_id: userId,
1641
+ username,
1642
+ channel_id: channelId,
1643
+ })
1644
+ .select()
1645
+ .single();
1646
+
1647
+ if (error) throw error;
1648
+ return data as Message;
1649
+ }
1650
+
1651
+ export async function getMessages(channelId: string, limit = 50): Promise<Message[]> {
1652
+ const { data, error } = await vaif
1653
+ .from("messages")
1654
+ .select("*")
1655
+ .eq("channel_id", channelId)
1656
+ .order("created_at", { ascending: true })
1657
+ .limit(limit);
1658
+
1659
+ if (error) throw error;
1660
+ return data as Message[];
1661
+ }
1662
+ `},{path:"src/hooks/useRealtimeMessages.ts",content:`import { useEffect, useState, useCallback } from "react";
1663
+ import { vaif, type Message, getMessages } from "../lib/vaif";
1664
+
1665
+ interface UseRealtimeMessagesOptions {
1666
+ channelId: string;
1667
+ initialLimit?: number;
1668
+ }
1669
+
1670
+ /**
1671
+ * Hook that subscribes to realtime message changes on a channel.
1672
+ *
1673
+ * Usage:
1674
+ * const { messages, isLoading, error } = useRealtimeMessages({
1675
+ * channelId: "general",
1676
+ * });
1677
+ */
1678
+ export function useRealtimeMessages({
1679
+ channelId,
1680
+ initialLimit = 50,
1681
+ }: UseRealtimeMessagesOptions) {
1682
+ const [messages, setMessages] = useState<Message[]>([]);
1683
+ const [isLoading, setIsLoading] = useState(true);
1684
+ const [error, setError] = useState<Error | null>(null);
1685
+
1686
+ // Load initial messages
1687
+ useEffect(() => {
1688
+ let cancelled = false;
1689
+
1690
+ async function load() {
1691
+ try {
1692
+ setIsLoading(true);
1693
+ const data = await getMessages(channelId, initialLimit);
1694
+ if (!cancelled) {
1695
+ setMessages(data);
1696
+ setError(null);
1697
+ }
1698
+ } catch (err) {
1699
+ if (!cancelled) {
1700
+ setError(err instanceof Error ? err : new Error(String(err)));
1701
+ }
1702
+ } finally {
1703
+ if (!cancelled) setIsLoading(false);
1704
+ }
1705
+ }
1706
+
1707
+ load();
1708
+ return () => { cancelled = true; };
1709
+ }, [channelId, initialLimit]);
1710
+
1711
+ // Subscribe to realtime changes
1712
+ useEffect(() => {
1713
+ const subscription = vaif
1714
+ .channel(\`messages:\${channelId}\`)
1715
+ .on(
1716
+ "postgres_changes",
1717
+ {
1718
+ event: "*",
1719
+ schema: "public",
1720
+ table: "messages",
1721
+ filter: \`channel_id=eq.\${channelId}\`,
1722
+ },
1723
+ (payload) => {
1724
+ if (payload.eventType === "INSERT") {
1725
+ setMessages((prev) => [...prev, payload.new as Message]);
1726
+ } else if (payload.eventType === "UPDATE") {
1727
+ setMessages((prev) =>
1728
+ prev.map((msg) =>
1729
+ msg.id === (payload.new as Message).id
1730
+ ? (payload.new as Message)
1731
+ : msg,
1732
+ ),
1733
+ );
1734
+ } else if (payload.eventType === "DELETE") {
1735
+ setMessages((prev) =>
1736
+ prev.filter((msg) => msg.id !== (payload.old as Message).id),
1737
+ );
1738
+ }
1739
+ },
1740
+ )
1741
+ .subscribe();
1742
+
1743
+ return () => {
1744
+ subscription.unsubscribe();
1745
+ };
1746
+ }, [channelId]);
1747
+
1748
+ const refresh = useCallback(async () => {
1749
+ const data = await getMessages(channelId, initialLimit);
1750
+ setMessages(data);
1751
+ }, [channelId, initialLimit]);
1752
+
1753
+ return { messages, isLoading, error, refresh };
1754
+ }
1755
+ `},{path:".env.example",content:`# VAIF Configuration
1756
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
1757
+
1758
+ VITE_VAIF_PROJECT_ID=your-project-id
1759
+ VITE_VAIF_API_KEY=your-anon-key
1760
+ `}],dependencies:["@vaiftech/client","@vaiftech/react"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Create a 'messages' table with columns: id (uuid), content (text), user_id (text), username (text), channel_id (text), created_at (timestamptz)","Enable Realtime on the messages table in your VAIF dashboard","Use the useRealtimeMessages hook in your components","Run: npx vaif generate to generate TypeScript types"]},"saas-starter":{name:"SaaS Starter",description:"Full SaaS starter with VAIF auth, team/org support, and server-side helpers",tag:"Next.js SaaS",defaultFeatures:["database","auth","functions"],files:[{path:"lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
1761
+ import { createServerClient } from "@vaiftech/client/server";
1762
+
1763
+ // Browser client \u2013 use in Client Components
1764
+ export const vaif = createClient({
1765
+ projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
1766
+ apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
1767
+ });
1768
+
1769
+ // Server client \u2013 use in Server Components, Route Handlers, Server Actions
1770
+ export function createVaifServer() {
1771
+ return createServerClient({
1772
+ projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
1773
+ secretKey: process.env.VAIF_SECRET_KEY!,
1774
+ });
1775
+ }
1776
+ `},{path:"lib/auth.ts",content:`import { createVaifServer } from "./vaif";
1777
+
1778
+ // \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
1779
+
1780
+ export async function getCurrentUser() {
1781
+ const vaif = createVaifServer();
1782
+ const { data: { user }, error } = await vaif.auth.getUser();
1783
+ if (error || !user) return null;
1784
+ return user;
1785
+ }
1786
+
1787
+ export async function requireUser() {
1788
+ const user = await getCurrentUser();
1789
+ if (!user) throw new Error("Unauthorized");
1790
+ return user;
1791
+ }
1792
+
1793
+ // \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
1794
+
1795
+ export interface Team {
1796
+ id: string;
1797
+ name: string;
1798
+ slug: string;
1799
+ owner_id: string;
1800
+ created_at: string;
1801
+ }
1802
+
1803
+ export interface TeamMember {
1804
+ id: string;
1805
+ team_id: string;
1806
+ user_id: string;
1807
+ role: "owner" | "admin" | "member" | "viewer";
1808
+ joined_at: string;
1809
+ }
1810
+
1811
+ export async function getUserTeams(userId: string): Promise<Team[]> {
1812
+ const vaif = createVaifServer();
1813
+
1814
+ // Get team IDs the user belongs to
1815
+ const { data: memberships, error: memberError } = await vaif
1816
+ .from("team_members")
1817
+ .select("team_id")
1818
+ .eq("user_id", userId);
1819
+
1820
+ if (memberError) throw memberError;
1821
+ if (!memberships?.length) return [];
1822
+
1823
+ const teamIds = memberships.map((m) => m.team_id);
1824
+
1825
+ const { data: teams, error: teamError } = await vaif
1826
+ .from("teams")
1827
+ .select("*")
1828
+ .in("id", teamIds)
1829
+ .order("name");
1830
+
1831
+ if (teamError) throw teamError;
1832
+ return (teams ?? []) as Team[];
1833
+ }
1834
+
1835
+ export async function getTeamMembers(teamId: string): Promise<TeamMember[]> {
1836
+ const vaif = createVaifServer();
1837
+
1838
+ const { data, error } = await vaif
1839
+ .from("team_members")
1840
+ .select("*")
1841
+ .eq("team_id", teamId)
1842
+ .order("joined_at");
1843
+
1844
+ if (error) throw error;
1845
+ return (data ?? []) as TeamMember[];
1846
+ }
1847
+
1848
+ export async function createTeam(name: string, slug: string): Promise<Team> {
1849
+ const user = await requireUser();
1850
+ const vaif = createVaifServer();
1851
+
1852
+ const { data: team, error } = await vaif
1853
+ .from("teams")
1854
+ .insert({ name, slug, owner_id: user.id })
1855
+ .select()
1856
+ .single();
1857
+
1858
+ if (error) throw error;
1859
+
1860
+ // Add the creator as owner
1861
+ await vaif.from("team_members").insert({
1862
+ team_id: team.id,
1863
+ user_id: user.id,
1864
+ role: "owner",
1865
+ });
1866
+
1867
+ return team as Team;
1868
+ }
1869
+
1870
+ export async function inviteToTeam(
1871
+ teamId: string,
1872
+ email: string,
1873
+ role: TeamMember["role"] = "member",
1874
+ ): Promise<void> {
1875
+ const vaif = createVaifServer();
1876
+
1877
+ // Look up user by email
1878
+ const { data: users } = await vaif
1879
+ .from("users")
1880
+ .select("id")
1881
+ .eq("email", email)
1882
+ .limit(1);
1883
+
1884
+ if (!users?.length) {
1885
+ throw new Error("User not found. They must create an account first.");
1886
+ }
1887
+
1888
+ const { error } = await vaif.from("team_members").insert({
1889
+ team_id: teamId,
1890
+ user_id: users[0].id,
1891
+ role,
1892
+ });
1893
+
1894
+ if (error) throw error;
1895
+ }
1896
+
1897
+ // \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
1898
+
1899
+ export async function requireTeamRole(
1900
+ teamId: string,
1901
+ requiredRoles: TeamMember["role"][],
1902
+ ): Promise<TeamMember> {
1903
+ const user = await requireUser();
1904
+ const vaif = createVaifServer();
1905
+
1906
+ const { data: member, error } = await vaif
1907
+ .from("team_members")
1908
+ .select("*")
1909
+ .eq("team_id", teamId)
1910
+ .eq("user_id", user.id)
1911
+ .single();
1912
+
1913
+ if (error || !member) {
1914
+ throw new Error("Not a member of this team");
1915
+ }
1916
+
1917
+ if (!requiredRoles.includes(member.role)) {
1918
+ throw new Error(\`Requires one of: \${requiredRoles.join(", ")}\`);
1919
+ }
1920
+
1921
+ return member as TeamMember;
1922
+ }
1923
+ `},{path:".env.example",content:`# VAIF Configuration
1924
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
1925
+
1926
+ NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
1927
+ NEXT_PUBLIC_VAIF_API_KEY=your-anon-key
1928
+ VAIF_SECRET_KEY=your-secret-key
1929
+ `}],dependencies:["@vaiftech/client","@vaiftech/auth","@vaiftech/react"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create 'teams' and 'team_members' tables in your VAIF dashboard","Import auth helpers from '@/lib/auth' in your Server Components/Actions","Use requireUser() for authenticated routes and requireTeamRole() for role checks","Run: npx vaif generate to generate TypeScript types"]},"ecommerce-api":{name:"E-commerce API",description:"API-first e-commerce setup with VAIF storage for product images",tag:"Next.js E-commerce",defaultFeatures:["database","auth","storage"],files:[{path:"lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
1930
+ import { createServerClient } from "@vaiftech/client/server";
1931
+
1932
+ // Browser client
1933
+ export const vaif = createClient({
1934
+ projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
1935
+ apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
1936
+ });
1937
+
1938
+ // Server client
1939
+ export function createVaifServer() {
1940
+ return createServerClient({
1941
+ projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
1942
+ secretKey: process.env.VAIF_SECRET_KEY!,
1943
+ });
1944
+ }
1945
+ `},{path:"lib/storage.ts",content:`import { createVaifServer } from "./vaif";
1946
+
1947
+ const PRODUCT_IMAGES_BUCKET = "product-images";
1948
+
1949
+ interface UploadResult {
1950
+ path: string;
1951
+ publicUrl: string;
1952
+ }
1953
+
1954
+ /**
1955
+ * Upload a product image to VAIF Storage.
1956
+ *
1957
+ * @param file - The file buffer or Blob to upload
1958
+ * @param productId - Product ID used to organise files in folders
1959
+ * @param fileName - Original filename (will be sanitised)
1960
+ * @returns The storage path and public URL
1961
+ */
1962
+ export async function uploadProductImage(
1963
+ file: Buffer | Blob,
1964
+ productId: string,
1965
+ fileName: string,
1966
+ ): Promise<UploadResult> {
1967
+ const vaif = createVaifServer();
1968
+
1969
+ // Sanitise filename and build path
1970
+ const sanitised = fileName.replace(/[^a-zA-Z0-9._-]/g, "_");
1971
+ const storagePath = \`\${productId}/\${Date.now()}-\${sanitised}\`;
1972
+
1973
+ const { data, error } = await vaif.storage
1974
+ .from(PRODUCT_IMAGES_BUCKET)
1975
+ .upload(storagePath, file, {
1976
+ contentType: getContentType(fileName),
1977
+ upsert: false,
1978
+ });
1979
+
1980
+ if (error) throw error;
1981
+
1982
+ const { data: urlData } = vaif.storage
1983
+ .from(PRODUCT_IMAGES_BUCKET)
1984
+ .getPublicUrl(data.path);
1985
+
1986
+ return {
1987
+ path: data.path,
1988
+ publicUrl: urlData.publicUrl,
1989
+ };
1990
+ }
1991
+
1992
+ /**
1993
+ * Delete a product image from storage.
1994
+ */
1995
+ export async function deleteProductImage(storagePath: string): Promise<void> {
1996
+ const vaif = createVaifServer();
1997
+
1998
+ const { error } = await vaif.storage
1999
+ .from(PRODUCT_IMAGES_BUCKET)
2000
+ .remove([storagePath]);
2001
+
2002
+ if (error) throw error;
2003
+ }
2004
+
2005
+ /**
2006
+ * Generate a signed URL for a private product image.
2007
+ *
2008
+ * @param storagePath - The path returned from uploadProductImage
2009
+ * @param expiresIn - Seconds until the URL expires (default: 1 hour)
2010
+ */
2011
+ export async function getSignedImageUrl(
2012
+ storagePath: string,
2013
+ expiresIn = 3600,
2014
+ ): Promise<string> {
2015
+ const vaif = createVaifServer();
2016
+
2017
+ const { data, error } = await vaif.storage
2018
+ .from(PRODUCT_IMAGES_BUCKET)
2019
+ .createSignedUrl(storagePath, expiresIn);
2020
+
2021
+ if (error) throw error;
2022
+ return data.signedUrl;
2023
+ }
2024
+
2025
+ /**
2026
+ * List all images for a product.
2027
+ */
2028
+ export async function listProductImages(productId: string) {
2029
+ const vaif = createVaifServer();
2030
+
2031
+ const { data, error } = await vaif.storage
2032
+ .from(PRODUCT_IMAGES_BUCKET)
2033
+ .list(productId, {
2034
+ sortBy: { column: "created_at", order: "desc" },
2035
+ });
2036
+
2037
+ if (error) throw error;
2038
+ return data;
2039
+ }
2040
+
2041
+ function getContentType(fileName: string): string {
2042
+ const ext = fileName.split(".").pop()?.toLowerCase();
2043
+ const mimeTypes: Record<string, string> = {
2044
+ jpg: "image/jpeg",
2045
+ jpeg: "image/jpeg",
2046
+ png: "image/png",
2047
+ gif: "image/gif",
2048
+ webp: "image/webp",
2049
+ svg: "image/svg+xml",
2050
+ avif: "image/avif",
2051
+ };
2052
+ return mimeTypes[ext ?? ""] ?? "application/octet-stream";
2053
+ }
2054
+ `},{path:".env.example",content:`# VAIF Configuration
2055
+ # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
2056
+
2057
+ NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
2058
+ NEXT_PUBLIC_VAIF_API_KEY=your-anon-key
2059
+ VAIF_SECRET_KEY=your-secret-key
2060
+ `}],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 ae(){console.log(""),console.log(d__default.default.bold("Available project templates")),console.log("");let t=26,e=22;console.log(` ${d__default.default.gray("Template".padEnd(t))}${d__default.default.gray("Stack".padEnd(e))}${d__default.default.gray("Description")}`),console.log(d__default.default.gray(" "+"-".repeat(t+e+40)));for(let[o,n]of Object.entries(re))console.log(` ${d__default.default.cyan(o.padEnd(t))}${d__default.default.yellow(n.tag.padEnd(e))}${d__default.default.white(n.description)}`);console.log(""),console.log(d__default.default.gray("Usage:")),console.log(d__default.default.gray(" npx @vaiftech/cli init --template <name>")),console.log(d__default.default.gray(" npx @vaiftech/cli init -t nextjs-fullstack")),console.log(d__default.default.gray(" npx @vaiftech/cli init -t react-spa --features auth,database,realtime")),console.log(""),console.log(d__default.default.gray("Available features: auth, database, realtime, storage, functions")),console.log("");}async function Ge(t){if(!process.stdin.isTTY||!process.stdout.isTTY)return t;let e=new Set(t.map(n=>$.findIndex(i=>i.name===n)).filter(n=>n>=0)),o=0;return new Promise(n=>{let i=ne__default.default.createInterface({input:process.stdin,output:process.stdout});ne__default.default.emitKeypressEvents(process.stdin,i),process.stdin.setRawMode&&process.stdin.setRawMode(true);function l(){let r=$.length+2;process.stdout.write(`\x1B[${r}A`),a();}function a(){console.log(d__default.default.bold(`
2061
+ ? Which VAIF features do you want to include?`)),$.forEach((r,s)=>{let c=e.has(s)?d__default.default.green("[x]"):"[ ]",f=s===o?d__default.default.cyan("> "):" ";console.log(`${f}${c} ${r.label} ${d__default.default.gray(`(${r.description})`)}`);}),console.log(d__default.default.gray(" (up/down to move, space to toggle, enter to confirm)"));}a(),process.stdin.on("keypress",(r,s)=>{if(s.name==="up"&&o>0)o--,l();else if(s.name==="down"&&o<$.length-1)o++,l();else if(s.name==="space")e.has(o)?e.delete(o):e.add(o),l();else if(s.name==="return"){process.stdin.setRawMode&&process.stdin.setRawMode(false),i.close();let c=[...e].sort().map(f=>$[f].name);n(c.length>0?c:t);}else s.name==="c"&&s.ctrl&&(process.stdin.setRawMode&&process.stdin.setRawMode(false),i.close(),process.exit(0));});})}async function ie(t,e={}){let o=re[t];o||(console.log(d__default.default.red(`
2062
+ Unknown template: ${t}`)),console.log(d__default.default.yellow(`Run 'vaif templates' to see available templates.
2063
+ `)),process.exit(1));let n;e.features&&e.features.length>0?n=e.features.filter(r=>$.some(s=>s.name===r)):o.featureFiles&&Object.keys(o.featureFiles).length>0?n=await Ge(o.defaultFeatures??["database","auth"]):n=o.defaultFeatures??[],console.log(""),console.log(d__default.default.bold(`Scaffolding ${d__default.default.cyan(o.name)} template...`)),n.length>0&&console.log(d__default.default.gray(` Features: ${n.join(", ")}`)),console.log("");let i=[...o.files];if(o.featureFiles)for(let r of n){let s=o.featureFiles[r];s&&i.push(...s);}let l=0,a=0;for(let r of i){let s=b__default.default.resolve(r.path),c=b__default.default.dirname(s);if(j__default.default.existsSync(c)||j__default.default.mkdirSync(c,{recursive:true}),j__default.default.existsSync(s)&&!e.force){console.log(d__default.default.yellow(` skip ${r.path} (already exists)`)),a++;continue}j__default.default.writeFileSync(s,r.content,"utf-8"),console.log(d__default.default.green(` create ${r.path}`)),l++;}console.log(""),l>0&&console.log(d__default.default.green(`Created ${l} file${l!==1?"s":""}.`)),a>0&&console.log(d__default.default.yellow(`Skipped ${a} file${a!==1?"s":""} (use --force to overwrite).`)),(o.dependencies?.length||o.devDependencies?.length)&&(console.log(""),console.log(d__default.default.bold("Install dependencies:")),o.dependencies?.length&&console.log(d__default.default.cyan(` npm install ${o.dependencies.join(" ")}`)),o.devDependencies?.length&&console.log(d__default.default.cyan(` npm install -D ${o.devDependencies.join(" ")}`))),console.log(""),console.log(d__default.default.bold.green("Project scaffolded successfully!")),console.log(""),console.log(d__default.default.bold(" Next steps:")),o.postInstructions.forEach(r=>{console.log(d__default.default.gray(` ${r}`));}),console.log(""),console.log(d__default.default.gray(" Get your project credentials at https://vaif.studio")),console.log("");}var Xe={$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 se(t){let e=K__default.default("Initializing VAIF configuration...").start(),o=b__default.default.resolve("vaif.config.json");j__default.default.existsSync(o)&&!t.force&&(e.fail("vaif.config.json already exists"),console.log(d__default.default.yellow(`
2064
+ Use --force to overwrite existing configuration.`)),process.exit(1));try{if(j__default.default.writeFileSync(o,JSON.stringify(Xe,null,2),"utf-8"),e.succeed("Created vaif.config.json"),t.template){let n=t.features?t.features.split(",").map(i=>i.trim()):void 0;await ie(t.template,{force:t.force,features:n});}else {let n=b__default.default.resolve(".env.example");if(j__default.default.existsSync(n)||(j__default.default.writeFileSync(n,`# VAIF Configuration
65
2065
  DATABASE_URL=postgresql://user:password@localhost:5432/database
66
2066
  VAIF_API_KEY=your-api-key
67
- `,"utf-8"),console.log(l__default.default.gray("Created .env.example"))),o.typescript){let r=y__default.default.resolve("src/types");E__default.default.existsSync(r)||(E__default.default.mkdirSync(r,{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(`
68
- Error: ${n.message}`)),process.exit(1);}}var J=y__default.default.join(ze__default.default.homedir(),".vaif"),R=y__default.default.join(J,"auth.json"),Ke=process.env.VAIF_API_URL||"https://api.vaif.studio";function Me(){E__default.default.existsSync(J)||E__default.default.mkdirSync(J,{recursive:true});}function Je(o){Me(),E__default.default.writeFileSync(R,JSON.stringify(o,null,2),"utf-8"),E__default.default.chmodSync(R,384);}function j(){if(!E__default.default.existsSync(R))return null;try{let o=E__default.default.readFileSync(R,"utf-8");return JSON.parse(o)}catch{return null}}function Ye(o){let e=Be__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(o,n=>{e.close(),t(n);});})}async function ee(o){try{let e=await fetch(`${Ke}/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 oe(o){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 t=o.token;t||(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(""),t=await Ye(l__default.default.cyan("Enter your API token: ")),(!t||t.trim()==="")&&(console.log(l__default.default.red(`
69
- No token provided. Login cancelled.`)),process.exit(1))),e.start("Validating token...");let{valid:n,email:r}=await ee(t.trim());n||(e.fail("Invalid token"),console.log(l__default.default.red(`
70
- 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:t.trim(),email:r,projectId:o.projectId,expiresAt:new Date(Date.now()+720*60*60*1e3).toISOString()};Je(a),e.succeed("Logged in successfully"),console.log(""),r&&console.log(l__default.default.green(` Authenticated as: ${r}`)),console.log(l__default.default.gray(` Config saved to: ${R}`)),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 ne(){E__default.default.existsSync(R)?(E__default.default.unlinkSync(R),console.log(l__default.default.green("Logged out successfully"))):console.log(l__default.default.yellow("Not currently logged in"));}async function te(){let o=j();(!o||!o.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:t,email:n}=await ee(o.token);t||(e.fail("Session expired"),console.log(l__default.default.yellow(`
71
- Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Authenticated"),console.log(""),console.log(l__default.default.green(` Email: ${n||o.email||"Unknown"}`)),o.projectId&&console.log(l__default.default.green(` Project: ${o.projectId}`)),console.log("");}var He=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Qe(o,e,t="public"){let n=await fetch(`${He}/v1/projects/${e}/schema?schema=${t}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!n.ok){let r=await n.text();throw new Error(`Failed to fetch schema: ${r}`)}return n.json()}async function se(o){let e=L__default.default(),t=j();(!t||!t.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=o.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await b(n);}catch(i){e.fail("Failed to load config"),console.log(l__default.default.red(`
72
- Error: ${i}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(l__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let a=o.projectId||r.projectId||t.projectId;a||(e.fail("No project ID specified"),console.log(l__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 i=o.schema||r.database?.schema||"public",s=await Qe(t.token,a,i);e.succeed("Schema fetched successfully");let c=o.output||y__default.default.resolve("vaif.schema.json"),p={$schema:"https://vaif.studio/schemas/schema.json",projectId:a,schema:i,pulledAt:new Date().toISOString(),...s};E__default.default.writeFileSync(c,JSON.stringify(p,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: ${(s.tables||[]).length}`)),console.log(l__default.default.gray(` Enums: ${(s.enums||[]).length}`)),console.log(l__default.default.gray(` Functions: ${(s.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(`
74
- Error: ${i.message}`)),process.exit(1);}}var re=process.env.VAIF_API_URL||"https://api.vaif.studio";function oo(o){let e=Be__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(o,n=>{e.close(),t(n);});})}async function no(o,e,t){let n=await fetch(`${re}/v1/projects/${e}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!n.ok){let r=await n.text();throw new Error(`Failed to preview changes: ${r}`)}return n.json()}async function to(o,e,t){let n=await fetch(`${re}/v1/projects/${e}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!n.ok){let r=await n.text();throw new Error(`Failed to apply changes: ${r}`)}return n.json()}function so(o){if(console.log(""),console.log(l__default.default.bold("Schema Changes:")),console.log(""),o.added.length===0&&o.modified.length===0&&o.removed.length===0){console.log(l__default.default.gray(" No changes detected. Schema is up to date."));return}if(o.added.length>0){console.log(l__default.default.green.bold(" + Added:"));for(let e of o.added)console.log(l__default.default.green(` + ${e.type}: ${e.name}`));console.log("");}if(o.modified.length>0){console.log(l__default.default.yellow.bold(" ~ Modified:"));for(let e of o.modified){console.log(l__default.default.yellow(` ~ ${e.type}: ${e.name}`));for(let t of e.changes)console.log(l__default.default.gray(` ${t}`));}console.log("");}if(o.removed.length>0){console.log(l__default.default.red.bold(" - Removed:"));for(let e of o.removed)console.log(l__default.default.red(` - ${e.type}: ${e.name}`));console.log("");}}async function ae(o){let e=L__default.default(),t=j();(!t||!t.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=o.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await b(n);}catch(c){e.fail("Failed to load config"),console.log(l__default.default.red(`
75
- Error: ${c}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(l__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let a=o.projectId||r.projectId||t.projectId;a||(e.fail("No project ID specified"),console.log(l__default.default.yellow(`
76
- Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=o.schema||y__default.default.resolve("vaif.schema.json");E__default.default.existsSync(i)||(e.fail("No local schema found"),console.log(l__default.default.yellow(`
77
- Expected schema file at: ${i}`)),console.log(l__default.default.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let s;try{let c=E__default.default.readFileSync(i,"utf-8");s=JSON.parse(c);}catch(c){e.fail("Failed to parse schema file"),c instanceof Error&&console.log(l__default.default.red(`
78
- Error: ${c.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:c,sql:p}=await no(t.token,a,s);if(e.stop(),so(c),c.added.length===0&&c.modified.length===0&&c.removed.length===0){console.log("");return}if(p.length>0){console.log(l__default.default.bold("SQL Migrations:")),console.log("");for(let f of p)console.log(l__default.default.gray(` ${f}`));console.log("");}if(o.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(!o.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 g=await oo(l__default.default.cyan("Apply these changes? [y/N] "));if(g.toLowerCase()!=="y"&&g.toLowerCase()!=="yes"){console.log(l__default.default.yellow(`
79
- Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let d=await to(t.token,a,s);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(`
80
- Error: ${c.message}`)),process.exit(1);}}var fe=process.env.VAIF_API_URL||"https://api.vaif.studio";async function io(o,e,t){let n=await fetch(`${fe}/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 r=await n.text();throw new Error(`Failed to deploy function: ${r}`)}return n.json()}async function ro(o,e,t){let n=new URL(`${fe}/v1/projects/${e}/functions`);t&&n.searchParams.set("envId",t);let r=await fetch(n.toString(),{headers:{Authorization:`Bearer ${o}`}});if(!r.ok){let a=await r.text();throw new Error(`Failed to list functions: ${a}`)}return r.json()}function ce(o){switch(y__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 le(o){let e=[],t=[".ts",".js",".mjs",".py",".go",".rs"];function n(r){if(!E__default.default.existsSync(r))return;let a=E__default.default.readdirSync(r,{withFileTypes:true});for(let i of a){let s=y__default.default.join(r,i.name);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&n(s);else if(i.isFile()){let c=y__default.default.extname(i.name).toLowerCase();t.includes(c)&&(i.name==="index.ts"||i.name==="index.js"||i.name.includes("function")||i.name.includes("handler"))&&e.push(s);}}}return n(o),e}async function pe(o){let e=L__default.default(),t=j();(!t||!t.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=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=o.projectId||r?.projectId||t.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=y__default.default.resolve("functions"),s=y__default.default.resolve("src/functions"),c=[];if(o.entrypoint){let g=y__default.default.resolve(o.entrypoint);E__default.default.existsSync(g)||(e.fail(`File not found: ${o.entrypoint}`),process.exit(1)),c=[g];}else c=[...le(i),...le(s)];c.length===0&&(e.fail("No function files found"),console.log(l__default.default.yellow(`
81
- 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(`
82
- Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${c.length} function(s)`),o.name&&(c=c.filter(g=>y__default.default.basename(g,y__default.default.extname(g)).includes(o.name)),c.length===0&&(console.log(l__default.default.yellow(`
83
- No functions matching "${o.name}" found`)),process.exit(1))),console.log(""),console.log(l__default.default.gray("Functions to deploy:"));for(let g of c){let u=y__default.default.basename(y__default.default.dirname(g))||y__default.default.basename(g,y__default.default.extname(g)),I=o.runtime||ce(g);console.log(l__default.default.gray(` - ${u} (${I})`));}if(console.log(""),o.dryRun){console.log(l__default.default.yellow("Dry run mode - no functions deployed."));return}let p=[];for(let g of c){let u=y__default.default.basename(y__default.default.dirname(g))||y__default.default.basename(g,y__default.default.extname(g)),I=o.runtime||ce(g);e.start(`Deploying ${u}...`);try{let _=E__default.default.readFileSync(g,"utf-8"),T=await io(t.token,a,{name:u,runtime:I,entrypoint:y__default.default.basename(g),code:_,envId:o.envId});e.succeed(`Deployed ${u} (v${T.version})`),p.push({name:u,success:!0,version:T.version});}catch(_){let T=_ instanceof Error?_.message:"Unknown error";e.fail(`Failed to deploy ${u}`),p.push({name:u,success:false,error:T});}}console.log("");let d=p.filter(g=>g.success).length;if(p.filter(g=>!g.success).length===0)console.log(l__default.default.green(`\u2713 Successfully deployed ${d} function(s)`));else {console.log(l__default.default.yellow(`Deployed ${d}/${p.length} function(s)`)),console.log(""),console.log(l__default.default.red("Failed deployments:"));for(let g of p.filter(u=>!u.success))console.log(l__default.default.red(` - ${g.name}: ${g.error}`));}console.log("");}async function de(o){let e=L__default.default(),t=j();(!t||!t.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=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=o.projectId||r?.projectId||t.projectId;a||(console.log(l__default.default.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let i=await ro(t.token,a,o.envId);if(e.stop(),i.length===0){console.log(l__default.default.yellow(`
84
- 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 s of i){let c=s.status==="active"?l__default.default.green:s.status==="deploying"?l__default.default.yellow:l__default.default.red;console.log(" "+s.name.padEnd(25)+s.runtime.padEnd(15)+`v${s.version}`.padEnd(10)+c(s.status.padEnd(12))+(s.lastDeployed?new Date(s.lastDeployed).toLocaleDateString():"-"));}console.log("");}catch(i){e.fail("Failed to fetch functions"),i instanceof Error&&console.log(l__default.default.red(`
85
- Error: ${i.message}`)),process.exit(1);}}var V=process.env.VAIF_API_URL||"https://api.vaif.studio";async function ao(o,e,t,n,r){let a=await fetch(`${V}/v1/projects/${e}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({table:t,records:n,truncate:r?.truncate??false})});if(!a.ok){let i=await a.text();throw new Error(`Failed to seed ${t}: ${i}`)}return a.json()}async function co(o,e){let t=await fetch(`${V}/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 Y(o){let e=[];if(!E__default.default.existsSync(o))return e;let t=E__default.default.readdirSync(o,{withFileTypes:true});for(let n of t)if(n.isFile()){let r=y__default.default.extname(n.name).toLowerCase();(r===".json"||r===".ts"||r===".js")&&e.push(y__default.default.join(o,n.name));}return e.sort()}async function ue(o){let e=y__default.default.extname(o).toLowerCase();if(e===".json"){let t=E__default.default.readFileSync(o,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?[{table:y__default.default.basename(o,e),data:n}]:n.table&&n.data?[n]:Object.entries(n).map(([r,a])=>({table:r,data:a}))}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 me(o){let e=L__default.default(),t=j();(!t||!t.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=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=o.projectId||r?.projectId||t.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(o.file){let d=y__default.default.resolve(o.file);E__default.default.existsSync(d)||(console.log(l__default.default.red(`File not found: ${o.file}`)),process.exit(1)),i=[d];}else {let d=y__default.default.resolve("seeds"),f=y__default.default.resolve("prisma/seed"),g=y__default.default.resolve("db/seeds");i=[...Y(d),...Y(f),...Y(g)];}i.length===0&&(console.log(l__default.default.yellow("No seed files found")),console.log(l__default.default.gray(`
86
- 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(`
87
- Or specify a file with --file`)),console.log(l__default.default.gray(`
88
- 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(` - ${y__default.default.relative(process.cwd(),d)}`));if(console.log(""),o.truncate&&(console.log(l__default.default.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),o.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 ${y__default.default.basename(d)}...`);try{let f=await ue(d);e.stop();for(let g of f)o.table&&g.table!==o.table||(console.log(l__default.default.cyan(`Table: ${g.table}`)),console.log(l__default.default.gray(` Records: ${g.data.length}`)),g.data.length>0&&console.log(l__default.default.gray(` Sample: ${JSON.stringify(g.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(f){e.fail(`Failed to load ${y__default.default.basename(d)}`),f instanceof Error&&console.log(l__default.default.red(` Error: ${f.message}`));}}return}let s=[];for(let d of i){e.start(`Processing ${y__default.default.basename(d)}...`);try{let f=await ue(d);e.stop();for(let g of f)if(!(o.table&&g.table!==o.table)){if(g.data.length===0){console.log(l__default.default.gray(` Skipping ${g.table} (no records)`));continue}e.start(`Seeding ${g.table} (${g.data.length} records)...`);try{let u=await ao(t.token,a,g.table,g.data,{truncate:o.truncate});e.succeed(`Seeded ${g.table}: ${u.inserted} records`),s.push({table:g.table,inserted:u.inserted});}catch(u){let I=u instanceof Error?u.message:"Unknown error";e.fail(`Failed to seed ${g.table}`),s.push({table:g.table,inserted:0,error:I});}}}catch(f){e.fail(`Failed to load ${y__default.default.basename(d)}`),f instanceof Error&&console.log(l__default.default.red(` Error: ${f.message}`));}}console.log("");let c=s.reduce((d,f)=>d+f.inserted,0),p=s.filter(d=>d.error).length;if(p===0)console.log(l__default.default.green(`\u2713 Successfully seeded ${c} records across ${s.length} table(s)`));else {console.log(l__default.default.yellow(`Seeded ${c} records with ${p} error(s)`)),console.log(""),console.log(l__default.default.red("Errors:"));for(let d of s.filter(f=>f.error))console.log(l__default.default.red(` - ${d.table}: ${d.error}`));}console.log("");}async function he(o){let e=L__default.default(),t=j();(!t||!t.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=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=o.projectId||r?.projectId||t.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=y__default.default.resolve(o.dir||"./drizzle");if(console.log(""),console.log(l__default.default.bold("VAIF Database Push")),console.log(""),!E__default.default.existsSync(i)){let f=y__default.default.resolve("./migrations");E__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(`
89
- Expected one of:`)),console.log(l__default.default.gray(" - ./drizzle/")),console.log(l__default.default.gray(" - ./migrations/")),console.log(l__default.default.gray(`
90
- Or specify with: vaif db push --dir <path>`)),process.exit(1));}let s=[],c=E__default.default.readdirSync(i,{withFileTypes:true});for(let f of c)if(f.isFile()&&f.name.endsWith(".sql"))s.push(y__default.default.join(i,f.name));else if(f.isDirectory()){let g=E__default.default.readdirSync(y__default.default.join(i,f.name),{withFileTypes:true});for(let u of g)u.isFile()&&u.name.endsWith(".sql")&&s.push(y__default.default.join(i,f.name,u.name));}s.sort(),s.length===0&&(console.log(l__default.default.yellow("No SQL migration files found")),process.exit(1)),console.log(l__default.default.gray(`Found ${s.length} migration(s):`));for(let f of s)console.log(l__default.default.gray(` - ${y__default.default.relative(process.cwd(),f)}`));if(console.log(""),o.dryRun){console.log(l__default.default.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let f of s){let g=E__default.default.readFileSync(f,"utf-8");console.log(l__default.default.cyan(`--- ${y__default.default.basename(f)} ---`)),console.log(l__default.default.gray(g.slice(0,500))),g.length>500&&console.log(l__default.default.gray("...")),console.log("");}return}let p=0,d=0;for(let f of s){let g=E__default.default.readFileSync(f,"utf-8"),u=y__default.default.relative(process.cwd(),f);e.start(`Applying ${u}...`);try{let I=await fetch(`${V}/v1/projects/${a}/schema/execute`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:g})});if(!I.ok){let _=await I.text();throw new Error(_)}e.succeed(`Applied ${u}`),p++;}catch(I){let _=I instanceof Error?I.message:"Unknown error";e.fail(`Failed ${u}: ${_}`),d++;}}console.log(""),console.log(d===0?l__default.default.green(`Successfully applied ${p} migration(s)`):l__default.default.yellow(`Applied ${p}, failed ${d} migration(s)`)),console.log("");}async function ye(o){let e=L__default.default(),t=j();(!t||!t.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=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=o.projectId||r?.projectId||t.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=y__default.default.resolve(o.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 s=await fetch(`${V}/v1/projects/${a}/schema`,{headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok){let d=await s.text();throw new Error(`Failed to pull schema: ${d}`)}let c=await s.json();E__default.default.writeFileSync(i,JSON.stringify(c,null,2),"utf-8"),e.succeed(`Schema written to ${y__default.default.relative(process.cwd(),i)}`);let p=c.tables?.length??Object.keys(c).length;console.log(l__default.default.gray(` ${p} table(s) pulled`)),console.log("");}catch(s){e.fail("Failed to pull schema"),s instanceof Error&&console.log(l__default.default.red(`
91
- Error: ${s.message}`)),process.exit(1);}}async function we(o){let e=L__default.default(),t=j();(!t||!t.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=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=o.projectId||r?.projectId||t.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(""),o.force||(console.log(l__default.default.yellow("Use --force to confirm this action.")),process.exit(1)),e.start("Resetting database...");try{await co(t.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(`
92
- Error: ${i.message}`)),process.exit(1);}}var je=process.env.VAIF_API_URL||"https://api.vaif.studio";function ve(o,e,t){return o.projectId||e?.projectId||t.projectId||null}async function Ie(o){let e=L__default.default(),t=j();(!t||!t.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=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=ve(o,r,t);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=o.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 s=await fetch(`${je}/v1/projects/${a}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i})});if(!s.ok){let p=await s.text();throw new Error(`Failed to generate key: ${p}`)}let c=await s.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(s){e.fail("Failed to generate API key"),s instanceof Error&&console.log(l__default.default.red(`
93
- Error: ${s.message}`)),process.exit(1);}}async function $e(o){let e=L__default.default(),t=j();(!t||!t.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=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=ve(o,r,t);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 ${t.token}`}});if(!i.ok){let f=await i.text();throw new Error(`Failed to list keys: ${f}`)}let s=await i.json(),c=s.keys||s;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(`
94
- Generate one with: vaif keys generate`));return}let p=Math.max(8,...c.map(f=>(f.name||"").length)),d=` ${"Name".padEnd(p)} ${"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 g=(f.name||"unnamed").padEnd(p),u=f.maskedKey||f.prefix||`${(f.key||"").slice(0,12)}...`,I=f.createdAt?new Date(f.createdAt).toLocaleDateString():"N/A";console.log(` ${g} ${u.padEnd(24)} ${I}`);}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(`
95
- Error: ${i.message}`)),process.exit(1);}}var Se=process.env.VAIF_API_URL||"https://api.vaif.studio";function go(o){try{let e=new URL(o);return e.password&&(e.password="****"),e.toString()}catch{return o.replace(/:[^@/]+@/,":****@")}}async function Ae(o){let e=L__default.default(),t=j();(!t||!t.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=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=o.projectId||r?.projectId||t.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(`${Se}/v1/projects/${a}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let d=await i.text();throw new Error(`Failed to fetch project: ${d}`)}let s=await i.json();e.stop(),console.log(""),console.log(l__default.default.bold("VAIF Project Info")),console.log("");let c=16,p=(d,f)=>{console.log(` ${l__default.default.gray(d.padEnd(c))} ${f}`);};p("Name:",l__default.default.white(s.name||"N/A")),p("Project ID:",l__default.default.white(a)),p("Region:",l__default.default.white(s.region||"us-east-1")),p("Plan:",l__default.default.white(s.plan||s.tier||"free")),p("Created:",l__default.default.white(s.createdAt?new Date(s.createdAt).toLocaleDateString():"N/A")),console.log(""),p("API URL:",l__default.default.cyan(s.apiUrl||`${Se}/v1`)),p("WS URL:",l__default.default.cyan(s.wsUrl||s.realtimeUrl||"N/A")),p("DB URL:",l__default.default.cyan(s.databaseUrl?go(s.databaseUrl):"N/A")),p("Storage URL:",l__default.default.cyan(s.storageUrl||"N/A")),console.log("");}catch(i){e.fail("Failed to fetch project info"),i instanceof Error&&console.log(l__default.default.red(`
96
- Error: ${i.message}`)),process.exit(1);}}var po=process.env.VAIF_API_URL||"https://api.vaif.studio";async function xe(o){let e=L__default.default(),t=j();(!t||!t.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=o.config||"vaif.config.json",r=null;try{r=await b(n);}catch{}let a=o.projectId||r?.projectId||t.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(`${po}/v1/projects/${a}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let I=await i.text();throw new Error(`Failed to fetch project status: ${I}`)}let s=await i.json();e.stop(),console.log(""),console.log(l__default.default.bold("VAIF Project Status")),console.log("");let c=22,p=(I,_)=>{console.log(` ${l__default.default.gray(I.padEnd(c))} ${_}`);};p("Project:",l__default.default.white(s.name||a)),p("Plan:",l__default.default.white(s.plan||s.tier||"free")),console.log(""),console.log(l__default.default.gray(" --- Resources ---")),console.log("");let d=s.tableCount??s.tables?.length??"N/A",f=s.functionCount??s.functions?.length??"N/A",g=s.bucketCount??s.storage?.buckets?.length??"N/A",u=s.activeConnections??s.connections??"N/A";p("Tables:",l__default.default.white(String(d))),p("Functions:",l__default.default.white(String(f))),p("Storage Buckets:",l__default.default.white(String(g))),p("Active Connections:",l__default.default.white(String(u))),s.usage&&(console.log(""),console.log(l__default.default.gray(" --- Usage ---")),console.log(""),s.usage.dbSize&&p("Database Size:",l__default.default.white(s.usage.dbSize)),s.usage.storageSize&&p("Storage Size:",l__default.default.white(s.usage.storageSize)),s.usage.bandwidth&&p("Bandwidth:",l__default.default.white(s.usage.bandwidth)),s.usage.functionInvocations!=null&&p("Function Invocations:",l__default.default.white(String(s.usage.functionInvocations)))),console.log("");}catch(i){e.fail("Failed to fetch project status"),i instanceof Error&&console.log(l__default.default.red(`
97
- Error: ${i.message}`)),process.exit(1);}}commander.program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.1.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(oe);commander.program.command("logout").description("Log out and remove stored credentials").action(ne);commander.program.command("whoami").description("Show current authenticated user").action(te);commander.program.command("init").description("Initialize VAIF configuration in your project").option("--typescript","Setup for TypeScript project").option("-f, --force","Overwrite existing config").action(Q);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(Ae);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(xe);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(se);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(ae);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(H);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(pe);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(de);var U=commander.program.command("db").description("Database management commands");U.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(he);U.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(ye);U.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(me);U.command("reset").description("Reset database (drop all tables and data)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --force","Confirm reset (required)").action(we);var Fe=commander.program.command("keys").description("Manage API keys");Fe.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(Ie);Fe.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($e);commander.program.parse(process.argv);process.argv.slice(2).length||commander.program.outputHelp();
2067
+ `,"utf-8"),console.log(d__default.default.gray("Created .env.example"))),t.typescript){let i=b__default.default.resolve("src/types");j__default.default.existsSync(i)||(j__default.default.mkdirSync(i,{recursive:!0}),console.log(d__default.default.gray("Created src/types directory")));}console.log(""),console.log(d__default.default.green("VAIF initialized successfully!")),console.log(""),console.log(d__default.default.gray("Next steps:")),console.log(d__default.default.gray(" 1. Update vaif.config.json with your project ID")),console.log(d__default.default.gray(" 2. Set DATABASE_URL in your environment")),console.log(d__default.default.gray(" 3. Run: npx vaif generate")),console.log("");}}catch(n){e.fail("Failed to initialize"),n instanceof Error&&console.error(d__default.default.red(`
2068
+ Error: ${n.message}`)),process.exit(1);}}var G=b__default.default.join(Ze__default.default.homedir(),".vaif"),D=b__default.default.join(G,"auth.json"),O=process.env.VAIF_API_URL||"https://api.vaif.studio";function et(){j__default.default.existsSync(G)||j__default.default.mkdirSync(G,{recursive:true});}function de(t){et(),j__default.default.writeFileSync(D,JSON.stringify(t,null,2),"utf-8"),j__default.default.chmodSync(D,384);}function w(){if(!j__default.default.existsSync(D))return null;try{let t=j__default.default.readFileSync(D,"utf-8");return JSON.parse(t)}catch{return null}}function tt(t){let e=ne__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}function ot(t){return new Promise(e=>{let o=ne__default.default.createInterface({input:process.stdin,output:process.stdout});process.stdin;let i=process.stdout.write.bind(process.stdout),l=false;process.stdout.write=((...a)=>l?true:i(...a)),o.question(t,a=>{l=false,process.stdout.write=i,console.log(""),o.close(),e(a);}),l=true;})}function nt(t){let e=process.platform,o;e==="darwin"?o=`open "${t}"`:e==="win32"?o=`start "" "${t}"`:o=`xdg-open "${t}"`,child_process.exec(o,n=>{});}function rt(t){return new Promise(e=>setTimeout(e,t))}async function at(t){try{let e=await fetch(`${O}/auth/me`,{headers:{Authorization:`Bearer ${t}`}});if(e.ok){let o=await e.json();return {valid:!0,email:o.user?.email||o.email}}return {valid:!1}}catch{return {valid:false}}}async function it(t){let e=K__default.default();e.start("Setting up authentication...");let o,n;try{let r=await fetch(`${O}/auth/cli/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});r.ok||(e.fail("Failed to initiate authentication"),console.log(d__default.default.red(`
2069
+ Could not connect to VAIF API. Please try again later.`)),process.exit(1));let s=await r.json();o=s.code,n=s.url;}catch{e.fail("Failed to connect to VAIF API"),console.log(d__default.default.red(`
2070
+ Could not connect to VAIF API.`)),console.log(d__default.default.gray("Check your internet connection or try: vaif login --email")),process.exit(1);}e.stop(),console.log(d__default.default.cyan(" Opening browser for authentication...")),console.log(""),console.log(d__default.default.gray(" If the browser doesn't open, visit this URL:")),console.log(d__default.default.white(` ${n}`)),console.log(""),nt(n),e.start("Waiting for browser authentication...");let i=12e4,l=2e3,a=Date.now();for(;Date.now()-a<i;){await rt(l);try{let r=await fetch(`${O}/auth/cli/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:o})});if(!r.ok){let c=await r.json();(c.error==="ExpiredCode"||c.error==="InvalidCode")&&(e.fail("Authentication expired"),console.log(d__default.default.red(`
2071
+ The authentication session expired. Please try again.`)),process.exit(1));continue}let s=await r.json();if(s.ok&&s.accessToken){let c={token:s.accessToken,email:s.user?.email,projectId:t,expiresAt:new Date(Date.now()+s.expiresIn*1e3).toISOString()};de(c),e.succeed("Logged in successfully"),console.log(""),s.user?.email&&console.log(d__default.default.green(` Authenticated as: ${s.user.email}`)),console.log(d__default.default.gray(` Config saved to: ${D}`)),console.log("");return}}catch{}}e.fail("Authentication timed out"),console.log(d__default.default.red(`
2072
+ Timed out waiting for browser authentication.`)),console.log(d__default.default.gray("Try again or use: vaif login --email")),process.exit(1);}async function st(t){console.log(""),console.log(d__default.default.bold("VAIF CLI Login")),console.log(d__default.default.gray("Enter your VAIF account credentials")),console.log("");let e=await tt(d__default.default.cyan(" Email: "));(!e||e.trim()==="")&&(console.log(d__default.default.red(`
2073
+ No email provided. Login cancelled.`)),process.exit(1));let o=await ot(d__default.default.cyan(" Password: "));(!o||o.trim()==="")&&(console.log(d__default.default.red(`
2074
+ No password provided. Login cancelled.`)),process.exit(1));let n=K__default.default("Authenticating...").start();try{let i=await fetch(`${O}/auth/cli/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e.trim(),password:o})}),l=await i.json();(!i.ok||!l.ok)&&(n.fail("Login failed"),console.log(d__default.default.red(`
2075
+ ${l.message||"Invalid email or password."}`)),process.exit(1));let a={token:l.accessToken,email:l.user?.email,projectId:t,expiresAt:new Date(Date.now()+l.expiresIn*1e3).toISOString()};de(a),n.succeed("Logged in successfully"),console.log(""),l.user?.email&&console.log(d__default.default.green(` Authenticated as: ${l.user.email}`)),console.log(d__default.default.gray(` Config saved to: ${D}`)),console.log("");}catch{n.fail("Failed to connect to VAIF API"),console.log(d__default.default.red(`
2076
+ Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function pe(t){console.log(""),console.log(d__default.default.bold("Welcome to VAIF CLI")),console.log(d__default.default.gray("Authenticate to access your VAIF projects")),console.log(""),t.email?await st(t.projectId):await it(t.projectId),console.log(d__default.default.gray("You can now use VAIF CLI commands like:")),console.log(d__default.default.gray(" vaif pull - Pull remote schema")),console.log(d__default.default.gray(" vaif push - Push schema changes")),console.log(d__default.default.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function ue(){j__default.default.existsSync(D)?(j__default.default.unlinkSync(D),console.log(d__default.default.green("Logged out successfully"))):console.log(d__default.default.yellow("Not currently logged in"));}async function fe(){let t=w();(!t||!t.token)&&(console.log(d__default.default.yellow("Not logged in")),console.log(d__default.default.gray("Run `vaif login` to authenticate")),process.exit(1));let e=K__default.default("Checking authentication...").start(),{valid:o,email:n}=await at(t.token);o||(e.fail("Session expired"),console.log(d__default.default.yellow(`
2077
+ Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Authenticated"),console.log(""),console.log(d__default.default.green(` Email: ${n||t.email||"Unknown"}`)),t.projectId&&console.log(d__default.default.green(` Project: ${t.projectId}`)),console.log("");}var pt=process.env.VAIF_API_URL||"https://api.vaif.studio";async function ut(t,e,o="public"){let n=await fetch(`${pt}/v1/projects/${e}/schema?schema=${o}`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!n.ok){let i=await n.text();throw new Error(`Failed to fetch schema: ${i}`)}return n.json()}async function ge(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(d__default.default.red("Not logged in")),console.log(d__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",i=null;e.start("Loading configuration...");try{i=await I(n);}catch(a){e.fail("Failed to load config"),console.log(d__default.default.red(`
2078
+ Error: ${a}`)),process.exit(1);}i||(e.fail("No configuration found"),console.log(d__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let l=t.projectId||i.projectId||o.projectId;l||(e.fail("No project ID specified"),console.log(d__default.default.yellow(`
2079
+ Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let a=t.schema||i.database?.schema||"public",r=await ut(o.token,l,a);e.succeed("Schema fetched successfully");let s=t.output||b__default.default.resolve("vaif.schema.json"),c={$schema:"https://vaif.studio/schemas/schema.json",projectId:l,schema:a,pulledAt:new Date().toISOString(),...r};j__default.default.writeFileSync(s,JSON.stringify(c,null,2),"utf-8"),console.log(""),console.log(d__default.default.green(`Schema saved to: ${s}`)),console.log(""),console.log(d__default.default.gray("Schema summary:")),console.log(d__default.default.gray(` Tables: ${(r.tables||[]).length}`)),console.log(d__default.default.gray(` Enums: ${(r.enums||[]).length}`)),console.log(d__default.default.gray(` Functions: ${(r.functions||[]).length}`)),console.log(""),console.log(d__default.default.gray("Next steps:")),console.log(d__default.default.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(d__default.default.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(a){e.fail("Failed to fetch schema"),a instanceof Error&&console.log(d__default.default.red(`
2080
+ Error: ${a.message}`)),process.exit(1);}}var he=process.env.VAIF_API_URL||"https://api.vaif.studio";function ht(t){let e=ne__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}async function yt(t,e,o){let n=await fetch(`${he}/v1/projects/${e}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!n.ok){let i=await n.text();throw new Error(`Failed to preview changes: ${i}`)}return n.json()}async function vt(t,e,o){let n=await fetch(`${he}/v1/projects/${e}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!n.ok){let i=await n.text();throw new Error(`Failed to apply changes: ${i}`)}return n.json()}function bt(t){if(console.log(""),console.log(d__default.default.bold("Schema Changes:")),console.log(""),t.added.length===0&&t.modified.length===0&&t.removed.length===0){console.log(d__default.default.gray(" No changes detected. Schema is up to date."));return}if(t.added.length>0){console.log(d__default.default.green.bold(" + Added:"));for(let e of t.added)console.log(d__default.default.green(` + ${e.type}: ${e.name}`));console.log("");}if(t.modified.length>0){console.log(d__default.default.yellow.bold(" ~ Modified:"));for(let e of t.modified){console.log(d__default.default.yellow(` ~ ${e.type}: ${e.name}`));for(let o of e.changes)console.log(d__default.default.gray(` ${o}`));}console.log("");}if(t.removed.length>0){console.log(d__default.default.red.bold(" - Removed:"));for(let e of t.removed)console.log(d__default.default.red(` - ${e.type}: ${e.name}`));console.log("");}}async function ye(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(d__default.default.red("Not logged in")),console.log(d__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",i=null;e.start("Loading configuration...");try{i=await I(n);}catch(s){e.fail("Failed to load config"),console.log(d__default.default.red(`
2081
+ Error: ${s}`)),process.exit(1);}i||(e.fail("No configuration found"),console.log(d__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let l=t.projectId||i.projectId||o.projectId;l||(e.fail("No project ID specified"),console.log(d__default.default.yellow(`
2082
+ Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let a=t.schema||b__default.default.resolve("vaif.schema.json");j__default.default.existsSync(a)||(e.fail("No local schema found"),console.log(d__default.default.yellow(`
2083
+ Expected schema file at: ${a}`)),console.log(d__default.default.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let r;try{let s=j__default.default.readFileSync(a,"utf-8");r=JSON.parse(s);}catch(s){e.fail("Failed to parse schema file"),s instanceof Error&&console.log(d__default.default.red(`
2084
+ Error: ${s.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:s,sql:c}=await yt(o.token,l,r);if(e.stop(),bt(s),s.added.length===0&&s.modified.length===0&&s.removed.length===0){console.log("");return}if(c.length>0){console.log(d__default.default.bold("SQL Migrations:")),console.log("");for(let u of c)console.log(d__default.default.gray(` ${u}`));console.log("");}if(t.dryRun){console.log(d__default.default.yellow("Dry run mode - no changes applied.")),console.log(d__default.default.gray("Remove --dry-run to apply these changes."));return}if(!t.force){s.removed.length>0&&(console.log(d__default.default.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(d__default.default.red(" This action cannot be undone!")),console.log(""));let p=await ht(d__default.default.cyan("Apply these changes? [y/N] "));if(p.toLowerCase()!=="y"&&p.toLowerCase()!=="yes"){console.log(d__default.default.yellow(`
2085
+ Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let f=await vt(o.token,l,r);if(f.success){if(e.succeed("Schema changes applied successfully"),console.log(""),f.migrations.length>0){console.log(d__default.default.gray("Migrations applied:"));for(let u of f.migrations)console.log(d__default.default.gray(` - ${u}`));console.log("");}console.log(d__default.default.green("Your database schema is now up to date.")),console.log(d__default.default.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else e.fail("Failed to apply some changes");}catch(s){e.fail("Failed to push schema changes"),s instanceof Error&&console.log(d__default.default.red(`
2086
+ Error: ${s.message}`)),process.exit(1);}}var we=process.env.VAIF_API_URL||"https://api.vaif.studio";async function It(t,e,o){let n=await fetch(`${we}/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 i=await n.text();throw new Error(`Failed to deploy function: ${i}`)}return n.json()}async function wt(t,e,o){let n=new URL(`${we}/v1/projects/${e}/functions`);o&&n.searchParams.set("envId",o);let i=await fetch(n.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!i.ok){let l=await i.text();throw new Error(`Failed to list functions: ${l}`)}return i.json()}function ve(t){switch(b__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 be(t){let e=[],o=[".ts",".js",".mjs",".py",".go",".rs"];function n(i){if(!j__default.default.existsSync(i))return;let l=j__default.default.readdirSync(i,{withFileTypes:true});for(let a of l){let r=b__default.default.join(i,a.name);if(a.isDirectory())a.name!=="node_modules"&&!a.name.startsWith(".")&&n(r);else if(a.isFile()){let s=b__default.default.extname(a.name).toLowerCase();o.includes(s)&&(a.name==="index.ts"||a.name==="index.js"||a.name.includes("function")||a.name.includes("handler"))&&e.push(r);}}}return n(t),e}async function _e(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(d__default.default.red("Not logged in")),console.log(d__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",i=null;try{i=await I(n);}catch{}let l=t.projectId||i?.projectId||o.projectId;l||(console.log(d__default.default.red("No project ID specified")),console.log(d__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(d__default.default.bold("VAIF Functions Deploy")),console.log(""),e.start("Scanning for function files...");let a=b__default.default.resolve("functions"),r=b__default.default.resolve("src/functions"),s=[];if(t.entrypoint){let p=b__default.default.resolve(t.entrypoint);j__default.default.existsSync(p)||(e.fail(`File not found: ${t.entrypoint}`),process.exit(1)),s=[p];}else s=[...be(a),...be(r)];s.length===0&&(e.fail("No function files found"),console.log(d__default.default.yellow(`
2087
+ Place your functions in:`)),console.log(d__default.default.gray(" - ./functions/")),console.log(d__default.default.gray(" - ./src/functions/")),console.log(d__default.default.gray(`
2088
+ Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${s.length} function(s)`),t.name&&(s=s.filter(p=>b__default.default.basename(p,b__default.default.extname(p)).includes(t.name)),s.length===0&&(console.log(d__default.default.yellow(`
2089
+ No functions matching "${t.name}" found`)),process.exit(1))),console.log(""),console.log(d__default.default.gray("Functions to deploy:"));for(let p of s){let h=b__default.default.basename(b__default.default.dirname(p))||b__default.default.basename(p,b__default.default.extname(p)),x=t.runtime||ve(p);console.log(d__default.default.gray(` - ${h} (${x})`));}if(console.log(""),t.dryRun){console.log(d__default.default.yellow("Dry run mode - no functions deployed."));return}let c=[];for(let p of s){let h=b__default.default.basename(b__default.default.dirname(p))||b__default.default.basename(p,b__default.default.extname(p)),x=t.runtime||ve(p);e.start(`Deploying ${h}...`);try{let R=j__default.default.readFileSync(p,"utf-8"),N=await It(o.token,l,{name:h,runtime:x,entrypoint:b__default.default.basename(p),code:R,envId:t.envId});e.succeed(`Deployed ${h} (v${N.version})`),c.push({name:h,success:!0,version:N.version});}catch(R){let N=R instanceof Error?R.message:"Unknown error";e.fail(`Failed to deploy ${h}`),c.push({name:h,success:false,error:N});}}console.log("");let f=c.filter(p=>p.success).length;if(c.filter(p=>!p.success).length===0)console.log(d__default.default.green(`\u2713 Successfully deployed ${f} function(s)`));else {console.log(d__default.default.yellow(`Deployed ${f}/${c.length} function(s)`)),console.log(""),console.log(d__default.default.red("Failed deployments:"));for(let p of c.filter(h=>!h.success))console.log(d__default.default.red(` - ${p.name}: ${p.error}`));}console.log("");}async function xe(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(d__default.default.red("Not logged in")),console.log(d__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",i=null;try{i=await I(n);}catch{}let l=t.projectId||i?.projectId||o.projectId;l||(console.log(d__default.default.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let a=await wt(o.token,l,t.envId);if(e.stop(),a.length===0){console.log(d__default.default.yellow(`
2090
+ No functions found`)),console.log(d__default.default.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(d__default.default.bold(`Functions (${a.length}):`)),console.log(""),console.log(d__default.default.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"VERSION".padEnd(10)+"STATUS".padEnd(12)+"LAST DEPLOYED")),console.log(d__default.default.gray(" "+"-".repeat(80)));for(let r of a){let s=r.status==="active"?d__default.default.green:r.status==="deploying"?d__default.default.yellow:d__default.default.red;console.log(" "+r.name.padEnd(25)+r.runtime.padEnd(15)+`v${r.version}`.padEnd(10)+s(r.status.padEnd(12))+(r.lastDeployed?new Date(r.lastDeployed).toLocaleDateString():"-"));}console.log("");}catch(a){e.fail("Failed to fetch functions"),a instanceof Error&&console.log(d__default.default.red(`
2091
+ Error: ${a.message}`)),process.exit(1);}}var B=process.env.VAIF_API_URL||"https://api.vaif.studio";async function _t(t,e,o,n,i){let l=await fetch(`${B}/v1/projects/${e}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({table:o,records:n,truncate:i?.truncate??false})});if(!l.ok){let a=await l.text();throw new Error(`Failed to seed ${o}: ${a}`)}return l.json()}async function xt(t,e){let o=await fetch(`${B}/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 X(t){let e=[];if(!j__default.default.existsSync(t))return e;let o=j__default.default.readdirSync(t,{withFileTypes:true});for(let n of o)if(n.isFile()){let i=b__default.default.extname(n.name).toLowerCase();(i===".json"||i===".ts"||i===".js")&&e.push(b__default.default.join(t,n.name));}return e.sort()}async function Se(t){let e=b__default.default.extname(t).toLowerCase();if(e===".json"){let o=j__default.default.readFileSync(t,"utf-8"),n=JSON.parse(o);return Array.isArray(n)?[{table:b__default.default.basename(t,e),data:n}]:n.table&&n.data?[n]:Object.entries(n).map(([i,l])=>({table:i,data:l}))}else if(e===".ts"||e===".js"){let o=await import(t),n=o.default||o;return typeof n=="function"?n():n}throw new Error(`Unsupported file format: ${e}`)}async function Ae(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(d__default.default.red("Not logged in")),console.log(d__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",i=null;try{i=await I(n);}catch{}let l=t.projectId||i?.projectId||o.projectId;l||(console.log(d__default.default.red("No project ID specified")),console.log(d__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(d__default.default.bold("VAIF Database Seed")),console.log("");let a=[];if(t.file){let f=b__default.default.resolve(t.file);j__default.default.existsSync(f)||(console.log(d__default.default.red(`File not found: ${t.file}`)),process.exit(1)),a=[f];}else {let f=b__default.default.resolve("seeds"),u=b__default.default.resolve("prisma/seed"),p=b__default.default.resolve("db/seeds");a=[...X(f),...X(u),...X(p)];}a.length===0&&(console.log(d__default.default.yellow("No seed files found")),console.log(d__default.default.gray(`
2092
+ Place your seed files in one of these directories:`)),console.log(d__default.default.gray(" - ./seeds/")),console.log(d__default.default.gray(" - ./prisma/seed/")),console.log(d__default.default.gray(" - ./db/seeds/")),console.log(d__default.default.gray(`
2093
+ Or specify a file with --file`)),console.log(d__default.default.gray(`
2094
+ Example seed file (seeds/users.json):`)),console.log(d__default.default.gray(" [")),console.log(d__default.default.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(d__default.default.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(d__default.default.gray(" ]")),process.exit(1)),console.log(d__default.default.gray("Seed files found:"));for(let f of a)console.log(d__default.default.gray(` - ${b__default.default.relative(process.cwd(),f)}`));if(console.log(""),t.truncate&&(console.log(d__default.default.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),t.dryRun){console.log(d__default.default.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let f of a){e.start(`Loading ${b__default.default.basename(f)}...`);try{let u=await Se(f);e.stop();for(let p of u)t.table&&p.table!==t.table||(console.log(d__default.default.cyan(`Table: ${p.table}`)),console.log(d__default.default.gray(` Records: ${p.data.length}`)),p.data.length>0&&console.log(d__default.default.gray(` Sample: ${JSON.stringify(p.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(u){e.fail(`Failed to load ${b__default.default.basename(f)}`),u instanceof Error&&console.log(d__default.default.red(` Error: ${u.message}`));}}return}let r=[];for(let f of a){e.start(`Processing ${b__default.default.basename(f)}...`);try{let u=await Se(f);e.stop();for(let p of u)if(!(t.table&&p.table!==t.table)){if(p.data.length===0){console.log(d__default.default.gray(` Skipping ${p.table} (no records)`));continue}e.start(`Seeding ${p.table} (${p.data.length} records)...`);try{let h=await _t(o.token,l,p.table,p.data,{truncate:t.truncate});e.succeed(`Seeded ${p.table}: ${h.inserted} records`),r.push({table:p.table,inserted:h.inserted});}catch(h){let x=h instanceof Error?h.message:"Unknown error";e.fail(`Failed to seed ${p.table}`),r.push({table:p.table,inserted:0,error:x});}}}catch(u){e.fail(`Failed to load ${b__default.default.basename(f)}`),u instanceof Error&&console.log(d__default.default.red(` Error: ${u.message}`));}}console.log("");let s=r.reduce((f,u)=>f+u.inserted,0),c=r.filter(f=>f.error).length;if(c===0)console.log(d__default.default.green(`\u2713 Successfully seeded ${s} records across ${r.length} table(s)`));else {console.log(d__default.default.yellow(`Seeded ${s} records with ${c} error(s)`)),console.log(""),console.log(d__default.default.red("Errors:"));for(let f of r.filter(u=>u.error))console.log(d__default.default.red(` - ${f.table}: ${f.error}`));}console.log("");}async function Ee(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(d__default.default.red("Not logged in")),console.log(d__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",i=null;try{i=await I(n);}catch{}let l=t.projectId||i?.projectId||o.projectId;l||(console.log(d__default.default.red("No project ID specified")),console.log(d__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let a=b__default.default.resolve(t.dir||"./drizzle");if(console.log(""),console.log(d__default.default.bold("VAIF Database Push")),console.log(""),!j__default.default.existsSync(a)){let u=b__default.default.resolve("./migrations");j__default.default.existsSync(u)?console.log(d__default.default.gray(`Using migrations from: ${u}`)):(console.log(d__default.default.red(`Migrations directory not found: ${a}`)),console.log(d__default.default.gray(`
2095
+ Expected one of:`)),console.log(d__default.default.gray(" - ./drizzle/")),console.log(d__default.default.gray(" - ./migrations/")),console.log(d__default.default.gray(`
2096
+ Or specify with: vaif db push --dir <path>`)),process.exit(1));}let r=[],s=j__default.default.readdirSync(a,{withFileTypes:true});for(let u of s)if(u.isFile()&&u.name.endsWith(".sql"))r.push(b__default.default.join(a,u.name));else if(u.isDirectory()){let p=j__default.default.readdirSync(b__default.default.join(a,u.name),{withFileTypes:true});for(let h of p)h.isFile()&&h.name.endsWith(".sql")&&r.push(b__default.default.join(a,u.name,h.name));}r.sort(),r.length===0&&(console.log(d__default.default.yellow("No SQL migration files found")),process.exit(1)),console.log(d__default.default.gray(`Found ${r.length} migration(s):`));for(let u of r)console.log(d__default.default.gray(` - ${b__default.default.relative(process.cwd(),u)}`));if(console.log(""),t.dryRun){console.log(d__default.default.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let u of r){let p=j__default.default.readFileSync(u,"utf-8");console.log(d__default.default.cyan(`--- ${b__default.default.basename(u)} ---`)),console.log(d__default.default.gray(p.slice(0,500))),p.length>500&&console.log(d__default.default.gray("...")),console.log("");}return}let c=0,f=0;for(let u of r){let p=j__default.default.readFileSync(u,"utf-8"),h=b__default.default.relative(process.cwd(),u);e.start(`Applying ${h}...`);try{let x=await fetch(`${B}/v1/projects/${l}/schema/execute`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:p})});if(!x.ok){let R=await x.text();throw new Error(R)}e.succeed(`Applied ${h}`),c++;}catch(x){let R=x instanceof Error?x.message:"Unknown error";e.fail(`Failed ${h}: ${R}`),f++;}}console.log(""),console.log(f===0?d__default.default.green(`Successfully applied ${c} migration(s)`):d__default.default.yellow(`Applied ${c}, failed ${f} migration(s)`)),console.log("");}async function Pe(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(d__default.default.red("Not logged in")),console.log(d__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",i=null;try{i=await I(n);}catch{}let l=t.projectId||i?.projectId||o.projectId;l||(console.log(d__default.default.red("No project ID specified")),console.log(d__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let a=b__default.default.resolve(t.output||"vaif.schema.json");console.log(""),console.log(d__default.default.bold("VAIF Database Pull")),console.log(""),e.start("Pulling schema from remote...");try{let r=await fetch(`${B}/v1/projects/${l}/schema`,{headers:{Authorization:`Bearer ${o.token}`}});if(!r.ok){let f=await r.text();throw new Error(`Failed to pull schema: ${f}`)}let s=await r.json();j__default.default.writeFileSync(a,JSON.stringify(s,null,2),"utf-8"),e.succeed(`Schema written to ${b__default.default.relative(process.cwd(),a)}`);let c=s.tables?.length??Object.keys(s).length;console.log(d__default.default.gray(` ${c} table(s) pulled`)),console.log("");}catch(r){e.fail("Failed to pull schema"),r instanceof Error&&console.log(d__default.default.red(`
2097
+ Error: ${r.message}`)),process.exit(1);}}async function Te(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(d__default.default.red("Not logged in")),console.log(d__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",i=null;try{i=await I(n);}catch{}let l=t.projectId||i?.projectId||o.projectId;l||(console.log(d__default.default.red("No project ID specified")),process.exit(1)),console.log(""),console.log(d__default.default.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(d__default.default.red("This will:")),console.log(d__default.default.red(" - Drop all tables")),console.log(d__default.default.red(" - Delete all data")),console.log(d__default.default.red(" - Reset migrations")),console.log(""),console.log(d__default.default.red.bold("This action cannot be undone!")),console.log(""),t.force||(console.log(d__default.default.yellow("Use --force to confirm this action.")),process.exit(1)),e.start("Resetting database...");try{await xt(o.token,l),e.succeed("Database reset complete"),console.log(""),console.log(d__default.default.gray("Your database is now empty.")),console.log(d__default.default.gray("Run `vaif push` to apply your schema, then `vaif db seed` to seed data.")),console.log("");}catch(a){e.fail("Failed to reset database"),a instanceof Error&&console.log(d__default.default.red(`
2098
+ Error: ${a.message}`)),process.exit(1);}}var Fe=process.env.VAIF_API_URL||"https://api.vaif.studio";function je(t,e,o){return t.projectId||e?.projectId||o.projectId||null}async function Re(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(d__default.default.red("Not logged in")),console.log(d__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",i=null;try{i=await I(n);}catch{}let l=je(t,i,o);l||(console.log(d__default.default.red("No project ID specified")),console.log(d__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let a=t.name||`cli-key-${Date.now()}`;console.log(""),console.log(d__default.default.bold("VAIF Generate API Key")),console.log(""),e.start("Generating API key...");try{let r=await fetch(`${Fe}/v1/projects/${l}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:a})});if(!r.ok){let c=await r.text();throw new Error(`Failed to generate key: ${c}`)}let s=await r.json();e.succeed("API key generated"),console.log(""),console.log(d__default.default.green(` Name: ${s.name}`)),console.log(d__default.default.green(` Key: ${s.key}`)),console.log(""),console.log(d__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(d__default.default.red(`
2099
+ Error: ${r.message}`)),process.exit(1);}}async function ke(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(d__default.default.red("Not logged in")),console.log(d__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",i=null;try{i=await I(n);}catch{}let l=je(t,i,o);l||(console.log(d__default.default.red("No project ID specified")),console.log(d__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(d__default.default.bold("VAIF API Keys")),console.log(""),e.start("Fetching API keys...");try{let a=await fetch(`${Fe}/v1/projects/${l}/api-keys`,{headers:{Authorization:`Bearer ${o.token}`}});if(!a.ok){let u=await a.text();throw new Error(`Failed to list keys: ${u}`)}let r=await a.json(),s=r.keys||r;if(e.stop(),!Array.isArray(s)||s.length===0){console.log(d__default.default.yellow("No API keys found")),console.log(d__default.default.gray(`
2100
+ Generate one with: vaif keys generate`));return}let c=Math.max(8,...s.map(u=>(u.name||"").length)),f=` ${"Name".padEnd(c)} ${"Key".padEnd(24)} Created`;console.log(d__default.default.gray(f)),console.log(d__default.default.gray(" "+"-".repeat(f.length-2)));for(let u of s){let p=(u.name||"unnamed").padEnd(c),h=u.maskedKey||u.prefix||`${(u.key||"").slice(0,12)}...`,x=u.createdAt?new Date(u.createdAt).toLocaleDateString():"N/A";console.log(` ${p} ${h.padEnd(24)} ${x}`);}console.log(""),console.log(d__default.default.gray(` ${s.length} key(s) total`)),console.log("");}catch(a){e.fail("Failed to list API keys"),a instanceof Error&&console.log(d__default.default.red(`
2101
+ Error: ${a.message}`)),process.exit(1);}}var Ve=process.env.VAIF_API_URL||"https://api.vaif.studio";function At(t){try{let e=new URL(t);return e.password&&(e.password="****"),e.toString()}catch{return t.replace(/:[^@/]+@/,":****@")}}async function De(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(d__default.default.red("Not logged in")),console.log(d__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",i=null;try{i=await I(n);}catch{}let l=t.projectId||i?.projectId||o.projectId;l||(console.log(d__default.default.red("No project ID specified")),console.log(d__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),e.start("Fetching project info...");try{let a=await fetch(`${Ve}/v1/projects/${l}`,{headers:{Authorization:`Bearer ${o.token}`}});if(!a.ok){let f=await a.text();throw new Error(`Failed to fetch project: ${f}`)}let r=await a.json();e.stop(),console.log(""),console.log(d__default.default.bold("VAIF Project Info")),console.log("");let s=16,c=(f,u)=>{console.log(` ${d__default.default.gray(f.padEnd(s))} ${u}`);};c("Name:",d__default.default.white(r.name||"N/A")),c("Project ID:",d__default.default.white(l)),c("Region:",d__default.default.white(r.region||"us-east-1")),c("Plan:",d__default.default.white(r.plan||r.tier||"free")),c("Created:",d__default.default.white(r.createdAt?new Date(r.createdAt).toLocaleDateString():"N/A")),console.log(""),c("API URL:",d__default.default.cyan(r.apiUrl||`${Ve}/v1`)),c("WS URL:",d__default.default.cyan(r.wsUrl||r.realtimeUrl||"N/A")),c("DB URL:",d__default.default.cyan(r.databaseUrl?At(r.databaseUrl):"N/A")),c("Storage URL:",d__default.default.cyan(r.storageUrl||"N/A")),console.log("");}catch(a){e.fail("Failed to fetch project info"),a instanceof Error&&console.log(d__default.default.red(`
2102
+ Error: ${a.message}`)),process.exit(1);}}var Pt=process.env.VAIF_API_URL||"https://api.vaif.studio";async function $e(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(d__default.default.red("Not logged in")),console.log(d__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",i=null;try{i=await I(n);}catch{}let l=t.projectId||i?.projectId||o.projectId;l||(console.log(d__default.default.red("No project ID specified")),console.log(d__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),e.start("Fetching project status...");try{let a=await fetch(`${Pt}/v1/projects/${l}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${o.token}`}});if(!a.ok){let x=await a.text();throw new Error(`Failed to fetch project status: ${x}`)}let r=await a.json();e.stop(),console.log(""),console.log(d__default.default.bold("VAIF Project Status")),console.log("");let s=22,c=(x,R)=>{console.log(` ${d__default.default.gray(x.padEnd(s))} ${R}`);};c("Project:",d__default.default.white(r.name||l)),c("Plan:",d__default.default.white(r.plan||r.tier||"free")),console.log(""),console.log(d__default.default.gray(" --- Resources ---")),console.log("");let f=r.tableCount??r.tables?.length??"N/A",u=r.functionCount??r.functions?.length??"N/A",p=r.bucketCount??r.storage?.buckets?.length??"N/A",h=r.activeConnections??r.connections??"N/A";c("Tables:",d__default.default.white(String(f))),c("Functions:",d__default.default.white(String(u))),c("Storage Buckets:",d__default.default.white(String(p))),c("Active Connections:",d__default.default.white(String(h))),r.usage&&(console.log(""),console.log(d__default.default.gray(" --- Usage ---")),console.log(""),r.usage.dbSize&&c("Database Size:",d__default.default.white(r.usage.dbSize)),r.usage.storageSize&&c("Storage Size:",d__default.default.white(r.usage.storageSize)),r.usage.bandwidth&&c("Bandwidth:",d__default.default.white(r.usage.bandwidth)),r.usage.functionInvocations!=null&&c("Function Invocations:",d__default.default.white(String(r.usage.functionInvocations)))),console.log("");}catch(a){e.fail("Failed to fetch project status"),a instanceof Error&&console.log(d__default.default.red(`
2103
+ Error: ${a.message}`)),process.exit(1);}}commander.program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.3.0");commander.program.command("login").description("Authenticate with VAIF (opens browser)").option("-e, --email","Login with email/password instead of browser").option("-p, --project-id <id>","Default project ID").action(pe);commander.program.command("logout").description("Log out and remove stored credentials").action(ue);commander.program.command("whoami").description("Show current authenticated user").action(fe);commander.program.command("init").description("Initialize VAIF configuration in your project").option("--typescript","Setup for TypeScript project").option("-f, --force","Overwrite existing config").option("-t, --template <name>","Scaffold from a template (run vaif templates for list)").option("--features <features>","Comma-separated features to include: auth,database,realtime,storage,functions").action(se);commander.program.command("templates").alias("tpl").description("List available project templates").action(ae);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(De);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($e);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(ge);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(ye);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(te);var Ue=commander.program.command("functions").alias("fn").description("Manage serverless functions");Ue.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(_e);Ue.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(xe);var z=commander.program.command("db").description("Database management commands");z.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(Ee);z.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(Pe);z.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(Ae);z.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(Te);var Ne=commander.program.command("keys").description("Manage API keys");Ne.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(Re);Ne.command("list").alias("ls").description("List API keys").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(ke);commander.program.parse(process.argv);process.argv.slice(2).length||commander.program.outputHelp();