@fluenti/cli 0.1.2 → 0.1.3

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 (40) hide show
  1. package/dist/catalog.d.ts +6 -2
  2. package/dist/catalog.d.ts.map +1 -1
  3. package/dist/cli.cjs +18 -6
  4. package/dist/cli.cjs.map +1 -1
  5. package/dist/cli.js +411 -236
  6. package/dist/cli.js.map +1 -1
  7. package/dist/compile-BJdEF9QX.js +357 -0
  8. package/dist/compile-BJdEF9QX.js.map +1 -0
  9. package/dist/compile-d4Q8bND5.cjs +16 -0
  10. package/dist/compile-d4Q8bND5.cjs.map +1 -0
  11. package/dist/compile.d.ts +16 -1
  12. package/dist/compile.d.ts.map +1 -1
  13. package/dist/index.cjs +1 -1
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.js +4 -2
  16. package/dist/index.js.map +1 -1
  17. package/dist/init.d.ts +24 -0
  18. package/dist/init.d.ts.map +1 -0
  19. package/dist/json-format.d.ts.map +1 -1
  20. package/dist/migrate.d.ts +36 -0
  21. package/dist/migrate.d.ts.map +1 -1
  22. package/dist/po-format.d.ts.map +1 -1
  23. package/dist/stats-format.d.ts +20 -0
  24. package/dist/stats-format.d.ts.map +1 -0
  25. package/dist/translate.d.ts +4 -0
  26. package/dist/translate.d.ts.map +1 -1
  27. package/dist/tsx-extractor-DZrY1LMS.js +268 -0
  28. package/dist/tsx-extractor-DZrY1LMS.js.map +1 -0
  29. package/dist/tsx-extractor-LEAVCuX9.cjs +2 -0
  30. package/dist/tsx-extractor-LEAVCuX9.cjs.map +1 -0
  31. package/dist/tsx-extractor.d.ts.map +1 -1
  32. package/dist/vue-extractor-BlHc3vzt.cjs +3 -0
  33. package/dist/vue-extractor-BlHc3vzt.cjs.map +1 -0
  34. package/dist/vue-extractor-iUl6SUkv.js +210 -0
  35. package/dist/vue-extractor-iUl6SUkv.js.map +1 -0
  36. package/package.json +2 -2
  37. package/dist/compile-DK1UYkah.cjs +0 -13
  38. package/dist/compile-DK1UYkah.cjs.map +0 -1
  39. package/dist/compile-DuHUSzlx.js +0 -747
  40. package/dist/compile-DuHUSzlx.js.map +0 -1
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/translate.ts","../src/migrate.ts","../src/cli.ts"],"sourcesContent":["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\nfunction buildPrompt(\n sourceLocale: string,\n targetLocale: string,\n messages: Record<string, 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 `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\nfunction 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 const parsed = JSON.parse(match[0])\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\nfunction 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\nfunction 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}\n\nexport async function translateCatalog(options: TranslateOptions): Promise<{\n catalog: CatalogData\n translated: number\n}> {\n const { provider, sourceLocale, targetLocale, catalog, batchSize } = options\n\n const untranslated = getUntranslatedEntries(catalog)\n const count = Object.keys(untranslated).length\n\n if (count === 0) {\n return { catalog, translated: 0 }\n }\n\n consola.info(` ${count} untranslated messages, translating with ${provider}...`)\n\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)\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 catalog[key] = {\n ...catalog[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, translated: totalTranslated }\n}\n","import { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport { readFileSync, existsSync } from 'node:fs'\nimport { resolve, join } from 'node:path'\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\nfunction resolveLibrary(from: string): SupportedLibrary | undefined {\n const normalized = from.toLowerCase().replace(/^@nuxtjs\\//, 'nuxt-').replace(/^@/, '')\n return SUPPORTED_NAMES.find((name) => name === normalized)\n}\n\ninterface 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 // Try to find the migration guide relative to the CLI package\n const candidates = [\n resolve('node_modules', '@fluenti', 'cli', '..', '..', guidePath),\n join(__dirname, '..', '..', '..', guidePath),\n join(__dirname, '..', '..', 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\nfunction 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') {\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\ninterface MigrateResult {\n config: string | undefined\n localeFiles: Array<{ locale: string; content: string }>\n steps: string | undefined\n installCommands: string | undefined\n}\n\nfunction 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","#!/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 { extractFromVue } from './vue-extractor'\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 } from './compile'\nimport { translateCatalog } from './translate'\nimport type { AIProvider } from './translate'\nimport { runMigrate } from './migrate'\nimport type { ExtractedMessage, FluentiConfig } from '@fluenti/core'\n\nconst defaultConfig: FluentiConfig = {\n sourceLocale: 'en',\n locales: ['en'],\n catalogDir: './locales',\n format: 'po',\n include: ['./src/**/*.{vue,tsx,jsx,ts,js}'],\n compileOutDir: './locales/compiled',\n}\n\nasync function loadConfig(configPath?: string): Promise<FluentiConfig> {\n const paths = configPath\n ? [resolve(configPath)]\n : [\n resolve('fluenti.config.ts'),\n resolve('fluenti.config.js'),\n resolve('fluenti.config.mjs'),\n ]\n\n for (const p of paths) {\n if (existsSync(p)) {\n try {\n const { createJiti } = await import('jiti')\n const jiti = createJiti(import.meta.url)\n const mod = await jiti.import(p) as { default?: Partial<FluentiConfig> }\n const userConfig = mod.default ?? mod as unknown as Partial<FluentiConfig>\n return { ...defaultConfig, ...userConfig }\n } catch {\n consola.warn(`Failed to load config from ${p}, using defaults`)\n }\n }\n }\n\n return defaultConfig\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\nfunction extractFromFile(filePath: string, code: string): ExtractedMessage[] {\n const ext = extname(filePath)\n if (ext === '.vue') return extractFromVue(code, filePath)\n return extractFromTsx(code, filePath)\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 },\n async run({ args }) {\n const config = await loadConfig(args.config)\n consola.info(`Extracting messages from ${config.include.join(', ')}`)\n\n const files = await fg(config.include)\n const allMessages: ExtractedMessage[] = []\n\n for (const file of files) {\n const code = readFileSync(file, 'utf-8')\n const messages = extractFromFile(file, code)\n allMessages.push(...messages)\n }\n\n consola.info(`Found ${allMessages.length} messages in ${files.length} files`)\n\n const ext = config.format === 'json' ? '.json' : '.po'\n const clean = args.clean ?? false\n\n for (const locale of config.locales) {\n const catalogPath = resolve(config.catalogDir, `${locale}${ext}`)\n const existing = readCatalog(catalogPath, config.format)\n const { catalog, result } = updateCatalog(existing, allMessages)\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})\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 },\n async run({ args }) {\n const config = await loadConfig(args.config)\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 for (const locale of config.locales) {\n const catalogPath = resolve(config.catalogDir, `${locale}${ext}`)\n allCatalogs[locale] = readCatalog(catalogPath, config.format)\n }\n\n const allIds = collectAllIds(allCatalogs)\n consola.info(`Compiling ${allIds.length} messages across ${config.locales.length} locales`)\n\n for (const locale of config.locales) {\n const { code, stats } = compileCatalog(\n allCatalogs[locale]!,\n locale,\n allIds,\n config.sourceLocale,\n )\n const outPath = resolve(config.compileOutDir, `${locale}.js`)\n writeFileSync(outPath, code, 'utf-8')\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\n // Generate index.js with locale list and lazy loaders\n const indexCode = compileIndex(config.locales, config.compileOutDir)\n const indexPath = resolve(config.compileOutDir, 'index.js')\n writeFileSync(indexPath, indexCode, 'utf-8')\n consola.success(`Generated index → ${indexPath}`)\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 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 config.locales) {\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(\n ` ${row.locale.padEnd(8)}│ ${String(row.total).padStart(5)} │ ${String(row.translated).padStart(10)} │ ${row.pct}`,\n )\n }\n consola.log('')\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 },\n async run({ args }) {\n const config = await loadConfig(args.config)\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 : config.locales.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 const { catalog: updated, translated } = await translateCatalog({\n provider,\n sourceLocale: config.sourceLocale,\n targetLocale: locale,\n catalog,\n batchSize,\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 main = defineCommand({\n meta: {\n name: 'fluenti',\n version: '0.0.1',\n description: 'Compile-time i18n for modern frameworks',\n },\n subCommands: { extract, compile, stats, translate, migrate },\n})\n\nrunMain(main)\n"],"mappings":";;;;;;;;;;AAKA,IAAM,IAAgB,EAAU,EAAS;AAIzC,SAAS,EACP,GACA,GACA,GACQ;CACR,IAAM,IAAO,KAAK,UAAU,GAAU,MAAM,EAAE;AAC9C,QAAO;EACL,6EAA6E,EAAa,QAAQ,EAAa;EAC/G;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,KAAK,KAAK;;AAGd,eAAe,EAAS,GAAsB,GAAiC;CAC7E,IAAM,IAAY,KAAK,OAAO;AAE9B,KAAI;AACF,MAAI,MAAa,UAAU;GACzB,IAAM,EAAE,cAAW,MAAM,EAAc,UAAU,CAAC,MAAM,EAAO,EAAE,EAAE,cAAW,CAAC;AAC/E,UAAO;SACF;GACL,IAAM,EAAE,cAAW,MAAM,EAAc,SAAS;IAAC;IAAM;IAAQ;IAAc,EAAE,EAAE,cAAW,CAAC;AAC7F,UAAO;;UAEF,GAAgB;AAUvB,QATY,EACJ,SAAS,WACL,MACR,IAAI,EAAS,gDACZ,MAAa,WACV,+CACA,kCACL,GAEG;;;AAIV,SAAS,EAAY,GAAsC;CAEzD,IAAM,IAAQ,EAAK,MAAM,cAAc;AACvC,KAAI,CAAC,EACH,OAAU,MAAM,sCAAsC;CAExD,IAAM,IAAS,KAAK,MAAM,EAAM,GAAG;AACnC,KAAI,OAAO,KAAW,aAAY,KAAmB,MAAM,QAAQ,EAAO,CACxE,OAAU,MAAM,yCAAyC;AAE3D,QAAO;;AAGT,SAAS,EAAuB,GAA8C;CAC5E,IAAM,IAAkC,EAAE;AAC1C,MAAK,IAAM,CAAC,GAAI,MAAU,OAAO,QAAQ,EAAQ,CAC3C,GAAM,aACN,CA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,aAAa;KAAgC,SAAS;KAAU;IAC5F,OAAO;KAAE,MAAM;KAAW,aAAa;KAAiC,SAAS;KAAO;IACzF;GACD,MAAM,IAAI,EAAE,WAAQ;IAClB,IAAM,IAAW,EAAK;AACtB,QAAI,MAAa,YAAY,MAAa,SAAS;AACjD,OAAQ,MAAM,qBAAqB,EAAS,6BAA6B;AACzE;;AAGF,UAAM,EAAW;KACf,MAAM,EAAK;KACX;KACA,OAAO,EAAK,SAAS;KACtB,CAAC;;GAEL,CAAC;EAQ4D;CAC7D,CAAC,CAEW"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/stats-format.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 { 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): 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 `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 const parsed = JSON.parse(match[0])\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}\n\nexport async function translateCatalog(options: TranslateOptions): Promise<{\n catalog: CatalogData\n translated: number\n}> {\n const { provider, sourceLocale, targetLocale, catalog, batchSize } = 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)\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 } from 'node:path'\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 // Try to find the migration guide relative to the CLI package\n const candidates = [\n resolve('node_modules', '@fluenti', 'cli', '..', '..', guidePath),\n join(__dirname, '..', '..', '..', guidePath),\n join(__dirname, '..', '..', 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') {\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\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/vite-plugin' },\n { dep: 'vue', name: 'vue', pluginPackage: '@fluenti/vite-plugin' },\n { dep: 'solid-js', name: 'solid', pluginPackage: '@fluenti/vite-plugin' },\n { dep: 'react', name: 'react', pluginPackage: '@fluenti/vite-plugin' },\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 fluentiPlugin() to your vite.config.ts'\n : '2. Configure your build tool to use @fluenti/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 { formatStatsRow } from './stats-format'\nimport { translateCatalog } from './translate'\nimport type { AIProvider } from './translate'\nimport { runMigrate } from './migrate'\nimport { runInit } from './init'\nimport type { ExtractedMessage, FluentiConfig } from '@fluenti/core'\n\nconst defaultConfig: FluentiConfig = {\n sourceLocale: 'en',\n locales: ['en'],\n catalogDir: './locales',\n format: 'po',\n include: ['./src/**/*.{vue,tsx,jsx,ts,js}'],\n compileOutDir: './src/locales/compiled',\n}\n\nasync function loadConfig(configPath?: string): Promise<FluentiConfig> {\n const paths = configPath\n ? [resolve(configPath)]\n : [\n resolve('fluenti.config.ts'),\n resolve('fluenti.config.js'),\n resolve('fluenti.config.mjs'),\n ]\n\n for (const p of paths) {\n if (existsSync(p)) {\n try {\n const { createJiti } = await import('jiti')\n const jiti = createJiti(import.meta.url)\n const mod = await jiti.import(p) as { default?: Partial<FluentiConfig> }\n const userConfig = mod.default ?? mod as unknown as Partial<FluentiConfig>\n return { ...defaultConfig, ...userConfig }\n } catch {\n consola.warn(`Failed to load config from ${p}, using defaults`)\n }\n }\n }\n\n return defaultConfig\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(filePath: string, code: string): Promise<ExtractedMessage[]> {\n const ext = extname(filePath)\n if (ext === '.vue') {\n const { extractFromVue } = await import('./vue-extractor')\n return extractFromVue(code, filePath)\n }\n return extractFromTsx(code, filePath)\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 },\n async run({ args }) {\n const config = await loadConfig(args.config)\n consola.info(`Extracting messages from ${config.include.join(', ')}`)\n\n const files = await fg(config.include)\n const allMessages: ExtractedMessage[] = []\n\n for (const file of files) {\n const code = readFileSync(file, 'utf-8')\n const messages = await extractFromFile(file, code)\n allMessages.push(...messages)\n }\n\n consola.info(`Found ${allMessages.length} messages in ${files.length} files`)\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 config.locales) {\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})\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 },\n async run({ args }) {\n const config = await loadConfig(args.config)\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 for (const locale of config.locales) {\n const catalogPath = resolve(config.catalogDir, `${locale}${ext}`)\n allCatalogs[locale] = readCatalog(catalogPath, config.format)\n }\n\n const allIds = collectAllIds(allCatalogs)\n consola.info(`Compiling ${allIds.length} messages across ${config.locales.length} locales`)\n\n const skipFuzzy = args['skip-fuzzy'] ?? false\n\n for (const locale of config.locales) {\n const { code, stats } = compileCatalog(\n allCatalogs[locale]!,\n locale,\n allIds,\n config.sourceLocale,\n { skipFuzzy },\n )\n const outPath = resolve(config.compileOutDir, `${locale}.js`)\n writeFileSync(outPath, code, 'utf-8')\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\n // Generate index.js with locale list and lazy loaders\n const indexCode = compileIndex(config.locales, config.compileOutDir)\n const indexPath = resolve(config.compileOutDir, 'index.js')\n writeFileSync(indexPath, indexCode, 'utf-8')\n consola.success(`Generated index → ${indexPath}`)\n\n // Generate type declarations\n const typesCode = compileTypeDeclaration(allIds, allCatalogs, config.sourceLocale)\n const typesPath = resolve(config.compileOutDir, 'messages.d.ts')\n writeFileSync(typesPath, typesCode, 'utf-8')\n consola.success(`Generated types → ${typesPath}`)\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 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 config.locales) {\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 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 },\n async run({ args }) {\n const config = await loadConfig(args.config)\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 : config.locales.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 const { catalog: updated, translated } = await translateCatalog({\n provider,\n sourceLocale: config.sourceLocale,\n targetLocale: locale,\n catalog,\n batchSize,\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, translate, migrate },\n})\n\nrunMain(main)\n"],"mappings":";;;;;;;;;;;AAAA,IAAM,IAAa,KACb,IAAc;AAQpB,SAAgB,EAAkB,GAAa,IAAQ,IAAY;CACjE,IAAM,IAAU,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,EAAI,CAAC,EACzC,IAAS,KAAK,MAAO,IAAU,MAAO,EAAM;AAClD,QAAO,EAAW,OAAO,EAAO,GAAG,EAAY,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,EACd,GACA,GACA,GACQ;CACR,IAAM,IAAM,IAAQ,IAAK,IAAa,IAAS,MAAM,GAC/C,IAAa,IAAQ,IAAI,EAAgB,EAAI,GAAG,KAChD,IAAM,IAAQ,IAAI,EAAkB,EAAI,GAAG;AACjD,QAAO,KAAK,EAAO,OAAO,EAAE,CAAC,IAAI,OAAO,EAAM,CAAC,SAAS,EAAE,CAAC,KAAK,OAAO,EAAW,CAAC,SAAS,GAAG,CAAC,KAAK,EAAI,GAAG;;;;ACnC9G,IAAM,IAAgB,EAAU,EAAS;AAIzC,SAAgB,GACd,GACA,GACA,GACQ;CACR,IAAM,IAAO,KAAK,UAAU,GAAU,MAAM,EAAE;AAC9C,QAAO;EACL,6EAA6E,EAAa,QAAQ,EAAa;EAC/G;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,KAAK,KAAK;;AAGd,eAAe,GAAS,GAAsB,GAA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ACjD,EAAQ,QAAQ,KAAK,EAAO,IAAI,EAAW,sBAAsB,IAEjE,EAAQ,QAAQ,KAAK,EAAO,4BAA4B;;;CAI/D,CAAC,EAEI,KAAU,EAAc;CAC5B,MAAM;EAAE,MAAM;EAAW,aAAa;EAA8C;CACpF,MAAM;EACJ,MAAM;GAAE,MAAM;GAAU,aAAa;GAAuF,UAAU;GAAM;EAC5I,UAAU;GAAE,MAAM;GAAU,aAAa;GAAgC,SAAS;GAAU;EAC5F,OAAO;GAAE,MAAM;GAAW,aAAa;GAAiC,SAAS;GAAO;EACzF;CACD,MAAM,IAAI,EAAE,WAAQ;EAClB,IAAM,IAAW,EAAK;AACtB,MAAI,MAAa,YAAY,MAAa,SAAS;AACjD,KAAQ,MAAM,qBAAqB,EAAS,6BAA6B;AACzE;;AAGF,QAAM,EAAW;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,EAAQ,EAAE,KAAK,QAAQ,KAAK,EAAE,CAAC;;GAExC,CAAC;EAQqB;EAAS;EAAS;EAAO;EAAW;EAAS;CACnE,CAAC,CAEW"}
@@ -0,0 +1,357 @@
1
+ import { hashMessage as e, parse as t } from "@fluenti/core";
2
+ import * as n from "gettext-parser";
3
+ //#region src/catalog.ts
4
+ function r(e, t, n) {
5
+ let r = new Set(t.map((e) => e.id)), o = /* @__PURE__ */ new Set(), s = {}, c = 0, l = 0, u = 0;
6
+ for (let r of t) {
7
+ let t = e[r.id], u = t ? void 0 : a(e, r, o), d = `${r.origin.file}:${r.origin.line}`, f = t ?? u?.entry;
8
+ if (u && o.add(u.id), f) s[r.id] = {
9
+ ...f,
10
+ message: r.message ?? f.message,
11
+ context: r.context,
12
+ comment: r.comment,
13
+ origin: d,
14
+ obsolete: !1
15
+ }, l++;
16
+ else if (s[r.id]) {
17
+ let e = s[r.id];
18
+ s[r.id] = {
19
+ ...e,
20
+ origin: i(e.origin, d)
21
+ };
22
+ } else s[r.id] = {
23
+ message: r.message,
24
+ context: r.context,
25
+ comment: r.comment,
26
+ origin: d
27
+ }, c++;
28
+ if (n?.stripFuzzy) {
29
+ let { fuzzy: e, ...t } = s[r.id];
30
+ s[r.id] = t;
31
+ }
32
+ }
33
+ for (let [t, i] of Object.entries(e)) if (!r.has(t)) {
34
+ let { fuzzy: e, ...r } = i;
35
+ s[t] = n?.stripFuzzy ? {
36
+ ...r,
37
+ obsolete: !0
38
+ } : {
39
+ ...i,
40
+ obsolete: !0
41
+ }, u++;
42
+ }
43
+ return {
44
+ catalog: s,
45
+ result: {
46
+ added: c,
47
+ unchanged: l,
48
+ obsolete: u
49
+ }
50
+ };
51
+ }
52
+ function i(e, t) {
53
+ if (!e) return t;
54
+ let n = Array.isArray(e) ? e : [e], r = [...new Set([...n, t])];
55
+ return r.length === 1 ? r[0] : r;
56
+ }
57
+ function a(e, t, n) {
58
+ if (!t.context) return;
59
+ let r = `${t.origin.file}:${t.origin.line}`;
60
+ for (let [i, a] of Object.entries(e)) if (!n.has(i) && a.context === void 0 && a.message === t.message && o(a.origin, r)) return {
61
+ id: i,
62
+ entry: a
63
+ };
64
+ }
65
+ function o(e, t) {
66
+ return e ? (Array.isArray(e) ? e : [e]).some((e) => e === t || s(e) === s(t)) : !1;
67
+ }
68
+ function s(e) {
69
+ return e.match(/^(.*):\d+$/)?.[1] ?? e;
70
+ }
71
+ //#endregion
72
+ //#region src/json-format.ts
73
+ function c(e) {
74
+ let t = JSON.parse(e), n = {};
75
+ for (let [e, r] of Object.entries(t)) if (typeof r == "object" && r) {
76
+ let t = r;
77
+ n[e] = {
78
+ message: typeof t.message == "string" ? t.message : void 0,
79
+ context: typeof t.context == "string" ? t.context : void 0,
80
+ comment: typeof t.comment == "string" ? t.comment : void 0,
81
+ translation: typeof t.translation == "string" ? t.translation : void 0,
82
+ origin: typeof t.origin == "string" || Array.isArray(t.origin) && t.origin.every((e) => typeof e == "string") ? t.origin : void 0,
83
+ obsolete: typeof t.obsolete == "boolean" ? t.obsolete : void 0,
84
+ fuzzy: typeof t.fuzzy == "boolean" ? t.fuzzy : void 0
85
+ };
86
+ }
87
+ return n;
88
+ }
89
+ function l(e) {
90
+ let t = {};
91
+ for (let [n, r] of Object.entries(e)) {
92
+ let e = {};
93
+ r.message !== void 0 && (e.message = r.message), r.context !== void 0 && (e.context = r.context), r.comment !== void 0 && (e.comment = r.comment), r.translation !== void 0 && (e.translation = r.translation), r.origin !== void 0 && (e.origin = r.origin), r.obsolete && (e.obsolete = !0), r.fuzzy && (e.fuzzy = !0), t[n] = e;
94
+ }
95
+ return JSON.stringify(t, null, 2) + "\n";
96
+ }
97
+ //#endregion
98
+ //#region src/po-format.ts
99
+ var u = "fluenti-id:";
100
+ function d(t) {
101
+ let r = n.po.parse(t), i = {}, a = r.translations ?? {};
102
+ for (let [t, n] of Object.entries(a)) for (let [r, a] of Object.entries(n)) {
103
+ if (!r) continue;
104
+ let n = t || a.msgctxt || void 0, o = a.msgstr?.[0] ?? void 0, s = a.comments?.reference ?? void 0, c = s?.includes("\n") ? s.split("\n").map((e) => e.trim()).filter(Boolean) : s?.includes(" ") ? s.split(/\s+/).filter(Boolean) : s, l = Array.isArray(c) && c.length === 1 ? c[0] : c, u = a.comments?.flag?.includes("fuzzy") ?? !1, { comment: d, customId: f, sourceMessage: m } = p(a.comments?.extracted), h = m && e(m, n) === r ? m : void 0, g = f ?? (h ? r : e(r, n));
105
+ i[g] = {
106
+ message: h ?? r,
107
+ ...n === void 0 ? {} : { context: n },
108
+ ...d === void 0 ? {} : { comment: d },
109
+ ...o ? { translation: o } : {},
110
+ ...l === void 0 ? {} : { origin: l },
111
+ ...u ? { fuzzy: !0 } : {}
112
+ };
113
+ }
114
+ return i;
115
+ }
116
+ function f(e) {
117
+ let t = { "": { "": {
118
+ msgid: "",
119
+ msgstr: ["Content-Type: text/plain; charset=UTF-8\n"]
120
+ } } };
121
+ for (let [n, r] of Object.entries(e)) {
122
+ let e = {
123
+ msgid: r.message ?? n,
124
+ ...r.context === void 0 ? {} : { msgctxt: r.context },
125
+ msgstr: [r.translation ?? ""]
126
+ }, i = {};
127
+ r.origin && (i.reference = Array.isArray(r.origin) ? r.origin.join("\n") : r.origin);
128
+ let a = h(n, r.message ?? n, r.context, r.comment);
129
+ a && (i.extracted = a), r.fuzzy && (i.flag = "fuzzy"), (i.reference || i.extracted || i.flag) && (e.comments = i);
130
+ let o = r.context ?? "";
131
+ t[o] ??= {}, t[o][e.msgid] = e;
132
+ }
133
+ let r = {
134
+ headers: { "Content-Type": "text/plain; charset=UTF-8" },
135
+ translations: t
136
+ };
137
+ return n.po.compile(r).toString();
138
+ }
139
+ function p(e) {
140
+ if (!e) return {};
141
+ let t = e.split("\n").map((e) => e.trim()).filter(Boolean), n, r, i = [];
142
+ for (let e of t) {
143
+ if (e.startsWith(u)) {
144
+ n = e.slice(11).trim() || void 0;
145
+ continue;
146
+ }
147
+ if (e.startsWith("msg`") && e.endsWith("`")) {
148
+ r = e.slice(4, -1);
149
+ continue;
150
+ }
151
+ if (e.startsWith("Trans: ")) {
152
+ r = m(e.slice(7));
153
+ continue;
154
+ }
155
+ i.push(e);
156
+ }
157
+ return {
158
+ ...i.length > 0 ? { comment: i.join("\n") } : {},
159
+ ...n ? { customId: n } : {},
160
+ ...r ? { sourceMessage: r } : {}
161
+ };
162
+ }
163
+ function m(e) {
164
+ let t = [], n = 0;
165
+ return e.replace(/<\/?([a-zA-Z][\w-]*)>/g, (e, r) => {
166
+ let i = r;
167
+ if (e.startsWith("</")) {
168
+ for (let e = t.length - 1; e >= 0; e--) {
169
+ let n = t[e];
170
+ if (n?.tag === i) return t = t.filter((t, n) => n !== e), `</${n.index}>`;
171
+ }
172
+ return e;
173
+ }
174
+ let a = n++;
175
+ return t.push({
176
+ tag: i,
177
+ index: a
178
+ }), `<${a}>`;
179
+ });
180
+ }
181
+ function h(t, n, r, i) {
182
+ let a = [];
183
+ return i && a.push(i), t !== e(n, r) && a.push(`${u} ${t}`), a.length > 0 ? a.join("\n") : void 0;
184
+ }
185
+ //#endregion
186
+ //#region src/compile.ts
187
+ var g = /\{(\w+)\}/g, _ = /\{(\w+)\}/;
188
+ function v(e) {
189
+ return _.test(e);
190
+ }
191
+ function y(e) {
192
+ return e.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
193
+ }
194
+ function b(e) {
195
+ return e.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
196
+ }
197
+ function x(e) {
198
+ return e.replace(g, (e, t) => `\${v.${t}}`);
199
+ }
200
+ var S = /\{(\w+),\s*(plural|select|selectordinal)\s*,/;
201
+ function C(e) {
202
+ return S.test(e);
203
+ }
204
+ function w(e, t) {
205
+ if (e.length === 0) return "''";
206
+ let n = e.map((e) => T(e, t));
207
+ return n.length === 1 ? n[0] : n.join(" + ");
208
+ }
209
+ function T(e, t) {
210
+ switch (e.type) {
211
+ case "text": return `'${y(e.value)}'`;
212
+ case "variable": return e.name === "#" ? "String(__c)" : `String(v.${e.name} ?? '{${e.name}}')`;
213
+ case "plural": return E(e, t);
214
+ case "select": return D(e, t);
215
+ case "function": return `String(v.${e.variable} ?? '')`;
216
+ }
217
+ }
218
+ function E(e, t) {
219
+ let n = e.offset ?? 0, r = n ? `(v.${e.variable} - ${n})` : `v.${e.variable}`, i = [];
220
+ i.push("((c) => { const __c = c; ");
221
+ let a = Object.keys(e.options).filter((e) => e.startsWith("="));
222
+ if (a.length > 0) for (let n of a) {
223
+ let r = n.slice(1), a = w(e.options[n], t);
224
+ i.push(`if (c === ${r}) return ${a}; `);
225
+ }
226
+ let o = Object.keys(e.options).filter((e) => !e.startsWith("="));
227
+ if (o.length > 1 || o.length === 1 && o[0] !== "other") {
228
+ i.push(`const __cat = new Intl.PluralRules('${y(t)}').select(c); `);
229
+ for (let n of o) {
230
+ if (n === "other") continue;
231
+ let r = w(e.options[n], t);
232
+ i.push(`if (__cat === '${n}') return ${r}; `);
233
+ }
234
+ }
235
+ let s = e.options.other ? w(e.options.other, t) : "''";
236
+ return i.push(`return ${s}; `), i.push(`})(${r})`), i.join("");
237
+ }
238
+ function D(e, t) {
239
+ let n = [];
240
+ n.push("((s) => { ");
241
+ let r = Object.keys(e.options).filter((e) => e !== "other");
242
+ for (let i of r) {
243
+ let r = w(e.options[i], t);
244
+ n.push(`if (s === '${y(i)}') return ${r}; `);
245
+ }
246
+ let i = e.options.other ? w(e.options.other, t) : "''";
247
+ return n.push(`return ${i}; `), n.push(`})(String(v.${e.variable} ?? ''))`), n.join("");
248
+ }
249
+ function O(n, r, i, a, o) {
250
+ let s = [];
251
+ s.push("// @fluenti/compiled v1");
252
+ let c = [], l = 0, u = [], d = /* @__PURE__ */ new Map();
253
+ for (let f of i) {
254
+ let i = e(f), p = d.get(i);
255
+ if (p !== void 0 && p !== f) throw Error(`Hash collision detected: messages "${p}" and "${f}" produce the same hash "${i}"`);
256
+ d.set(i, f);
257
+ let m = `_${i}`, h = n[f], g = k(h, f, r, a, o?.skipFuzzy);
258
+ if (g === void 0) s.push(`export const ${m} = undefined`), u.push(f);
259
+ else if (C(g)) {
260
+ let e = w(t(g), r);
261
+ s.push(`export const ${m} = (v) => ${e}`), l++;
262
+ } else if (v(g)) {
263
+ let e = x(b(g));
264
+ s.push(`export const ${m} = (v) => \`${e}\``), l++;
265
+ } else s.push(`export const ${m} = '${y(g)}'`), l++;
266
+ c.push({
267
+ id: f,
268
+ exportName: m
269
+ });
270
+ }
271
+ if (c.length === 0) return {
272
+ code: "// @fluenti/compiled v1\n// empty catalog\nexport default {}\n",
273
+ stats: {
274
+ compiled: 0,
275
+ missing: []
276
+ }
277
+ };
278
+ s.push(""), s.push("export default {");
279
+ for (let { id: e, exportName: t } of c) s.push(` '${y(e)}': ${t},`);
280
+ return s.push("}"), s.push(""), {
281
+ code: s.join("\n"),
282
+ stats: {
283
+ compiled: l,
284
+ missing: u
285
+ }
286
+ };
287
+ }
288
+ function k(e, t, n, r, i) {
289
+ let a = r ?? n;
290
+ if (e && !(i && e.fuzzy)) {
291
+ if (e.translation !== void 0 && e.translation.length > 0) return e.translation;
292
+ if (n === a) return e.message ?? t;
293
+ }
294
+ }
295
+ function A(e, t) {
296
+ let n = [];
297
+ n.push(`export const locales = ${JSON.stringify(e)}`), n.push(""), n.push("export const loaders = {");
298
+ for (let t of e) n.push(` '${y(t)}': () => import('./${y(t)}.js'),`);
299
+ return n.push("}"), n.push(""), n.join("\n");
300
+ }
301
+ function j(e) {
302
+ let t = /* @__PURE__ */ new Set();
303
+ for (let n of Object.values(e)) for (let [e, r] of Object.entries(n)) r.obsolete || t.add(e);
304
+ return [...t].sort();
305
+ }
306
+ function M(e) {
307
+ let n = t(e), r = /* @__PURE__ */ new Map();
308
+ return N(n, r), [...r.entries()].sort(([e], [t]) => e.localeCompare(t)).map(([e, t]) => ({
309
+ name: e,
310
+ type: t
311
+ }));
312
+ }
313
+ function N(e, t) {
314
+ for (let n of e) switch (n.type) {
315
+ case "variable":
316
+ n.name !== "#" && !t.has(n.name) && t.set(n.name, "string | number");
317
+ break;
318
+ case "plural": {
319
+ let e = n;
320
+ t.set(e.variable, "number");
321
+ for (let n of Object.values(e.options)) N(n, t);
322
+ break;
323
+ }
324
+ case "select": {
325
+ 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";
326
+ t.set(e.variable, o);
327
+ for (let n of Object.values(e.options)) N(n, t);
328
+ break;
329
+ }
330
+ case "function":
331
+ t.has(n.variable) || t.set(n.variable, "string | number");
332
+ break;
333
+ case "text": break;
334
+ }
335
+ }
336
+ function P(e, t, n) {
337
+ let r = [];
338
+ if (r.push("// Auto-generated by @fluenti/cli — do not edit"), r.push(""), e.length === 0) r.push("export type MessageId = never");
339
+ else {
340
+ r.push("export type MessageId =");
341
+ for (let t of e) r.push(` | '${y(t)}'`);
342
+ }
343
+ r.push(""), r.push("export interface MessageValues {");
344
+ for (let i of e) {
345
+ let e = M(t[n]?.[i]?.message ?? i), a = y(i);
346
+ if (e.length === 0) r.push(` '${a}': Record<string, never>`);
347
+ else {
348
+ let t = e.map((e) => `${e.name}: ${e.type}`).join("; ");
349
+ r.push(` '${a}': { ${t} }`);
350
+ }
351
+ }
352
+ return r.push("}"), r.push(""), r.join("\n");
353
+ }
354
+ //#endregion
355
+ export { d as a, l as c, P as i, r as l, O as n, f as o, A as r, c as s, j as t };
356
+
357
+ //# sourceMappingURL=compile-BJdEF9QX.js.map