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