@fluenti/next 0.3.1 → 0.3.2
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.
- package/dist/dev-runner.d.ts +2 -6
- package/dist/dev-runner.d.ts.map +1 -1
- package/dist/dev-watcher.d.ts.map +1 -1
- package/dist/generate-server-module.d.ts.map +1 -1
- package/dist/index.cjs +18 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +41 -69
- package/dist/index.js.map +1 -1
- package/dist/middleware.cjs +2 -0
- package/dist/middleware.cjs.map +1 -0
- package/dist/middleware.js +36 -0
- package/dist/middleware.js.map +1 -0
- package/dist/navigation.cjs +3 -0
- package/dist/navigation.cjs.map +1 -0
- package/dist/navigation.js +29 -0
- package/dist/navigation.js.map +1 -0
- package/dist/provider.cjs +1 -6
- package/dist/provider.cjs.map +1 -1
- package/dist/provider.js +9 -187
- package/dist/provider.js.map +1 -1
- package/package.json +23 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/read-config.ts","../src/generate-server-module.ts","../src/dev-runner.ts","../src/dev-watcher.ts","../src/with-fluenti.ts","../src/index.ts"],"sourcesContent":["import { loadConfigSync, DEFAULT_FLUENTI_CONFIG } from '@fluenti/core/config'\nimport type { FluentiBuildConfig } from '@fluenti/core/internal'\nimport type { WithFluentConfig, ResolvedFluentConfig } from './types'\n\n/**\n * Read fluenti.config.ts and merge with withFluenti() overrides.\n *\n * Delegates config file loading to `@fluenti/core`'s shared `loadConfigSync()`.\n */\nexport function resolveConfig(\n projectRoot: string,\n overrides?: WithFluentConfig,\n): ResolvedFluentConfig {\n let fluentiConfig: FluentiBuildConfig\n\n if (overrides?.config && typeof overrides.config === 'object') {\n // Inline config — merge with defaults\n fluentiConfig = { ...DEFAULT_FLUENTI_CONFIG, ...overrides.config }\n } else {\n // string path or auto-discover\n fluentiConfig = loadConfigSync(\n typeof overrides?.config === 'string' ? overrides.config : undefined,\n projectRoot,\n )\n }\n\n const serverModuleOutDir = overrides?.serverModuleOutDir ?? '.fluenti'\n const cookieName = overrides?.cookieName ?? 'locale'\n\n const resolved: ResolvedFluentConfig = {\n fluentiConfig,\n serverModule: overrides?.serverModule ?? null,\n serverModuleOutDir,\n cookieName,\n }\n if (overrides?.resolveLocale) resolved.resolveLocale = overrides.resolveLocale\n return resolved\n}\n","import { writeFileSync, mkdirSync, existsSync } from 'node:fs'\nimport { resolve, relative } from 'node:path'\nimport { validateLocale } from '@fluenti/core'\nimport { resolveLocaleCodes } from '@fluenti/core/internal'\nimport type { ResolvedFluentConfig } from './types'\n\n/**\n * Generate the server module that provides:\n * - setLocale / getI18n\n * - Trans / Plural / Select / DateTime / NumberFormat (server components)\n * - I18nProvider (async server component for layouts)\n *\n * @returns Absolute path to the generated server module.\n */\nexport function generateServerModule(\n projectRoot: string,\n config: ResolvedFluentConfig,\n): string {\n if (config.serverModule) {\n return resolve(projectRoot, config.serverModule)\n }\n\n const outDir = resolve(projectRoot, config.serverModuleOutDir)\n const outPath = resolve(outDir, 'server.js')\n const dtsPath = resolve(outDir, 'server.d.ts')\n\n if (!existsSync(outDir)) {\n mkdirSync(outDir, { recursive: true })\n }\n\n const locales = resolveLocaleCodes(config.fluentiConfig.locales)\n const defaultLocale = config.fluentiConfig.defaultLocale ?? config.fluentiConfig.sourceLocale\n const compiledDir = config.fluentiConfig.compileOutDir\n const fallbackChain = config.fluentiConfig.fallbackChain\n const cookieName = escapeJsSingleQuoted(config.cookieName)\n const defaultLocaleSafe = escapeJsSingleQuoted(defaultLocale)\n\n for (const locale of locales) {\n validateLocale(locale, 'next-plugin')\n }\n\n const compiledDirAbs = resolve(projectRoot, compiledDir)\n const compiledRelative = toForwardSlash(relative(outDir, compiledDirAbs))\n\n const localeImports = locales\n .map((locale) => ` case '${escapeJsSingleQuoted(locale)}': return import('${compiledRelative}/${locale}')`)\n .join('\\n')\n\n const fallbackChainStr = fallbackChain\n ? JSON.stringify(fallbackChain)\n : 'undefined'\n\n // Generate a 'use client' provider that imports messages statically.\n // Messages contain functions (interpolation) which can't cross the RSC boundary.\n const clientProviderPath = resolve(outDir, 'client-provider.js')\n\n const clientStaticImports = locales\n .map((locale) => {\n const safe = locale.replace(/[^a-zA-Z0-9]/g, '_')\n return `import ${safe} from '${compiledRelative}/${locale}'`\n })\n .join('\\n')\n\n const clientAllMessagesEntries = locales\n .map((locale) => {\n const safe = locale.replace(/[^a-zA-Z0-9]/g, '_')\n return `'${escapeJsSingleQuoted(locale)}': ${safe}`\n })\n .join(', ')\n\n const clientProviderSource = `\"use client\";\n// Auto-generated by @fluenti/next — do not edit\n// @ts-nocheck\nimport { createElement } from 'react'\nimport { I18nProvider } from '@fluenti/react'\n${clientStaticImports}\n\nconst __allMessages = { ${clientAllMessagesEntries} }\n\nexport function ClientI18nProvider({ locale, fallbackLocale, fallbackChain, children }) {\n return createElement(I18nProvider, { locale, fallbackLocale, messages: __allMessages, fallbackChain }, children)\n}\n`\n writeFileSync(clientProviderPath, clientProviderSource, 'utf-8')\n\n const resolveLocaleImport = config.resolveLocale\n ? (() => {\n const absPath = resolve(projectRoot, config.resolveLocale)\n const relPath = toForwardSlash(relative(outDir, absPath))\n return `import __resolveLocale from '${relPath}'`\n })()\n : null\n\n const resolveLocaleFn = config.resolveLocale\n ? `resolveLocale: __resolveLocale,`\n : `resolveLocale: async () => {\n try {\n const { cookies, headers } = await import('next/headers')\n const [cookieStore, headerStore] = await Promise.all([cookies(), headers()])\n\n // 1. Referer URL path segment (available in Server Action context)\n const referer = headerStore.get('referer')\n if (referer) {\n try {\n const seg = new URL(referer).pathname.split('/')[1]\n if (seg && __locales.includes(seg)) return seg\n } catch {}\n }\n\n // 2. Cookie (configurable name)\n const fromCookie = cookieStore.get('${cookieName}')?.value\n if (fromCookie && __locales.includes(fromCookie)) return fromCookie\n\n // 3. Accept-Language header\n const acceptLang = headerStore.get('accept-language')\n if (acceptLang) {\n for (const part of acceptLang.split(',')) {\n const lang = part.split(';')[0].trim()\n if (__locales.includes(lang)) return lang\n const prefix = lang.split('-')[0]\n const match = __locales.find(l => l === prefix || l.startsWith(prefix + '-'))\n if (match) return match\n }\n }\n\n return '${defaultLocaleSafe}'\n } catch {\n return '${defaultLocaleSafe}'\n }\n },`\n\n const localesArrayStr = JSON.stringify(locales)\n\n const moduleSource = `// Auto-generated by @fluenti/next — do not edit\n// @ts-nocheck\nimport { createServerI18n } from '@fluenti/react/server'\nimport { createElement } from 'react'\n${resolveLocaleImport ? `${resolveLocaleImport}\\n` : ''}\nconst __locales = ${localesArrayStr}\n\nconst serverI18n = createServerI18n({\n loadMessages: async (locale) => {\n switch (locale) {\n${localeImports}\n default: return import('${compiledRelative}/${defaultLocaleSafe}')\n }\n },\n fallbackLocale: '${defaultLocaleSafe}',\n fallbackChain: ${fallbackChainStr},\n ${resolveLocaleFn}\n})\n\nexport const setLocale = serverI18n.setLocale\nexport const getI18n = serverI18n.getI18n\nexport const t = (..._args) => {\n throw new Error(\n \"[fluenti] \\`t\\` imported from '@fluenti/next' is a compile-time API replaced at build time.\\\\n\" +\n ' Ensure:\\\\n' +\n ' 1. \\`withFluenti()\\` is configured in next.config.ts\\\\n' +\n ' 2. The file is inside src/ (not node_modules)\\\\n' +\n \" 3. For client components, import from '@fluenti/react'\",\n )\n}\nexport const Trans = serverI18n.Trans\nexport const Plural = serverI18n.Plural\nexport const Select = serverI18n.Select\nexport const DateTime = serverI18n.DateTime\nexport const NumberFormat = serverI18n.NumberFormat\n\n/**\n * Async server component for root layouts.\n *\n * Sets up both server-side (React.cache) and client-side (I18nProvider) i18n.\n */\nexport async function I18nProvider({ locale, children }) {\n const activeLocale = (locale && locale.trim()) ? locale : '${defaultLocaleSafe}'\n\n // 1. Initialize server-side i18n (React.cache scoped)\n serverI18n.setLocale(activeLocale)\n await serverI18n.getI18n()\n\n // 2. Import the local 'use client' provider that has messages statically bundled.\n // Messages contain functions (interpolation) which can't be serialized across the RSC boundary.\n const { ClientI18nProvider } = await import('./client-provider.js')\n\n return createElement(ClientI18nProvider, {\n locale: activeLocale,\n fallbackLocale: '${defaultLocaleSafe}',\n fallbackChain: ${fallbackChainStr},\n }, children)\n}\n`\n\n const dtsSource = `// Auto-generated by @fluenti/next — do not edit\nimport type { ReactNode, ReactElement } from 'react'\nimport type { CompileTimeT, FluentiCoreInstanceFull } from '@fluenti/core'\n\nexport declare function setLocale(locale: string): void\nexport declare function getI18n(): Promise<FluentiCoreInstanceFull & { locale: string }>\nexport declare const t: CompileTimeT\n\nexport declare function Trans(props: {\n children: ReactNode\n id?: string\n context?: string\n comment?: string\n render?: (translation: ReactNode) => ReactNode\n}): Promise<ReactElement>\n\nexport declare function Plural(props: {\n value: number\n id?: string\n context?: string\n comment?: string\n zero?: ReactNode\n one?: ReactNode\n two?: ReactNode\n few?: ReactNode\n many?: ReactNode\n other: ReactNode\n offset?: number\n}): Promise<ReactElement>\n\nexport declare function Select(props: {\n value: string\n id?: string\n context?: string\n comment?: string\n other: ReactNode\n options?: Record<string, ReactNode>\n [key: string]: ReactNode | Record<string, ReactNode> | string | undefined\n}): Promise<ReactElement>\n\nexport declare function DateTime(props: {\n value: Date | number\n style?: string\n}): Promise<ReactElement>\n\nexport declare function NumberFormat(props: {\n value: number\n style?: string\n}): Promise<ReactElement>\n\nexport declare function I18nProvider(props: {\n locale?: string\n children: ReactNode\n}): Promise<ReactElement>\n`\n\n writeFileSync(outPath, moduleSource, 'utf-8')\n writeFileSync(dtsPath, dtsSource, 'utf-8')\n\n return outPath\n}\n\n/** Escape a string for safe embedding inside a single-quoted JS string literal. */\nfunction escapeJsSingleQuoted(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")\n}\n\nfunction toForwardSlash(p: string): string {\n return p.split('\\\\').join('/')\n}\n","import { exec } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { resolve, dirname, join } from 'node:path'\nimport { createRequire } from 'node:module'\n\nexport interface DevRunnerOptions {\n cwd: string\n onSuccess?: () => void\n onError?: (err: Error) => void\n /** If true, reject the promise on failure instead of swallowing the error */\n throwOnError?: boolean\n /** Run only compile (skip extract). Useful for production builds where source is unchanged. */\n compileOnly?: boolean\n /** Enable parallel compilation across locales using worker threads */\n parallelCompile?: boolean\n}\n\n/**\n * Walk up from `cwd` to find `node_modules/.bin/fluenti`.\n * Returns the absolute path or null if not found.\n */\nexport function resolveCliBin(cwd: string): string | null {\n let dir = cwd\n for (;;) {\n const bin = resolve(dir, 'node_modules/.bin/fluenti')\n if (existsSync(bin)) return bin\n const parent = dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n return null\n}\n\n/**\n * Run compile in-process via `@fluenti/cli` (for compileOnly mode),\n * or fall back to shell-out for extract + compile (dev mode).\n */\nexport async function runExtractCompile(options: DevRunnerOptions): Promise<void> {\n if (options.compileOnly) {\n try {\n // Resolve @fluenti/cli from the project's cwd (not from this package's location)\n // using createRequire so pnpm's strict node_modules layout works correctly.\n // Use require() (not import()) to load @fluenti/cli — avoids CJS/ESM interop\n // issues when dynamic import() loads minified CJS with chunk requires.\n const projectRequire = createRequire(join(options.cwd, 'package.json'))\n const { runCompile } = projectRequire('@fluenti/cli')\n await runCompile(options.cwd)\n console.log('[fluenti] Compiling... done')\n options.onSuccess?.()\n return\n } catch (e) {\n const error = e instanceof Error ? e : new Error(String(e))\n if (options.throwOnError) throw error\n console.warn('[fluenti] Compile failed:', error.message)\n options.onError?.(error)\n return\n }\n }\n\n // Dev mode: try in-process extract + compile first (avoids shell-out overhead).\n // Step 1: check if @fluenti/cli is installed — if not, fall back to shell-out.\n // Step 2: run — errors here mean the CLI ran but failed; surface them, don't fall through.\n let fluentCli: { runExtract: (cwd: string) => Promise<void>; runCompile: (cwd: string, opts?: { parallel: boolean }) => Promise<void> } | null = null\n try {\n const projectRequire = createRequire(join(options.cwd, 'package.json'))\n fluentCli = projectRequire('@fluenti/cli')\n } catch {\n // @fluenti/cli not installed — fall back to shell-out\n }\n\n if (fluentCli) {\n try {\n await fluentCli.runExtract(options.cwd)\n if (options.parallelCompile) {\n await fluentCli.runCompile(options.cwd, { parallel: true })\n } else {\n await fluentCli.runCompile(options.cwd)\n }\n console.log('[fluenti] Extracting and compiling... done')\n options.onSuccess?.()\n return\n } catch (e) {\n const error = e instanceof Error ? e : new Error(String(e))\n if (options.throwOnError) throw error\n console.warn('[fluenti] Extract/compile failed:', error.message)\n options.onError?.(error)\n return\n }\n }\n\n const bin = resolveCliBin(options.cwd)\n if (!bin) {\n const msg = '[fluenti] CLI not found — skipping auto-compile. Install @fluenti/cli as a devDependency.'\n if (options.throwOnError) {\n return Promise.reject(new Error(msg))\n }\n console.warn(msg)\n return Promise.resolve()\n }\n\n const parallelFlag = options.parallelCompile ? ' --parallel' : ''\n const command = `${bin} extract && ${bin} compile${parallelFlag}`\n return new Promise<void>((resolve, reject) => {\n exec(\n command,\n { cwd: options.cwd },\n (err, _stdout, stderr) => {\n if (err) {\n const error = new Error(stderr || err.message)\n if (options.throwOnError) {\n reject(error)\n return\n }\n console.warn('[fluenti] Extract/compile failed:', error.message)\n options.onError?.(error)\n } else {\n console.log('[fluenti] Extracting and compiling... done')\n options.onSuccess?.()\n }\n resolve()\n },\n )\n })\n}\n\n/**\n * Create a debounced runner that collapses rapid calls.\n *\n * - If called while idle, schedules a run after `delay` ms.\n * - If called while a run is in progress, marks a pending rerun.\n * - Never runs concurrently.\n */\nexport function createDebouncedRunner(\n options: DevRunnerOptions,\n delay = 300,\n): () => void {\n let timer: ReturnType<typeof setTimeout> | null = null\n let running = false\n let pendingRerun = false\n\n async function execute(): Promise<void> {\n running = true\n try {\n await runExtractCompile(options)\n } finally {\n running = false\n if (pendingRerun) {\n pendingRerun = false\n schedule()\n }\n }\n }\n\n function schedule(): void {\n if (timer !== null) {\n clearTimeout(timer)\n }\n timer = setTimeout(() => {\n timer = null\n if (running) {\n pendingRerun = true\n } else {\n execute()\n }\n }, delay)\n }\n\n return schedule\n}\n","import { watch } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { createRequire } from 'node:module'\nimport { createDebouncedRunner } from './dev-runner'\n\nexport interface DevWatcherOptions {\n cwd: string\n compiledDir: string\n delay?: number\n /** Glob patterns from fluenti.config.ts `include` field */\n include?: string[]\n /** Glob patterns from fluenti.config.ts `exclude` field */\n exclude?: string[]\n /** Enable parallel compilation across locales using worker threads */\n parallelCompile?: boolean\n}\n\nlet activeWatcher: (() => void) | null = null\n\n/**\n * Extract watch directories from include glob patterns.\n *\n * Takes the static prefix before the first glob wildcard (`*`).\n * Falls back to `src` if no include patterns are provided.\n *\n * @example\n * extractWatchDirs('/proj', ['./src/**\\/*.tsx']) → ['/proj/src']\n * extractWatchDirs('/proj', ['./app/**\\/*.ts', './lib/**\\/*.ts']) → ['/proj/app', '/proj/lib']\n * extractWatchDirs('/proj', ['./**\\/*.ts']) → ['/proj']\n */\nexport function extractWatchDirs(cwd: string, include?: string[]): string[] {\n if (!include || include.length === 0) {\n return [resolve(cwd, 'src')]\n }\n\n const dirs = new Set<string>()\n for (const pattern of include) {\n const normalized = pattern.replace(/^\\.\\//, '')\n const staticPart = normalized.split('*')[0]!.replace(/\\/+$/, '')\n dirs.add(staticPart || '.')\n }\n return [...dirs].map(d => resolve(cwd, d))\n}\n\n/**\n * Start a standalone file watcher for dev auto-compile.\n *\n * Works independently of webpack/Turbopack — watches source directories\n * (inferred from `include` patterns) for changes and triggers\n * extract+compile via the debounced runner.\n *\n * Only one watcher is active at a time (guards against multiple `applyFluenti()` calls).\n *\n * @returns A cleanup function that stops the watcher.\n */\nexport function startDevWatcher(options: DevWatcherOptions): () => void {\n // Clean up previous watcher if one exists (e.g., dev server reload)\n if (activeWatcher) {\n activeWatcher()\n }\n\n const { cwd, compiledDir, delay = 1000, include, exclude, parallelCompile } = options\n const compiledDirResolved = resolve(cwd, compiledDir)\n const _require = createRequire(import.meta.url)\n const picomatch = _require('picomatch') as (patterns: string[]) => (str: string) => boolean\n const isExcluded = exclude?.length ? picomatch(exclude) : () => false\n const runnerOpts: Parameters<typeof createDebouncedRunner>[0] = { cwd }\n if (parallelCompile) runnerOpts.parallelCompile = true\n const debouncedRun = createDebouncedRunner(runnerOpts, delay)\n\n // Initial run\n debouncedRun()\n\n const watchDirs = extractWatchDirs(cwd, include)\n const watchers = watchDirs.map(dir =>\n watch(dir, { recursive: true }, (_event, filename) => {\n if (!filename) return\n if (!/\\.[jt]sx?$/.test(filename)) return\n if (filename.includes('node_modules') || filename.includes('.next')) return\n const full = resolve(dir, filename)\n if (full.startsWith(compiledDirResolved)) return\n if (isExcluded(filename)) return\n debouncedRun()\n }),\n )\n\n const cleanup = (): void => {\n for (const w of watchers) w.close()\n activeWatcher = null\n }\n\n activeWatcher = cleanup\n return cleanup\n}\n","import { existsSync } from 'node:fs'\nimport { resolve, dirname } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport type { WithFluentConfig } from './types'\nimport { resolveConfig } from './read-config'\nimport { generateServerModule } from './generate-server-module'\nimport { startDevWatcher } from './dev-watcher'\n\ntype NextConfig = Record<string, unknown>\n\n/**\n * Wrap your Next.js config with Fluenti support.\n *\n * Adds a webpack loader that transforms `t\\`\\`` and `t()` calls,\n * and generates a server module for RSC i18n.\n *\n * @example\n * ```ts\n * // next.config.ts — function style (recommended)\n * import { withFluenti } from '@fluenti/next'\n * export default withFluenti()({ reactStrictMode: true })\n * ```\n *\n * @example\n * ```ts\n * // next.config.ts — direct style\n * import { withFluenti } from '@fluenti/next'\n * export default withFluenti({ reactStrictMode: true })\n * ```\n */\nexport function withFluenti(fluentConfig?: WithFluentConfig): (nextConfig?: NextConfig) => NextConfig\nexport function withFluenti(nextConfig: NextConfig): NextConfig\nexport function withFluenti(\n configOrNext?: WithFluentConfig | NextConfig,\n): NextConfig | ((nextConfig?: NextConfig) => NextConfig) {\n if (configOrNext && !isFluentConfig(configOrNext as Record<string, unknown>)) {\n // Has keys but none are fluent-specific → treat as NextConfig\n return applyFluenti({}, configOrNext as NextConfig)\n }\n\n const fluentConfig = (configOrNext ?? {}) as WithFluentConfig\n return function wrappedConfig(nextConfig?: NextConfig): NextConfig {\n return applyFluenti(fluentConfig, nextConfig ?? {})\n }\n}\n\nfunction isFluentConfig(obj: Record<string, unknown>): boolean {\n const fluentOnlyKeys = [\n 'config', 'serverModule', 'serverModuleOutDir', 'resolveLocale',\n 'cookieName', 'loaderEnforce',\n ]\n return fluentOnlyKeys.some((key) => key in obj)\n}\n\nfunction applyFluenti(\n fluentConfig: WithFluentConfig,\n nextConfig: NextConfig,\n): NextConfig {\n const projectRoot = process.cwd()\n const resolved = resolveConfig(projectRoot, fluentConfig)\n const fluentiConfig = resolved.fluentiConfig\n const compiledDir = fluentiConfig.compileOutDir\n\n // Warn if compiled catalogs directory doesn't exist yet\n const compiledDirAbs = resolve(projectRoot, compiledDir)\n if (!existsSync(compiledDirAbs)) {\n console.warn(\n `\\n[fluenti] Compiled catalogs not found at ${compiledDir}.\\n` +\n `Run: npx fluenti extract && npx fluenti compile\\n`,\n )\n }\n\n // Generate server module for RSC\n const serverModulePath = generateServerModule(projectRoot, resolved)\n\n // Resolve the loader path — use import.meta.url for ESM compatibility\n const thisDir = typeof __dirname !== 'undefined'\n ? __dirname\n : dirname(fileURLToPath(import.meta.url))\n const loaderPath = resolve(thisDir, 'loader.js')\n\n const existingWebpack = nextConfig['webpack'] as\n | ((config: WebpackConfig, options: WebpackOptions) => WebpackConfig)\n | undefined\n\n let buildCompileRan = false\n\n // ── Turbopack config ──────────────────────────────────────────────\n // Turbopack loader-runner supports webpack loaders via turbopack.rules.\n // Use package name (not file path) — Turbopack resolves loaders as packages,\n // file paths trigger static analysis errors (TP1006) in the loader-runner.\n const fluentTurboRules = Object.fromEntries(\n ['*.ts', '*.tsx', '*.js', '*.jsx'].map((ext) => [\n ext,\n {\n condition: { not: 'foreign' },\n loaders: ['@fluenti/next/loader'],\n },\n ]),\n )\n\n // Turbopack resolveAlias requires relative paths (absolute paths get\n // misinterpreted as \"./abs/path\"). Use \"./\" + relative-from-cwd.\n const relativeServerModule = './' + serverModulePath\n .replace(projectRoot + '/', '')\n .replace(projectRoot + '\\\\', '')\n const fluentTurboAlias: Record<string, string> = {\n '@fluenti/next': relativeServerModule,\n }\n\n // ── Dev auto-compile via standalone watcher (works with both webpack & Turbopack) ──\n const isDev = process.env['NODE_ENV'] === 'development'\n || process.argv.some(a => a === 'dev')\n const devAutoCompile = fluentiConfig.devAutoCompile ?? true\n\n if (isDev && devAutoCompile) {\n const watcherOpts: Parameters<typeof startDevWatcher>[0] = {\n cwd: projectRoot,\n compiledDir,\n delay: fluentiConfig.devAutoCompileDelay ?? 1000,\n }\n if (fluentiConfig.parallelCompile) watcherOpts.parallelCompile = true\n if (fluentiConfig.include) watcherOpts.include = fluentiConfig.include\n if (fluentiConfig.exclude) watcherOpts.exclude = fluentiConfig.exclude\n startDevWatcher(watcherOpts)\n }\n\n return {\n ...nextConfig,\n turbopack: mergeTurbopackConfig(\n nextConfig['turbopack'] as Record<string, unknown> | undefined,\n { rules: fluentTurboRules, resolveAlias: fluentTurboAlias },\n ),\n webpack(config: WebpackConfig, options: WebpackOptions) {\n // Add fluenti loader\n const loaderEnforce = fluentConfig.loaderEnforce === undefined && !('loaderEnforce' in (fluentConfig as Record<string, unknown>))\n ? 'pre' as const\n : fluentConfig.loaderEnforce\n config.module.rules.push({\n test: /\\.[jt]sx?$/,\n ...(loaderEnforce ? { enforce: loaderEnforce } : {}),\n exclude: [/node_modules/, /\\.next/],\n use: [\n {\n loader: loaderPath,\n options: {\n serverModulePath,\n },\n },\n ],\n })\n\n // Add resolve alias so loader can import from generated server module\n config.resolve = config.resolve ?? {} as WebpackConfig['resolve']\n config.resolve.alias = config.resolve.alias ?? {}\n config.resolve.alias['@fluenti/next$'] = serverModulePath\n\n // Auto compile before production build via async beforeRun hook\n const buildAutoCompile = fluentiConfig.buildAutoCompile ?? true\n if (!options.dev && buildAutoCompile) {\n config.plugins = config.plugins ?? []\n config.plugins.push({\n apply(compiler: WebpackCompiler) {\n compiler.hooks.beforeRun.tapPromise('fluenti-compile', async () => {\n if (buildCompileRan) return\n buildCompileRan = true\n // Step 1: try to load @fluenti/cli — if not installed, skip silently\n let fluentCli: { runCompile: (cwd: string, opts?: { parallel?: boolean }) => Promise<void> }\n try {\n // @ts-expect-error — @fluenti/cli is an optional peer dependency\n fluentCli = await import('@fluenti/cli')\n } catch {\n // @fluenti/cli not installed — optional peer dep, nothing to do\n return\n }\n // Step 2: run compile — errors here mean compilation failed, let them surface\n await fluentCli.runCompile(projectRoot, fluentiConfig.parallelCompile ? { parallel: true } : undefined)\n })\n },\n })\n }\n\n // Call user's webpack config if provided\n if (existingWebpack) {\n return existingWebpack(config, options)\n }\n\n return config\n },\n }\n}\n\nfunction mergeTurbopackConfig(\n existing: Record<string, unknown> | undefined,\n fluenti: { rules: Record<string, unknown>; resolveAlias: Record<string, string> },\n): Record<string, unknown> {\n const base = existing ?? {}\n const userRules = (base['rules'] as Record<string, unknown>) ?? {}\n\n // Warn when user rules override fluenti's source-file rules\n const fluentKeys = Object.keys(fluenti.rules)\n const overlapping = fluentKeys.filter(k => k in userRules)\n if (overlapping.length > 0) {\n console.warn(\n `[fluenti] Your turbopack.rules override Fluenti's loader for: ${overlapping.join(', ')}.\\n` +\n ` Fluenti's t\\`\\` transform will NOT run on these file types.\\n` +\n ` If this is intentional, you can suppress this warning with { devAutoCompile: false }.`,\n )\n }\n\n return {\n ...base,\n rules: { ...fluenti.rules, ...userRules },\n resolveAlias: { ...fluenti.resolveAlias, ...(base['resolveAlias'] as Record<string, string>) },\n }\n}\n\n// Minimal webpack types for the config function\ninterface WebpackCompiler {\n hooks: {\n beforeRun: {\n tapPromise(name: string, cb: () => Promise<void>): void\n }\n }\n}\n\ninterface WebpackConfig {\n module: {\n rules: Array<Record<string, unknown>>\n }\n resolve: {\n alias?: Record<string, string>\n }\n plugins?: Array<{ apply(compiler: WebpackCompiler): void }>\n}\n\ninterface WebpackOptions {\n isServer: boolean\n dev: boolean\n}\n","/**\n * @fluenti/next — Next.js plugin for Fluenti\n *\n * Provides:\n * - `withFluenti()` — wraps next.config.ts with t`` transform support\n * - I18nProvider — async server component (exported from generated module)\n * - Webpack loader for strict, binding-aware tagged-template optimization\n *\n * @example\n * ```ts\n * // next.config.ts\n * import { withFluenti } from '@fluenti/next'\n * export default withFluenti()({ reactStrictMode: true })\n * ```\n *\n * @example\n * ```tsx\n * // app/layout.tsx — resolved by webpack alias to the generated module\n * import { I18nProvider } from '@fluenti/next'\n * ```\n */\nexport { withFluenti } from './with-fluenti'\nexport type { WithFluentConfig, I18nProviderProps } from './types'\n\n// ── Runtime stubs ────────────────────────────────────────────────────\n// TypeScript resolves types from this file (via package.json exports).\n// At runtime, webpack `resolve.alias` redirects `@fluenti/next$` to the\n// generated server module, so these stubs are never actually called in\n// a correctly configured project. They exist only to provide helpful\n// errors if `withFluenti()` is not configured.\n\nimport type { ReactNode, ReactElement } from 'react'\nimport type { CompileTimeT, FluentiCoreInstanceFull } from '@fluenti/core'\n\nconst NOT_CONFIGURED =\n '[fluenti] `withFluenti()` must be configured in next.config.ts before importing from \"@fluenti/next\".'\n\nfunction throwNotConfigured(): never {\n throw new Error(NOT_CONFIGURED)\n}\n\n/** @see Generated module for the real implementation. */\nexport const setLocale: (locale: string) => void = throwNotConfigured\n/** @see Generated module for the real implementation. */\nexport const getI18n: () => Promise<FluentiCoreInstanceFull & { locale: string }> = throwNotConfigured as () => Promise<FluentiCoreInstanceFull & { locale: string }>\n/** @see Generated module for the real implementation. */\nexport const t: CompileTimeT = throwNotConfigured as unknown as CompileTimeT\n/** @see Generated module for the real implementation. */\nexport const Trans: (props: { children: ReactNode; id?: string; context?: string; comment?: string; render?: (translation: ReactNode) => ReactNode }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof Trans\n/** @see Generated module for the real implementation. */\nexport const Plural: (props: { value: number; id?: string; context?: string; comment?: string; zero?: ReactNode; one?: ReactNode; two?: ReactNode; few?: ReactNode; many?: ReactNode; other: ReactNode; offset?: number }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof Plural\n/** @see Generated module for the real implementation. */\nexport const Select: (props: { value: string; id?: string; context?: string; comment?: string; other: ReactNode; options?: Record<string, ReactNode>; [key: string]: ReactNode | Record<string, ReactNode> | string | undefined }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof Select\n/** @see Generated module for the real implementation. */\nexport const DateTime: (props: { value: Date | number; style?: string }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof DateTime\n/** @see Generated module for the real implementation. */\nexport const NumberFormat: (props: { value: number; style?: string }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof NumberFormat\n/** @see Generated module for the real implementation. */\nexport const I18nProvider: (props: { locale?: string; children: ReactNode }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof I18nProvider\n"],"mappings":";;;;;;;;;AASA,SAAgB,EACd,GACA,GACsB;CACtB,IAAI;AAEJ,CAKE,IALE,GAAW,UAAU,OAAO,EAAU,UAAW,WAEnC;EAAE,GAAG;EAAwB,GAAG,EAAU;EAAQ,GAGlD,EACd,OAAO,GAAW,UAAW,WAAW,EAAU,SAAS,KAAA,GAC3D,EACD;CAGH,IAAM,IAAqB,GAAW,sBAAsB,YACtD,IAAa,GAAW,cAAc,UAEtC,IAAiC;EACrC;EACA,cAAc,GAAW,gBAAgB;EACzC;EACA;EACD;AAED,QADI,GAAW,kBAAe,EAAS,gBAAgB,EAAU,gBAC1D;;;;ACtBT,SAAgB,EACd,GACA,GACQ;AACR,KAAI,EAAO,aACT,QAAO,EAAQ,GAAa,EAAO,aAAa;CAGlD,IAAM,IAAS,EAAQ,GAAa,EAAO,mBAAmB,EACxD,IAAU,EAAQ,GAAQ,YAAY,EACtC,IAAU,EAAQ,GAAQ,cAAc;AAE9C,CAAK,EAAW,EAAO,IACrB,EAAU,GAAQ,EAAE,WAAW,IAAM,CAAC;CAGxC,IAAM,IAAU,EAAmB,EAAO,cAAc,QAAQ,EAC1D,IAAgB,EAAO,cAAc,iBAAiB,E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ACJ;AAEF,SAAS,IAA4B;AACnC,OAAU,MAAM,EAAe;;AAIjC,IAAa,IAAsC,GAEtC,IAAuE,GAEvE,IAAkB,GAElB,IAAoK,GAEpK,IAAyO,GAEzO,IAAiP,GAEjP,IAAuF,GAEvF,IAAoF,GAEpF,IAA2F"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/read-config.ts","../src/generate-server-module.ts","../src/dev-runner.ts","../src/dev-watcher.ts","../src/with-fluenti.ts","../src/index.ts"],"sourcesContent":["import { loadConfigSync, DEFAULT_FLUENTI_CONFIG } from '@fluenti/core/config'\nimport type { FluentiBuildConfig } from '@fluenti/core/internal'\nimport type { WithFluentConfig, ResolvedFluentConfig } from './types'\n\n/**\n * Read fluenti.config.ts and merge with withFluenti() overrides.\n *\n * Delegates config file loading to `@fluenti/core`'s shared `loadConfigSync()`.\n */\nexport function resolveConfig(\n projectRoot: string,\n overrides?: WithFluentConfig,\n): ResolvedFluentConfig {\n let fluentiConfig: FluentiBuildConfig\n\n if (overrides?.config && typeof overrides.config === 'object') {\n // Inline config — merge with defaults\n fluentiConfig = { ...DEFAULT_FLUENTI_CONFIG, ...overrides.config }\n } else {\n // string path or auto-discover\n fluentiConfig = loadConfigSync(\n typeof overrides?.config === 'string' ? overrides.config : undefined,\n projectRoot,\n )\n }\n\n const serverModuleOutDir = overrides?.serverModuleOutDir ?? '.fluenti'\n const cookieName = overrides?.cookieName ?? 'locale'\n\n const resolved: ResolvedFluentConfig = {\n fluentiConfig,\n serverModule: overrides?.serverModule ?? null,\n serverModuleOutDir,\n cookieName,\n }\n if (overrides?.resolveLocale) resolved.resolveLocale = overrides.resolveLocale\n return resolved\n}\n","import { writeFileSync, mkdirSync, existsSync } from 'node:fs'\nimport { resolve, relative } from 'node:path'\nimport { validateLocale } from '@fluenti/core'\nimport { resolveLocaleCodes } from '@fluenti/core/internal'\nimport type { ResolvedFluentConfig } from './types'\n\n/**\n * Generate the server module that provides:\n * - setLocale / getI18n\n * - Trans / Plural / Select / DateTime / NumberFormat (server components)\n * - I18nProvider (async server component for layouts)\n *\n * @returns Absolute path to the generated server module.\n */\nexport function generateServerModule(\n projectRoot: string,\n config: ResolvedFluentConfig,\n): string {\n if (config.serverModule) {\n return resolve(projectRoot, config.serverModule)\n }\n\n const outDir = resolve(projectRoot, config.serverModuleOutDir)\n const outPath = resolve(outDir, 'server.js')\n const dtsPath = resolve(outDir, 'server.d.ts')\n\n if (!existsSync(outDir)) {\n mkdirSync(outDir, { recursive: true })\n }\n\n const locales = resolveLocaleCodes(config.fluentiConfig.locales)\n const defaultLocale = config.fluentiConfig.defaultLocale ?? config.fluentiConfig.sourceLocale\n const compiledDir = config.fluentiConfig.compileOutDir\n const fallbackChain = config.fluentiConfig.fallbackChain\n const cookieName = escapeJsSingleQuoted(config.cookieName)\n const defaultLocaleSafe = escapeJsSingleQuoted(defaultLocale)\n\n for (const locale of locales) {\n validateLocale(locale, 'next-plugin')\n }\n\n const compiledDirAbs = resolve(projectRoot, compiledDir)\n const compiledRelative = toForwardSlash(relative(outDir, compiledDirAbs))\n\n const localeImports = locales\n .map((locale) => ` case '${escapeJsSingleQuoted(locale)}': return import('${compiledRelative}/${locale}')`)\n .join('\\n')\n\n const fallbackChainStr = fallbackChain\n ? JSON.stringify(fallbackChain)\n : 'undefined'\n\n // Generate a 'use client' provider that imports messages statically.\n // Messages contain functions (interpolation) which can't cross the RSC boundary.\n const clientProviderPath = resolve(outDir, 'client-provider.js')\n\n const clientStaticImports = locales\n .map((locale) => {\n const safe = locale.replace(/[^a-zA-Z0-9]/g, '_')\n return `import ${safe} from '${compiledRelative}/${locale}'`\n })\n .join('\\n')\n\n const clientAllMessagesEntries = locales\n .map((locale) => {\n const safe = locale.replace(/[^a-zA-Z0-9]/g, '_')\n return `'${escapeJsSingleQuoted(locale)}': ${safe}`\n })\n .join(', ')\n\n const clientProviderSource = `\"use client\";\n// Auto-generated by @fluenti/next — do not edit\n// @ts-nocheck\nimport { createElement } from 'react'\nimport { I18nProvider } from '@fluenti/react'\n${clientStaticImports}\n\nconst __allMessages = { ${clientAllMessagesEntries} }\n\nexport function ClientI18nProvider({ locale, fallbackLocale, fallbackChain, children }) {\n return createElement(I18nProvider, { locale, fallbackLocale, messages: __allMessages, fallbackChain }, children)\n}\n`\n writeFileSync(clientProviderPath, clientProviderSource, 'utf-8')\n\n const clientProviderDtsPath = resolve(outDir, 'client-provider.d.ts')\n const clientProviderDtsSource = `// Auto-generated by @fluenti/next — do not edit\nimport type { ReactNode, ReactElement } from 'react'\n\nexport declare function ClientI18nProvider(props: {\n locale: string\n fallbackLocale: string\n fallbackChain?: Record<string, string[]>\n children: ReactNode\n}): ReactElement\n`\n writeFileSync(clientProviderDtsPath, clientProviderDtsSource, 'utf-8')\n\n const resolveLocaleImport = config.resolveLocale\n ? (() => {\n const absPath = resolve(projectRoot, config.resolveLocale)\n const relPath = toForwardSlash(relative(outDir, absPath))\n return `import __resolveLocale from '${relPath}'`\n })()\n : null\n\n const resolveLocaleFn = config.resolveLocale\n ? `resolveLocale: __resolveLocale,`\n : `resolveLocale: async () => {\n try {\n const { cookies, headers } = await import('next/headers')\n const [cookieStore, headerStore] = await Promise.all([cookies(), headers()])\n\n // 1. Referer URL path segment (available in Server Action context)\n const referer = headerStore.get('referer')\n if (referer) {\n try {\n const seg = new URL(referer).pathname.split('/')[1]\n if (seg && __locales.includes(seg)) return seg\n } catch {}\n }\n\n // 2. Cookie (configurable name)\n const fromCookie = cookieStore.get('${cookieName}')?.value\n if (fromCookie && __locales.includes(fromCookie)) return fromCookie\n\n // 3. Accept-Language header\n const acceptLang = headerStore.get('accept-language')\n if (acceptLang) {\n for (const part of acceptLang.split(',')) {\n const lang = part.split(';')[0].trim()\n if (__locales.includes(lang)) return lang\n const prefix = lang.split('-')[0]\n const match = __locales.find(l => l === prefix || l.startsWith(prefix + '-'))\n if (match) return match\n }\n }\n\n return '${defaultLocaleSafe}'\n } catch {\n return '${defaultLocaleSafe}'\n }\n },`\n\n const localesArrayStr = JSON.stringify(locales)\n\n const moduleSource = `// Auto-generated by @fluenti/next — do not edit\n// @ts-nocheck\nimport { createServerI18n } from '@fluenti/react/server'\nimport { createElement } from 'react'\n${resolveLocaleImport ? `${resolveLocaleImport}\\n` : ''}\nconst __locales = ${localesArrayStr}\n\nconst serverI18n = createServerI18n({\n loadMessages: async (locale) => {\n switch (locale) {\n${localeImports}\n default: return import('${compiledRelative}/${defaultLocaleSafe}')\n }\n },\n fallbackLocale: '${defaultLocaleSafe}',\n fallbackChain: ${fallbackChainStr},\n ${resolveLocaleFn}\n})\n\nexport const setLocale = serverI18n.setLocale\nexport const getI18n = serverI18n.getI18n\nexport const t = (..._args) => {\n throw new Error(\n \"[fluenti] \\`t\\` imported from '@fluenti/next' is a compile-time API replaced at build time.\\\\n\" +\n ' Ensure:\\\\n' +\n ' 1. \\`withFluenti()\\` is configured in next.config.ts\\\\n' +\n ' 2. The file is inside src/ (not node_modules)\\\\n' +\n \" 3. For client components, import from '@fluenti/react'\",\n )\n}\nexport const Trans = serverI18n.Trans\nexport const Plural = serverI18n.Plural\nexport const Select = serverI18n.Select\nexport const DateTime = serverI18n.DateTime\nexport const NumberFormat = serverI18n.NumberFormat\n\n/**\n * Async server component for root layouts.\n *\n * Sets up both server-side (React.cache) and client-side (I18nProvider) i18n.\n */\nexport async function I18nProvider({ locale, children }) {\n const activeLocale = (locale && locale.trim()) ? locale : '${defaultLocaleSafe}'\n\n // 1. Initialize server-side i18n (React.cache scoped)\n serverI18n.setLocale(activeLocale)\n await serverI18n.getI18n()\n\n // 2. Import the local 'use client' provider that has messages statically bundled.\n // Messages contain functions (interpolation) which can't be serialized across the RSC boundary.\n const { ClientI18nProvider } = await import('./client-provider.js')\n\n return createElement(ClientI18nProvider, {\n locale: activeLocale,\n fallbackLocale: '${defaultLocaleSafe}',\n fallbackChain: ${fallbackChainStr},\n }, children)\n}\n`\n\n const dtsSource = `// Auto-generated by @fluenti/next — do not edit\nimport type { ReactNode, ReactElement } from 'react'\nimport type { CompileTimeT, FluentiCoreInstanceFull } from '@fluenti/core'\n\nexport declare function setLocale(locale: string): void\nexport declare function getI18n(): Promise<FluentiCoreInstanceFull & { locale: string }>\nexport declare const t: CompileTimeT\n\nexport declare function Trans(props: {\n children: ReactNode\n id?: string\n context?: string\n comment?: string\n render?: (translation: ReactNode) => ReactNode\n}): Promise<ReactElement>\n\nexport declare function Plural(props: {\n value: number\n id?: string\n context?: string\n comment?: string\n zero?: ReactNode\n one?: ReactNode\n two?: ReactNode\n few?: ReactNode\n many?: ReactNode\n other: ReactNode\n offset?: number\n}): Promise<ReactElement>\n\nexport declare function Select(props: {\n value: string\n id?: string\n context?: string\n comment?: string\n other: ReactNode\n options?: Record<string, ReactNode>\n [key: string]: ReactNode | Record<string, ReactNode> | string | undefined\n}): Promise<ReactElement>\n\nexport declare function DateTime(props: {\n value: Date | number\n style?: string\n}): Promise<ReactElement>\n\nexport declare function NumberFormat(props: {\n value: number\n style?: string\n}): Promise<ReactElement>\n\nexport declare function I18nProvider(props: {\n locale?: string\n children: ReactNode\n}): Promise<ReactElement>\n`\n\n writeFileSync(outPath, moduleSource, 'utf-8')\n writeFileSync(dtsPath, dtsSource, 'utf-8')\n\n return outPath\n}\n\n/** Escape a string for safe embedding inside a single-quoted JS string literal. */\nfunction escapeJsSingleQuoted(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")\n}\n\nfunction toForwardSlash(p: string): string {\n return p.split('\\\\').join('/')\n}\n","import { join } from 'node:path'\nimport { createRequire } from 'node:module'\n\nexport interface DevRunnerOptions {\n cwd: string\n onSuccess?: () => void\n onError?: (err: Error) => void\n /** If true, reject the promise on failure instead of swallowing the error */\n throwOnError?: boolean\n /** Run only compile (skip extract). Useful for production builds where source is unchanged. */\n compileOnly?: boolean\n /** Enable parallel compilation across locales using worker threads */\n parallelCompile?: boolean\n}\n\n/**\n * Run compile in-process via `@fluenti/cli` (for compileOnly mode),\n * or extract + compile in dev mode. Requires `@fluenti/cli` to be installed\n * as a devDependency.\n */\nexport async function runExtractCompile(options: DevRunnerOptions): Promise<void> {\n if (options.compileOnly) {\n try {\n // Resolve @fluenti/cli from the project's cwd (not from this package's location)\n // using createRequire so pnpm's strict node_modules layout works correctly.\n // Use require() (not import()) to load @fluenti/cli — avoids CJS/ESM interop\n // issues when dynamic import() loads minified CJS with chunk requires.\n const projectRequire = createRequire(join(options.cwd, 'package.json'))\n const { runCompile } = projectRequire('@fluenti/cli')\n await runCompile(options.cwd)\n console.log('[fluenti] Compiling... done')\n options.onSuccess?.()\n return\n } catch (e) {\n const error = e instanceof Error ? e : new Error(String(e))\n if (options.throwOnError) throw error\n console.warn('[fluenti] Compile failed:', error.message)\n options.onError?.(error)\n return\n }\n }\n\n // Dev mode: run in-process extract + compile.\n // Step 1: load @fluenti/cli — if not installed, guide user to install it.\n // Step 2: run — errors here mean the CLI ran but failed; surface them.\n let fluentCli: { runExtract: (cwd: string) => Promise<void>; runCompile: (cwd: string, opts?: { parallel: boolean }) => Promise<void> } | null = null\n try {\n const projectRequire = createRequire(join(options.cwd, 'package.json'))\n fluentCli = projectRequire('@fluenti/cli')\n } catch {\n // @fluenti/cli not installed — will show install guide below\n }\n\n if (fluentCli) {\n try {\n await fluentCli.runExtract(options.cwd)\n if (options.parallelCompile) {\n await fluentCli.runCompile(options.cwd, { parallel: true })\n } else {\n await fluentCli.runCompile(options.cwd)\n }\n console.log('[fluenti] Extracting and compiling... done')\n options.onSuccess?.()\n return\n } catch (e) {\n const error = e instanceof Error ? e : new Error(String(e))\n if (options.throwOnError) throw error\n console.warn('[fluenti] Extract/compile failed:', error.message)\n options.onError?.(error)\n return\n }\n }\n\n const msg =\n '[fluenti] @fluenti/cli is required for auto-compile.\\n' +\n ' Install it as a devDependency:\\n' +\n ' pnpm add -D @fluenti/cli\\n' +\n ' See: https://fluenti.dev/start/introduction/'\n if (options.throwOnError) {\n throw new Error(msg)\n }\n console.warn(msg)\n options.onError?.(new Error(msg))\n}\n\n/**\n * Create a debounced runner that collapses rapid calls.\n *\n * - If called while idle, schedules a run after `delay` ms.\n * - If called while a run is in progress, marks a pending rerun.\n * - Never runs concurrently.\n */\nexport function createDebouncedRunner(\n options: DevRunnerOptions,\n delay = 300,\n): () => void {\n let timer: ReturnType<typeof setTimeout> | null = null\n let running = false\n let pendingRerun = false\n\n async function execute(): Promise<void> {\n running = true\n try {\n await runExtractCompile(options)\n } finally {\n running = false\n if (pendingRerun) {\n pendingRerun = false\n schedule()\n }\n }\n }\n\n function schedule(): void {\n if (timer !== null) {\n clearTimeout(timer)\n }\n timer = setTimeout(() => {\n timer = null\n if (running) {\n pendingRerun = true\n } else {\n execute()\n }\n }, delay)\n }\n\n return schedule\n}\n","import { watch } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { createRequire } from 'node:module'\nimport { createDebouncedRunner } from './dev-runner'\n\nexport interface DevWatcherOptions {\n cwd: string\n compiledDir: string\n delay?: number\n /** Glob patterns from fluenti.config.ts `include` field */\n include?: string[]\n /** Glob patterns from fluenti.config.ts `exclude` field */\n exclude?: string[]\n /** Enable parallel compilation across locales using worker threads */\n parallelCompile?: boolean\n}\n\nlet activeWatcher: (() => void) | null = null\n\n/**\n * Extract watch directories from include glob patterns.\n *\n * Takes the static prefix before the first glob wildcard (`*`).\n * Falls back to `src` if no include patterns are provided.\n *\n * @example\n * extractWatchDirs('/proj', ['./src/**\\/*.tsx']) → ['/proj/src']\n * extractWatchDirs('/proj', ['./app/**\\/*.ts', './lib/**\\/*.ts']) → ['/proj/app', '/proj/lib']\n * extractWatchDirs('/proj', ['./**\\/*.ts']) → ['/proj']\n */\nexport function extractWatchDirs(cwd: string, include?: string[]): string[] {\n if (!include || include.length === 0) {\n return [resolve(cwd, 'src')]\n }\n\n const dirs = new Set<string>()\n for (const pattern of include) {\n const normalized = pattern.replace(/^\\.\\//, '')\n const staticPart = normalized.split('*')[0]!.replace(/\\/+$/, '')\n dirs.add(staticPart || '.')\n }\n return [...dirs].map(d => resolve(cwd, d))\n}\n\n/**\n * Start a standalone file watcher for dev auto-compile.\n *\n * Works independently of webpack/Turbopack — watches source directories\n * (inferred from `include` patterns) for changes and triggers\n * extract+compile via the debounced runner.\n *\n * Only one watcher is active at a time (guards against multiple `applyFluenti()` calls).\n *\n * @returns A cleanup function that stops the watcher.\n */\nexport function startDevWatcher(options: DevWatcherOptions): () => void {\n // Clean up previous watcher if one exists (e.g., dev server reload)\n if (activeWatcher) {\n activeWatcher()\n }\n\n const { cwd, compiledDir, delay = 1000, include, exclude, parallelCompile } = options\n const compiledDirResolved = resolve(cwd, compiledDir)\n const _require = createRequire(\n typeof __filename !== 'undefined' ? __filename : import.meta.url,\n )\n const picomatch = _require('picomatch') as (patterns: string[]) => (str: string) => boolean\n const isExcluded = exclude?.length ? picomatch(exclude) : () => false\n const runnerOpts: Parameters<typeof createDebouncedRunner>[0] = { cwd }\n if (parallelCompile) runnerOpts.parallelCompile = true\n const debouncedRun = createDebouncedRunner(runnerOpts, delay)\n\n // Initial run\n debouncedRun()\n\n const watchDirs = extractWatchDirs(cwd, include)\n const watchers = watchDirs.map(dir =>\n watch(dir, { recursive: true }, (_event, filename) => {\n if (!filename) return\n if (!/\\.[jt]sx?$/.test(filename)) return\n if (filename.includes('node_modules') || filename.includes('.next')) return\n const full = resolve(dir, filename)\n if (full.startsWith(compiledDirResolved)) return\n if (isExcluded(filename)) return\n debouncedRun()\n }),\n )\n\n const cleanup = (): void => {\n for (const w of watchers) w.close()\n activeWatcher = null\n }\n\n activeWatcher = cleanup\n return cleanup\n}\n","import { existsSync } from 'node:fs'\nimport { resolve, dirname } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport type { WithFluentConfig } from './types'\nimport { resolveConfig } from './read-config'\nimport { generateServerModule } from './generate-server-module'\nimport { startDevWatcher } from './dev-watcher'\n\ntype NextConfig = Record<string, unknown>\n\n/**\n * Wrap your Next.js config with Fluenti support.\n *\n * Adds a webpack loader that transforms `t\\`\\`` and `t()` calls,\n * and generates a server module for RSC i18n.\n *\n * @example\n * ```ts\n * // next.config.ts — function style (recommended)\n * import { withFluenti } from '@fluenti/next'\n * export default withFluenti()({ reactStrictMode: true })\n * ```\n *\n * @example\n * ```ts\n * // next.config.ts — direct style\n * import { withFluenti } from '@fluenti/next'\n * export default withFluenti({ reactStrictMode: true })\n * ```\n */\nexport function withFluenti(fluentConfig?: WithFluentConfig): (nextConfig?: NextConfig) => NextConfig\nexport function withFluenti(nextConfig: NextConfig): NextConfig\nexport function withFluenti(\n configOrNext?: WithFluentConfig | NextConfig,\n): NextConfig | ((nextConfig?: NextConfig) => NextConfig) {\n if (configOrNext && !isFluentConfig(configOrNext as Record<string, unknown>)) {\n // Has keys but none are fluent-specific → treat as NextConfig\n return applyFluenti({}, configOrNext as NextConfig)\n }\n\n const fluentConfig = (configOrNext ?? {}) as WithFluentConfig\n return function wrappedConfig(nextConfig?: NextConfig): NextConfig {\n return applyFluenti(fluentConfig, nextConfig ?? {})\n }\n}\n\nfunction isFluentConfig(obj: Record<string, unknown>): boolean {\n const fluentOnlyKeys = [\n 'config', 'serverModule', 'serverModuleOutDir', 'resolveLocale',\n 'cookieName', 'loaderEnforce',\n ]\n return fluentOnlyKeys.some((key) => key in obj)\n}\n\nfunction applyFluenti(\n fluentConfig: WithFluentConfig,\n nextConfig: NextConfig,\n): NextConfig {\n const projectRoot = process.cwd()\n const resolved = resolveConfig(projectRoot, fluentConfig)\n const fluentiConfig = resolved.fluentiConfig\n const compiledDir = fluentiConfig.compileOutDir\n\n // Warn if compiled catalogs directory doesn't exist yet\n const compiledDirAbs = resolve(projectRoot, compiledDir)\n if (!existsSync(compiledDirAbs)) {\n console.warn(\n `\\n[fluenti] Compiled catalogs not found at ${compiledDir}.\\n` +\n `Run: npx fluenti extract && npx fluenti compile\\n`,\n )\n }\n\n // Generate server module for RSC\n const serverModulePath = generateServerModule(projectRoot, resolved)\n\n // Resolve the loader path — use import.meta.url for ESM compatibility\n const thisDir = typeof __dirname !== 'undefined'\n ? __dirname\n : dirname(fileURLToPath(import.meta.url))\n const loaderPath = resolve(thisDir, 'loader.js')\n\n const existingWebpack = nextConfig['webpack'] as\n | ((config: WebpackConfig, options: WebpackOptions) => WebpackConfig)\n | undefined\n\n let buildCompileRan = false\n\n // ── Turbopack config ──────────────────────────────────────────────\n // Turbopack loader-runner supports webpack loaders via turbopack.rules.\n // Use package name (not file path) — Turbopack resolves loaders as packages,\n // file paths trigger static analysis errors (TP1006) in the loader-runner.\n const fluentTurboRules = Object.fromEntries(\n ['*.ts', '*.tsx', '*.js', '*.jsx'].map((ext) => [\n ext,\n {\n condition: { not: 'foreign' },\n loaders: ['@fluenti/next/loader'],\n },\n ]),\n )\n\n // Turbopack resolveAlias requires relative paths (absolute paths get\n // misinterpreted as \"./abs/path\"). Use \"./\" + relative-from-cwd.\n const relativeServerModule = './' + serverModulePath\n .replace(projectRoot + '/', '')\n .replace(projectRoot + '\\\\', '')\n const fluentTurboAlias: Record<string, string> = {\n '@fluenti/next': relativeServerModule,\n }\n\n // ── Dev auto-compile via standalone watcher (works with both webpack & Turbopack) ──\n const isDev = process.env['NODE_ENV'] === 'development'\n || process.argv.some(a => a === 'dev')\n const devAutoCompile = fluentiConfig.devAutoCompile ?? true\n\n if (isDev && devAutoCompile) {\n const watcherOpts: Parameters<typeof startDevWatcher>[0] = {\n cwd: projectRoot,\n compiledDir,\n delay: fluentiConfig.devAutoCompileDelay ?? 1000,\n }\n if (fluentiConfig.parallelCompile) watcherOpts.parallelCompile = true\n if (fluentiConfig.include) watcherOpts.include = fluentiConfig.include\n if (fluentiConfig.exclude) watcherOpts.exclude = fluentiConfig.exclude\n startDevWatcher(watcherOpts)\n }\n\n return {\n ...nextConfig,\n turbopack: mergeTurbopackConfig(\n nextConfig['turbopack'] as Record<string, unknown> | undefined,\n { rules: fluentTurboRules, resolveAlias: fluentTurboAlias },\n ),\n webpack(config: WebpackConfig, options: WebpackOptions) {\n // Add fluenti loader\n const loaderEnforce = fluentConfig.loaderEnforce === undefined && !('loaderEnforce' in (fluentConfig as Record<string, unknown>))\n ? 'pre' as const\n : fluentConfig.loaderEnforce\n config.module.rules.push({\n test: /\\.[jt]sx?$/,\n ...(loaderEnforce ? { enforce: loaderEnforce } : {}),\n exclude: [/node_modules/, /\\.next/],\n use: [\n {\n loader: loaderPath,\n options: {\n serverModulePath,\n },\n },\n ],\n })\n\n // Add resolve alias so loader can import from generated server module\n config.resolve = config.resolve ?? {} as WebpackConfig['resolve']\n config.resolve.alias = config.resolve.alias ?? {}\n config.resolve.alias['@fluenti/next$'] = serverModulePath\n\n // Auto compile before production build via async beforeRun hook\n const buildAutoCompile = fluentiConfig.buildAutoCompile ?? true\n if (!options.dev && buildAutoCompile) {\n config.plugins = config.plugins ?? []\n config.plugins.push({\n apply(compiler: WebpackCompiler) {\n compiler.hooks.beforeRun.tapPromise('fluenti-compile', async () => {\n if (buildCompileRan) return\n buildCompileRan = true\n // Step 1: try to load @fluenti/cli — if not installed, skip silently\n let fluentCli: { runCompile: (cwd: string, opts?: { parallel?: boolean }) => Promise<void> }\n try {\n // @ts-expect-error — @fluenti/cli is an optional peer dependency\n fluentCli = await import('@fluenti/cli')\n } catch {\n // @fluenti/cli not installed — optional peer dep, nothing to do\n return\n }\n // Step 2: run compile — errors here mean compilation failed, let them surface\n await fluentCli.runCompile(projectRoot, fluentiConfig.parallelCompile ? { parallel: true } : undefined)\n })\n },\n })\n }\n\n // Call user's webpack config if provided\n if (existingWebpack) {\n return existingWebpack(config, options)\n }\n\n return config\n },\n }\n}\n\nfunction mergeTurbopackConfig(\n existing: Record<string, unknown> | undefined,\n fluenti: { rules: Record<string, unknown>; resolveAlias: Record<string, string> },\n): Record<string, unknown> {\n const base = existing ?? {}\n const userRules = (base['rules'] as Record<string, unknown>) ?? {}\n\n // Warn when user rules override fluenti's source-file rules\n const fluentKeys = Object.keys(fluenti.rules)\n const overlapping = fluentKeys.filter(k => k in userRules)\n if (overlapping.length > 0) {\n console.warn(\n `[fluenti] Your turbopack.rules override Fluenti's loader for: ${overlapping.join(', ')}.\\n` +\n ` Fluenti's t\\`\\` transform will NOT run on these file types.\\n` +\n ` If this is intentional, you can suppress this warning with { devAutoCompile: false }.`,\n )\n }\n\n return {\n ...base,\n rules: { ...fluenti.rules, ...userRules },\n resolveAlias: { ...fluenti.resolveAlias, ...(base['resolveAlias'] as Record<string, string>) },\n }\n}\n\n// Minimal webpack types for the config function\ninterface WebpackCompiler {\n hooks: {\n beforeRun: {\n tapPromise(name: string, cb: () => Promise<void>): void\n }\n }\n}\n\ninterface WebpackConfig {\n module: {\n rules: Array<Record<string, unknown>>\n }\n resolve: {\n alias?: Record<string, string>\n }\n plugins?: Array<{ apply(compiler: WebpackCompiler): void }>\n}\n\ninterface WebpackOptions {\n isServer: boolean\n dev: boolean\n}\n","/**\n * @fluenti/next — Next.js plugin for Fluenti\n *\n * Provides:\n * - `withFluenti()` — wraps next.config.ts with t`` transform support\n * - I18nProvider — async server component (exported from generated module)\n * - Webpack loader for strict, binding-aware tagged-template optimization\n *\n * @example\n * ```ts\n * // next.config.ts\n * import { withFluenti } from '@fluenti/next'\n * export default withFluenti()({ reactStrictMode: true })\n * ```\n *\n * @example\n * ```tsx\n * // app/layout.tsx — resolved by webpack alias to the generated module\n * import { I18nProvider } from '@fluenti/next'\n * ```\n */\nexport { withFluenti } from './with-fluenti'\nexport type { WithFluentConfig, I18nProviderProps } from './types'\n\n// ── Runtime stubs ────────────────────────────────────────────────────\n// TypeScript resolves types from this file (via package.json exports).\n// At runtime, webpack `resolve.alias` redirects `@fluenti/next$` to the\n// generated server module, so these stubs are never actually called in\n// a correctly configured project. They exist only to provide helpful\n// errors if `withFluenti()` is not configured.\n\nimport type { ReactNode, ReactElement } from 'react'\nimport type { CompileTimeT, FluentiCoreInstanceFull } from '@fluenti/core'\n\nconst NOT_CONFIGURED =\n '[fluenti] `withFluenti()` must be configured in next.config.ts before importing from \"@fluenti/next\".'\n\nfunction throwNotConfigured(): never {\n throw new Error(NOT_CONFIGURED)\n}\n\n/** @see Generated module for the real implementation. */\nexport const setLocale: (locale: string) => void = throwNotConfigured\n/** @see Generated module for the real implementation. */\nexport const getI18n: () => Promise<FluentiCoreInstanceFull & { locale: string }> = throwNotConfigured as () => Promise<FluentiCoreInstanceFull & { locale: string }>\n/** @see Generated module for the real implementation. */\nexport const t: CompileTimeT = throwNotConfigured as unknown as CompileTimeT\n/** @see Generated module for the real implementation. */\nexport const Trans: (props: { children: ReactNode; id?: string; context?: string; comment?: string; render?: (translation: ReactNode) => ReactNode }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof Trans\n/** @see Generated module for the real implementation. */\nexport const Plural: (props: { value: number; id?: string; context?: string; comment?: string; zero?: ReactNode; one?: ReactNode; two?: ReactNode; few?: ReactNode; many?: ReactNode; other: ReactNode; offset?: number }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof Plural\n/** @see Generated module for the real implementation. */\nexport const Select: (props: { value: string; id?: string; context?: string; comment?: string; other: ReactNode; options?: Record<string, ReactNode>; [key: string]: ReactNode | Record<string, ReactNode> | string | undefined }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof Select\n/** @see Generated module for the real implementation. */\nexport const DateTime: (props: { value: Date | number; style?: string }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof DateTime\n/** @see Generated module for the real implementation. */\nexport const NumberFormat: (props: { value: number; style?: string }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof NumberFormat\n/** @see Generated module for the real implementation. */\nexport const I18nProvider: (props: { locale?: string; children: ReactNode }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof I18nProvider\n"],"mappings":";;;;;;;;AASA,SAAgB,EACd,GACA,GACsB;CACtB,IAAI;AAEJ,CAKE,IALE,GAAW,UAAU,OAAO,EAAU,UAAW,WAEnC;EAAE,GAAG;EAAwB,GAAG,EAAU;EAAQ,GAGlD,EACd,OAAO,GAAW,UAAW,WAAW,EAAU,SAAS,KAAA,GAC3D,EACD;CAGH,IAAM,IAAqB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oK,GAEpK,IAAyO,GAEzO,IAAiP,GAEjP,IAAuF,GAEvF,IAAoF,GAEpF,IAA2F"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=`x-fluenti-locale`;function t(t){let{NextResponse:r}=t,i=t.locales??[`en`],a=t.sourceLocale??`en`,o=t.cookieName??`locale`,s=t.localePrefix??`as-needed`;return function(t){let c=i,l=a,{pathname:u}=t.nextUrl,d=u.split(`/`),f=d[1]??``,p=c.includes(f)?f:null,m;m=p||n(t,c,l,o);let h=new Headers(t.headers);if(h.set(e,m),!p&&(s===`always`||m!==l)){let n=new URL(`/${m}${u}${t.nextUrl.search}`,t.url),i=r.redirect(n);return i.headers.set(e,m),i}if(s===`as-needed`&&p===l){let n=`/`+d.slice(2).join(`/`),i=new URL(`${n}${t.nextUrl.search}`,t.url),a=r.rewrite(i,{request:{headers:h}});return a.headers.set(e,m),a}let g=r.next({request:{headers:h}});return g.headers.set(e,m),g}}function n(e,t,n,r){let i=e.cookies.get(r)?.value;if(i&&t.includes(i))return i;let a=e.headers.get(`accept-language`);if(a)for(let e of a.split(`,`)){let n=e.split(`;`)[0].trim();if(t.includes(n))return n;let r=n.split(`-`)[0],i=t.find(e=>e===r||e.startsWith(r+`-`));if(i)return i}return n}exports.LOCALE_HEADER=e,exports.createI18nMiddleware=t;
|
|
2
|
+
//# sourceMappingURL=middleware.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware.cjs","names":[],"sources":["../src/middleware.ts"],"sourcesContent":["/**\n * @module @fluenti/next/middleware\n *\n * Built-in i18n middleware for Next.js App Router.\n *\n * Uses `x-fluenti-locale` request header to pass locale from middleware to\n * server components — avoids `Set-Cookie` on every request (CDN-friendly).\n *\n * Cookie is only used to remember user preference (set by LocaleSwitcher).\n *\n * @example\n * ```ts\n * // src/middleware.ts\n * import { NextResponse } from 'next/server'\n * import { createI18nMiddleware } from '@fluenti/next/middleware'\n *\n * export default createI18nMiddleware({ NextResponse })\n *\n * export const config = {\n * matcher: ['/((?!_next|api|favicon).*)'],\n * }\n * ```\n *\n * @example Composing with Clerk\n * ```ts\n * import { NextResponse } from 'next/server'\n * import { clerkMiddleware } from '@clerk/nextjs/server'\n * import { createI18nMiddleware } from '@fluenti/next/middleware'\n *\n * const i18nMiddleware = createI18nMiddleware({ NextResponse })\n *\n * export default clerkMiddleware(async (auth, req) => {\n * await auth.protect()\n * return i18nMiddleware(req)\n * })\n * ```\n */\n\n/** Header name used to pass resolved locale from middleware to RSC */\nexport const LOCALE_HEADER = 'x-fluenti-locale'\n\nexport interface I18nMiddlewareConfig {\n /** Available locales. If omitted, reads from `fluenti.config.ts`. */\n locales?: string[]\n /** Source/default locale. If omitted, reads from `fluenti.config.ts`. */\n sourceLocale?: string\n /** Cookie name for reading user preference (default: 'locale') */\n cookieName?: string\n /**\n * Locale prefix strategy:\n * - `'always'`: all locales get a URL prefix (e.g. `/en/about`, `/fr/about`)\n * - `'as-needed'`: source locale has no prefix, others do (e.g. `/about`, `/fr/about`)\n *\n * Default: `'as-needed'`\n */\n localePrefix?: 'always' | 'as-needed'\n}\n\ntype NextRequest = {\n nextUrl: { pathname: string; search: string }\n url: string\n cookies: { get(name: string): { value: string } | undefined }\n headers: Headers\n}\n\ntype NextResponseStatic = {\n redirect(url: URL): NextResponseInstance\n rewrite(url: URL, init?: Record<string, unknown>): NextResponseInstance\n next(init?: Record<string, unknown>): NextResponseInstance\n}\n\ntype NextResponseInstance = {\n headers: { set(name: string, value: string): void }\n}\n\n/**\n * Create an i18n middleware function for Next.js.\n *\n * Requires `NextResponse` to be passed in because the middleware module runs\n * in Next.js Edge Runtime where `require('next/server')` is not available.\n *\n * @example\n * ```ts\n * import { NextResponse } from 'next/server'\n * import { createI18nMiddleware } from '@fluenti/next/middleware'\n *\n * export default createI18nMiddleware({ NextResponse })\n * ```\n *\n * @example With explicit locales\n * ```ts\n * import { NextResponse } from 'next/server'\n * import { createI18nMiddleware } from '@fluenti/next/middleware'\n *\n * export default createI18nMiddleware({\n * NextResponse,\n * locales: ['en', 'ja', 'zh-CN'],\n * sourceLocale: 'en',\n * })\n * ```\n */\nexport function createI18nMiddleware(config: I18nMiddlewareConfig & { NextResponse: NextResponseStatic }) {\n const { NextResponse } = config\n const resolvedLocales: string[] = config.locales ?? ['en']\n const resolvedSourceLocale: string = config.sourceLocale ?? 'en'\n const cookieName = config.cookieName ?? 'locale'\n const localePrefix = config.localePrefix ?? 'as-needed'\n\n return function i18nMiddleware(request: NextRequest) {\n const locales = resolvedLocales\n const sourceLocale = resolvedSourceLocale\n const { pathname } = request.nextUrl\n\n // Extract locale from URL path\n // Note: request.nextUrl.pathname already strips basePath (Next.js behavior)\n const segments = pathname.split('/')\n const firstSegment = segments[1] ?? ''\n const pathLocale = locales.includes(firstSegment) ? firstSegment : null\n\n // Determine the active locale\n let locale: string\n\n if (pathLocale) {\n locale = pathLocale\n } else {\n // No locale in path — detect from cookie → Accept-Language → default\n locale = detectLocale(request, locales, sourceLocale, cookieName)\n }\n\n // Build new request headers preserving originals (auth headers, etc.)\n const requestHeaders = new Headers(request.headers)\n requestHeaders.set(LOCALE_HEADER, locale)\n\n // Case 1: No locale in path → redirect to /{locale}{path}\n // In 'always' mode: redirect all bare paths (including source locale)\n // In 'as-needed' mode: only redirect non-source locales\n if (!pathLocale && (localePrefix === 'always' || locale !== sourceLocale)) {\n const redirectUrl = new URL(\n `/${locale}${pathname}${request.nextUrl.search}`,\n request.url,\n )\n const response = NextResponse.redirect(redirectUrl)\n response.headers.set(LOCALE_HEADER, locale)\n return response\n }\n\n // Case 2: as-needed mode, default locale has prefix → rewrite without prefix\n if (localePrefix === 'as-needed' && pathLocale === sourceLocale) {\n const pathWithoutLocale = '/' + segments.slice(2).join('/')\n const rewriteUrl = new URL(\n `${pathWithoutLocale}${request.nextUrl.search}`,\n request.url,\n )\n const response = NextResponse.rewrite(rewriteUrl, {\n request: { headers: requestHeaders },\n })\n response.headers.set(LOCALE_HEADER, locale)\n return response\n }\n\n // Case 3: No locale in path, source locale → pass through with header\n // Case 4: Non-default locale with correct prefix → pass through\n const response = NextResponse.next({\n request: { headers: requestHeaders },\n })\n response.headers.set(LOCALE_HEADER, locale)\n\n return response\n }\n}\n\n/**\n * Detect locale from request: cookie → Accept-Language → default.\n */\nfunction detectLocale(\n request: NextRequest,\n locales: string[],\n defaultLocale: string,\n cookieName: string,\n): string {\n // 1. Cookie (user preference)\n const cookieLocale = request.cookies.get(cookieName)?.value\n if (cookieLocale && locales.includes(cookieLocale)) {\n return cookieLocale\n }\n\n // 2. Accept-Language header\n const acceptLang = request.headers.get('accept-language')\n if (acceptLang) {\n for (const part of acceptLang.split(',')) {\n const lang = part.split(';')[0]!.trim()\n if (locales.includes(lang)) return lang\n const prefix = lang.split('-')[0]!\n const match = locales.find(l => l === prefix || l.startsWith(prefix + '-'))\n if (match) return match\n }\n }\n\n // 3. Default\n return defaultLocale\n}\n"],"mappings":"mEAuCA,IAAa,EAAgB,mBA8D7B,SAAgB,EAAqB,EAAqE,CACxG,GAAM,CAAE,gBAAiB,EACnB,EAA4B,EAAO,SAAW,CAAC,KAAK,CACpD,EAA+B,EAAO,cAAgB,KACtD,EAAa,EAAO,YAAc,SAClC,EAAe,EAAO,cAAgB,YAE5C,OAAO,SAAwB,EAAsB,CACnD,IAAM,EAAU,EACV,EAAe,EACf,CAAE,YAAa,EAAQ,QAIvB,EAAW,EAAS,MAAM,IAAI,CAC9B,EAAe,EAAS,IAAM,GAC9B,EAAa,EAAQ,SAAS,EAAa,CAAG,EAAe,KAG/D,EAEJ,AAIE,EAJE,GAIO,EAAa,EAAS,EAAS,EAAc,EAAW,CAInE,IAAM,EAAiB,IAAI,QAAQ,EAAQ,QAAQ,CAMnD,GALA,EAAe,IAAI,EAAe,EAAO,CAKrC,CAAC,IAAe,IAAiB,UAAY,IAAW,GAAe,CACzE,IAAM,EAAc,IAAI,IACtB,IAAI,IAAS,IAAW,EAAQ,QAAQ,SACxC,EAAQ,IACT,CACK,EAAW,EAAa,SAAS,EAAY,CAEnD,OADA,EAAS,QAAQ,IAAI,EAAe,EAAO,CACpC,EAIT,GAAI,IAAiB,aAAe,IAAe,EAAc,CAC/D,IAAM,EAAoB,IAAM,EAAS,MAAM,EAAE,CAAC,KAAK,IAAI,CACrD,EAAa,IAAI,IACrB,GAAG,IAAoB,EAAQ,QAAQ,SACvC,EAAQ,IACT,CACK,EAAW,EAAa,QAAQ,EAAY,CAChD,QAAS,CAAE,QAAS,EAAgB,CACrC,CAAC,CAEF,OADA,EAAS,QAAQ,IAAI,EAAe,EAAO,CACpC,EAKT,IAAM,EAAW,EAAa,KAAK,CACjC,QAAS,CAAE,QAAS,EAAgB,CACrC,CAAC,CAGF,OAFA,EAAS,QAAQ,IAAI,EAAe,EAAO,CAEpC,GAOX,SAAS,EACP,EACA,EACA,EACA,EACQ,CAER,IAAM,EAAe,EAAQ,QAAQ,IAAI,EAAW,EAAE,MACtD,GAAI,GAAgB,EAAQ,SAAS,EAAa,CAChD,OAAO,EAIT,IAAM,EAAa,EAAQ,QAAQ,IAAI,kBAAkB,CACzD,GAAI,EACF,IAAK,IAAM,KAAQ,EAAW,MAAM,IAAI,CAAE,CACxC,IAAM,EAAO,EAAK,MAAM,IAAI,CAAC,GAAI,MAAM,CACvC,GAAI,EAAQ,SAAS,EAAK,CAAE,OAAO,EACnC,IAAM,EAAS,EAAK,MAAM,IAAI,CAAC,GACzB,EAAQ,EAAQ,KAAK,GAAK,IAAM,GAAU,EAAE,WAAW,EAAS,IAAI,CAAC,CAC3E,GAAI,EAAO,OAAO,EAKtB,OAAO"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
//#region src/middleware.ts
|
|
2
|
+
var e = "x-fluenti-locale";
|
|
3
|
+
function t(t) {
|
|
4
|
+
let { NextResponse: r } = t, i = t.locales ?? ["en"], a = t.sourceLocale ?? "en", o = t.cookieName ?? "locale", s = t.localePrefix ?? "as-needed";
|
|
5
|
+
return function(t) {
|
|
6
|
+
let c = i, l = a, { pathname: u } = t.nextUrl, d = u.split("/"), f = d[1] ?? "", p = c.includes(f) ? f : null, m;
|
|
7
|
+
m = p || n(t, c, l, o);
|
|
8
|
+
let h = new Headers(t.headers);
|
|
9
|
+
if (h.set(e, m), !p && (s === "always" || m !== l)) {
|
|
10
|
+
let n = new URL(`/${m}${u}${t.nextUrl.search}`, t.url), i = r.redirect(n);
|
|
11
|
+
return i.headers.set(e, m), i;
|
|
12
|
+
}
|
|
13
|
+
if (s === "as-needed" && p === l) {
|
|
14
|
+
let n = "/" + d.slice(2).join("/"), i = new URL(`${n}${t.nextUrl.search}`, t.url), a = r.rewrite(i, { request: { headers: h } });
|
|
15
|
+
return a.headers.set(e, m), a;
|
|
16
|
+
}
|
|
17
|
+
let g = r.next({ request: { headers: h } });
|
|
18
|
+
return g.headers.set(e, m), g;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
function n(e, t, n, r) {
|
|
22
|
+
let i = e.cookies.get(r)?.value;
|
|
23
|
+
if (i && t.includes(i)) return i;
|
|
24
|
+
let a = e.headers.get("accept-language");
|
|
25
|
+
if (a) for (let e of a.split(",")) {
|
|
26
|
+
let n = e.split(";")[0].trim();
|
|
27
|
+
if (t.includes(n)) return n;
|
|
28
|
+
let r = n.split("-")[0], i = t.find((e) => e === r || e.startsWith(r + "-"));
|
|
29
|
+
if (i) return i;
|
|
30
|
+
}
|
|
31
|
+
return n;
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
export { e as LOCALE_HEADER, t as createI18nMiddleware };
|
|
35
|
+
|
|
36
|
+
//# sourceMappingURL=middleware.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware.js","names":[],"sources":["../src/middleware.ts"],"sourcesContent":["/**\n * @module @fluenti/next/middleware\n *\n * Built-in i18n middleware for Next.js App Router.\n *\n * Uses `x-fluenti-locale` request header to pass locale from middleware to\n * server components — avoids `Set-Cookie` on every request (CDN-friendly).\n *\n * Cookie is only used to remember user preference (set by LocaleSwitcher).\n *\n * @example\n * ```ts\n * // src/middleware.ts\n * import { NextResponse } from 'next/server'\n * import { createI18nMiddleware } from '@fluenti/next/middleware'\n *\n * export default createI18nMiddleware({ NextResponse })\n *\n * export const config = {\n * matcher: ['/((?!_next|api|favicon).*)'],\n * }\n * ```\n *\n * @example Composing with Clerk\n * ```ts\n * import { NextResponse } from 'next/server'\n * import { clerkMiddleware } from '@clerk/nextjs/server'\n * import { createI18nMiddleware } from '@fluenti/next/middleware'\n *\n * const i18nMiddleware = createI18nMiddleware({ NextResponse })\n *\n * export default clerkMiddleware(async (auth, req) => {\n * await auth.protect()\n * return i18nMiddleware(req)\n * })\n * ```\n */\n\n/** Header name used to pass resolved locale from middleware to RSC */\nexport const LOCALE_HEADER = 'x-fluenti-locale'\n\nexport interface I18nMiddlewareConfig {\n /** Available locales. If omitted, reads from `fluenti.config.ts`. */\n locales?: string[]\n /** Source/default locale. If omitted, reads from `fluenti.config.ts`. */\n sourceLocale?: string\n /** Cookie name for reading user preference (default: 'locale') */\n cookieName?: string\n /**\n * Locale prefix strategy:\n * - `'always'`: all locales get a URL prefix (e.g. `/en/about`, `/fr/about`)\n * - `'as-needed'`: source locale has no prefix, others do (e.g. `/about`, `/fr/about`)\n *\n * Default: `'as-needed'`\n */\n localePrefix?: 'always' | 'as-needed'\n}\n\ntype NextRequest = {\n nextUrl: { pathname: string; search: string }\n url: string\n cookies: { get(name: string): { value: string } | undefined }\n headers: Headers\n}\n\ntype NextResponseStatic = {\n redirect(url: URL): NextResponseInstance\n rewrite(url: URL, init?: Record<string, unknown>): NextResponseInstance\n next(init?: Record<string, unknown>): NextResponseInstance\n}\n\ntype NextResponseInstance = {\n headers: { set(name: string, value: string): void }\n}\n\n/**\n * Create an i18n middleware function for Next.js.\n *\n * Requires `NextResponse` to be passed in because the middleware module runs\n * in Next.js Edge Runtime where `require('next/server')` is not available.\n *\n * @example\n * ```ts\n * import { NextResponse } from 'next/server'\n * import { createI18nMiddleware } from '@fluenti/next/middleware'\n *\n * export default createI18nMiddleware({ NextResponse })\n * ```\n *\n * @example With explicit locales\n * ```ts\n * import { NextResponse } from 'next/server'\n * import { createI18nMiddleware } from '@fluenti/next/middleware'\n *\n * export default createI18nMiddleware({\n * NextResponse,\n * locales: ['en', 'ja', 'zh-CN'],\n * sourceLocale: 'en',\n * })\n * ```\n */\nexport function createI18nMiddleware(config: I18nMiddlewareConfig & { NextResponse: NextResponseStatic }) {\n const { NextResponse } = config\n const resolvedLocales: string[] = config.locales ?? ['en']\n const resolvedSourceLocale: string = config.sourceLocale ?? 'en'\n const cookieName = config.cookieName ?? 'locale'\n const localePrefix = config.localePrefix ?? 'as-needed'\n\n return function i18nMiddleware(request: NextRequest) {\n const locales = resolvedLocales\n const sourceLocale = resolvedSourceLocale\n const { pathname } = request.nextUrl\n\n // Extract locale from URL path\n // Note: request.nextUrl.pathname already strips basePath (Next.js behavior)\n const segments = pathname.split('/')\n const firstSegment = segments[1] ?? ''\n const pathLocale = locales.includes(firstSegment) ? firstSegment : null\n\n // Determine the active locale\n let locale: string\n\n if (pathLocale) {\n locale = pathLocale\n } else {\n // No locale in path — detect from cookie → Accept-Language → default\n locale = detectLocale(request, locales, sourceLocale, cookieName)\n }\n\n // Build new request headers preserving originals (auth headers, etc.)\n const requestHeaders = new Headers(request.headers)\n requestHeaders.set(LOCALE_HEADER, locale)\n\n // Case 1: No locale in path → redirect to /{locale}{path}\n // In 'always' mode: redirect all bare paths (including source locale)\n // In 'as-needed' mode: only redirect non-source locales\n if (!pathLocale && (localePrefix === 'always' || locale !== sourceLocale)) {\n const redirectUrl = new URL(\n `/${locale}${pathname}${request.nextUrl.search}`,\n request.url,\n )\n const response = NextResponse.redirect(redirectUrl)\n response.headers.set(LOCALE_HEADER, locale)\n return response\n }\n\n // Case 2: as-needed mode, default locale has prefix → rewrite without prefix\n if (localePrefix === 'as-needed' && pathLocale === sourceLocale) {\n const pathWithoutLocale = '/' + segments.slice(2).join('/')\n const rewriteUrl = new URL(\n `${pathWithoutLocale}${request.nextUrl.search}`,\n request.url,\n )\n const response = NextResponse.rewrite(rewriteUrl, {\n request: { headers: requestHeaders },\n })\n response.headers.set(LOCALE_HEADER, locale)\n return response\n }\n\n // Case 3: No locale in path, source locale → pass through with header\n // Case 4: Non-default locale with correct prefix → pass through\n const response = NextResponse.next({\n request: { headers: requestHeaders },\n })\n response.headers.set(LOCALE_HEADER, locale)\n\n return response\n }\n}\n\n/**\n * Detect locale from request: cookie → Accept-Language → default.\n */\nfunction detectLocale(\n request: NextRequest,\n locales: string[],\n defaultLocale: string,\n cookieName: string,\n): string {\n // 1. Cookie (user preference)\n const cookieLocale = request.cookies.get(cookieName)?.value\n if (cookieLocale && locales.includes(cookieLocale)) {\n return cookieLocale\n }\n\n // 2. Accept-Language header\n const acceptLang = request.headers.get('accept-language')\n if (acceptLang) {\n for (const part of acceptLang.split(',')) {\n const lang = part.split(';')[0]!.trim()\n if (locales.includes(lang)) return lang\n const prefix = lang.split('-')[0]!\n const match = locales.find(l => l === prefix || l.startsWith(prefix + '-'))\n if (match) return match\n }\n }\n\n // 3. Default\n return defaultLocale\n}\n"],"mappings":";AAuCA,IAAa,IAAgB;AA8D7B,SAAgB,EAAqB,GAAqE;CACxG,IAAM,EAAE,oBAAiB,GACnB,IAA4B,EAAO,WAAW,CAAC,KAAK,EACpD,IAA+B,EAAO,gBAAgB,MACtD,IAAa,EAAO,cAAc,UAClC,IAAe,EAAO,gBAAgB;AAE5C,QAAO,SAAwB,GAAsB;EACnD,IAAM,IAAU,GACV,IAAe,GACf,EAAE,gBAAa,EAAQ,SAIvB,IAAW,EAAS,MAAM,IAAI,EAC9B,IAAe,EAAS,MAAM,IAC9B,IAAa,EAAQ,SAAS,EAAa,GAAG,IAAe,MAG/D;AAEJ,EAIE,IAJE,KAIO,EAAa,GAAS,GAAS,GAAc,EAAW;EAInE,IAAM,IAAiB,IAAI,QAAQ,E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client";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require(`@fluenti/react`),t=require(`next/navigation`);function n(e,t,n){let r=n?.sourceLocale??`en`,i=e.split(`/`),a=i[1]??``,o=(n?.locales?n.locales.includes(a):/^[a-z]{2}(-[A-Za-z]{2,})?$/.test(a))?`/`+i.slice(2).join(`/`):e;return t===r?o||`/`:`/${t}${o}`}function r(r){let i=(0,t.useRouter)(),a=(0,t.usePathname)(),{locale:o,setLocale:s,getLocales:c}=(0,e.useI18n)(),l=c(),u=r?.sourceLocale??l[0]??`en`;return{switchLocale:e=>{document.cookie=`locale=${e};path=/;max-age=31536000;samesite=lax`,s(e);let t=n(a,e,{sourceLocale:u,locales:l});i.push(t),i.refresh()},currentLocale:o,locales:l,sourceLocale:u}}exports.getLocalePath=n,exports.useLocaleSwitcher=r;
|
|
3
|
+
//# sourceMappingURL=navigation.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"navigation.cjs","names":[],"sources":["../src/navigation.ts"],"sourcesContent":["'use client'\n\n/**\n * @module @fluenti/next/navigation\n *\n * Navigation utilities for locale-aware routing in Next.js App Router.\n *\n * @example\n * ```tsx\n * import { useLocaleSwitcher } from '@fluenti/next/navigation'\n *\n * function LanguagePicker() {\n * const { switchLocale, currentLocale, locales } = useLocaleSwitcher()\n * return (\n * <select value={currentLocale} onChange={(e) => switchLocale(e.target.value)}>\n * {locales.map((l) => <option key={l} value={l}>{l}</option>)}\n * </select>\n * )\n * }\n * ```\n */\nimport { useRouter, usePathname } from 'next/navigation'\nimport { useI18n } from '@fluenti/react'\n\nexport interface GetLocalePathOptions {\n /** Source/default locale (no prefix in as-needed mode) */\n sourceLocale?: string\n /**\n * Known locale codes (e.g. ['en', 'fr', 'ja']).\n * When provided, the existing prefix is only stripped when it's an actual locale —\n * preventing false matches on generic 2-letter path segments like /my or /us.\n */\n locales?: string[]\n}\n\n/**\n * Get the locale-prefixed path for a given pathname and locale.\n *\n * Pure function — works on both server and client.\n *\n * @example\n * ```ts\n * getLocalePath('/about', 'fr') // → '/fr/about'\n * getLocalePath('/about', 'en') // → '/about' (source locale, no prefix)\n * getLocalePath('/fr/about', 'en') // → '/about'\n * getLocalePath('/fr/about', 'ja') // → '/ja/about'\n * ```\n */\nexport function getLocalePath(\n pathname: string,\n locale: string,\n options?: GetLocalePathOptions,\n): string {\n const sourceLocale = options?.sourceLocale ?? 'en'\n\n // Strip existing locale prefix if present\n const segments = pathname.split('/')\n const firstSegment = segments[1] ?? ''\n\n // Check if the first segment is a locale prefix.\n // If a locales list is provided, do an exact membership check to avoid false positives\n // on generic 2-letter path segments (e.g. /my/page or /us/pricing).\n // Otherwise fall back to the heuristic regex.\n const hasLocalePrefix = options?.locales\n ? options.locales.includes(firstSegment)\n : /^[a-z]{2}(-[A-Za-z]{2,})?$/.test(firstSegment)\n const pathWithoutLocale = hasLocalePrefix\n ? '/' + segments.slice(2).join('/')\n : pathname\n\n // Source locale gets no prefix (as-needed mode)\n if (locale === sourceLocale) {\n return pathWithoutLocale || '/'\n }\n\n return `/${locale}${pathWithoutLocale}`\n}\n\n/**\n * Hook for switching locales in Next.js App Router.\n *\n * Sets a cookie to remember user preference, navigates to the new locale path,\n * and triggers a server component refresh.\n */\nexport function useLocaleSwitcher(options?: {\n /** Override the source/default locale instead of inferring from locales[0]. */\n sourceLocale?: string\n}) {\n const router = useRouter()\n const pathname = usePathname()\n const { locale, setLocale, getLocales } = useI18n()\n\n // Read locales from I18nProvider context (works on client without fs)\n const locales = getLocales()\n const sourceLocale = options?.sourceLocale ?? locales[0] ?? 'en'\n\n const switchLocale = (newLocale: string) => {\n // 1. Set cookie to remember preference\n document.cookie = `locale=${newLocale};path=/;max-age=31536000;samesite=lax`\n // 2. Update React context\n setLocale(newLocale)\n // 3. Navigate to new locale path\n const newPath = getLocalePath(pathname, newLocale, { sourceLocale, locales })\n router.push(newPath)\n // 4. Refresh server components\n router.refresh()\n }\n\n return {\n switchLocale,\n currentLocale: locale,\n locales,\n sourceLocale,\n }\n}\n"],"mappings":"6IAgDA,SAAgB,EACd,EACA,EACA,EACQ,CACR,IAAM,EAAe,GAAS,cAAgB,KAGxC,EAAW,EAAS,MAAM,IAAI,CAC9B,EAAe,EAAS,IAAM,GAS9B,GAHkB,GAAS,QAC7B,EAAQ,QAAQ,SAAS,EAAa,CACtC,6BAA6B,KAAK,EAAa,EAE/C,IAAM,EAAS,MAAM,EAAE,CAAC,KAAK,IAAI,CACjC,EAOJ,OAJI,IAAW,EACN,GAAqB,IAGvB,IAAI,IAAS,IAStB,SAAgB,EAAkB,EAG/B,CACD,IAAM,GAAA,EAAA,EAAA,YAAoB,CACpB,GAAA,EAAA,EAAA,cAAwB,CACxB,CAAE,SAAQ,YAAW,eAAA,EAAA,EAAA,UAAwB,CAG7C,EAAU,GAAY,CACtB,EAAe,GAAS,cAAgB,EAAQ,IAAM,KAc5D,MAAO,CACL,aAboB,GAAsB,CAE1C,SAAS,OAAS,UAAU,EAAU,uCAEtC,EAAU,EAAU,CAEpB,IAAM,EAAU,EAAc,EAAU,EAAW,CAAE,eAAc,UAAS,CAAC,CAC7E,EAAO,KAAK,EAAQ,CAEpB,EAAO,SAAS,EAKhB,cAAe,EACf,UACA,eACD"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
"use client";
|
|
3
|
+
import { useI18n as e } from "@fluenti/react";
|
|
4
|
+
import { usePathname as t, useRouter as n } from "next/navigation";
|
|
5
|
+
//#region src/navigation.ts
|
|
6
|
+
function r(e, t, n) {
|
|
7
|
+
let r = n?.sourceLocale ?? "en", i = e.split("/"), a = i[1] ?? "", o = (n?.locales ? n.locales.includes(a) : /^[a-z]{2}(-[A-Za-z]{2,})?$/.test(a)) ? "/" + i.slice(2).join("/") : e;
|
|
8
|
+
return t === r ? o || "/" : `/${t}${o}`;
|
|
9
|
+
}
|
|
10
|
+
function i(i) {
|
|
11
|
+
let a = n(), o = t(), { locale: s, setLocale: c, getLocales: l } = e(), u = l(), d = i?.sourceLocale ?? u[0] ?? "en";
|
|
12
|
+
return {
|
|
13
|
+
switchLocale: (e) => {
|
|
14
|
+
document.cookie = `locale=${e};path=/;max-age=31536000;samesite=lax`, c(e);
|
|
15
|
+
let t = r(o, e, {
|
|
16
|
+
sourceLocale: d,
|
|
17
|
+
locales: u
|
|
18
|
+
});
|
|
19
|
+
a.push(t), a.refresh();
|
|
20
|
+
},
|
|
21
|
+
currentLocale: s,
|
|
22
|
+
locales: u,
|
|
23
|
+
sourceLocale: d
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
//#endregion
|
|
27
|
+
export { r as getLocalePath, i as useLocaleSwitcher };
|
|
28
|
+
|
|
29
|
+
//# sourceMappingURL=navigation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"navigation.js","names":[],"sources":["../src/navigation.ts"],"sourcesContent":["'use client'\n\n/**\n * @module @fluenti/next/navigation\n *\n * Navigation utilities for locale-aware routing in Next.js App Router.\n *\n * @example\n * ```tsx\n * import { useLocaleSwitcher } from '@fluenti/next/navigation'\n *\n * function LanguagePicker() {\n * const { switchLocale, currentLocale, locales } = useLocaleSwitcher()\n * return (\n * <select value={currentLocale} onChange={(e) => switchLocale(e.target.value)}>\n * {locales.map((l) => <option key={l} value={l}>{l}</option>)}\n * </select>\n * )\n * }\n * ```\n */\nimport { useRouter, usePathname } from 'next/navigation'\nimport { useI18n } from '@fluenti/react'\n\nexport interface GetLocalePathOptions {\n /** Source/default locale (no prefix in as-needed mode) */\n sourceLocale?: string\n /**\n * Known locale codes (e.g. ['en', 'fr', 'ja']).\n * When provided, the existing prefix is only stripped when it's an actual locale —\n * preventing false matches on generic 2-letter path segments like /my or /us.\n */\n locales?: string[]\n}\n\n/**\n * Get the locale-prefixed path for a given pathname and locale.\n *\n * Pure function — works on both server and client.\n *\n * @example\n * ```ts\n * getLocalePath('/about', 'fr') // → '/fr/about'\n * getLocalePath('/about', 'en') // → '/about' (source locale, no prefix)\n * getLocalePath('/fr/about', 'en') // → '/about'\n * getLocalePath('/fr/about', 'ja') // → '/ja/about'\n * ```\n */\nexport function getLocalePath(\n pathname: string,\n locale: string,\n options?: GetLocalePathOptions,\n): string {\n const sourceLocale = options?.sourceLocale ?? 'en'\n\n // Strip existing locale prefix if present\n const segments = pathname.split('/')\n const firstSegment = segments[1] ?? ''\n\n // Check if the first segment is a locale prefix.\n // If a locales list is provided, do an exact membership check to avoid false positives\n // on generic 2-letter path segments (e.g. /my/page or /us/pricing).\n // Otherwise fall back to the heuristic regex.\n const hasLocalePrefix = options?.locales\n ? options.locales.includes(firstSegment)\n : /^[a-z]{2}(-[A-Za-z]{2,})?$/.test(firstSegment)\n const pathWithoutLocale = hasLocalePrefix\n ? '/' + segments.slice(2).join('/')\n : pathname\n\n // Source locale gets no prefix (as-needed mode)\n if (locale === sourceLocale) {\n return pathWithoutLocale || '/'\n }\n\n return `/${locale}${pathWithoutLocale}`\n}\n\n/**\n * Hook for switching locales in Next.js App Router.\n *\n * Sets a cookie to remember user preference, navigates to the new locale path,\n * and triggers a server component refresh.\n */\nexport function useLocaleSwitcher(options?: {\n /** Override the source/default locale instead of inferring from locales[0]. */\n sourceLocale?: string\n}) {\n const router = useRouter()\n const pathname = usePathname()\n const { locale, setLocale, getLocales } = useI18n()\n\n // Read locales from I18nProvider context (works on client without fs)\n const locales = getLocales()\n const sourceLocale = options?.sourceLocale ?? locales[0] ?? 'en'\n\n const switchLocale = (newLocale: string) => {\n // 1. Set cookie to remember preference\n document.cookie = `locale=${newLocale};path=/;max-age=31536000;samesite=lax`\n // 2. Update React context\n setLocale(newLocale)\n // 3. Navigate to new locale path\n const newPath = getLocalePath(pathname, newLocale, { sourceLocale, locales })\n router.push(newPath)\n // 4. Refresh server components\n router.refresh()\n }\n\n return {\n switchLocale,\n currentLocale: locale,\n locales,\n sourceLocale,\n }\n}\n"],"mappings":";;;;AAgDA,SAAgB,EACd,GACA,GACA,GACQ;CACR,IAAM,IAAe,GAAS,gBAAgB,MAGxC,IAAW,EAAS,MAAM,IAAI,EAC9B,IAAe,EAAS,MAAM,IAS9B,KAHkB,GAAS,UAC7B,EAAQ,QAAQ,SAAS,EAAa,GACtC,6BAA6B,KAAK,EAAa,IAE/C,MAAM,EAAS,MAAM,EAAE,CAAC,KAAK,IAAI,GACjC;AAOJ,QAJI,MAAW,IACN,KAAqB,MAGvB,IAAI,IAAS;;AAStB,SAAgB,EAAkB,GAG/B;CACD,IAAM,IAAS,GAAW,EACpB,IAAW,GAAa,EACxB,EAAE,WAAQ,cAAW,kBAAe,GAAS,EAG7C,IAAU,GAAY,EACtB,IAAe,GAAS,gBAAgB,EAAQ,MAAM;AAc5D,QAAO;EACL,eAboB,MAAsB;AAI1C,GAFA,SAAS,SAAS,UAAU,EAAU,wCAEtC,EAAU,EAAU;GAEpB,IAAM,IAAU,EAAc,GAAU,GAAW;IAAE;IAAc;IAAS,CAAC;AAG7E,GAFA,EAAO,KAAK,EAAQ,EAEpB,EAAO,SAAS;;EAKhB,eAAe;EACf;EACA;EACD"}
|
package/dist/provider.cjs
CHANGED
|
@@ -1,8 +1,3 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});
|
|
3
|
-
let props = %s;
|
|
4
|
-
<%s {...props} />
|
|
5
|
-
React keys must be passed directly to JSX without using spread:
|
|
6
|
-
let props = %s;
|
|
7
|
-
<%s key={someKey} {...props} />`,o,p,m,p),L[p+o]=!0)}if(p=null,i!==void 0&&(r(i),p=``+i),s(n)&&(r(n.key),p=``+n.key),`key`in n)for(var h in i={},n)h!==`key`&&(i[h]=n[h]);else i=n;return p&&c(i,typeof e==`function`?e.displayName||e.name||`Unknown`:e),u(e,p,i,a(),l,d)}function f(e){p(e)?e._store&&(e._store.validated=1):typeof e==`object`&&e&&e.$$typeof===E&&(e._payload.status===`fulfilled`?p(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function p(e){return typeof e==`object`&&!!e&&e.$$typeof===h}var m=require(`react`),h=Symbol.for(`react.transitional.element`),g=Symbol.for(`react.portal`),_=Symbol.for(`react.fragment`),v=Symbol.for(`react.strict_mode`),y=Symbol.for(`react.profiler`),b=Symbol.for(`react.consumer`),x=Symbol.for(`react.context`),S=Symbol.for(`react.forward_ref`),C=Symbol.for(`react.suspense`),w=Symbol.for(`react.suspense_list`),T=Symbol.for(`react.memo`),E=Symbol.for(`react.lazy`),D=Symbol.for(`react.activity`),O=Symbol.for(`react.client.reference`),k=m.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,A=Object.prototype.hasOwnProperty,j=Array.isArray,M=console.createTask?console.createTask:function(){return null};m={react_stack_bottom_frame:function(e){return e()}};var N,P={},F=m.react_stack_bottom_frame.bind(m,o)(),I=M(i(o)),L={};e.Fragment=_,e.jsx=function(e,t,n){var r=1e4>k.recentlyCreatedOwnerStacks++;return d(e,t,n,!1,r?Error(`react-stack-top-frame`):F,r?M(i(e)):I)},e.jsxs=function(e,t,n){var r=1e4>k.recentlyCreatedOwnerStacks++;return d(e,t,n,!0,r?Error(`react-stack-top-frame`):F,r?M(i(e)):I)}})()})),i=e(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=n():t.exports=r()}))();function a({locale:e,fallbackLocale:n,messages:r,fallbackChain:a,dateFormats:o,numberFormats:s,children:c}){return(0,i.jsx)(t.I18nProvider,{locale:e,fallbackLocale:n,messages:r,...a?{fallbackChain:a}:{},...o?{dateFormats:o}:{},...s?{numberFormats:s}:{},children:c})}exports.I18nProvider=a;
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require(`@fluenti/react`),t=require(`react/jsx-runtime`);function n({locale:n,fallbackLocale:r,messages:i,fallbackChain:a,dateFormats:o,numberFormats:s,children:c}){return(0,t.jsx)(e.I18nProvider,{locale:n,fallbackLocale:r,messages:i,...a?{fallbackChain:a}:{},...o?{dateFormats:o}:{},...s?{numberFormats:s}:{},children:c})}exports.I18nProvider=n;
|
|
8
3
|
//# sourceMappingURL=provider.cjs.map
|
package/dist/provider.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider.cjs","names":[],"sources":["../../../node_modules/.pnpm/react@19.2.4/node_modules/react/cjs/react-jsx-runtime.production.js","../../../node_modules/.pnpm/react@19.2.4/node_modules/react/cjs/react-jsx-runtime.development.js","../../../node_modules/.pnpm/react@19.2.4/node_modules/react/jsx-runtime.js","../src/client-provider.tsx"],"sourcesContent":["/**\n * @license React\n * react-jsx-runtime.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\");\nfunction jsxProd(type, config, maybeKey) {\n var key = null;\n void 0 !== maybeKey && (key = \"\" + maybeKey);\n void 0 !== config.key && (key = \"\" + config.key);\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n config = maybeKey.ref;\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n ref: void 0 !== config ? config : null,\n props: maybeKey\n };\n}\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsxProd;\nexports.jsxs = jsxProd;\n","/**\n * @license React\n * react-jsx-runtime.development.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\n\"production\" !== process.env.NODE_ENV &&\n (function () {\n function getComponentNameFromType(type) {\n if (null == type) return null;\n if (\"function\" === typeof type)\n return type.$$typeof === REACT_CLIENT_REFERENCE\n ? null\n : type.displayName || type.name || null;\n if (\"string\" === typeof type) return type;\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return \"Fragment\";\n case REACT_PROFILER_TYPE:\n return \"Profiler\";\n case REACT_STRICT_MODE_TYPE:\n return \"StrictMode\";\n case REACT_SUSPENSE_TYPE:\n return \"Suspense\";\n case REACT_SUSPENSE_LIST_TYPE:\n return \"SuspenseList\";\n case REACT_ACTIVITY_TYPE:\n return \"Activity\";\n }\n if (\"object\" === typeof type)\n switch (\n (\"number\" === typeof type.tag &&\n console.error(\n \"Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.\"\n ),\n type.$$typeof)\n ) {\n case REACT_PORTAL_TYPE:\n return \"Portal\";\n case REACT_CONTEXT_TYPE:\n return type.displayName || \"Context\";\n case REACT_CONSUMER_TYPE:\n return (type._context.displayName || \"Context\") + \".Consumer\";\n case REACT_FORWARD_REF_TYPE:\n var innerType = type.render;\n type = type.displayName;\n type ||\n ((type = innerType.displayName || innerType.name || \"\"),\n (type = \"\" !== type ? \"ForwardRef(\" + type + \")\" : \"ForwardRef\"));\n return type;\n case REACT_MEMO_TYPE:\n return (\n (innerType = type.displayName || null),\n null !== innerType\n ? innerType\n : getComponentNameFromType(type.type) || \"Memo\"\n );\n case REACT_LAZY_TYPE:\n innerType = type._payload;\n type = type._init;\n try {\n return getComponentNameFromType(type(innerType));\n } catch (x) {}\n }\n return null;\n }\n function testStringCoercion(value) {\n return \"\" + value;\n }\n function checkKeyStringCoercion(value) {\n try {\n testStringCoercion(value);\n var JSCompiler_inline_result = !1;\n } catch (e) {\n JSCompiler_inline_result = !0;\n }\n if (JSCompiler_inline_result) {\n JSCompiler_inline_result = console;\n var JSCompiler_temp_const = JSCompiler_inline_result.error;\n var JSCompiler_inline_result$jscomp$0 =\n (\"function\" === typeof Symbol &&\n Symbol.toStringTag &&\n value[Symbol.toStringTag]) ||\n value.constructor.name ||\n \"Object\";\n JSCompiler_temp_const.call(\n JSCompiler_inline_result,\n \"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.\",\n JSCompiler_inline_result$jscomp$0\n );\n return testStringCoercion(value);\n }\n }\n function getTaskName(type) {\n if (type === REACT_FRAGMENT_TYPE) return \"<>\";\n if (\n \"object\" === typeof type &&\n null !== type &&\n type.$$typeof === REACT_LAZY_TYPE\n )\n return \"<...>\";\n try {\n var name = getComponentNameFromType(type);\n return name ? \"<\" + name + \">\" : \"<...>\";\n } catch (x) {\n return \"<...>\";\n }\n }\n function getOwner() {\n var dispatcher = ReactSharedInternals.A;\n return null === dispatcher ? null : dispatcher.getOwner();\n }\n function UnknownOwner() {\n return Error(\"react-stack-top-frame\");\n }\n function hasValidKey(config) {\n if (hasOwnProperty.call(config, \"key\")) {\n var getter = Object.getOwnPropertyDescriptor(config, \"key\").get;\n if (getter && getter.isReactWarning) return !1;\n }\n return void 0 !== config.key;\n }\n function defineKeyPropWarningGetter(props, displayName) {\n function warnAboutAccessingKey() {\n specialPropKeyWarningShown ||\n ((specialPropKeyWarningShown = !0),\n console.error(\n \"%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)\",\n displayName\n ));\n }\n warnAboutAccessingKey.isReactWarning = !0;\n Object.defineProperty(props, \"key\", {\n get: warnAboutAccessingKey,\n configurable: !0\n });\n }\n function elementRefGetterWithDeprecationWarning() {\n var componentName = getComponentNameFromType(this.type);\n didWarnAboutElementRef[componentName] ||\n ((didWarnAboutElementRef[componentName] = !0),\n console.error(\n \"Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.\"\n ));\n componentName = this.props.ref;\n return void 0 !== componentName ? componentName : null;\n }\n function ReactElement(type, key, props, owner, debugStack, debugTask) {\n var refProp = props.ref;\n type = {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n props: props,\n _owner: owner\n };\n null !== (void 0 !== refProp ? refProp : null)\n ? Object.defineProperty(type, \"ref\", {\n enumerable: !1,\n get: elementRefGetterWithDeprecationWarning\n })\n : Object.defineProperty(type, \"ref\", { enumerable: !1, value: null });\n type._store = {};\n Object.defineProperty(type._store, \"validated\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: 0\n });\n Object.defineProperty(type, \"_debugInfo\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: null\n });\n Object.defineProperty(type, \"_debugStack\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: debugStack\n });\n Object.defineProperty(type, \"_debugTask\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: debugTask\n });\n Object.freeze && (Object.freeze(type.props), Object.freeze(type));\n return type;\n }\n function jsxDEVImpl(\n type,\n config,\n maybeKey,\n isStaticChildren,\n debugStack,\n debugTask\n ) {\n var children = config.children;\n if (void 0 !== children)\n if (isStaticChildren)\n if (isArrayImpl(children)) {\n for (\n isStaticChildren = 0;\n isStaticChildren < children.length;\n isStaticChildren++\n )\n validateChildKeys(children[isStaticChildren]);\n Object.freeze && Object.freeze(children);\n } else\n console.error(\n \"React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.\"\n );\n else validateChildKeys(children);\n if (hasOwnProperty.call(config, \"key\")) {\n children = getComponentNameFromType(type);\n var keys = Object.keys(config).filter(function (k) {\n return \"key\" !== k;\n });\n isStaticChildren =\n 0 < keys.length\n ? \"{key: someKey, \" + keys.join(\": ..., \") + \": ...}\"\n : \"{key: someKey}\";\n didWarnAboutKeySpread[children + isStaticChildren] ||\n ((keys =\n 0 < keys.length ? \"{\" + keys.join(\": ..., \") + \": ...}\" : \"{}\"),\n console.error(\n 'A props object containing a \"key\" prop is being spread into JSX:\\n let props = %s;\\n <%s {...props} />\\nReact keys must be passed directly to JSX without using spread:\\n let props = %s;\\n <%s key={someKey} {...props} />',\n isStaticChildren,\n children,\n keys,\n children\n ),\n (didWarnAboutKeySpread[children + isStaticChildren] = !0));\n }\n children = null;\n void 0 !== maybeKey &&\n (checkKeyStringCoercion(maybeKey), (children = \"\" + maybeKey));\n hasValidKey(config) &&\n (checkKeyStringCoercion(config.key), (children = \"\" + config.key));\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n children &&\n defineKeyPropWarningGetter(\n maybeKey,\n \"function\" === typeof type\n ? type.displayName || type.name || \"Unknown\"\n : type\n );\n return ReactElement(\n type,\n children,\n maybeKey,\n getOwner(),\n debugStack,\n debugTask\n );\n }\n function validateChildKeys(node) {\n isValidElement(node)\n ? node._store && (node._store.validated = 1)\n : \"object\" === typeof node &&\n null !== node &&\n node.$$typeof === REACT_LAZY_TYPE &&\n (\"fulfilled\" === node._payload.status\n ? isValidElement(node._payload.value) &&\n node._payload.value._store &&\n (node._payload.value._store.validated = 1)\n : node._store && (node._store.validated = 1));\n }\n function isValidElement(object) {\n return (\n \"object\" === typeof object &&\n null !== object &&\n object.$$typeof === REACT_ELEMENT_TYPE\n );\n }\n var React = require(\"react\"),\n REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_PORTAL_TYPE = Symbol.for(\"react.portal\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\"),\n REACT_STRICT_MODE_TYPE = Symbol.for(\"react.strict_mode\"),\n REACT_PROFILER_TYPE = Symbol.for(\"react.profiler\"),\n REACT_CONSUMER_TYPE = Symbol.for(\"react.consumer\"),\n REACT_CONTEXT_TYPE = Symbol.for(\"react.context\"),\n REACT_FORWARD_REF_TYPE = Symbol.for(\"react.forward_ref\"),\n REACT_SUSPENSE_TYPE = Symbol.for(\"react.suspense\"),\n REACT_SUSPENSE_LIST_TYPE = Symbol.for(\"react.suspense_list\"),\n REACT_MEMO_TYPE = Symbol.for(\"react.memo\"),\n REACT_LAZY_TYPE = Symbol.for(\"react.lazy\"),\n REACT_ACTIVITY_TYPE = Symbol.for(\"react.activity\"),\n REACT_CLIENT_REFERENCE = Symbol.for(\"react.client.reference\"),\n ReactSharedInternals =\n React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,\n hasOwnProperty = Object.prototype.hasOwnProperty,\n isArrayImpl = Array.isArray,\n createTask = console.createTask\n ? console.createTask\n : function () {\n return null;\n };\n React = {\n react_stack_bottom_frame: function (callStackForError) {\n return callStackForError();\n }\n };\n var specialPropKeyWarningShown;\n var didWarnAboutElementRef = {};\n var unknownOwnerDebugStack = React.react_stack_bottom_frame.bind(\n React,\n UnknownOwner\n )();\n var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));\n var didWarnAboutKeySpread = {};\n exports.Fragment = REACT_FRAGMENT_TYPE;\n exports.jsx = function (type, config, maybeKey) {\n var trackActualOwner =\n 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;\n return jsxDEVImpl(\n type,\n config,\n maybeKey,\n !1,\n trackActualOwner\n ? Error(\"react-stack-top-frame\")\n : unknownOwnerDebugStack,\n trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask\n );\n };\n exports.jsxs = function (type, config, maybeKey) {\n var trackActualOwner =\n 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;\n return jsxDEVImpl(\n type,\n config,\n maybeKey,\n !0,\n trackActualOwner\n ? Error(\"react-stack-top-frame\")\n : unknownOwnerDebugStack,\n trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask\n );\n };\n })();\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","'use client'\n\nimport type { ReactNode } from 'react'\nimport { I18nProvider } from '@fluenti/react'\nimport type { AllMessages, DateFormatOptions, NumberFormatOptions, Locale } from '@fluenti/core'\n\nexport interface ClientI18nProviderProps {\n locale: string\n fallbackLocale: string\n messages: AllMessages\n fallbackChain?: Record<string, Locale[]>\n dateFormats?: DateFormatOptions\n numberFormats?: NumberFormatOptions\n children: ReactNode\n}\n\n/**\n * Client-side I18nProvider wrapper.\n * Used internally by I18nProvider to hydrate client components.\n */\nexport function ClientI18nProvider({\n locale,\n fallbackLocale,\n messages,\n fallbackChain,\n dateFormats,\n numberFormats,\n children,\n}: ClientI18nProviderProps) {\n return (\n <I18nProvider\n locale={locale}\n fallbackLocale={fallbackLocale}\n messages={messages}\n {...(fallbackChain ? { fallbackChain } : {})}\n {...(dateFormats ? { dateFormats } : {})}\n {...(numberFormats ? { numberFormats } : {})}\n >\n {children}\n </I18nProvider>\n )\n}\n"],"x_google_ignoreList":[0,1,2],"mappings":"8KAWA,IAAI,EAAqB,OAAO,IAAI,6BAA6B,CAC/D,EAAsB,OAAO,IAAI,iBAAiB,CACpD,SAAS,EAAQ,EAAM,EAAQ,EAAU,CACvC,IAAI,EAAM,KAGV,GAFW,IAAX,IAAK,KAAmB,EAAM,GAAK,GACxB,EAAO,MAAlB,IAAK,KAAqB,EAAM,GAAK,EAAO,KACxC,QAAS,EAEX,IAAK,IAAI,IADT,GAAW,EAAE,CACQ,EACT,IAAV,QAAuB,EAAS,GAAY,EAAO,SAChD,EAAW,EAElB,MADA,GAAS,EAAS,IACX,CACL,SAAU,EACJ,OACD,MACL,IAAgB,IAAX,IAAK,GAAwB,KAAT,EACzB,MAAO,EACR,CAEH,EAAQ,SAAW,EACnB,EAAQ,IAAM,EACd,EAAQ,KAAO,cCtBf,QAAA,IAAA,WAAA,eACG,UAAY,CACX,SAAS,EAAyB,EAAM,CACtC,GAAY,GAAR,KAAc,OAAO,KACzB,GAAmB,OAAO,GAAtB,WACF,OAAO,EAAK,WAAa,EACrB,KACA,EAAK,aAAe,EAAK,MAAQ,KACvC,GAAiB,OAAO,GAApB,SAA0B,OAAO,EACrC,OAAQ,EAAR,CACE,KAAK,EACH,MAAO,WACT,KAAK,EACH,MAAO,WACT,KAAK,EACH,MAAO,aACT,KAAK,EACH,MAAO,WACT,KAAK,EACH,MAAO,eACT,KAAK,EACH,MAAO,WAEX,GA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,IAAI,EACF,IAAM,EAAqB,6BAC7B,OAAO,EACL,EACA,EACA,EACA,CAAC,EACD,EACI,MAAM,wBAAwB,CAC9B,EACJ,EAAmB,EAAW,EAAY,EAAK,CAAC,CAAG,EACpD,EAEH,EAAQ,KAAO,SAAU,EAAM,EAAQ,EAAU,CAC/C,IAAI,EACF,IAAM,EAAqB,6BAC7B,OAAO,EACL,EACA,EACA,EACA,CAAC,EACD,EACI,MAAM,wBAAwB,CAC9B,EACJ,EAAmB,EAAW,EAAY,EAAK,CAAC,CAAG,EACpD,KAED,iBC7VN,QAAA,IAAA,WAA6B,aAC3B,EAAO,QAAA,GAAA,CAEP,EAAO,QAAA,GAAA,MCeT,SAAgB,EAAmB,CACjC,SACA,iBACA,WACA,gBACA,cACA,gBACA,YAC0B,CAC1B,OAAA,EAAA,EAAA,KACG,EAAA,aAAD,CACU,SACQ,iBACN,WACV,GAAK,EAAgB,CAAE,gBAAe,CAAG,EAAE,CAC3C,GAAK,EAAc,CAAE,cAAa,CAAG,EAAE,CACvC,GAAK,EAAgB,CAAE,gBAAe,CAAG,EAAE,CAE1C,WACY,CAAA"}
|
|
1
|
+
{"version":3,"file":"provider.cjs","names":[],"sources":["../src/client-provider.tsx"],"sourcesContent":["'use client'\n\nimport type { ReactNode } from 'react'\nimport { I18nProvider } from '@fluenti/react'\nimport type { AllMessages, DateFormatOptions, NumberFormatOptions, Locale } from '@fluenti/core'\n\nexport interface ClientI18nProviderProps {\n locale: string\n fallbackLocale: string\n messages: AllMessages\n fallbackChain?: Record<string, Locale[]>\n dateFormats?: DateFormatOptions\n numberFormats?: NumberFormatOptions\n children: ReactNode\n}\n\n/**\n * Client-side I18nProvider wrapper.\n * Used internally by I18nProvider to hydrate client components.\n */\nexport function ClientI18nProvider({\n locale,\n fallbackLocale,\n messages,\n fallbackChain,\n dateFormats,\n numberFormats,\n children,\n}: ClientI18nProviderProps) {\n return (\n <I18nProvider\n locale={locale}\n fallbackLocale={fallbackLocale}\n messages={messages}\n {...(fallbackChain ? { fallbackChain } : {})}\n {...(dateFormats ? { dateFormats } : {})}\n {...(numberFormats ? { numberFormats } : {})}\n >\n {children}\n </I18nProvider>\n )\n}\n"],"mappings":"kIAoBA,SAAgB,EAAmB,CACjC,SACA,iBACA,WACA,gBACA,cACA,gBACA,YAC0B,CAC1B,OAAA,EAAA,EAAA,KACG,EAAA,aAAD,CACU,SACQ,iBACN,WACV,GAAK,EAAgB,CAAE,gBAAe,CAAG,EAAE,CAC3C,GAAK,EAAc,CAAE,cAAa,CAAG,EAAE,CACvC,GAAK,EAAgB,CAAE,gBAAe,CAAG,EAAE,CAE1C,WACY,CAAA"}
|