@fluenti/cli 0.3.3 → 0.3.4

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.
Files changed (51) hide show
  1. package/dist/cli.cjs +9 -9
  2. package/dist/cli.cjs.map +1 -1
  3. package/dist/cli.js +290 -251
  4. package/dist/cli.js.map +1 -1
  5. package/dist/compile-CX1b_JVQ.cjs +8 -0
  6. package/dist/compile-CX1b_JVQ.cjs.map +1 -0
  7. package/dist/{compile-B4y2UPsX.js → compile-CXReVuTG.js} +35 -32
  8. package/dist/compile-CXReVuTG.js.map +1 -0
  9. package/dist/compile-cache.d.ts.map +1 -1
  10. package/dist/compile-worker.cjs +1 -1
  11. package/dist/compile-worker.cjs.map +1 -1
  12. package/dist/compile-worker.d.ts +1 -0
  13. package/dist/compile-worker.d.ts.map +1 -1
  14. package/dist/compile-worker.js +19 -7
  15. package/dist/compile-worker.js.map +1 -1
  16. package/dist/compile.d.ts.map +1 -1
  17. package/dist/{extract-cache-DYoHe5P-.js → extract-cache-BTxWgic2.js} +57 -44
  18. package/dist/extract-cache-BTxWgic2.js.map +1 -0
  19. package/dist/{extract-cache-idNfsd7n.cjs → extract-cache-CGSKwh76.cjs} +5 -5
  20. package/dist/extract-cache-CGSKwh76.cjs.map +1 -0
  21. package/dist/extract-cache.d.ts.map +1 -1
  22. package/dist/extract-runner.d.ts.map +1 -1
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.js +10 -4
  26. package/dist/index.js.map +1 -1
  27. package/dist/lint.d.ts.map +1 -1
  28. package/dist/parallel-compile.d.ts.map +1 -1
  29. package/dist/po-format.d.ts.map +1 -1
  30. package/dist/translate.d.ts +2 -1
  31. package/dist/translate.d.ts.map +1 -1
  32. package/dist/{tsx-extractor-C-9_TnCW.cjs → tsx-extractor-BOD7JJQK.cjs} +2 -2
  33. package/dist/tsx-extractor-BOD7JJQK.cjs.map +1 -0
  34. package/dist/{tsx-extractor-CjQIMvKo.js → tsx-extractor-C-HZNobu.js} +2 -2
  35. package/dist/tsx-extractor-C-HZNobu.js.map +1 -0
  36. package/dist/tsx-extractor.d.ts.map +1 -1
  37. package/dist/validation.d.ts +4 -1
  38. package/dist/validation.d.ts.map +1 -1
  39. package/dist/vue-extractor.cjs +2 -2
  40. package/dist/vue-extractor.cjs.map +1 -1
  41. package/dist/vue-extractor.d.ts.map +1 -1
  42. package/dist/vue-extractor.js +3 -3
  43. package/dist/vue-extractor.js.map +1 -1
  44. package/package.json +2 -2
  45. package/dist/compile-B4y2UPsX.js.map +0 -1
  46. package/dist/compile-Brygn0bn.cjs +0 -8
  47. package/dist/compile-Brygn0bn.cjs.map +0 -1
  48. package/dist/extract-cache-DYoHe5P-.js.map +0 -1
  49. package/dist/extract-cache-idNfsd7n.cjs.map +0 -1
  50. package/dist/tsx-extractor-C-9_TnCW.cjs.map +0 -1
  51. package/dist/tsx-extractor-CjQIMvKo.js.map +0 -1
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/stats-format.ts","../src/lint.ts","../src/check.ts","../src/compile-cache.ts","../src/translate.ts","../src/migrate.ts","../src/init.ts","../src/cli.ts"],"sourcesContent":["const BLOCK_FULL = '█'\nconst BLOCK_EMPTY = '░'\n\n/**\n * Render a Unicode progress bar.\n *\n * @param pct - Percentage (0–100)\n * @param width - Character width of the bar (default 20)\n */\nexport function formatProgressBar(pct: number, width = 20): string {\n const clamped = Math.max(0, Math.min(100, pct))\n const filled = Math.round((clamped / 100) * width)\n return BLOCK_FULL.repeat(filled) + BLOCK_EMPTY.repeat(width - filled)\n}\n\n/**\n * Wrap a percentage string in ANSI colour based on value.\n *\n * - ≥90 → green (\\x1b[32m)\n * - ≥70 → yellow (\\x1b[33m)\n * - <70 → red (\\x1b[31m)\n */\nexport function colorizePercent(pct: number): string {\n const label = pct.toFixed(1) + '%'\n if (pct >= 90) return `\\x1b[32m${label}\\x1b[0m`\n if (pct >= 70) return `\\x1b[33m${label}\\x1b[0m`\n return `\\x1b[31m${label}\\x1b[0m`\n}\n\n/**\n * Format a full stats row for a single locale.\n */\nexport function formatStatsRow(\n locale: string,\n total: number,\n translated: number,\n): string {\n const pct = total > 0 ? (translated / total) * 100 : 0\n const pctDisplay = total > 0 ? colorizePercent(pct) : '—'\n const bar = total > 0 ? formatProgressBar(pct) : ''\n return ` ${locale.padEnd(8)}│ ${String(total).padStart(5)} │ ${String(translated).padStart(10)} │ ${bar} ${pctDisplay}`\n}\n","import type { CatalogData } from './catalog'\n\n/** Severity levels for lint diagnostics */\nexport type LintSeverity = 'error' | 'warning' | 'info'\n\n/** A single lint diagnostic */\nexport interface LintDiagnostic {\n /** Lint rule that produced this diagnostic */\n rule: string\n /** Severity level */\n severity: LintSeverity\n /** Human-readable message */\n message: string\n /** Affected message ID */\n messageId?: string\n /** Affected locale */\n locale?: string\n}\n\n/** Options for configuring lint behavior */\nexport interface LintOptions {\n /** Locales to lint (default: all) */\n locales?: string[]\n /** Source locale for comparison */\n sourceLocale: string\n /** Whether to fail on warnings (default: false) */\n strict?: boolean\n}\n\n/**\n * Run all lint rules against the provided catalogs.\n *\n * Returns an array of diagnostics. Empty array = all checks passed.\n */\nexport function lintCatalogs(\n catalogs: Record<string, CatalogData>,\n options: LintOptions,\n): LintDiagnostic[] {\n const diagnostics: LintDiagnostic[] = []\n const { sourceLocale } = options\n const locales = options.locales ?? Object.keys(catalogs)\n const sourceCatalog = catalogs[sourceLocale]\n\n if (!sourceCatalog) {\n diagnostics.push({\n rule: 'missing-source',\n severity: 'error',\n message: `Source locale catalog \"${sourceLocale}\" not found`,\n })\n return diagnostics\n }\n\n // Collect non-obsolete source IDs\n const sourceIds = Object.entries(sourceCatalog)\n .filter(([, entry]) => !entry.obsolete)\n .map(([id]) => id)\n\n for (const locale of locales) {\n if (locale === sourceLocale) continue\n const catalog = catalogs[locale]\n if (!catalog) {\n diagnostics.push({\n rule: 'missing-locale',\n severity: 'error',\n message: `Catalog for locale \"${locale}\" not found`,\n locale,\n })\n continue\n }\n\n for (const id of sourceIds) {\n const sourceEntry = sourceCatalog[id]!\n const targetEntry = catalog[id]\n\n // Rule: missing-translation\n if (!targetEntry || !targetEntry.translation || targetEntry.translation.length === 0) {\n diagnostics.push({\n rule: 'missing-translation',\n severity: 'error',\n message: `Missing translation for \"${id}\" in locale \"${locale}\"`,\n messageId: id,\n locale,\n })\n continue\n }\n\n // Rule: inconsistent-placeholders\n const sourceMessage = sourceEntry.message ?? id\n const sourcePlaceholders = extractPlaceholders(sourceMessage)\n const targetPlaceholders = extractPlaceholders(targetEntry.translation)\n\n const missingInTarget = sourcePlaceholders.filter((p) => !targetPlaceholders.includes(p))\n const extraInTarget = targetPlaceholders.filter((p) => !sourcePlaceholders.includes(p))\n\n if (missingInTarget.length > 0) {\n diagnostics.push({\n rule: 'inconsistent-placeholders',\n severity: 'error',\n message: `Translation for \"${id}\" in \"${locale}\" is missing placeholders: ${missingInTarget.map((p) => `{${p}}`).join(', ')}`,\n messageId: id,\n locale,\n })\n }\n\n if (extraInTarget.length > 0) {\n diagnostics.push({\n rule: 'inconsistent-placeholders',\n severity: 'warning',\n message: `Translation for \"${id}\" in \"${locale}\" has extra placeholders: ${extraInTarget.map((p) => `{${p}}`).join(', ')}`,\n messageId: id,\n locale,\n })\n }\n\n // Rule: fuzzy-translation\n if (targetEntry.fuzzy) {\n diagnostics.push({\n rule: 'fuzzy-translation',\n severity: 'warning',\n message: `Translation for \"${id}\" in \"${locale}\" is marked as fuzzy`,\n messageId: id,\n locale,\n })\n }\n }\n\n // Rule: orphan-translation (target has entries not in source)\n for (const [id, entry] of Object.entries(catalog)) {\n if (entry.obsolete) continue\n if (!sourceCatalog[id] || sourceCatalog[id]!.obsolete) {\n diagnostics.push({\n rule: 'orphan-translation',\n severity: 'warning',\n message: `Translation \"${id}\" in \"${locale}\" has no corresponding source message`,\n messageId: id,\n locale,\n })\n }\n }\n }\n\n // Rule: duplicate-messages (same translation text for different IDs in source)\n const messageToIds = new Map<string, string[]>()\n for (const [id, entry] of Object.entries(sourceCatalog)) {\n if (entry.obsolete) continue\n const msg = entry.message ?? id\n const existing = messageToIds.get(msg)\n if (existing) {\n existing.push(id)\n } else {\n messageToIds.set(msg, [id])\n }\n }\n for (const [msg, ids] of messageToIds) {\n if (ids.length > 1) {\n diagnostics.push({\n rule: 'duplicate-message',\n severity: 'info',\n message: `Duplicate source message \"${msg.slice(0, 60)}${msg.length > 60 ? '...' : ''}\" used by ${ids.length} entries: ${ids.join(', ')}`,\n locale: sourceLocale,\n })\n }\n }\n\n return diagnostics\n}\n\n/** Extract ICU placeholder names from a message string */\nfunction extractPlaceholders(message: string): string[] {\n const placeholders: string[] = []\n // Match {name}, {name, type}, {name, plural, ...}, etc.\n // but not the option keywords inside plural/select\n const regex = /\\{(\\w+)(?:\\s*,\\s*(?:plural|select|selectordinal|number|date|time))?/g\n let match\n while ((match = regex.exec(message)) !== null) {\n const name = match[1]!\n if (!placeholders.includes(name)) {\n placeholders.push(name)\n }\n }\n return placeholders.sort()\n}\n\n/**\n * Format lint diagnostics for console output.\n */\nexport function formatDiagnostics(diagnostics: LintDiagnostic[]): string {\n if (diagnostics.length === 0) return ' ✓ All checks passed'\n\n const lines: string[] = []\n const grouped = groupBy(diagnostics, (d) => d.rule)\n\n for (const [rule, items] of Object.entries(grouped)) {\n lines.push(` ${rule} (${items.length}):`)\n for (const d of items) {\n const icon = d.severity === 'error' ? '✗' : d.severity === 'warning' ? '⚠' : 'ℹ'\n lines.push(` ${icon} ${d.message}`)\n }\n }\n\n const errors = diagnostics.filter((d) => d.severity === 'error').length\n const warnings = diagnostics.filter((d) => d.severity === 'warning').length\n const infos = diagnostics.filter((d) => d.severity === 'info').length\n\n lines.push('')\n lines.push(` Summary: ${errors} errors, ${warnings} warnings, ${infos} info`)\n\n return lines.join('\\n')\n}\n\nfunction groupBy<T>(items: T[], key: (item: T) => string): Record<string, T[]> {\n const result: Record<string, T[]> = {}\n for (const item of items) {\n const k = key(item)\n ;(result[k] ?? (result[k] = [])).push(item)\n }\n return result\n}\n","import type { CatalogData } from './catalog'\nimport { lintCatalogs } from './lint'\nimport type { LintDiagnostic } from './lint'\n\n/** Per-locale coverage result */\nexport interface CheckResult {\n locale: string\n total: number\n translated: number\n missing: number\n fuzzy: number\n coverage: number // 0-100\n}\n\n/** Options for the check command */\nexport interface CheckOptions {\n /** Source locale for comparison */\n sourceLocale: string\n /** Minimum coverage percentage (0-100) */\n minCoverage: number\n /** Check only a specific locale */\n locale?: string\n /** Output format */\n format: 'text' | 'json' | 'github'\n}\n\n/** Full check result */\nexport interface CheckOutput {\n results: CheckResult[]\n passed: boolean\n minCoverage: number\n actualCoverage: number\n diagnostics: LintDiagnostic[]\n}\n\n/**\n * Check translation coverage across all locale catalogs.\n */\nexport function checkCoverage(\n catalogs: Record<string, CatalogData>,\n options: CheckOptions,\n): CheckOutput {\n const { sourceLocale, minCoverage, locale: targetLocale } = options\n const sourceCatalog = catalogs[sourceLocale]\n\n if (!sourceCatalog) {\n return {\n results: [],\n passed: false,\n minCoverage,\n actualCoverage: 0,\n diagnostics: [{\n rule: 'missing-source',\n severity: 'error',\n message: `Source locale catalog \"${sourceLocale}\" not found`,\n }],\n }\n }\n\n // Count non-obsolete source entries\n const sourceIds = Object.entries(sourceCatalog)\n .filter(([, entry]) => !entry.obsolete)\n .map(([id]) => id)\n\n const total = sourceIds.length\n\n // Determine which locales to check\n const localesToCheck = targetLocale\n ? [targetLocale]\n : Object.keys(catalogs).filter((l) => l !== sourceLocale)\n\n const results: CheckResult[] = []\n\n for (const locale of localesToCheck) {\n const catalog = catalogs[locale]\n if (!catalog) {\n results.push({\n locale,\n total,\n translated: 0,\n missing: total,\n fuzzy: 0,\n coverage: 0,\n })\n continue\n }\n\n let translated = 0\n let missing = 0\n let fuzzy = 0\n\n for (const id of sourceIds) {\n const entry = catalog[id]\n if (!entry || !entry.translation || entry.translation.length === 0) {\n missing++\n } else {\n translated++\n if (entry.fuzzy) {\n fuzzy++\n }\n }\n }\n\n const coverage = total > 0 ? (translated / total) * 100 : 100\n results.push({ locale, total, translated, missing, fuzzy, coverage })\n }\n\n // Calculate overall coverage\n const totalTranslated = results.reduce((sum, r) => sum + r.translated, 0)\n const totalEntries = results.reduce((sum, r) => sum + r.total, 0)\n const actualCoverage = totalEntries > 0\n ? (totalTranslated / totalEntries) * 100\n : 100\n\n const passed = results.every((r) => r.coverage >= minCoverage)\n\n // Run lint diagnostics for missing translations\n const lintOpts: Parameters<typeof lintCatalogs>[1] = { sourceLocale }\n if (targetLocale) {\n lintOpts.locales = [sourceLocale, targetLocale]\n }\n\n const diagnostics = lintCatalogs(catalogs, lintOpts)\n\n return { results, passed, minCoverage, actualCoverage, diagnostics }\n}\n\n/**\n * Format check output as plain text.\n */\nexport function formatCheckText(output: CheckOutput): string {\n const lines: string[] = []\n\n for (const r of output.results) {\n const icon = r.coverage >= output.minCoverage ? '✓' : '✗'\n const pct = r.coverage.toFixed(1)\n const details = r.missing > 0 ? ` — ${r.missing} missing` : ''\n const fuzzyNote = r.fuzzy > 0 ? `, ${r.fuzzy} fuzzy` : ''\n lines.push(`${icon} ${r.locale}: ${pct}% (${r.translated}/${r.total})${details}${fuzzyNote}`)\n }\n\n lines.push('')\n const overallPct = output.actualCoverage.toFixed(1)\n const status = output.passed ? 'PASSED' : 'FAILED'\n lines.push(`Coverage: ${overallPct}% (min: ${output.minCoverage}%) — ${status}`)\n\n return lines.join('\\n')\n}\n\n/**\n * Format check output as GitHub Actions annotations.\n */\nexport function formatCheckGitHub(\n output: CheckOutput,\n catalogDir: string,\n format: 'json' | 'po',\n): string {\n const lines: string[] = []\n const ext = format === 'json' ? '.json' : '.po'\n\n for (const r of output.results) {\n if (r.coverage < output.minCoverage) {\n const file = `${catalogDir}/${r.locale}${ext}`\n lines.push(\n `::error file=${file}::Translation coverage ${r.coverage.toFixed(1)}% below minimum ${output.minCoverage}%`,\n )\n }\n }\n\n // Add individual missing translation warnings\n const missingDiags = output.diagnostics.filter((d) => d.rule === 'missing-translation')\n for (const d of missingDiags) {\n if (d.locale) {\n const file = `${catalogDir}/${d.locale}${ext}`\n lines.push(`::warning file=${file}::${d.message}`)\n }\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Format check output as JSON.\n */\nexport function formatCheckJson(output: CheckOutput): string {\n return JSON.stringify({\n results: output.results,\n passed: output.passed,\n minCoverage: output.minCoverage,\n actualCoverage: Math.round(output.actualCoverage * 10) / 10,\n }, null, 2)\n}\n","import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { createHash } from 'node:crypto'\nimport { dirname, resolve } from 'node:path'\n\n/** Cache format version — bump when the structure changes */\nconst CACHE_VERSION = '1'\n\ninterface CompileCacheEntry {\n inputHash: string\n}\n\ninterface CompileCacheData {\n version: string\n entries: Record<string, CompileCacheEntry> // keyed by locale\n}\n\n/**\n * Compile cache that skips re-compilation when PO/JSON files haven't changed.\n *\n * Uses MD5 of input file content as change detection (non-cryptographic, fast).\n */\nexport class CompileCache {\n private data: CompileCacheData\n private cachePath: string\n private dirty = false\n\n constructor(catalogDir: string, projectId?: string) {\n const cacheDir = projectId\n ? resolve(catalogDir, '.cache', projectId)\n : resolve(catalogDir, '.cache')\n this.cachePath = resolve(cacheDir, 'compile-cache.json')\n this.data = this.load()\n }\n\n /**\n * Check if a locale's catalog has changed since last compile.\n * Returns true if unchanged (cache hit), false if re-compilation needed.\n */\n isUpToDate(locale: string, catalogContent: string): boolean {\n const entry = this.data.entries[locale]\n if (!entry) return false\n\n const currentHash = hashContent(catalogContent)\n return entry.inputHash === currentHash\n }\n\n /**\n * Update the cache after a successful compilation.\n */\n set(locale: string, catalogContent: string): void {\n this.data.entries[locale] = {\n inputHash: hashContent(catalogContent),\n }\n this.dirty = true\n }\n\n /**\n * Write the cache to disk if any changes were made.\n */\n save(): void {\n if (!this.dirty) return\n\n mkdirSync(dirname(this.cachePath), { recursive: true })\n writeFileSync(this.cachePath, JSON.stringify(this.data), 'utf-8')\n this.dirty = false\n }\n\n private load(): CompileCacheData {\n try {\n if (existsSync(this.cachePath)) {\n const raw = readFileSync(this.cachePath, 'utf-8')\n const parsed = JSON.parse(raw) as CompileCacheData\n if (parsed.version === CACHE_VERSION) {\n return parsed\n }\n }\n } catch {\n // Corrupt or unreadable cache — start fresh\n }\n\n return { version: CACHE_VERSION, entries: {} }\n }\n}\n\nfunction hashContent(content: string): string {\n return createHash('md5').update(content).digest('hex')\n}\n","import { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport consola from 'consola'\nimport type { CatalogData } from './catalog'\n\nconst execFileAsync = promisify(execFile)\n\nexport type AIProvider = 'claude' | 'codex'\n\nexport function buildPrompt(\n sourceLocale: string,\n targetLocale: string,\n messages: Record<string, string>,\n context?: string,\n): string {\n const json = JSON.stringify(messages, null, 2)\n return [\n `You are a professional translator. Translate the following messages from \"${sourceLocale}\" to \"${targetLocale}\".`,\n '',\n ...(context ? [`Project context: ${context}`, ''] : []),\n `Input (JSON):`,\n json,\n '',\n 'Rules:',\n '- Output ONLY valid JSON with the same keys and translated values.',\n '- Keep ICU MessageFormat placeholders like {name}, {count}, {gender} unchanged.',\n '- Keep HTML tags unchanged.',\n '- Do not add any explanation or markdown formatting, output raw JSON only.',\n ].join('\\n')\n}\n\nasync function invokeAI(provider: AIProvider, prompt: string): Promise<string> {\n const maxBuffer = 10 * 1024 * 1024\n\n try {\n if (provider === 'claude') {\n const { stdout } = await execFileAsync('claude', ['-p', prompt], { maxBuffer })\n return stdout\n } else {\n const { stdout } = await execFileAsync('codex', ['-p', prompt, '--full-auto'], { maxBuffer })\n return stdout\n }\n } catch (error: unknown) {\n const err = error as Error & { code?: string }\n if (err.code === 'ENOENT') {\n throw new Error(\n `\"${provider}\" CLI not found. Please install it first:\\n` +\n (provider === 'claude'\n ? ' npm install -g @anthropic-ai/claude-code'\n : ' npm install -g @openai/codex'),\n )\n }\n throw error\n }\n}\n\nexport function extractJSON(text: string): Record<string, string> {\n // Try to find a JSON object in the response\n const match = text.match(/\\{[\\s\\S]*\\}/)\n if (!match) {\n throw new Error('No JSON object found in AI response')\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(match[0])\n } catch {\n throw new Error(`Failed to parse JSON from AI response: ${match[0].slice(0, 200)}`)\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error('AI response is not a valid JSON object')\n }\n return parsed as Record<string, string>\n}\n\nexport function getUntranslatedEntries(catalog: CatalogData): Record<string, string> {\n const entries: Record<string, string> = {}\n for (const [id, entry] of Object.entries(catalog)) {\n if (entry.obsolete) continue\n if (!entry.translation || entry.translation.length === 0) {\n entries[id] = entry.message ?? id\n }\n }\n return entries\n}\n\nexport function chunkEntries(\n entries: Record<string, string>,\n batchSize: number,\n): Array<Record<string, string>> {\n const keys = Object.keys(entries)\n const chunks: Array<Record<string, string>> = []\n\n for (let i = 0; i < keys.length; i += batchSize) {\n const chunk: Record<string, string> = {}\n for (const key of keys.slice(i, i + batchSize)) {\n chunk[key] = entries[key]!\n }\n chunks.push(chunk)\n }\n\n return chunks\n}\n\nexport interface TranslateOptions {\n provider: AIProvider\n sourceLocale: string\n targetLocale: string\n catalog: CatalogData\n batchSize: number\n context?: string\n}\n\nexport async function translateCatalog(options: TranslateOptions): Promise<{\n catalog: CatalogData\n translated: number\n}> {\n const { provider, sourceLocale, targetLocale, catalog, batchSize, context } = options\n\n const untranslated = getUntranslatedEntries(catalog)\n const count = Object.keys(untranslated).length\n\n if (count === 0) {\n return { catalog: { ...catalog }, translated: 0 }\n }\n\n consola.info(` ${count} untranslated messages, translating with ${provider}...`)\n\n const result = { ...catalog }\n const batches = chunkEntries(untranslated, batchSize)\n let totalTranslated = 0\n\n for (let i = 0; i < batches.length; i++) {\n const batch = batches[i]!\n const batchKeys = Object.keys(batch)\n\n if (batches.length > 1) {\n consola.info(` Batch ${i + 1}/${batches.length} (${batchKeys.length} messages)`)\n }\n\n const prompt = buildPrompt(sourceLocale, targetLocale, batch, context)\n const response = await invokeAI(provider, prompt)\n const translations = extractJSON(response)\n\n for (const key of batchKeys) {\n if (translations[key] && typeof translations[key] === 'string') {\n result[key] = {\n ...result[key],\n translation: translations[key],\n }\n totalTranslated++\n } else {\n consola.warn(` Missing translation for key: ${key}`)\n }\n }\n }\n\n return { catalog: result, translated: totalTranslated }\n}\n","import { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport { readFileSync, existsSync } from 'node:fs'\nimport { resolve, join, dirname } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport fg from 'fast-glob'\nimport consola from 'consola'\nimport type { AIProvider } from './translate'\n\nconst execFileAsync = promisify(execFile)\n\nexport type SupportedLibrary =\n | 'vue-i18n'\n | 'nuxt-i18n'\n | 'react-i18next'\n | 'next-intl'\n | 'next-i18next'\n | 'lingui'\n\ninterface LibraryInfo {\n name: SupportedLibrary\n framework: string\n configPatterns: string[]\n localePatterns: string[]\n sourcePatterns: string[]\n migrationGuide: string // relative path from packages/\n}\n\nconst LIBRARY_INFO: Record<SupportedLibrary, LibraryInfo> = {\n 'vue-i18n': {\n name: 'vue-i18n',\n framework: 'Vue',\n configPatterns: ['i18n.ts', 'i18n.js', 'i18n/index.ts', 'i18n/index.js', 'src/i18n.ts', 'src/i18n.js', 'src/i18n/index.ts', 'src/plugins/i18n.ts'],\n localePatterns: ['locales/*.json', 'src/locales/*.json', 'i18n/*.json', 'src/i18n/*.json', 'lang/*.json', 'src/lang/*.json', 'locales/*.yaml', 'locales/*.yml'],\n sourcePatterns: ['src/**/*.vue'],\n migrationGuide: 'vue/llms-migration.txt',\n },\n 'nuxt-i18n': {\n name: 'nuxt-i18n',\n framework: 'Nuxt',\n configPatterns: ['nuxt.config.ts', 'nuxt.config.js', 'i18n.config.ts', 'i18n.config.js'],\n localePatterns: ['locales/*.json', 'lang/*.json', 'i18n/*.json', 'locales/*.yaml', 'locales/*.yml'],\n sourcePatterns: ['pages/**/*.vue', 'components/**/*.vue', 'layouts/**/*.vue'],\n migrationGuide: 'nuxt/llms-migration.txt',\n },\n 'react-i18next': {\n name: 'react-i18next',\n framework: 'React',\n configPatterns: ['i18n.ts', 'i18n.js', 'src/i18n.ts', 'src/i18n.js', 'src/i18n/index.ts', 'src/i18n/config.ts'],\n localePatterns: ['locales/*.json', 'src/locales/*.json', 'public/locales/**/*.json', 'translations/*.json', 'src/translations/*.json'],\n sourcePatterns: ['src/**/*.tsx', 'src/**/*.jsx', 'src/**/*.ts'],\n migrationGuide: 'react/llms-migration.txt',\n },\n 'next-intl': {\n name: 'next-intl',\n framework: 'Next.js',\n configPatterns: ['next.config.ts', 'next.config.js', 'next.config.mjs', 'i18n.ts', 'src/i18n.ts', 'i18n/request.ts', 'src/i18n/request.ts'],\n localePatterns: ['messages/*.json', 'locales/*.json', 'src/messages/*.json', 'src/locales/*.json'],\n sourcePatterns: ['app/**/*.tsx', 'src/app/**/*.tsx', 'pages/**/*.tsx', 'components/**/*.tsx'],\n migrationGuide: 'next-plugin/llms-migration.txt',\n },\n 'next-i18next': {\n name: 'next-i18next',\n framework: 'Next.js',\n configPatterns: ['next-i18next.config.js', 'next-i18next.config.mjs', 'next.config.ts', 'next.config.js'],\n localePatterns: ['public/locales/**/*.json'],\n sourcePatterns: ['pages/**/*.tsx', 'src/pages/**/*.tsx', 'components/**/*.tsx', 'src/components/**/*.tsx'],\n migrationGuide: 'next-plugin/llms-migration.txt',\n },\n 'lingui': {\n name: 'lingui',\n framework: 'React',\n configPatterns: ['lingui.config.ts', 'lingui.config.js', '.linguirc'],\n localePatterns: ['locales/*.po', 'src/locales/*.po', 'locales/*/messages.po', 'src/locales/*/messages.po'],\n sourcePatterns: ['src/**/*.tsx', 'src/**/*.jsx', 'src/**/*.ts'],\n migrationGuide: 'react/llms-migration.txt',\n },\n}\n\nconst SUPPORTED_NAMES = Object.keys(LIBRARY_INFO) as SupportedLibrary[]\n\nexport function resolveLibrary(from: string): SupportedLibrary | undefined {\n const normalized = from.toLowerCase().replace(/^@nuxtjs\\//, 'nuxt-').replace(/^@/, '')\n return SUPPORTED_NAMES.find((name) => name === normalized)\n}\n\nexport interface DetectedFiles {\n configFiles: Array<{ path: string; content: string }>\n localeFiles: Array<{ path: string; content: string }>\n sampleSources: Array<{ path: string; content: string }>\n packageJson: string | undefined\n}\n\nasync function detectFiles(info: LibraryInfo): Promise<DetectedFiles> {\n const result: DetectedFiles = {\n configFiles: [],\n localeFiles: [],\n sampleSources: [],\n packageJson: undefined,\n }\n\n // Read package.json\n const pkgPath = resolve('package.json')\n if (existsSync(pkgPath)) {\n result.packageJson = readFileSync(pkgPath, 'utf-8')\n }\n\n // Find config files\n for (const pattern of info.configPatterns) {\n const fullPath = resolve(pattern)\n if (existsSync(fullPath)) {\n result.configFiles.push({\n path: pattern,\n content: readFileSync(fullPath, 'utf-8'),\n })\n }\n }\n\n // Find locale files (limit to 10 to avoid huge prompts)\n const localeGlobs = await fg(info.localePatterns, { absolute: false })\n for (const file of localeGlobs.slice(0, 10)) {\n const fullPath = resolve(file)\n const content = readFileSync(fullPath, 'utf-8')\n // Truncate large files\n result.localeFiles.push({\n path: file,\n content: content.length > 5000 ? content.slice(0, 5000) + '\\n... (truncated)' : content,\n })\n }\n\n // Find sample source files (limit to 5 for prompt size)\n const sourceGlobs = await fg(info.sourcePatterns, { absolute: false })\n for (const file of sourceGlobs.slice(0, 5)) {\n const fullPath = resolve(file)\n const content = readFileSync(fullPath, 'utf-8')\n result.sampleSources.push({\n path: file,\n content: content.length > 3000 ? content.slice(0, 3000) + '\\n... (truncated)' : content,\n })\n }\n\n return result\n}\n\nfunction loadMigrationGuide(guidePath: string): string {\n const thisDir = typeof __dirname !== 'undefined'\n ? __dirname\n : dirname(fileURLToPath(import.meta.url))\n // Try to find the migration guide relative to the CLI package\n const candidates = [\n resolve('node_modules', '@fluenti', 'cli', '..', '..', guidePath),\n join(thisDir, '..', '..', '..', guidePath),\n join(thisDir, '..', '..', guidePath),\n ]\n\n for (const candidate of candidates) {\n if (existsSync(candidate)) {\n return readFileSync(candidate, 'utf-8')\n }\n }\n\n return ''\n}\n\nexport function buildMigratePrompt(\n library: LibraryInfo,\n detected: DetectedFiles,\n migrationGuide: string,\n): string {\n const sections: string[] = []\n\n sections.push(\n `You are a migration assistant helping convert a ${library.framework} project from \"${library.name}\" to Fluenti (@fluenti).`,\n '',\n 'Your task:',\n '1. Generate a `fluenti.config.ts` file based on the existing i18n configuration',\n '2. Convert each locale/translation file to Fluenti PO format',\n '3. List the code changes needed (file by file) to migrate source code from the old API to Fluenti API',\n '',\n )\n\n if (migrationGuide) {\n sections.push(\n '=== MIGRATION GUIDE ===',\n migrationGuide,\n '',\n )\n }\n\n if (detected.packageJson) {\n sections.push(\n '=== package.json ===',\n detected.packageJson,\n '',\n )\n }\n\n if (detected.configFiles.length > 0) {\n sections.push('=== EXISTING CONFIG FILES ===')\n for (const file of detected.configFiles) {\n sections.push(`--- ${file.path} ---`, file.content, '')\n }\n }\n\n if (detected.localeFiles.length > 0) {\n sections.push('=== EXISTING LOCALE FILES ===')\n for (const file of detected.localeFiles) {\n sections.push(`--- ${file.path} ---`, file.content, '')\n }\n }\n\n if (detected.sampleSources.length > 0) {\n sections.push('=== SAMPLE SOURCE FILES ===')\n for (const file of detected.sampleSources) {\n sections.push(`--- ${file.path} ---`, file.content, '')\n }\n }\n\n sections.push(\n '',\n '=== OUTPUT FORMAT ===',\n 'Respond with the following sections, each starting with the exact header shown:',\n '',\n '### FLUENTI_CONFIG',\n '```ts',\n '// The fluenti.config.ts content',\n '```',\n '',\n '### LOCALE_FILES',\n 'For each locale file, output:',\n '#### LOCALE: {locale_code}',\n '```po',\n '// The PO file content',\n '```',\n '',\n '### MIGRATION_STEPS',\n 'A numbered checklist of specific code changes needed, with before/after examples.',\n '',\n '### INSTALL_COMMANDS',\n '```bash',\n '// The install and uninstall commands',\n '```',\n )\n\n return sections.join('\\n')\n}\n\nasync function invokeAI(provider: AIProvider, prompt: string): Promise<string> {\n const maxBuffer = 10 * 1024 * 1024\n\n try {\n if (provider === 'claude') {\n const { stdout } = await execFileAsync('claude', ['-p', prompt], { maxBuffer })\n return stdout\n } else {\n const { stdout } = await execFileAsync('codex', ['-p', prompt, '--full-auto'], { maxBuffer })\n return stdout\n }\n } catch (error: unknown) {\n const err = error as Error & { code?: string }\n if (err.code === 'ENOENT' || err.code === 'EPERM' || err.code === 'EACCES') {\n throw new Error(\n `\"${provider}\" CLI not found or not executable. Please install it first:\\n` +\n (provider === 'claude'\n ? ' npm install -g @anthropic-ai/claude-code'\n : ' npm install -g @openai/codex'),\n )\n }\n throw error\n }\n}\n\ninterface MigrateResult {\n config: string | undefined\n localeFiles: Array<{ locale: string; content: string }>\n steps: string | undefined\n installCommands: string | undefined\n}\n\nexport function parseResponse(response: string): MigrateResult {\n const result: MigrateResult = {\n config: undefined,\n localeFiles: [],\n steps: undefined,\n installCommands: undefined,\n }\n\n // Extract fluenti.config.ts\n const configMatch = response.match(/### FLUENTI_CONFIG[\\s\\S]*?```(?:ts|typescript)?\\n([\\s\\S]*?)```/)\n if (configMatch) {\n result.config = configMatch[1]!.trim()\n }\n\n // Extract locale files\n const localeSection = response.match(/### LOCALE_FILES([\\s\\S]*?)(?=### MIGRATION_STEPS|### INSTALL_COMMANDS|$)/)\n if (localeSection) {\n const localeRegex = /#### LOCALE:\\s*(\\S+)\\s*\\n```(?:po)?\\n([\\s\\S]*?)```/g\n let match\n while ((match = localeRegex.exec(localeSection[1]!)) !== null) {\n result.localeFiles.push({\n locale: match[1]!,\n content: match[2]!.trim(),\n })\n }\n }\n\n // Extract migration steps\n const stepsMatch = response.match(/### MIGRATION_STEPS\\s*\\n([\\s\\S]*?)(?=### INSTALL_COMMANDS|$)/)\n if (stepsMatch) {\n result.steps = stepsMatch[1]!.trim()\n }\n\n // Extract install commands\n const installMatch = response.match(/### INSTALL_COMMANDS[\\s\\S]*?```(?:bash|sh)?\\n([\\s\\S]*?)```/)\n if (installMatch) {\n result.installCommands = installMatch[1]!.trim()\n }\n\n return result\n}\n\nexport interface MigrateOptions {\n from: string\n provider: AIProvider\n write: boolean\n}\n\nexport async function runMigrate(options: MigrateOptions): Promise<void> {\n const { from, provider, write } = options\n\n const library = resolveLibrary(from)\n if (!library) {\n consola.error(`Unsupported library \"${from}\". Supported libraries:`)\n for (const name of SUPPORTED_NAMES) {\n consola.log(` - ${name}`)\n }\n return\n }\n\n const info = LIBRARY_INFO[library]\n consola.info(`Migrating from ${info.name} (${info.framework}) to Fluenti`)\n\n // Detect existing files\n consola.info('Scanning project for existing i18n files...')\n const detected = await detectFiles(info)\n\n if (detected.configFiles.length === 0 && detected.localeFiles.length === 0) {\n consola.warn(`No ${info.name} configuration or locale files found.`)\n consola.info('Make sure you are running this command from the project root directory.')\n return\n }\n\n consola.info(`Found: ${detected.configFiles.length} config file(s), ${detected.localeFiles.length} locale file(s), ${detected.sampleSources.length} source file(s)`)\n\n // Load migration guide\n const migrationGuide = loadMigrationGuide(info.migrationGuide)\n\n // Build prompt and invoke AI\n consola.info(`Generating migration plan with ${provider}...`)\n const prompt = buildMigratePrompt(info, detected, migrationGuide)\n const response = await invokeAI(provider, prompt)\n const result = parseResponse(response)\n\n // Display install commands\n if (result.installCommands) {\n consola.log('')\n consola.box({\n title: 'Install Commands',\n message: result.installCommands,\n })\n }\n\n // Write or display fluenti.config.ts\n if (result.config) {\n if (write) {\n const { writeFileSync } = await import('node:fs')\n const configPath = resolve('fluenti.config.ts')\n writeFileSync(configPath, result.config, 'utf-8')\n consola.success(`Written: ${configPath}`)\n } else {\n consola.log('')\n consola.box({\n title: 'fluenti.config.ts',\n message: result.config,\n })\n }\n }\n\n // Write or display locale files\n if (result.localeFiles.length > 0) {\n if (write) {\n const { writeFileSync, mkdirSync } = await import('node:fs')\n const catalogDir = './locales'\n mkdirSync(resolve(catalogDir), { recursive: true })\n for (const file of result.localeFiles) {\n const outPath = resolve(catalogDir, `${file.locale}.po`)\n writeFileSync(outPath, file.content, 'utf-8')\n consola.success(`Written: ${outPath}`)\n }\n } else {\n for (const file of result.localeFiles) {\n consola.log('')\n consola.box({\n title: `locales/${file.locale}.po`,\n message: file.content.length > 500\n ? file.content.slice(0, 500) + '\\n... (use --write to save full file)'\n : file.content,\n })\n }\n }\n }\n\n // Display migration steps\n if (result.steps) {\n consola.log('')\n consola.box({\n title: 'Migration Steps',\n message: result.steps,\n })\n }\n\n if (!write && (result.config || result.localeFiles.length > 0)) {\n consola.log('')\n consola.info('Run with --write to save generated files to disk:')\n consola.log(` fluenti migrate --from ${from} --write`)\n }\n}\n","import { readFileSync, writeFileSync, existsSync, appendFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport consola from 'consola'\n\nconst LOCALE_PATTERN = /^[a-zA-Z]{2,3}(-[a-zA-Z0-9]{1,8})*$/\n\nexport function validateLocale(locale: string): string {\n if (!LOCALE_PATTERN.test(locale)) {\n throw new Error(`Invalid locale format: \"${locale}\"`)\n }\n return locale\n}\n\nexport interface DetectedFramework {\n name: 'nextjs' | 'nuxt' | 'vue' | 'solid' | 'solidstart' | 'react' | 'unknown'\n pluginPackage: string | null\n}\n\nconst FRAMEWORK_DETECTION: Array<{\n dep: string\n name: DetectedFramework['name']\n pluginPackage: string\n}> = [\n { dep: 'next', name: 'nextjs', pluginPackage: '@fluenti/next' },\n { dep: 'nuxt', name: 'nuxt', pluginPackage: '@fluenti/vue' },\n { dep: '@solidjs/start', name: 'solidstart', pluginPackage: '@fluenti/solid' },\n { dep: 'vue', name: 'vue', pluginPackage: '@fluenti/vue' },\n { dep: 'solid-js', name: 'solid', pluginPackage: '@fluenti/solid' },\n { dep: 'react', name: 'react', pluginPackage: '@fluenti/react' },\n]\n\n/**\n * Detect the framework from package.json dependencies.\n */\nexport function detectFramework(deps: Record<string, string>): DetectedFramework {\n for (const entry of FRAMEWORK_DETECTION) {\n if (entry.dep in deps) {\n return { name: entry.name, pluginPackage: entry.pluginPackage }\n }\n }\n return { name: 'unknown', pluginPackage: null }\n}\n\n/**\n * Generate fluenti.config.ts content.\n */\nexport function generateFluentiConfig(opts: {\n sourceLocale: string\n locales: string[]\n format: 'po' | 'json'\n}): string {\n const localesList = opts.locales.map((l) => `'${l}'`).join(', ')\n return `import { defineConfig } from '@fluenti/cli'\n\nexport default defineConfig({\n sourceLocale: '${opts.sourceLocale}',\n locales: [${localesList}],\n catalogDir: './locales',\n format: '${opts.format}',\n include: ['./src/**/*.{vue,tsx,jsx,ts,js}'],\n compileOutDir: './src/locales/compiled',\n})\n`\n}\n\n/**\n * Interactive init flow.\n */\nexport async function runInit(options: { cwd: string }): Promise<void> {\n const pkgPath = resolve(options.cwd, 'package.json')\n if (!existsSync(pkgPath)) {\n consola.error('No package.json found in current directory.')\n return\n }\n\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')) as {\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n scripts?: Record<string, string>\n }\n const allDeps = { ...pkg.dependencies, ...pkg.devDependencies }\n const framework = detectFramework(allDeps)\n\n consola.info(`Detected framework: ${framework.name}`)\n if (framework.pluginPackage) {\n consola.info(`Recommended plugin: ${framework.pluginPackage}`)\n }\n\n // Check if config already exists\n const configPath = resolve(options.cwd, 'fluenti.config.ts')\n if (existsSync(configPath)) {\n consola.warn('fluenti.config.ts already exists. Skipping config generation.')\n return\n }\n\n // Prompt for configuration\n const sourceLocale = await consola.prompt('Source locale?', {\n type: 'text',\n default: 'en',\n placeholder: 'en',\n }) as unknown as string\n\n if (typeof sourceLocale === 'symbol') return // user cancelled\n\n const targetLocalesInput = await consola.prompt('Target locales (comma-separated)?', {\n type: 'text',\n default: 'ja,zh-CN',\n placeholder: 'ja,zh-CN',\n }) as unknown as string\n\n if (typeof targetLocalesInput === 'symbol') return\n\n const format = await consola.prompt('Catalog format?', {\n type: 'select',\n options: ['po', 'json'],\n initial: 'po',\n }) as unknown as string\n\n if (typeof format === 'symbol') return\n\n const targetLocales = targetLocalesInput.split(',').map((l) => l.trim()).filter(Boolean)\n\n // Validate locale formats\n validateLocale(sourceLocale)\n for (const locale of targetLocales) {\n validateLocale(locale)\n }\n\n const allLocales = [sourceLocale, ...targetLocales.filter((l) => l !== sourceLocale)]\n\n // Write config\n const configContent = generateFluentiConfig({\n sourceLocale,\n locales: allLocales,\n format: format as 'po' | 'json',\n })\n writeFileSync(configPath, configContent, 'utf-8')\n consola.success('Created fluenti.config.ts')\n\n // Append to .gitignore\n const gitignorePath = resolve(options.cwd, '.gitignore')\n const gitignoreEntry = 'src/locales/compiled/'\n if (existsSync(gitignorePath)) {\n const existing = readFileSync(gitignorePath, 'utf-8')\n if (!existing.includes(gitignoreEntry)) {\n appendFileSync(gitignorePath, `\\n# Fluenti compiled catalogs\\n${gitignoreEntry}\\n`)\n consola.success('Updated .gitignore')\n }\n } else {\n writeFileSync(gitignorePath, `# Fluenti compiled catalogs\\n${gitignoreEntry}\\n`)\n consola.success('Created .gitignore')\n }\n\n // Patch package.json scripts\n const existingScripts = pkg.scripts ?? {}\n const newScripts: Record<string, string> = {}\n let scriptsChanged = false\n if (!existingScripts['i18n:extract']) {\n newScripts['i18n:extract'] = 'fluenti extract'\n scriptsChanged = true\n }\n if (!existingScripts['i18n:compile']) {\n newScripts['i18n:compile'] = 'fluenti compile'\n scriptsChanged = true\n }\n if (scriptsChanged) {\n const updatedPkg = {\n ...pkg,\n scripts: { ...existingScripts, ...newScripts },\n }\n writeFileSync(pkgPath, JSON.stringify(updatedPkg, null, 2) + '\\n', 'utf-8')\n consola.success('Added i18n:extract and i18n:compile scripts to package.json')\n }\n\n // Print next steps\n consola.log('')\n consola.box({\n title: 'Next steps',\n message: [\n framework.pluginPackage\n ? `1. Install: pnpm add -D ${framework.pluginPackage} @fluenti/cli`\n : '1. Install: pnpm add -D @fluenti/cli',\n framework.name === 'nextjs'\n ? '2. Add withFluenti() to your next.config.ts'\n : framework.name !== 'unknown'\n ? '2. Add the Vite plugin to your vite.config.ts (e.g. fluentiVue() from @fluenti/vue/vite-plugin)'\n : '2. Configure your build tool with the framework Vite plugin or @fluenti/next',\n '3. Run: npx fluenti extract',\n '4. Translate your messages',\n '5. Run: npx fluenti compile',\n ].join('\\n'),\n })\n}\n","#!/usr/bin/env node\nimport { defineCommand, runMain } from 'citty'\nimport consola from 'consola'\nimport fg from 'fast-glob'\nimport { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs'\nimport { resolve, dirname, extname } from 'node:path'\nimport { extractFromTsx } from './tsx-extractor'\nimport { updateCatalog } from './catalog'\nimport type { CatalogData } from './catalog'\nimport { readJsonCatalog, writeJsonCatalog } from './json-format'\nimport { readPoCatalog, writePoCatalog } from './po-format'\nimport { compileCatalog, compileIndex, collectAllIds, compileTypeDeclaration } from './compile'\nimport { parallelCompile } from './parallel-compile'\nimport { formatStatsRow } from './stats-format'\nimport { lintCatalogs, formatDiagnostics } from './lint'\nimport { checkCoverage, formatCheckText, formatCheckGitHub, formatCheckJson } from './check'\nimport { ExtractCache } from './extract-cache'\nimport { CompileCache } from './compile-cache'\nimport { translateCatalog } from './translate'\nimport type { AIProvider } from './translate'\nimport { runMigrate } from './migrate'\nimport { runInit } from './init'\nimport { loadConfig } from './config-loader'\nimport { createHash } from 'node:crypto'\nimport type { ExtractedMessage } from '@fluenti/core/internal'\nimport { resolveLocaleCodes } from '@fluenti/core/internal'\nimport type { FluentiPlugin, PluginCompileContext, FluentiBuildConfig } from '@fluenti/core/internal'\n\nfunction deriveProjectId(cwd: string): string {\n return createHash('md5').update(cwd).digest('hex').slice(0, 8)\n}\n\nfunction readCatalog(filePath: string, format: 'json' | 'po'): CatalogData {\n if (!existsSync(filePath)) return {}\n const content = readFileSync(filePath, 'utf-8')\n return format === 'json' ? readJsonCatalog(content) : readPoCatalog(content)\n}\n\nfunction writeCatalog(filePath: string, catalog: CatalogData, format: 'json' | 'po'): void {\n mkdirSync(dirname(filePath), { recursive: true })\n const content = format === 'json' ? writeJsonCatalog(catalog) : writePoCatalog(catalog)\n writeFileSync(filePath, content, 'utf-8')\n}\n\nasync function extractFromFile(\n filePath: string,\n code: string,\n idGenerator?: (message: string, context?: string) => string,\n): Promise<ExtractedMessage[]> {\n const ext = extname(filePath)\n if (ext === '.vue') {\n try {\n const { extractFromVue } = await import('./vue-extractor')\n return extractFromVue(code, filePath, idGenerator)\n } catch {\n consola.warn(\n `Skipping ${filePath}: install @vue/compiler-sfc to extract from .vue files`,\n )\n return []\n }\n }\n return extractFromTsx(code, filePath, idGenerator)\n}\n\nconst extract = defineCommand({\n meta: { name: 'extract', description: 'Extract messages from source files' },\n args: {\n config: { type: 'string', description: 'Path to config file' },\n clean: { type: 'boolean', description: 'Remove obsolete entries instead of marking them', default: false },\n 'no-fuzzy': { type: 'boolean', description: 'Strip fuzzy flags from all entries', default: false },\n 'no-cache': { type: 'boolean', description: 'Disable incremental extraction cache', default: false },\n },\n async run({ args }) {\n const config = await loadConfig(args.config)\n const localeCodes = resolveLocaleCodes(config.locales)\n consola.info(`Extracting messages from ${config.include.join(', ')}`)\n\n const files = await fg(config.include, { ignore: config.exclude ?? [] })\n const allMessages: ExtractedMessage[] = []\n const useCache = !(args['no-cache'] ?? false)\n const cache = useCache ? new ExtractCache(config.catalogDir, deriveProjectId(process.cwd())) : null\n\n let cacheHits = 0\n\n for (const file of files) {\n if (cache) {\n const cached = cache.get(file)\n if (cached) {\n allMessages.push(...cached)\n cacheHits++\n continue\n }\n }\n\n const code = readFileSync(file, 'utf-8')\n const messages = await extractFromFile(file, code, config.idGenerator)\n allMessages.push(...messages)\n\n if (cache) {\n cache.set(file, messages)\n }\n }\n\n // Prune cache entries for deleted files\n if (cache) {\n cache.prune(new Set(files))\n cache.save()\n }\n\n if (cacheHits > 0) {\n consola.info(`Found ${allMessages.length} messages in ${files.length} files (${cacheHits} cached)`)\n } else {\n consola.info(`Found ${allMessages.length} messages in ${files.length} files`)\n }\n\n const ext = config.format === 'json' ? '.json' : '.po'\n const clean = args.clean ?? false\n const stripFuzzy = args['no-fuzzy'] ?? false\n\n for (const locale of localeCodes) {\n const catalogPath = resolve(config.catalogDir, `${locale}${ext}`)\n const existing = readCatalog(catalogPath, config.format)\n const { catalog, result } = updateCatalog(existing, allMessages, { stripFuzzy })\n\n const finalCatalog = clean\n ? Object.fromEntries(Object.entries(catalog).filter(([, entry]) => !entry.obsolete))\n : catalog\n\n writeCatalog(catalogPath, finalCatalog, config.format)\n\n const obsoleteLabel = clean\n ? `${result.obsolete} removed`\n : `${result.obsolete} obsolete`\n consola.success(\n `${locale}: ${result.added} added, ${result.unchanged} unchanged, ${obsoleteLabel}`,\n )\n }\n\n // Run plugin onAfterExtract hooks\n for (const plugin of config.plugins ?? []) {\n await plugin.onAfterExtract?.({\n messages: new Map(allMessages.map((m) => [m.id, m])),\n sourceLocale: config.sourceLocale,\n targetLocales: localeCodes.filter((l: string) => l !== config.sourceLocale),\n config,\n })\n }\n },\n})\n\n/** Build a Record<string, string> of raw message strings from a catalog for transformMessages hooks */\nfunction catalogToRawMessages(catalog: CatalogData): Record<string, string> {\n const result: Record<string, string> = {}\n for (const [id, entry] of Object.entries(catalog)) {\n if (entry.translation && entry.translation.length > 0) {\n result[id] = entry.translation\n } else if (entry.message) {\n result[id] = entry.message\n }\n }\n return result\n}\n\n/** Apply transformMessages hooks from all plugins and return an updated catalog */\nasync function applyTransformMessages(\n catalog: CatalogData,\n locale: string,\n plugins: readonly FluentiPlugin[],\n): Promise<CatalogData> {\n let rawMessages = catalogToRawMessages(catalog)\n\n for (const plugin of plugins) {\n if (plugin.transformMessages) {\n rawMessages = await plugin.transformMessages(rawMessages, locale)\n }\n }\n\n // Build a new catalog with transformed translations\n const updated: CatalogData = {}\n for (const [id, entry] of Object.entries(catalog)) {\n const transformed = rawMessages[id]\n updated[id] = transformed !== undefined\n ? { ...entry, translation: transformed }\n : { ...entry }\n }\n return updated\n}\n\n/** Build a PluginCompileContext for hook invocation */\nfunction buildCompileContext(\n locale: string,\n catalog: CatalogData,\n outDir: string,\n config: FluentiBuildConfig,\n): PluginCompileContext {\n const messages: Record<string, string> = {}\n for (const [id, entry] of Object.entries(catalog)) {\n if (entry.translation && entry.translation.length > 0) {\n messages[id] = entry.translation\n } else if (entry.message) {\n messages[id] = entry.message\n }\n }\n return { locale, messages, outDir, config }\n}\n\nconst compile = defineCommand({\n meta: { name: 'compile', description: 'Compile message catalogs to JS modules' },\n args: {\n config: { type: 'string', description: 'Path to config file' },\n 'skip-fuzzy': { type: 'boolean', description: 'Exclude fuzzy entries from compilation', default: false },\n 'no-cache': { type: 'boolean', description: 'Disable compilation cache', default: false },\n parallel: { type: 'boolean', description: 'Enable parallel compilation using worker threads', default: false },\n concurrency: { type: 'string', description: 'Max number of worker threads (default: auto)' },\n },\n async run({ args }) {\n const config = await loadConfig(args.config)\n const localeCodes = resolveLocaleCodes(config.locales)\n const ext = config.format === 'json' ? '.json' : '.po'\n\n mkdirSync(config.compileOutDir, { recursive: true })\n\n // Collect all catalogs and build union of IDs\n const allCatalogs: Record<string, CatalogData> = {}\n const catalogContents: Record<string, string> = {}\n for (const locale of localeCodes) {\n const catalogPath = resolve(config.catalogDir, `${locale}${ext}`)\n if (existsSync(catalogPath)) {\n const content = readFileSync(catalogPath, 'utf-8')\n catalogContents[locale] = content\n allCatalogs[locale] = config.format === 'json'\n ? readJsonCatalog(content)\n : readPoCatalog(content)\n } else {\n catalogContents[locale] = ''\n allCatalogs[locale] = {}\n }\n }\n\n const allIds = collectAllIds(allCatalogs)\n consola.info(`Compiling ${allIds.length} messages across ${localeCodes.length} locales`)\n\n const skipFuzzy = args['skip-fuzzy'] ?? false\n const useCache = !(args['no-cache'] ?? false)\n const cache = useCache ? new CompileCache(config.catalogDir, deriveProjectId(process.cwd())) : null\n const useParallel = args.parallel ?? false\n const concurrency = args.concurrency ? parseInt(args.concurrency, 10) : undefined\n\n if (concurrency !== undefined && (isNaN(concurrency) || concurrency < 1)) {\n consola.error('Invalid --concurrency. Must be a positive integer.')\n process.exitCode = 1\n return\n }\n\n let skipped = 0\n let needsRegenIndex = false\n\n // Filter locales that need compilation (cache check)\n const localesToCompile: string[] = []\n for (const locale of localeCodes) {\n if (cache && cache.isUpToDate(locale, catalogContents[locale]!)) {\n const outPath = resolve(config.compileOutDir, `${locale}.js`)\n if (existsSync(outPath)) {\n skipped++\n continue\n }\n }\n localesToCompile.push(locale)\n }\n\n if (localesToCompile.length > 0) {\n needsRegenIndex = true\n }\n\n if (useParallel && localesToCompile.length > 1) {\n // Parallel compilation via worker threads\n const plugins = config.plugins ?? []\n\n // Apply onBeforeCompile and transformMessages hooks before parallel dispatch\n const transformedCatalogs: Record<string, CatalogData> = {}\n for (const locale of localesToCompile) {\n for (const plugin of plugins) {\n await plugin.onBeforeCompile?.(\n buildCompileContext(locale, allCatalogs[locale]!, config.compileOutDir, config),\n )\n }\n transformedCatalogs[locale] = plugins.length > 0\n ? await applyTransformMessages(allCatalogs[locale]!, locale, plugins)\n : allCatalogs[locale]!\n }\n\n const tasks = localesToCompile.map((locale) => ({\n locale,\n catalog: transformedCatalogs[locale]!,\n allIds,\n sourceLocale: config.sourceLocale,\n options: { skipFuzzy },\n }))\n\n const results = await parallelCompile(tasks, concurrency)\n\n for (const result of results) {\n const outPath = resolve(config.compileOutDir, `${result.locale}.js`)\n writeFileSync(outPath, result.code, 'utf-8')\n\n if (cache) {\n cache.set(result.locale, catalogContents[result.locale]!)\n }\n\n if (result.stats.missing.length > 0) {\n consola.warn(\n `${result.locale}: ${result.stats.compiled} compiled, ${result.stats.missing.length} missing translations`,\n )\n for (const id of result.stats.missing) {\n consola.warn(` ⤷ ${id}`)\n }\n } else {\n consola.success(`Compiled ${result.locale}: ${result.stats.compiled} messages → ${outPath}`)\n }\n }\n\n // onAfterCompile hooks after parallel results\n for (const locale of localesToCompile) {\n for (const plugin of plugins) {\n await plugin.onAfterCompile?.(\n buildCompileContext(locale, transformedCatalogs[locale]!, config.compileOutDir, config),\n )\n }\n }\n } else {\n // Serial compilation\n const plugins = config.plugins ?? []\n\n for (const locale of localesToCompile) {\n const outPath = resolve(config.compileOutDir, `${locale}.js`)\n\n // onBeforeCompile hooks\n for (const plugin of plugins) {\n await plugin.onBeforeCompile?.(\n buildCompileContext(locale, allCatalogs[locale]!, config.compileOutDir, config),\n )\n }\n\n // transformMessages hooks\n const catalogForLocale = plugins.length > 0\n ? await applyTransformMessages(allCatalogs[locale]!, locale, plugins)\n : allCatalogs[locale]!\n\n const { code, stats } = compileCatalog(\n catalogForLocale,\n locale,\n allIds,\n config.sourceLocale,\n { skipFuzzy },\n )\n writeFileSync(outPath, code, 'utf-8')\n\n if (cache) {\n cache.set(locale, catalogContents[locale]!)\n }\n\n if (stats.missing.length > 0) {\n consola.warn(\n `${locale}: ${stats.compiled} compiled, ${stats.missing.length} missing translations`,\n )\n for (const id of stats.missing) {\n consola.warn(` ⤷ ${id}`)\n }\n } else {\n consola.success(`Compiled ${locale}: ${stats.compiled} messages → ${outPath}`)\n }\n\n // onAfterCompile hooks\n for (const plugin of plugins) {\n await plugin.onAfterCompile?.(\n buildCompileContext(locale, catalogForLocale, config.compileOutDir, config),\n )\n }\n }\n }\n\n if (skipped > 0) {\n consola.info(`${skipped} locale(s) unchanged — skipped`)\n }\n\n if (cache) {\n cache.save()\n }\n\n // Generate index.js and types when any locale changed or outputs don't exist\n const indexPath = resolve(config.compileOutDir, 'index.js')\n const typesPath = resolve(config.compileOutDir, 'messages.d.ts')\n\n if (needsRegenIndex || !existsSync(indexPath)) {\n const indexCode = compileIndex(localeCodes, config.compileOutDir)\n writeFileSync(indexPath, indexCode, 'utf-8')\n consola.success(`Generated index → ${indexPath}`)\n }\n\n if (needsRegenIndex || !existsSync(typesPath)) {\n const typesCode = compileTypeDeclaration(allIds, allCatalogs, config.sourceLocale)\n writeFileSync(typesPath, typesCode, 'utf-8')\n consola.success(`Generated types → ${typesPath}`)\n }\n },\n})\n\nconst stats = defineCommand({\n meta: { name: 'stats', description: 'Show translation progress' },\n args: {\n config: { type: 'string', description: 'Path to config file' },\n },\n async run({ args }) {\n const config = await loadConfig(args.config)\n const localeCodes = resolveLocaleCodes(config.locales)\n const ext = config.format === 'json' ? '.json' : '.po'\n\n const rows: Array<{ locale: string; total: number; translated: number; pct: string }> = []\n\n for (const locale of localeCodes) {\n const catalogPath = resolve(config.catalogDir, `${locale}${ext}`)\n const catalog = readCatalog(catalogPath, config.format)\n const entries = Object.values(catalog).filter((e) => !e.obsolete)\n const total = entries.length\n const translated = entries.filter((e) => e.translation && e.translation.length > 0).length\n const pct = total > 0 ? ((translated / total) * 100).toFixed(1) + '%' : '—'\n rows.push({ locale, total, translated, pct })\n }\n\n consola.log('')\n consola.log(' Locale │ Total │ Translated │ Progress')\n consola.log(' ────────┼───────┼────────────┼─────────────────────────────')\n for (const row of rows) {\n consola.log(formatStatsRow(row.locale, row.total, row.translated))\n }\n consola.log('')\n },\n})\n\nconst lint = defineCommand({\n meta: { name: 'lint', description: 'Check translation quality (missing, inconsistent placeholders, fuzzy)' },\n args: {\n config: { type: 'string', description: 'Path to config file' },\n strict: { type: 'boolean', description: 'Treat warnings as errors', default: false },\n locale: { type: 'string', description: 'Lint a specific locale only' },\n },\n async run({ args }) {\n const config = await loadConfig(args.config)\n const localeCodes = resolveLocaleCodes(config.locales)\n const ext = config.format === 'json' ? '.json' : '.po'\n\n const allCatalogs: Record<string, CatalogData> = {}\n for (const locale of localeCodes) {\n const catalogPath = resolve(config.catalogDir, `${locale}${ext}`)\n allCatalogs[locale] = readCatalog(catalogPath, config.format)\n }\n\n const targetLocales = args.locale\n ? [args.locale]\n : undefined\n\n consola.info(`Linting ${targetLocales ? targetLocales.join(', ') : 'all locales'} (source: ${config.sourceLocale})`)\n\n const lintOpts: Parameters<typeof lintCatalogs>[1] = {\n sourceLocale: config.sourceLocale,\n strict: args.strict ?? false,\n }\n if (targetLocales) lintOpts.locales = targetLocales\n const diagnostics = lintCatalogs(allCatalogs, lintOpts)\n\n consola.log('')\n consola.log(formatDiagnostics(diagnostics))\n consola.log('')\n\n const errors = diagnostics.filter((d) => d.severity === 'error')\n const warnings = diagnostics.filter((d) => d.severity === 'warning')\n\n if (errors.length > 0) {\n process.exitCode = 1\n } else if (args.strict && warnings.length > 0) {\n process.exitCode = 1\n }\n },\n})\n\nconst check = defineCommand({\n meta: { name: 'check', description: 'Check translation coverage for CI' },\n args: {\n config: { type: 'string', description: 'Path to config file' },\n ci: { type: 'boolean', description: 'Alias for --format github', default: false },\n 'min-coverage': { type: 'string', description: 'Minimum coverage percentage (0-100)', default: '100' },\n format: { type: 'string', description: 'Output format: text | json | github' },\n locale: { type: 'string', description: 'Check a specific locale only' },\n },\n async run({ args }) {\n const config = await loadConfig(args.config)\n const localeCodes = resolveLocaleCodes(config.locales)\n const ext = config.format === 'json' ? '.json' : '.po'\n\n const allCatalogs: Record<string, CatalogData> = {}\n for (const locale of localeCodes) {\n const catalogPath = resolve(config.catalogDir, `${locale}${ext}`)\n allCatalogs[locale] = readCatalog(catalogPath, config.format)\n }\n\n const minCoverage = parseFloat(args['min-coverage'] ?? '100')\n if (isNaN(minCoverage) || minCoverage < 0 || minCoverage > 100) {\n consola.error('Invalid --min-coverage. Must be a number between 0 and 100.')\n process.exitCode = 1\n return\n }\n\n const outputFormat = args.format ?? (args.ci ? 'github' : 'text')\n\n const checkOpts: Parameters<typeof checkCoverage>[1] = {\n sourceLocale: config.sourceLocale,\n minCoverage,\n format: outputFormat as 'text' | 'json' | 'github',\n }\n if (args.locale) checkOpts.locale = args.locale\n\n const output = checkCoverage(allCatalogs, checkOpts)\n\n switch (outputFormat) {\n case 'json':\n consola.log(formatCheckJson(output))\n break\n case 'github':\n consola.log(formatCheckGitHub(output, config.catalogDir, config.format))\n break\n default:\n consola.log('')\n consola.log(formatCheckText(output))\n consola.log('')\n break\n }\n\n if (!output.passed) {\n process.exitCode = 1\n }\n },\n})\n\nconst translate = defineCommand({\n meta: { name: 'translate', description: 'Translate messages using AI (Claude Code or Codex CLI)' },\n args: {\n config: { type: 'string', description: 'Path to config file' },\n provider: { type: 'string', description: 'AI provider: claude or codex', default: 'claude' },\n locale: { type: 'string', description: 'Translate a specific locale only' },\n 'batch-size': { type: 'string', description: 'Messages per batch', default: '50' },\n 'dry-run': { type: 'boolean', description: 'Preview translation results without writing files', default: false },\n context: { type: 'string', description: 'Project context description to improve translation quality' },\n },\n async run({ args }) {\n const config = await loadConfig(args.config)\n const localeCodes = resolveLocaleCodes(config.locales)\n const provider = args.provider as AIProvider\n\n if (provider !== 'claude' && provider !== 'codex') {\n consola.error(`Invalid provider \"${provider}\". Use \"claude\" or \"codex\".`)\n return\n }\n\n const batchSize = parseInt(args['batch-size'] ?? '50', 10)\n if (isNaN(batchSize) || batchSize < 1) {\n consola.error('Invalid batch-size. Must be a positive integer.')\n return\n }\n\n const targetLocales = args.locale\n ? [args.locale]\n : localeCodes.filter((l: string) => l !== config.sourceLocale)\n\n if (targetLocales.length === 0) {\n consola.warn('No target locales to translate.')\n return\n }\n\n consola.info(`Translating with ${provider} (batch size: ${batchSize})`)\n const ext = config.format === 'json' ? '.json' : '.po'\n\n for (const locale of targetLocales) {\n consola.info(`\\n[${locale}]`)\n const catalogPath = resolve(config.catalogDir, `${locale}${ext}`)\n const catalog = readCatalog(catalogPath, config.format)\n\n if (args['dry-run']) {\n const untranslated = Object.entries(catalog).filter(\n ([, entry]) => !entry.obsolete && (!entry.translation || entry.translation.length === 0),\n )\n if (untranslated.length > 0) {\n for (const [id, entry] of untranslated) {\n consola.log(` ${id}: ${entry.message ?? id}`)\n }\n consola.success(` ${locale}: ${untranslated.length} messages would be translated (dry-run)`)\n } else {\n consola.success(` ${locale}: already fully translated`)\n }\n continue\n }\n\n const { catalog: updated, translated } = await translateCatalog({\n provider,\n sourceLocale: config.sourceLocale,\n targetLocale: locale,\n catalog,\n batchSize,\n ...(args.context ? { context: args.context } : {}),\n })\n\n if (translated > 0) {\n writeCatalog(catalogPath, updated, config.format)\n consola.success(` ${locale}: ${translated} messages translated`)\n } else {\n consola.success(` ${locale}: already fully translated`)\n }\n }\n },\n})\n\nconst migrate = defineCommand({\n meta: { name: 'migrate', description: 'Migrate from another i18n library using AI' },\n args: {\n from: { type: 'string', description: 'Source library: vue-i18n, nuxt-i18n, react-i18next, next-intl, next-i18next, lingui', required: true },\n provider: { type: 'string', description: 'AI provider: claude or codex', default: 'claude' },\n write: { type: 'boolean', description: 'Write generated files to disk', default: false },\n },\n async run({ args }) {\n const provider = args.provider as AIProvider\n if (provider !== 'claude' && provider !== 'codex') {\n consola.error(`Invalid provider \"${provider}\". Use \"claude\" or \"codex\".`)\n return\n }\n\n await runMigrate({\n from: args.from!,\n provider,\n write: args.write ?? false,\n })\n },\n})\n\nconst init = defineCommand({\n meta: { name: 'init', description: 'Initialize Fluenti in your project' },\n args: {},\n async run() {\n await runInit({ cwd: process.cwd() })\n },\n})\n\nconst main = defineCommand({\n meta: {\n name: 'fluenti',\n version: '0.0.1',\n description: 'Compile-time i18n for modern frameworks',\n },\n subCommands: { init, extract, compile, stats, lint, check, translate, migrate },\n})\n\nrunMain(main)\n"],"mappings":";;;;;;;;;;;;;;;AAAA,IAAM,KAAa,KACb,KAAc;AAQpB,SAAgB,GAAkB,GAAa,IAAQ,IAAY;CAEjE,IAAM,IAAS,KAAK,MADJ,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,EAAI,CAAC,GACV,MAAO,EAAM;AAClD,QAAO,GAAW,OAAO,EAAO,GAAG,GAAY,OAAO,IAAQ,EAAO;;AAUvE,SAAgB,GAAgB,GAAqB;CACnD,IAAM,IAAQ,EAAI,QAAQ,EAAE,GAAG;AAG/B,QAFI,KAAO,KAAW,WAAW,EAAM,WACnC,KAAO,KAAW,WAAW,EAAM,WAChC,WAAW,EAAM;;AAM1B,SAAgB,GACd,GACA,GACA,GACQ;CACR,IAAM,IAAM,IAAQ,IAAK,IAAa,IAAS,MAAM,GAC/C,IAAa,IAAQ,IAAI,GAAgB,EAAI,GAAG,KAChD,IAAM,IAAQ,IAAI,GAAkB,EAAI,GAAG;AACjD,QAAO,KAAK,EAAO,OAAO,EAAE,CAAC,IAAI,OAAO,EAAM,CAAC,SAAS,EA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AAS;AACjD,KAAQ,MAAM,qBAAqB,EAAS,6BAA6B;AACzE;;AAGF,QAAM,GAAW;GACf,MAAM,EAAK;GACX;GACA,OAAO,EAAK,SAAS;GACtB,CAAC;;CAEL,CAAC;AAmBF,EATa,EAAc;CACzB,MAAM;EACJ,MAAM;EACN,SAAS;EACT,aAAa;EACd;CACD,aAAa;EAAE,MAdJ,EAAc;GACzB,MAAM;IAAE,MAAM;IAAQ,aAAa;IAAsC;GACzE,MAAM,EAAE;GACR,MAAM,MAAM;AACV,UAAM,GAAQ,EAAE,KAAK,QAAQ,KAAK,EAAE,CAAC;;GAExC,CAAC;EAQqB;EAAS;EAAS;EAAO;EAAM;EAAO;EAAW;EAAS;CAChF,CAAC,CAEW"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/stats-format.ts","../src/validation.ts","../src/lint.ts","../src/check.ts","../src/compile-cache.ts","../src/ai-provider.ts","../src/translate.ts","../src/migrate.ts","../src/init.ts","../src/cli.ts"],"sourcesContent":["const BLOCK_FULL = '█'\nconst BLOCK_EMPTY = '░'\n\n/**\n * Render a Unicode progress bar.\n *\n * @param pct - Percentage (0–100)\n * @param width - Character width of the bar (default 20)\n */\nexport function formatProgressBar(pct: number, width = 20): string {\n const clamped = Math.max(0, Math.min(100, pct))\n const filled = Math.round((clamped / 100) * width)\n return BLOCK_FULL.repeat(filled) + BLOCK_EMPTY.repeat(width - filled)\n}\n\n/**\n * Wrap a percentage string in ANSI colour based on value.\n *\n * - ≥90 → green (\\x1b[32m)\n * - ≥70 → yellow (\\x1b[33m)\n * - <70 → red (\\x1b[31m)\n */\nexport function colorizePercent(pct: number): string {\n const label = pct.toFixed(1) + '%'\n if (pct >= 90) return `\\x1b[32m${label}\\x1b[0m`\n if (pct >= 70) return `\\x1b[33m${label}\\x1b[0m`\n return `\\x1b[31m${label}\\x1b[0m`\n}\n\n/**\n * Format a full stats row for a single locale.\n */\nexport function formatStatsRow(\n locale: string,\n total: number,\n translated: number,\n): string {\n const pct = total > 0 ? (translated / total) * 100 : 0\n const pctDisplay = total > 0 ? colorizePercent(pct) : '—'\n const bar = total > 0 ? formatProgressBar(pct) : ''\n return ` ${locale.padEnd(8)}│ ${String(total).padStart(5)} │ ${String(translated).padStart(10)} │ ${bar} ${pctDisplay}`\n}\n","export interface ValidationResult {\n valid: boolean\n missingPlaceholders: string[]\n extraPlaceholders: string[]\n missingHtmlTags: string[]\n extraHtmlTags: string[]\n syntaxErrors: string[]\n}\n\nimport { parse } from '@fluenti/core/internal'\nimport type { ASTNode } from '@fluenti/core/internal'\n\nconst ICU_PLURAL_SELECT_RE = /\\{(\\w+),\\s*(plural|select|selectordinal)\\s*,/\n\n/** Extract unique ICU placeholder names from a message, sorted alphabetically.\n * Uses the ICU parser so only top-level variables are returned — select/plural case\n * body words (e.g. the `he`/`she` in `{g, select, male {he} other {she}}`) are not\n * mistakenly treated as placeholder names. */\nexport function extractPlaceholders(message: string): string[] {\n try {\n const ast = parse(message)\n const seen = new Set<string>()\n collectVariableNames(ast, seen)\n return [...seen].sort()\n } catch {\n // Fallback for unparseable messages: extract only top-level {word} patterns\n const seen = new Set<string>()\n // Match {word} at depth 0 — skip nested braces inside plural/select case bodies\n let depth = 0\n let i = 0\n while (i < message.length) {\n if (message[i] === '{') {\n depth++\n if (depth === 1) {\n const end = message.indexOf('}', i + 1)\n if (end !== -1) {\n const inner = message.slice(i + 1, end).trim()\n const nameMatch = /^(\\w+)/.exec(inner)\n if (nameMatch) seen.add(nameMatch[1]!)\n }\n }\n } else if (message[i] === '}') {\n depth--\n }\n i++\n }\n return [...seen].sort()\n }\n}\n\nfunction collectVariableNames(nodes: ASTNode[], seen: Set<string>): void {\n for (const node of nodes) {\n if (node.type === 'variable' && node.name !== '#') {\n seen.add(node.name)\n } else if (node.type === 'plural' || node.type === 'select') {\n seen.add(node.variable)\n for (const branch of Object.values(node.options)) {\n collectVariableNames(branch, seen)\n }\n } else if (node.type === 'function') {\n seen.add(node.variable)\n }\n }\n}\n\n/** Extract unique HTML tag names from a message, lowercased and sorted */\nexport function extractHtmlTags(message: string): string[] {\n const seen = new Set<string>()\n const regex = /<\\/?([a-zA-Z][\\w-]*)[^>]*>/g\n let match\n while ((match = regex.exec(message)) !== null) {\n seen.add(match[1]!.toLowerCase())\n }\n return [...seen].sort()\n}\n\n/** Validate that a translation preserves placeholders and HTML tags from the source */\nexport function validateTranslation(source: string, translation: string): ValidationResult {\n const sourcePlaceholders = extractPlaceholders(source)\n const translationPlaceholders = extractPlaceholders(translation)\n const sourceHtmlTags = extractHtmlTags(source)\n const translationHtmlTags = extractHtmlTags(translation)\n\n const missingPlaceholders = sourcePlaceholders.filter(p => !translationPlaceholders.includes(p))\n const extraPlaceholders = translationPlaceholders.filter(p => !sourcePlaceholders.includes(p))\n const missingHtmlTags = sourceHtmlTags.filter(t => !translationHtmlTags.includes(t))\n const extraHtmlTags = translationHtmlTags.filter(t => !sourceHtmlTags.includes(t))\n\n const syntaxErrors: string[] = []\n if (ICU_PLURAL_SELECT_RE.test(translation)) {\n try {\n parse(translation)\n } catch (err) {\n syntaxErrors.push((err as Error).message)\n }\n }\n\n return {\n valid: missingPlaceholders.length === 0\n && extraPlaceholders.length === 0\n && missingHtmlTags.length === 0\n && extraHtmlTags.length === 0\n && syntaxErrors.length === 0,\n missingPlaceholders,\n extraPlaceholders,\n missingHtmlTags,\n extraHtmlTags,\n syntaxErrors,\n }\n}\n\n/** Validate a batch of translations, returning only invalid entries */\nexport function validateBatch(\n sources: Record<string, string>,\n translations: Record<string, string>,\n): Record<string, ValidationResult> {\n const results: Record<string, ValidationResult> = {}\n\n for (const key of Object.keys(sources)) {\n const translation = translations[key]\n if (translation === undefined) continue\n\n const result = validateTranslation(sources[key]!, translation)\n if (!result.valid) {\n results[key] = result\n }\n }\n\n return results\n}\n","import type { CatalogData } from './catalog'\nimport { extractPlaceholders } from './validation.js'\n\n/** Severity levels for lint diagnostics */\nexport type LintSeverity = 'error' | 'warning' | 'info'\n\n/** A single lint diagnostic */\nexport interface LintDiagnostic {\n /** Lint rule that produced this diagnostic */\n rule: string\n /** Severity level */\n severity: LintSeverity\n /** Human-readable message */\n message: string\n /** Affected message ID */\n messageId?: string\n /** Affected locale */\n locale?: string\n}\n\n/** Options for configuring lint behavior */\nexport interface LintOptions {\n /** Locales to lint (default: all) */\n locales?: string[]\n /** Source locale for comparison */\n sourceLocale: string\n /** Whether to fail on warnings (default: false) */\n strict?: boolean\n}\n\n/**\n * Run all lint rules against the provided catalogs.\n *\n * Returns an array of diagnostics. Empty array = all checks passed.\n */\nexport function lintCatalogs(\n catalogs: Record<string, CatalogData>,\n options: LintOptions,\n): LintDiagnostic[] {\n const diagnostics: LintDiagnostic[] = []\n const { sourceLocale } = options\n const locales = options.locales ?? Object.keys(catalogs)\n const sourceCatalog = catalogs[sourceLocale]\n\n if (!sourceCatalog) {\n diagnostics.push({\n rule: 'missing-source',\n severity: 'error',\n message: `Source locale catalog \"${sourceLocale}\" not found`,\n })\n return diagnostics\n }\n\n // Collect non-obsolete source IDs\n const sourceIds = Object.entries(sourceCatalog)\n .filter(([, entry]) => !entry.obsolete)\n .map(([id]) => id)\n\n for (const locale of locales) {\n if (locale === sourceLocale) continue\n const catalog = catalogs[locale]\n if (!catalog) {\n diagnostics.push({\n rule: 'missing-locale',\n severity: 'error',\n message: `Catalog for locale \"${locale}\" not found`,\n locale,\n })\n continue\n }\n\n for (const id of sourceIds) {\n const sourceEntry = sourceCatalog[id]!\n const targetEntry = catalog[id]\n\n // Rule: missing-translation\n if (!targetEntry || !targetEntry.translation || targetEntry.translation.length === 0) {\n diagnostics.push({\n rule: 'missing-translation',\n severity: 'error',\n message: `Missing translation for \"${id}\" in locale \"${locale}\"`,\n messageId: id,\n locale,\n })\n continue\n }\n\n // Rule: inconsistent-placeholders\n const sourceMessage = sourceEntry.message ?? id\n const sourcePlaceholders = extractPlaceholders(sourceMessage)\n const targetPlaceholders = extractPlaceholders(targetEntry.translation)\n\n const missingInTarget = sourcePlaceholders.filter((p) => !targetPlaceholders.includes(p))\n const extraInTarget = targetPlaceholders.filter((p) => !sourcePlaceholders.includes(p))\n\n if (missingInTarget.length > 0) {\n diagnostics.push({\n rule: 'inconsistent-placeholders',\n severity: 'error',\n message: `Translation for \"${id}\" in \"${locale}\" is missing placeholders: ${missingInTarget.map((p) => `{${p}}`).join(', ')}`,\n messageId: id,\n locale,\n })\n }\n\n if (extraInTarget.length > 0) {\n diagnostics.push({\n rule: 'inconsistent-placeholders',\n severity: 'warning',\n message: `Translation for \"${id}\" in \"${locale}\" has extra placeholders: ${extraInTarget.map((p) => `{${p}}`).join(', ')}`,\n messageId: id,\n locale,\n })\n }\n\n // Rule: fuzzy-translation\n if (targetEntry.fuzzy) {\n diagnostics.push({\n rule: 'fuzzy-translation',\n severity: 'warning',\n message: `Translation for \"${id}\" in \"${locale}\" is marked as fuzzy`,\n messageId: id,\n locale,\n })\n }\n }\n\n // Rule: orphan-translation (target has entries not in source)\n for (const [id, entry] of Object.entries(catalog)) {\n if (entry.obsolete) continue\n if (!sourceCatalog[id] || sourceCatalog[id]!.obsolete) {\n diagnostics.push({\n rule: 'orphan-translation',\n severity: 'warning',\n message: `Translation \"${id}\" in \"${locale}\" has no corresponding source message`,\n messageId: id,\n locale,\n })\n }\n }\n }\n\n // Rule: duplicate-messages (same translation text for different IDs in source)\n const messageToIds = new Map<string, string[]>()\n for (const [id, entry] of Object.entries(sourceCatalog)) {\n if (entry.obsolete) continue\n const msg = entry.message ?? id\n const existing = messageToIds.get(msg)\n if (existing) {\n existing.push(id)\n } else {\n messageToIds.set(msg, [id])\n }\n }\n for (const [msg, ids] of messageToIds) {\n if (ids.length > 1) {\n diagnostics.push({\n rule: 'duplicate-message',\n severity: 'info',\n message: `Duplicate source message \"${msg.slice(0, 60)}${msg.length > 60 ? '...' : ''}\" used by ${ids.length} entries: ${ids.join(', ')}`,\n locale: sourceLocale,\n })\n }\n }\n\n return diagnostics\n}\n\n\n/**\n * Format lint diagnostics for console output.\n */\nexport function formatDiagnostics(diagnostics: LintDiagnostic[]): string {\n if (diagnostics.length === 0) return ' ✓ All checks passed'\n\n const lines: string[] = []\n const grouped = groupBy(diagnostics, (d) => d.rule)\n\n for (const [rule, items] of Object.entries(grouped)) {\n lines.push(` ${rule} (${items.length}):`)\n for (const d of items) {\n const icon = d.severity === 'error' ? '✗' : d.severity === 'warning' ? '⚠' : 'ℹ'\n lines.push(` ${icon} ${d.message}`)\n }\n }\n\n const errors = diagnostics.filter((d) => d.severity === 'error').length\n const warnings = diagnostics.filter((d) => d.severity === 'warning').length\n const infos = diagnostics.filter((d) => d.severity === 'info').length\n\n lines.push('')\n lines.push(` Summary: ${errors} errors, ${warnings} warnings, ${infos} info`)\n\n return lines.join('\\n')\n}\n\nfunction groupBy<T>(items: T[], key: (item: T) => string): Record<string, T[]> {\n const result: Record<string, T[]> = {}\n for (const item of items) {\n const k = key(item)\n ;(result[k] ?? (result[k] = [])).push(item)\n }\n return result\n}\n","import type { CatalogData } from './catalog'\nimport { lintCatalogs } from './lint'\nimport type { LintDiagnostic } from './lint'\n\n/** Per-locale coverage result */\nexport interface CheckResult {\n locale: string\n total: number\n translated: number\n missing: number\n fuzzy: number\n coverage: number // 0-100\n}\n\n/** Options for the check command */\nexport interface CheckOptions {\n /** Source locale for comparison */\n sourceLocale: string\n /** Minimum coverage percentage (0-100) */\n minCoverage: number\n /** Check only a specific locale */\n locale?: string\n /** Output format */\n format: 'text' | 'json' | 'github'\n}\n\n/** Full check result */\nexport interface CheckOutput {\n results: CheckResult[]\n passed: boolean\n minCoverage: number\n actualCoverage: number\n diagnostics: LintDiagnostic[]\n}\n\n/**\n * Check translation coverage across all locale catalogs.\n */\nexport function checkCoverage(\n catalogs: Record<string, CatalogData>,\n options: CheckOptions,\n): CheckOutput {\n const { sourceLocale, minCoverage, locale: targetLocale } = options\n const sourceCatalog = catalogs[sourceLocale]\n\n if (!sourceCatalog) {\n return {\n results: [],\n passed: false,\n minCoverage,\n actualCoverage: 0,\n diagnostics: [{\n rule: 'missing-source',\n severity: 'error',\n message: `Source locale catalog \"${sourceLocale}\" not found`,\n }],\n }\n }\n\n // Count non-obsolete source entries\n const sourceIds = Object.entries(sourceCatalog)\n .filter(([, entry]) => !entry.obsolete)\n .map(([id]) => id)\n\n const total = sourceIds.length\n\n // Determine which locales to check\n const localesToCheck = targetLocale\n ? [targetLocale]\n : Object.keys(catalogs).filter((l) => l !== sourceLocale)\n\n const results: CheckResult[] = []\n\n for (const locale of localesToCheck) {\n const catalog = catalogs[locale]\n if (!catalog) {\n results.push({\n locale,\n total,\n translated: 0,\n missing: total,\n fuzzy: 0,\n coverage: 0,\n })\n continue\n }\n\n let translated = 0\n let missing = 0\n let fuzzy = 0\n\n for (const id of sourceIds) {\n const entry = catalog[id]\n if (!entry || !entry.translation || entry.translation.length === 0) {\n missing++\n } else {\n translated++\n if (entry.fuzzy) {\n fuzzy++\n }\n }\n }\n\n const coverage = total > 0 ? (translated / total) * 100 : 100\n results.push({ locale, total, translated, missing, fuzzy, coverage })\n }\n\n // Calculate overall coverage\n const totalTranslated = results.reduce((sum, r) => sum + r.translated, 0)\n const totalEntries = results.reduce((sum, r) => sum + r.total, 0)\n const actualCoverage = totalEntries > 0\n ? (totalTranslated / totalEntries) * 100\n : 100\n\n const passed = results.every((r) => r.coverage >= minCoverage)\n\n // Run lint diagnostics for missing translations\n const lintOpts: Parameters<typeof lintCatalogs>[1] = { sourceLocale }\n if (targetLocale) {\n lintOpts.locales = [sourceLocale, targetLocale]\n }\n\n const diagnostics = lintCatalogs(catalogs, lintOpts)\n\n return { results, passed, minCoverage, actualCoverage, diagnostics }\n}\n\n/**\n * Format check output as plain text.\n */\nexport function formatCheckText(output: CheckOutput): string {\n const lines: string[] = []\n\n for (const r of output.results) {\n const icon = r.coverage >= output.minCoverage ? '✓' : '✗'\n const pct = r.coverage.toFixed(1)\n const details = r.missing > 0 ? ` — ${r.missing} missing` : ''\n const fuzzyNote = r.fuzzy > 0 ? `, ${r.fuzzy} fuzzy` : ''\n lines.push(`${icon} ${r.locale}: ${pct}% (${r.translated}/${r.total})${details}${fuzzyNote}`)\n }\n\n lines.push('')\n const overallPct = output.actualCoverage.toFixed(1)\n const status = output.passed ? 'PASSED' : 'FAILED'\n lines.push(`Coverage: ${overallPct}% (min: ${output.minCoverage}%) — ${status}`)\n\n return lines.join('\\n')\n}\n\n/**\n * Format check output as GitHub Actions annotations.\n */\nexport function formatCheckGitHub(\n output: CheckOutput,\n catalogDir: string,\n format: 'json' | 'po',\n): string {\n const lines: string[] = []\n const ext = format === 'json' ? '.json' : '.po'\n\n for (const r of output.results) {\n if (r.coverage < output.minCoverage) {\n const file = `${catalogDir}/${r.locale}${ext}`\n lines.push(\n `::error file=${file}::Translation coverage ${r.coverage.toFixed(1)}% below minimum ${output.minCoverage}%`,\n )\n }\n }\n\n // Add individual missing translation warnings\n const missingDiags = output.diagnostics.filter((d) => d.rule === 'missing-translation')\n for (const d of missingDiags) {\n if (d.locale) {\n const file = `${catalogDir}/${d.locale}${ext}`\n lines.push(`::warning file=${file}::${d.message}`)\n }\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Format check output as JSON.\n */\nexport function formatCheckJson(output: CheckOutput): string {\n return JSON.stringify({\n results: output.results,\n passed: output.passed,\n minCoverage: output.minCoverage,\n actualCoverage: Math.round(output.actualCoverage * 10) / 10,\n }, null, 2)\n}\n","import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { createHash } from 'node:crypto'\nimport { dirname, resolve } from 'node:path'\n\n/** Cache format version — bump when the structure changes */\nconst CACHE_VERSION = '1'\n\ninterface CompileCacheEntry {\n inputHash: string\n}\n\ninterface CompileCacheData {\n version: string\n entries: Record<string, CompileCacheEntry> // keyed by locale\n}\n\n/**\n * Compile cache that skips re-compilation when PO/JSON files haven't changed.\n *\n * Uses MD5 of input file content as change detection (non-cryptographic, fast).\n */\nexport class CompileCache {\n private data: CompileCacheData\n private cachePath: string\n private dirty = false\n\n constructor(catalogDir: string, projectId?: string) {\n const cacheDir = projectId\n ? resolve(catalogDir, '.cache', projectId)\n : resolve(catalogDir, '.cache')\n this.cachePath = resolve(cacheDir, 'compile-cache.json')\n this.data = this.load()\n }\n\n /**\n * Check if a locale's catalog has changed since last compile.\n * Returns true if unchanged (cache hit), false if re-compilation needed.\n */\n isUpToDate(locale: string, catalogContent: string): boolean {\n const entry = this.data.entries[locale]\n if (!entry) return false\n\n const currentHash = hashContent(catalogContent)\n return entry.inputHash === currentHash\n }\n\n /**\n * Update the cache after a successful compilation.\n */\n set(locale: string, catalogContent: string): void {\n this.data.entries[locale] = {\n inputHash: hashContent(catalogContent),\n }\n this.dirty = true\n }\n\n /**\n * Write the cache to disk if any changes were made.\n */\n save(): void {\n if (!this.dirty) return\n\n try {\n mkdirSync(dirname(this.cachePath), { recursive: true })\n writeFileSync(this.cachePath, JSON.stringify(this.data), 'utf-8')\n this.dirty = false\n } catch {\n // Cache write failure is non-fatal — next run will re-compile\n }\n }\n\n private load(): CompileCacheData {\n try {\n if (existsSync(this.cachePath)) {\n const raw = readFileSync(this.cachePath, 'utf-8')\n const parsed = JSON.parse(raw) as CompileCacheData\n if (parsed.version === CACHE_VERSION) {\n return parsed\n }\n }\n } catch {\n // Corrupt or unreadable cache — start fresh\n }\n\n return { version: CACHE_VERSION, entries: {} }\n }\n}\n\nfunction hashContent(content: string): string {\n return createHash('md5').update(content).digest('hex')\n}\n","import { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport { setTimeout as sleep } from 'node:timers/promises'\n\nconst execFileAsync = promisify(execFile)\n\nexport type AIProvider = 'claude' | 'codex'\n\nexport interface AIInvokeOptions {\n readonly provider: AIProvider\n readonly prompt: string\n readonly maxRetries?: number\n readonly initialDelayMs?: number\n readonly maxBuffer?: number\n}\n\nexport interface AIInvokeResult {\n readonly stdout: string\n readonly attempts: number\n}\n\nconst INSTALL_COMMANDS: Record<AIProvider, string> = {\n claude: 'npm install -g @anthropic-ai/claude-code',\n codex: 'npm install -g @openai/codex',\n}\n\nfunction buildArgs(provider: AIProvider, prompt: string): readonly string[] {\n return provider === 'claude'\n ? ['-p', prompt]\n : ['-p', prompt, '--full-auto']\n}\n\nfunction isEnoent(error: unknown): boolean {\n return (error as Error & { code?: string }).code === 'ENOENT'\n}\n\nexport async function invokeAI(options: AIInvokeOptions): Promise<AIInvokeResult> {\n const {\n provider,\n prompt,\n maxRetries = 3,\n initialDelayMs = 1000,\n maxBuffer = 10 * 1024 * 1024,\n } = options\n\n const args = buildArgs(provider, prompt)\n const command = provider === 'claude' ? 'claude' : 'codex'\n let lastError: unknown\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const { stdout } = await execFileAsync(command, [...args], { maxBuffer })\n return { stdout, attempts: attempt + 1 }\n } catch (error: unknown) {\n if (isEnoent(error)) {\n throw new Error(\n `\"${provider}\" CLI not found. Please install it first:\\n ${INSTALL_COMMANDS[provider]}`,\n )\n }\n lastError = error\n if (attempt < maxRetries) {\n const delay = initialDelayMs * 2 ** attempt\n await sleep(delay)\n }\n }\n }\n\n throw lastError\n}\n","import consola from 'consola'\nimport type { CatalogData } from './catalog'\nimport { invokeAI } from './ai-provider'\nimport type { AIProvider } from './ai-provider'\nexport type { AIProvider } from './ai-provider'\n\nexport function buildPrompt(\n sourceLocale: string,\n targetLocale: string,\n messages: Record<string, string>,\n context?: string,\n): string {\n const json = JSON.stringify(messages, null, 2)\n return [\n `You are a professional translator. Translate the following messages from \"${sourceLocale}\" to \"${targetLocale}\".`,\n '',\n ...(context ? [`Project context: ${context}`, ''] : []),\n `Input (JSON):`,\n json,\n '',\n 'Rules:',\n '- Output ONLY valid JSON with the same keys and translated values.',\n '- Keep ICU MessageFormat placeholders like {name}, {count}, {gender} unchanged.',\n '- Keep HTML tags unchanged.',\n '- Do not add any explanation or markdown formatting, output raw JSON only.',\n ].join('\\n')\n}\n\n\nexport function extractJSON(text: string): Record<string, string> {\n // Try to find a JSON object in the response\n const match = text.match(/\\{[\\s\\S]*\\}/)\n if (!match) {\n throw new Error('No JSON object found in AI response')\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(match[0])\n } catch {\n throw new Error(`Failed to parse JSON from AI response: ${match[0].slice(0, 200)}`)\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error('AI response is not a valid JSON object')\n }\n return parsed as Record<string, string>\n}\n\nexport function getUntranslatedEntries(catalog: CatalogData): Record<string, string> {\n const entries: Record<string, string> = {}\n for (const [id, entry] of Object.entries(catalog)) {\n if (entry.obsolete) continue\n if (!entry.translation || entry.translation.length === 0) {\n entries[id] = entry.message ?? id\n }\n }\n return entries\n}\n\nexport function chunkEntries(\n entries: Record<string, string>,\n batchSize: number,\n): Array<Record<string, string>> {\n const keys = Object.keys(entries)\n const chunks: Array<Record<string, string>> = []\n\n for (let i = 0; i < keys.length; i += batchSize) {\n const chunk: Record<string, string> = {}\n for (const key of keys.slice(i, i + batchSize)) {\n chunk[key] = entries[key]!\n }\n chunks.push(chunk)\n }\n\n return chunks\n}\n\nexport interface TranslateOptions {\n provider: AIProvider\n sourceLocale: string\n targetLocale: string\n catalog: CatalogData\n batchSize: number\n context?: string\n}\n\nexport async function translateCatalog(options: TranslateOptions): Promise<{\n catalog: CatalogData\n translated: number\n}> {\n const { provider, sourceLocale, targetLocale, catalog, batchSize, context } = options\n\n const untranslated = getUntranslatedEntries(catalog)\n const count = Object.keys(untranslated).length\n\n if (count === 0) {\n return { catalog: { ...catalog }, translated: 0 }\n }\n\n consola.info(` ${count} untranslated messages, translating with ${provider}...`)\n\n const result = { ...catalog }\n const batches = chunkEntries(untranslated, batchSize)\n let totalTranslated = 0\n\n for (let i = 0; i < batches.length; i++) {\n const batch = batches[i]!\n const batchKeys = Object.keys(batch)\n\n if (batches.length > 1) {\n consola.info(` Batch ${i + 1}/${batches.length} (${batchKeys.length} messages)`)\n }\n\n const prompt = buildPrompt(sourceLocale, targetLocale, batch, context)\n const { stdout: response } = await invokeAI({ provider, prompt })\n const translations = extractJSON(response)\n\n for (const key of batchKeys) {\n if (translations[key] && typeof translations[key] === 'string') {\n result[key] = {\n ...result[key],\n translation: translations[key],\n }\n totalTranslated++\n } else {\n consola.warn(` Missing translation for key: ${key}`)\n }\n }\n }\n\n return { catalog: result, translated: totalTranslated }\n}\n","import { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport { readFileSync, existsSync } from 'node:fs'\nimport { resolve, join, dirname } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport fg from 'fast-glob'\nimport consola from 'consola'\nimport type { AIProvider } from './translate'\n\nconst execFileAsync = promisify(execFile)\n\nexport type SupportedLibrary =\n | 'vue-i18n'\n | 'nuxt-i18n'\n | 'react-i18next'\n | 'next-intl'\n | 'next-i18next'\n | 'lingui'\n\ninterface LibraryInfo {\n name: SupportedLibrary\n framework: string\n configPatterns: string[]\n localePatterns: string[]\n sourcePatterns: string[]\n migrationGuide: string // relative path from packages/\n}\n\nconst LIBRARY_INFO: Record<SupportedLibrary, LibraryInfo> = {\n 'vue-i18n': {\n name: 'vue-i18n',\n framework: 'Vue',\n configPatterns: ['i18n.ts', 'i18n.js', 'i18n/index.ts', 'i18n/index.js', 'src/i18n.ts', 'src/i18n.js', 'src/i18n/index.ts', 'src/plugins/i18n.ts'],\n localePatterns: ['locales/*.json', 'src/locales/*.json', 'i18n/*.json', 'src/i18n/*.json', 'lang/*.json', 'src/lang/*.json', 'locales/*.yaml', 'locales/*.yml'],\n sourcePatterns: ['src/**/*.vue'],\n migrationGuide: 'vue/llms-migration.txt',\n },\n 'nuxt-i18n': {\n name: 'nuxt-i18n',\n framework: 'Nuxt',\n configPatterns: ['nuxt.config.ts', 'nuxt.config.js', 'i18n.config.ts', 'i18n.config.js'],\n localePatterns: ['locales/*.json', 'lang/*.json', 'i18n/*.json', 'locales/*.yaml', 'locales/*.yml'],\n sourcePatterns: ['pages/**/*.vue', 'components/**/*.vue', 'layouts/**/*.vue'],\n migrationGuide: 'nuxt/llms-migration.txt',\n },\n 'react-i18next': {\n name: 'react-i18next',\n framework: 'React',\n configPatterns: ['i18n.ts', 'i18n.js', 'src/i18n.ts', 'src/i18n.js', 'src/i18n/index.ts', 'src/i18n/config.ts'],\n localePatterns: ['locales/*.json', 'src/locales/*.json', 'public/locales/**/*.json', 'translations/*.json', 'src/translations/*.json'],\n sourcePatterns: ['src/**/*.tsx', 'src/**/*.jsx', 'src/**/*.ts'],\n migrationGuide: 'react/llms-migration.txt',\n },\n 'next-intl': {\n name: 'next-intl',\n framework: 'Next.js',\n configPatterns: ['next.config.ts', 'next.config.js', 'next.config.mjs', 'i18n.ts', 'src/i18n.ts', 'i18n/request.ts', 'src/i18n/request.ts'],\n localePatterns: ['messages/*.json', 'locales/*.json', 'src/messages/*.json', 'src/locales/*.json'],\n sourcePatterns: ['app/**/*.tsx', 'src/app/**/*.tsx', 'pages/**/*.tsx', 'components/**/*.tsx'],\n migrationGuide: 'next-plugin/llms-migration.txt',\n },\n 'next-i18next': {\n name: 'next-i18next',\n framework: 'Next.js',\n configPatterns: ['next-i18next.config.js', 'next-i18next.config.mjs', 'next.config.ts', 'next.config.js'],\n localePatterns: ['public/locales/**/*.json'],\n sourcePatterns: ['pages/**/*.tsx', 'src/pages/**/*.tsx', 'components/**/*.tsx', 'src/components/**/*.tsx'],\n migrationGuide: 'next-plugin/llms-migration.txt',\n },\n 'lingui': {\n name: 'lingui',\n framework: 'React',\n configPatterns: ['lingui.config.ts', 'lingui.config.js', '.linguirc'],\n localePatterns: ['locales/*.po', 'src/locales/*.po', 'locales/*/messages.po', 'src/locales/*/messages.po'],\n sourcePatterns: ['src/**/*.tsx', 'src/**/*.jsx', 'src/**/*.ts'],\n migrationGuide: 'react/llms-migration.txt',\n },\n}\n\nconst SUPPORTED_NAMES = Object.keys(LIBRARY_INFO) as SupportedLibrary[]\n\nexport function resolveLibrary(from: string): SupportedLibrary | undefined {\n const normalized = from.toLowerCase().replace(/^@nuxtjs\\//, 'nuxt-').replace(/^@/, '')\n return SUPPORTED_NAMES.find((name) => name === normalized)\n}\n\nexport interface DetectedFiles {\n configFiles: Array<{ path: string; content: string }>\n localeFiles: Array<{ path: string; content: string }>\n sampleSources: Array<{ path: string; content: string }>\n packageJson: string | undefined\n}\n\nasync function detectFiles(info: LibraryInfo): Promise<DetectedFiles> {\n const result: DetectedFiles = {\n configFiles: [],\n localeFiles: [],\n sampleSources: [],\n packageJson: undefined,\n }\n\n // Read package.json\n const pkgPath = resolve('package.json')\n if (existsSync(pkgPath)) {\n result.packageJson = readFileSync(pkgPath, 'utf-8')\n }\n\n // Find config files\n for (const pattern of info.configPatterns) {\n const fullPath = resolve(pattern)\n if (existsSync(fullPath)) {\n result.configFiles.push({\n path: pattern,\n content: readFileSync(fullPath, 'utf-8'),\n })\n }\n }\n\n // Find locale files (limit to 10 to avoid huge prompts)\n const localeGlobs = await fg(info.localePatterns, { absolute: false })\n for (const file of localeGlobs.slice(0, 10)) {\n const fullPath = resolve(file)\n const content = readFileSync(fullPath, 'utf-8')\n // Truncate large files\n result.localeFiles.push({\n path: file,\n content: content.length > 5000 ? content.slice(0, 5000) + '\\n... (truncated)' : content,\n })\n }\n\n // Find sample source files (limit to 5 for prompt size)\n const sourceGlobs = await fg(info.sourcePatterns, { absolute: false })\n for (const file of sourceGlobs.slice(0, 5)) {\n const fullPath = resolve(file)\n const content = readFileSync(fullPath, 'utf-8')\n result.sampleSources.push({\n path: file,\n content: content.length > 3000 ? content.slice(0, 3000) + '\\n... (truncated)' : content,\n })\n }\n\n return result\n}\n\nfunction loadMigrationGuide(guidePath: string): string {\n const thisDir = typeof __dirname !== 'undefined'\n ? __dirname\n : dirname(fileURLToPath(import.meta.url))\n // Try to find the migration guide relative to the CLI package\n const candidates = [\n resolve('node_modules', '@fluenti', 'cli', '..', '..', guidePath),\n join(thisDir, '..', '..', '..', guidePath),\n join(thisDir, '..', '..', guidePath),\n ]\n\n for (const candidate of candidates) {\n if (existsSync(candidate)) {\n return readFileSync(candidate, 'utf-8')\n }\n }\n\n return ''\n}\n\nexport function buildMigratePrompt(\n library: LibraryInfo,\n detected: DetectedFiles,\n migrationGuide: string,\n): string {\n const sections: string[] = []\n\n sections.push(\n `You are a migration assistant helping convert a ${library.framework} project from \"${library.name}\" to Fluenti (@fluenti).`,\n '',\n 'Your task:',\n '1. Generate a `fluenti.config.ts` file based on the existing i18n configuration',\n '2. Convert each locale/translation file to Fluenti PO format',\n '3. List the code changes needed (file by file) to migrate source code from the old API to Fluenti API',\n '',\n )\n\n if (migrationGuide) {\n sections.push(\n '=== MIGRATION GUIDE ===',\n migrationGuide,\n '',\n )\n }\n\n if (detected.packageJson) {\n sections.push(\n '=== package.json ===',\n detected.packageJson,\n '',\n )\n }\n\n if (detected.configFiles.length > 0) {\n sections.push('=== EXISTING CONFIG FILES ===')\n for (const file of detected.configFiles) {\n sections.push(`--- ${file.path} ---`, file.content, '')\n }\n }\n\n if (detected.localeFiles.length > 0) {\n sections.push('=== EXISTING LOCALE FILES ===')\n for (const file of detected.localeFiles) {\n sections.push(`--- ${file.path} ---`, file.content, '')\n }\n }\n\n if (detected.sampleSources.length > 0) {\n sections.push('=== SAMPLE SOURCE FILES ===')\n for (const file of detected.sampleSources) {\n sections.push(`--- ${file.path} ---`, file.content, '')\n }\n }\n\n sections.push(\n '',\n '=== OUTPUT FORMAT ===',\n 'Respond with the following sections, each starting with the exact header shown:',\n '',\n '### FLUENTI_CONFIG',\n '```ts',\n '// The fluenti.config.ts content',\n '```',\n '',\n '### LOCALE_FILES',\n 'For each locale file, output:',\n '#### LOCALE: {locale_code}',\n '```po',\n '// The PO file content',\n '```',\n '',\n '### MIGRATION_STEPS',\n 'A numbered checklist of specific code changes needed, with before/after examples.',\n '',\n '### INSTALL_COMMANDS',\n '```bash',\n '// The install and uninstall commands',\n '```',\n )\n\n return sections.join('\\n')\n}\n\nasync function invokeAI(provider: AIProvider, prompt: string): Promise<string> {\n const maxBuffer = 10 * 1024 * 1024\n\n try {\n if (provider === 'claude') {\n const { stdout } = await execFileAsync('claude', ['-p', prompt], { maxBuffer })\n return stdout\n } else {\n const { stdout } = await execFileAsync('codex', ['-p', prompt, '--full-auto'], { maxBuffer })\n return stdout\n }\n } catch (error: unknown) {\n const err = error as Error & { code?: string }\n if (err.code === 'ENOENT' || err.code === 'EPERM' || err.code === 'EACCES') {\n throw new Error(\n `\"${provider}\" CLI not found or not executable. Please install it first:\\n` +\n (provider === 'claude'\n ? ' npm install -g @anthropic-ai/claude-code'\n : ' npm install -g @openai/codex'),\n )\n }\n throw error\n }\n}\n\ninterface MigrateResult {\n config: string | undefined\n localeFiles: Array<{ locale: string; content: string }>\n steps: string | undefined\n installCommands: string | undefined\n}\n\nexport function parseResponse(response: string): MigrateResult {\n const result: MigrateResult = {\n config: undefined,\n localeFiles: [],\n steps: undefined,\n installCommands: undefined,\n }\n\n // Extract fluenti.config.ts\n const configMatch = response.match(/### FLUENTI_CONFIG[\\s\\S]*?```(?:ts|typescript)?\\n([\\s\\S]*?)```/)\n if (configMatch) {\n result.config = configMatch[1]!.trim()\n }\n\n // Extract locale files\n const localeSection = response.match(/### LOCALE_FILES([\\s\\S]*?)(?=### MIGRATION_STEPS|### INSTALL_COMMANDS|$)/)\n if (localeSection) {\n const localeRegex = /#### LOCALE:\\s*(\\S+)\\s*\\n```(?:po)?\\n([\\s\\S]*?)```/g\n let match\n while ((match = localeRegex.exec(localeSection[1]!)) !== null) {\n result.localeFiles.push({\n locale: match[1]!,\n content: match[2]!.trim(),\n })\n }\n }\n\n // Extract migration steps\n const stepsMatch = response.match(/### MIGRATION_STEPS\\s*\\n([\\s\\S]*?)(?=### INSTALL_COMMANDS|$)/)\n if (stepsMatch) {\n result.steps = stepsMatch[1]!.trim()\n }\n\n // Extract install commands\n const installMatch = response.match(/### INSTALL_COMMANDS[\\s\\S]*?```(?:bash|sh)?\\n([\\s\\S]*?)```/)\n if (installMatch) {\n result.installCommands = installMatch[1]!.trim()\n }\n\n return result\n}\n\nexport interface MigrateOptions {\n from: string\n provider: AIProvider\n write: boolean\n}\n\nexport async function runMigrate(options: MigrateOptions): Promise<void> {\n const { from, provider, write } = options\n\n const library = resolveLibrary(from)\n if (!library) {\n consola.error(`Unsupported library \"${from}\". Supported libraries:`)\n for (const name of SUPPORTED_NAMES) {\n consola.log(` - ${name}`)\n }\n return\n }\n\n const info = LIBRARY_INFO[library]\n consola.info(`Migrating from ${info.name} (${info.framework}) to Fluenti`)\n\n // Detect existing files\n consola.info('Scanning project for existing i18n files...')\n const detected = await detectFiles(info)\n\n if (detected.configFiles.length === 0 && detected.localeFiles.length === 0) {\n consola.warn(`No ${info.name} configuration or locale files found.`)\n consola.info('Make sure you are running this command from the project root directory.')\n return\n }\n\n consola.info(`Found: ${detected.configFiles.length} config file(s), ${detected.localeFiles.length} locale file(s), ${detected.sampleSources.length} source file(s)`)\n\n // Load migration guide\n const migrationGuide = loadMigrationGuide(info.migrationGuide)\n\n // Build prompt and invoke AI\n consola.info(`Generating migration plan with ${provider}...`)\n const prompt = buildMigratePrompt(info, detected, migrationGuide)\n const response = await invokeAI(provider, prompt)\n const result = parseResponse(response)\n\n // Display install commands\n if (result.installCommands) {\n consola.log('')\n consola.box({\n title: 'Install Commands',\n message: result.installCommands,\n })\n }\n\n // Write or display fluenti.config.ts\n if (result.config) {\n if (write) {\n const { writeFileSync } = await import('node:fs')\n const configPath = resolve('fluenti.config.ts')\n writeFileSync(configPath, result.config, 'utf-8')\n consola.success(`Written: ${configPath}`)\n } else {\n consola.log('')\n consola.box({\n title: 'fluenti.config.ts',\n message: result.config,\n })\n }\n }\n\n // Write or display locale files\n if (result.localeFiles.length > 0) {\n if (write) {\n const { writeFileSync, mkdirSync } = await import('node:fs')\n const catalogDir = './locales'\n mkdirSync(resolve(catalogDir), { recursive: true })\n for (const file of result.localeFiles) {\n const outPath = resolve(catalogDir, `${file.locale}.po`)\n writeFileSync(outPath, file.content, 'utf-8')\n consola.success(`Written: ${outPath}`)\n }\n } else {\n for (const file of result.localeFiles) {\n consola.log('')\n consola.box({\n title: `locales/${file.locale}.po`,\n message: file.content.length > 500\n ? file.content.slice(0, 500) + '\\n... (use --write to save full file)'\n : file.content,\n })\n }\n }\n }\n\n // Display migration steps\n if (result.steps) {\n consola.log('')\n consola.box({\n title: 'Migration Steps',\n message: result.steps,\n })\n }\n\n if (!write && (result.config || result.localeFiles.length > 0)) {\n consola.log('')\n consola.info('Run with --write to save generated files to disk:')\n consola.log(` fluenti migrate --from ${from} --write`)\n }\n}\n","import { readFileSync, writeFileSync, existsSync, appendFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport consola from 'consola'\n\nconst LOCALE_PATTERN = /^[a-zA-Z]{2,3}(-[a-zA-Z0-9]{1,8})*$/\n\nexport function validateLocale(locale: string): string {\n if (!LOCALE_PATTERN.test(locale)) {\n throw new Error(`Invalid locale format: \"${locale}\"`)\n }\n return locale\n}\n\nexport interface DetectedFramework {\n name: 'nextjs' | 'nuxt' | 'vue' | 'solid' | 'solidstart' | 'react' | 'unknown'\n pluginPackage: string | null\n}\n\nconst FRAMEWORK_DETECTION: Array<{\n dep: string\n name: DetectedFramework['name']\n pluginPackage: string\n}> = [\n { dep: 'next', name: 'nextjs', pluginPackage: '@fluenti/next' },\n { dep: 'nuxt', name: 'nuxt', pluginPackage: '@fluenti/vue' },\n { dep: '@solidjs/start', name: 'solidstart', pluginPackage: '@fluenti/solid' },\n { dep: 'vue', name: 'vue', pluginPackage: '@fluenti/vue' },\n { dep: 'solid-js', name: 'solid', pluginPackage: '@fluenti/solid' },\n { dep: 'react', name: 'react', pluginPackage: '@fluenti/react' },\n]\n\n/**\n * Detect the framework from package.json dependencies.\n */\nexport function detectFramework(deps: Record<string, string>): DetectedFramework {\n for (const entry of FRAMEWORK_DETECTION) {\n if (entry.dep in deps) {\n return { name: entry.name, pluginPackage: entry.pluginPackage }\n }\n }\n return { name: 'unknown', pluginPackage: null }\n}\n\n/**\n * Generate fluenti.config.ts content.\n */\nexport function generateFluentiConfig(opts: {\n sourceLocale: string\n locales: string[]\n format: 'po' | 'json'\n}): string {\n const localesList = opts.locales.map((l) => `'${l}'`).join(', ')\n return `import { defineConfig } from '@fluenti/cli'\n\nexport default defineConfig({\n sourceLocale: '${opts.sourceLocale}',\n locales: [${localesList}],\n catalogDir: './locales',\n format: '${opts.format}',\n include: ['./src/**/*.{vue,tsx,jsx,ts,js}'],\n compileOutDir: './src/locales/compiled',\n})\n`\n}\n\n/**\n * Interactive init flow.\n */\nexport async function runInit(options: { cwd: string }): Promise<void> {\n const pkgPath = resolve(options.cwd, 'package.json')\n if (!existsSync(pkgPath)) {\n consola.error('No package.json found in current directory.')\n return\n }\n\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')) as {\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n scripts?: Record<string, string>\n }\n const allDeps = { ...pkg.dependencies, ...pkg.devDependencies }\n const framework = detectFramework(allDeps)\n\n consola.info(`Detected framework: ${framework.name}`)\n if (framework.pluginPackage) {\n consola.info(`Recommended plugin: ${framework.pluginPackage}`)\n }\n\n // Check if config already exists\n const configPath = resolve(options.cwd, 'fluenti.config.ts')\n if (existsSync(configPath)) {\n consola.warn('fluenti.config.ts already exists. Skipping config generation.')\n return\n }\n\n // Prompt for configuration\n const sourceLocale = await consola.prompt('Source locale?', {\n type: 'text',\n default: 'en',\n placeholder: 'en',\n }) as unknown as string\n\n if (typeof sourceLocale === 'symbol') return // user cancelled\n\n const targetLocalesInput = await consola.prompt('Target locales (comma-separated)?', {\n type: 'text',\n default: 'ja,zh-CN',\n placeholder: 'ja,zh-CN',\n }) as unknown as string\n\n if (typeof targetLocalesInput === 'symbol') return\n\n const format = await consola.prompt('Catalog format?', {\n type: 'select',\n options: ['po', 'json'],\n initial: 'po',\n }) as unknown as string\n\n if (typeof format === 'symbol') return\n\n const targetLocales = targetLocalesInput.split(',').map((l) => l.trim()).filter(Boolean)\n\n // Validate locale formats\n validateLocale(sourceLocale)\n for (const locale of targetLocales) {\n validateLocale(locale)\n }\n\n const allLocales = [sourceLocale, ...targetLocales.filter((l) => l !== sourceLocale)]\n\n // Write config\n const configContent = generateFluentiConfig({\n sourceLocale,\n locales: allLocales,\n format: format as 'po' | 'json',\n })\n writeFileSync(configPath, configContent, 'utf-8')\n consola.success('Created fluenti.config.ts')\n\n // Append to .gitignore\n const gitignorePath = resolve(options.cwd, '.gitignore')\n const gitignoreEntry = 'src/locales/compiled/'\n if (existsSync(gitignorePath)) {\n const existing = readFileSync(gitignorePath, 'utf-8')\n if (!existing.includes(gitignoreEntry)) {\n appendFileSync(gitignorePath, `\\n# Fluenti compiled catalogs\\n${gitignoreEntry}\\n`)\n consola.success('Updated .gitignore')\n }\n } else {\n writeFileSync(gitignorePath, `# Fluenti compiled catalogs\\n${gitignoreEntry}\\n`)\n consola.success('Created .gitignore')\n }\n\n // Patch package.json scripts\n const existingScripts = pkg.scripts ?? {}\n const newScripts: Record<string, string> = {}\n let scriptsChanged = false\n if (!existingScripts['i18n:extract']) {\n newScripts['i18n:extract'] = 'fluenti extract'\n scriptsChanged = true\n }\n if (!existingScripts['i18n:compile']) {\n newScripts['i18n:compile'] = 'fluenti compile'\n scriptsChanged = true\n }\n if (scriptsChanged) {\n const updatedPkg = {\n ...pkg,\n scripts: { ...existingScripts, ...newScripts },\n }\n writeFileSync(pkgPath, JSON.stringify(updatedPkg, null, 2) + '\\n', 'utf-8')\n consola.success('Added i18n:extract and i18n:compile scripts to package.json')\n }\n\n // Print next steps\n consola.log('')\n consola.box({\n title: 'Next steps',\n message: [\n framework.pluginPackage\n ? `1. Install: pnpm add -D ${framework.pluginPackage} @fluenti/cli`\n : '1. Install: pnpm add -D @fluenti/cli',\n framework.name === 'nextjs'\n ? '2. Add withFluenti() to your next.config.ts'\n : framework.name !== 'unknown'\n ? '2. Add the Vite plugin to your vite.config.ts (e.g. fluentiVue() from @fluenti/vue/vite-plugin)'\n : '2. Configure your build tool with the framework Vite plugin or @fluenti/next',\n '3. Run: npx fluenti extract',\n '4. Translate your messages',\n '5. Run: npx fluenti compile',\n ].join('\\n'),\n })\n}\n","#!/usr/bin/env node\nimport { defineCommand, runMain } from 'citty'\nimport consola from 'consola'\nimport fg from 'fast-glob'\nimport { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs'\nimport { resolve, dirname, extname } from 'node:path'\nimport { extractFromTsx } from './tsx-extractor'\nimport { updateCatalog } from './catalog'\nimport type { CatalogData } from './catalog'\nimport { readJsonCatalog, writeJsonCatalog } from './json-format'\nimport { readPoCatalog, writePoCatalog } from './po-format'\nimport { compileCatalog, compileIndex, collectAllIds, compileTypeDeclaration } from './compile'\nimport { parallelCompile } from './parallel-compile'\nimport { formatStatsRow } from './stats-format'\nimport { lintCatalogs, formatDiagnostics } from './lint'\nimport { checkCoverage, formatCheckText, formatCheckGitHub, formatCheckJson } from './check'\nimport { ExtractCache } from './extract-cache'\nimport { CompileCache } from './compile-cache'\nimport { translateCatalog } from './translate'\nimport type { AIProvider } from './translate'\nimport { runMigrate } from './migrate'\nimport { runInit } from './init'\nimport { loadConfig } from './config-loader'\nimport { createHash } from 'node:crypto'\nimport type { ExtractedMessage } from '@fluenti/core/internal'\nimport { resolveLocaleCodes } from '@fluenti/core/internal'\nimport type { FluentiPlugin, PluginCompileContext, FluentiBuildConfig } from '@fluenti/core/internal'\n\nfunction deriveProjectId(cwd: string): string {\n return createHash('md5').update(cwd).digest('hex').slice(0, 8)\n}\n\nfunction readCatalog(filePath: string, format: 'json' | 'po'): CatalogData {\n if (!existsSync(filePath)) return {}\n const content = readFileSync(filePath, 'utf-8')\n return format === 'json' ? readJsonCatalog(content) : readPoCatalog(content)\n}\n\nfunction writeCatalog(filePath: string, catalog: CatalogData, format: 'json' | 'po'): void {\n mkdirSync(dirname(filePath), { recursive: true })\n const content = format === 'json' ? writeJsonCatalog(catalog) : writePoCatalog(catalog)\n writeFileSync(filePath, content, 'utf-8')\n}\n\nasync function extractFromFile(\n filePath: string,\n code: string,\n idGenerator?: (message: string, context?: string) => string,\n): Promise<ExtractedMessage[]> {\n const ext = extname(filePath)\n if (ext === '.vue') {\n try {\n const { extractFromVue } = await import('./vue-extractor')\n return extractFromVue(code, filePath, idGenerator)\n } catch {\n consola.warn(\n `Skipping ${filePath}: install @vue/compiler-sfc to extract from .vue files`,\n )\n return []\n }\n }\n return extractFromTsx(code, filePath, idGenerator)\n}\n\nconst extract = defineCommand({\n meta: { name: 'extract', description: 'Extract messages from source files' },\n args: {\n config: { type: 'string', description: 'Path to config file' },\n clean: { type: 'boolean', description: 'Remove obsolete entries instead of marking them', default: false },\n 'no-fuzzy': { type: 'boolean', description: 'Strip fuzzy flags from all entries', default: false },\n 'no-cache': { type: 'boolean', description: 'Disable incremental extraction cache', default: false },\n },\n async run({ args }) {\n const config = await loadConfig(args.config)\n const localeCodes = resolveLocaleCodes(config.locales)\n consola.info(`Extracting messages from ${config.include.join(', ')}`)\n\n const files = await fg(config.include, { ignore: config.exclude ?? [] })\n const allMessages: ExtractedMessage[] = []\n const useCache = !(args['no-cache'] ?? false)\n const cache = useCache ? new ExtractCache(config.catalogDir, deriveProjectId(process.cwd())) : null\n\n let cacheHits = 0\n\n for (const file of files) {\n if (cache) {\n const cached = cache.get(file)\n if (cached) {\n allMessages.push(...cached)\n cacheHits++\n continue\n }\n }\n\n const code = readFileSync(file, 'utf-8')\n const messages = await extractFromFile(file, code, config.idGenerator)\n allMessages.push(...messages)\n\n if (cache) {\n cache.set(file, messages)\n }\n }\n\n // Prune cache entries for deleted files\n if (cache) {\n cache.prune(new Set(files))\n cache.save()\n }\n\n if (cacheHits > 0) {\n consola.info(`Found ${allMessages.length} messages in ${files.length} files (${cacheHits} cached)`)\n } else {\n consola.info(`Found ${allMessages.length} messages in ${files.length} files`)\n }\n\n const ext = config.format === 'json' ? '.json' : '.po'\n const clean = args.clean ?? false\n const stripFuzzy = args['no-fuzzy'] ?? false\n\n for (const locale of localeCodes) {\n const catalogPath = resolve(config.catalogDir, `${locale}${ext}`)\n const existing = readCatalog(catalogPath, config.format)\n const { catalog, result } = updateCatalog(existing, allMessages, { stripFuzzy })\n\n const finalCatalog = clean\n ? Object.fromEntries(Object.entries(catalog).filter(([, entry]) => !entry.obsolete))\n : catalog\n\n writeCatalog(catalogPath, finalCatalog, config.format)\n\n const obsoleteLabel = clean\n ? `${result.obsolete} removed`\n : `${result.obsolete} obsolete`\n consola.success(\n `${locale}: ${result.added} added, ${result.unchanged} unchanged, ${obsoleteLabel}`,\n )\n }\n\n // Run plugin onAfterExtract hooks\n for (const plugin of config.plugins ?? []) {\n await plugin.onAfterExtract?.({\n messages: new Map(allMessages.map((m) => [m.id, m])),\n sourceLocale: config.sourceLocale,\n targetLocales: localeCodes.filter((l: string) => l !== config.sourceLocale),\n config,\n })\n }\n },\n})\n\n/** Build a Record<string, string> of raw message strings from a catalog for transformMessages hooks */\nfunction catalogToRawMessages(catalog: CatalogData): Record<string, string> {\n const result: Record<string, string> = {}\n for (const [id, entry] of Object.entries(catalog)) {\n if (entry.translation && entry.translation.length > 0) {\n result[id] = entry.translation\n } else if (entry.message) {\n result[id] = entry.message\n }\n }\n return result\n}\n\n/** Apply transformMessages hooks from all plugins and return an updated catalog */\nasync function applyTransformMessages(\n catalog: CatalogData,\n locale: string,\n plugins: readonly FluentiPlugin[],\n): Promise<CatalogData> {\n let rawMessages = catalogToRawMessages(catalog)\n\n for (const plugin of plugins) {\n if (plugin.transformMessages) {\n rawMessages = await plugin.transformMessages(rawMessages, locale)\n }\n }\n\n // Build a new catalog with transformed translations\n const updated: CatalogData = {}\n for (const [id, entry] of Object.entries(catalog)) {\n const transformed = rawMessages[id]\n updated[id] = transformed !== undefined\n ? { ...entry, translation: transformed }\n : { ...entry }\n }\n return updated\n}\n\n/** Build a PluginCompileContext for hook invocation */\nfunction buildCompileContext(\n locale: string,\n catalog: CatalogData,\n outDir: string,\n config: FluentiBuildConfig,\n): PluginCompileContext {\n const messages: Record<string, string> = {}\n for (const [id, entry] of Object.entries(catalog)) {\n if (entry.translation && entry.translation.length > 0) {\n messages[id] = entry.translation\n } else if (entry.message) {\n messages[id] = entry.message\n }\n }\n return { locale, messages, outDir, config }\n}\n\nconst compile = defineCommand({\n meta: { name: 'compile', description: 'Compile message catalogs to JS modules' },\n args: {\n config: { type: 'string', description: 'Path to config file' },\n 'skip-fuzzy': { type: 'boolean', description: 'Exclude fuzzy entries from compilation', default: false },\n 'no-cache': { type: 'boolean', description: 'Disable compilation cache', default: false },\n parallel: { type: 'boolean', description: 'Enable parallel compilation using worker threads', default: false },\n concurrency: { type: 'string', description: 'Max number of worker threads (default: auto)' },\n },\n async run({ args }) {\n const config = await loadConfig(args.config)\n const localeCodes = resolveLocaleCodes(config.locales)\n const ext = config.format === 'json' ? '.json' : '.po'\n\n mkdirSync(config.compileOutDir, { recursive: true })\n\n // Collect all catalogs and build union of IDs\n const allCatalogs: Record<string, CatalogData> = {}\n const catalogContents: Record<string, string> = {}\n for (const locale of localeCodes) {\n const catalogPath = resolve(config.catalogDir, `${locale}${ext}`)\n if (existsSync(catalogPath)) {\n const content = readFileSync(catalogPath, 'utf-8')\n catalogContents[locale] = content\n allCatalogs[locale] = config.format === 'json'\n ? readJsonCatalog(content)\n : readPoCatalog(content)\n } else {\n catalogContents[locale] = ''\n allCatalogs[locale] = {}\n }\n }\n\n const allIds = collectAllIds(allCatalogs)\n consola.info(`Compiling ${allIds.length} messages across ${localeCodes.length} locales`)\n\n const skipFuzzy = args['skip-fuzzy'] ?? false\n const useCache = !(args['no-cache'] ?? false)\n const cache = useCache ? new CompileCache(config.catalogDir, deriveProjectId(process.cwd())) : null\n const useParallel = args.parallel ?? false\n const concurrency = args.concurrency ? parseInt(args.concurrency, 10) : undefined\n\n if (concurrency !== undefined && (isNaN(concurrency) || concurrency < 1)) {\n consola.error('Invalid --concurrency. Must be a positive integer.')\n process.exitCode = 1\n return\n }\n\n let skipped = 0\n let needsRegenIndex = false\n\n // Filter locales that need compilation (cache check)\n const localesToCompile: string[] = []\n for (const locale of localeCodes) {\n if (cache && cache.isUpToDate(locale, catalogContents[locale]!)) {\n const outPath = resolve(config.compileOutDir, `${locale}.js`)\n if (existsSync(outPath)) {\n skipped++\n continue\n }\n }\n localesToCompile.push(locale)\n }\n\n if (localesToCompile.length > 0) {\n needsRegenIndex = true\n }\n\n if (useParallel && localesToCompile.length > 1) {\n // Parallel compilation via worker threads\n const plugins = config.plugins ?? []\n\n // Apply onBeforeCompile and transformMessages hooks before parallel dispatch\n const transformedCatalogs: Record<string, CatalogData> = {}\n for (const locale of localesToCompile) {\n for (const plugin of plugins) {\n await plugin.onBeforeCompile?.(\n buildCompileContext(locale, allCatalogs[locale]!, config.compileOutDir, config),\n )\n }\n transformedCatalogs[locale] = plugins.length > 0\n ? await applyTransformMessages(allCatalogs[locale]!, locale, plugins)\n : allCatalogs[locale]!\n }\n\n const tasks = localesToCompile.map((locale) => ({\n locale,\n catalog: transformedCatalogs[locale]!,\n allIds,\n sourceLocale: config.sourceLocale,\n options: { skipFuzzy },\n }))\n\n const results = await parallelCompile(tasks, concurrency)\n\n for (const result of results) {\n const outPath = resolve(config.compileOutDir, `${result.locale}.js`)\n writeFileSync(outPath, result.code, 'utf-8')\n\n if (cache) {\n cache.set(result.locale, catalogContents[result.locale]!)\n }\n\n if (result.stats.missing.length > 0) {\n consola.warn(\n `${result.locale}: ${result.stats.compiled} compiled, ${result.stats.missing.length} missing translations`,\n )\n for (const id of result.stats.missing) {\n consola.warn(` ⤷ ${id}`)\n }\n } else {\n consola.success(`Compiled ${result.locale}: ${result.stats.compiled} messages → ${outPath}`)\n }\n }\n\n // onAfterCompile hooks after parallel results\n for (const locale of localesToCompile) {\n for (const plugin of plugins) {\n await plugin.onAfterCompile?.(\n buildCompileContext(locale, transformedCatalogs[locale]!, config.compileOutDir, config),\n )\n }\n }\n } else {\n // Serial compilation\n const plugins = config.plugins ?? []\n\n for (const locale of localesToCompile) {\n const outPath = resolve(config.compileOutDir, `${locale}.js`)\n\n // onBeforeCompile hooks\n for (const plugin of plugins) {\n await plugin.onBeforeCompile?.(\n buildCompileContext(locale, allCatalogs[locale]!, config.compileOutDir, config),\n )\n }\n\n // transformMessages hooks\n const catalogForLocale = plugins.length > 0\n ? await applyTransformMessages(allCatalogs[locale]!, locale, plugins)\n : allCatalogs[locale]!\n\n const { code, stats } = compileCatalog(\n catalogForLocale,\n locale,\n allIds,\n config.sourceLocale,\n { skipFuzzy },\n )\n writeFileSync(outPath, code, 'utf-8')\n\n if (cache) {\n cache.set(locale, catalogContents[locale]!)\n }\n\n if (stats.missing.length > 0) {\n consola.warn(\n `${locale}: ${stats.compiled} compiled, ${stats.missing.length} missing translations`,\n )\n for (const id of stats.missing) {\n consola.warn(` ⤷ ${id}`)\n }\n } else {\n consola.success(`Compiled ${locale}: ${stats.compiled} messages → ${outPath}`)\n }\n\n // onAfterCompile hooks\n for (const plugin of plugins) {\n await plugin.onAfterCompile?.(\n buildCompileContext(locale, catalogForLocale, config.compileOutDir, config),\n )\n }\n }\n }\n\n if (skipped > 0) {\n consola.info(`${skipped} locale(s) unchanged — skipped`)\n }\n\n if (cache) {\n cache.save()\n }\n\n // Generate index.js and types when any locale changed or outputs don't exist\n const indexPath = resolve(config.compileOutDir, 'index.js')\n const typesPath = resolve(config.compileOutDir, 'messages.d.ts')\n\n if (needsRegenIndex || !existsSync(indexPath)) {\n const indexCode = compileIndex(localeCodes, config.compileOutDir)\n writeFileSync(indexPath, indexCode, 'utf-8')\n consola.success(`Generated index → ${indexPath}`)\n }\n\n if (needsRegenIndex || !existsSync(typesPath)) {\n const typesCode = compileTypeDeclaration(allIds, allCatalogs, config.sourceLocale)\n writeFileSync(typesPath, typesCode, 'utf-8')\n consola.success(`Generated types → ${typesPath}`)\n }\n },\n})\n\nconst stats = defineCommand({\n meta: { name: 'stats', description: 'Show translation progress' },\n args: {\n config: { type: 'string', description: 'Path to config file' },\n },\n async run({ args }) {\n const config = await loadConfig(args.config)\n const localeCodes = resolveLocaleCodes(config.locales)\n const ext = config.format === 'json' ? '.json' : '.po'\n\n const rows: Array<{ locale: string; total: number; translated: number; pct: string }> = []\n\n for (const locale of localeCodes) {\n const catalogPath = resolve(config.catalogDir, `${locale}${ext}`)\n const catalog = readCatalog(catalogPath, config.format)\n const entries = Object.values(catalog).filter((e) => !e.obsolete)\n const total = entries.length\n const translated = entries.filter((e) => e.translation && e.translation.length > 0).length\n const pct = total > 0 ? ((translated / total) * 100).toFixed(1) + '%' : '—'\n rows.push({ locale, total, translated, pct })\n }\n\n consola.log('')\n consola.log(' Locale │ Total │ Translated │ Progress')\n consola.log(' ────────┼───────┼────────────┼─────────────────────────────')\n for (const row of rows) {\n consola.log(formatStatsRow(row.locale, row.total, row.translated))\n }\n consola.log('')\n },\n})\n\nconst lint = defineCommand({\n meta: { name: 'lint', description: 'Check translation quality (missing, inconsistent placeholders, fuzzy)' },\n args: {\n config: { type: 'string', description: 'Path to config file' },\n strict: { type: 'boolean', description: 'Treat warnings as errors', default: false },\n locale: { type: 'string', description: 'Lint a specific locale only' },\n },\n async run({ args }) {\n const config = await loadConfig(args.config)\n const localeCodes = resolveLocaleCodes(config.locales)\n const ext = config.format === 'json' ? '.json' : '.po'\n\n const allCatalogs: Record<string, CatalogData> = {}\n for (const locale of localeCodes) {\n const catalogPath = resolve(config.catalogDir, `${locale}${ext}`)\n allCatalogs[locale] = readCatalog(catalogPath, config.format)\n }\n\n const targetLocales = args.locale\n ? [args.locale]\n : undefined\n\n consola.info(`Linting ${targetLocales ? targetLocales.join(', ') : 'all locales'} (source: ${config.sourceLocale})`)\n\n const lintOpts: Parameters<typeof lintCatalogs>[1] = {\n sourceLocale: config.sourceLocale,\n strict: args.strict ?? false,\n }\n if (targetLocales) lintOpts.locales = targetLocales\n const diagnostics = lintCatalogs(allCatalogs, lintOpts)\n\n consola.log('')\n consola.log(formatDiagnostics(diagnostics))\n consola.log('')\n\n const errors = diagnostics.filter((d) => d.severity === 'error')\n const warnings = diagnostics.filter((d) => d.severity === 'warning')\n\n if (errors.length > 0) {\n process.exitCode = 1\n } else if (args.strict && warnings.length > 0) {\n process.exitCode = 1\n }\n },\n})\n\nconst check = defineCommand({\n meta: { name: 'check', description: 'Check translation coverage for CI' },\n args: {\n config: { type: 'string', description: 'Path to config file' },\n ci: { type: 'boolean', description: 'Alias for --format github', default: false },\n 'min-coverage': { type: 'string', description: 'Minimum coverage percentage (0-100)', default: '100' },\n format: { type: 'string', description: 'Output format: text | json | github' },\n locale: { type: 'string', description: 'Check a specific locale only' },\n },\n async run({ args }) {\n const config = await loadConfig(args.config)\n const localeCodes = resolveLocaleCodes(config.locales)\n const ext = config.format === 'json' ? '.json' : '.po'\n\n const allCatalogs: Record<string, CatalogData> = {}\n for (const locale of localeCodes) {\n const catalogPath = resolve(config.catalogDir, `${locale}${ext}`)\n allCatalogs[locale] = readCatalog(catalogPath, config.format)\n }\n\n const minCoverage = parseFloat(args['min-coverage'] ?? '100')\n if (isNaN(minCoverage) || minCoverage < 0 || minCoverage > 100) {\n consola.error('Invalid --min-coverage. Must be a number between 0 and 100.')\n process.exitCode = 1\n return\n }\n\n const outputFormat = args.format ?? (args.ci ? 'github' : 'text')\n\n const checkOpts: Parameters<typeof checkCoverage>[1] = {\n sourceLocale: config.sourceLocale,\n minCoverage,\n format: outputFormat as 'text' | 'json' | 'github',\n }\n if (args.locale) checkOpts.locale = args.locale\n\n const output = checkCoverage(allCatalogs, checkOpts)\n\n switch (outputFormat) {\n case 'json':\n consola.log(formatCheckJson(output))\n break\n case 'github':\n consola.log(formatCheckGitHub(output, config.catalogDir, config.format))\n break\n default:\n consola.log('')\n consola.log(formatCheckText(output))\n consola.log('')\n break\n }\n\n if (!output.passed) {\n process.exitCode = 1\n }\n },\n})\n\nconst translate = defineCommand({\n meta: { name: 'translate', description: 'Translate messages using AI (Claude Code or Codex CLI)' },\n args: {\n config: { type: 'string', description: 'Path to config file' },\n provider: { type: 'string', description: 'AI provider: claude or codex', default: 'claude' },\n locale: { type: 'string', description: 'Translate a specific locale only' },\n 'batch-size': { type: 'string', description: 'Messages per batch', default: '50' },\n 'dry-run': { type: 'boolean', description: 'Preview translation results without writing files', default: false },\n context: { type: 'string', description: 'Project context description to improve translation quality' },\n },\n async run({ args }) {\n const config = await loadConfig(args.config)\n const localeCodes = resolveLocaleCodes(config.locales)\n const provider = args.provider as AIProvider\n\n if (provider !== 'claude' && provider !== 'codex') {\n consola.error(`Invalid provider \"${provider}\". Use \"claude\" or \"codex\".`)\n return\n }\n\n const batchSize = parseInt(args['batch-size'] ?? '50', 10)\n if (isNaN(batchSize) || batchSize < 1) {\n consola.error('Invalid batch-size. Must be a positive integer.')\n return\n }\n\n const targetLocales = args.locale\n ? [args.locale]\n : localeCodes.filter((l: string) => l !== config.sourceLocale)\n\n if (targetLocales.length === 0) {\n consola.warn('No target locales to translate.')\n return\n }\n\n consola.info(`Translating with ${provider} (batch size: ${batchSize})`)\n const ext = config.format === 'json' ? '.json' : '.po'\n\n for (const locale of targetLocales) {\n consola.info(`\\n[${locale}]`)\n const catalogPath = resolve(config.catalogDir, `${locale}${ext}`)\n const catalog = readCatalog(catalogPath, config.format)\n\n if (args['dry-run']) {\n const untranslated = Object.entries(catalog).filter(\n ([, entry]) => !entry.obsolete && (!entry.translation || entry.translation.length === 0),\n )\n if (untranslated.length > 0) {\n for (const [id, entry] of untranslated) {\n consola.log(` ${id}: ${entry.message ?? id}`)\n }\n consola.success(` ${locale}: ${untranslated.length} messages would be translated (dry-run)`)\n } else {\n consola.success(` ${locale}: already fully translated`)\n }\n continue\n }\n\n const { catalog: updated, translated } = await translateCatalog({\n provider,\n sourceLocale: config.sourceLocale,\n targetLocale: locale,\n catalog,\n batchSize,\n ...(args.context ? { context: args.context } : {}),\n })\n\n if (translated > 0) {\n writeCatalog(catalogPath, updated, config.format)\n consola.success(` ${locale}: ${translated} messages translated`)\n } else {\n consola.success(` ${locale}: already fully translated`)\n }\n }\n },\n})\n\nconst migrate = defineCommand({\n meta: { name: 'migrate', description: 'Migrate from another i18n library using AI' },\n args: {\n from: { type: 'string', description: 'Source library: vue-i18n, nuxt-i18n, react-i18next, next-intl, next-i18next, lingui', required: true },\n provider: { type: 'string', description: 'AI provider: claude or codex', default: 'claude' },\n write: { type: 'boolean', description: 'Write generated files to disk', default: false },\n },\n async run({ args }) {\n const provider = args.provider as AIProvider\n if (provider !== 'claude' && provider !== 'codex') {\n consola.error(`Invalid provider \"${provider}\". Use \"claude\" or \"codex\".`)\n return\n }\n\n await runMigrate({\n from: args.from!,\n provider,\n write: args.write ?? false,\n })\n },\n})\n\nconst init = defineCommand({\n meta: { name: 'init', description: 'Initialize Fluenti in your project' },\n args: {},\n async run() {\n await runInit({ cwd: process.cwd() })\n },\n})\n\nconst main = defineCommand({\n meta: {\n name: 'fluenti',\n version: '0.0.1',\n description: 'Compile-time i18n for modern frameworks',\n },\n subCommands: { init, extract, compile, stats, lint, check, translate, migrate },\n})\n\nrunMain(main)\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,IAAM,KAAa,KACb,KAAc;AAQpB,SAAgB,GAAkB,GAAa,IAAQ,IAAY;CAEjE,IAAM,IAAS,KAAK,MADJ,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,EAAI,CAAC,GACV,MAAO,EAAM;AAClD,QAAO,GAAW,OAAO,EAAO,GAAG,GAAY,OAAO,IAAQ,EAAO;;AAUvE,SAAgB,EAAgB,GAAqB;CACnD,IAAM,IAAQ,EAAI,QAAQ,EAAE,GAAG;AAG/B,QAFI,KAAO,KAAW,WAAW,EAAM,WACnC,KAAO,KAAW,WAAW,EAAM,WAChC,WAAW,EAAM;;AAM1B,SAAgB,GACd,GACA,GACA,GACQ;CACR,IAAM,IAAM,IAAQ,IAAK,IAAa,IAAS,MAAM,GAC/C,IAAa,IAAQ,IAAI,EAAgB,EAAI,GAAG,KAChD,IAAM,IAAQ,IAAI,GAAkB,EAAI,GAAG;AACjD,QAAO,KAAK,EAAO,OAAO,EAAE,CAAC,IAAI,OAAO,EAAM,CAAC,SAAS,EAAE,CAAC,KAAK,OAAO,EAAW,CAAC,SAAS,GAAG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MAAM;EACJ,MAAM;EACN,SAAS;EACT,aAAa;EACd;CACD,aAAa;EAAE,MAdJ,EAAc;GACzB,MAAM;IAAE,MAAM;IAAQ,aAAa;IAAsC;GACzE,MAAM,EAAE;GACR,MAAM,MAAM;AACV,UAAM,GAAQ,EAAE,KAAK,QAAQ,KAAK,EAAE,CAAC;;GAExC,CAAC;EAQqB;EAAS;EAAS;EAAO;EAAM;EAAO;EAAW;EAAS;CAChF,CAAC,CAEW"}
@@ -0,0 +1,8 @@
1
+ const e=require(`./extract-cache-CGSKwh76.cjs`);let t=require(`@fluenti/core/internal`);var n=e.c({CATALOG_VERSION:()=>1,collectAllIds:()=>y,compileCatalog:()=>g,compileIndex:()=>v,compileTypeDeclaration:()=>S,extractMessageVariables:()=>b}),r=/\{(\w+)\}/g,i=/\{(\w+)\}/;function a(e){return i.test(e)}function o(e){return e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`)}function s(e,t){return/^\d/.test(t)?`${e}['${t}']`:`${e}.${t}`}function c(e){return e.replace(/\\/g,`\\\\`).replace(/`/g,"\\`").replace(/\$\{/g,"\\${").replace(/\n/g,`\\n`).replace(/\r/g,`\\r`)}function l(e){r.lastIndex=0;let t=[],n=0,i;for(;(i=r.exec(e))!==null;)t.push(c(e.slice(n,i.index))),t.push(`\${${s(`v`,i[1])}}`),n=r.lastIndex;return t.push(c(e.slice(n))),t.join(``)}var u=/\{(\w+),\s*(plural|select|selectordinal)\s*,/;function d(e){return u.test(e)}function f(e,t){if(e.length===0)return`''`;let n=e.map(e=>p(e,t));return n.length===1?n[0]:n.join(` + `)}function p(e,t){switch(e.type){case`text`:return`'${o(e.value)}'`;case`variable`:return e.name===`#`?`String(__c)`:`String(${s(`v`,e.name)} ?? '{${e.name}}')`;case`plural`:return m(e,t);case`select`:return h(e,t);case`function`:return`String(${s(`v`,e.variable)} ?? '')`}}function m(e,t){let n=e.offset??0,r=s(`v`,e.variable),i=n?`(${r} - ${n})`:r,a=[];a.push(`((c) => { const __c = c; `);let c=Object.keys(e.options).filter(e=>e.startsWith(`=`));if(c.length>0)for(let n of c){let r=n.slice(1),i=f(e.options[n],t);a.push(`if (c === ${r}) return ${i}; `)}let l=Object.keys(e.options).filter(e=>!e.startsWith(`=`));if(l.length>1||l.length===1&&l[0]!==`other`){a.push(`const __cat = new Intl.PluralRules('${o(t)}').select(c); `);for(let n of l){if(n===`other`)continue;let r=f(e.options[n],t);a.push(`if (__cat === '${n}') return ${r}; `)}}let u=e.options.other?f(e.options.other,t):`''`;return a.push(`return ${u}; `),a.push(`})(${i})`),a.join(``)}function h(e,t){let n=[];n.push(`((s) => { `);let r=Object.keys(e.options).filter(e=>e!==`other`);for(let i of r){let r=f(e.options[i],t);n.push(`if (s === '${o(i)}') return ${r}; `)}let i=e.options.other?f(e.options.other,t):`''`;return n.push(`return ${i}; `),n.push(`})(String(${s(`v`,e.variable)} ?? ''))`),n.join(``)}function g(e,n,r,i,s){let c=[];c.push(`// @fluenti/compiled v1`),c.push(`// @ts-nocheck`);let u=[],p=0,m=[],h=new Map;for(let g of r){let r=(0,t.hashMessage)(g),v=h.get(r);if(v!==void 0&&v!==g)throw Error(`Hash collision detected: messages "${v}" and "${g}" produce the same hash "${r}"`);h.set(r,g);let y=`_${r}`,b=e[g],x=_(b,g,n,i,s?.skipFuzzy);if(x===void 0)c.push(`export const ${y} = undefined`),m.push(g);else if(d(x)){let e;try{e=(0,t.parse)(x)}catch(e){console.warn(`[fluenti] Skipping malformed ICU translation for "${g}" (${n}): ${e.message}`),c.push(`export const ${y} = undefined`),m.push(g),u.push({id:g,exportName:y});continue}let r=f(e,n);c.push(`export const ${y} = (v) => ${r}`),p++}else if(a(x)){let e=l(x);c.push(`export const ${y} = (v) => \`${e}\``),p++}else c.push(`export const ${y} = '${o(x)}'`),p++;u.push({id:g,exportName:y})}if(u.length===0)return{code:`// @fluenti/compiled v1
2
+ // empty catalog
3
+ export default {}
4
+ `,stats:{compiled:0,missing:[]}};c.push(``),c.push(`export default {`);for(let{id:e,exportName:t}of u)c.push(` '${o(e)}': ${t},`);return c.push(`}`),c.push(``),{code:c.join(`
5
+ `),stats:{compiled:p,missing:m}}}function _(e,t,n,r,i){let a=r??n;if(e&&!(i&&e.fuzzy)){if(e.translation!==void 0&&e.translation.length>0)return e.translation;if(n===a)return e.message??t}}function v(e,t){let n=[];n.push(`export const locales = ${JSON.stringify(e)}`),n.push(``),n.push(`export const loaders = {`);for(let t of e)n.push(` '${o(t)}': () => import('./${o(t)}.js'),`);return n.push(`}`),n.push(``),n.join(`
6
+ `)}function y(e){let t=new Set;for(let n of Object.values(e))for(let[e,r]of Object.entries(n))r.obsolete||t.add(e);return[...t].sort()}function b(e){let n=(0,t.parse)(e),r=new Map;return x(n,r),[...r.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({name:e,type:t}))}function x(e,t){for(let n of e)switch(n.type){case`variable`:n.name!==`#`&&!t.has(n.name)&&t.set(n.name,`string | number`);break;case`plural`:{let e=n;t.set(e.variable,`number`);for(let n of Object.values(e.options))x(n,t);break}case`select`:{let e=n,r=Object.keys(e.options).filter(e=>e!==`other`),i=`other`in e.options,a=r.map(e=>`'${e}'`).join(` | `),o=i?r.length>0?`${a} | string`:`string`:r.length>0?a:`string`;t.set(e.variable,o);for(let n of Object.values(e.options))x(n,t);break}case`function`:t.has(n.variable)||t.set(n.variable,`string | number`);break;case`text`:break}}function S(e,t,n){let r=[];if(r.push(`// Auto-generated by @fluenti/cli — do not edit`),r.push(``),r.push(`export type { LocalizedString } from '@fluenti/core'`),r.push(``),e.length===0)r.push(`export type MessageId = never`);else{r.push(`export type MessageId =`);for(let t of e)r.push(` | '${o(t)}'`)}r.push(``),r.push(`export interface MessageValues {`);for(let i of e){let e=b(t[n]?.[i]?.message??i),a=o(i);if(e.length===0)r.push(` '${a}': Record<string, never>`);else{let t=e.map(e=>`${e.name}: ${e.type}`).join(`; `);r.push(` '${a}': { ${t} }`)}}r.push(`}`),r.push(``);let i=Object.keys(t).map(e=>`'${o(e)}'`).join(` | `);return r.push(`// Auto-wiring: narrows t() and setLocale() to compiled types`),r.push(`declare module '@fluenti/core' {`),r.push(` interface FluentiTypeConfig {`),r.push(` locale: ${i||`string`}`),r.push(` messageIds: MessageId`),r.push(` messageValues: MessageValues`),r.push(` }`),r.push(`}`),r.push(``),r.join(`
7
+ `)}Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return y}});
8
+ //# sourceMappingURL=compile-CX1b_JVQ.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile-CX1b_JVQ.cjs","names":[],"sources":["../src/compile.ts"],"sourcesContent":["import type { CatalogData } from './catalog'\nimport { hashMessage, parse } from '@fluenti/core/internal'\nimport type { ASTNode, PluralNode, SelectNode, VariableNode, FunctionNode } from '@fluenti/core/internal'\n\nconst ICU_VAR_REGEX = /\\{(\\w+)\\}/g\nconst ICU_VAR_TEST = /\\{(\\w+)\\}/\n\nfunction hasVariables(message: string): boolean {\n return ICU_VAR_TEST.test(message)\n}\n\n\nfunction escapeStringLiteral(str: string): string {\n return str\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n}\n\n/** Generate safe JS property access: `v.name` for valid identifiers, `v['name']` for others */\nfunction propAccess(obj: string, name: string): string {\n // Names starting with a digit are not valid JS identifiers; use quoted bracket notation.\n // e.g. {0} → v['0'], {1st} → v['1st']. Pure integers (v['0']) work the same as v[0].\n return /^\\d/.test(name) ? `${obj}['${name}']` : `${obj}.${name}`\n}\n\nfunction escapeTemplateLiteral(str: string): string {\n return str\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/`/g, '\\\\`')\n .replace(/\\$\\{/g, '\\\\${')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n}\n\n/**\n * Convert a simple ICU message (only `{varName}` placeholders) into a JS template literal body.\n * Static segments are escaped independently so literal `${`, backticks, etc. are preserved\n * without interfering with the ICU variable interpolations that are inserted afterwards.\n */\nfunction messageToTemplateString(message: string): string {\n ICU_VAR_REGEX.lastIndex = 0\n const parts: string[] = []\n let lastIndex = 0\n let m: RegExpExecArray | null\n while ((m = ICU_VAR_REGEX.exec(message)) !== null) {\n parts.push(escapeTemplateLiteral(message.slice(lastIndex, m.index)))\n parts.push(`\\${${propAccess('v', m[1]!)}}`)\n lastIndex = ICU_VAR_REGEX.lastIndex\n }\n parts.push(escapeTemplateLiteral(message.slice(lastIndex)))\n return parts.join('')\n}\n\n\n// ─── ICU → JS code generation for split mode ───────────────────────────────\n\nconst ICU_PLURAL_SELECT_REGEX = /\\{(\\w+),\\s*(plural|select|selectordinal)\\s*,/\n\n/** Check if message contains ICU plural/select syntax */\nfunction hasIcuPluralOrSelect(message: string): boolean {\n return ICU_PLURAL_SELECT_REGEX.test(message)\n}\n\n/**\n * Compile an ICU AST node array into a JS expression string.\n * Used for generating static code (not runtime evaluation).\n */\nfunction astToJsExpression(nodes: ASTNode[], locale: string): string {\n if (nodes.length === 0) return \"''\"\n\n const parts = nodes.map((node) => astNodeToJs(node, locale))\n\n if (parts.length === 1) return parts[0]!\n return parts.join(' + ')\n}\n\nfunction astNodeToJs(node: ASTNode, locale: string): string {\n switch (node.type) {\n case 'text':\n return `'${escapeStringLiteral(node.value)}'`\n\n case 'variable':\n if (node.name === '#') return 'String(__c)'\n return `String(${propAccess('v', node.name)} ?? '{${node.name}}')`\n\n case 'plural':\n return pluralToJs(node as PluralNode, locale)\n\n case 'select':\n return selectToJs(node as SelectNode, locale)\n\n case 'function':\n return `String(${propAccess('v', node.variable)} ?? '')`\n }\n}\n\nfunction pluralToJs(node: PluralNode, locale: string): string {\n const offset = node.offset ?? 0\n const access = propAccess('v', node.variable)\n const countExpr = offset ? `(${access} - ${offset})` : access\n\n const lines: string[] = []\n lines.push(`((c) => { const __c = c; `)\n\n // Exact matches first\n const exactKeys = Object.keys(node.options).filter((k) => k.startsWith('='))\n if (exactKeys.length > 0) {\n for (const key of exactKeys) {\n const num = key.slice(1)\n const body = astToJsExpression(node.options[key]!, locale)\n lines.push(`if (c === ${num}) return ${body}; `)\n }\n }\n\n // CLDR categories via Intl.PluralRules\n const cldrKeys = Object.keys(node.options).filter((k) => !k.startsWith('='))\n if (cldrKeys.length > 1 || (cldrKeys.length === 1 && cldrKeys[0] !== 'other')) {\n lines.push(`const __cat = new Intl.PluralRules('${escapeStringLiteral(locale)}').select(c); `)\n for (const key of cldrKeys) {\n if (key === 'other') continue\n const body = astToJsExpression(node.options[key]!, locale)\n lines.push(`if (__cat === '${key}') return ${body}; `)\n }\n }\n\n // Fallback to 'other'\n const otherBody = node.options['other']\n ? astToJsExpression(node.options['other'], locale)\n : \"''\"\n lines.push(`return ${otherBody}; `)\n lines.push(`})(${countExpr})`)\n\n return lines.join('')\n}\n\nfunction selectToJs(node: SelectNode, locale: string): string {\n const lines: string[] = []\n lines.push(`((s) => { `)\n\n const keys = Object.keys(node.options).filter((k) => k !== 'other')\n for (const key of keys) {\n const body = astToJsExpression(node.options[key]!, locale)\n lines.push(`if (s === '${escapeStringLiteral(key)}') return ${body}; `)\n }\n\n const otherBody = node.options['other']\n ? astToJsExpression(node.options['other'], locale)\n : \"''\"\n lines.push(`return ${otherBody}; `)\n lines.push(`})(String(${propAccess('v', node.variable)} ?? ''))`)\n\n return lines.join('')\n}\n\n/**\n * Compile a catalog to ES module with tree-shakeable named exports.\n * Each message becomes a `/* @__PURE__ *​/` annotated named export.\n * A default export maps message IDs to their compiled values for runtime lookup.\n */\n/** Catalog format version. Bump when the compiled output format changes. */\nexport const CATALOG_VERSION = 1\n\nexport interface CompileStats {\n compiled: number\n missing: string[]\n}\n\nexport interface CompileOptions {\n skipFuzzy?: boolean\n}\n\nexport function compileCatalog(\n catalog: CatalogData,\n locale: string,\n allIds: string[],\n sourceLocale?: string,\n options?: CompileOptions,\n): { code: string; stats: CompileStats } {\n const lines: string[] = []\n lines.push(`// @fluenti/compiled v${CATALOG_VERSION}`)\n lines.push(`// @ts-nocheck`)\n const exportNames: Array<{ id: string; exportName: string }> = []\n let compiled = 0\n const missing: string[] = []\n\n const hashToId = new Map<string, string>()\n\n for (const id of allIds) {\n const hash = hashMessage(id)\n\n const existingId = hashToId.get(hash)\n if (existingId !== undefined && existingId !== id) {\n throw new Error(\n `Hash collision detected: messages \"${existingId}\" and \"${id}\" produce the same hash \"${hash}\"`,\n )\n }\n hashToId.set(hash, id)\n\n const exportName = `_${hash}`\n const entry = catalog[id]\n const translated = resolveCompiledMessage(entry, id, locale, sourceLocale, options?.skipFuzzy)\n\n if (translated === undefined) {\n lines.push(`export const ${exportName} = undefined`)\n missing.push(id)\n } else if (hasIcuPluralOrSelect(translated)) {\n // Parse ICU and compile to JS\n let ast\n try {\n ast = parse(translated)\n } catch (err) {\n console.warn(\n `[fluenti] Skipping malformed ICU translation for \"${id}\" (${locale}): ${(err as Error).message}`,\n )\n lines.push(`export const ${exportName} = undefined`)\n missing.push(id)\n exportNames.push({ id, exportName })\n continue\n }\n const jsExpr = astToJsExpression(ast, locale)\n lines.push(`export const ${exportName} = (v) => ${jsExpr}`)\n compiled++\n } else if (hasVariables(translated)) {\n const templateStr = messageToTemplateString(translated)\n lines.push(`export const ${exportName} = (v) => \\`${templateStr}\\``)\n compiled++\n } else {\n lines.push(`export const ${exportName} = '${escapeStringLiteral(translated)}'`)\n compiled++\n }\n\n exportNames.push({ id, exportName })\n }\n\n if (exportNames.length === 0) {\n return {\n code: `// @fluenti/compiled v${CATALOG_VERSION}\\n// empty catalog\\nexport default {}\\n`,\n stats: { compiled: 0, missing: [] },\n }\n }\n\n // Default export maps message IDs → compiled values for runtime lookup\n lines.push('')\n lines.push('export default {')\n for (const { id, exportName } of exportNames) {\n lines.push(` '${escapeStringLiteral(id)}': ${exportName},`)\n }\n lines.push('}')\n lines.push('')\n\n return { code: lines.join('\\n'), stats: { compiled, missing } }\n}\n\nfunction resolveCompiledMessage(\n entry: CatalogData[string] | undefined,\n id: string,\n locale: string,\n sourceLocale: string | undefined,\n skipFuzzy?: boolean,\n): string | undefined {\n const effectiveSourceLocale = sourceLocale ?? locale\n\n if (!entry) {\n return undefined\n }\n\n if (skipFuzzy && entry.fuzzy) {\n return undefined\n }\n\n if (entry.translation !== undefined && entry.translation.length > 0) {\n return entry.translation\n }\n\n if (locale === effectiveSourceLocale) {\n return entry.message ?? id\n }\n\n return undefined\n}\n\n/**\n * Generate the index module that exports locale list and lazy loaders.\n */\nexport function compileIndex(locales: string[], _catalogDir: string): string {\n const lines: string[] = []\n lines.push(`export const locales = ${JSON.stringify(locales)}`)\n lines.push('')\n lines.push('export const loaders = {')\n for (const locale of locales) {\n lines.push(` '${escapeStringLiteral(locale)}': () => import('./${escapeStringLiteral(locale)}.js'),`)\n }\n lines.push('}')\n lines.push('')\n return lines.join('\\n')\n}\n\n/**\n * Collect the union of all message IDs across all locale catalogs.\n * Ensures every locale file exports the same names.\n */\nexport function collectAllIds(catalogs: Record<string, CatalogData>): string[] {\n const idSet = new Set<string>()\n for (const catalog of Object.values(catalogs)) {\n for (const [id, entry] of Object.entries(catalog)) {\n if (!entry.obsolete) {\n idSet.add(id)\n }\n }\n }\n return [...idSet].sort()\n}\n\n// ─── Type-safe message ID generation ─────────────────────────────────────────\n\nexport interface MessageVariable {\n name: string\n type: string\n}\n\n/**\n * Extract variable names and their TypeScript types from an ICU message string.\n */\nexport function extractMessageVariables(message: string): MessageVariable[] {\n const ast = parse(message)\n const vars = new Map<string, string>()\n collectVariablesFromNodes(ast, vars)\n return [...vars.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([name, type]) => ({ name, type }))\n}\n\nfunction collectVariablesFromNodes(nodes: ASTNode[], vars: Map<string, string>): void {\n for (const node of nodes) {\n switch (node.type) {\n case 'variable':\n if (node.name !== '#' && !vars.has(node.name)) {\n vars.set((node as VariableNode).name, 'string | number')\n }\n break\n case 'plural': {\n const pn = node as PluralNode\n // Plural variable is always a number\n vars.set(pn.variable, 'number')\n // Recurse into plural option bodies\n for (const optionNodes of Object.values(pn.options)) {\n collectVariablesFromNodes(optionNodes, vars)\n }\n break\n }\n case 'select': {\n const sn = node as SelectNode\n const keys = Object.keys(sn.options).filter((k) => k !== 'other')\n const hasOther = 'other' in sn.options\n const literalTypes = keys.map((k) => `'${k}'`).join(' | ')\n const selectType = hasOther\n ? (keys.length > 0 ? `${literalTypes} | string` : 'string')\n : (keys.length > 0 ? literalTypes : 'string')\n vars.set(sn.variable, selectType)\n // Recurse into select option bodies\n for (const optionNodes of Object.values(sn.options)) {\n collectVariablesFromNodes(optionNodes, vars)\n }\n break\n }\n case 'function':\n if (!vars.has((node as FunctionNode).variable)) {\n vars.set((node as FunctionNode).variable, 'string | number')\n }\n break\n case 'text':\n break\n }\n }\n}\n\n/**\n * Generate a TypeScript declaration file with MessageId union and MessageValues interface.\n */\nexport function compileTypeDeclaration(\n allIds: string[],\n catalogs: Record<string, CatalogData>,\n sourceLocale: string,\n): string {\n const lines: string[] = []\n lines.push('// Auto-generated by @fluenti/cli — do not edit')\n lines.push('')\n lines.push('export type { LocalizedString } from \\'@fluenti/core\\'')\n lines.push('')\n\n // MessageId union\n if (allIds.length === 0) {\n lines.push('export type MessageId = never')\n } else {\n lines.push('export type MessageId =')\n for (const id of allIds) {\n lines.push(` | '${escapeStringLiteral(id)}'`)\n }\n }\n\n lines.push('')\n\n // MessageValues interface\n lines.push('export interface MessageValues {')\n for (const id of allIds) {\n // Use source locale catalog to get the message for variable extraction\n const sourceCatalog = catalogs[sourceLocale]\n const entry = sourceCatalog?.[id]\n const message = entry?.message ?? id\n const vars = extractMessageVariables(message)\n\n const escapedId = escapeStringLiteral(id)\n if (vars.length === 0) {\n lines.push(` '${escapedId}': Record<string, never>`)\n } else {\n const fields = vars.map((v) => `${v.name}: ${v.type}`).join('; ')\n lines.push(` '${escapedId}': { ${fields} }`)\n }\n }\n lines.push('}')\n lines.push('')\n\n // Module augmentation: auto-wire MessageId and MessageValues into CompileTimeT\n // Locale union from catalog keys\n const localeKeys = Object.keys(catalogs).map((l) => `'${escapeStringLiteral(l)}'`).join(' | ')\n\n lines.push('// Auto-wiring: narrows t() and setLocale() to compiled types')\n lines.push(\"declare module '@fluenti/core' {\")\n lines.push(' interface FluentiTypeConfig {')\n lines.push(` locale: ${localeKeys || 'string'}`)\n lines.push(' messageIds: MessageId')\n lines.push(' messageValues: MessageValues')\n lines.push(' }')\n lines.push('}')\n lines.push('')\n\n return lines.join('\\n')\n}\n"],"mappings":"kPAIM,EAAgB,aAChB,EAAe,YAErB,SAAS,EAAa,EAA0B,CAC9C,OAAO,EAAa,KAAK,EAAQ,CAInC,SAAS,EAAoB,EAAqB,CAChD,OAAO,EACJ,QAAQ,MAAO,OAAO,CACtB,QAAQ,KAAM,MAAM,CACpB,QAAQ,MAAO,MAAM,CACrB,QAAQ,MAAO,MAAM,CAI1B,SAAS,EAAW,EAAa,EAAsB,CAGrD,MAAO,MAAM,KAAK,EAAK,CAAG,GAAG,EAAI,IAAI,EAAK,IAAM,GAAG,EAAI,GAAG,IAG5D,SAAS,EAAsB,EAAqB,CAClD,OAAO,EACJ,QAAQ,MAAO,OAAO,CACtB,QAAQ,KAAM,MAAM,CACpB,QAAQ,QAAS,OAAO,CACxB,QAAQ,MAAO,MAAM,CACrB,QAAQ,MAAO,MAAM,CAQ1B,SAAS,EAAwB,EAAyB,CACxD,EAAc,UAAY,EAC1B,IAAM,EAAkB,EAAE,CACtB,EAAY,EACZ,EACJ,MAAQ,EAAI,EAAc,KAAK,EAAQ,IAAM,MAC3C,EAAM,KAAK,EAAsB,EAAQ,MAAM,EAAW,EAAE,MAAM,CAAC,CAAC,CACpE,EAAM,KA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