@vaiftech/cli 1.3.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,10 +1,10 @@
1
- 'use strict';var v=require('fs'),S=require('path'),M=require('dotenv'),N=require('pg'),L=require('ora'),u=require('chalk'),O=require('prettier'),k=require('readline');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var v__default=/*#__PURE__*/_interopDefault(v);var S__default=/*#__PURE__*/_interopDefault(S);var M__default=/*#__PURE__*/_interopDefault(M);var N__default=/*#__PURE__*/_interopDefault(N);var L__default=/*#__PURE__*/_interopDefault(L);var u__default=/*#__PURE__*/_interopDefault(u);var O__default=/*#__PURE__*/_interopDefault(O);var k__default=/*#__PURE__*/_interopDefault(k);M__default.default.config();async function x(r){let a=S__default.default.resolve(r);if(!v__default.default.existsSync(a))return null;try{let t=v__default.default.readFileSync(a,"utf-8"),e=JSON.parse(t);return e.database?.url&&(e.database.url=F(e.database.url)),e.api?.apiKey&&(e.api.apiKey=F(e.api.apiKey)),e}catch{throw new Error(`Failed to parse config file: ${r}`)}}function F(r){return r.replace(/\$\{([^}]+)\}/g,(a,t)=>process.env[t]||a)}async function j(r,a){let t=await r.query(`
1
+ 'use strict';var h=require('fs'),w=require('path'),M=require('dotenv'),K=require('pg'),z=require('ora'),m=require('chalk'),q=require('prettier'),D=require('readline');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var h__default=/*#__PURE__*/_interopDefault(h);var w__default=/*#__PURE__*/_interopDefault(w);var M__default=/*#__PURE__*/_interopDefault(M);var K__default=/*#__PURE__*/_interopDefault(K);var z__default=/*#__PURE__*/_interopDefault(z);var m__default=/*#__PURE__*/_interopDefault(m);var q__default=/*#__PURE__*/_interopDefault(q);var D__default=/*#__PURE__*/_interopDefault(D);M__default.default.config();async function E(n){let a=w__default.default.resolve(n);if(!h__default.default.existsSync(a))return null;try{let t=h__default.default.readFileSync(a,"utf-8"),e=JSON.parse(t);return e.database?.url&&(e.database.url=L(e.database.url)),e.api?.apiKey&&(e.api.apiKey=L(e.api.apiKey)),e}catch{throw new Error(`Failed to parse config file: ${n}`)}}function L(n){return n.replace(/\$\{([^}]+)\}/g,(a,t)=>process.env[t]||a)}async function B(n,a){let t=await n.query(`
2
2
  SELECT table_name, table_type
3
3
  FROM information_schema.tables
4
4
  WHERE table_schema = $1
5
5
  AND table_type = 'BASE TABLE'
6
6
  ORDER BY table_name
7
- `,[a]),e=await r.query(`
7
+ `,[a]),e=await n.query(`
8
8
  SELECT
9
9
  table_name,
10
10
  column_name,
@@ -19,7 +19,7 @@
19
19
  FROM information_schema.columns
20
20
  WHERE table_schema = $1
21
21
  ORDER BY table_name, ordinal_position
22
- `,[a]),o=await r.query(`
22
+ `,[a]),i=await n.query(`
23
23
  SELECT
24
24
  tc.constraint_name,
25
25
  tc.table_name,
@@ -35,7 +35,7 @@
35
35
  AND ccu.table_schema = tc.table_schema
36
36
  WHERE tc.constraint_type = 'FOREIGN KEY'
37
37
  AND tc.table_schema = $1
38
- `,[a]),i=await r.query(`
38
+ `,[a]),r=await n.query(`
39
39
  SELECT
40
40
  t.typname as enum_name,
41
41
  e.enumlabel as enum_value
@@ -44,22 +44,22 @@
44
44
  JOIN pg_namespace n ON n.oid = t.typnamespace
45
45
  WHERE n.nspname = $1
46
46
  ORDER BY t.typname, e.enumsortorder
47
- `,[a]),l=new Map;for(let n of t.rows)l.set(n.table_name,[]);for(let n of e.rows){let p=l.get(n.table_name);p&&p.push(n);}let s=new Map;for(let n of i.rows){let p=s.get(n.enum_name)||[];p.push(n.enum_value),s.set(n.enum_name,p);}return {tables:l,enums:s,foreignKeys:o.rows}}var w={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 $(r,a){let{data_type:t,udt_name:e,is_nullable:o}=r;if(a.has(e)){let s=a.get(e).map(n=>`"${n}"`).join(" | ");return o==="YES"?`(${s}) | null`:s}if(t==="ARRAY"){let l=e.replace(/^_/,"");if(a.has(l)){let p=a.get(l).map(c=>`"${c}"`).join(" | ");return o==="YES"?`(${p})[] | null`:`(${p})[]`}let s=w[l]||"unknown";return o==="YES"?`${s}[] | null`:`${s}[]`}let i=w[t]||w[e]||"unknown";return o==="YES"&&(i=`${i} | null`),i}function T(r){return r.split(/[_\-\s]+/).map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join("")}function K(r,a){let t=T(r),e=a.map(o=>` | "${o}"`).join(`
47
+ `,[a]),c=new Map;for(let l of t.rows)c.set(l.table_name,[]);for(let l of e.rows){let o=c.get(l.table_name);o&&o.push(l);}let u=new Map;for(let l of r.rows){let o=u.get(l.enum_name)||[];o.push(l.enum_value),u.set(l.enum_name,o);}return {tables:c,enums:u,foreignKeys:i.rows}}var S={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 $(n,a){let{data_type:t,udt_name:e,is_nullable:i}=n;if(a.has(e)){let u=a.get(e).map(l=>`"${l}"`).join(" | ");return i==="YES"?`(${u}) | null`:u}if(t==="ARRAY"){let c=e.replace(/^_/,"");if(a.has(c)){let o=a.get(c).map(s=>`"${s}"`).join(" | ");return i==="YES"?`(${o})[] | null`:`(${o})[]`}let u=S[c]||"unknown";return i==="YES"?`${u}[] | null`:`${u}[]`}let r=S[t]||S[e]||"unknown";return i==="YES"&&(r=`${r} | null`),r}function x(n){return n.split(/[_\-\s]+/).map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join("")}function Y(n,a){let t=x(n),e=a.map(i=>` | "${i}"`).join(`
48
48
  `);return `export type ${t} =
49
- ${e};`}function B(r,a,t){let e=T(r),o=[],i=[],l=[];for(let c of a){let d=$(c,t),f=c.column_name,_=c.column_default!==null||c.is_identity==="YES",I=c.is_nullable==="YES";o.push(` ${f}: ${d};`),_||c.column_name==="id"?i.push(` ${f}?: ${d.replace(" | null","")} | null;`):I?i.push(` ${f}?: ${d};`):i.push(` ${f}: ${d.replace(" | null","")};`),l.push(` ${f}?: ${d.replace(" | null","")} | null;`);}let s=`export interface ${e} {
50
- ${o.join(`
51
- `)}
52
- }`,n=`export interface ${e}Insert {
49
+ ${e};`}function G(n,a,t){let e=x(n),i=[],r=[],c=[];for(let s of a){let d=$(s,t),p=s.column_name,g=s.column_default!==null||s.is_identity==="YES",b=s.is_nullable==="YES";i.push(` ${p}: ${d};`),g||s.column_name==="id"?r.push(` ${p}?: ${d.replace(" | null","")} | null;`):b?r.push(` ${p}?: ${d};`):r.push(` ${p}: ${d.replace(" | null","")};`),c.push(` ${p}?: ${d.replace(" | null","")} | null;`);}let u=`export interface ${e} {
53
50
  ${i.join(`
54
51
  `)}
55
- }`,p=`export interface ${e}Update {
56
- ${l.join(`
52
+ }`,l=`export interface ${e}Insert {
53
+ ${r.join(`
54
+ `)}
55
+ }`,o=`export interface ${e}Update {
56
+ ${c.join(`
57
57
  `)}
58
- }`;return {base:s,insert:n,update:p}}function Y(r,a,t){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(a.size>0){e.push("// ============ ENUMS ============"),e.push("");for(let[i,l]of a)e.push(K(i,l)),e.push("");}e.push("// ============ TABLES ============"),e.push("");let o=[];for(let[i,l]of r){let{base:s,insert:n,update:p}=B(i,l,a);o.push(i),e.push(s),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 i of o){let l=T(i);e.push(` ${i}: {`),e.push(` Row: ${l};`),e.push(` Insert: ${l}Insert;`),e.push(` Update: ${l}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 q(r){let a=L__default.default("Loading configuration...").start();try{let t=await x(r.config),e=r.connection||t?.database?.url||process.env.DATABASE_URL;e||(a.fail("No database connection string provided"),console.log(u__default.default.yellow(`
60
- Provide a connection string via:`)),console.log(u__default.default.gray(" --connection <url>")),console.log(u__default.default.gray(" DATABASE_URL environment variable")),console.log(u__default.default.gray(" vaif.config.json database.url")),process.exit(1)),a.text="Connecting to database...";let o=new N__default.default.Client({connectionString:e});await o.connect(),a.text="Introspecting schema...";let{tables:i,enums:l,foreignKeys:s}=await j(o,r.schema);if(await o.end(),i.size===0){a.warn(`No tables found in schema "${r.schema}"`);return}a.text=`Generating types for ${i.size} tables...`;let n=Y(i,l,s),p=await O__default.default.format(n,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100});if(r.dryRun){a.succeed("Generated types (dry run):"),console.log(""),console.log(u__default.default.gray("\u2500".repeat(60))),console.log(p),console.log(u__default.default.gray("\u2500".repeat(60)));return}let c=S__default.default.resolve(r.output),d=S__default.default.dirname(c);v__default.default.existsSync(d)||v__default.default.mkdirSync(d,{recursive:!0}),v__default.default.writeFileSync(c,p,"utf-8"),a.succeed(`Generated types for ${i.size} tables \u2192 ${u__default.default.cyan(r.output)}`),console.log(""),console.log(u__default.default.green("Generated:")),console.log(u__default.default.gray(` Tables: ${i.size}`)),console.log(u__default.default.gray(` Enums: ${l.size}`)),console.log(""),console.log(u__default.default.gray("Import in your code:")),console.log(u__default.default.cyan(` import type { Database, Row, Insert, Update } from "${r.output.replace(/\.ts$/,"")}";`));}catch(t){a.fail("Failed to generate types"),t instanceof Error&&(console.error(u__default.default.red(`
61
- Error: ${t.message}`)),t.message.includes("ECONNREFUSED")&&console.log(u__default.default.yellow(`
62
- Make sure your database is running and accessible.`))),process.exit(1);}}var h=[{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"}],z={"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:`{
58
+ }`;return {base:u,insert:l,update:o}}function H(n,a,t){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(a.size>0){e.push("// ============ ENUMS ============"),e.push("");for(let[r,c]of a)e.push(Y(r,c)),e.push("");}e.push("// ============ TABLES ============"),e.push("");let i=[];for(let[r,c]of n){let{base:u,insert:l,update:o}=G(r,c,a);i.push(r),e.push(u),e.push(""),e.push(l),e.push(""),e.push(o),e.push("");}e.push("// ============ DATABASE SCHEMA ============"),e.push(""),e.push("export interface Database {");for(let r of i){let c=x(r);e.push(` ${r}: {`),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 W(n){let a=z__default.default("Loading configuration...").start();try{let t=await E(n.config),e=n.connection||t?.database?.url||process.env.DATABASE_URL;e||(a.fail("No database connection string provided"),console.log(m__default.default.yellow(`
60
+ Provide a connection string via:`)),console.log(m__default.default.gray(" --connection <url>")),console.log(m__default.default.gray(" DATABASE_URL environment variable")),console.log(m__default.default.gray(" vaif.config.json database.url")),process.exit(1)),a.text="Connecting to database...";let i=new K__default.default.Client({connectionString:e});await i.connect(),a.text="Introspecting schema...";let{tables:r,enums:c,foreignKeys:u}=await B(i,n.schema);if(await i.end(),r.size===0){a.warn(`No tables found in schema "${n.schema}"`);return}a.text=`Generating types for ${r.size} tables...`;let l=H(r,c,u),o=await q__default.default.format(l,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100});if(n.dryRun){a.succeed("Generated types (dry run):"),console.log(""),console.log(m__default.default.gray("\u2500".repeat(60))),console.log(o),console.log(m__default.default.gray("\u2500".repeat(60)));return}let s=w__default.default.resolve(n.output),d=w__default.default.dirname(s);h__default.default.existsSync(d)||h__default.default.mkdirSync(d,{recursive:!0}),h__default.default.writeFileSync(s,o,"utf-8"),a.succeed(`Generated types for ${r.size} tables \u2192 ${m__default.default.cyan(n.output)}`),console.log(""),console.log(m__default.default.green("Generated:")),console.log(m__default.default.gray(` Tables: ${r.size}`)),console.log(m__default.default.gray(` Enums: ${c.size}`)),console.log(""),console.log(m__default.default.gray("Import in your code:")),console.log(m__default.default.cyan(` import type { Database, Row, Insert, Update } from "${n.output.replace(/\.ts$/,"")}";`));}catch(t){a.fail("Failed to generate types"),t instanceof Error&&(console.error(m__default.default.red(`
61
+ Error: ${t.message}`)),t.message.includes("ECONNREFUSED")&&console.log(m__default.default.yellow(`
62
+ Make sure your database is running and accessible.`))),process.exit(1);}}var y=[{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"}],J={"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
63
  "name": "my-vaif-app",
64
64
  "private": true,
65
65
  "version": "0.1.0",
@@ -178,6 +178,101 @@ out
178
178
  .env
179
179
  .env.local
180
180
  *.local
181
+ `},{path:"README.md",content:`# My VAIF App \u2014 Next.js Full-Stack
182
+
183
+ A full-stack Next.js application powered by [VAIF Studio](https://vaif.studio), with server and client VAIF clients, auth middleware, and React hooks.
184
+
185
+ ## Prerequisites
186
+
187
+ - [Node.js](https://nodejs.org/) v18 or later
188
+ - npm (included with Node.js)
189
+ - A VAIF Studio account \u2014 sign up at <https://vaif.studio>
190
+
191
+ ## Setup
192
+
193
+ 1. **Install dependencies**
194
+
195
+ \\\`\\\`\\\`bash
196
+ npm install
197
+ \\\`\\\`\\\`
198
+
199
+ 2. **Configure credentials**
200
+
201
+ Copy the example environment file and fill in your project values:
202
+
203
+ \\\`\\\`\\\`bash
204
+ cp .env.local.example .env.local
205
+ \\\`\\\`\\\`
206
+
207
+ Get your Project ID, API Key, and Secret Key from <https://vaif.studio/dashboard> under **Project Settings > API Keys**.
208
+
209
+ 3. **Install and log in to the VAIF CLI**
210
+
211
+ \\\`\\\`\\\`bash
212
+ npm install -g @vaiftech/cli
213
+ vaif login
214
+ \\\`\\\`\\\`
215
+
216
+ 4. **Pull your database schema**
217
+
218
+ \\\`\\\`\\\`bash
219
+ vaif pull
220
+ \\\`\\\`\\\`
221
+
222
+ 5. **Push database migrations** (if using the database feature)
223
+
224
+ \\\`\\\`\\\`bash
225
+ vaif db push
226
+ \\\`\\\`\\\`
227
+
228
+ 6. **Deploy serverless functions** (if using the functions feature)
229
+
230
+ \\\`\\\`\\\`bash
231
+ vaif functions deploy
232
+ \\\`\\\`\\\`
233
+
234
+ 7. **Generate TypeScript types**
235
+
236
+ \\\`\\\`\\\`bash
237
+ vaif generate
238
+ \\\`\\\`\\\`
239
+
240
+ 8. **Run the development server**
241
+
242
+ \\\`\\\`\\\`bash
243
+ npm run dev
244
+ \\\`\\\`\\\`
245
+
246
+ Open [http://localhost:3000](http://localhost:3000) in your browser.
247
+
248
+ ## Project Structure
249
+
250
+ \\\`\\\`\\\`
251
+ .
252
+ \u251C\u2500\u2500 app/
253
+ \u2502 \u251C\u2500\u2500 layout.tsx # Root layout with VaifProvider
254
+ \u2502 \u251C\u2500\u2500 page.tsx # Home page
255
+ \u2502 \u2514\u2500\u2500 globals.css # Global styles
256
+ \u251C\u2500\u2500 lib/
257
+ \u2502 \u2514\u2500\u2500 vaif.ts # Browser + server VAIF client setup
258
+ \u251C\u2500\u2500 .env.local.example # Environment variable template
259
+ \u251C\u2500\u2500 next.config.ts # Next.js configuration
260
+ \u251C\u2500\u2500 tsconfig.json # TypeScript configuration
261
+ \u2514\u2500\u2500 package.json
262
+ \\\`\\\`\\\`
263
+
264
+ ## Available Scripts
265
+
266
+ | Command | Description |
267
+ | ---------------- | --------------------------- |
268
+ | \\\`npm run dev\\\` | Start development server |
269
+ | \\\`npm run build\\\` | Create production build |
270
+ | \\\`npm run start\\\` | Start production server |
271
+ | \\\`npm run lint\\\` | Run ESLint |
272
+
273
+ ## Documentation
274
+
275
+ Full documentation is available at <https://docs.vaif.studio>.
181
276
  `}],featureFiles:{auth:[{path:"middleware.ts",content:`import { NextResponse, type NextRequest } from "next/server";
182
277
  import { createServerClient } from "@vaiftech/client/server";
183
278
  import { authMiddleware } from "@vaiftech/auth/nextjs";
@@ -385,6 +480,55 @@ export function useRealtime<T extends { id: string }>({
385
480
 
386
481
  return { data, refresh };
387
482
  }
483
+ `}],database:[{path:"drizzle/0001_initial.sql",content:`-- Initial migration
484
+ -- Customize this schema for your project
485
+
486
+ CREATE TABLE IF NOT EXISTS "users" (
487
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
488
+ "email" text NOT NULL UNIQUE,
489
+ "name" text,
490
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
491
+ );
492
+
493
+ CREATE TABLE IF NOT EXISTS "posts" (
494
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
495
+ "user_id" uuid NOT NULL REFERENCES "users"("id"),
496
+ "title" text NOT NULL,
497
+ "content" text,
498
+ "published" boolean NOT NULL DEFAULT false,
499
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
500
+ );
501
+ `},{path:"drizzle.config.ts",content:`import { defineConfig } from "drizzle-kit";
502
+
503
+ export default defineConfig({
504
+ schema: "./src/db/schema.ts",
505
+ out: "./drizzle",
506
+ dialect: "postgresql",
507
+ dbCredentials: {
508
+ url: process.env.DATABASE_URL!,
509
+ },
510
+ });
511
+ `},{path:"src/db/schema.ts",content:`import { pgTable, uuid, text, boolean, timestamp } from "drizzle-orm/pg-core";
512
+
513
+ export const users = pgTable("users", {
514
+ id: uuid("id").primaryKey().defaultRandom(),
515
+ email: text("email").notNull().unique(),
516
+ name: text("name"),
517
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
518
+ });
519
+
520
+ export const posts = pgTable("posts", {
521
+ id: uuid("id").primaryKey().defaultRandom(),
522
+ userId: uuid("user_id").notNull().references(() => users.id),
523
+ title: text("title").notNull(),
524
+ content: text("content"),
525
+ published: boolean("published").notNull().default(false),
526
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
527
+ });
528
+ `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
529
+ const { name } = await req.json().catch(() => ({ name: "World" }));
530
+ return Response.json({ message: \`Hello, \${name}!\` });
531
+ }
388
532
  `}]},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
533
  "name": "my-vaif-app",
390
534
  "private": true,
@@ -519,6 +663,99 @@ dist
519
663
  .env
520
664
  .env.local
521
665
  *.local
666
+ `},{path:"README.md",content:`# My VAIF App \u2014 React SPA
667
+
668
+ A single-page React application built with [Vite](https://vite.dev/) and powered by [VAIF Studio](https://vaif.studio).
669
+
670
+ ## Prerequisites
671
+
672
+ - [Node.js](https://nodejs.org/) v18 or later
673
+ - npm (included with Node.js)
674
+ - A VAIF Studio account \u2014 sign up at <https://vaif.studio>
675
+
676
+ ## Setup
677
+
678
+ 1. **Install dependencies**
679
+
680
+ \\\`\\\`\\\`bash
681
+ npm install
682
+ \\\`\\\`\\\`
683
+
684
+ 2. **Configure credentials**
685
+
686
+ \\\`\\\`\\\`bash
687
+ cp .env.example .env
688
+ \\\`\\\`\\\`
689
+
690
+ Get your Project ID and API Key from <https://vaif.studio/dashboard> under **Project Settings > API Keys**.
691
+
692
+ 3. **Install and log in to the VAIF CLI**
693
+
694
+ \\\`\\\`\\\`bash
695
+ npm install -g @vaiftech/cli
696
+ vaif login
697
+ \\\`\\\`\\\`
698
+
699
+ 4. **Pull your database schema**
700
+
701
+ \\\`\\\`\\\`bash
702
+ vaif pull
703
+ \\\`\\\`\\\`
704
+
705
+ 5. **Push database migrations** (if using the database feature)
706
+
707
+ \\\`\\\`\\\`bash
708
+ vaif db push
709
+ \\\`\\\`\\\`
710
+
711
+ 6. **Deploy serverless functions** (if using the functions feature)
712
+
713
+ \\\`\\\`\\\`bash
714
+ vaif functions deploy
715
+ \\\`\\\`\\\`
716
+
717
+ 7. **Generate TypeScript types**
718
+
719
+ \\\`\\\`\\\`bash
720
+ vaif generate
721
+ \\\`\\\`\\\`
722
+
723
+ 8. **Run the development server**
724
+
725
+ \\\`\\\`\\\`bash
726
+ npm run dev
727
+ \\\`\\\`\\\`
728
+
729
+ Open the URL shown in your terminal (usually [http://localhost:5173](http://localhost:5173)).
730
+
731
+ ## Project Structure
732
+
733
+ \\\`\\\`\\\`
734
+ .
735
+ \u251C\u2500\u2500 src/
736
+ \u2502 \u251C\u2500\u2500 App.tsx # Root component with routes
737
+ \u2502 \u251C\u2500\u2500 main.tsx # Entry point with VaifProvider
738
+ \u2502 \u251C\u2500\u2500 lib/
739
+ \u2502 \u2502 \u2514\u2500\u2500 vaif.ts # VAIF client setup
740
+ \u2502 \u2514\u2500\u2500 vite-env.d.ts # Vite environment types
741
+ \u251C\u2500\u2500 index.html # HTML entry point
742
+ \u251C\u2500\u2500 vite.config.ts # Vite configuration
743
+ \u251C\u2500\u2500 tsconfig.json # TypeScript configuration
744
+ \u251C\u2500\u2500 .env.example # Environment variable template
745
+ \u2514\u2500\u2500 package.json
746
+ \\\`\\\`\\\`
747
+
748
+ ## Available Scripts
749
+
750
+ | Command | Description |
751
+ | -------------------- | ------------------------------ |
752
+ | \\\`npm run dev\\\` | Start development server |
753
+ | \\\`npm run build\\\` | Create production build |
754
+ | \\\`npm run preview\\\` | Preview production build |
755
+
756
+ ## Documentation
757
+
758
+ Full documentation is available at <https://docs.vaif.studio>.
522
759
  `}],featureFiles:{auth:[{path:"src/pages/Login.tsx",content:`import { useState } from "react";
523
760
  import { useNavigate } from "react-router-dom";
524
761
  import { vaif } from "../lib/vaif";
@@ -752,6 +989,55 @@ export function useRealtimeSubscription<T extends { id: string }>({
752
989
 
753
990
  return { data, refresh };
754
991
  }
992
+ `}],database:[{path:"drizzle/0001_initial.sql",content:`-- Initial migration
993
+ -- Customize this schema for your project
994
+
995
+ CREATE TABLE IF NOT EXISTS "users" (
996
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
997
+ "email" text NOT NULL UNIQUE,
998
+ "name" text,
999
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
1000
+ );
1001
+
1002
+ CREATE TABLE IF NOT EXISTS "posts" (
1003
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
1004
+ "user_id" uuid NOT NULL REFERENCES "users"("id"),
1005
+ "title" text NOT NULL,
1006
+ "content" text,
1007
+ "published" boolean NOT NULL DEFAULT false,
1008
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
1009
+ );
1010
+ `},{path:"drizzle.config.ts",content:`import { defineConfig } from "drizzle-kit";
1011
+
1012
+ export default defineConfig({
1013
+ schema: "./src/db/schema.ts",
1014
+ out: "./drizzle",
1015
+ dialect: "postgresql",
1016
+ dbCredentials: {
1017
+ url: process.env.DATABASE_URL!,
1018
+ },
1019
+ });
1020
+ `},{path:"src/db/schema.ts",content:`import { pgTable, uuid, text, boolean, timestamp } from "drizzle-orm/pg-core";
1021
+
1022
+ export const users = pgTable("users", {
1023
+ id: uuid("id").primaryKey().defaultRandom(),
1024
+ email: text("email").notNull().unique(),
1025
+ name: text("name"),
1026
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1027
+ });
1028
+
1029
+ export const posts = pgTable("posts", {
1030
+ id: uuid("id").primaryKey().defaultRandom(),
1031
+ userId: uuid("user_id").notNull().references(() => users.id),
1032
+ title: text("title").notNull(),
1033
+ content: text("content"),
1034
+ published: boolean("published").notNull().default(false),
1035
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1036
+ });
1037
+ `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
1038
+ const { name } = await req.json().catch(() => ({ name: "World" }));
1039
+ return Response.json({ message: \`Hello, \${name}!\` });
1040
+ }
755
1041
  `}]},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
1042
  import VaifClient
757
1043
 
@@ -858,6 +1144,102 @@ Run the VAIF CLI to generate Swift models from your schema:
858
1144
  \`\`\`bash
859
1145
  npx @vaiftech/cli generate --output ./Models/Database.swift --lang swift
860
1146
  \`\`\`
1147
+ `},{path:"README.md",content:`# My VAIF App \u2014 iOS Swift
1148
+
1149
+ An iOS/macOS application powered by [VAIF Studio](https://vaif.studio), using the VaifClient Swift package.
1150
+
1151
+ ## Prerequisites
1152
+
1153
+ - Xcode 15 or later
1154
+ - iOS 17+ / macOS 14+ deployment target
1155
+ - A VAIF Studio account \u2014 sign up at <https://vaif.studio>
1156
+ - (Optional) VAIF CLI for type generation: \\\`npm install -g @vaiftech/cli\\\`
1157
+
1158
+ ## Setup
1159
+
1160
+ 1. **Add the Swift Package**
1161
+
1162
+ In Xcode: **File > Add Package Dependencies...**
1163
+
1164
+ Enter the repository URL:
1165
+
1166
+ \\\`\\\`\\\`
1167
+ https://github.com/vaif-technologies/vaif-swift
1168
+ \\\`\\\`\\\`
1169
+
1170
+ Select the **VaifClient** library and add it to your target.
1171
+
1172
+ 2. **Configure credentials**
1173
+
1174
+ Add your project credentials to your Xcode scheme:
1175
+
1176
+ - **Edit Scheme > Run > Arguments > Environment Variables**
1177
+ - Add \\\`VAIF_PROJECT_ID\\\` and \\\`VAIF_API_KEY\\\`
1178
+
1179
+ Alternatively, add them to **Info.plist**:
1180
+
1181
+ \\\`\\\`\\\`xml
1182
+ <key>VAIF_PROJECT_ID</key>
1183
+ <string>your-project-id</string>
1184
+ <key>VAIF_API_KEY</key>
1185
+ <string>your-anon-key</string>
1186
+ \\\`\\\`\\\`
1187
+
1188
+ Get your credentials from <https://vaif.studio/dashboard> under **Project Settings > API Keys**.
1189
+
1190
+ 3. **Install and log in to the VAIF CLI** (for type generation)
1191
+
1192
+ \\\`\\\`\\\`bash
1193
+ npm install -g @vaiftech/cli
1194
+ vaif login
1195
+ \\\`\\\`\\\`
1196
+
1197
+ 4. **Pull your database schema**
1198
+
1199
+ \\\`\\\`\\\`bash
1200
+ vaif pull
1201
+ \\\`\\\`\\\`
1202
+
1203
+ 5. **Generate Swift models**
1204
+
1205
+ \\\`\\\`\\\`bash
1206
+ vaif generate --output ./Models/Database.swift --lang swift
1207
+ \\\`\\\`\\\`
1208
+
1209
+ 6. **Build and run**
1210
+
1211
+ Press **Cmd+R** in Xcode or run from the command line:
1212
+
1213
+ \\\`\\\`\\\`bash
1214
+ xcodebuild -scheme MyApp -destination 'platform=iOS Simulator,name=iPhone 16'
1215
+ \\\`\\\`\\\`
1216
+
1217
+ ## Project Structure
1218
+
1219
+ \\\`\\\`\\\`
1220
+ .
1221
+ \u251C\u2500\u2500 VaifManager.swift # Singleton VAIF client manager
1222
+ \u251C\u2500\u2500 .env.example # Environment variable reference
1223
+ \u2514\u2500\u2500 README-VAIF.md # Additional VAIF setup notes
1224
+ \\\`\\\`\\\`
1225
+
1226
+ ## Usage
1227
+
1228
+ \\\`\\\`\\\`swift
1229
+ import SwiftUI
1230
+
1231
+ struct ContentView: View {
1232
+ @StateObject private var vaif = VaifManager.shared
1233
+
1234
+ var body: some View {
1235
+ Text("Connected to VAIF")
1236
+ }
1237
+ }
1238
+ \\\`\\\`\\\`
1239
+
1240
+ ## Documentation
1241
+
1242
+ Full documentation is available at <https://docs.vaif.studio>.
861
1243
  `}],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
1244
  "name": "my-vaif-app",
863
1245
  "version": "0.1.0",
@@ -938,6 +1320,99 @@ EXPO_PUBLIC_VAIF_API_KEY=your-anon-key
938
1320
  .expo
939
1321
  dist
940
1322
  .env
1323
+ `},{path:"README.md",content:`# My VAIF App \u2014 Expo Mobile
1324
+
1325
+ A React Native / Expo mobile application powered by [VAIF Studio](https://vaif.studio), with Expo Router and native async storage.
1326
+
1327
+ ## Prerequisites
1328
+
1329
+ - [Node.js](https://nodejs.org/) v18 or later
1330
+ - npm (included with Node.js)
1331
+ - [Expo CLI](https://docs.expo.dev/get-started/installation/) (\\\`npx expo\\\`)
1332
+ - iOS Simulator (macOS) or Android Emulator, or the Expo Go app on your device
1333
+ - A VAIF Studio account \u2014 sign up at <https://vaif.studio>
1334
+
1335
+ ## Setup
1336
+
1337
+ 1. **Install dependencies**
1338
+
1339
+ \\\`\\\`\\\`bash
1340
+ npm install
1341
+ \\\`\\\`\\\`
1342
+
1343
+ 2. **Configure credentials**
1344
+
1345
+ \\\`\\\`\\\`bash
1346
+ cp .env.example .env
1347
+ \\\`\\\`\\\`
1348
+
1349
+ Get your Project ID and API Key from <https://vaif.studio/dashboard> under **Project Settings > API Keys**.
1350
+
1351
+ 3. **Install and log in to the VAIF CLI**
1352
+
1353
+ \\\`\\\`\\\`bash
1354
+ npm install -g @vaiftech/cli
1355
+ vaif login
1356
+ \\\`\\\`\\\`
1357
+
1358
+ 4. **Pull your database schema**
1359
+
1360
+ \\\`\\\`\\\`bash
1361
+ vaif pull
1362
+ \\\`\\\`\\\`
1363
+
1364
+ 5. **Push database migrations** (if using the database feature)
1365
+
1366
+ \\\`\\\`\\\`bash
1367
+ vaif db push
1368
+ \\\`\\\`\\\`
1369
+
1370
+ 6. **Deploy serverless functions** (if using the functions feature)
1371
+
1372
+ \\\`\\\`\\\`bash
1373
+ vaif functions deploy
1374
+ \\\`\\\`\\\`
1375
+
1376
+ 7. **Generate TypeScript types**
1377
+
1378
+ \\\`\\\`\\\`bash
1379
+ vaif generate
1380
+ \\\`\\\`\\\`
1381
+
1382
+ 8. **Start the development server**
1383
+
1384
+ \\\`\\\`\\\`bash
1385
+ npx expo start
1386
+ \\\`\\\`\\\`
1387
+
1388
+ Scan the QR code with Expo Go, or press \\\`i\\\` for iOS Simulator / \\\`a\\\` for Android Emulator.
1389
+
1390
+ ## Project Structure
1391
+
1392
+ \\\`\\\`\\\`
1393
+ .
1394
+ \u251C\u2500\u2500 app/
1395
+ \u2502 \u251C\u2500\u2500 _layout.tsx # Root layout with VaifProvider
1396
+ \u2502 \u2514\u2500\u2500 index.tsx # Home screen
1397
+ \u251C\u2500\u2500 lib/
1398
+ \u2502 \u2514\u2500\u2500 vaif.ts # Expo VAIF client setup
1399
+ \u251C\u2500\u2500 app.json # Expo configuration
1400
+ \u251C\u2500\u2500 .env.example # Environment variable template
1401
+ \u2514\u2500\u2500 package.json
1402
+ \\\`\\\`\\\`
1403
+
1404
+ ## Available Scripts
1405
+
1406
+ | Command | Description |
1407
+ | -------------------------- | --------------------------------- |
1408
+ | \\\`npx expo start\\\` | Start Expo development server |
1409
+ | \\\`npx expo start --ios\\\` | Start on iOS Simulator |
1410
+ | \\\`npx expo start --android\\\`| Start on Android Emulator |
1411
+ | \\\`npx expo start --web\\\` | Start in web browser |
1412
+
1413
+ ## Documentation
1414
+
1415
+ Full documentation is available at <https://docs.vaif.studio>.
941
1416
  `}],featureFiles:{auth:[{path:"app/(auth)/login.tsx",content:`import { useState } from "react";
942
1417
  import { View, Text, TextInput, TouchableOpacity, StyleSheet, Alert } from "react-native";
943
1418
  import { useRouter } from "expo-router";
@@ -1103,6 +1578,55 @@ export function useRealtimeMessages(channelId: string) {
1103
1578
 
1104
1579
  return { messages, loading, refresh };
1105
1580
  }
1581
+ `}],database:[{path:"drizzle/0001_initial.sql",content:`-- Initial migration
1582
+ -- Customize this schema for your project
1583
+
1584
+ CREATE TABLE IF NOT EXISTS "users" (
1585
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
1586
+ "email" text NOT NULL UNIQUE,
1587
+ "name" text,
1588
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
1589
+ );
1590
+
1591
+ CREATE TABLE IF NOT EXISTS "posts" (
1592
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
1593
+ "user_id" uuid NOT NULL REFERENCES "users"("id"),
1594
+ "title" text NOT NULL,
1595
+ "content" text,
1596
+ "published" boolean NOT NULL DEFAULT false,
1597
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
1598
+ );
1599
+ `},{path:"drizzle.config.ts",content:`import { defineConfig } from "drizzle-kit";
1600
+
1601
+ export default defineConfig({
1602
+ schema: "./src/db/schema.ts",
1603
+ out: "./drizzle",
1604
+ dialect: "postgresql",
1605
+ dbCredentials: {
1606
+ url: process.env.DATABASE_URL!,
1607
+ },
1608
+ });
1609
+ `},{path:"src/db/schema.ts",content:`import { pgTable, uuid, text, boolean, timestamp } from "drizzle-orm/pg-core";
1610
+
1611
+ export const users = pgTable("users", {
1612
+ id: uuid("id").primaryKey().defaultRandom(),
1613
+ email: text("email").notNull().unique(),
1614
+ name: text("name"),
1615
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1616
+ });
1617
+
1618
+ export const posts = pgTable("posts", {
1619
+ id: uuid("id").primaryKey().defaultRandom(),
1620
+ userId: uuid("user_id").notNull().references(() => users.id),
1621
+ title: text("title").notNull(),
1622
+ content: text("content"),
1623
+ published: boolean("published").notNull().default(false),
1624
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1625
+ });
1626
+ `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
1627
+ const { name } = await req.json().catch(() => ({ name: "World" }));
1628
+ return Response.json({ message: \`Hello, \${name}!\` });
1629
+ }
1106
1630
  `}]},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
1631
  import 'vaif_client.dart';
1108
1632
 
@@ -1187,6 +1711,84 @@ VAIF_API_KEY=your-anon-key
1187
1711
  .packages
1188
1712
  .env
1189
1713
  *.iml
1714
+ `},{path:"README.md",content:`# My VAIF App \u2014 Flutter
1715
+
1716
+ A Flutter application powered by [VAIF Studio](https://vaif.studio), with Dart client and environment configuration.
1717
+
1718
+ ## Prerequisites
1719
+
1720
+ - [Flutter SDK](https://flutter.dev/docs/get-started/install) 3.5 or later
1721
+ - Dart SDK (included with Flutter)
1722
+ - A VAIF Studio account \u2014 sign up at <https://vaif.studio>
1723
+ - (Optional) VAIF CLI for type generation: \\\`npm install -g @vaiftech/cli\\\`
1724
+
1725
+ ## Setup
1726
+
1727
+ 1. **Install dependencies**
1728
+
1729
+ \\\`\\\`\\\`bash
1730
+ flutter pub get
1731
+ \\\`\\\`\\\`
1732
+
1733
+ 2. **Configure credentials**
1734
+
1735
+ \\\`\\\`\\\`bash
1736
+ cp .env.example .env
1737
+ \\\`\\\`\\\`
1738
+
1739
+ Get your Project ID and API Key from <https://vaif.studio/dashboard> under **Project Settings > API Keys**.
1740
+
1741
+ 3. **Install and log in to the VAIF CLI** (for schema and type generation)
1742
+
1743
+ \\\`\\\`\\\`bash
1744
+ npm install -g @vaiftech/cli
1745
+ vaif login
1746
+ \\\`\\\`\\\`
1747
+
1748
+ 4. **Pull your database schema**
1749
+
1750
+ \\\`\\\`\\\`bash
1751
+ vaif pull
1752
+ \\\`\\\`\\\`
1753
+
1754
+ 5. **Generate Dart models**
1755
+
1756
+ \\\`\\\`\\\`bash
1757
+ vaif generate --output ./lib/models/database.dart --lang dart
1758
+ \\\`\\\`\\\`
1759
+
1760
+ 6. **Run the app**
1761
+
1762
+ \\\`\\\`\\\`bash
1763
+ flutter run
1764
+ \\\`\\\`\\\`
1765
+
1766
+ ## Project Structure
1767
+
1768
+ \\\`\\\`\\\`
1769
+ .
1770
+ \u251C\u2500\u2500 lib/
1771
+ \u2502 \u251C\u2500\u2500 main.dart # App entry point
1772
+ \u2502 \u251C\u2500\u2500 vaif_client.dart # VAIF client setup
1773
+ \u2502 \u2514\u2500\u2500 screens/ # Screen widgets (added by features)
1774
+ \u251C\u2500\u2500 pubspec.yaml # Dart dependencies
1775
+ \u251C\u2500\u2500 .env.example # Environment variable template
1776
+ \u2514\u2500\u2500 .gitignore
1777
+ \\\`\\\`\\\`
1778
+
1779
+ ## Available Commands
1780
+
1781
+ | Command | Description |
1782
+ | ------------------------ | ---------------------------------- |
1783
+ | \\\`flutter pub get\\\` | Install dependencies |
1784
+ | \\\`flutter run\\\` | Run on connected device/emulator |
1785
+ | \\\`flutter build apk\\\` | Build Android APK |
1786
+ | \\\`flutter build ios\\\` | Build iOS app |
1787
+ | \\\`flutter test\\\` | Run tests |
1788
+
1789
+ ## Documentation
1790
+
1791
+ Full documentation is available at <https://docs.vaif.studio>.
1190
1792
  `}],featureFiles:{auth:[{path:"lib/screens/login_screen.dart",content:`import 'package:flutter/material.dart';
1191
1793
  import '../vaif_client.dart';
1192
1794
 
@@ -1244,6 +1846,92 @@ class _LoginScreenState extends State<LoginScreen> {
1244
1846
  );
1245
1847
  }
1246
1848
  }
1849
+ `}],database:[{path:"lib/models/database.dart",content:`/// Database models for VAIF.
1850
+ /// Run \`vaif generate --output ./lib/models/database.dart --lang dart\` to regenerate.
1851
+
1852
+ class User {
1853
+ final String id;
1854
+ final String email;
1855
+ final String? name;
1856
+ final DateTime createdAt;
1857
+
1858
+ User({required this.id, required this.email, this.name, required this.createdAt});
1859
+
1860
+ factory User.fromJson(Map<String, dynamic> json) => User(
1861
+ id: json['id'] as String,
1862
+ email: json['email'] as String,
1863
+ name: json['name'] as String?,
1864
+ createdAt: DateTime.parse(json['created_at'] as String),
1865
+ );
1866
+
1867
+ Map<String, dynamic> toJson() => {
1868
+ 'id': id,
1869
+ 'email': email,
1870
+ 'name': name,
1871
+ 'created_at': createdAt.toIso8601String(),
1872
+ };
1873
+ }
1874
+
1875
+ class Post {
1876
+ final String id;
1877
+ final String userId;
1878
+ final String title;
1879
+ final String? content;
1880
+ final bool published;
1881
+ final DateTime createdAt;
1882
+
1883
+ Post({
1884
+ required this.id,
1885
+ required this.userId,
1886
+ required this.title,
1887
+ this.content,
1888
+ required this.published,
1889
+ required this.createdAt,
1890
+ });
1891
+
1892
+ factory Post.fromJson(Map<String, dynamic> json) => Post(
1893
+ id: json['id'] as String,
1894
+ userId: json['user_id'] as String,
1895
+ title: json['title'] as String,
1896
+ content: json['content'] as String?,
1897
+ published: json['published'] as bool,
1898
+ createdAt: DateTime.parse(json['created_at'] as String),
1899
+ );
1900
+
1901
+ Map<String, dynamic> toJson() => {
1902
+ 'id': id,
1903
+ 'user_id': userId,
1904
+ 'title': title,
1905
+ 'content': content,
1906
+ 'published': published,
1907
+ 'created_at': createdAt.toIso8601String(),
1908
+ };
1909
+ }
1910
+ `}],functions:[{path:"lib/services/functions_service.dart",content:`import '../vaif_client.dart';
1911
+
1912
+ /// Service for invoking VAIF serverless functions.
1913
+ class FunctionsService {
1914
+ /// Invoke the "hello" function with an optional name parameter.
1915
+ static Future<Map<String, dynamic>> hello({String name = 'World'}) async {
1916
+ final result = await vaif.functions.invoke(
1917
+ 'hello',
1918
+ body: {'name': name},
1919
+ );
1920
+ return result.data as Map<String, dynamic>;
1921
+ }
1922
+
1923
+ /// Invoke any VAIF function by name.
1924
+ static Future<Map<String, dynamic>> invoke(
1925
+ String functionName, {
1926
+ Map<String, dynamic>? body,
1927
+ }) async {
1928
+ final result = await vaif.functions.invoke(
1929
+ functionName,
1930
+ body: body ?? {},
1931
+ );
1932
+ return result.data as Map<String, dynamic>;
1933
+ }
1934
+ }
1247
1935
  `}]},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
1936
 
1249
1937
  from fastapi import FastAPI
@@ -1316,6 +2004,106 @@ VAIF_SECRET_KEY=your-secret-key
1316
2004
  .env
1317
2005
  .venv
1318
2006
  venv
2007
+ `},{path:"README.md",content:`# My VAIF App \u2014 Python FastAPI Backend
2008
+
2009
+ A FastAPI backend application powered by [VAIF Studio](https://vaif.studio), with auth middleware and type-safe queries.
2010
+
2011
+ ## Prerequisites
2012
+
2013
+ - [Python](https://www.python.org/) 3.10 or later
2014
+ - pip (included with Python)
2015
+ - A VAIF Studio account \u2014 sign up at <https://vaif.studio>
2016
+ - (Optional) VAIF CLI for schema management: \\\`npm install -g @vaiftech/cli\\\`
2017
+
2018
+ ## Setup
2019
+
2020
+ 1. **Create a virtual environment** (recommended)
2021
+
2022
+ \\\`\\\`\\\`bash
2023
+ python -m venv .venv
2024
+ source .venv/bin/activate # On Windows: .venv\\\\Scripts\\\\activate
2025
+ \\\`\\\`\\\`
2026
+
2027
+ 2. **Install dependencies**
2028
+
2029
+ \\\`\\\`\\\`bash
2030
+ pip install -r requirements.txt
2031
+ \\\`\\\`\\\`
2032
+
2033
+ 3. **Configure credentials**
2034
+
2035
+ \\\`\\\`\\\`bash
2036
+ cp .env.example .env
2037
+ \\\`\\\`\\\`
2038
+
2039
+ Get your Project ID, API Key, and Secret Key from <https://vaif.studio/dashboard> under **Project Settings > API Keys**.
2040
+
2041
+ 4. **Install and log in to the VAIF CLI**
2042
+
2043
+ \\\`\\\`\\\`bash
2044
+ npm install -g @vaiftech/cli
2045
+ vaif login
2046
+ \\\`\\\`\\\`
2047
+
2048
+ 5. **Pull your database schema**
2049
+
2050
+ \\\`\\\`\\\`bash
2051
+ vaif pull
2052
+ \\\`\\\`\\\`
2053
+
2054
+ 6. **Push database migrations** (if using the database feature)
2055
+
2056
+ \\\`\\\`\\\`bash
2057
+ vaif db push
2058
+ \\\`\\\`\\\`
2059
+
2060
+ 7. **Deploy serverless functions** (if using the functions feature)
2061
+
2062
+ \\\`\\\`\\\`bash
2063
+ vaif functions deploy
2064
+ \\\`\\\`\\\`
2065
+
2066
+ 8. **Generate Python types**
2067
+
2068
+ \\\`\\\`\\\`bash
2069
+ vaif generate --lang python
2070
+ \\\`\\\`\\\`
2071
+
2072
+ 9. **Run the development server**
2073
+
2074
+ \\\`\\\`\\\`bash
2075
+ uvicorn main:app --reload
2076
+ \\\`\\\`\\\`
2077
+
2078
+ The API will be available at [http://localhost:8000](http://localhost:8000). Interactive docs at [http://localhost:8000/docs](http://localhost:8000/docs).
2079
+
2080
+ ## Project Structure
2081
+
2082
+ \\\`\\\`\\\`
2083
+ .
2084
+ \u251C\u2500\u2500 main.py # FastAPI application entry point
2085
+ \u251C\u2500\u2500 vaif_client.py # VAIF client setup (public + admin)
2086
+ \u251C\u2500\u2500 middleware/
2087
+ \u2502 \u2514\u2500\u2500 auth.py # Auth middleware (added by auth feature)
2088
+ \u251C\u2500\u2500 routes/
2089
+ \u2502 \u251C\u2500\u2500 storage.py # Storage routes (added by storage feature)
2090
+ \u2502 \u2514\u2500\u2500 functions.py # Functions routes (added by functions feature)
2091
+ \u251C\u2500\u2500 requirements.txt # Python dependencies
2092
+ \u251C\u2500\u2500 .env.example # Environment variable template
2093
+ \u2514\u2500\u2500 .gitignore
2094
+ \\\`\\\`\\\`
2095
+
2096
+ ## Available Endpoints
2097
+
2098
+ | Method | Path | Description |
2099
+ | ------ | -------------------------------- | ------------------------ |
2100
+ | GET | \\\`/\\\` | Health check |
2101
+ | GET | \\\`/health\\\` | Health status |
2102
+ | GET | \\\`/items\\\` | List items from database |
2103
+
2104
+ ## Documentation
2105
+
2106
+ Full documentation is available at <https://docs.vaif.studio>.
1319
2107
  `}],featureFiles:{auth:[{path:"middleware/auth.py",content:`"""VAIF auth middleware for FastAPI."""
1320
2108
 
1321
2109
  from typing import Optional
@@ -1379,7 +2167,60 @@ async def upload_file(file: UploadFile = File(...)):
1379
2167
  url_data = client.storage.from_(BUCKET).get_public_url(result.path)
1380
2168
 
1381
2169
  return {"path": result.path, "public_url": url_data}
1382
- `},{path:"routes/__init__.py",content:""}],functions:[{path:"routes/functions.py",content:`"""Invoke VAIF serverless functions."""
2170
+ `},{path:"routes/__init__.py",content:""}],database:[{path:"migrations/0001_initial.sql",content:`-- Initial migration
2171
+ -- Customize this schema for your project
2172
+
2173
+ CREATE TABLE IF NOT EXISTS "users" (
2174
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
2175
+ "email" text NOT NULL UNIQUE,
2176
+ "name" text,
2177
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
2178
+ );
2179
+
2180
+ CREATE TABLE IF NOT EXISTS "posts" (
2181
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
2182
+ "user_id" uuid NOT NULL REFERENCES "users"("id"),
2183
+ "title" text NOT NULL,
2184
+ "content" text,
2185
+ "published" boolean NOT NULL DEFAULT false,
2186
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
2187
+ );
2188
+ `},{path:"models.py",content:`"""Pydantic models matching the database schema."""
2189
+
2190
+ from datetime import datetime
2191
+ from typing import Optional
2192
+ from uuid import UUID
2193
+
2194
+ from pydantic import BaseModel, EmailStr
2195
+
2196
+
2197
+ class UserBase(BaseModel):
2198
+ email: str
2199
+ name: Optional[str] = None
2200
+
2201
+
2202
+ class User(UserBase):
2203
+ id: UUID
2204
+ created_at: datetime
2205
+
2206
+ class Config:
2207
+ from_attributes = True
2208
+
2209
+
2210
+ class PostBase(BaseModel):
2211
+ title: str
2212
+ content: Optional[str] = None
2213
+ published: bool = False
2214
+
2215
+
2216
+ class Post(PostBase):
2217
+ id: UUID
2218
+ user_id: UUID
2219
+ created_at: datetime
2220
+
2221
+ class Config:
2222
+ from_attributes = True
2223
+ `}],functions:[{path:"routes/functions.py",content:`"""Invoke VAIF serverless functions."""
1383
2224
 
1384
2225
  from fastapi import APIRouter
1385
2226
  from vaif_client import get_vaif_client
@@ -1392,6 +2233,26 @@ async def invoke_function(function_name: str, payload: dict = {}):
1392
2233
  client = get_vaif_client()
1393
2234
  result = await client.functions.invoke(function_name, body=payload)
1394
2235
  return {"data": result}
2236
+ `},{path:"functions/hello.py",content:`"""Example VAIF serverless function."""
2237
+
2238
+ import json
2239
+
2240
+
2241
+ def handler(request):
2242
+ """Simple hello function.
2243
+
2244
+ Deploy with: vaif functions deploy
2245
+ """
2246
+ try:
2247
+ body = json.loads(request.body) if request.body else {}
2248
+ name = body.get("name", "World")
2249
+ except (json.JSONDecodeError, AttributeError):
2250
+ name = "World"
2251
+
2252
+ return {
2253
+ "statusCode": 200,
2254
+ "body": json.dumps({"message": f"Hello, {name}!"}),
2255
+ }
1395
2256
  `}]},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
2257
 
1397
2258
  import (
@@ -1469,6 +2330,96 @@ VAIF_SECRET_KEY=your-secret-key
1469
2330
  *.so
1470
2331
  *.dylib
1471
2332
  .env
2333
+ `},{path:"README.md",content:`# My VAIF App \u2014 Go Backend API
2334
+
2335
+ A Go backend API powered by [VAIF Studio](https://vaif.studio), with HTTP handlers and auth middleware.
2336
+
2337
+ ## Prerequisites
2338
+
2339
+ - [Go](https://go.dev/dl/) 1.22 or later
2340
+ - A VAIF Studio account \u2014 sign up at <https://vaif.studio>
2341
+ - (Optional) VAIF CLI for schema management: \\\`npm install -g @vaiftech/cli\\\`
2342
+
2343
+ ## Setup
2344
+
2345
+ 1. **Install dependencies**
2346
+
2347
+ \\\`\\\`\\\`bash
2348
+ go mod tidy
2349
+ \\\`\\\`\\\`
2350
+
2351
+ 2. **Configure credentials**
2352
+
2353
+ \\\`\\\`\\\`bash
2354
+ cp .env.example .env
2355
+ \\\`\\\`\\\`
2356
+
2357
+ Get your Project ID, API Key, and Secret Key from <https://vaif.studio/dashboard> under **Project Settings > API Keys**.
2358
+
2359
+ 3. **Install and log in to the VAIF CLI**
2360
+
2361
+ \\\`\\\`\\\`bash
2362
+ npm install -g @vaiftech/cli
2363
+ vaif login
2364
+ \\\`\\\`\\\`
2365
+
2366
+ 4. **Pull your database schema**
2367
+
2368
+ \\\`\\\`\\\`bash
2369
+ vaif pull
2370
+ \\\`\\\`\\\`
2371
+
2372
+ 5. **Push database migrations** (if using the database feature)
2373
+
2374
+ \\\`\\\`\\\`bash
2375
+ vaif db push
2376
+ \\\`\\\`\\\`
2377
+
2378
+ 6. **Deploy serverless functions** (if using the functions feature)
2379
+
2380
+ \\\`\\\`\\\`bash
2381
+ vaif functions deploy
2382
+ \\\`\\\`\\\`
2383
+
2384
+ 7. **Generate Go types**
2385
+
2386
+ \\\`\\\`\\\`bash
2387
+ vaif generate --lang go
2388
+ \\\`\\\`\\\`
2389
+
2390
+ 8. **Run the server**
2391
+
2392
+ \\\`\\\`\\\`bash
2393
+ go run main.go
2394
+ \\\`\\\`\\\`
2395
+
2396
+ The API will be available at [http://localhost:8080](http://localhost:8080).
2397
+
2398
+ ## Project Structure
2399
+
2400
+ \\\`\\\`\\\`
2401
+ .
2402
+ \u251C\u2500\u2500 main.go # Application entry point
2403
+ \u251C\u2500\u2500 vaif/
2404
+ \u2502 \u2514\u2500\u2500 client.go # VAIF client initialisation
2405
+ \u251C\u2500\u2500 middleware/
2406
+ \u2502 \u2514\u2500\u2500 auth.go # Auth middleware (added by auth feature)
2407
+ \u251C\u2500\u2500 handlers/
2408
+ \u2502 \u2514\u2500\u2500 storage.go # Storage handlers (added by storage feature)
2409
+ \u251C\u2500\u2500 go.mod # Go module definition
2410
+ \u251C\u2500\u2500 .env.example # Environment variable template
2411
+ \u2514\u2500\u2500 .gitignore
2412
+ \\\`\\\`\\\`
2413
+
2414
+ ## Available Endpoints
2415
+
2416
+ | Method | Path | Description |
2417
+ | ------ | ---------- | -------------- |
2418
+ | GET | \\\`/health\\\` | Health check |
2419
+
2420
+ ## Documentation
2421
+
2422
+ Full documentation is available at <https://docs.vaif.studio>.
1472
2423
  `}],featureFiles:{auth:[{path:"middleware/auth.go",content:`package middleware
1473
2424
 
1474
2425
  import (
@@ -1544,6 +2495,79 @@ func UploadHandler(w http.ResponseWriter, r *http.Request) {
1544
2495
  w.Header().Set("Content-Type", "application/json")
1545
2496
  json.NewEncoder(w).Encode(result)
1546
2497
  }
2498
+ `}],database:[{path:"migrations/0001_initial.sql",content:`-- Initial migration
2499
+ -- Customize this schema for your project
2500
+ -- Use goose or another Go migration tool to apply:
2501
+ -- goose postgres "$DATABASE_URL" up
2502
+
2503
+ CREATE TABLE IF NOT EXISTS "users" (
2504
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
2505
+ "email" text NOT NULL UNIQUE,
2506
+ "name" text,
2507
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
2508
+ );
2509
+
2510
+ CREATE TABLE IF NOT EXISTS "posts" (
2511
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
2512
+ "user_id" uuid NOT NULL REFERENCES "users"("id"),
2513
+ "title" text NOT NULL,
2514
+ "content" text,
2515
+ "published" boolean NOT NULL DEFAULT false,
2516
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
2517
+ );
2518
+ `},{path:"models/models.go",content:`package models
2519
+
2520
+ import (
2521
+ "time"
2522
+
2523
+ "github.com/google/uuid"
2524
+ )
2525
+
2526
+ type User struct {
2527
+ ID uuid.UUID \`json:"id"\`
2528
+ Email string \`json:"email"\`
2529
+ Name *string \`json:"name,omitempty"\`
2530
+ CreatedAt time.Time \`json:"created_at"\`
2531
+ }
2532
+
2533
+ type Post struct {
2534
+ ID uuid.UUID \`json:"id"\`
2535
+ UserID uuid.UUID \`json:"user_id"\`
2536
+ Title string \`json:"title"\`
2537
+ Content *string \`json:"content,omitempty"\`
2538
+ Published bool \`json:"published"\`
2539
+ CreatedAt time.Time \`json:"created_at"\`
2540
+ }
2541
+ `}],functions:[{path:"functions/hello.go",content:`package functions
2542
+
2543
+ import (
2544
+ "encoding/json"
2545
+ "fmt"
2546
+ "net/http"
2547
+ )
2548
+
2549
+ // HelloRequest is the expected request body.
2550
+ type HelloRequest struct {
2551
+ Name string \`json:"name"\`
2552
+ }
2553
+
2554
+ // HelloResponse is the response body.
2555
+ type HelloResponse struct {
2556
+ Message string \`json:"message"\`
2557
+ }
2558
+
2559
+ // HelloHandler is an example VAIF serverless function.
2560
+ func HelloHandler(w http.ResponseWriter, r *http.Request) {
2561
+ var req HelloRequest
2562
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Name == "" {
2563
+ req.Name = "World"
2564
+ }
2565
+
2566
+ w.Header().Set("Content-Type", "application/json")
2567
+ json.NewEncoder(w).Encode(HelloResponse{
2568
+ Message: fmt.Sprintf("Hello, %s!", req.Name),
2569
+ })
2570
+ }
1547
2571
  `}]},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
2572
 
1549
2573
  export const vaif = createClient({
@@ -1603,7 +2627,134 @@ export async function deleteTodo(id: string): Promise<void> {
1603
2627
 
1604
2628
  VITE_VAIF_PROJECT_ID=your-project-id
1605
2629
  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";
2630
+ `},{path:"README.md",content:`# Todo App \u2014 VAIF Starter
2631
+
2632
+ A simple React todo application for learning [VAIF Studio](https://vaif.studio) basics, including typed database queries and CRUD operations.
2633
+
2634
+ ## Prerequisites
2635
+
2636
+ - [Node.js](https://nodejs.org/) v18 or later
2637
+ - npm (included with Node.js)
2638
+ - A VAIF Studio account \u2014 sign up at <https://vaif.studio>
2639
+
2640
+ ## Setup
2641
+
2642
+ 1. **Install dependencies**
2643
+
2644
+ \\\`\\\`\\\`bash
2645
+ npm install
2646
+ \\\`\\\`\\\`
2647
+
2648
+ 2. **Configure credentials**
2649
+
2650
+ \\\`\\\`\\\`bash
2651
+ cp .env.example .env
2652
+ \\\`\\\`\\\`
2653
+
2654
+ Get your Project ID and API Key from <https://vaif.studio/dashboard> under **Project Settings > API Keys**.
2655
+
2656
+ 3. **Install and log in to the VAIF CLI**
2657
+
2658
+ \\\`\\\`\\\`bash
2659
+ npm install -g @vaiftech/cli
2660
+ vaif login
2661
+ \\\`\\\`\\\`
2662
+
2663
+ 4. **Create the todos table**
2664
+
2665
+ Create a \\\`todos\\\` table in your VAIF dashboard with columns:
2666
+ - \\\`id\\\` (uuid, primary key)
2667
+ - \\\`title\\\` (text)
2668
+ - \\\`done\\\` (boolean)
2669
+ - \\\`created_at\\\` (timestamptz)
2670
+ - \\\`user_id\\\` (uuid, optional)
2671
+
2672
+ 5. **Pull your database schema**
2673
+
2674
+ \\\`\\\`\\\`bash
2675
+ vaif pull
2676
+ \\\`\\\`\\\`
2677
+
2678
+ 6. **Generate TypeScript types**
2679
+
2680
+ \\\`\\\`\\\`bash
2681
+ vaif generate
2682
+ \\\`\\\`\\\`
2683
+
2684
+ 7. **Run the development server**
2685
+
2686
+ \\\`\\\`\\\`bash
2687
+ npm run dev
2688
+ \\\`\\\`\\\`
2689
+
2690
+ ## Project Structure
2691
+
2692
+ \\\`\\\`\\\`
2693
+ .
2694
+ \u251C\u2500\u2500 src/
2695
+ \u2502 \u2514\u2500\u2500 lib/
2696
+ \u2502 \u2514\u2500\u2500 vaif.ts # VAIF client + typed todo helpers
2697
+ \u251C\u2500\u2500 .env.example # Environment variable template
2698
+ \u2514\u2500\u2500 package.json
2699
+ \\\`\\\`\\\`
2700
+
2701
+ ## Key Files
2702
+
2703
+ - **\\\`src/lib/vaif.ts\\\`** \u2014 VAIF client setup plus typed helpers for \\\`getTodos\\\`, \\\`addTodo\\\`, \\\`toggleTodo\\\`, and \\\`deleteTodo\\\`.
2704
+
2705
+ ## Documentation
2706
+
2707
+ Full documentation is available at <https://docs.vaif.studio>.
2708
+ `}],featureFiles:{database:[{path:"drizzle/0001_initial.sql",content:`-- Initial migration
2709
+ -- Customize this schema for your project
2710
+
2711
+ CREATE TABLE IF NOT EXISTS "users" (
2712
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
2713
+ "email" text NOT NULL UNIQUE,
2714
+ "name" text,
2715
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
2716
+ );
2717
+
2718
+ CREATE TABLE IF NOT EXISTS "posts" (
2719
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
2720
+ "user_id" uuid NOT NULL REFERENCES "users"("id"),
2721
+ "title" text NOT NULL,
2722
+ "content" text,
2723
+ "published" boolean NOT NULL DEFAULT false,
2724
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
2725
+ );
2726
+ `},{path:"drizzle.config.ts",content:`import { defineConfig } from "drizzle-kit";
2727
+
2728
+ export default defineConfig({
2729
+ schema: "./src/db/schema.ts",
2730
+ out: "./drizzle",
2731
+ dialect: "postgresql",
2732
+ dbCredentials: {
2733
+ url: process.env.DATABASE_URL!,
2734
+ },
2735
+ });
2736
+ `},{path:"src/db/schema.ts",content:`import { pgTable, uuid, text, boolean, timestamp } from "drizzle-orm/pg-core";
2737
+
2738
+ export const users = pgTable("users", {
2739
+ id: uuid("id").primaryKey().defaultRandom(),
2740
+ email: text("email").notNull().unique(),
2741
+ name: text("name"),
2742
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2743
+ });
2744
+
2745
+ export const posts = pgTable("posts", {
2746
+ id: uuid("id").primaryKey().defaultRandom(),
2747
+ userId: uuid("user_id").notNull().references(() => users.id),
2748
+ title: text("title").notNull(),
2749
+ content: text("content"),
2750
+ published: boolean("published").notNull().default(false),
2751
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2752
+ });
2753
+ `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
2754
+ const { name } = await req.json().catch(() => ({ name: "World" }));
2755
+ return Response.json({ message: \`Hello, \${name}!\` });
2756
+ }
2757
+ `}]},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
2758
 
1608
2759
  export const vaif = createClient({
1609
2760
  projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
@@ -1756,7 +2907,148 @@ export function useRealtimeMessages({
1756
2907
 
1757
2908
  VITE_VAIF_PROJECT_ID=your-project-id
1758
2909
  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";
2910
+ `},{path:"README.md",content:`# Realtime Chat \u2014 VAIF Starter
2911
+
2912
+ A React chat application with live messaging powered by [VAIF Studio](https://vaif.studio) realtime subscriptions.
2913
+
2914
+ ## Prerequisites
2915
+
2916
+ - [Node.js](https://nodejs.org/) v18 or later
2917
+ - npm (included with Node.js)
2918
+ - A VAIF Studio account \u2014 sign up at <https://vaif.studio>
2919
+
2920
+ ## Setup
2921
+
2922
+ 1. **Install dependencies**
2923
+
2924
+ \\\`\\\`\\\`bash
2925
+ npm install
2926
+ \\\`\\\`\\\`
2927
+
2928
+ 2. **Configure credentials**
2929
+
2930
+ \\\`\\\`\\\`bash
2931
+ cp .env.example .env
2932
+ \\\`\\\`\\\`
2933
+
2934
+ Get your Project ID and API Key from <https://vaif.studio/dashboard> under **Project Settings > API Keys**.
2935
+
2936
+ 3. **Install and log in to the VAIF CLI**
2937
+
2938
+ \\\`\\\`\\\`bash
2939
+ npm install -g @vaiftech/cli
2940
+ vaif login
2941
+ \\\`\\\`\\\`
2942
+
2943
+ 4. **Create the messages table**
2944
+
2945
+ Create a \\\`messages\\\` table in your VAIF dashboard with columns:
2946
+ - \\\`id\\\` (uuid, primary key)
2947
+ - \\\`content\\\` (text)
2948
+ - \\\`user_id\\\` (text)
2949
+ - \\\`username\\\` (text)
2950
+ - \\\`channel_id\\\` (text)
2951
+ - \\\`created_at\\\` (timestamptz)
2952
+
2953
+ 5. **Enable Realtime**
2954
+
2955
+ In your VAIF dashboard, enable Realtime on the \\\`messages\\\` table.
2956
+
2957
+ 6. **Pull your database schema**
2958
+
2959
+ \\\`\\\`\\\`bash
2960
+ vaif pull
2961
+ \\\`\\\`\\\`
2962
+
2963
+ 7. **Push database migrations** (if using the database feature)
2964
+
2965
+ \\\`\\\`\\\`bash
2966
+ vaif db push
2967
+ \\\`\\\`\\\`
2968
+
2969
+ 8. **Generate TypeScript types**
2970
+
2971
+ \\\`\\\`\\\`bash
2972
+ vaif generate
2973
+ \\\`\\\`\\\`
2974
+
2975
+ 9. **Run the development server**
2976
+
2977
+ \\\`\\\`\\\`bash
2978
+ npm run dev
2979
+ \\\`\\\`\\\`
2980
+
2981
+ ## Project Structure
2982
+
2983
+ \\\`\\\`\\\`
2984
+ .
2985
+ \u251C\u2500\u2500 src/
2986
+ \u2502 \u251C\u2500\u2500 lib/
2987
+ \u2502 \u2502 \u2514\u2500\u2500 vaif.ts # VAIF client + message helpers
2988
+ \u2502 \u2514\u2500\u2500 hooks/
2989
+ \u2502 \u2514\u2500\u2500 useRealtimeMessages.ts # Realtime subscription hook
2990
+ \u251C\u2500\u2500 .env.example # Environment variable template
2991
+ \u2514\u2500\u2500 package.json
2992
+ \\\`\\\`\\\`
2993
+
2994
+ ## Key Files
2995
+
2996
+ - **\\\`src/lib/vaif.ts\\\`** \u2014 VAIF client setup with realtime enabled, plus \\\`sendMessage\\\` and \\\`getMessages\\\` helpers.
2997
+ - **\\\`src/hooks/useRealtimeMessages.ts\\\`** \u2014 React hook that subscribes to live message updates on a channel.
2998
+
2999
+ ## Documentation
3000
+
3001
+ Full documentation is available at <https://docs.vaif.studio>.
3002
+ `}],featureFiles:{database:[{path:"drizzle/0001_initial.sql",content:`-- Initial migration
3003
+ -- Customize this schema for your project
3004
+
3005
+ CREATE TABLE IF NOT EXISTS "users" (
3006
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
3007
+ "email" text NOT NULL UNIQUE,
3008
+ "name" text,
3009
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
3010
+ );
3011
+
3012
+ CREATE TABLE IF NOT EXISTS "posts" (
3013
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
3014
+ "user_id" uuid NOT NULL REFERENCES "users"("id"),
3015
+ "title" text NOT NULL,
3016
+ "content" text,
3017
+ "published" boolean NOT NULL DEFAULT false,
3018
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
3019
+ );
3020
+ `},{path:"drizzle.config.ts",content:`import { defineConfig } from "drizzle-kit";
3021
+
3022
+ export default defineConfig({
3023
+ schema: "./src/db/schema.ts",
3024
+ out: "./drizzle",
3025
+ dialect: "postgresql",
3026
+ dbCredentials: {
3027
+ url: process.env.DATABASE_URL!,
3028
+ },
3029
+ });
3030
+ `},{path:"src/db/schema.ts",content:`import { pgTable, uuid, text, boolean, timestamp } from "drizzle-orm/pg-core";
3031
+
3032
+ export const users = pgTable("users", {
3033
+ id: uuid("id").primaryKey().defaultRandom(),
3034
+ email: text("email").notNull().unique(),
3035
+ name: text("name"),
3036
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3037
+ });
3038
+
3039
+ export const posts = pgTable("posts", {
3040
+ id: uuid("id").primaryKey().defaultRandom(),
3041
+ userId: uuid("user_id").notNull().references(() => users.id),
3042
+ title: text("title").notNull(),
3043
+ content: text("content"),
3044
+ published: boolean("published").notNull().default(false),
3045
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3046
+ });
3047
+ `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
3048
+ const { name } = await req.json().catch(() => ({ name: "World" }));
3049
+ return Response.json({ message: \`Hello, \${name}!\` });
3050
+ }
3051
+ `}]},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
3052
  import { createServerClient } from "@vaiftech/client/server";
1761
3053
 
1762
3054
  // Browser client \u2013 use in Client Components
@@ -1925,7 +3217,144 @@ export async function requireTeamRole(
1925
3217
  NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
1926
3218
  NEXT_PUBLIC_VAIF_API_KEY=your-anon-key
1927
3219
  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";
3220
+ `},{path:"README.md",content:`# SaaS Starter \u2014 VAIF Studio
3221
+
3222
+ A full SaaS starter kit powered by [VAIF Studio](https://vaif.studio) with authentication, team/organization support, role-based access control, and server-side helpers.
3223
+
3224
+ ## Prerequisites
3225
+
3226
+ - [Node.js](https://nodejs.org/) v18 or later
3227
+ - npm (included with Node.js)
3228
+ - A VAIF Studio account \u2014 sign up at <https://vaif.studio>
3229
+
3230
+ ## Setup
3231
+
3232
+ 1. **Install dependencies**
3233
+
3234
+ \\\`\\\`\\\`bash
3235
+ npm install
3236
+ \\\`\\\`\\\`
3237
+
3238
+ 2. **Configure credentials**
3239
+
3240
+ \\\`\\\`\\\`bash
3241
+ cp .env.example .env.local
3242
+ \\\`\\\`\\\`
3243
+
3244
+ Get your Project ID, API Key, and Secret Key from <https://vaif.studio/dashboard> under **Project Settings > API Keys**.
3245
+
3246
+ 3. **Install and log in to the VAIF CLI**
3247
+
3248
+ \\\`\\\`\\\`bash
3249
+ npm install -g @vaiftech/cli
3250
+ vaif login
3251
+ \\\`\\\`\\\`
3252
+
3253
+ 4. **Create required tables**
3254
+
3255
+ Create the following tables in your VAIF dashboard:
3256
+ - \\\`teams\\\` \u2014 id (uuid), name (text), slug (text), owner_id (uuid), created_at (timestamptz)
3257
+ - \\\`team_members\\\` \u2014 id (uuid), team_id (uuid), user_id (uuid), role (text), joined_at (timestamptz)
3258
+
3259
+ 5. **Pull your database schema**
3260
+
3261
+ \\\`\\\`\\\`bash
3262
+ vaif pull
3263
+ \\\`\\\`\\\`
3264
+
3265
+ 6. **Push database migrations** (if using the database feature)
3266
+
3267
+ \\\`\\\`\\\`bash
3268
+ vaif db push
3269
+ \\\`\\\`\\\`
3270
+
3271
+ 7. **Deploy serverless functions** (if using the functions feature)
3272
+
3273
+ \\\`\\\`\\\`bash
3274
+ vaif functions deploy
3275
+ \\\`\\\`\\\`
3276
+
3277
+ 8. **Generate TypeScript types**
3278
+
3279
+ \\\`\\\`\\\`bash
3280
+ vaif generate
3281
+ \\\`\\\`\\\`
3282
+
3283
+ 9. **Run the development server**
3284
+
3285
+ \\\`\\\`\\\`bash
3286
+ npm run dev
3287
+ \\\`\\\`\\\`
3288
+
3289
+ ## Project Structure
3290
+
3291
+ \\\`\\\`\\\`
3292
+ .
3293
+ \u251C\u2500\u2500 lib/
3294
+ \u2502 \u251C\u2500\u2500 vaif.ts # Browser + server VAIF client setup
3295
+ \u2502 \u2514\u2500\u2500 auth.ts # User, team, and role-based auth helpers
3296
+ \u251C\u2500\u2500 .env.example # Environment variable template
3297
+ \u2514\u2500\u2500 package.json
3298
+ \\\`\\\`\\\`
3299
+
3300
+ ## Key Files
3301
+
3302
+ - **\\\`lib/vaif.ts\\\`** \u2014 Browser and server VAIF client setup.
3303
+ - **\\\`lib/auth.ts\\\`** \u2014 Helpers for \\\`getCurrentUser\\\`, \\\`requireUser\\\`, \\\`getUserTeams\\\`, \\\`createTeam\\\`, \\\`inviteToTeam\\\`, and \\\`requireTeamRole\\\`.
3304
+
3305
+ ## Documentation
3306
+
3307
+ Full documentation is available at <https://docs.vaif.studio>.
3308
+ `}],featureFiles:{database:[{path:"drizzle/0001_initial.sql",content:`-- Initial migration
3309
+ -- Customize this schema for your project
3310
+
3311
+ CREATE TABLE IF NOT EXISTS "users" (
3312
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
3313
+ "email" text NOT NULL UNIQUE,
3314
+ "name" text,
3315
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
3316
+ );
3317
+
3318
+ CREATE TABLE IF NOT EXISTS "posts" (
3319
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
3320
+ "user_id" uuid NOT NULL REFERENCES "users"("id"),
3321
+ "title" text NOT NULL,
3322
+ "content" text,
3323
+ "published" boolean NOT NULL DEFAULT false,
3324
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
3325
+ );
3326
+ `},{path:"drizzle.config.ts",content:`import { defineConfig } from "drizzle-kit";
3327
+
3328
+ export default defineConfig({
3329
+ schema: "./src/db/schema.ts",
3330
+ out: "./drizzle",
3331
+ dialect: "postgresql",
3332
+ dbCredentials: {
3333
+ url: process.env.DATABASE_URL!,
3334
+ },
3335
+ });
3336
+ `},{path:"src/db/schema.ts",content:`import { pgTable, uuid, text, boolean, timestamp } from "drizzle-orm/pg-core";
3337
+
3338
+ export const users = pgTable("users", {
3339
+ id: uuid("id").primaryKey().defaultRandom(),
3340
+ email: text("email").notNull().unique(),
3341
+ name: text("name"),
3342
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3343
+ });
3344
+
3345
+ export const posts = pgTable("posts", {
3346
+ id: uuid("id").primaryKey().defaultRandom(),
3347
+ userId: uuid("user_id").notNull().references(() => users.id),
3348
+ title: text("title").notNull(),
3349
+ content: text("content"),
3350
+ published: boolean("published").notNull().default(false),
3351
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3352
+ });
3353
+ `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
3354
+ const { name } = await req.json().catch(() => ({ name: "World" }));
3355
+ return Response.json({ message: \`Hello, \${name}!\` });
3356
+ }
3357
+ `}]},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
3358
  import { createServerClient } from "@vaiftech/client/server";
1930
3359
 
1931
3360
  // Browser client
@@ -2056,21 +3485,158 @@ function getContentType(fileName: string): string {
2056
3485
  NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
2057
3486
  NEXT_PUBLIC_VAIF_API_KEY=your-anon-key
2058
3487
  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"]}};async function J(r){if(!process.stdin.isTTY||!process.stdout.isTTY)return r;let a=new Set(r.map(e=>h.findIndex(o=>o.name===e)).filter(e=>e>=0)),t=0;return new Promise(e=>{let o=k__default.default.createInterface({input:process.stdin,output:process.stdout});k__default.default.emitKeypressEvents(process.stdin,o),process.stdin.setRawMode&&process.stdin.setRawMode(true);function i(){let s=h.length+2;process.stdout.write(`\x1B[${s}A`),l();}function l(){console.log(u__default.default.bold(`
2060
- ? Which VAIF features do you want to include?`)),h.forEach((s,n)=>{let p=a.has(n)?u__default.default.green("[x]"):"[ ]",c=n===t?u__default.default.cyan("> "):" ";console.log(`${c}${p} ${s.label} ${u__default.default.gray(`(${s.description})`)}`);}),console.log(u__default.default.gray(" (up/down to move, space to toggle, enter to confirm)"));}l(),process.stdin.on("keypress",(s,n)=>{if(n.name==="up"&&t>0)t--,i();else if(n.name==="down"&&t<h.length-1)t++,i();else if(n.name==="space")a.has(t)?a.delete(t):a.add(t),i();else if(n.name==="return"){process.stdin.setRawMode&&process.stdin.setRawMode(false),o.close();let p=[...a].sort().map(c=>h[c].name);e(p.length>0?p:r);}else n.name==="c"&&n.ctrl&&(process.stdin.setRawMode&&process.stdin.setRawMode(false),o.close(),process.exit(0));});})}async function D(r,a={}){let t=z[r];t||(console.log(u__default.default.red(`
2061
- Unknown template: ${r}`)),console.log(u__default.default.yellow(`Run 'vaif templates' to see available templates.
2062
- `)),process.exit(1));let e;a.features&&a.features.length>0?e=a.features.filter(s=>h.some(n=>n.name===s)):t.featureFiles&&Object.keys(t.featureFiles).length>0?e=await J(t.defaultFeatures??["database","auth"]):e=t.defaultFeatures??[],console.log(""),console.log(u__default.default.bold(`Scaffolding ${u__default.default.cyan(t.name)} template...`)),e.length>0&&console.log(u__default.default.gray(` Features: ${e.join(", ")}`)),console.log("");let o=[...t.files];if(t.featureFiles)for(let s of e){let n=t.featureFiles[s];n&&o.push(...n);}let i=0,l=0;for(let s of o){let n=S__default.default.resolve(s.path),p=S__default.default.dirname(n);if(v__default.default.existsSync(p)||v__default.default.mkdirSync(p,{recursive:true}),v__default.default.existsSync(n)&&!a.force){console.log(u__default.default.yellow(` skip ${s.path} (already exists)`)),l++;continue}v__default.default.writeFileSync(n,s.content,"utf-8"),console.log(u__default.default.green(` create ${s.path}`)),i++;}console.log(""),i>0&&console.log(u__default.default.green(`Created ${i} file${i!==1?"s":""}.`)),l>0&&console.log(u__default.default.yellow(`Skipped ${l} file${l!==1?"s":""} (use --force to overwrite).`)),(t.dependencies?.length||t.devDependencies?.length)&&(console.log(""),console.log(u__default.default.bold("Install dependencies:")),t.dependencies?.length&&console.log(u__default.default.cyan(` npm install ${t.dependencies.join(" ")}`)),t.devDependencies?.length&&console.log(u__default.default.cyan(` npm install -D ${t.devDependencies.join(" ")}`))),console.log(""),console.log(u__default.default.bold.green("Project scaffolded successfully!")),console.log(""),console.log(u__default.default.bold(" Next steps:")),t.postInstructions.forEach(s=>{console.log(u__default.default.gray(` ${s}`));}),console.log(""),console.log(u__default.default.gray(" Get your project credentials at https://vaif.studio")),console.log("");}var H={$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 G(r){let a=L__default.default("Initializing VAIF configuration...").start(),t=S__default.default.resolve("vaif.config.json");v__default.default.existsSync(t)&&!r.force&&(a.fail("vaif.config.json already exists"),console.log(u__default.default.yellow(`
2063
- Use --force to overwrite existing configuration.`)),process.exit(1));try{if(v__default.default.writeFileSync(t,JSON.stringify(H,null,2),"utf-8"),a.succeed("Created vaif.config.json"),r.template){let e=r.features?r.features.split(",").map(o=>o.trim()):void 0;await D(r.template,{force:r.force,features:e});}else {let e=S__default.default.resolve(".env.example");if(v__default.default.existsSync(e)||(v__default.default.writeFileSync(e,`# VAIF Configuration
3488
+ `},{path:"README.md",content:`# E-commerce API \u2014 VAIF Studio
3489
+
3490
+ An API-first e-commerce setup powered by [VAIF Studio](https://vaif.studio) with product image storage, signed URLs, and server-side helpers.
3491
+
3492
+ ## Prerequisites
3493
+
3494
+ - [Node.js](https://nodejs.org/) v18 or later
3495
+ - npm (included with Node.js)
3496
+ - A VAIF Studio account \u2014 sign up at <https://vaif.studio>
3497
+
3498
+ ## Setup
3499
+
3500
+ 1. **Install dependencies**
3501
+
3502
+ \\\`\\\`\\\`bash
3503
+ npm install
3504
+ \\\`\\\`\\\`
3505
+
3506
+ 2. **Configure credentials**
3507
+
3508
+ \\\`\\\`\\\`bash
3509
+ cp .env.example .env.local
3510
+ \\\`\\\`\\\`
3511
+
3512
+ Get your Project ID, API Key, and Secret Key from <https://vaif.studio/dashboard> under **Project Settings > API Keys**.
3513
+
3514
+ 3. **Install and log in to the VAIF CLI**
3515
+
3516
+ \\\`\\\`\\\`bash
3517
+ npm install -g @vaiftech/cli
3518
+ vaif login
3519
+ \\\`\\\`\\\`
3520
+
3521
+ 4. **Create a storage bucket**
3522
+
3523
+ In your VAIF dashboard, create a \\\`product-images\\\` storage bucket.
3524
+
3525
+ 5. **Pull your database schema**
3526
+
3527
+ \\\`\\\`\\\`bash
3528
+ vaif pull
3529
+ \\\`\\\`\\\`
3530
+
3531
+ 6. **Push database migrations** (if using the database feature)
3532
+
3533
+ \\\`\\\`\\\`bash
3534
+ vaif db push
3535
+ \\\`\\\`\\\`
3536
+
3537
+ 7. **Deploy serverless functions** (if using the functions feature)
3538
+
3539
+ \\\`\\\`\\\`bash
3540
+ vaif functions deploy
3541
+ \\\`\\\`\\\`
3542
+
3543
+ 8. **Generate TypeScript types**
3544
+
3545
+ \\\`\\\`\\\`bash
3546
+ vaif generate
3547
+ \\\`\\\`\\\`
3548
+
3549
+ 9. **Run the development server**
3550
+
3551
+ \\\`\\\`\\\`bash
3552
+ npm run dev
3553
+ \\\`\\\`\\\`
3554
+
3555
+ ## Project Structure
3556
+
3557
+ \\\`\\\`\\\`
3558
+ .
3559
+ \u251C\u2500\u2500 lib/
3560
+ \u2502 \u251C\u2500\u2500 vaif.ts # Browser + server VAIF client setup
3561
+ \u2502 \u2514\u2500\u2500 storage.ts # Product image upload, delete, signed URLs
3562
+ \u251C\u2500\u2500 .env.example # Environment variable template
3563
+ \u2514\u2500\u2500 package.json
3564
+ \\\`\\\`\\\`
3565
+
3566
+ ## Key Files
3567
+
3568
+ - **\\\`lib/vaif.ts\\\`** \u2014 Browser and server VAIF client setup.
3569
+ - **\\\`lib/storage.ts\\\`** \u2014 Helpers for \\\`uploadProductImage\\\`, \\\`deleteProductImage\\\`, \\\`getSignedImageUrl\\\`, and \\\`listProductImages\\\`.
3570
+
3571
+ ## Documentation
3572
+
3573
+ Full documentation is available at <https://docs.vaif.studio>.
3574
+ `}],featureFiles:{database:[{path:"drizzle/0001_initial.sql",content:`-- Initial migration
3575
+ -- Customize this schema for your project
3576
+
3577
+ CREATE TABLE IF NOT EXISTS "users" (
3578
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
3579
+ "email" text NOT NULL UNIQUE,
3580
+ "name" text,
3581
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
3582
+ );
3583
+
3584
+ CREATE TABLE IF NOT EXISTS "posts" (
3585
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
3586
+ "user_id" uuid NOT NULL REFERENCES "users"("id"),
3587
+ "title" text NOT NULL,
3588
+ "content" text,
3589
+ "published" boolean NOT NULL DEFAULT false,
3590
+ "created_at" timestamp with time zone NOT NULL DEFAULT now()
3591
+ );
3592
+ `},{path:"drizzle.config.ts",content:`import { defineConfig } from "drizzle-kit";
3593
+
3594
+ export default defineConfig({
3595
+ schema: "./src/db/schema.ts",
3596
+ out: "./drizzle",
3597
+ dialect: "postgresql",
3598
+ dbCredentials: {
3599
+ url: process.env.DATABASE_URL!,
3600
+ },
3601
+ });
3602
+ `},{path:"src/db/schema.ts",content:`import { pgTable, uuid, text, boolean, timestamp } from "drizzle-orm/pg-core";
3603
+
3604
+ export const users = pgTable("users", {
3605
+ id: uuid("id").primaryKey().defaultRandom(),
3606
+ email: text("email").notNull().unique(),
3607
+ name: text("name"),
3608
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3609
+ });
3610
+
3611
+ export const posts = pgTable("posts", {
3612
+ id: uuid("id").primaryKey().defaultRandom(),
3613
+ userId: uuid("user_id").notNull().references(() => users.id),
3614
+ title: text("title").notNull(),
3615
+ content: text("content"),
3616
+ published: boolean("published").notNull().default(false),
3617
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3618
+ });
3619
+ `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
3620
+ const { name } = await req.json().catch(() => ({ name: "World" }));
3621
+ return Response.json({ message: \`Hello, \${name}!\` });
3622
+ }
3623
+ `}]},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"]}};async function X(n){if(!process.stdin.isTTY||!process.stdout.isTTY)return n;let a=new Set(n.map(e=>y.findIndex(i=>i.name===e)).filter(e=>e>=0)),t=0;return new Promise(e=>{let i=D__default.default.createInterface({input:process.stdin,output:process.stdout});D__default.default.emitKeypressEvents(process.stdin,i),process.stdin.setRawMode&&process.stdin.setRawMode(true);function r(){let u=y.length+2;process.stdout.write(`\x1B[${u}A`),c();}function c(){console.log(m__default.default.bold(`
3624
+ ? Which VAIF features do you want to include?`)),y.forEach((u,l)=>{let o=a.has(l)?m__default.default.green("[x]"):"[ ]",s=l===t?m__default.default.cyan("> "):" ";console.log(`${s}${o} ${u.label} ${m__default.default.gray(`(${u.description})`)}`);}),console.log(m__default.default.gray(" (up/down to move, space to toggle, enter to confirm)"));}c(),process.stdin.on("keypress",(u,l)=>{if(l.name==="up"&&t>0)t--,r();else if(l.name==="down"&&t<y.length-1)t++,r();else if(l.name==="space")a.has(t)?a.delete(t):a.add(t),r();else if(l.name==="return"){process.stdin.setRawMode&&process.stdin.setRawMode(false),i.close();let o=[...a].sort().map(s=>y[s].name);e(o.length>0?o:n);}else l.name==="c"&&l.ctrl&&(process.stdin.setRawMode&&process.stdin.setRawMode(false),i.close(),process.exit(0));});})}async function j(n,a={}){let t=J[n];t||(console.log(m__default.default.red(`
3625
+ Unknown template: ${n}`)),console.log(m__default.default.yellow(`Run 'vaif templates' to see available templates.
3626
+ `)),process.exit(1));let e;a.features&&a.features.length>0?e=a.features.filter(o=>y.some(s=>s.name===o)):t.featureFiles&&Object.keys(t.featureFiles).length>0?e=await X(t.defaultFeatures??["database","auth"]):e=t.defaultFeatures??[],console.log(""),console.log(m__default.default.bold(`Scaffolding ${m__default.default.cyan(t.name)} template...`)),e.length>0&&console.log(m__default.default.gray(` Features: ${e.join(", ")}`)),console.log("");let i=[...t.files];if(t.featureFiles)for(let o of e){let s=t.featureFiles[o];s&&i.push(...s);}let r=0,c=0;for(let o of i){let s=w__default.default.resolve(o.path),d=w__default.default.dirname(s);if(h__default.default.existsSync(d)||h__default.default.mkdirSync(d,{recursive:true}),o.path==="package.json"&&h__default.default.existsSync(s)&&!a.force)try{let p=JSON.parse(h__default.default.readFileSync(s,"utf-8")),g=JSON.parse(o.content),b=C=>{if(!C)return {};let N={};for(let[O,_]of Object.entries(C))!_.startsWith("workspace:")&&!_.startsWith("link:")&&!_.startsWith("file:")&&(N[O]=_);return N};p.dependencies={...b(p.dependencies),...g.dependencies||{}},p.devDependencies={...b(p.devDependencies),...g.devDependencies||{}},g.scripts&&(p.scripts={...p.scripts||{},...g.scripts}),h__default.default.writeFileSync(s,JSON.stringify(p,null,2)+`
3627
+ `,"utf-8"),console.log(m__default.default.green(` merge ${o.path} (added dependencies)`)),r++;continue}catch{}if(h__default.default.existsSync(s)&&!a.force){console.log(m__default.default.yellow(` skip ${o.path} (already exists)`)),c++;continue}h__default.default.writeFileSync(s,o.content,"utf-8"),console.log(m__default.default.green(` create ${o.path}`)),r++;}console.log(""),r>0&&console.log(m__default.default.green(`Created ${r} file${r!==1?"s":""}.`)),c>0&&console.log(m__default.default.yellow(`Skipped ${c} file${c!==1?"s":""} (use --force to overwrite).`));let u={auth:{"@vaiftech/auth":"^1.0.0"},database:{},realtime:{},storage:{},functions:{}},l=w__default.default.resolve("package.json");if(h__default.default.existsSync(l)&&e.length>0)try{let o=JSON.parse(h__default.default.readFileSync(l,"utf-8")),s=!1;for(let d of e){let p=u[d];if(p)for(let[g,b]of Object.entries(p))o.dependencies?.[g]||(o.dependencies=o.dependencies||{},o.dependencies[g]=b,s=!0);}s&&h__default.default.writeFileSync(l,JSON.stringify(o,null,2)+`
3628
+ `,"utf-8");}catch{}(t.dependencies?.length||t.devDependencies?.length)&&(console.log(""),console.log(m__default.default.bold("Install dependencies:")),t.dependencies?.length&&console.log(m__default.default.cyan(` npm install ${t.dependencies.join(" ")}`)),t.devDependencies?.length&&console.log(m__default.default.cyan(` npm install -D ${t.devDependencies.join(" ")}`))),console.log(""),console.log(m__default.default.bold.green("Project scaffolded successfully!")),console.log(""),console.log(m__default.default.bold(" Next steps:")),t.postInstructions.forEach(o=>{console.log(m__default.default.gray(` ${o}`));}),console.log(""),console.log(m__default.default.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 ee(n){let a=z__default.default("Initializing VAIF configuration...").start(),t=w__default.default.resolve("vaif.config.json");h__default.default.existsSync(t)&&!n.force&&(a.fail("vaif.config.json already exists"),console.log(m__default.default.yellow(`
3629
+ Use --force to overwrite existing configuration.`)),process.exit(1));try{if(h__default.default.writeFileSync(t,JSON.stringify(Z,null,2),"utf-8"),a.succeed("Created vaif.config.json"),n.template){let e=n.features?n.features.split(",").map(i=>i.trim()):void 0;await j(n.template,{force:n.force,features:e});}else {let e=w__default.default.resolve(".env.example");if(h__default.default.existsSync(e)||(h__default.default.writeFileSync(e,`# VAIF Configuration
2064
3630
  DATABASE_URL=postgresql://user:password@localhost:5432/database
2065
3631
  VAIF_API_KEY=your-api-key
2066
- `,"utf-8"),console.log(u__default.default.gray("Created .env.example"))),r.typescript){let o=S__default.default.resolve("src/types");v__default.default.existsSync(o)||(v__default.default.mkdirSync(o,{recursive:!0}),console.log(u__default.default.gray("Created src/types directory")));}console.log(""),console.log(u__default.default.green("VAIF initialized successfully!")),console.log(""),console.log(u__default.default.gray("Next steps:")),console.log(u__default.default.gray(" 1. Update vaif.config.json with your project ID")),console.log(u__default.default.gray(" 2. Set DATABASE_URL in your environment")),console.log(u__default.default.gray(" 3. Run: npx vaif generate")),console.log("");}}catch(e){a.fail("Failed to initialize"),e instanceof Error&&console.error(u__default.default.red(`
2067
- Error: ${e.message}`)),process.exit(1);}}async function Fe(r){let{connectionString:a,schema:t="public"}=r,e=new N__default.default.Client({connectionString:a});await e.connect();try{let o=await e.query(`
3632
+ `,"utf-8"),console.log(m__default.default.gray("Created .env.example"))),n.typescript){let i=w__default.default.resolve("src/types");h__default.default.existsSync(i)||(h__default.default.mkdirSync(i,{recursive:!0}),console.log(m__default.default.gray("Created src/types directory")));}console.log(""),console.log(m__default.default.green("VAIF initialized successfully!")),console.log(""),console.log(m__default.default.gray("Next steps:")),console.log(m__default.default.gray(" 1. Update vaif.config.json with your project ID")),console.log(m__default.default.gray(" 2. Set DATABASE_URL in your environment")),console.log(m__default.default.gray(" 3. Run: npx vaif generate")),console.log("");}}catch(e){a.fail("Failed to initialize"),e instanceof Error&&console.error(m__default.default.red(`
3633
+ Error: ${e.message}`)),process.exit(1);}}async function Le(n){let{connectionString:a,schema:t="public"}=n,e=new K__default.default.Client({connectionString:a});await e.connect();try{let i=await e.query(`
2068
3634
  SELECT table_name, table_type
2069
3635
  FROM information_schema.tables
2070
3636
  WHERE table_schema = $1
2071
3637
  AND table_type = 'BASE TABLE'
2072
3638
  ORDER BY table_name
2073
- `,[t]),i=await e.query(`
3639
+ `,[t]),r=await e.query(`
2074
3640
  SELECT
2075
3641
  table_name,
2076
3642
  column_name,
@@ -2085,7 +3651,7 @@ Error: ${e.message}`)),process.exit(1);}}async function Fe(r){let{connectionStri
2085
3651
  FROM information_schema.columns
2086
3652
  WHERE table_schema = $1
2087
3653
  ORDER BY table_name, ordinal_position
2088
- `,[t]),l=await e.query(`
3654
+ `,[t]),c=await e.query(`
2089
3655
  SELECT
2090
3656
  t.typname as enum_name,
2091
3657
  e.enumlabel as enum_value
@@ -2094,16 +3660,16 @@ Error: ${e.message}`)),process.exit(1);}}async function Fe(r){let{connectionStri
2094
3660
  JOIN pg_namespace n ON n.oid = t.typnamespace
2095
3661
  WHERE n.nspname = $1
2096
3662
  ORDER BY t.typname, e.enumsortorder
2097
- `,[t]),s=new Map;for(let c of o.rows)s.set(c.table_name,[]);for(let c of i.rows){let d=s.get(c.table_name);d&&d.push(c);}let n=new Map;for(let c of l.rows){let d=n.get(c.enum_name)||[];d.push(c.enum_value),n.set(c.enum_name,d);}let p=ee(s,n);return O__default.default.format(p,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100})}finally{await e.end();}}var A={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",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",point:"{ x: number; y: number }",ARRAY:"unknown[]"};function Q(r,a){let{data_type:t,udt_name:e,is_nullable:o}=r;if(a.has(e)){let s=a.get(e).map(n=>`"${n}"`).join(" | ");return o==="YES"?`(${s}) | null`:s}if(t==="ARRAY"){let l=e.replace(/^_/,"");if(a.has(l)){let p=a.get(l).map(c=>`"${c}"`).join(" | ");return o==="YES"?`(${p})[] | null`:`(${p})[]`}let s=A[l]||"unknown";return o==="YES"?`${s}[] | null`:`${s}[]`}let i=A[t]||A[e]||"unknown";return o==="YES"&&(i=`${i} | null`),i}function C(r){return r.split(/[_\-\s]+/).map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join("")}function ee(r,a){let t=["/**"," * 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(a.size>0){t.push("// ============ ENUMS ============"),t.push("");for(let[o,i]of a){let l=C(o),s=i.map(n=>` | "${n}"`).join(`
2098
- `);t.push(`export type ${l} =
2099
- ${s};`),t.push("");}}t.push("// ============ TABLES ============"),t.push("");let e=[];for(let[o,i]of r){e.push(o);let l=C(o),s=[],n=[],p=[];for(let c of i){let d=Q(c,a),f=c.column_name,_=c.column_default!==null||c.is_identity==="YES",I=c.is_nullable==="YES";s.push(` ${f}: ${d};`),_||c.column_name==="id"?n.push(` ${f}?: ${d.replace(" | null","")} | null;`):I?n.push(` ${f}?: ${d};`):n.push(` ${f}: ${d.replace(" | null","")};`),p.push(` ${f}?: ${d.replace(" | null","")} | null;`);}t.push(`export interface ${l} {
2100
- ${s.join(`
3663
+ `,[t]),u=new Map;for(let s of i.rows)u.set(s.table_name,[]);for(let s of r.rows){let d=u.get(s.table_name);d&&d.push(s);}let l=new Map;for(let s of c.rows){let d=l.get(s.enum_name)||[];d.push(s.enum_value),l.set(s.enum_name,d);}let o=ie(u,l);return q__default.default.format(o,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100})}finally{await e.end();}}var R={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",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",point:"{ x: number; y: number }",ARRAY:"unknown[]"};function ne(n,a){let{data_type:t,udt_name:e,is_nullable:i}=n;if(a.has(e)){let u=a.get(e).map(l=>`"${l}"`).join(" | ");return i==="YES"?`(${u}) | null`:u}if(t==="ARRAY"){let c=e.replace(/^_/,"");if(a.has(c)){let o=a.get(c).map(s=>`"${s}"`).join(" | ");return i==="YES"?`(${o})[] | null`:`(${o})[]`}let u=R[c]||"unknown";return i==="YES"?`${u}[] | null`:`${u}[]`}let r=R[t]||R[e]||"unknown";return i==="YES"&&(r=`${r} | null`),r}function P(n){return n.split(/[_\-\s]+/).map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join("")}function ie(n,a){let t=["/**"," * 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(a.size>0){t.push("// ============ ENUMS ============"),t.push("");for(let[i,r]of a){let c=P(i),u=r.map(l=>` | "${l}"`).join(`
3664
+ `);t.push(`export type ${c} =
3665
+ ${u};`),t.push("");}}t.push("// ============ TABLES ============"),t.push("");let e=[];for(let[i,r]of n){e.push(i);let c=P(i),u=[],l=[],o=[];for(let s of r){let d=ne(s,a),p=s.column_name,g=s.column_default!==null||s.is_identity==="YES",b=s.is_nullable==="YES";u.push(` ${p}: ${d};`),g||s.column_name==="id"?l.push(` ${p}?: ${d.replace(" | null","")} | null;`):b?l.push(` ${p}?: ${d};`):l.push(` ${p}: ${d.replace(" | null","")};`),o.push(` ${p}?: ${d.replace(" | null","")} | null;`);}t.push(`export interface ${c} {
3666
+ ${u.join(`
2101
3667
  `)}
2102
- }`),t.push(""),t.push(`export interface ${l}Insert {
2103
- ${n.join(`
3668
+ }`),t.push(""),t.push(`export interface ${c}Insert {
3669
+ ${l.join(`
2104
3670
  `)}
2105
- }`),t.push(""),t.push(`export interface ${l}Update {
2106
- ${p.join(`
3671
+ }`),t.push(""),t.push(`export interface ${c}Update {
3672
+ ${o.join(`
2107
3673
  `)}
2108
- }`),t.push("");}t.push("// ============ DATABASE SCHEMA ============"),t.push(""),t.push("export interface Database {");for(let o of e){let i=C(o);t.push(` ${o}: {`),t.push(` Row: ${i};`),t.push(` Insert: ${i}Insert;`),t.push(` Update: ${i}Update;`),t.push(" };");}return t.push("}"),t.push(""),t.push("export type TableName = keyof Database;"),t.push(""),t.push("// ============ HELPER TYPES ============"),t.push(""),t.push('export type Row<T extends TableName> = Database[T]["Row"];'),t.push('export type Insert<T extends TableName> = Database[T]["Insert"];'),t.push('export type Update<T extends TableName> = Database[T]["Update"];'),t.push(""),t.join(`
2109
- `)}exports.generateTypes=q;exports.generateTypesFromConnection=Fe;exports.initConfig=G;exports.loadConfig=x;
3674
+ }`),t.push("");}t.push("// ============ DATABASE SCHEMA ============"),t.push(""),t.push("export interface Database {");for(let i of e){let r=P(i);t.push(` ${i}: {`),t.push(` Row: ${r};`),t.push(` Insert: ${r}Insert;`),t.push(` Update: ${r}Update;`),t.push(" };");}return t.push("}"),t.push(""),t.push("export type TableName = keyof Database;"),t.push(""),t.push("// ============ HELPER TYPES ============"),t.push(""),t.push('export type Row<T extends TableName> = Database[T]["Row"];'),t.push('export type Insert<T extends TableName> = Database[T]["Insert"];'),t.push('export type Update<T extends TableName> = Database[T]["Update"];'),t.push(""),t.join(`
3675
+ `)}exports.generateTypes=W;exports.generateTypesFromConnection=Le;exports.initConfig=ee;exports.loadConfig=E;