feat: base build template, free plan with usage limits

This commit is contained in:
Zebratic committed 2026-03-14 18:16:22 +00:00
1 parent 5b9a1f90f3
commit 74a46db4d9
15 files changed
+290 -107

No files matched your search

+84 -85
View File
@@ -81,97 +81,96 @@ async function runBuild({ buildId, files, appName, packageName, version }) {
}
fs.mkdirSync(projectDir, { recursive: true });
// Write all project files
// ── Template-based build: start from golden template, merge LLM additions ──
const TEMPLATE_DIR = path.join(__dirname, "template");
const CONFIG_FILES = ["package.json", "app.json", "babel.config.js", "tsconfig.json"];
// 1. Copy template files as the base
for (const cf of CONFIG_FILES) {
const src = path.join(TEMPLATE_DIR, cf);
const dst = path.join(projectDir, cf);
if (fs.existsSync(src)) {
fs.copyFileSync(src, dst);
}
}
// 2. Parse LLM-generated package.json for extra deps (if any)
const pkgPath = path.join(projectDir, "package.json");
const templatePkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
const coreDeps = new Set(Object.keys(templatePkg.dependencies));
const coreDevDeps = new Set(Object.keys(templatePkg.devDependencies || {}));
if (files["package.json"]) {
try {
const llmPkg = JSON.parse(files["package.json"]);
// Add extra deps that aren't in the template (never override core)
for (const [dep, ver] of Object.entries(llmPkg.dependencies || {})) {
if (!coreDeps.has(dep)) {
templatePkg.dependencies[dep] = ver;
}
}
for (const [dep, ver] of Object.entries(llmPkg.devDependencies || {})) {
if (!coreDevDeps.has(dep)) {
templatePkg.devDependencies[dep] = ver;
}
}
} catch (e) {
log(buildId, "warn", "Could not parse LLM package.json, using template only");
}
}
// Update package name
templatePkg.name = (packageName || "apk-forge-app").replace(/[^a-z0-9-]/g, "-");
fs.writeFileSync(pkgPath, JSON.stringify(templatePkg, null, 2));
// 3. Merge app.json — take name/slug/colors from LLM, keep template structure
const appJsonPath = path.join(projectDir, "app.json");
const templateAppJson = JSON.parse(fs.readFileSync(appJsonPath, "utf-8"));
if (files["app.json"]) {
try {
const llmAppJson = JSON.parse(files["app.json"]);
const llmExpo = llmAppJson.expo || {};
// Merge cosmetic fields from LLM
if (llmExpo.name) templateAppJson.expo.name = llmExpo.name;
if (llmExpo.slug) templateAppJson.expo.slug = llmExpo.slug;
if (llmExpo.icon) templateAppJson.expo.icon = llmExpo.icon;
if (llmExpo.splash?.backgroundColor) templateAppJson.expo.splash.backgroundColor = llmExpo.splash.backgroundColor;
if (llmExpo.android?.adaptiveIcon?.backgroundColor) {
templateAppJson.expo.android.adaptiveIcon.backgroundColor = llmExpo.android.adaptiveIcon.backgroundColor;
}
if (llmExpo.android?.package) templateAppJson.expo.android.package = llmExpo.android.package;
// Merge extra plugins from LLM
if (llmExpo.plugins) {
const existingPlugins = new Set(templateAppJson.expo.plugins.map(p => typeof p === "string" ? p : p[0]));
for (const plugin of llmExpo.plugins) {
const pluginName = typeof plugin === "string" ? plugin : plugin[0];
if (!existingPlugins.has(pluginName)) {
templateAppJson.expo.plugins.push(plugin);
}
}
}
} catch (e) {
log(buildId, "warn", "Could not parse LLM app.json, using template only");
}
}
// Apply defaults
const safeName = (appName || templateAppJson.expo.name || "APK Forge App").replace(/[^a-zA-Z0-9 ]/g, "");
const safeSlug = safeName.toLowerCase().replace(/\s+/g, "-");
templateAppJson.expo.name = safeName;
if (!templateAppJson.expo.slug || templateAppJson.expo.slug === "my-app") templateAppJson.expo.slug = safeSlug;
if (!templateAppJson.expo.android.package) {
templateAppJson.expo.android.package = packageName || `com.apkforge.${safeSlug.replace(/-/g, "")}`;
}
fs.writeFileSync(appJsonPath, JSON.stringify(templateAppJson, null, 2));
// 4. Write only LLM-generated source files (skip config files handled by template)
const skipFiles = new Set(CONFIG_FILES);
for (const [filePath, content] of Object.entries(files)) {
if (skipFiles.has(filePath)) continue;
const fullPath = path.join(projectDir, filePath);
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
fs.writeFileSync(fullPath, content);
}
// Force correct package.json with compatible Expo deps (LLM often generates ancient versions)
const pkgPath = path.join(projectDir, "package.json");
const REQUIRED_DEPS = {
"expo": "~52.0.0",
"expo-status-bar": "~2.0.0",
"react": "18.3.1",
"react-native": "0.76.3",
"react-native-screens": "~4.1.0",
"react-native-safe-area-context": "~5.0.0",
"@expo/vector-icons": "^14.0.0"
};
const REQUIRED_DEV_DEPS = {
"@babel/core": "^7.24.0",
"typescript": "~5.3.3",
"@types/react": "~18.2.45"
};
let pkg;
if (fs.existsSync(pkgPath)) {
pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
// Force main entry point
pkg.main = "expo/AppEntry.js";
// Override core deps with known-working versions
pkg.dependencies = { ...(pkg.dependencies || {}), ...REQUIRED_DEPS };
// Fix navigation deps if present (force v7 compatible with Expo 52)
if (pkg.dependencies["@react-navigation/native"]) pkg.dependencies["@react-navigation/native"] = "^7.0.0";
if (pkg.dependencies["@react-navigation/native-stack"]) pkg.dependencies["@react-navigation/native-stack"] = "^7.0.0";
if (pkg.dependencies["react-native-reanimated"]) pkg.dependencies["react-native-reanimated"] = "~3.16.0";
if (pkg.dependencies["react-native-gesture-handler"]) pkg.dependencies["react-native-gesture-handler"] = "~2.20.0";
pkg.devDependencies = { ...(pkg.devDependencies || {}), ...REQUIRED_DEV_DEPS };
// Remove old expo config from package.json (use app.json instead)
delete pkg.expo;
} else {
pkg = {
name: (packageName || "apk-forge-app").replace(/[^a-z0-9-]/g, "-"),
version: "1.0.0",
main: "expo/AppEntry.js",
scripts: {
start: "expo start",
android: "expo start --android",
ios: "expo start --ios",
web: "expo start --web"
},
dependencies: {
...REQUIRED_DEPS,
"@react-navigation/native": "^7.0.0",
"@react-navigation/native-stack": "^7.0.0",
},
devDependencies: REQUIRED_DEV_DEPS
};
}
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
// Ensure app.json exists
const appJsonPath = path.join(projectDir, "app.json");
if (!fs.existsSync(appJsonPath)) {
const safeName = (appName || "APK Forge App").replace(/[^a-zA-Z0-9 ]/g, "");
const safeSlug = safeName.toLowerCase().replace(/\s+/g, "-");
const appJson = {
expo: {
name: safeName,
slug: safeSlug,
version: "1.0.0",
orientation: "portrait",
icon: "./assets/icon.png",
userInterfaceStyle: "automatic",
newArchEnabled: true,
splash: {
image: "./assets/splash-icon.png",
resizeMode: "contain",
backgroundColor: "#1a1a2e"
},
android: {
adaptiveIcon: {
foregroundImage: "./assets/adaptive-icon.png",
backgroundColor: "#1a1a2e"
},
package: packageName || `com.apkforge.${safeSlug.replace(/-/g, "")}`
},
plugins: ["expo-router"]
}
};
fs.writeFileSync(appJsonPath, JSON.stringify(appJson, null, 2));
}
// Create placeholder assets if missing
const assetsDir = path.join(projectDir, "assets");
fs.mkdirSync(assetsDir, { recursive: true });
+32
View File
@@ -0,0 +1,32 @@
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { StatusBar } from 'expo-status-bar';
export default function App() {
return (
<View style={styles.container}>
<Text style={styles.title}>Welcome to My App</Text>
<Text style={styles.subtitle}>Built with APK Forge</Text>
<StatusBar style="light" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#1a1a2e',
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontSize: 28,
fontWeight: 'bold',
color: '#ffffff',
marginBottom: 8,
},
subtitle: {
fontSize: 16,
color: '#a0a0b0',
},
});
+24
View File
@@ -0,0 +1,24 @@
{
"expo": {
"name": "My App",
"slug": "my-app",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/icon.png",
"userInterfaceStyle": "automatic",
"newArchEnabled": true,
"splash": {
"image": "./assets/splash-icon.png",
"resizeMode": "contain",
"backgroundColor": "#1a1a2e"
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#1a1a2e"
},
"package": "com.apkforge.myapp"
},
"plugins": ["expo-font", "expo-haptics"]
}
}
+4
View File
@@ -0,0 +1,4 @@
module.exports = function (api) {
api.cache(true);
return { presets: ['babel-preset-expo'] };
};
+31
View File
@@ -0,0 +1,31 @@
{
"name": "apk-forge-app",
"version": "1.0.0",
"main": "expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android"
},
"dependencies": {
"expo": "~52.0.0",
"expo-status-bar": "~2.0.0",
"react": "18.3.1",
"react-native": "0.76.3",
"@react-navigation/native": "^7.0.0",
"@react-navigation/native-stack": "^7.0.0",
"react-native-screens": "~4.1.0",
"react-native-safe-area-context": "~5.0.0",
"react-native-reanimated": "~3.16.0",
"react-native-gesture-handler": "~2.20.0",
"@expo/vector-icons": "^14.0.0",
"expo-linear-gradient": "~14.0.0",
"expo-haptics": "~14.0.0",
"expo-font": "~13.0.0",
"@react-native-async-storage/async-storage": "2.1.0"
},
"devDependencies": {
"@babel/core": "^7.24.0",
"typescript": "~5.3.3",
"@types/react": "~18.2.45"
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "expo/tsconfig.base",
"compilerOptions": {
"strict": true
}
}
+7 -1
View File
@@ -76,7 +76,13 @@ export async function POST(req: NextRequest) {
// Check build limit
const buildCheck = await checkBuildLimit(session.userId);
if (!buildCheck.allowed) {
return NextResponse.json({ error: "Build limit reached. Upgrade your plan." }, { status: 403 });
// Fetch user to give plan-specific message
const db2 = await getDb();
const buildUser = await db2.collection("users").findOne({ _id: new ObjectId(session.userId) });
const errorMsg = buildUser?.plan === "free"
? "Free plan allows 3 APK builds per month. Upgrade to continue."
: "Build limit reached. Upgrade your plan.";
return NextResponse.json({ error: errorMsg }, { status: 403 });
}
// Determine version
+12 -3
View File
@@ -1,6 +1,6 @@
// @ts-nocheck
import { NextRequest, NextResponse } from "next/server";
import { getSession, incrementUsage, checkBuildLimit } from "@/lib/auth";
import { getSession, incrementUsage, checkBuildLimit, checkLlmLimit } from "@/lib/auth";
import { checkRateLimit } from "@/lib/rate-limit";
import { getDb } from "@/lib/db";
import { callLLM } from "@/lib/llm";
@@ -67,6 +67,15 @@ export async function POST(req: NextRequest) {
);
}
// Check LLM usage limit (free plan)
const llmCheck = await checkLlmLimit(session.userId);
if (!llmCheck.allowed) {
return NextResponse.json(
{ error: "Free plan allows 50 AI messages per month. Upgrade to continue." },
{ status: 403 }
);
}
const { projectId, message, questionAnswers, markFormSubmitted } = await req.json();
// Handle marking a form as submitted (no LLM call needed)
@@ -168,8 +177,8 @@ export async function POST(req: NextRequest) {
projectName: project.name,
});
// Track usage
await incrementUsage(session.userId, "totalPrompts");
// Track usage (increments both promptsThisMonth and totalPrompts)
await incrementUsage(session.userId, "promptsThisMonth");
// If build is ready, check limits and increment
if (aiResponse.buildReady) {
+12
View File
@@ -24,6 +24,13 @@ interface UserInfo {
username: string;
role: string;
plan: string;
usage?: {
buildsThisMonth: number;
promptsThisMonth: number;
totalBuilds: number;
totalPrompts: number;
monthResetAt: string;
};
}
const templates = [
@@ -146,6 +153,11 @@ export default function DashboardPage() {
<Link href="/dashboard/settings" className="text-zinc-400 hover:text-white"><Settings className="w-4 h-4" /></Link>
<span className="text-sm text-zinc-500">{user?.username}</span>
<span className="text-xs px-2 py-0.5 rounded-full bg-zinc-800 text-zinc-400 capitalize">{user?.plan}</span>
{user?.usage && (
<span className="text-xs text-zinc-500 hidden sm:inline">
{user.usage.promptsThisMonth || 0}/{user.plan === "free" ? "50" : "∞"} AI messages · {user.usage.buildsThisMonth || 0}/{user.plan === "free" ? "3" : user.plan === "starter" ? "10" : user.plan === "pro" ? "50" : "∞"} builds
</span>
)}
<button onClick={logout} className="text-zinc-400 hover:text-white"><LogOut className="w-4 h-4" /></button>
</div>
</div>
+7 -2
View File
@@ -17,9 +17,14 @@ const steps = [
];
const plans = [
{
name: "Free", price: "$0", period: "/month",
features: ["3 builds per month", "50 AI messages per month", "Source code download", "Community support"],
cta: "Get Started", highlight: false,
},
{
name: "Starter", price: "$12", period: "/month",
features: ["10 builds per month", "AI-powered code generation", "Source code download", "APK builds", "Build history"],
features: ["10 builds per month", "Unlimited AI messages", "Source code download", "APK builds", "Build history"],
cta: "Get Started", highlight: false,
},
{
@@ -195,7 +200,7 @@ export default function Home() {
<div className="max-w-5xl mx-auto">
<h2 className="text-3xl font-bold text-center mb-4">Simple Pricing</h2>
<p className="text-center text-zinc-400 mb-12">No hidden fees. Cancel anytime.</p>
<div className="grid md:grid-cols-3 gap-6">
<div className="grid md:grid-cols-4 gap-6">
{plans.map((plan) => (
<div key={plan.name} className={`p-6 rounded-xl border flex flex-col ${plan.highlight ? "border-blue-500 bg-blue-500/5 ring-1 ring-blue-500/20" : "border-zinc-800 bg-zinc-900/50"}`}>
{plan.highlight && <div className="text-xs font-medium text-blue-400 mb-2">Most popular</div>}
+42 -14
View File
@@ -76,11 +76,12 @@ export async function createUser(
email: email.toLowerCase().trim(),
passwordHash,
role: "user",
plan: "starter" as PlanTier,
plan: "free" as PlanTier,
emailVerified: false,
emailVerificationToken: generateToken(),
usage: {
buildsThisMonth: 0,
promptsThisMonth: 0,
totalBuilds: 0,
totalPrompts: 0,
monthResetAt: getNextMonthReset(),
@@ -119,32 +120,41 @@ export async function updateUser(id: string, update: Partial<User>): Promise<voi
// ─── Usage Tracking ─────────────────────────────────────────────
export async function incrementUsage(
userId: string,
field: "buildsThisMonth" | "totalBuilds" | "totalPrompts"
field: "buildsThisMonth" | "promptsThisMonth" | "totalBuilds" | "totalPrompts"
): Promise<void> {
const db = await getDb();
const user = await findUserById(userId);
if (!user) return;
// Reset monthly counter if needed
const isMonthlyField = field === "buildsThisMonth" || field === "promptsThisMonth";
// Reset monthly counters if needed
if (new Date() >= user.usage.monthResetAt) {
const setFields: Record<string, unknown> = {
"usage.buildsThisMonth": field === "buildsThisMonth" ? 1 : 0,
"usage.promptsThisMonth": field === "promptsThisMonth" ? 1 : 0,
"usage.monthResetAt": getNextMonthReset(),
updatedAt: new Date(),
};
const incFields: Record<string, number> = {};
if (field === "buildsThisMonth") incFields["usage.totalBuilds"] = 1;
else if (field === "promptsThisMonth") incFields["usage.totalPrompts"] = 1;
else incFields[`usage.${field}`] = 1;
await db.collection("users").updateOne(
{ _id: new ObjectId(userId) },
{
$set: {
"usage.buildsThisMonth": field === "buildsThisMonth" ? 1 : 0,
"usage.monthResetAt": getNextMonthReset(),
updatedAt: new Date(),
},
$inc: {
[`usage.${field === "buildsThisMonth" ? "totalBuilds" : field}`]: 1,
},
}
{ $set: setFields, $inc: incFields }
);
} else {
const incFields: Record<string, number> = { [`usage.${field}`]: 1 };
// Also increment the total counter for monthly fields
if (field === "buildsThisMonth") incFields["usage.totalBuilds"] = 1;
else if (field === "promptsThisMonth") incFields["usage.totalPrompts"] = 1;
await db.collection("users").updateOne(
{ _id: new ObjectId(userId) },
{
$inc: { [`usage.${field}`]: 1 },
$inc: incFields,
$set: { updatedAt: new Date() },
}
);
@@ -169,6 +179,24 @@ export async function checkBuildLimit(userId: string): Promise<{ allowed: boolea
return { allowed: remaining > 0, remaining };
}
export async function checkLlmLimit(userId: string): Promise<{ allowed: boolean; remaining: number }> {
const user = await findUserById(userId);
if (!user) return { allowed: false, remaining: 0 };
const { plan, usage } = user;
const allLimits = (await import("@/types")).PLAN_LIMITS;
const limits = allLimits[plan] || allLimits["free"] || { llmRequestsPerMonth: 50 };
if (limits.llmRequestsPerMonth === -1) return { allowed: true, remaining: -1 };
// Reset if month passed
let currentPrompts = usage.promptsThisMonth || 0;
if (new Date() >= usage.monthResetAt) currentPrompts = 0;
const remaining = limits.llmRequestsPerMonth - currentPrompts;
return { allowed: remaining > 0, remaining };
}
// ─── Helpers ────────────────────────────────────────────────────
function generateToken(): string {
return crypto.randomBytes(32).toString('hex');
+1
View File
@@ -8,6 +8,7 @@ interface RateLimitEntry {
}
const RATE_LIMITS: Record<PlanTier, number> = {
free: 5,
starter: 10,
pro: 30,
unlimited: 60,
+12
View File
@@ -65,6 +65,18 @@ When the user describes an app for the first time:
6. Set \`buildReady\` to true — the project MUST be complete and buildable
7. The \`questions\` array MUST be empty when generating files
### Available Packages
The project uses Expo SDK 52 with React Native 0.76. The following packages are pre-installed and available:
- expo, expo-status-bar, expo-linear-gradient, expo-haptics, expo-font
- @react-navigation/native, @react-navigation/native-stack
- react-native-screens, react-native-safe-area-context
- react-native-reanimated, react-native-gesture-handler
- @expo/vector-icons (MaterialIcons, Ionicons, FontAwesome, etc.)
- @react-native-async-storage/async-storage
Use these packages freely. If you need additional packages, include them in package.json dependencies.
Do NOT specify version numbers for expo, react, or react-native in package.json — the build system handles versions.
### Code Style
- Use TypeScript for all React Native code
- Follow Material Design 3 patterns
+15 -1
View File
@@ -1,30 +1,41 @@
import { ObjectId } from "mongodb";
// ─── Subscription & Plans ───────────────────────────────────────
export type PlanTier = "starter" | "pro" | "unlimited";
export type PlanTier = "free" | "starter" | "pro" | "unlimited";
export interface PlanLimits {
buildsPerMonth: number; // -1 = unlimited
llmRequestsPerMonth: number; // -1 = unlimited
models: string[];
priorityBuild: boolean;
customBranding: boolean;
}
export const PLAN_LIMITS: Record<PlanTier, PlanLimits> = {
free: {
buildsPerMonth: 3,
llmRequestsPerMonth: 50,
models: ["gpt-4.1-mini"],
priorityBuild: false,
customBranding: false,
},
starter: {
buildsPerMonth: 10,
llmRequestsPerMonth: -1,
models: ["claude-sonnet-4-6", "gpt-4.1-mini"],
priorityBuild: false,
customBranding: false,
},
pro: {
buildsPerMonth: 50,
llmRequestsPerMonth: -1,
models: ["claude-sonnet-4-6", "gpt-4.1-mini", "claude-opus-4-6", "gpt-5-mini", "deepseek-chat"],
priorityBuild: true,
customBranding: false,
},
unlimited: {
buildsPerMonth: -1,
llmRequestsPerMonth: -1,
models: ["claude-sonnet-4-6", "gpt-4.1-mini", "claude-opus-4-6", "gpt-5-mini", "gpt-5.4", "o3", "deepseek-chat"],
priorityBuild: true,
customBranding: true,
@@ -32,12 +43,14 @@ export const PLAN_LIMITS: Record<PlanTier, PlanLimits> = {
};
export const PLAN_PRICES: Record<PlanTier, number> = {
free: 0,
starter: 12,
pro: 29,
unlimited: 59,
};
export const PLAN_NAMES: Record<PlanTier, string> = {
free: "Free",
starter: "Starter",
pro: "Pro",
unlimited: "Unlimited",
@@ -60,6 +73,7 @@ export interface User {
passwordResetExpires?: Date;
usage: {
buildsThisMonth: number;
promptsThisMonth: number;
totalBuilds: number;
totalPrompts: number;
monthResetAt: Date;
+1 -1
View File
@@ -30,5 +30,5 @@
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
"exclude": ["node_modules", "build-worker"]
}