npm package: @gringow/gringow-nextjs
Description: A Next.js plugin for Gringow AI-powered translation tool
Author: Renato Gaspar
Latest version: 0.2.2

# @gringow/gringow-nextjs

[![npm version](https://img.shields.io/npm/v/@gringow/gringow-nextjs)](https://www.npmjs.com/package/@gringow/gringow-nextjs)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

⚠️ **Experimental** Next.js integration for Gringow AI-powered translations. Currently targets Turbopack with minimal build-time cache generation.

## ⚠️ Status: Experimental

This package is in early development and provides basic functionality. For production use, consider:
- **[@gringow/gringow-vite](https://www.npmjs.com/package/@gringow/gringow-vite)** - Production-ready Vite plugin
- **[@gringow/gringow-cli](https://www.npmjs.com/package/@gringow/gringow-cli)** - CLI cache builder

## Features

- 🎯 **Turbopack-First** - Built for Next.js 15+ with Turbopack
- 🔍 **Auto-Extraction** - Scans for `g` tagged templates
- 💾 **Cache Building** - Generates translations on first request
- ⚡ **Minimal Setup** - Simple configuration wrapper

## Current Limitations

- **Turbopack only** - Webpack integration is a stub (no build hooks)
- **No CLI flags** - `--gringow=build|clear|reset` not implemented
- **Headers hook** - Cache builds during `headers()` call (not ideal)
- **No cache pruning** - Stale entries not removed automatically

**Contributions welcome** to improve Webpack support and add proper build hooks!

## Installation

```bash
# Using pnpm
pnpm add @gringow/gringow-nextjs @gringow/gringow @gringow/gringow-react

# Using npm
npm install @gringow/gringow-nextjs @gringow/gringow @gringow/gringow-react

# Using yarn
yarn add @gringow/gringow-nextjs @gringow/gringow @gringow/gringow-react
```

## Quick Start

### 1. Configure Next.js

```typescript
// next.config.ts
import type { NextConfig } from 'next'
import GringowNextjsPlugin from '@gringow/gringow-nextjs/plugin'

const withGringow = GringowNextjsPlugin({
  debug: process.env.NODE_ENV === 'development'
})

const nextConfig: NextConfig = {
  // Your Next.js configuration
  experimental: {
    turbo: {}, // Turbopack recommended
  },
}

export default withGringow(nextConfig)
```

### 2. Create Gringow Config

```javascript
// gringow.config.js
export default {
  llm: {
    provider: 'openai',
    apiKey: process.env.OPENAI_API_KEY,
    model: 'gpt-4o-mini',
  },
  languages: ['pt-BR', 'es-ES', 'fr-CA'],
  sourceLanguage: 'en-US',
  globby: './app/**/*.{ts,tsx}', // Adjust to your structure
}
```

### 3. Use in Components

```tsx
// app/page.tsx
import { g } from '@gringow/gringow-react'

export default function HomePage() {
  const name = 'Alice'
  
  return (
    <div>
      <h1>{g`Welcome ${name}!`}</h1>
      <p>{g`This text will be automatically translated.`}</p>
    </div>
  )
}
```

### 4. Run Development Server

```bash
pnpm dev

# First request triggers cache build
# Translations stored in ./gringow/gringow.json
```

## Configuration

### Plugin Options

```typescript
interface GringowNextjsPluginOptions {
  debug?: boolean  // Log cache build operations (default: false)
}
```

**Example:**
```typescript
const withGringow = GringowNextjsPlugin({ debug: true })
```

### Gringow Config

The plugin reads your `gringow.config.js`:

- **`globby`** - File patterns to scan (e.g., `'./app/**/*.{ts,tsx}'`)
- **`llm.*`** - LLM provider configuration
- **`languages`** - Target translation languages
- **`cache.dir`** - Cache directory (default: `'./gringow'`)

See [@gringow/gringow](https://www.npmjs.com/package/@gringow/gringow) for complete options.

## How It Works

### Turbopack Flow

1. **Plugin wraps** Next.js config with Gringow middleware
2. **Headers hook** - First `headers()` call triggers cache build
3. **File scanning** - Uses `globby` pattern from config
4. **Extraction** - Finds all `g` tagged templates
5. **Translation** - Calls core library to translate
6. **Cache write** - Stores in `./gringow/gringow.json`

### Webpack Flow

Currently returns config unchanged. Build hooks not yet implemented.

## Usage Examples

### App Router with Server Components

```tsx
// app/page.tsx
import { g } from '@gringow/gringow-react'

export default async function Page() {
  const data = await fetchData()
  
  return (
    <main>
      <h1>{g`Welcome to our platform`}</h1>
      <p>{g`You have ${data.count} items`}</p>
    </main>
  )
}
```

### Pages Router

```tsx
// pages/index.tsx
import { g } from '@gringow/gringow-react'
import type { NextPage } from 'next'

const HomePage: NextPage = () => {
  return (
    <div>
      <h1>{g`Home Page`}</h1>
      <p>{g`Welcome back!`}</p>
    </div>
  )
}

export default HomePage
```

### Client Components

```tsx
'use client'

import { g, changeLanguage } from '@gringow/gringow-react'
import { useEffect } from 'react'

export function LanguageSwitcher() {
  useEffect(() => {
    // Initialize Gringow store on client
    import('@gringow/gringow-react/store').then(({ GringowStore }) => {
      GringowStore.cacheUrl = '/gringow/gringow.json'
      GringowStore.language = 'en-US'
      GringowStore.fetchCache()
    })
  }, [])

  return (
    <div>
      <button onClick={() => changeLanguage('en-US')}>
        {g`English`}
      </button>
      <button onClick={() => changeLanguage('pt-BR')}>
        {g`Portuguese`}
      </button>
    </div>
  )
}
```

## Development scripts
```bash
pnpm run build   # Emit dist/ with tsup
pnpm run watch   # Continuous rebuild for local development
```

## License
MIT © Renato Gaspar

## Workarounds & Tips

### Pre-Build Cache

Since CLI flags aren't implemented, generate cache before deployment:

```bash
# Use CLI to build cache
pnpm gringow cache list  # or use Vite plugin
```

### Commit Cache File

For faster deployments, commit `gringow/gringow.json`:

```bash
git add gringow/gringow.json
git commit -m "Add translation cache"
```

### Use Vite for Development

For better DX, develop with Vite and deploy with Next.js:

```json
{
  "scripts": {
    "dev": "vite",
    "build:translations": "vite build --gringow=build",
    "build": "pnpm build:translations && next build"
  }
}
```

## Known Issues

- **Webpack**: No build hooks - returns config unchanged
- **CLI flags**: `--gringow=build|clear|reset` not supported
- **Cache pruning**: Stale entries not automatically removed
- **Build timing**: Cache builds on first request, not at build time

## Roadmap

- [ ] Proper Webpack integration with build hooks
- [ ] CLI flags support (`--gringow=build|clear|reset`)
- [ ] Build-time cache generation (not request-time)
- [ ] Automatic cache pruning
- [ ] Better error handling and logging

**Want to contribute?** PRs welcome on [GitHub](https://github.com/rntgspr/gringow)!

## Development

```bash
# Install dependencies
pnpm install

# Build the plugin
pnpm run build

# Watch mode
pnpm run watch
```

## Related Packages

Gringow provides a complete ecosystem for AI-powered translation:

- **[@gringow/gringow](https://www.npmjs.com/package/@gringow/gringow)** - Core translation library
- **[@gringow/gringow-vite](https://www.npmjs.com/package/@gringow/gringow-vite)** - Vite plugin for build-time extraction
- **[@gringow/gringow-react](https://www.npmjs.com/package/@gringow/gringow-react)** - React hooks and components
- **[@gringow/gringow-shadow](https://www.npmjs.com/package/@gringow/gringow-shadow)** - Web Component layer
- **[@gringow/gringow-cli](https://www.npmjs.com/package/@gringow/gringow-cli)** - CLI tool
- **[@gringow/gringow-nextjs](https://www.npmjs.com/package/@gringow/gringow-nextjs)** - Next.js plugin (experimental)

## Resources

- [Documentation](https://gringow.dev)
- [GitHub Repository](https://github.com/rntgspr/gringow)
- [Vite Example](https://github.com/rntgspr/gringow/tree/main/example-gringow-vite)

## License

MIT © [Renato Gaspar](https://github.com/rntgspr)

---

**Questions?** Open an issue on [GitHub](https://github.com/rntgspr/gringow/issues)