@fluenti/next 0.1.2 → 0.2.0

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/README.md CHANGED
@@ -33,7 +33,7 @@ No runtime parsing. No bundle bloat. Messages are compiled at build time and tre
33
33
  - **Next.js 14 & 15** compatible (`next >= 14.0.0`)
34
34
  - **`t\`\`` tagged templates** — write messages inline, extract them with the CLI
35
35
  - **Binding-aware transforms** — the webpack loader rewrites tagged templates only for proven Fluenti bindings
36
- - **`FluentProvider`** — async server component that sets up both server and client i18n in one place
36
+ - **`I18nProvider`** — async server component that sets up both server and client i18n in one place
37
37
  - **`withLocale()`** — per-component locale isolation in RSC
38
38
  - **ICU MessageFormat** — plurals, selects, nested arguments, custom formatters
39
39
  - **Code splitting** — messages split per locale, loaded on demand
@@ -72,12 +72,12 @@ export default withFluenti({
72
72
  })(nextConfig)
73
73
  ```
74
74
 
75
- ### 3. Set up `FluentProvider` in your root layout
75
+ ### 3. Set up `I18nProvider` in your root layout
76
76
 
77
77
  ```tsx
78
78
  // app/layout.tsx
79
79
  import { cookies } from 'next/headers'
80
- import { FluentProvider } from '@fluenti/next/__generated'
80
+ import { I18nProvider } from '@fluenti/next'
81
81
 
82
82
  export default async function RootLayout({ children }: { children: React.ReactNode }) {
83
83
  const cookieStore = await cookies()
@@ -86,16 +86,16 @@ export default async function RootLayout({ children }: { children: React.ReactNo
86
86
  return (
87
87
  <html lang={locale}>
88
88
  <body>
89
- <FluentProvider locale={locale}>
89
+ <I18nProvider locale={locale}>
90
90
  {children}
91
- </FluentProvider>
91
+ </I18nProvider>
92
92
  </body>
93
93
  </html>
94
94
  )
95
95
  }
96
96
  ```
97
97
 
98
- `FluentProvider` is an async server component. It initializes the server-side i18n instance (via `React.cache`) and wraps children in a client-side `I18nProvider` for hydration.
98
+ `I18nProvider` is an async server component. It initializes the server-side i18n instance (via `React.cache`) and wraps children in a client-side `I18nProvider` for hydration.
99
99
 
100
100
  ### 4. Use `t\`\`` in your pages
101
101
 
@@ -150,7 +150,7 @@ Server components use `t\`\`` with zero client-side JavaScript. The loader detec
150
150
  For direct access to the i18n instance in RSC:
151
151
 
152
152
  ```tsx
153
- import { setLocale, getI18n } from '@fluenti/next/__generated'
153
+ import { setLocale, getI18n } from '@fluenti/next'
154
154
 
155
155
  export default async function Page({ searchParams }) {
156
156
  const params = await searchParams
@@ -169,7 +169,7 @@ Works with `Suspense` boundaries — streamed content is translated on the serve
169
169
  import { Suspense } from 'react'
170
170
 
171
171
  async function SlowContent() {
172
- const { getI18n } = await import('@fluenti/next/__generated')
172
+ const { getI18n } = await import('@fluenti/next')
173
173
  const { t } = await getI18n()
174
174
  await fetchData()
175
175
  return <p>{t`Streamed content loaded!`}</p>
@@ -203,7 +203,7 @@ export async function greetAction(): Promise<string> {
203
203
  Translate Next.js metadata using the server i18n instance:
204
204
 
205
205
  ```tsx
206
- import { getI18n } from '@fluenti/next/__generated'
206
+ import { getI18n } from '@fluenti/next'
207
207
 
208
208
  export async function generateMetadata() {
209
209
  const i18n = await getI18n()
@@ -282,9 +282,9 @@ Wraps your Next.js config with Fluenti support. Accepts an optional `WithFluentC
282
282
  | `numberFormats` | `NumberFormatOptions` | Custom number format styles |
283
283
  | `fallbackChain` | `Record<string, Locale[]>` | Fallback chain per locale |
284
284
 
285
- ### `FluentProvider`
285
+ ### `I18nProvider`
286
286
 
287
- Async server component (imported from `@fluenti/next/__generated`). Place in your root layout.
287
+ Async server component (imported from `@fluenti/next`). Place in your root layout.
288
288
 
289
289
  | Prop | Type | Description |
290
290
  |------|------|-------------|
@@ -297,11 +297,11 @@ Server utility (imported from `@fluenti/next/server`). Executes `fn` with a temp
297
297
 
298
298
  ### Generated Server Module
299
299
 
300
- `@fluenti/next/__generated` exports:
300
+ `@fluenti/next` exports:
301
301
 
302
302
  | Export | Description |
303
303
  |--------|-------------|
304
- | `FluentProvider` | Async server component for layouts |
304
+ | `I18nProvider` | Async server component for layouts |
305
305
  | `setLocale(locale)` | Set the request-scoped locale |
306
306
  | `getI18n()` | Get the i18n instance (async) |
307
307
  | `t` | Compile-time translation API, preserved for advanced/server-specific imports |
@@ -11,7 +11,7 @@ export interface ClientI18nProviderProps {
11
11
  }
12
12
  /**
13
13
  * Client-side I18nProvider wrapper.
14
- * Used internally by FluentProvider to hydrate client components.
14
+ * Used internally by I18nProvider to hydrate client components.
15
15
  */
16
16
  export declare function ClientI18nProvider({ locale, fallbackLocale, messages, fallbackChain, dateFormats, numberFormats, children, }: ClientI18nProviderProps): import("react/jsx-runtime").JSX.Element;
17
17
  //# sourceMappingURL=client-provider.d.ts.map
@@ -0,0 +1,28 @@
1
+ export interface DevRunnerOptions {
2
+ cwd: string;
3
+ onSuccess?: () => void;
4
+ onError?: (err: Error) => void;
5
+ /** If true, reject the promise on failure instead of swallowing the error */
6
+ throwOnError?: boolean;
7
+ /** Run only compile (skip extract). Useful for production builds where source is unchanged. */
8
+ compileOnly?: boolean;
9
+ }
10
+ /**
11
+ * Walk up from `cwd` to find `node_modules/.bin/fluenti`.
12
+ * Returns the absolute path or null if not found.
13
+ */
14
+ export declare function resolveCliBin(cwd: string): string | null;
15
+ /**
16
+ * Run compile in-process via `@fluenti/cli` (for compileOnly mode),
17
+ * or fall back to shell-out for extract + compile (dev mode).
18
+ */
19
+ export declare function runExtractCompile(options: DevRunnerOptions): Promise<void>;
20
+ /**
21
+ * Create a debounced runner that collapses rapid calls.
22
+ *
23
+ * - If called while idle, schedules a run after `delay` ms.
24
+ * - If called while a run is in progress, marks a pending rerun.
25
+ * - Never runs concurrently.
26
+ */
27
+ export declare function createDebouncedRunner(options: DevRunnerOptions, delay?: number): () => void;
28
+ //# sourceMappingURL=dev-runner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-runner.d.ts","sourceRoot":"","sources":["../src/dev-runner.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE,MAAM,CAAA;IACX,SAAS,CAAC,EAAE,MAAM,IAAI,CAAA;IACtB,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,CAAA;IAC9B,6EAA6E;IAC7E,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,+FAA+F;IAC/F,WAAW,CAAC,EAAE,OAAO,CAAA;CACtB;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAUxD;AAED;;;GAGG;AACH,wBAAsB,iBAAiB,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAuDhF;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,gBAAgB,EACzB,KAAK,SAAM,GACV,MAAM,IAAI,CAiCZ"}
@@ -3,7 +3,7 @@ import { ResolvedFluentConfig } from './types';
3
3
  * Generate the server module that provides:
4
4
  * - setLocale / getI18n
5
5
  * - Trans / Plural / Select / DateTime / NumberFormat (server components)
6
- * - FluentProvider (async server component for layouts)
6
+ * - I18nProvider (async server component for layouts)
7
7
  *
8
8
  * @returns Absolute path to the generated server module.
9
9
  */
@@ -1 +1 @@
1
- {"version":3,"file":"generate-server-module.d.ts","sourceRoot":"","sources":["../src/generate-server-module.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAEnD;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAClC,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE,oBAAoB,GAC3B,MAAM,CAyLR"}
1
+ {"version":3,"file":"generate-server-module.d.ts","sourceRoot":"","sources":["../src/generate-server-module.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAEnD;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAClC,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE,oBAAoB,GAC3B,MAAM,CAiMR"}
package/dist/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require(`node:path`),t=require(`node:fs`),n=require(`node:module`);var r=typeof __filename==`string`?__filename:{}.url,{createJiti:i}=(0,n.createRequire)(r)(`jiti`);function a(t,n){let r=o(t),i=n?.defaultLocale??r?.sourceLocale??`en`,a=n?.locales??r?.locales??[i],s=n?.compiledDir??r?.compileOutDir??`./src/locales/compiled`,c=n?.serverModuleOutDir??(0,e.join)(`node_modules`,`.fluenti`),l={locales:a,defaultLocale:i,compiledDir:s,serverModule:n?.serverModule??null,serverModuleOutDir:c};return n?.resolveLocale&&(l.resolveLocale=n.resolveLocale),n?.dateFormats&&(l.dateFormats=n.dateFormats),n?.numberFormats&&(l.numberFormats=n.numberFormats),n?.fallbackChain&&(l.fallbackChain=n.fallbackChain),l}function o(n){let a=i(r,{moduleCache:!1,interopDefault:!0});for(let r of[`fluenti.config.ts`,`fluenti.config.js`,`fluenti.config.mjs`]){let i=(0,e.resolve)(n,r);if((0,t.existsSync)(i))try{return c(a(i))}catch{return s(i,a)||null}}return null}function s(n,r){let i=(0,t.readFileSync)(n,`utf8`),a=i.match(/import\s*\{\s*defineConfig(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*\}\s*from\s*['"]@fluenti\/cli['"]\s*;?/);if(!a)return null;let o=a[1]??`defineConfig`,s=i.replace(a[0],``),l=(0,e.join)((0,e.dirname)(n),`.${(0,e.basename)(n,(0,e.extname)(n))}.next-plugin-read-config${(0,e.extname)(n)||`.ts`}`);(0,t.writeFileSync)(l,`const ${o} = (config) => config\n${s}`,`utf8`);try{return c(r(l))}catch{return null}finally{(0,t.rmSync)(l,{force:!0})}}function c(e){return typeof e==`object`&&e&&`default`in e?e.default??{}:e}function l(n,r){if(r.serverModule)return(0,e.resolve)(n,r.serverModule);let i=(0,e.resolve)(n,r.serverModuleOutDir),a=(0,e.resolve)(i,`server.js`),o=(0,e.resolve)(i,`server.d.ts`);(0,t.existsSync)(i)||(0,t.mkdirSync)(i,{recursive:!0});let s=u((0,e.relative)(i,(0,e.resolve)(n,r.compiledDir))),c=r.locales.map(e=>` case '${e}': return import('${s}/${e}')`).join(`
2
- `),l=r.fallbackChain?JSON.stringify(r.fallbackChain):`undefined`;(0,t.writeFileSync)((0,e.resolve)(i,`client-provider.js`),`"use client";
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require(`node:fs`),t=require(`node:child_process`),n=require(`node:path`),r=require(`node:module`),i=require(`@fluenti/core`);var a=typeof __filename==`string`?__filename:{}.url,{createJiti:o}=(0,r.createRequire)(a)(`jiti`);function s(e,t){let r=c(e),i=t?.defaultLocale??r?.sourceLocale??`en`,a=t?.locales??r?.locales??[i],o=t?.compiledDir??r?.compileOutDir??`./src/locales/compiled`,s=t?.serverModuleOutDir??(0,n.join)(`node_modules`,`.fluenti`),l={locales:a,defaultLocale:i,compiledDir:o,serverModule:t?.serverModule??null,serverModuleOutDir:s};return t?.resolveLocale&&(l.resolveLocale=t.resolveLocale),t?.dateFormats&&(l.dateFormats=t.dateFormats),t?.numberFormats&&(l.numberFormats=t.numberFormats),t?.fallbackChain&&(l.fallbackChain=t.fallbackChain),l}function c(t){let r=o(a,{moduleCache:!1,interopDefault:!0});for(let i of[`fluenti.config.ts`,`fluenti.config.js`,`fluenti.config.mjs`]){let a=(0,n.resolve)(t,i);if((0,e.existsSync)(a))try{return u(r(a))}catch{return l(a,r)||null}}return null}function l(t,r){let i=(0,e.readFileSync)(t,`utf8`),a=i.match(/import\s*\{\s*defineConfig(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*\}\s*from\s*['"]@fluenti\/cli['"]\s*;?/);if(!a)return null;let o=a[1]??`defineConfig`,s=i.replace(a[0],``),c=(0,n.join)((0,n.dirname)(t),`.${(0,n.basename)(t,(0,n.extname)(t))}.next-plugin-read-config${(0,n.extname)(t)||`.ts`}`);(0,e.writeFileSync)(c,`const ${o} = (config) => config\n${s}`,`utf8`);try{return u(r(c))}catch{return null}finally{(0,e.rmSync)(c,{force:!0})}}function u(e){return typeof e==`object`&&e&&`default`in e?e.default??{}:e}function d(t,r){if(r.serverModule)return(0,n.resolve)(t,r.serverModule);let a=(0,n.resolve)(t,r.serverModuleOutDir),o=(0,n.resolve)(a,`server.js`),s=(0,n.resolve)(a,`server.d.ts`);(0,e.existsSync)(a)||(0,e.mkdirSync)(a,{recursive:!0});for(let e of r.locales)(0,i.validateLocale)(e,`next-plugin`);let c=f((0,n.relative)(a,(0,n.resolve)(t,r.compiledDir))),l=r.locales.map(e=>` case '${e}': return import('${c}/${e}')`).join(`
2
+ `),u=r.fallbackChain?JSON.stringify(r.fallbackChain):`undefined`;(0,e.writeFileSync)((0,n.resolve)(a,`client-provider.js`),`"use client";
3
3
  // Auto-generated by @fluenti/next — do not edit
4
4
  import { createElement } from 'react'
5
5
  import { I18nProvider } from '@fluenti/react'
6
- ${r.locales.map(e=>`import ${e.replace(/[^a-zA-Z0-9]/g,`_`)} from '${s}/${e}'`).join(`
6
+ ${r.locales.map(e=>`import ${e.replace(/[^a-zA-Z0-9]/g,`_`)} from '${c}/${e}'`).join(`
7
7
  `)}
8
8
 
9
9
  const __allMessages = { ${r.locales.map(e=>`'${e}': ${e.replace(/[^a-zA-Z0-9]/g,`_`)}`).join(`, `)} }
@@ -11,34 +11,34 @@ const __allMessages = { ${r.locales.map(e=>`'${e}': ${e.replace(/[^a-zA-Z0-9]/g,
11
11
  export function ClientI18nProvider({ locale, fallbackLocale, fallbackChain, children }) {
12
12
  return createElement(I18nProvider, { locale, fallbackLocale, messages: __allMessages, fallbackChain }, children)
13
13
  }
14
- `,`utf-8`);let d=r.resolveLocale?`import __resolveLocale from '${r.resolveLocale}'`:null,f=r.resolveLocale?`resolveLocale: __resolveLocale,`:`resolveLocale: async () => {
14
+ `,`utf-8`);let d=r.resolveLocale?`import __resolveLocale from '${f((0,n.relative)(a,(0,n.resolve)(t,r.resolveLocale)))}'`:null,p=r.resolveLocale?`resolveLocale: __resolveLocale,`:`resolveLocale: async () => {
15
15
  try {
16
16
  const { cookies } = await import('next/headers')
17
17
  return (await cookies()).get('locale')?.value ?? '${r.defaultLocale}'
18
18
  } catch {
19
19
  return '${r.defaultLocale}'
20
20
  }
21
- },`,p=`// Auto-generated by @fluenti/next — do not edit
21
+ },`,m=`// Auto-generated by @fluenti/next — do not edit
22
22
  import { createServerI18n } from '@fluenti/react/server'
23
23
  import { createElement } from 'react'
24
24
  ${d?`${d}\n`:``}
25
25
  const serverI18n = createServerI18n({
26
26
  loadMessages: async (locale) => {
27
27
  switch (locale) {
28
- ${c}
29
- default: return import('${s}/${r.defaultLocale}')
28
+ ${l}
29
+ default: return import('${c}/${r.defaultLocale}')
30
30
  }
31
31
  },
32
32
  fallbackLocale: '${r.defaultLocale}',
33
- fallbackChain: ${l},
34
- ${f}
33
+ fallbackChain: ${u},
34
+ ${p}
35
35
  })
36
36
 
37
37
  export const setLocale = serverI18n.setLocale
38
38
  export const getI18n = serverI18n.getI18n
39
39
  export const t = (..._args) => {
40
40
  throw new Error(
41
- "[fluenti] \`t\` imported from '@fluenti/next/__generated' is a compile-time API. " +
41
+ "[fluenti] \`t\` imported from '@fluenti/next' is a compile-time API. " +
42
42
  'Use it only with the Fluenti loader inside an async server scope.',
43
43
  )
44
44
  }
@@ -53,7 +53,7 @@ export const NumberFormat = serverI18n.NumberFormat
53
53
  *
54
54
  * Sets up both server-side (React.cache) and client-side (I18nProvider) i18n.
55
55
  */
56
- export async function FluentProvider({ locale, children }) {
56
+ export async function I18nProvider({ locale, children }) {
57
57
  const activeLocale = locale ?? '${r.defaultLocale}'
58
58
 
59
59
  // 1. Initialize server-side i18n (React.cache scoped)
@@ -67,10 +67,10 @@ export async function FluentProvider({ locale, children }) {
67
67
  return createElement(ClientI18nProvider, {
68
68
  locale: activeLocale,
69
69
  fallbackLocale: '${r.defaultLocale}',
70
- fallbackChain: ${l},
70
+ fallbackChain: ${u},
71
71
  }, children)
72
72
  }
73
- `;return(0,t.writeFileSync)(a,p,`utf-8`),(0,t.writeFileSync)(o,`// Auto-generated by @fluenti/next — do not edit
73
+ `;return(0,e.writeFileSync)(o,m,`utf-8`),(0,e.writeFileSync)(s,`// Auto-generated by @fluenti/next — do not edit
74
74
  import type { ReactNode, ReactElement } from 'react'
75
75
  import type { CompileTimeT, FluentInstanceExtended } from '@fluenti/core'
76
76
 
@@ -120,9 +120,9 @@ export declare function NumberFormat(props: {
120
120
  style?: string
121
121
  }): Promise<ReactElement>
122
122
 
123
- export declare function FluentProvider(props: {
123
+ export declare function I18nProvider(props: {
124
124
  locale?: string
125
125
  children: ReactNode
126
126
  }): Promise<ReactElement>
127
- `,`utf-8`),a}function u(e){return e.split(`\\`).join(`/`)}function d(e){if(e&&f(e))return p({},e);let t=e??{};return function(e){return p(t,e??{})}}function f(e){return[`reactStrictMode`,`experimental`,`images`,`env`,`webpack`,`rewrites`,`redirects`,`headers`,`pageExtensions`,`output`,`basePath`,`i18n`,`trailingSlash`,`compiler`,`transpilePackages`].some(t=>t in e)}function p(t,n){let r=process.cwd(),i=l(r,a(r,t)),o=(0,e.resolve)(typeof __dirname<`u`?__dirname:(0,e.dirname)(new URL({}.url).pathname),`loader.js`),s=n.webpack;return{...n,webpack(e,t){return e.module.rules.push({test:/\.[jt]sx?$/,enforce:`pre`,exclude:[/node_modules/,/\.next/],use:[{loader:o,options:{serverModulePath:i}}]}),e.resolve=e.resolve??{},e.resolve.alias=e.resolve.alias??{},e.resolve.alias[`@fluenti/next/__generated`]=i,s?s(e,t):e}}}exports.withFluenti=d;
127
+ `,`utf-8`),o}function f(e){return e.split(`\\`).join(`/`)}function p(t){let r=t;for(;;){let t=(0,n.resolve)(r,`node_modules/.bin/fluenti`);if((0,e.existsSync)(t))return t;let i=(0,n.dirname)(r);if(i===r)break;r=i}return null}async function m(e){if(e.compileOnly)try{let{runCompile:t}=(0,r.createRequire)((0,n.join)(e.cwd,`package.json`))(`@fluenti/cli`);await t(e.cwd),console.log(`[fluenti] Compiling... done`),e.onSuccess?.();return}catch(t){let n=t instanceof Error?t:Error(String(t));if(e.throwOnError)throw n;console.warn(`[fluenti] Compile failed:`,n.message),e.onError?.(n);return}let i=p(e.cwd);if(!i){let t=`[fluenti] CLI not found — skipping auto-compile. Install @fluenti/cli as a devDependency.`;return e.throwOnError?Promise.reject(Error(t)):(console.warn(t),Promise.resolve())}let a=`${i} extract && ${i} compile`;return new Promise((n,r)=>{(0,t.exec)(a,{cwd:e.cwd},(t,i,a)=>{if(t){let n=Error(a||t.message);if(e.throwOnError){r(n);return}console.warn(`[fluenti] Extract/compile failed:`,n.message),e.onError?.(n)}else console.log(`[fluenti] Extracting and compiling... done`),e.onSuccess?.();n()})})}function h(e,t=300){let n=null,r=!1,i=!1;async function a(){r=!0;try{await m(e)}finally{r=!1,i&&(i=!1,o())}}function o(){n!==null&&clearTimeout(n),n=setTimeout(()=>{n=null,r?i=!0:a()},t)}return o}function g(e){if(e&&_(e))return v({},e);let t=e??{};return function(e){return v(t,e??{})}}function _(e){return[`reactStrictMode`,`experimental`,`images`,`env`,`webpack`,`rewrites`,`redirects`,`headers`,`pageExtensions`,`output`,`basePath`,`i18n`,`trailingSlash`,`compiler`,`transpilePackages`].some(t=>t in e)}function v(r,i){let a=process.cwd(),o=s(a,r);(0,e.existsSync)((0,n.resolve)(a,o.compiledDir))||console.warn(`\n[fluenti] Compiled catalogs not found at ${o.compiledDir}.\nRun: npx fluenti extract && npx fluenti compile\n`);let c=d(a,o),l=(0,n.resolve)(typeof __dirname<`u`?__dirname:(0,n.dirname)(new URL({}.url).pathname),`loader.js`),u=i.webpack,f=!1;return{...i,webpack(e,i){e.module.rules.push({test:/\.[jt]sx?$/,enforce:`pre`,exclude:[/node_modules/,/\.next/],use:[{loader:l,options:{serverModulePath:c}}]}),e.resolve=e.resolve??{},e.resolve.alias=e.resolve.alias??{},e.resolve.alias[`@fluenti/next$`]=c;let s=r.buildAutoCompile??!0;if(!i.dev&&s&&!f){f=!0;try{(0,t.execSync)(`node --input-type=module -e "const { runCompile } = await import('@fluenti/cli'); await runCompile('${a.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`)}')"`,{cwd:a,stdio:`inherit`})}catch{}}let d=r.devAutoCompile??!0;if(i.dev&&d){let t=r.devAutoCompileDelay??1e3,i=h({cwd:a},t),s=(0,n.resolve)(a,o.compiledDir);e.plugins=e.plugins??[],e.plugins.push({apply(e){let t=!0;e.hooks.watchRun.tapAsync(`fluenti-dev`,(e,n)=>{t&&(t=!1,i());let r=e.modifiedFiles;r&&[...r].some(e=>/\.[jt]sx?$/.test(e)&&!e.includes(`node_modules`)&&!e.includes(`.next`)&&!e.startsWith(s))&&i(),n()})}})}return u?u(e,i):e}}}var y='[fluenti] `withFluenti()` must be configured in next.config.ts before importing from "@fluenti/next".';function b(){throw Error(y)}var x=b,S=b,C=b,w=b,T=b,E=b,D=b,O=b,k=b;exports.DateTime=D,exports.I18nProvider=k,exports.NumberFormat=O,exports.Plural=T,exports.Select=E,exports.Trans=w,exports.getI18n=S,exports.setLocale=x,exports.t=C,exports.withFluenti=g;
128
128
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":[],"sources":["../src/read-config.ts","../src/generate-server-module.ts","../src/with-fluenti.ts"],"sourcesContent":["import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { basename, dirname, extname, join, resolve } from 'node:path'\nimport type { FluentiConfig } from '@fluenti/core'\nimport type { WithFluentConfig, ResolvedFluentConfig } from './types'\n\nconst runtimeModulePath = typeof __filename === 'string'\n ? __filename\n : import.meta.url\nconst require = createRequire(runtimeModulePath)\nconst { createJiti } = require('jiti') as {\n createJiti: (\n url: string,\n options?: { moduleCache?: boolean; interopDefault?: boolean },\n ) => (path: string) => unknown\n}\n\n/**\n * Read fluenti.config.ts and merge with withFluenti() overrides.\n */\nexport function resolveConfig(\n projectRoot: string,\n overrides?: WithFluentConfig,\n): ResolvedFluentConfig {\n const fileConfig = readFluentConfigSync(projectRoot)\n\n const defaultLocale = overrides?.defaultLocale\n ?? fileConfig?.sourceLocale\n ?? 'en'\n\n const locales = overrides?.locales\n ?? fileConfig?.locales\n ?? [defaultLocale]\n\n const compiledDir = overrides?.compiledDir\n ?? fileConfig?.compileOutDir\n ?? './src/locales/compiled'\n\n const serverModuleOutDir = overrides?.serverModuleOutDir\n ?? join('node_modules', '.fluenti')\n\n const resolved: ResolvedFluentConfig = {\n locales,\n defaultLocale,\n compiledDir,\n serverModule: overrides?.serverModule ?? null,\n serverModuleOutDir,\n }\n if (overrides?.resolveLocale) resolved.resolveLocale = overrides.resolveLocale\n if (overrides?.dateFormats) resolved.dateFormats = overrides.dateFormats\n if (overrides?.numberFormats) resolved.numberFormats = overrides.numberFormats\n if (overrides?.fallbackChain) resolved.fallbackChain = overrides.fallbackChain\n return resolved\n}\n\n/**\n * Attempt to read fluenti.config.ts synchronously.\n * Returns null if file doesn't exist or can't be parsed.\n */\nfunction readFluentConfigSync(projectRoot: string): FluentiConfig | null {\n const jiti = createJiti(runtimeModulePath, {\n moduleCache: false,\n interopDefault: true,\n })\n const candidates = [\n 'fluenti.config.ts',\n 'fluenti.config.js',\n 'fluenti.config.mjs',\n ]\n\n for (const name of candidates) {\n const configPath = resolve(projectRoot, name)\n if (existsSync(configPath)) {\n try {\n return normalizeLoadedConfig(jiti(configPath) as FluentiConfig | { default?: FluentiConfig })\n } catch {\n const rewritten = tryLoadConfigViaDefineConfigShim(configPath, jiti)\n if (rewritten) {\n return rewritten\n }\n return null\n }\n }\n }\n\n return null\n}\n\nfunction tryLoadConfigViaDefineConfigShim(\n configPath: string,\n jiti: (path: string) => unknown,\n): FluentiConfig | null {\n const source = readFileSync(configPath, 'utf8')\n const importMatch = source.match(\n /import\\s*\\{\\s*defineConfig(?:\\s+as\\s+([A-Za-z_$][\\w$]*))?\\s*\\}\\s*from\\s*['\"]@fluenti\\/cli['\"]\\s*;?/,\n )\n if (!importMatch) {\n return null\n }\n\n const helperName = importMatch[1] ?? 'defineConfig'\n const rewrittenSource = source.replace(importMatch[0], '')\n const tempPath = join(\n dirname(configPath),\n `.${basename(configPath, extname(configPath))}.next-plugin-read-config${extname(configPath) || '.ts'}`,\n )\n\n writeFileSync(tempPath, `const ${helperName} = (config) => config\\n${rewrittenSource}`, 'utf8')\n\n try {\n return normalizeLoadedConfig(jiti(tempPath) as FluentiConfig | { default?: FluentiConfig })\n } catch {\n return null\n } finally {\n rmSync(tempPath, { force: true })\n }\n}\n\nfunction normalizeLoadedConfig(\n mod: FluentiConfig | { default?: FluentiConfig },\n): FluentiConfig {\n return typeof mod === 'object' && mod !== null && 'default' in mod\n ? (mod.default ?? {}) as FluentiConfig\n : mod as FluentiConfig\n}\n","import { writeFileSync, mkdirSync, existsSync } from 'node:fs'\nimport { resolve, relative } from 'node:path'\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 * - FluentProvider (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 compiledDirAbs = resolve(projectRoot, config.compiledDir)\n const compiledRelative = toForwardSlash(relative(outDir, compiledDirAbs))\n\n const localeImports = config.locales\n .map((locale) => ` case '${locale}': return import('${compiledRelative}/${locale}')`)\n .join('\\n')\n\n const fallbackChainStr = config.fallbackChain\n ? JSON.stringify(config.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 = config.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 = config.locales\n .map((locale) => {\n const safe = locale.replace(/[^a-zA-Z0-9]/g, '_')\n return `'${locale}': ${safe}`\n })\n .join(', ')\n\n const clientProviderSource = `\"use client\";\n// Auto-generated by @fluenti/next — do not edit\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 ? `import __resolveLocale from '${config.resolveLocale}'`\n : null\n\n const resolveLocaleFn = config.resolveLocale\n ? `resolveLocale: __resolveLocale,`\n : `resolveLocale: async () => {\n try {\n const { cookies } = await import('next/headers')\n return (await cookies()).get('locale')?.value ?? '${config.defaultLocale}'\n } catch {\n return '${config.defaultLocale}'\n }\n },`\n\n const moduleSource = `// Auto-generated by @fluenti/next — do not edit\nimport { createServerI18n } from '@fluenti/react/server'\nimport { createElement } from 'react'\n${resolveLocaleImport ? `${resolveLocaleImport}\\n` : ''}\nconst serverI18n = createServerI18n({\n loadMessages: async (locale) => {\n switch (locale) {\n${localeImports}\n default: return import('${compiledRelative}/${config.defaultLocale}')\n }\n },\n fallbackLocale: '${config.defaultLocale}',\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/__generated' is a compile-time API. \" +\n 'Use it only with the Fluenti loader inside an async server scope.',\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 FluentProvider({ locale, children }) {\n const activeLocale = locale ?? '${config.defaultLocale}'\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: '${config.defaultLocale}',\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, FluentInstanceExtended } from '@fluenti/core'\n\nexport declare function setLocale(locale: string): void\nexport declare function getI18n(): Promise<FluentInstanceExtended & { 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 FluentProvider(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\nfunction toForwardSlash(p: string): string {\n return p.split('\\\\').join('/')\n}\n","import { resolve, dirname } from 'node:path'\nimport type { WithFluentConfig } from './types'\nimport { resolveConfig } from './read-config'\nimport { generateServerModule } from './generate-server-module'\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 && isNextConfig(configOrNext 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 isNextConfig(obj: NextConfig): boolean {\n const nextKeys = [\n 'reactStrictMode', 'experimental', 'images', 'env', 'webpack',\n 'rewrites', 'redirects', 'headers', 'pageExtensions', 'output',\n 'basePath', 'i18n', 'trailingSlash', 'compiler', 'transpilePackages',\n ]\n return nextKeys.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\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(new URL(import.meta.url).pathname)\n const loaderPath = resolve(thisDir, 'loader.js')\n\n const existingWebpack = nextConfig['webpack'] as\n | ((config: WebpackConfig, options: WebpackOptions) => WebpackConfig)\n | undefined\n\n return {\n ...nextConfig,\n webpack(config: WebpackConfig, options: WebpackOptions) {\n // Add fluenti loader (enforce: pre — runs before other loaders)\n config.module.rules.push({\n test: /\\.[jt]sx?$/,\n enforce: 'pre' as const,\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/__generated'] = serverModulePath\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\n// Minimal webpack types for the config function\ninterface WebpackConfig {\n module: {\n rules: Array<{\n test: RegExp\n enforce?: 'pre' | 'post'\n exclude?: Array<RegExp>\n use: Array<{ loader: string; options: Record<string, unknown> }>\n }>\n }\n resolve: {\n alias?: Record<string, string>\n }\n}\n\ninterface WebpackOptions {\n isServer: boolean\n dev: boolean\n}\n"],"mappings":"4IAMA,IAAM,EAAoB,OAAO,YAAe,SAC5C,WAAA,EAAA,CACY,IAEV,CAAE,eAAA,EAAA,EAAA,eADsB,EAAkB,CACjB,OAAO,CAUtC,SAAgB,EACd,EACA,EACsB,CACtB,IAAM,EAAa,EAAqB,EAAY,CAE9C,EAAgB,GAAW,eAC5B,GAAY,cACZ,KAEC,EAAU,GAAW,SACtB,GAAY,SACZ,CAAC,EAAc,CAEd,EAAc,GAAW,aAC1B,GAAY,eACZ,yBAEC,EAAqB,GAAW,qBAAA,EAAA,EAAA,M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ACrC,EAAO,QAAQ,MAAQ,EAAO,QAAQ,OAAS,EAAE,CACjD,EAAO,QAAQ,MAAM,6BAA+B,EAGhD,EACK,EAAgB,EAAQ,EAAQ,CAGlC,GAEV"}
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../src/read-config.ts","../src/generate-server-module.ts","../src/dev-runner.ts","../src/with-fluenti.ts","../src/index.ts"],"sourcesContent":["import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { basename, dirname, extname, join, resolve } from 'node:path'\nimport type { FluentiConfig } from '@fluenti/core'\nimport type { WithFluentConfig, ResolvedFluentConfig } from './types'\n\nconst runtimeModulePath = typeof __filename === 'string'\n ? __filename\n : import.meta.url\nconst require = createRequire(runtimeModulePath)\nconst { createJiti } = require('jiti') as {\n createJiti: (\n url: string,\n options?: { moduleCache?: boolean; interopDefault?: boolean },\n ) => (path: string) => unknown\n}\n\n/**\n * Read fluenti.config.ts and merge with withFluenti() overrides.\n */\nexport function resolveConfig(\n projectRoot: string,\n overrides?: WithFluentConfig,\n): ResolvedFluentConfig {\n const fileConfig = readFluentConfigSync(projectRoot)\n\n const defaultLocale = overrides?.defaultLocale\n ?? fileConfig?.sourceLocale\n ?? 'en'\n\n const locales = overrides?.locales\n ?? fileConfig?.locales\n ?? [defaultLocale]\n\n const compiledDir = overrides?.compiledDir\n ?? fileConfig?.compileOutDir\n ?? './src/locales/compiled'\n\n const serverModuleOutDir = overrides?.serverModuleOutDir\n ?? join('node_modules', '.fluenti')\n\n const resolved: ResolvedFluentConfig = {\n locales,\n defaultLocale,\n compiledDir,\n serverModule: overrides?.serverModule ?? null,\n serverModuleOutDir,\n }\n if (overrides?.resolveLocale) resolved.resolveLocale = overrides.resolveLocale\n if (overrides?.dateFormats) resolved.dateFormats = overrides.dateFormats\n if (overrides?.numberFormats) resolved.numberFormats = overrides.numberFormats\n if (overrides?.fallbackChain) resolved.fallbackChain = overrides.fallbackChain\n return resolved\n}\n\n/**\n * Attempt to read fluenti.config.ts synchronously.\n * Returns null if file doesn't exist or can't be parsed.\n */\nfunction readFluentConfigSync(projectRoot: string): FluentiConfig | null {\n const jiti = createJiti(runtimeModulePath, {\n moduleCache: false,\n interopDefault: true,\n })\n const candidates = [\n 'fluenti.config.ts',\n 'fluenti.config.js',\n 'fluenti.config.mjs',\n ]\n\n for (const name of candidates) {\n const configPath = resolve(projectRoot, name)\n if (existsSync(configPath)) {\n try {\n return normalizeLoadedConfig(jiti(configPath) as FluentiConfig | { default?: FluentiConfig })\n } catch {\n const rewritten = tryLoadConfigViaDefineConfigShim(configPath, jiti)\n if (rewritten) {\n return rewritten\n }\n return null\n }\n }\n }\n\n return null\n}\n\nfunction tryLoadConfigViaDefineConfigShim(\n configPath: string,\n jiti: (path: string) => unknown,\n): FluentiConfig | null {\n const source = readFileSync(configPath, 'utf8')\n const importMatch = source.match(\n /import\\s*\\{\\s*defineConfig(?:\\s+as\\s+([A-Za-z_$][\\w$]*))?\\s*\\}\\s*from\\s*['\"]@fluenti\\/cli['\"]\\s*;?/,\n )\n if (!importMatch) {\n return null\n }\n\n const helperName = importMatch[1] ?? 'defineConfig'\n const rewrittenSource = source.replace(importMatch[0], '')\n const tempPath = join(\n dirname(configPath),\n `.${basename(configPath, extname(configPath))}.next-plugin-read-config${extname(configPath) || '.ts'}`,\n )\n\n writeFileSync(tempPath, `const ${helperName} = (config) => config\\n${rewrittenSource}`, 'utf8')\n\n try {\n return normalizeLoadedConfig(jiti(tempPath) as FluentiConfig | { default?: FluentiConfig })\n } catch {\n return null\n } finally {\n rmSync(tempPath, { force: true })\n }\n}\n\nfunction normalizeLoadedConfig(\n mod: FluentiConfig | { default?: FluentiConfig },\n): FluentiConfig {\n return typeof mod === 'object' && mod !== null && 'default' in mod\n ? (mod.default ?? {}) as FluentiConfig\n : mod as FluentiConfig\n}\n","import { writeFileSync, mkdirSync, existsSync } from 'node:fs'\nimport { resolve, relative } from 'node:path'\nimport { validateLocale } from '@fluenti/core'\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 for (const locale of config.locales) {\n validateLocale(locale, 'next-plugin')\n }\n\n const compiledDirAbs = resolve(projectRoot, config.compiledDir)\n const compiledRelative = toForwardSlash(relative(outDir, compiledDirAbs))\n\n const localeImports = config.locales\n .map((locale) => ` case '${locale}': return import('${compiledRelative}/${locale}')`)\n .join('\\n')\n\n const fallbackChainStr = config.fallbackChain\n ? JSON.stringify(config.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 = config.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 = config.locales\n .map((locale) => {\n const safe = locale.replace(/[^a-zA-Z0-9]/g, '_')\n return `'${locale}': ${safe}`\n })\n .join(', ')\n\n const clientProviderSource = `\"use client\";\n// Auto-generated by @fluenti/next — do not edit\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 } = await import('next/headers')\n return (await cookies()).get('locale')?.value ?? '${config.defaultLocale}'\n } catch {\n return '${config.defaultLocale}'\n }\n },`\n\n const moduleSource = `// Auto-generated by @fluenti/next — do not edit\nimport { createServerI18n } from '@fluenti/react/server'\nimport { createElement } from 'react'\n${resolveLocaleImport ? `${resolveLocaleImport}\\n` : ''}\nconst serverI18n = createServerI18n({\n loadMessages: async (locale) => {\n switch (locale) {\n${localeImports}\n default: return import('${compiledRelative}/${config.defaultLocale}')\n }\n },\n fallbackLocale: '${config.defaultLocale}',\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. \" +\n 'Use it only with the Fluenti loader inside an async server scope.',\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 ?? '${config.defaultLocale}'\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: '${config.defaultLocale}',\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, FluentInstanceExtended } from '@fluenti/core'\n\nexport declare function setLocale(locale: string): void\nexport declare function getI18n(): Promise<FluentInstanceExtended & { 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\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}\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: shell out for extract + compile\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 command = `${bin} extract && ${bin} compile`\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 { existsSync } from 'node:fs'\nimport { execSync } from 'node:child_process'\nimport { resolve, dirname } from 'node:path'\nimport type { WithFluentConfig } from './types'\nimport { resolveConfig } from './read-config'\nimport { generateServerModule } from './generate-server-module'\nimport { createDebouncedRunner } from './dev-runner'\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 && isNextConfig(configOrNext 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 isNextConfig(obj: NextConfig): boolean {\n const nextKeys = [\n 'reactStrictMode', 'experimental', 'images', 'env', 'webpack',\n 'rewrites', 'redirects', 'headers', 'pageExtensions', 'output',\n 'basePath', 'i18n', 'trailingSlash', 'compiler', 'transpilePackages',\n ]\n return nextKeys.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\n // Warn if compiled catalogs directory doesn't exist yet\n const compiledDir = resolve(projectRoot, resolved.compiledDir)\n if (!existsSync(compiledDir)) {\n console.warn(\n `\\n[fluenti] Compiled catalogs not found at ${resolved.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(new URL(import.meta.url).pathname)\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 return {\n ...nextConfig,\n webpack(config: WebpackConfig, options: WebpackOptions) {\n // Add fluenti loader (enforce: pre — runs before other loaders)\n config.module.rules.push({\n test: /\\.[jt]sx?$/,\n enforce: 'pre' as const,\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 (run once across server+client passes)\n const buildAutoCompile = fluentConfig.buildAutoCompile ?? true\n if (!options.dev && buildAutoCompile && !buildCompileRan) {\n buildCompileRan = true\n try {\n // Use node -e with dynamic import — avoids CLI binary resolution issues.\n // webpack() is sync, so we use execSync to block until compile finishes.\n const escapedRoot = projectRoot.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")\n execSync(\n `node --input-type=module -e \"const { runCompile } = await import('@fluenti/cli'); await runCompile('${escapedRoot}')\"`,\n { cwd: projectRoot, stdio: 'inherit' },\n )\n } catch {\n // @fluenti/cli not available or compile failed — skip silently\n }\n }\n\n // Auto extract+compile in dev mode\n const devAutoCompile = fluentConfig.devAutoCompile ?? true\n if (options.dev && devAutoCompile) {\n const devDelay = fluentConfig.devAutoCompileDelay ?? 1000\n const debouncedRun = createDebouncedRunner({ cwd: projectRoot }, devDelay)\n const compiledDirResolved = resolve(projectRoot, resolved.compiledDir)\n\n config.plugins = config.plugins ?? []\n config.plugins.push({\n apply(compiler: WebpackCompiler) {\n let isFirstBuild = true\n compiler.hooks.watchRun.tapAsync('fluenti-dev', (_compiler: WebpackCompiler, callback: () => void) => {\n if (isFirstBuild) {\n isFirstBuild = false\n debouncedRun()\n }\n const modifiedFiles = _compiler.modifiedFiles\n if (modifiedFiles) {\n const hasSourceChange = [...modifiedFiles].some((f: string) =>\n /\\.[jt]sx?$/.test(f)\n && !f.includes('node_modules')\n && !f.includes('.next')\n && !f.startsWith(compiledDirResolved),\n )\n if (hasSourceChange) {\n debouncedRun()\n }\n }\n callback()\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\n// Minimal webpack types for the config function\ninterface WebpackConfig {\n module: {\n rules: Array<{\n test: RegExp\n enforce?: 'pre' | 'post'\n exclude?: Array<RegExp>\n use: Array<{ loader: string; options: Record<string, unknown> }>\n }>\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\ninterface WebpackCompiler {\n hooks: {\n watchRun: {\n tapAsync(name: string, cb: (compiler: WebpackCompiler, callback: () => void) => void): void\n }\n }\n modifiedFiles?: Set<string>\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, FluentInstanceExtended } 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<FluentInstanceExtended & { locale: string }> = throwNotConfigured as () => Promise<FluentInstanceExtended & { 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":"uMAMA,IAAM,EAAoB,OAAO,YAAe,SAC5C,WAAA,EAAA,CACY,IAEV,CAAE,eAAA,EAAA,EAAA,eADsB,EAAkB,CACjB,OAAO,CAUtC,SAAgB,EACd,EACA,EACsB,CACtB,IAAM,EAAa,EAAqB,EAAY,CAE9C,EAAgB,GAAW,eAC5B,GAAY,cACZ,KAEC,EAAU,GAAW,SACtB,GAAY,SACZ,CAAC,EAAc,CAEd,EAAc,GAAW,aAC1B,GAAY,eACZ,yBAEC,EAAqB,GAAW,qBAAA,EAAA,EAAA,MAC5B,eAAgB,WAAW,CAE/B,EAAiC,CACrC,UACA,gBACA,cACA,aAAc,GAAW,cAAgB,KACzC,qBACD,CAKD,OAJI,GAAW,gBAAe,EAAS,cAAgB,EAAU,eAC7D,GAAW,cAAa,EAAS,YAAc,EAAU,aACzD,GAAW,gBAAe,EAAS,cAAgB,EAAU,eAC7D,GAAW,gBAAe,EAAS,cAAgB,EAAU,eAC1D,EAOT,SAAS,EAAqB,EAA2C,CACvE,IAAM,EAAO,EAAW,EAAmB,CACzC,YAAa,GACb,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U,EACV,EAEL,CAAC,CAQJ,OAJI,EACK,EAAgB,EAAQ,EAAQ,CAGlC,GAEV,CCpIH,IAAM,EACJ,wGAEF,SAAS,GAA4B,CACnC,MAAU,MAAM,EAAe,CAIjC,IAAa,EAAsC,EAEtC,EAAsE,EAEtE,EAAkB,EAElB,EAAoK,EAEpK,EAAyO,EAEzO,EAAiP,EAEjP,EAAuF,EAEvF,EAAoF,EAEpF,EAA2F"}
package/dist/index.d.ts CHANGED
@@ -1,9 +1,11 @@
1
+ import { ReactNode, ReactElement } from 'react';
2
+ import { CompileTimeT, FluentInstanceExtended } from '@fluenti/core';
1
3
  /**
2
4
  * @fluenti/next — Next.js plugin for Fluenti
3
5
  *
4
6
  * Provides:
5
7
  * - `withFluenti()` — wraps next.config.ts with t`` transform support
6
- * - FluentProvider — async server component (exported from generated module)
8
+ * - I18nProvider — async server component (exported from generated module)
7
9
  * - Webpack loader for strict, binding-aware tagged-template optimization
8
10
  *
9
11
  * @example
@@ -12,7 +14,68 @@
12
14
  * import { withFluenti } from '@fluenti/next'
13
15
  * export default withFluenti()({ reactStrictMode: true })
14
16
  * ```
17
+ *
18
+ * @example
19
+ * ```tsx
20
+ * // app/layout.tsx — resolved by webpack alias to the generated module
21
+ * import { I18nProvider } from '@fluenti/next'
22
+ * ```
15
23
  */
16
24
  export { withFluenti } from './with-fluenti';
17
- export type { WithFluentConfig, FluentProviderProps } from './types';
25
+ export type { WithFluentConfig, I18nProviderProps } from './types';
26
+ /** @see Generated module for the real implementation. */
27
+ export declare const setLocale: (locale: string) => void;
28
+ /** @see Generated module for the real implementation. */
29
+ export declare const getI18n: () => Promise<FluentInstanceExtended & {
30
+ locale: string;
31
+ }>;
32
+ /** @see Generated module for the real implementation. */
33
+ export declare const t: CompileTimeT;
34
+ /** @see Generated module for the real implementation. */
35
+ export declare const Trans: (props: {
36
+ children: ReactNode;
37
+ id?: string;
38
+ context?: string;
39
+ comment?: string;
40
+ render?: (translation: ReactNode) => ReactNode;
41
+ }) => Promise<ReactElement>;
42
+ /** @see Generated module for the real implementation. */
43
+ export declare const Plural: (props: {
44
+ value: number;
45
+ id?: string;
46
+ context?: string;
47
+ comment?: string;
48
+ zero?: ReactNode;
49
+ one?: ReactNode;
50
+ two?: ReactNode;
51
+ few?: ReactNode;
52
+ many?: ReactNode;
53
+ other: ReactNode;
54
+ offset?: number;
55
+ }) => Promise<ReactElement>;
56
+ /** @see Generated module for the real implementation. */
57
+ export declare const Select: (props: {
58
+ value: string;
59
+ id?: string;
60
+ context?: string;
61
+ comment?: string;
62
+ other: ReactNode;
63
+ options?: Record<string, ReactNode>;
64
+ [key: string]: ReactNode | Record<string, ReactNode> | string | undefined;
65
+ }) => Promise<ReactElement>;
66
+ /** @see Generated module for the real implementation. */
67
+ export declare const DateTime: (props: {
68
+ value: Date | number;
69
+ style?: string;
70
+ }) => Promise<ReactElement>;
71
+ /** @see Generated module for the real implementation. */
72
+ export declare const NumberFormat: (props: {
73
+ value: number;
74
+ style?: string;
75
+ }) => Promise<ReactElement>;
76
+ /** @see Generated module for the real implementation. */
77
+ export declare const I18nProvider: (props: {
78
+ locale?: string;
79
+ children: ReactNode;
80
+ }) => Promise<ReactElement>;
18
81
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAC5C,YAAY,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAC5C,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAA;AASlE,OAAO,KAAK,EAAE,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