@vaiftech/cli 1.2.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/chunk-7XA2HKEQ.js +2067 -0
- package/dist/cli.cjs +1196 -279
- package/dist/cli.js +36 -30
- package/dist/index.cjs +1171 -260
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-VD3KS4ZK.js +0 -1156
package/dist/cli.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';var commander=require('commander'),
|
|
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
|
|
@@ -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]),
|
|
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]),
|
|
39
|
+
`,[e]),l=await t.query(`
|
|
40
40
|
SELECT
|
|
41
41
|
t.typname as enum_name,
|
|
42
42
|
e.enumlabel as enum_value
|
|
@@ -45,22 +45,113 @@
|
|
|
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]),
|
|
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
49
|
`);return `export type ${o} =
|
|
50
|
-
${n};`}function
|
|
51
|
-
${
|
|
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
|
-
}`,
|
|
54
|
-
${
|
|
53
|
+
}`,s=`export interface ${n}Insert {
|
|
54
|
+
${l.join(`
|
|
55
55
|
`)}
|
|
56
|
-
}`,
|
|
57
|
-
${
|
|
56
|
+
}`,c=`export interface ${n}Update {
|
|
57
|
+
${a.join(`
|
|
58
58
|
`)}
|
|
59
|
-
}`;return {base:r,insert:
|
|
60
|
-
`)}async function
|
|
61
|
-
Provide a connection string via:`)),console.log(
|
|
62
|
-
Error: ${o.message}`)),o.message.includes("ECONNREFUSED")&&console.log(
|
|
63
|
-
Make sure your database is running and accessible.`))),process.exit(1);}}var
|
|
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";
|
|
64
155
|
import { createServerClient } from "@vaiftech/client/server";
|
|
65
156
|
|
|
66
157
|
// Browser client \u2013 safe to use in Client Components
|
|
@@ -82,21 +173,22 @@ export function createVaifServer() {
|
|
|
82
173
|
NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
|
|
83
174
|
NEXT_PUBLIC_VAIF_API_KEY=your-anon-key
|
|
84
175
|
VAIF_SECRET_KEY=your-secret-key
|
|
85
|
-
`},{path:"
|
|
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";
|
|
86
183
|
import { createServerClient } from "@vaiftech/client/server";
|
|
87
184
|
import { authMiddleware } from "@vaiftech/auth/nextjs";
|
|
88
185
|
|
|
89
|
-
// Routes that require authentication
|
|
90
186
|
const protectedRoutes = ["/dashboard", "/settings", "/api/protected"];
|
|
91
187
|
|
|
92
188
|
export async function middleware(request: NextRequest) {
|
|
93
189
|
const { pathname } = request.nextUrl;
|
|
94
|
-
|
|
95
|
-
// Skip auth for public routes
|
|
96
190
|
const isProtected = protectedRoutes.some((route) => pathname.startsWith(route));
|
|
97
|
-
if (!isProtected)
|
|
98
|
-
return NextResponse.next();
|
|
99
|
-
}
|
|
191
|
+
if (!isProtected) return NextResponse.next();
|
|
100
192
|
|
|
101
193
|
const vaif = createServerClient({
|
|
102
194
|
projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
|
|
@@ -116,29 +208,552 @@ export async function middleware(request: NextRequest) {
|
|
|
116
208
|
export const config = {
|
|
117
209
|
matcher: ["/dashboard/:path*", "/settings/:path*", "/api/protected/:path*"],
|
|
118
210
|
};
|
|
119
|
-
`}
|
|
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";
|
|
120
498
|
|
|
121
499
|
export const vaif = createClient({
|
|
122
500
|
projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
|
|
123
501
|
apiKey: import.meta.env.VITE_VAIF_API_KEY,
|
|
124
502
|
});
|
|
125
|
-
`},{path:"src/
|
|
126
|
-
import { vaif } from "../lib/vaif";
|
|
127
|
-
import type { ReactNode } from "react";
|
|
503
|
+
`},{path:"src/vite-env.d.ts",content:`/// <reference types="vite/client" />
|
|
128
504
|
|
|
129
|
-
interface
|
|
130
|
-
|
|
505
|
+
interface ImportMetaEnv {
|
|
506
|
+
readonly VITE_VAIF_PROJECT_ID: string;
|
|
507
|
+
readonly VITE_VAIF_API_KEY: string;
|
|
131
508
|
}
|
|
132
509
|
|
|
133
|
-
|
|
134
|
-
|
|
510
|
+
interface ImportMeta {
|
|
511
|
+
readonly env: ImportMetaEnv;
|
|
135
512
|
}
|
|
136
513
|
`},{path:".env.example",content:`# VAIF Configuration
|
|
137
514
|
# Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
|
|
138
515
|
|
|
139
516
|
VITE_VAIF_PROJECT_ID=your-project-id
|
|
140
517
|
VITE_VAIF_API_KEY=your-anon-key
|
|
141
|
-
`}
|
|
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
|
|
142
757
|
import VaifClient
|
|
143
758
|
|
|
144
759
|
/// Singleton manager for the VAIF client.
|
|
@@ -244,42 +859,287 @@ Run the VAIF CLI to generate Swift models from your schema:
|
|
|
244
859
|
\`\`\`bash
|
|
245
860
|
npx @vaiftech/cli generate --output ./Models/Database.swift --lang swift
|
|
246
861
|
\`\`\`
|
|
247
|
-
`}],postInstructions:["Add the VaifClient Swift package from https://github.com/vaif-technologies/vaif-swift","Add VAIF_PROJECT_ID and VAIF_API_KEY to your Xcode scheme environment","See README-VAIF.md for full setup instructions"]},"expo-mobile-app":{name:"Expo Mobile App",description:"React Native / Expo app with VAIF client configured for mobile",tag:"Expo / React Native",files:[{path:"
|
|
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";
|
|
248
925
|
import AsyncStorage from "@react-native-async-storage/async-storage";
|
|
249
926
|
|
|
250
927
|
export const vaif = createExpoClient({
|
|
251
928
|
projectId: process.env.EXPO_PUBLIC_VAIF_PROJECT_ID!,
|
|
252
929
|
apiKey: process.env.EXPO_PUBLIC_VAIF_API_KEY!,
|
|
253
930
|
storage: AsyncStorage,
|
|
254
|
-
|
|
255
|
-
realtime: {
|
|
256
|
-
enabled: true,
|
|
257
|
-
},
|
|
258
|
-
});
|
|
259
|
-
`},{path:"app.config.ts",content:`import { ExpoConfig, ConfigContext } from "expo/config";
|
|
260
|
-
|
|
261
|
-
export default ({ config }: ConfigContext): ExpoConfig => ({
|
|
262
|
-
...config,
|
|
263
|
-
name: "my-vaif-app",
|
|
264
|
-
slug: "my-vaif-app",
|
|
265
|
-
extra: {
|
|
266
|
-
// These are available via process.env.EXPO_PUBLIC_* in SDK 49+
|
|
267
|
-
// Set them in .env and they will be embedded at build time
|
|
268
|
-
vaifProjectId: process.env.EXPO_PUBLIC_VAIF_PROJECT_ID,
|
|
269
|
-
vaifApiKey: process.env.EXPO_PUBLIC_VAIF_API_KEY,
|
|
270
|
-
},
|
|
931
|
+
realtime: { enabled: true },
|
|
271
932
|
});
|
|
272
933
|
`},{path:".env.example",content:`# VAIF Configuration
|
|
273
934
|
# Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
|
|
274
935
|
|
|
275
936
|
EXPO_PUBLIC_VAIF_PROJECT_ID=your-project-id
|
|
276
937
|
EXPO_PUBLIC_VAIF_API_KEY=your-anon-key
|
|
277
|
-
`}
|
|
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';
|
|
278
1141
|
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
|
279
1142
|
|
|
280
|
-
/// Global VAIF client instance.
|
|
281
|
-
///
|
|
282
|
-
/// Initialise by calling [initVaif] in your main() before runApp().
|
|
283
1143
|
late final VaifClient vaif;
|
|
284
1144
|
|
|
285
1145
|
Future<void> initVaif() async {
|
|
@@ -289,149 +1149,186 @@ Future<void> initVaif() async {
|
|
|
289
1149
|
final apiKey = dotenv.env['VAIF_API_KEY'];
|
|
290
1150
|
|
|
291
1151
|
if (projectId == null || apiKey == null) {
|
|
292
|
-
throw Exception(
|
|
293
|
-
'VAIF_PROJECT_ID and VAIF_API_KEY must be set in .env',
|
|
294
|
-
);
|
|
1152
|
+
throw Exception('VAIF_PROJECT_ID and VAIF_API_KEY must be set in .env');
|
|
295
1153
|
}
|
|
296
1154
|
|
|
297
1155
|
vaif = VaifClient(
|
|
298
1156
|
projectId: projectId,
|
|
299
1157
|
apiKey: apiKey,
|
|
300
|
-
// Enable realtime subscriptions
|
|
301
1158
|
realtime: const RealtimeConfig(enabled: true),
|
|
302
1159
|
);
|
|
303
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'
|
|
304
1165
|
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
final response = await vaif.from(table).select().execute();
|
|
308
|
-
return List<Map<String, dynamic>>.from(response.data);
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
/// Example: insert a row.
|
|
312
|
-
Future<void> insertRow(String table, Map<String, dynamic> values) async {
|
|
313
|
-
await vaif.from(table).insert(values).execute();
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
/// Example: subscribe to realtime changes.
|
|
317
|
-
void subscribeToTable(
|
|
318
|
-
String table,
|
|
319
|
-
void Function(Map<String, dynamic> payload) onEvent,
|
|
320
|
-
) {
|
|
321
|
-
vaif.realtime.channel(table).on(
|
|
322
|
-
RealtimeListenTypes.postgresChanges,
|
|
323
|
-
ChannelFilter(event: '*', schema: 'public', table: table),
|
|
324
|
-
(payload, [ref]) => onEvent(payload),
|
|
325
|
-
).subscribe();
|
|
326
|
-
}
|
|
327
|
-
`},{path:".env.example",content:`# VAIF Configuration
|
|
328
|
-
# Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
|
|
329
|
-
|
|
330
|
-
VAIF_PROJECT_ID=your-project-id
|
|
331
|
-
VAIF_API_KEY=your-anon-key
|
|
332
|
-
`},{path:"README-VAIF.md",content:`# VAIF Flutter Setup
|
|
333
|
-
|
|
334
|
-
## 1. Add Dependencies
|
|
1166
|
+
environment:
|
|
1167
|
+
sdk: ^3.5.0
|
|
335
1168
|
|
|
336
|
-
Add the following to your \`pubspec.yaml\`:
|
|
337
|
-
|
|
338
|
-
\`\`\`yaml
|
|
339
1169
|
dependencies:
|
|
1170
|
+
flutter:
|
|
1171
|
+
sdk: flutter
|
|
340
1172
|
vaif_client: ^1.0.0
|
|
341
1173
|
flutter_dotenv: ^5.1.0
|
|
342
|
-
\`\`\`
|
|
343
1174
|
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
flutter
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
## 2. Configure Environment
|
|
1175
|
+
dev_dependencies:
|
|
1176
|
+
flutter_test:
|
|
1177
|
+
sdk: flutter
|
|
1178
|
+
flutter_lints: ^5.0.0
|
|
350
1179
|
|
|
351
|
-
Copy \`.env.example\` to \`.env\` and fill in your credentials.
|
|
352
|
-
|
|
353
|
-
Add the \`.env\` file to your \`pubspec.yaml\` assets:
|
|
354
|
-
|
|
355
|
-
\`\`\`yaml
|
|
356
1180
|
flutter:
|
|
1181
|
+
uses-material-design: true
|
|
357
1182
|
assets:
|
|
358
1183
|
- .env
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
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
|
+
}
|
|
362
1200
|
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
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
|
+
}
|
|
366
1222
|
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
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
|
+
}
|
|
371
1247
|
}
|
|
372
|
-
|
|
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."""
|
|
373
1249
|
|
|
374
|
-
|
|
1250
|
+
from fastapi import FastAPI
|
|
1251
|
+
from fastapi.middleware.cors import CORSMiddleware
|
|
1252
|
+
from vaif_client import get_vaif_client
|
|
375
1253
|
|
|
376
|
-
|
|
377
|
-
// Query data
|
|
378
|
-
final todos = await vaif.from('todos').select().execute();
|
|
1254
|
+
app = FastAPI(title="My VAIF API", version="0.1.0")
|
|
379
1255
|
|
|
380
|
-
|
|
381
|
-
|
|
1256
|
+
app.add_middleware(
|
|
1257
|
+
CORSMiddleware,
|
|
1258
|
+
allow_origins=["*"],
|
|
1259
|
+
allow_credentials=True,
|
|
1260
|
+
allow_methods=["*"],
|
|
1261
|
+
allow_headers=["*"],
|
|
1262
|
+
)
|
|
382
1263
|
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
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."""
|
|
393
1281
|
|
|
394
1282
|
import os
|
|
395
1283
|
from functools import lru_cache
|
|
396
|
-
from typing import Optional
|
|
397
1284
|
|
|
398
1285
|
from dotenv import load_dotenv
|
|
399
|
-
from fastapi import Depends, HTTPException, Request, status
|
|
400
|
-
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
401
1286
|
from vaif import Client, ServiceClient
|
|
402
1287
|
|
|
403
1288
|
load_dotenv()
|
|
404
1289
|
|
|
405
1290
|
VAIF_PROJECT_ID = os.environ["VAIF_PROJECT_ID"]
|
|
406
1291
|
VAIF_API_KEY = os.environ["VAIF_API_KEY"]
|
|
407
|
-
VAIF_SECRET_KEY = os.environ
|
|
1292
|
+
VAIF_SECRET_KEY = os.environ.get("VAIF_SECRET_KEY", "")
|
|
408
1293
|
|
|
409
1294
|
|
|
410
1295
|
@lru_cache()
|
|
411
1296
|
def get_vaif_client() -> Client:
|
|
412
1297
|
"""Public client using the anon key (respects Row Level Security)."""
|
|
413
|
-
return Client(
|
|
414
|
-
project_id=VAIF_PROJECT_ID,
|
|
415
|
-
api_key=VAIF_API_KEY,
|
|
416
|
-
)
|
|
1298
|
+
return Client(project_id=VAIF_PROJECT_ID, api_key=VAIF_API_KEY)
|
|
417
1299
|
|
|
418
1300
|
|
|
419
1301
|
@lru_cache()
|
|
420
1302
|
def get_vaif_admin() -> ServiceClient:
|
|
421
1303
|
"""Admin/service client that bypasses RLS. Use with caution."""
|
|
422
|
-
return ServiceClient(
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
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."""
|
|
426
1321
|
|
|
1322
|
+
from typing import Optional
|
|
427
1323
|
|
|
428
|
-
|
|
1324
|
+
from fastapi import Depends, HTTPException, status
|
|
1325
|
+
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
1326
|
+
from vaif_client import get_vaif_admin
|
|
429
1327
|
|
|
430
1328
|
security = HTTPBearer(auto_error=False)
|
|
431
1329
|
|
|
432
1330
|
|
|
433
1331
|
async def get_current_user(
|
|
434
|
-
request: Request,
|
|
435
1332
|
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
|
|
436
1333
|
):
|
|
437
1334
|
"""FastAPI dependency that validates VAIF auth tokens.
|
|
@@ -463,52 +1360,77 @@ async def get_current_user(
|
|
|
463
1360
|
)
|
|
464
1361
|
|
|
465
1362
|
return user
|
|
1363
|
+
`},{path:"middleware/__init__.py",content:""}],storage:[{path:"routes/storage.py",content:`"""File upload routes using VAIF Storage."""
|
|
466
1364
|
|
|
1365
|
+
from fastapi import APIRouter, UploadFile, File
|
|
1366
|
+
from vaif_client import get_vaif_admin
|
|
467
1367
|
|
|
468
|
-
|
|
1368
|
+
router = APIRouter(prefix="/storage", tags=["storage"])
|
|
469
1369
|
|
|
1370
|
+
BUCKET = "uploads"
|
|
470
1371
|
|
|
471
|
-
async def query_table(table: str, filters: Optional[dict] = None):
|
|
472
|
-
"""Quick helper to query a table with optional filters."""
|
|
473
|
-
client = get_vaif_client()
|
|
474
|
-
q = client.from_(table).select("*")
|
|
475
|
-
if filters:
|
|
476
|
-
for key, value in filters.items():
|
|
477
|
-
q = q.eq(key, value)
|
|
478
|
-
return await q.execute()
|
|
479
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
|
|
480
1387
|
|
|
481
|
-
|
|
482
|
-
|
|
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 = {}):
|
|
483
1393
|
client = get_vaif_client()
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
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
|
|
487
1397
|
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
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
|
|
496
1424
|
|
|
497
1425
|
import (
|
|
498
1426
|
"fmt"
|
|
499
|
-
"net/http"
|
|
500
1427
|
"os"
|
|
501
|
-
"strings"
|
|
502
1428
|
|
|
503
1429
|
vaifclient "github.com/vaif-technologies/vaif-go"
|
|
504
1430
|
)
|
|
505
1431
|
|
|
506
|
-
// Client is the global VAIF client instance.
|
|
507
|
-
// Initialise by calling Init() at application start.
|
|
508
1432
|
var Client *vaifclient.Client
|
|
509
1433
|
|
|
510
|
-
// Init creates the VAIF client from environment variables.
|
|
511
|
-
// Call this in main() before starting your HTTP server.
|
|
512
1434
|
func Init() error {
|
|
513
1435
|
projectID := os.Getenv("VAIF_PROJECT_ID")
|
|
514
1436
|
apiKey := os.Getenv("VAIF_API_KEY")
|
|
@@ -530,9 +1452,34 @@ func Init() error {
|
|
|
530
1452
|
|
|
531
1453
|
return nil
|
|
532
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
|
+
)
|
|
533
1482
|
|
|
534
|
-
// AuthMiddleware validates the VAIF auth token from the Authorization header.
|
|
535
|
-
// It injects the authenticated user into the request context.
|
|
536
1483
|
func AuthMiddleware(next http.Handler) http.Handler {
|
|
537
1484
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
538
1485
|
auth := r.Header.Get("Authorization")
|
|
@@ -547,7 +1494,7 @@ func AuthMiddleware(next http.Handler) http.Handler {
|
|
|
547
1494
|
return
|
|
548
1495
|
}
|
|
549
1496
|
|
|
550
|
-
user, err := Client.Auth.GetUser(r.Context(), token)
|
|
1497
|
+
user, err := vaif.Client.Auth.GetUser(r.Context(), token)
|
|
551
1498
|
if err != nil {
|
|
552
1499
|
http.Error(w, "invalid or expired token", http.StatusUnauthorized)
|
|
553
1500
|
return
|
|
@@ -557,85 +1504,48 @@ func AuthMiddleware(next http.Handler) http.Handler {
|
|
|
557
1504
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
558
1505
|
})
|
|
559
1506
|
}
|
|
560
|
-
`},{path:".
|
|
561
|
-
# Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
|
|
562
|
-
|
|
563
|
-
VAIF_PROJECT_ID=your-project-id
|
|
564
|
-
VAIF_API_KEY=your-anon-key
|
|
565
|
-
VAIF_SECRET_KEY=your-secret-key
|
|
566
|
-
`},{path:"README-VAIF.md",content:`# VAIF Go Setup
|
|
567
|
-
|
|
568
|
-
## 1. Install the Go Client
|
|
569
|
-
|
|
570
|
-
\`\`\`bash
|
|
571
|
-
go get github.com/vaif-technologies/vaif-go
|
|
572
|
-
\`\`\`
|
|
573
|
-
|
|
574
|
-
## 2. Configure Environment
|
|
575
|
-
|
|
576
|
-
Copy \`.env.example\` to \`.env\` and fill in your credentials.
|
|
577
|
-
|
|
578
|
-
Use a library like [godotenv](https://github.com/joho/godotenv) to load the file:
|
|
579
|
-
|
|
580
|
-
\`\`\`bash
|
|
581
|
-
go get github.com/joho/godotenv
|
|
582
|
-
\`\`\`
|
|
583
|
-
|
|
584
|
-
## 3. Initialise in main.go
|
|
585
|
-
|
|
586
|
-
\`\`\`go
|
|
587
|
-
package main
|
|
1507
|
+
`}],storage:[{path:"handlers/storage.go",content:`package handlers
|
|
588
1508
|
|
|
589
1509
|
import (
|
|
590
|
-
"
|
|
1510
|
+
"encoding/json"
|
|
1511
|
+
"fmt"
|
|
1512
|
+
"io"
|
|
591
1513
|
"net/http"
|
|
1514
|
+
"time"
|
|
592
1515
|
|
|
593
|
-
"
|
|
594
|
-
"yourmodule/vaif"
|
|
1516
|
+
"myapp/vaif"
|
|
595
1517
|
)
|
|
596
1518
|
|
|
597
|
-
func
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
log.Fatalf("Failed to initialise VAIF: %v", err)
|
|
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
|
|
602
1523
|
}
|
|
603
1524
|
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
protected := vaif.AuthMiddleware(http.HandlerFunc(protectedHandler))
|
|
611
|
-
mux.Handle("/api/data", protected)
|
|
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()
|
|
612
1531
|
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
1532
|
+
data, err := io.ReadAll(file)
|
|
1533
|
+
if err != nil {
|
|
1534
|
+
http.Error(w, "failed to read file", http.StatusInternalServerError)
|
|
1535
|
+
return
|
|
1536
|
+
}
|
|
616
1537
|
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
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
|
+
}
|
|
620
1544
|
|
|
621
|
-
|
|
622
|
-
w.
|
|
1545
|
+
w.Header().Set("Content-Type", "application/json")
|
|
1546
|
+
json.NewEncoder(w).Encode(result)
|
|
623
1547
|
}
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
## 4. Query Data
|
|
627
|
-
|
|
628
|
-
\`\`\`go
|
|
629
|
-
// Fetch rows
|
|
630
|
-
rows, err := vaif.Client.From("todos").Select("*").Execute(ctx)
|
|
631
|
-
|
|
632
|
-
// Insert a row
|
|
633
|
-
_, err := vaif.Client.From("todos").Insert(map[string]interface{}{
|
|
634
|
-
"title": "Buy milk",
|
|
635
|
-
"done": false,
|
|
636
|
-
}).Execute(ctx)
|
|
637
|
-
\`\`\`
|
|
638
|
-
`}],postInstructions:["Run: go get github.com/vaif-technologies/vaif-go","Copy .env.example to .env and fill in your project credentials","Call vaif.Init() in main() before starting your server","See README-VAIF.md for full setup instructions"]},"todo-app":{name:"Todo App",description:"Simple React todo app \u2013 great for learning VAIF basics",tag:"React Starter",files:[{path:"src/lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
|
|
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";
|
|
639
1549
|
|
|
640
1550
|
export const vaif = createClient({
|
|
641
1551
|
projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
|
|
@@ -694,7 +1604,7 @@ export async function deleteTodo(id: string): Promise<void> {
|
|
|
694
1604
|
|
|
695
1605
|
VITE_VAIF_PROJECT_ID=your-project-id
|
|
696
1606
|
VITE_VAIF_API_KEY=your-anon-key
|
|
697
|
-
`}],dependencies:["@vaiftech/client","@vaiftech/react"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Create a 'todos' table in your VAIF dashboard with columns: id (uuid), title (text), done (boolean), created_at (timestamptz)","Import helpers from './lib/vaif' in your components","Run: npx vaif generate to generate TypeScript types"]},"realtime-chat":{name:"Realtime Chat",description:"React chat app with VAIF realtime subscriptions for live messaging",tag:"React + Realtime",files:[{path:"src/lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
|
|
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";
|
|
698
1608
|
|
|
699
1609
|
export const vaif = createClient({
|
|
700
1610
|
projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
|
|
@@ -847,7 +1757,7 @@ export function useRealtimeMessages({
|
|
|
847
1757
|
|
|
848
1758
|
VITE_VAIF_PROJECT_ID=your-project-id
|
|
849
1759
|
VITE_VAIF_API_KEY=your-anon-key
|
|
850
|
-
`}],dependencies:["@vaiftech/client","@vaiftech/react"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Create a 'messages' table with columns: id (uuid), content (text), user_id (text), username (text), channel_id (text), created_at (timestamptz)","Enable Realtime on the messages table in your VAIF dashboard","Use the useRealtimeMessages hook in your components","Run: npx vaif generate to generate TypeScript types"]},"saas-starter":{name:"SaaS Starter",description:"Full SaaS starter with VAIF auth, team/org support, and server-side helpers",tag:"Next.js SaaS",files:[{path:"lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
|
|
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";
|
|
851
1761
|
import { createServerClient } from "@vaiftech/client/server";
|
|
852
1762
|
|
|
853
1763
|
// Browser client \u2013 use in Client Components
|
|
@@ -1016,7 +1926,7 @@ export async function requireTeamRole(
|
|
|
1016
1926
|
NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
|
|
1017
1927
|
NEXT_PUBLIC_VAIF_API_KEY=your-anon-key
|
|
1018
1928
|
VAIF_SECRET_KEY=your-secret-key
|
|
1019
|
-
`}],dependencies:["@vaiftech/client","@vaiftech/auth","@vaiftech/react"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create 'teams' and 'team_members' tables in your VAIF dashboard","Import auth helpers from '@/lib/auth' in your Server Components/Actions","Use requireUser() for authenticated routes and requireTeamRole() for role checks","Run: npx vaif generate to generate TypeScript types"]},"ecommerce-api":{name:"E-commerce API",description:"API-first e-commerce setup with VAIF storage for product images",tag:"Next.js E-commerce",files:[{path:"lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
|
|
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";
|
|
1020
1930
|
import { createServerClient } from "@vaiftech/client/server";
|
|
1021
1931
|
|
|
1022
1932
|
// Browser client
|
|
@@ -1147,40 +2057,47 @@ function getContentType(fileName: string): string {
|
|
|
1147
2057
|
NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
|
|
1148
2058
|
NEXT_PUBLIC_VAIF_API_KEY=your-anon-key
|
|
1149
2059
|
VAIF_SECRET_KEY=your-secret-key
|
|
1150
|
-
`}],dependencies:["@vaiftech/client","@vaiftech/auth"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create a 'product-images' storage bucket in your VAIF dashboard","Import storage helpers from '@/lib/storage' in your API routes","Use uploadProductImage() in your product creation flow","Run: npx vaif generate to generate TypeScript types"]}};function
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
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
|
|
1154
2065
|
DATABASE_URL=postgresql://user:password@localhost:5432/database
|
|
1155
2066
|
VAIF_API_KEY=your-api-key
|
|
1156
|
-
`,"utf-8"),console.log(
|
|
1157
|
-
Error: ${n.message}`)),process.exit(1);}}var
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
Error: ${
|
|
1168
|
-
|
|
1169
|
-
Error: ${
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
Error: ${
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
Error: ${
|
|
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();
|