@vaiftech/cli 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1156 +0,0 @@
1
- import g from'fs';import A from'path';import U from'dotenv';import j from'pg';import K from'ora';import s from'chalk';import k from'prettier';U.config();async function P(r){let t=A.resolve(r);if(!g.existsSync(t))return null;try{let n=g.readFileSync(t,"utf-8"),e=JSON.parse(n);return e.database?.url&&(e.database.url=C(e.database.url)),e.api?.apiKey&&(e.api.apiKey=C(e.api.apiKey)),e}catch{throw new Error(`Failed to parse config file: ${r}`)}}function C(r){return r.replace(/\$\{([^}]+)\}/g,(t,n)=>process.env[n]||t)}async function O(r,t){let n=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]),o=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]),a=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]),i=new Map;for(let l of n.rows)i.set(l.table_name,[]);for(let l of e.rows){let p=i.get(l.table_name);p&&p.push(l);}let c=new Map;for(let l of a.rows){let p=c.get(l.enum_name)||[];p.push(l.enum_value),c.set(l.enum_name,p);}return {tables:i,enums:c,foreignKeys:o.rows}}var b={smallint:"number",integer:"number",bigint:"string",int2:"number",int4:"number",int8:"string",decimal:"string",numeric:"string",real:"number",float4:"number",float8:"number","double precision":"number",money:"string",boolean:"boolean",bool:"boolean",text:"string",varchar:"string",char:"string",character:"string","character varying":"string",name:"string",citext:"string",date:"string",time:"string",timetz:"string","time without time zone":"string","time with time zone":"string",timestamp:"string",timestamptz:"string","timestamp without time zone":"string","timestamp with time zone":"string",interval:"string",bytea:"Buffer",uuid:"string",json:"unknown",jsonb:"unknown",inet:"string",cidr:"string",macaddr:"string",macaddr8:"string",point:"{ x: number; y: number }",line:"string",lseg:"string",box:"string",path:"string",polygon:"string",circle:"string",ARRAY:"unknown[]"};function M(r,t){let{data_type:n,udt_name:e,is_nullable:o}=r;if(t.has(e)){let c=t.get(e).map(l=>`"${l}"`).join(" | ");return o==="YES"?`(${c}) | null`:c}if(n==="ARRAY"){let i=e.replace(/^_/,"");if(t.has(i)){let p=t.get(i).map(d=>`"${d}"`).join(" | ");return o==="YES"?`(${p})[] | null`:`(${p})[]`}let c=b[i]||"unknown";return o==="YES"?`${c}[] | null`:`${c}[]`}let a=b[n]||b[e]||"unknown";return o==="YES"&&(a=`${a} | null`),a}function E(r){return r.split(/[_\-\s]+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function N(r,t){let n=E(r),e=t.map(o=>` | "${o}"`).join(`
48
- `);return `export type ${n} =
49
- ${e};`}function $(r,t,n){let e=E(r),o=[],a=[],i=[];for(let d of t){let f=M(d,n),h=d.column_name,F=d.column_default!==null||d.is_identity==="YES",R=d.is_nullable==="YES";o.push(` ${h}: ${f};`),F||d.column_name==="id"?a.push(` ${h}?: ${f.replace(" | null","")} | null;`):R?a.push(` ${h}?: ${f};`):a.push(` ${h}: ${f.replace(" | null","")};`),i.push(` ${h}?: ${f.replace(" | null","")} | null;`);}let c=`export interface ${e} {
50
- ${o.join(`
51
- `)}
52
- }`,l=`export interface ${e}Insert {
53
- ${a.join(`
54
- `)}
55
- }`,p=`export interface ${e}Update {
56
- ${i.join(`
57
- `)}
58
- }`;return {base:c,insert:l,update:p}}function L(r,t,n){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[a,i]of t)e.push(N(a,i)),e.push("");}e.push("// ============ TABLES ============"),e.push("");let o=[];for(let[a,i]of r){let{base:c,insert:l,update:p}=$(a,i,t);o.push(a),e.push(c),e.push(""),e.push(l),e.push(""),e.push(p),e.push("");}e.push("// ============ DATABASE SCHEMA ============"),e.push(""),e.push("export interface Database {");for(let a of o){let i=E(a);e.push(` ${a}: {`),e.push(` Row: ${i};`),e.push(` Insert: ${i}Insert;`),e.push(` Update: ${i}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 ne(r){let t=K("Loading configuration...").start();try{let n=await P(r.config),e=r.connection||n?.database?.url||process.env.DATABASE_URL;e||(t.fail("No database connection string provided"),console.log(s.yellow(`
60
- Provide a connection string via:`)),console.log(s.gray(" --connection <url>")),console.log(s.gray(" DATABASE_URL environment variable")),console.log(s.gray(" vaif.config.json database.url")),process.exit(1)),t.text="Connecting to database...";let o=new j.Client({connectionString:e});await o.connect(),t.text="Introspecting schema...";let{tables:a,enums:i,foreignKeys:c}=await O(o,r.schema);if(await o.end(),a.size===0){t.warn(`No tables found in schema "${r.schema}"`);return}t.text=`Generating types for ${a.size} tables...`;let l=L(a,i,c),p=await k.format(l,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100});if(r.dryRun){t.succeed("Generated types (dry run):"),console.log(""),console.log(s.gray("\u2500".repeat(60))),console.log(p),console.log(s.gray("\u2500".repeat(60)));return}let d=A.resolve(r.output),f=A.dirname(d);g.existsSync(f)||g.mkdirSync(f,{recursive:!0}),g.writeFileSync(d,p,"utf-8"),t.succeed(`Generated types for ${a.size} tables \u2192 ${s.cyan(r.output)}`),console.log(""),console.log(s.green("Generated:")),console.log(s.gray(` Tables: ${a.size}`)),console.log(s.gray(` Enums: ${i.size}`)),console.log(""),console.log(s.gray("Import in your code:")),console.log(s.cyan(` import type { Database, Row, Insert, Update } from "${r.output.replace(/\.ts$/,"")}";`));}catch(n){t.fail("Failed to generate types"),n instanceof Error&&(console.error(s.red(`
61
- Error: ${n.message}`)),n.message.includes("ECONNREFUSED")&&console.log(s.yellow(`
62
- Make sure your database is running and accessible.`))),process.exit(1);}}var S={"nextjs-fullstack":{name:"Next.js Full-Stack",description:"Next.js app with server/client VAIF client, auth middleware, and React hooks",tag:"Next.js",files:[{path:"lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
63
- import { createServerClient } from "@vaiftech/client/server";
64
-
65
- // Browser client \u2013 safe to use in Client Components
66
- export const vaif = createClient({
67
- projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
68
- apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
69
- });
70
-
71
- // Server client \u2013 use in Server Components, Route Handlers, Server Actions
72
- export function createVaifServer() {
73
- return createServerClient({
74
- projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
75
- secretKey: process.env.VAIF_SECRET_KEY!,
76
- });
77
- }
78
- `},{path:".env.local.example",content:`# VAIF Configuration
79
- # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
80
-
81
- NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
82
- NEXT_PUBLIC_VAIF_API_KEY=your-anon-key
83
- VAIF_SECRET_KEY=your-secret-key
84
- `},{path:"middleware.ts",content:`import { NextResponse, type NextRequest } from "next/server";
85
- import { createServerClient } from "@vaiftech/client/server";
86
- import { authMiddleware } from "@vaiftech/auth/nextjs";
87
-
88
- // Routes that require authentication
89
- const protectedRoutes = ["/dashboard", "/settings", "/api/protected"];
90
-
91
- export async function middleware(request: NextRequest) {
92
- const { pathname } = request.nextUrl;
93
-
94
- // Skip auth for public routes
95
- const isProtected = protectedRoutes.some((route) => pathname.startsWith(route));
96
- if (!isProtected) {
97
- return NextResponse.next();
98
- }
99
-
100
- const vaif = createServerClient({
101
- projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
102
- secretKey: process.env.VAIF_SECRET_KEY!,
103
- });
104
-
105
- return authMiddleware(vaif, request, {
106
- loginRedirect: "/login",
107
- onUnauthenticated: () => {
108
- const loginUrl = new URL("/login", request.url);
109
- loginUrl.searchParams.set("redirect", pathname);
110
- return NextResponse.redirect(loginUrl);
111
- },
112
- });
113
- }
114
-
115
- export const config = {
116
- matcher: ["/dashboard/:path*", "/settings/:path*", "/api/protected/:path*"],
117
- };
118
- `}],dependencies:["@vaiftech/client","@vaiftech/auth","@vaiftech/react"],postInstructions:["Copy .env.local.example to .env.local and fill in your project credentials","Import { vaif } from '@/lib/vaif' in Client Components","Import { createVaifServer } from '@/lib/vaif' in Server Components","Run: npx vaif generate to generate TypeScript types from your schema"]},"react-spa":{name:"React SPA",description:"Single-page React app with Vite, VAIF client, and provider wrapper",tag:"React + Vite",files:[{path:"src/lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
119
-
120
- export const vaif = createClient({
121
- projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
122
- apiKey: import.meta.env.VITE_VAIF_API_KEY,
123
- });
124
- `},{path:"src/providers/VaifProvider.tsx",content:`import { VaifProvider as Provider } from "@vaiftech/react";
125
- import { vaif } from "../lib/vaif";
126
- import type { ReactNode } from "react";
127
-
128
- interface Props {
129
- children: ReactNode;
130
- }
131
-
132
- export function VaifProvider({ children }: Props) {
133
- return <Provider client={vaif}>{children}</Provider>;
134
- }
135
- `},{path:".env.example",content:`# VAIF Configuration
136
- # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
137
-
138
- VITE_VAIF_PROJECT_ID=your-project-id
139
- VITE_VAIF_API_KEY=your-anon-key
140
- `}],dependencies:["@vaiftech/client","@vaiftech/react"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Wrap your <App /> with <VaifProvider> in main.tsx","Import { vaif } from './lib/vaif' to query your database","Run: npx vaif generate to generate TypeScript types"]},"ios-swift-app":{name:"iOS Swift App",description:"Swift client manager for iOS/macOS apps using Swift Package Manager",tag:"Swift / iOS",files:[{path:"VaifManager.swift",content:`import Foundation
141
- import VaifClient
142
-
143
- /// Singleton manager for the VAIF client.
144
- /// Add your project ID and API key in the initialiser or load from a config file.
145
- @MainActor
146
- final class VaifManager: ObservableObject {
147
- static let shared = VaifManager()
148
-
149
- let client: VaifClient
150
-
151
- @Published var isAuthenticated = false
152
-
153
- private init() {
154
- guard
155
- let projectId = ProcessInfo.processInfo.environment["VAIF_PROJECT_ID"]
156
- ?? Bundle.main.infoDictionary?["VAIF_PROJECT_ID"] as? String,
157
- let apiKey = ProcessInfo.processInfo.environment["VAIF_API_KEY"]
158
- ?? Bundle.main.infoDictionary?["VAIF_API_KEY"] as? String
159
- else {
160
- fatalError("VAIF_PROJECT_ID and VAIF_API_KEY must be set")
161
- }
162
-
163
- self.client = VaifClient(
164
- projectId: projectId,
165
- apiKey: apiKey
166
- )
167
- }
168
-
169
- // MARK: - Auth helpers
170
-
171
- func signIn(email: String, password: String) async throws {
172
- try await client.auth.signIn(email: email, password: password)
173
- isAuthenticated = true
174
- }
175
-
176
- func signOut() async throws {
177
- try await client.auth.signOut()
178
- isAuthenticated = false
179
- }
180
-
181
- // MARK: - Database helpers
182
-
183
- func query<T: Decodable>(_ table: String, type: T.Type) async throws -> [T] {
184
- return try await client.from(table).select().execute().value
185
- }
186
-
187
- func insert<T: Encodable>(_ table: String, values: T) async throws {
188
- try await client.from(table).insert(values).execute()
189
- }
190
- }
191
- `},{path:".env.example",content:`# VAIF Configuration
192
- # Add these to your Xcode scheme environment variables or Info.plist
193
-
194
- VAIF_PROJECT_ID=your-project-id
195
- VAIF_API_KEY=your-anon-key
196
- `},{path:"README-VAIF.md",content:`# VAIF Swift Setup
197
-
198
- ## 1. Add the Swift Package
199
-
200
- In Xcode: **File \u2192 Add Package Dependencies\u2026**
201
-
202
- Enter the repository URL:
203
- \`\`\`
204
- https://github.com/vaif-technologies/vaif-swift
205
- \`\`\`
206
-
207
- Select the **VaifClient** library and add it to your target.
208
-
209
- ## 2. Configure Environment
210
-
211
- Add your project credentials to your Xcode scheme:
212
-
213
- 1. Edit Scheme \u2192 Run \u2192 Arguments \u2192 Environment Variables
214
- 2. Add \`VAIF_PROJECT_ID\` and \`VAIF_API_KEY\`
215
-
216
- Or add them to **Info.plist**:
217
- \`\`\`xml
218
- <key>VAIF_PROJECT_ID</key>
219
- <string>your-project-id</string>
220
- <key>VAIF_API_KEY</key>
221
- <string>your-anon-key</string>
222
- \`\`\`
223
-
224
- ## 3. Usage
225
-
226
- \`\`\`swift
227
- import SwiftUI
228
-
229
- struct ContentView: View {
230
- @StateObject private var vaif = VaifManager.shared
231
-
232
- var body: some View {
233
- // Use vaif.client to interact with your project
234
- Text("Connected to VAIF")
235
- }
236
- }
237
- \`\`\`
238
-
239
- ## 4. Generate Types
240
-
241
- Run the VAIF CLI to generate Swift models from your schema:
242
-
243
- \`\`\`bash
244
- npx @vaiftech/cli generate --output ./Models/Database.swift --lang swift
245
- \`\`\`
246
- `}],postInstructions:["Add the VaifClient Swift package from https://github.com/vaif-technologies/vaif-swift","Add VAIF_PROJECT_ID and VAIF_API_KEY to your Xcode scheme environment","See README-VAIF.md for full setup instructions"]},"expo-mobile-app":{name:"Expo Mobile App",description:"React Native / Expo app with VAIF client configured for mobile",tag:"Expo / React Native",files:[{path:"lib/vaif.ts",content:`import { createExpoClient } from "@vaiftech/sdk-expo";
247
- import AsyncStorage from "@react-native-async-storage/async-storage";
248
-
249
- export const vaif = createExpoClient({
250
- projectId: process.env.EXPO_PUBLIC_VAIF_PROJECT_ID!,
251
- apiKey: process.env.EXPO_PUBLIC_VAIF_API_KEY!,
252
- storage: AsyncStorage,
253
- // Realtime is enabled by default on the Expo client
254
- realtime: {
255
- enabled: true,
256
- },
257
- });
258
- `},{path:"app.config.ts",content:`import { ExpoConfig, ConfigContext } from "expo/config";
259
-
260
- export default ({ config }: ConfigContext): ExpoConfig => ({
261
- ...config,
262
- name: "my-vaif-app",
263
- slug: "my-vaif-app",
264
- extra: {
265
- // These are available via process.env.EXPO_PUBLIC_* in SDK 49+
266
- // Set them in .env and they will be embedded at build time
267
- vaifProjectId: process.env.EXPO_PUBLIC_VAIF_PROJECT_ID,
268
- vaifApiKey: process.env.EXPO_PUBLIC_VAIF_API_KEY,
269
- },
270
- });
271
- `},{path:".env.example",content:`# VAIF Configuration
272
- # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
273
-
274
- EXPO_PUBLIC_VAIF_PROJECT_ID=your-project-id
275
- EXPO_PUBLIC_VAIF_API_KEY=your-anon-key
276
- `}],dependencies:["@vaiftech/sdk-expo","@react-native-async-storage/async-storage"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Import { vaif } from './lib/vaif' in your screens","The Expo client persists auth tokens via AsyncStorage automatically","Run: npx vaif generate to generate TypeScript types"]},"flutter-app":{name:"Flutter App",description:"Dart/Flutter client setup with environment configuration",tag:"Flutter / Dart",files:[{path:"lib/vaif_client.dart",content:`import 'package:vaif_client/vaif_client.dart';
277
- import 'package:flutter_dotenv/flutter_dotenv.dart';
278
-
279
- /// Global VAIF client instance.
280
- ///
281
- /// Initialise by calling [initVaif] in your main() before runApp().
282
- late final VaifClient vaif;
283
-
284
- Future<void> initVaif() async {
285
- await dotenv.load(fileName: '.env');
286
-
287
- final projectId = dotenv.env['VAIF_PROJECT_ID'];
288
- final apiKey = dotenv.env['VAIF_API_KEY'];
289
-
290
- if (projectId == null || apiKey == null) {
291
- throw Exception(
292
- 'VAIF_PROJECT_ID and VAIF_API_KEY must be set in .env',
293
- );
294
- }
295
-
296
- vaif = VaifClient(
297
- projectId: projectId,
298
- apiKey: apiKey,
299
- // Enable realtime subscriptions
300
- realtime: const RealtimeConfig(enabled: true),
301
- );
302
- }
303
-
304
- /// Example: fetch rows from a table.
305
- Future<List<Map<String, dynamic>>> fetchRows(String table) async {
306
- final response = await vaif.from(table).select().execute();
307
- return List<Map<String, dynamic>>.from(response.data);
308
- }
309
-
310
- /// Example: insert a row.
311
- Future<void> insertRow(String table, Map<String, dynamic> values) async {
312
- await vaif.from(table).insert(values).execute();
313
- }
314
-
315
- /// Example: subscribe to realtime changes.
316
- void subscribeToTable(
317
- String table,
318
- void Function(Map<String, dynamic> payload) onEvent,
319
- ) {
320
- vaif.realtime.channel(table).on(
321
- RealtimeListenTypes.postgresChanges,
322
- ChannelFilter(event: '*', schema: 'public', table: table),
323
- (payload, [ref]) => onEvent(payload),
324
- ).subscribe();
325
- }
326
- `},{path:".env.example",content:`# VAIF Configuration
327
- # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
328
-
329
- VAIF_PROJECT_ID=your-project-id
330
- VAIF_API_KEY=your-anon-key
331
- `},{path:"README-VAIF.md",content:`# VAIF Flutter Setup
332
-
333
- ## 1. Add Dependencies
334
-
335
- Add the following to your \`pubspec.yaml\`:
336
-
337
- \`\`\`yaml
338
- dependencies:
339
- vaif_client: ^1.0.0
340
- flutter_dotenv: ^5.1.0
341
- \`\`\`
342
-
343
- Then run:
344
- \`\`\`bash
345
- flutter pub get
346
- \`\`\`
347
-
348
- ## 2. Configure Environment
349
-
350
- Copy \`.env.example\` to \`.env\` and fill in your credentials.
351
-
352
- Add the \`.env\` file to your \`pubspec.yaml\` assets:
353
-
354
- \`\`\`yaml
355
- flutter:
356
- assets:
357
- - .env
358
- \`\`\`
359
-
360
- ## 3. Initialise in main.dart
361
-
362
- \`\`\`dart
363
- import 'package:flutter/material.dart';
364
- import 'lib/vaif_client.dart';
365
-
366
- void main() async {
367
- WidgetsFlutterBinding.ensureInitialized();
368
- await initVaif();
369
- runApp(const MyApp());
370
- }
371
- \`\`\`
372
-
373
- ## 4. Usage
374
-
375
- \`\`\`dart
376
- // Query data
377
- final todos = await vaif.from('todos').select().execute();
378
-
379
- // Insert data
380
- await vaif.from('todos').insert({'title': 'Buy milk', 'done': false}).execute();
381
-
382
- // Realtime subscription
383
- vaif.realtime.channel('todos').on(
384
- RealtimeListenTypes.postgresChanges,
385
- ChannelFilter(event: '*', schema: 'public', table: 'todos'),
386
- (payload, [ref]) {
387
- print('Change: $payload');
388
- },
389
- ).subscribe();
390
- \`\`\`
391
- `}],postInstructions:["Add vaif_client and flutter_dotenv to your pubspec.yaml (see README-VAIF.md)","Copy .env.example to .env and fill in your project credentials","Call initVaif() in main() before runApp()","See README-VAIF.md for full setup instructions"]},"python-fastapi-backend":{name:"Python FastAPI Backend",description:"FastAPI backend with VAIF client, auth middleware, and type-safe queries",tag:"Python / FastAPI",files:[{path:"vaif_client.py",content:`"""VAIF client setup and auth middleware for FastAPI."""
392
-
393
- import os
394
- from functools import lru_cache
395
- from typing import Optional
396
-
397
- from dotenv import load_dotenv
398
- from fastapi import Depends, HTTPException, Request, status
399
- from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
400
- from vaif import Client, ServiceClient
401
-
402
- load_dotenv()
403
-
404
- VAIF_PROJECT_ID = os.environ["VAIF_PROJECT_ID"]
405
- VAIF_API_KEY = os.environ["VAIF_API_KEY"]
406
- VAIF_SECRET_KEY = os.environ["VAIF_SECRET_KEY"]
407
-
408
-
409
- @lru_cache()
410
- def get_vaif_client() -> Client:
411
- """Public client using the anon key (respects Row Level Security)."""
412
- return Client(
413
- project_id=VAIF_PROJECT_ID,
414
- api_key=VAIF_API_KEY,
415
- )
416
-
417
-
418
- @lru_cache()
419
- def get_vaif_admin() -> ServiceClient:
420
- """Admin/service client that bypasses RLS. Use with caution."""
421
- return ServiceClient(
422
- project_id=VAIF_PROJECT_ID,
423
- secret_key=VAIF_SECRET_KEY,
424
- )
425
-
426
-
427
- # \u2500\u2500 Auth middleware \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
428
-
429
- security = HTTPBearer(auto_error=False)
430
-
431
-
432
- async def get_current_user(
433
- request: Request,
434
- credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
435
- ):
436
- """FastAPI dependency that validates VAIF auth tokens.
437
-
438
- Usage:
439
- @app.get("/protected")
440
- async def protected_route(user=Depends(get_current_user)):
441
- return {"user_id": user["id"]}
442
- """
443
- if credentials is None:
444
- raise HTTPException(
445
- status_code=status.HTTP_401_UNAUTHORIZED,
446
- detail="Missing authorization header",
447
- )
448
-
449
- client = get_vaif_admin()
450
- try:
451
- user = await client.auth.get_user(credentials.credentials)
452
- except Exception as exc:
453
- raise HTTPException(
454
- status_code=status.HTTP_401_UNAUTHORIZED,
455
- detail=f"Invalid token: {exc}",
456
- )
457
-
458
- if user is None:
459
- raise HTTPException(
460
- status_code=status.HTTP_401_UNAUTHORIZED,
461
- detail="Invalid or expired token",
462
- )
463
-
464
- return user
465
-
466
-
467
- # \u2500\u2500 Convenience query helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
468
-
469
-
470
- async def query_table(table: str, filters: Optional[dict] = None):
471
- """Quick helper to query a table with optional filters."""
472
- client = get_vaif_client()
473
- q = client.from_(table).select("*")
474
- if filters:
475
- for key, value in filters.items():
476
- q = q.eq(key, value)
477
- return await q.execute()
478
-
479
-
480
- async def insert_row(table: str, data: dict):
481
- """Insert a single row and return the result."""
482
- client = get_vaif_client()
483
- return await client.from_(table).insert(data).execute()
484
- `},{path:".env.example",content:`# VAIF Configuration
485
- # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
486
-
487
- VAIF_PROJECT_ID=your-project-id
488
- VAIF_API_KEY=your-anon-key
489
- VAIF_SECRET_KEY=your-secret-key
490
- `},{path:"requirements.txt",content:`vaif-client>=1.0.0
491
- fastapi>=0.110.0
492
- uvicorn[standard]>=0.27.0
493
- python-dotenv>=1.0.0
494
- `}],postInstructions:["Install dependencies: pip install -r requirements.txt","Copy .env.example to .env and fill in your project credentials","Use get_current_user as a FastAPI Depends() for protected routes","Run your server: uvicorn main:app --reload"]},"go-backend-api":{name:"Go Backend API",description:"Go backend with VAIF client initialisation and HTTP middleware",tag:"Go",files:[{path:"vaif/client.go",content:`package vaif
495
-
496
- import (
497
- "fmt"
498
- "net/http"
499
- "os"
500
- "strings"
501
-
502
- vaifclient "github.com/vaif-technologies/vaif-go"
503
- )
504
-
505
- // Client is the global VAIF client instance.
506
- // Initialise by calling Init() at application start.
507
- var Client *vaifclient.Client
508
-
509
- // Init creates the VAIF client from environment variables.
510
- // Call this in main() before starting your HTTP server.
511
- func Init() error {
512
- projectID := os.Getenv("VAIF_PROJECT_ID")
513
- apiKey := os.Getenv("VAIF_API_KEY")
514
- secretKey := os.Getenv("VAIF_SECRET_KEY")
515
-
516
- if projectID == "" || apiKey == "" {
517
- return fmt.Errorf("VAIF_PROJECT_ID and VAIF_API_KEY must be set")
518
- }
519
-
520
- var err error
521
- Client, err = vaifclient.NewClient(vaifclient.Config{
522
- ProjectID: projectID,
523
- APIKey: apiKey,
524
- SecretKey: secretKey,
525
- })
526
- if err != nil {
527
- return fmt.Errorf("failed to create VAIF client: %w", err)
528
- }
529
-
530
- return nil
531
- }
532
-
533
- // AuthMiddleware validates the VAIF auth token from the Authorization header.
534
- // It injects the authenticated user into the request context.
535
- func AuthMiddleware(next http.Handler) http.Handler {
536
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
537
- auth := r.Header.Get("Authorization")
538
- if auth == "" {
539
- http.Error(w, "missing authorization header", http.StatusUnauthorized)
540
- return
541
- }
542
-
543
- token := strings.TrimPrefix(auth, "Bearer ")
544
- if token == auth {
545
- http.Error(w, "invalid authorization format", http.StatusUnauthorized)
546
- return
547
- }
548
-
549
- user, err := Client.Auth.GetUser(r.Context(), token)
550
- if err != nil {
551
- http.Error(w, "invalid or expired token", http.StatusUnauthorized)
552
- return
553
- }
554
-
555
- ctx := vaifclient.WithUser(r.Context(), user)
556
- next.ServeHTTP(w, r.WithContext(ctx))
557
- })
558
- }
559
- `},{path:".env.example",content:`# VAIF Configuration
560
- # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
561
-
562
- VAIF_PROJECT_ID=your-project-id
563
- VAIF_API_KEY=your-anon-key
564
- VAIF_SECRET_KEY=your-secret-key
565
- `},{path:"README-VAIF.md",content:`# VAIF Go Setup
566
-
567
- ## 1. Install the Go Client
568
-
569
- \`\`\`bash
570
- go get github.com/vaif-technologies/vaif-go
571
- \`\`\`
572
-
573
- ## 2. Configure Environment
574
-
575
- Copy \`.env.example\` to \`.env\` and fill in your credentials.
576
-
577
- Use a library like [godotenv](https://github.com/joho/godotenv) to load the file:
578
-
579
- \`\`\`bash
580
- go get github.com/joho/godotenv
581
- \`\`\`
582
-
583
- ## 3. Initialise in main.go
584
-
585
- \`\`\`go
586
- package main
587
-
588
- import (
589
- "log"
590
- "net/http"
591
-
592
- "github.com/joho/godotenv"
593
- "yourmodule/vaif"
594
- )
595
-
596
- func main() {
597
- _ = godotenv.Load()
598
-
599
- if err := vaif.Init(); err != nil {
600
- log.Fatalf("Failed to initialise VAIF: %v", err)
601
- }
602
-
603
- mux := http.NewServeMux()
604
-
605
- // Public routes
606
- mux.HandleFunc("/health", healthHandler)
607
-
608
- // Protected routes
609
- protected := vaif.AuthMiddleware(http.HandlerFunc(protectedHandler))
610
- mux.Handle("/api/data", protected)
611
-
612
- log.Println("Server running on :8080")
613
- log.Fatal(http.ListenAndServe(":8080", mux))
614
- }
615
-
616
- func healthHandler(w http.ResponseWriter, r *http.Request) {
617
- w.Write([]byte("ok"))
618
- }
619
-
620
- func protectedHandler(w http.ResponseWriter, r *http.Request) {
621
- w.Write([]byte("authenticated"))
622
- }
623
- \`\`\`
624
-
625
- ## 4. Query Data
626
-
627
- \`\`\`go
628
- // Fetch rows
629
- rows, err := vaif.Client.From("todos").Select("*").Execute(ctx)
630
-
631
- // Insert a row
632
- _, err := vaif.Client.From("todos").Insert(map[string]interface{}{
633
- "title": "Buy milk",
634
- "done": false,
635
- }).Execute(ctx)
636
- \`\`\`
637
- `}],postInstructions:["Run: go get github.com/vaif-technologies/vaif-go","Copy .env.example to .env and fill in your project credentials","Call vaif.Init() in main() before starting your server","See README-VAIF.md for full setup instructions"]},"todo-app":{name:"Todo App",description:"Simple React todo app \u2013 great for learning VAIF basics",tag:"React Starter",files:[{path:"src/lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
638
-
639
- export const vaif = createClient({
640
- projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
641
- apiKey: import.meta.env.VITE_VAIF_API_KEY,
642
- });
643
-
644
- // Typed helpers for the todos table
645
- export interface Todo {
646
- id: string;
647
- title: string;
648
- done: boolean;
649
- created_at: string;
650
- user_id?: string;
651
- }
652
-
653
- export async function getTodos(): Promise<Todo[]> {
654
- const { data, error } = await vaif
655
- .from("todos")
656
- .select("*")
657
- .order("created_at", { ascending: false });
658
-
659
- if (error) throw error;
660
- return data as Todo[];
661
- }
662
-
663
- export async function addTodo(title: string): Promise<Todo> {
664
- const { data, error } = await vaif
665
- .from("todos")
666
- .insert({ title, done: false })
667
- .select()
668
- .single();
669
-
670
- if (error) throw error;
671
- return data as Todo;
672
- }
673
-
674
- export async function toggleTodo(id: string, done: boolean): Promise<void> {
675
- const { error } = await vaif
676
- .from("todos")
677
- .update({ done })
678
- .eq("id", id);
679
-
680
- if (error) throw error;
681
- }
682
-
683
- export async function deleteTodo(id: string): Promise<void> {
684
- const { error } = await vaif
685
- .from("todos")
686
- .delete()
687
- .eq("id", id);
688
-
689
- if (error) throw error;
690
- }
691
- `},{path:".env.example",content:`# VAIF Configuration
692
- # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
693
-
694
- VITE_VAIF_PROJECT_ID=your-project-id
695
- VITE_VAIF_API_KEY=your-anon-key
696
- `}],dependencies:["@vaiftech/client","@vaiftech/react"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Create a 'todos' table in your VAIF dashboard with columns: id (uuid), title (text), done (boolean), created_at (timestamptz)","Import helpers from './lib/vaif' in your components","Run: npx vaif generate to generate TypeScript types"]},"realtime-chat":{name:"Realtime Chat",description:"React chat app with VAIF realtime subscriptions for live messaging",tag:"React + Realtime",files:[{path:"src/lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
697
-
698
- export const vaif = createClient({
699
- projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
700
- apiKey: import.meta.env.VITE_VAIF_API_KEY,
701
- realtime: {
702
- enabled: true,
703
- // Automatically reconnect on connection loss
704
- reconnect: true,
705
- reconnectInterval: 1000,
706
- maxReconnectAttempts: 10,
707
- },
708
- });
709
-
710
- export interface Message {
711
- id: string;
712
- content: string;
713
- user_id: string;
714
- username: string;
715
- channel_id: string;
716
- created_at: string;
717
- }
718
-
719
- export async function sendMessage(
720
- channelId: string,
721
- content: string,
722
- userId: string,
723
- username: string,
724
- ): Promise<Message> {
725
- const { data, error } = await vaif
726
- .from("messages")
727
- .insert({
728
- content,
729
- user_id: userId,
730
- username,
731
- channel_id: channelId,
732
- })
733
- .select()
734
- .single();
735
-
736
- if (error) throw error;
737
- return data as Message;
738
- }
739
-
740
- export async function getMessages(channelId: string, limit = 50): Promise<Message[]> {
741
- const { data, error } = await vaif
742
- .from("messages")
743
- .select("*")
744
- .eq("channel_id", channelId)
745
- .order("created_at", { ascending: true })
746
- .limit(limit);
747
-
748
- if (error) throw error;
749
- return data as Message[];
750
- }
751
- `},{path:"src/hooks/useRealtimeMessages.ts",content:`import { useEffect, useState, useCallback } from "react";
752
- import { vaif, type Message, getMessages } from "../lib/vaif";
753
-
754
- interface UseRealtimeMessagesOptions {
755
- channelId: string;
756
- initialLimit?: number;
757
- }
758
-
759
- /**
760
- * Hook that subscribes to realtime message changes on a channel.
761
- *
762
- * Usage:
763
- * const { messages, isLoading, error } = useRealtimeMessages({
764
- * channelId: "general",
765
- * });
766
- */
767
- export function useRealtimeMessages({
768
- channelId,
769
- initialLimit = 50,
770
- }: UseRealtimeMessagesOptions) {
771
- const [messages, setMessages] = useState<Message[]>([]);
772
- const [isLoading, setIsLoading] = useState(true);
773
- const [error, setError] = useState<Error | null>(null);
774
-
775
- // Load initial messages
776
- useEffect(() => {
777
- let cancelled = false;
778
-
779
- async function load() {
780
- try {
781
- setIsLoading(true);
782
- const data = await getMessages(channelId, initialLimit);
783
- if (!cancelled) {
784
- setMessages(data);
785
- setError(null);
786
- }
787
- } catch (err) {
788
- if (!cancelled) {
789
- setError(err instanceof Error ? err : new Error(String(err)));
790
- }
791
- } finally {
792
- if (!cancelled) setIsLoading(false);
793
- }
794
- }
795
-
796
- load();
797
- return () => { cancelled = true; };
798
- }, [channelId, initialLimit]);
799
-
800
- // Subscribe to realtime changes
801
- useEffect(() => {
802
- const subscription = vaif
803
- .channel(\`messages:\${channelId}\`)
804
- .on(
805
- "postgres_changes",
806
- {
807
- event: "*",
808
- schema: "public",
809
- table: "messages",
810
- filter: \`channel_id=eq.\${channelId}\`,
811
- },
812
- (payload) => {
813
- if (payload.eventType === "INSERT") {
814
- setMessages((prev) => [...prev, payload.new as Message]);
815
- } else if (payload.eventType === "UPDATE") {
816
- setMessages((prev) =>
817
- prev.map((msg) =>
818
- msg.id === (payload.new as Message).id
819
- ? (payload.new as Message)
820
- : msg,
821
- ),
822
- );
823
- } else if (payload.eventType === "DELETE") {
824
- setMessages((prev) =>
825
- prev.filter((msg) => msg.id !== (payload.old as Message).id),
826
- );
827
- }
828
- },
829
- )
830
- .subscribe();
831
-
832
- return () => {
833
- subscription.unsubscribe();
834
- };
835
- }, [channelId]);
836
-
837
- const refresh = useCallback(async () => {
838
- const data = await getMessages(channelId, initialLimit);
839
- setMessages(data);
840
- }, [channelId, initialLimit]);
841
-
842
- return { messages, isLoading, error, refresh };
843
- }
844
- `},{path:".env.example",content:`# VAIF Configuration
845
- # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
846
-
847
- VITE_VAIF_PROJECT_ID=your-project-id
848
- VITE_VAIF_API_KEY=your-anon-key
849
- `}],dependencies:["@vaiftech/client","@vaiftech/react"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Create a 'messages' table with columns: id (uuid), content (text), user_id (text), username (text), channel_id (text), created_at (timestamptz)","Enable Realtime on the messages table in your VAIF dashboard","Use the useRealtimeMessages hook in your components","Run: npx vaif generate to generate TypeScript types"]},"saas-starter":{name:"SaaS Starter",description:"Full SaaS starter with VAIF auth, team/org support, and server-side helpers",tag:"Next.js SaaS",files:[{path:"lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
850
- import { createServerClient } from "@vaiftech/client/server";
851
-
852
- // Browser client \u2013 use in Client Components
853
- export const vaif = createClient({
854
- projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
855
- apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
856
- });
857
-
858
- // Server client \u2013 use in Server Components, Route Handlers, Server Actions
859
- export function createVaifServer() {
860
- return createServerClient({
861
- projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
862
- secretKey: process.env.VAIF_SECRET_KEY!,
863
- });
864
- }
865
- `},{path:"lib/auth.ts",content:`import { createVaifServer } from "./vaif";
866
-
867
- // \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
868
-
869
- export async function getCurrentUser() {
870
- const vaif = createVaifServer();
871
- const { data: { user }, error } = await vaif.auth.getUser();
872
- if (error || !user) return null;
873
- return user;
874
- }
875
-
876
- export async function requireUser() {
877
- const user = await getCurrentUser();
878
- if (!user) throw new Error("Unauthorized");
879
- return user;
880
- }
881
-
882
- // \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
883
-
884
- export interface Team {
885
- id: string;
886
- name: string;
887
- slug: string;
888
- owner_id: string;
889
- created_at: string;
890
- }
891
-
892
- export interface TeamMember {
893
- id: string;
894
- team_id: string;
895
- user_id: string;
896
- role: "owner" | "admin" | "member" | "viewer";
897
- joined_at: string;
898
- }
899
-
900
- export async function getUserTeams(userId: string): Promise<Team[]> {
901
- const vaif = createVaifServer();
902
-
903
- // Get team IDs the user belongs to
904
- const { data: memberships, error: memberError } = await vaif
905
- .from("team_members")
906
- .select("team_id")
907
- .eq("user_id", userId);
908
-
909
- if (memberError) throw memberError;
910
- if (!memberships?.length) return [];
911
-
912
- const teamIds = memberships.map((m) => m.team_id);
913
-
914
- const { data: teams, error: teamError } = await vaif
915
- .from("teams")
916
- .select("*")
917
- .in("id", teamIds)
918
- .order("name");
919
-
920
- if (teamError) throw teamError;
921
- return (teams ?? []) as Team[];
922
- }
923
-
924
- export async function getTeamMembers(teamId: string): Promise<TeamMember[]> {
925
- const vaif = createVaifServer();
926
-
927
- const { data, error } = await vaif
928
- .from("team_members")
929
- .select("*")
930
- .eq("team_id", teamId)
931
- .order("joined_at");
932
-
933
- if (error) throw error;
934
- return (data ?? []) as TeamMember[];
935
- }
936
-
937
- export async function createTeam(name: string, slug: string): Promise<Team> {
938
- const user = await requireUser();
939
- const vaif = createVaifServer();
940
-
941
- const { data: team, error } = await vaif
942
- .from("teams")
943
- .insert({ name, slug, owner_id: user.id })
944
- .select()
945
- .single();
946
-
947
- if (error) throw error;
948
-
949
- // Add the creator as owner
950
- await vaif.from("team_members").insert({
951
- team_id: team.id,
952
- user_id: user.id,
953
- role: "owner",
954
- });
955
-
956
- return team as Team;
957
- }
958
-
959
- export async function inviteToTeam(
960
- teamId: string,
961
- email: string,
962
- role: TeamMember["role"] = "member",
963
- ): Promise<void> {
964
- const vaif = createVaifServer();
965
-
966
- // Look up user by email
967
- const { data: users } = await vaif
968
- .from("users")
969
- .select("id")
970
- .eq("email", email)
971
- .limit(1);
972
-
973
- if (!users?.length) {
974
- throw new Error("User not found. They must create an account first.");
975
- }
976
-
977
- const { error } = await vaif.from("team_members").insert({
978
- team_id: teamId,
979
- user_id: users[0].id,
980
- role,
981
- });
982
-
983
- if (error) throw error;
984
- }
985
-
986
- // \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
987
-
988
- export async function requireTeamRole(
989
- teamId: string,
990
- requiredRoles: TeamMember["role"][],
991
- ): Promise<TeamMember> {
992
- const user = await requireUser();
993
- const vaif = createVaifServer();
994
-
995
- const { data: member, error } = await vaif
996
- .from("team_members")
997
- .select("*")
998
- .eq("team_id", teamId)
999
- .eq("user_id", user.id)
1000
- .single();
1001
-
1002
- if (error || !member) {
1003
- throw new Error("Not a member of this team");
1004
- }
1005
-
1006
- if (!requiredRoles.includes(member.role)) {
1007
- throw new Error(\`Requires one of: \${requiredRoles.join(", ")}\`);
1008
- }
1009
-
1010
- return member as TeamMember;
1011
- }
1012
- `},{path:".env.example",content:`# VAIF Configuration
1013
- # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
1014
-
1015
- NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
1016
- NEXT_PUBLIC_VAIF_API_KEY=your-anon-key
1017
- VAIF_SECRET_KEY=your-secret-key
1018
- `}],dependencies:["@vaiftech/client","@vaiftech/auth","@vaiftech/react"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create 'teams' and 'team_members' tables in your VAIF dashboard","Import auth helpers from '@/lib/auth' in your Server Components/Actions","Use requireUser() for authenticated routes and requireTeamRole() for role checks","Run: npx vaif generate to generate TypeScript types"]},"ecommerce-api":{name:"E-commerce API",description:"API-first e-commerce setup with VAIF storage for product images",tag:"Next.js E-commerce",files:[{path:"lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
1019
- import { createServerClient } from "@vaiftech/client/server";
1020
-
1021
- // Browser client
1022
- export const vaif = createClient({
1023
- projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
1024
- apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
1025
- });
1026
-
1027
- // Server client
1028
- export function createVaifServer() {
1029
- return createServerClient({
1030
- projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
1031
- secretKey: process.env.VAIF_SECRET_KEY!,
1032
- });
1033
- }
1034
- `},{path:"lib/storage.ts",content:`import { createVaifServer } from "./vaif";
1035
-
1036
- const PRODUCT_IMAGES_BUCKET = "product-images";
1037
-
1038
- interface UploadResult {
1039
- path: string;
1040
- publicUrl: string;
1041
- }
1042
-
1043
- /**
1044
- * Upload a product image to VAIF Storage.
1045
- *
1046
- * @param file - The file buffer or Blob to upload
1047
- * @param productId - Product ID used to organise files in folders
1048
- * @param fileName - Original filename (will be sanitised)
1049
- * @returns The storage path and public URL
1050
- */
1051
- export async function uploadProductImage(
1052
- file: Buffer | Blob,
1053
- productId: string,
1054
- fileName: string,
1055
- ): Promise<UploadResult> {
1056
- const vaif = createVaifServer();
1057
-
1058
- // Sanitise filename and build path
1059
- const sanitised = fileName.replace(/[^a-zA-Z0-9._-]/g, "_");
1060
- const storagePath = \`\${productId}/\${Date.now()}-\${sanitised}\`;
1061
-
1062
- const { data, error } = await vaif.storage
1063
- .from(PRODUCT_IMAGES_BUCKET)
1064
- .upload(storagePath, file, {
1065
- contentType: getContentType(fileName),
1066
- upsert: false,
1067
- });
1068
-
1069
- if (error) throw error;
1070
-
1071
- const { data: urlData } = vaif.storage
1072
- .from(PRODUCT_IMAGES_BUCKET)
1073
- .getPublicUrl(data.path);
1074
-
1075
- return {
1076
- path: data.path,
1077
- publicUrl: urlData.publicUrl,
1078
- };
1079
- }
1080
-
1081
- /**
1082
- * Delete a product image from storage.
1083
- */
1084
- export async function deleteProductImage(storagePath: string): Promise<void> {
1085
- const vaif = createVaifServer();
1086
-
1087
- const { error } = await vaif.storage
1088
- .from(PRODUCT_IMAGES_BUCKET)
1089
- .remove([storagePath]);
1090
-
1091
- if (error) throw error;
1092
- }
1093
-
1094
- /**
1095
- * Generate a signed URL for a private product image.
1096
- *
1097
- * @param storagePath - The path returned from uploadProductImage
1098
- * @param expiresIn - Seconds until the URL expires (default: 1 hour)
1099
- */
1100
- export async function getSignedImageUrl(
1101
- storagePath: string,
1102
- expiresIn = 3600,
1103
- ): Promise<string> {
1104
- const vaif = createVaifServer();
1105
-
1106
- const { data, error } = await vaif.storage
1107
- .from(PRODUCT_IMAGES_BUCKET)
1108
- .createSignedUrl(storagePath, expiresIn);
1109
-
1110
- if (error) throw error;
1111
- return data.signedUrl;
1112
- }
1113
-
1114
- /**
1115
- * List all images for a product.
1116
- */
1117
- export async function listProductImages(productId: string) {
1118
- const vaif = createVaifServer();
1119
-
1120
- const { data, error } = await vaif.storage
1121
- .from(PRODUCT_IMAGES_BUCKET)
1122
- .list(productId, {
1123
- sortBy: { column: "created_at", order: "desc" },
1124
- });
1125
-
1126
- if (error) throw error;
1127
- return data;
1128
- }
1129
-
1130
- function getContentType(fileName: string): string {
1131
- const ext = fileName.split(".").pop()?.toLowerCase();
1132
- const mimeTypes: Record<string, string> = {
1133
- jpg: "image/jpeg",
1134
- jpeg: "image/jpeg",
1135
- png: "image/png",
1136
- gif: "image/gif",
1137
- webp: "image/webp",
1138
- svg: "image/svg+xml",
1139
- avif: "image/avif",
1140
- };
1141
- return mimeTypes[ext ?? ""] ?? "application/octet-stream";
1142
- }
1143
- `},{path:".env.example",content:`# VAIF Configuration
1144
- # Get these values from https://vaif.studio/dashboard \u2192 Project Settings \u2192 API Keys
1145
-
1146
- NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
1147
- NEXT_PUBLIC_VAIF_API_KEY=your-anon-key
1148
- VAIF_SECRET_KEY=your-secret-key
1149
- `}],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 le(){console.log(""),console.log(s.bold("Available project templates")),console.log("");let r=26,t=22;console.log(` ${s.gray("Template".padEnd(r))}${s.gray("Stack".padEnd(t))}${s.gray("Description")}`),console.log(s.gray(" "+"-".repeat(r+t+40)));for(let[n,e]of Object.entries(S))console.log(` ${s.cyan(n.padEnd(r))}${s.yellow(e.tag.padEnd(t))}${s.white(e.description)}`);console.log(""),console.log(s.gray("Usage:")),console.log(s.gray(" npx @vaiftech/cli init --template <name>")),console.log(s.gray(" npx @vaiftech/cli init -t nextjs-fullstack")),console.log("");}async function V(r,t={}){let n=S[r];n||(console.log(s.red(`
1150
- Unknown template: ${r}`)),console.log(s.yellow(`Run 'vaif templates' to see available templates.
1151
- `)),process.exit(1)),console.log(""),console.log(s.bold(`Scaffolding ${s.cyan(n.name)} template...`)),console.log("");let e=0,o=0;for(let a of n.files){let i=A.resolve(a.path),c=A.dirname(i);if(g.existsSync(c)||g.mkdirSync(c,{recursive:true}),g.existsSync(i)&&!t.force){console.log(s.yellow(` skip ${a.path} (already exists)`)),o++;continue}g.writeFileSync(i,a.content,"utf-8"),console.log(s.green(` create ${a.path}`)),e++;}console.log(""),e>0&&console.log(s.green(`Created ${e} file${e!==1?"s":""}.`)),o>0&&console.log(s.yellow(`Skipped ${o} file${o!==1?"s":""} (use --force to overwrite).`)),(n.dependencies?.length||n.devDependencies?.length)&&(console.log(""),console.log(s.bold("Install dependencies:")),n.dependencies?.length&&console.log(s.cyan(` npm install ${n.dependencies.join(" ")}`)),n.devDependencies?.length&&console.log(s.cyan(` npm install -D ${n.devDependencies.join(" ")}`))),n.postInstructions.length>0&&(console.log(""),console.log(s.bold("Next steps:")),n.postInstructions.forEach((a,i)=>{console.log(s.gray(` ${i+1}. ${a}`));})),console.log("");}var B={$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 ve(r){let t=K("Initializing VAIF configuration...").start(),n=A.resolve("vaif.config.json");g.existsSync(n)&&!r.force&&(t.fail("vaif.config.json already exists"),console.log(s.yellow(`
1152
- Use --force to overwrite existing configuration.`)),process.exit(1));try{if(g.writeFileSync(n,JSON.stringify(B,null,2),"utf-8"),t.succeed("Created vaif.config.json"),r.template)await V(r.template,{force:r.force});else {let e=A.resolve(".env.example");if(g.existsSync(e)||(g.writeFileSync(e,`# VAIF Configuration
1153
- DATABASE_URL=postgresql://user:password@localhost:5432/database
1154
- VAIF_API_KEY=your-api-key
1155
- `,"utf-8"),console.log(s.gray("Created .env.example"))),r.typescript){let o=A.resolve("src/types");g.existsSync(o)||(g.mkdirSync(o,{recursive:!0}),console.log(s.gray("Created src/types directory")));}console.log(""),console.log(s.green("VAIF initialized successfully!")),console.log(""),console.log(s.gray("Next steps:")),console.log(s.gray(" 1. Update vaif.config.json with your project ID")),console.log(s.gray(" 2. Set DATABASE_URL in your environment")),console.log(s.gray(" 3. Run: npx vaif generate")),console.log("");}}catch(e){t.fail("Failed to initialize"),e instanceof Error&&console.error(s.red(`
1156
- Error: ${e.message}`)),process.exit(1);}}export{P as a,ne as b,le as c,ve as d};