# 🚀 StaticFlow

**Automated SSG Engine for React SPAs** — Zero-config static site generation with AI-first optimization.

[![npm version](https://img.shields.io/npm/v/@mamdouh-aboammar/staticflow.svg)](https://www.npmjs.com/package/@mamdouh-aboammar/staticflow)
[![npm downloads](https://img.shields.io/npm/dm/@mamdouh-aboammar/staticflow.svg)](https://www.npmjs.com/package/@mamdouh-aboammar/staticflow)
[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![GitHub stars](https://img.shields.io/github/stars/Pixora-dev-ai/StaticFlow.svg?style=social&label=Star)](https://github.com/Pixora-dev-ai/StaticFlow)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.7-blue)](https://www.typescriptlang.org/)
[![React 19](https://img.shields.io/badge/React-19-61dafb)](https://react.dev/)

---

## 🎯 Problem

**React SPAs render empty HTML:**

```html
<!DOCTYPE html>
<html>
  <head><title>My Site</title></head>
  <body>
    <div id="root"></div>
    <script src="/assets/main.js"></script>
  </body>
</html>
```

**Result:**
- ❌ AI crawlers (ChatGPT, Claude, Gemini) see nothing
- ❌ Search engines index empty pages
- ❌ No SEO/AEO/GEO optimization
- ❌ Poor social media previews

---

## ✨ Solution

**StaticFlow transforms your SPA into fully static, pre-rendered HTML:**

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>My Awesome App | Home</title>
    <meta name="description" content="Welcome to my awesome React application with full SEO support">
    <meta property="og:title" content="My Awesome App">
    <meta property="og:description" content="Full-featured React SPA with static generation">
    <script type="application/ld+json">
      {"@context": "https://schema.org", "@type": "WebSite" ...}
    </script>
  </head>
  <body>
    <nav>...</nav>
    <main>
      <h1>Welcome to My Awesome App</h1>
      <!-- Full pre-rendered content -->
    </main>
    <footer>...</footer>
    <script src="/assets/main.js"></script>
  </body>
</html>
```

**Result:**
- ✅ AI agents read full content
- ✅ Search engines index everything
- ✅ Perfect SEO/AEO/GEO scores
- ✅ Rich social media previews

---

## 📦 Installation

```bash
npm install @mamdouh-aboammar/staticflow --save-dev

# Optional: For ZIP deployment feature
npm install archiver --save-dev
```

---

## 🚀 Quick Start

### 1. Vite Plugin (Recommended)

Add to your `vite.config.ts`:

```typescript
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { staticFlowPlugin } from '@mamdouh-aboammar/staticflow';

export default defineConfig({
  plugins: [
    react(),
    staticFlowPlugin({
      // Zero config! Auto-detects routes, pages, content
    }),
  ],
});
```

Build your site:

```bash
npm run build
```

**That's it!** StaticFlow automatically:
- 📄 Scans all routes in `src/pages/`, `src/routes/`
- 🔧 Pre-renders HTML with React 19 SSR
- 📋 Generates `sitemap.xml` + `ai-sitemap.xml`
- 🗜️ Minifies HTML/CSS/JS
- 🚀 Outputs to `dist/` ready for deployment

---

### 2. CLI Tool

```bash
# Build static site
npx staticflow build

# Analyze project structure
npx staticflow analyze

# Build + create deployment ZIP
npx staticflow build --zip

# Skip optimization
npx staticflow build --no-optimize
```

---

## 📚 API Reference

### `staticFlowPlugin(config?)`

Vite plugin for automatic SSG.

```typescript
interface StaticFlowConfig {
  root?: string;               // Project root (default: process.cwd())
  base?: string;               // Base URL path (default: '/')
  
  routes?: {
    include?: string[];        // Glob patterns (default: ['src/pages/**/*.tsx'])
    exclude?: string[];        // Exclude patterns
  };
  
  content?: {
    dir?: string;              // Content directory (default: 'src/content')
    patterns?: string[];       // File patterns (default: ['**/*.md', '**/*.mdx'])
  };
  
  output?: {
    dir?: string;              // Output directory (default: 'dist')
    sitemap?: boolean;         // Generate sitemaps (default: true)
    robots?: boolean;          // Generate robots.txt (default: true)
  };
  
  seo?: {
    defaultTitle?: string;
    defaultDescription?: string;
    keywords?: string[];
    twitterSite?: string;
    ogImage?: string;
  };
  
  optimization?: {
    minifyHTML?: boolean;      // Minify HTML (default: true)
    minifyCSS?: boolean;       // Minify CSS (default: true)
    minifyJS?: boolean;        // Minify JS (default: true)
    inlineCriticalCSS?: boolean; // Inline critical CSS (default: true)
  };
  
  hooks?: {
    beforeScan?: () => void | Promise<void>;
    afterScan?: (routes: Route[]) => void | Promise<void>;
    beforeRender?: (route: Route) => void | Promise<void>;
    afterRender?: (result: RenderResult) => void | Promise<void>;
    beforeBuild?: () => void | Promise<void>;
    afterBuild?: (result: BuildResult) => void | Promise<void>;
  };
}
```

---

### `StaticFlowEngine`

Programmatic API for advanced use cases.

```typescript
import { StaticFlowEngine } from '@staticflow/core';

const engine = new StaticFlowEngine({
  root: process.cwd(),
  output: { dir: 'dist' },
});

// Scan project
const scanResult = await engine.scan();

// Pre-render routes
await engine.preRender(scanResult.routes, (completed, total) => {
  console.log(`Progress: ${completed}/${total}`);
});

// Generate sitemaps
await engine.generateSitemaps(scanResult.routes);

// Full build
const buildResult = await engine.build();
```

---

## 🎨 Features

### ✅ Zero-Config Auto-Discovery

Automatically finds:
- **Static pages**: `src/pages/Home.tsx` → `/`
- **Nested routes**: `src/pages/about/Team.tsx` → `/about/team`
- **Dynamic routes**: `src/routes/BlogPost.tsx` → `/blog/:slug`
- **Content files**: `src/content/posts/hello.md` → `/blog/hello`

### ✅ React 19 SSR

Uses latest React APIs:
- `renderToStaticMarkup()` for full HTML
- `react-helmet-async` for meta tags
- Streaming support (future)

### ✅ AI-First Optimization

Generates **2 sitemaps**:

**sitemap.xml** (standard):
```xml
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://your-site.com/</loc>
    <lastmod>2025-11-18</lastmod>
    <priority>1.0</priority>
  </url>
</urlset>
```

**ai-sitemap.xml** (AI-optimized):
```xml
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://your-site.com/</loc>
    <priority>1.0</priority>
    <changefreq>weekly</changefreq>
    <ai:content_summary>Comprehensive documentation and guides for React developers...</ai:content_summary>
    <ai:keywords>React, SPA, SSG, SEO, Static Generation, Performance</ai:keywords>
  </url>
</urlset>
```

### ✅ Performance Optimization

- 🗜️ HTML/CSS/JS minification (30-50% reduction)
- 🎨 Critical CSS inlining (faster FCP)
- 📦 Asset compression
- 🚀 Parallel rendering (5 routes at once)

### ✅ Internationalization (i18n)

Preserves:
- `dir` attributes (RTL/LTR)
- `lang` attributes (any language)
- Helmet meta tags in any language
- Structured data localization

---

## 📊 Performance

**Real-world production site (42 pages):**

| Metric | Before (SPA) | After (StaticFlow) | Improvement |
|--------|-------------|-------------------|-------------|
| **HTML Size** | 1.2KB (empty) | 10KB+ (full) | **+733%** |
| **First Contentful Paint** | 2.8s | 0.9s | **3.1x faster** |
| **SEO Score** | 45/100 | 98/100 | **+118%** |
| **AI Indexable** | ❌ 0 pages | ✅ 42 pages | **∞** |
| **Build Time** | 8.2s | 14.2s | +6s |

---

## 🏗️ Architecture

```
StaticFlow Engine
│
├── Scanner (Auto-Discovery)
│   ├── scanStaticPages()   → src/pages/**/*.tsx
│   ├── scanContentFiles()  → src/content/**/*.md
│   └── scanDynamicRoutes() → src/routes/**/*.tsx
│
├── Renderer (SSR)
│   ├── renderRoute()       → React → HTML
│   ├── renderAll()         → Parallel (5x)
│   └── minifyHTML()        → html-minifier-terser
│
├── Optimizer (Assets)
│   ├── minifyHTML()
│   ├── minifyCSS()
│   ├── inlineCriticalCSS()
│   └── compressImages()    → (requires sharp)
│
└── Engine (Orchestrator)
    ├── scan()              → Routes
    ├── preRender()         → HTML files
    ├── generateSitemaps()  → sitemap.xml, ai-sitemap.xml
    └── build()             → Full pipeline
```

---

## 🧪 Testing

```bash
# Run tests
npm test

# Type check
npm run typecheck

# Build library
npm run build
```

---

## 📝 Examples

### Custom SEO

```typescript
staticFlowPlugin({
  seo: {
    defaultTitle: 'My Awesome App',
    defaultDescription: 'A modern React application with full SEO support',
    keywords: ['react', 'spa', 'ssg', 'seo'],
    ogImage: 'https://your-site.com/og-image.jpg',
    twitterSite: '@your_handle',
  },
});
```

### Lifecycle Hooks

```typescript
staticFlowPlugin({
  hooks: {
    afterScan: async (routes) => {
      console.log(`Found ${routes.length} routes`);
    },
    beforeRender: async (route) => {
      console.log(`Rendering ${route.path}...`);
    },
    afterBuild: async (result) => {
      console.log(`Build complete in ${result.duration}ms`);
    },
  },
});
```

### Custom Routes

```typescript
staticFlowPlugin({
  routes: {
    include: [
      'src/pages/**/*.tsx',
      'src/views/**/*.tsx',
      'app/routes/**/*.tsx',
    ],
    exclude: ['**/*.test.tsx', '**/*.stories.tsx'],
  },
});
```

---

## 🚢 Deployment

### Hostinger (Apache/LiteSpeed)

```bash
# Build + ZIP
npx staticflow build --zip

# Upload to Hostinger
# Extract to public_html/
# Done! ✅
```

### Vercel/Netlify

```bash
npm run build
# Outputs to dist/
# Auto-deploys via Git
```

### Docker

```dockerfile
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Serve dist/ with nginx/serve
```

---

## 🤝 Contributing

We welcome contributions! See [CONTRIBUTING.md](CONTRIBUTING.md).

---

## 📄 License

MIT © 2025 Mamdouh Aboammar

---

## 🙏 Credits

**Built with:**
- [React 19](https://react.dev/) — UI framework
- [Vite](https://vite.dev/) — Build tool
- [TypeScript](https://www.typescriptlang.org/) — Type safety
- [fast-glob](https://github.com/mrmlnc/fast-glob) — File scanning
- [gray-matter](https://github.com/jonschlinkert/gray-matter) — Markdown parsing
- [html-minifier-terser](https://github.com/terser/html-minifier-terser) — HTML optimization

---

## 📞 Support

- **Issues**: [GitHub Issues](https://github.com/Pixora-dev-ai/StaticFlow/issues)
- **Discussions**: [GitHub Discussions](https://github.com/Pixora-dev-ai/StaticFlow/discussions)
- **Email**: mamdouhfces1997@gmail.com

---

**Made with ❤️ for the React community**
