# AUDIT PROTOCOL: FRONTEND LANGUAGES (i18n)

**Target:** All Frontend Projects (SolidJS, React, Next.js, Vue, etc.)
**Purpose:** Ensure 100% internationalization coverage - NO hardcoded user-facing text
**Executor:** AI Agent / LLM
**Frequency:** Run periodically or before major releases

---

## 1. PRIME DIRECTIVE

**Every piece of text visible to users MUST come from the translation system.**

This includes:
- Visible text in JSX/TSX
- Error messages
- Validation messages
- Toast notifications
- Alert messages
- Placeholder text
- Button labels
- Form labels
- Status messages
- Conditional text (ternary operators)
- Text inside variables/constants
- Dynamic text with interpolation

---

## 2. TRANSLATION SYSTEM REQUIREMENTS

### 2.1 Translation Files Structure
```
src/locales/
├── en.json    # English (default)
├── es.json    # Spanish
└── [other].json
```

### 2.2 Translation Hook Usage
```typescript
// Every component with user-facing text MUST import and use:
import { useLanguage } from '../contexts/LanguageContext';

function MyComponent() {
  const { t } = useLanguage();
  
  // ✅ CORRECT
  return <h1>{t('myComponent.title')}</h1>;
  
  // ❌ WRONG
  return <h1>My Title</h1>;
}
```

### 2.3 Key Naming Convention
```
category.subcategory.item

Examples:
- error.userNotFound
- validation.emailRequired
- button.submit
- menu.dashboard
- status.loading
```

---

## 3. COMPREHENSIVE SEARCH PATTERNS

Execute ALL of these grep patterns to find hardcoded text:

### 3.1 Direct Text in JSX (Most Common)
```bash
# Text between JSX tags
grep -rn ">[A-Z][a-zA-Z ]" --include="*.tsx" src/ | grep -v "t('" | grep -v "{t("

# Spanish text (ñ, accents)
grep -rn ">[A-Za-záéíóúñÁÉÍÓÚÑ ]" --include="*.tsx" src/
```

### 3.2 String Literals in Code
```bash
# Single-quoted strings with capital letters (potential UI text)
grep -rn "'[A-Z][a-zA-Z ]*'" --include="*.tsx" src/ | grep -v "t('" | grep -v "import" | grep -v "class=" | grep -v "type="

# Double-quoted strings
grep -rn '"[A-Z][a-zA-Z ]*"' --include="*.tsx" src/ | grep -v 't("' | grep -v "import"
```

### 3.3 Error Messages (CRITICAL - Often Missed)
```bash
# throw new Error with hardcoded text
grep -rn "throw new Error('[A-Z]" --include="*.tsx" src/
grep -rn 'throw new Error("[A-Z]' --include="*.tsx" src/

# setError with hardcoded text
grep -rn "setError('[A-Z]" --include="*.tsx" src/
grep -rn 'setError("[A-Z]' --include="*.tsx" src/

# Error messages in catch blocks
grep -rn "catch.*Error\|error\|err" --include="*.tsx" src/ -A 3
```

### 3.4 Conditional Text (CRITICAL - Often Missed)
```bash
# Ternary operators with strings
grep -rn "? '[A-Z]" --include="*.tsx" src/
grep -rn ': "[A-Z]' --include="*.tsx" src/

# Fallback text with ||
grep -rn "|| '[A-Z]" --include="*.tsx" src/
grep -rn '|| "[A-Z]' --include="*.tsx" src/
```

### 3.5 Variables and Constants (CRITICAL - Often Missed)
```bash
# const/let with string assignments
grep -rn "const [a-zA-Z]* = '[A-Z]" --include="*.tsx" src/
grep -rn 'const [a-zA-Z]* = "[A-Z]' --include="*.tsx" src/

# Object properties with string values
grep -rn "label: '[A-Z]" --include="*.tsx" src/
grep -rn "message: '[A-Z]" --include="*.tsx" src/
grep -rn "title: '[A-Z]" --include="*.tsx" src/
grep -rn "description: '[A-Z]" --include="*.tsx" src/
grep -rn "placeholder: '[A-Z]" --include="*.tsx" src/
```

### 3.6 Alert/Toast/Notification Messages
```bash
grep -rn "alert('[A-Z]" --include="*.tsx" src/
grep -rn "toast('[A-Z]" --include="*.tsx" src/
grep -rn "notify('[A-Z]" --include="*.tsx" src/
```

### 3.7 Form Validation Messages
```bash
grep -rn "required.*message" --include="*.tsx" src/
grep -rn "validation" --include="*.tsx" src/ | grep -v "import"
```

### 3.8 Status/State Text
```bash
grep -rn "status.*=" --include="*.tsx" src/ | grep "'[A-Z]"
grep -rn "state.*=" --include="*.tsx" src/ | grep "'[A-Z]"
```

---

## 4. EXCLUSION LIST (False Positives)

These patterns are NOT violations:

### 4.1 Technical Strings (Not User-Facing)
- HTTP methods: `'GET'`, `'POST'`, `'PATCH'`, `'DELETE'`
- Content types: `'Content-Type'`, `'Authorization'`
- Storage keys: `localStorage.getItem('token')`
- CSS values: `'center'`, `'flex'`, `'block'`, `'none'`
- Event names: `'click'`, `'change'`, `'submit'`
- Route paths: `'/dashboard'`, `'/login'`
- Environment variables: `import.meta.env.VITE_*`
- Console logs: `console.log()`, `console.error()`
- Type definitions: `type Status = 'active' | 'closed'`

### 4.2 Brand Names (Keep as-is)
- Product names: `'PayPal'`, `'Binance'`, `'Telegram'`
- Company names: `'Cryptonite'`
- Technical terms: `'WebSocket'`, `'API'`

### 4.3 SVG/Accessibility Attributes
- `alt="Logo"` - Should be translated
- `aria-label="Close"` - Should be translated
- `title="Menu"` - Should be translated
- SVG `<title>` elements - Should be translated

### 4.4 Debug/Internal Pages
- Files named `*Status.tsx`, `*Debug.tsx`, `*Test.tsx`
- Admin-only pages (if internal use only)

---

## 5. COMMON VIOLATION PATTERNS

### 5.1 Hardcoded Error Messages
```typescript
// ❌ WRONG
setError('User not found');
throw new Error('Failed to load data');

// ✅ CORRECT
setError(t('error.userNotFound'));
throw new Error(t('error.failedToLoadData'));
```

### 5.2 Conditional Text
```typescript
// ❌ WRONG
{isConnected ? 'Connected' : 'Disconnected'}
{status === 'active' ? 'Active' : 'Inactive'}

// ✅ CORRECT
{isConnected ? t('status.connected') : t('status.disconnected')}
{status === 'active' ? t('status.active') : t('status.inactive')}
```

### 5.3 Variables with UI Text
```typescript
// ❌ WRONG
const errorMessage = 'Something went wrong';
const buttonLabel = 'Submit';
const menuItems = [{ label: 'Dashboard' }, { label: 'Settings' }];

// ✅ CORRECT
const errorMessage = t('error.somethingWentWrong');
const buttonLabel = t('button.submit');
const menuItems = [{ label: t('menu.dashboard') }, { label: t('menu.settings') }];
```

### 5.4 Fallback Text with ||
```typescript
// ❌ WRONG (fallback is hardcoded)
{t('welcome') || 'Welcome'}

// ✅ CORRECT (ensure key exists, no fallback needed)
{t('welcome')}
```

### 5.5 Template Literals with Text
```typescript
// ❌ WRONG
`Order ${orderId} has been placed`

// ✅ CORRECT
t('order.placed').replace('{orderId}', orderId)
// Or use translation with variables:
t('order.placed', { orderId })
```

### 5.6 Activity/Event Descriptions
```typescript
// ❌ WRONG
description: 'Account created'
description: order.action === 'close' ? 'Position closed' : 'Order filled'

// ✅ CORRECT
description: t('activity.accountCreated')
description: order.action === 'close' ? t('activity.positionClosed') : t('activity.orderFilled')
```

---

## 6. TRANSLATION FILE VALIDATION

### 6.1 Check for Duplicate Keys
```bash
# Find duplicate keys in JSON (will cause warnings)
grep -o '"[^"]*":' src/locales/en.json | sort | uniq -d
grep -o '"[^"]*":' src/locales/es.json | sort | uniq -d
```

### 6.2 Check Key Parity Between Languages
```bash
# Extract keys from both files and compare
diff <(grep -o '"[^"]*":' src/locales/en.json | sort) \
     <(grep -o '"[^"]*":' src/locales/es.json | sort)
```

### 6.3 Validate JSON Syntax
```bash
# Check JSON is valid
cat src/locales/en.json | python3 -m json.tool > /dev/null
cat src/locales/es.json | python3 -m json.tool > /dev/null
```

---

## 7. AUDIT EXECUTION CHECKLIST

### Phase 1: Automated Scan
- [ ] Run all grep patterns from Section 3
- [ ] Filter out false positives from Section 4
- [ ] Generate list of potential violations

### Phase 2: Manual Review
- [ ] Review each potential violation
- [ ] Categorize: UI Text vs Technical String
- [ ] Identify missing translation keys

### Phase 3: Fix Implementation
- [ ] Add missing keys to `en.json`
- [ ] Add missing keys to `es.json` (and other languages)
- [ ] Update components to use `t()` function
- [ ] Ensure `useLanguage` is imported where needed

### Phase 4: Validation
- [ ] Run duplicate key check
- [ ] Run key parity check
- [ ] Validate JSON syntax
- [ ] Test UI in both languages

---

## 8. SCORING

| Category | Weight | Criteria |
|----------|--------|----------|
| Error Messages | 25% | All error/validation messages use t() |
| UI Labels | 25% | All buttons, labels, headings use t() |
| Conditional Text | 20% | All ternary/conditional text uses t() |
| Variables | 15% | All text in variables uses t() |
| Translation Files | 15% | No duplicates, all keys present in all languages |

**Score Calculation:**
- 100%: Perfect - No violations
- 90-99%: Excellent - Minor issues only
- 80-89%: Good - Some violations, mostly cosmetic
- 70-79%: Needs Work - Significant violations
- <70%: FAILED - Critical violations, hardcoded text in production

---

## 9. QUICK REFERENCE COMMANDS

```bash
# MASTER COMMAND: Find ALL potential hardcoded text
grep -rn "'[A-Z][a-zA-Z ]*'" --include="*.tsx" src/ | \
  grep -v "t('" | grep -v "{t(" | grep -v "import" | \
  grep -v "class=" | grep -v "style=" | grep -v "type=" | \
  grep -v "console" | grep -v "method:" | grep -v "Authorization" | \
  grep -v "Content-Type" | grep -v "localStorage" | grep -v "sessionStorage"

# Count potential violations
grep -rn "'[A-Z][a-zA-Z ]*'" --include="*.tsx" src/ | \
  grep -v "t('" | grep -v "{t(" | grep -v "import" | \
  grep -v "class=" | grep -v "type=" | wc -l

# Find files without useLanguage import (that might need it)
for f in $(find src/components src/routes -name "*.tsx"); do
  if grep -q "'[A-Z][a-zA-Z ]*'" "$f" && ! grep -q "useLanguage" "$f"; then
    echo "$f"
  fi
done
```

---

## 10. MAINTENANCE

- **Run this audit:** Before every major release
- **Update patterns:** When new UI patterns are introduced
- **Add languages:** Ensure all new keys are added to ALL language files
- **Review fallbacks:** Remove `|| 'fallback'` patterns once keys are confirmed

---

*Last Updated: 2026-02-03*
*Based on lessons learned from broker i18n audit*
