next-intlayer 9.0.0-canary.9 → 9.0.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.
Files changed (86) hide show
  1. package/dist/cjs/client/IntlayerClientProvider.cjs +0 -1
  2. package/dist/cjs/client/IntlayerClientProvider.cjs.map +1 -1
  3. package/dist/cjs/client/index.cjs +0 -1
  4. package/dist/cjs/client/useLocale.cjs +2 -2
  5. package/dist/cjs/client/useLocale.cjs.map +1 -1
  6. package/dist/cjs/client/useLocalePageRouter.cjs +2 -2
  7. package/dist/cjs/client/useLocalePageRouter.cjs.map +1 -1
  8. package/dist/cjs/client/usePathname.cjs +2 -2
  9. package/dist/cjs/client/usePathname.cjs.map +1 -1
  10. package/dist/cjs/client/useRewriteURL.cjs +0 -1
  11. package/dist/cjs/generateStaticParams.cjs +0 -1
  12. package/dist/cjs/generateStaticParams.cjs.map +1 -1
  13. package/dist/cjs/index.cjs +0 -1
  14. package/dist/cjs/index.cjs.map +1 -1
  15. package/dist/cjs/proxy/intlayerProxy.cjs +86 -50
  16. package/dist/cjs/proxy/intlayerProxy.cjs.map +1 -1
  17. package/dist/cjs/proxy/localeDetector.cjs +0 -1
  18. package/dist/cjs/proxy/localeDetector.cjs.map +1 -1
  19. package/dist/cjs/proxy/multipleProxies.cjs +0 -1
  20. package/dist/cjs/proxy/multipleProxies.cjs.map +1 -1
  21. package/dist/cjs/server/getLocale.cjs +0 -1
  22. package/dist/cjs/server/getLocale.cjs.map +1 -1
  23. package/dist/cjs/server/index.cjs +0 -1
  24. package/dist/cjs/server/useDictionary.cjs +0 -1
  25. package/dist/cjs/server/useDictionary.cjs.map +1 -1
  26. package/dist/cjs/server/useDictionaryAsync.cjs +0 -1
  27. package/dist/cjs/server/useDictionaryAsync.cjs.map +1 -1
  28. package/dist/cjs/server/useDictionaryDynamic.cjs +0 -1
  29. package/dist/cjs/server/useDictionaryDynamic.cjs.map +1 -1
  30. package/dist/cjs/server/useIntlayer.cjs.map +1 -1
  31. package/dist/cjs/server/withIntlayer.cjs +46 -14
  32. package/dist/cjs/server/withIntlayer.cjs.map +1 -1
  33. package/dist/esm/client/IntlayerClientProvider.mjs.map +1 -1
  34. package/dist/esm/client/useLocale.mjs +2 -1
  35. package/dist/esm/client/useLocale.mjs.map +1 -1
  36. package/dist/esm/client/useLocalePageRouter.mjs +2 -1
  37. package/dist/esm/client/useLocalePageRouter.mjs.map +1 -1
  38. package/dist/esm/client/usePathname.mjs +2 -1
  39. package/dist/esm/client/usePathname.mjs.map +1 -1
  40. package/dist/esm/generateStaticParams.mjs.map +1 -1
  41. package/dist/esm/proxy/intlayerProxy.mjs +87 -50
  42. package/dist/esm/proxy/intlayerProxy.mjs.map +1 -1
  43. package/dist/esm/proxy/localeDetector.mjs.map +1 -1
  44. package/dist/esm/proxy/multipleProxies.mjs.map +1 -1
  45. package/dist/esm/server/getLocale.mjs.map +1 -1
  46. package/dist/esm/server/useDictionary.mjs.map +1 -1
  47. package/dist/esm/server/useDictionaryAsync.mjs.map +1 -1
  48. package/dist/esm/server/useDictionaryDynamic.mjs.map +1 -1
  49. package/dist/esm/server/useIntlayer.mjs.map +1 -1
  50. package/dist/esm/server/withIntlayer.mjs +42 -10
  51. package/dist/esm/server/withIntlayer.mjs.map +1 -1
  52. package/dist/types/client/IntlayerClientProvider.d.ts +0 -1
  53. package/dist/types/client/IntlayerClientProvider.d.ts.map +1 -1
  54. package/dist/types/client/useLocale.d.ts +1 -6
  55. package/dist/types/client/useLocale.d.ts.map +1 -1
  56. package/dist/types/client/useLocalePageRouter.d.ts +1 -5
  57. package/dist/types/client/useLocalePageRouter.d.ts.map +1 -1
  58. package/dist/types/client/usePathname.d.ts.map +1 -1
  59. package/dist/types/generateStaticParams.d.ts.map +1 -1
  60. package/dist/types/index.d.ts +13 -440
  61. package/dist/types/index.d.ts.map +1 -1
  62. package/dist/types/markdown/index.d.ts +0 -3
  63. package/dist/types/proxy/intlayerProxy.d.ts +0 -1
  64. package/dist/types/proxy/intlayerProxy.d.ts.map +1 -1
  65. package/dist/types/proxy/localeDetector.d.ts +0 -1
  66. package/dist/types/proxy/localeDetector.d.ts.map +1 -1
  67. package/dist/types/proxy/middleware.d.ts +4 -4
  68. package/dist/types/proxy/middleware.d.ts.map +1 -1
  69. package/dist/types/proxy/multipleProxies.d.ts +0 -1
  70. package/dist/types/proxy/multipleProxies.d.ts.map +1 -1
  71. package/dist/types/server/getLocale.d.ts +0 -1
  72. package/dist/types/server/getLocale.d.ts.map +1 -1
  73. package/dist/types/server/useDictionary.d.ts +0 -1
  74. package/dist/types/server/useDictionary.d.ts.map +1 -1
  75. package/dist/types/server/useDictionaryAsync.d.ts +0 -1
  76. package/dist/types/server/useDictionaryAsync.d.ts.map +1 -1
  77. package/dist/types/server/useDictionaryDynamic.d.ts +0 -1
  78. package/dist/types/server/useDictionaryDynamic.d.ts.map +1 -1
  79. package/dist/types/server/useIntlayer.d.ts +0 -1
  80. package/dist/types/server/useIntlayer.d.ts.map +1 -1
  81. package/dist/types/server/withIntlayer.d.ts +1 -8
  82. package/dist/types/server/withIntlayer.d.ts.map +1 -1
  83. package/dist/types/types/NextPage.d.ts +0 -1
  84. package/dist/types/types/NextPage.d.ts.map +1 -1
  85. package/dist/types/types/index.d.ts +1 -1
  86. package/package.json +12 -12
@@ -1,5 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
2
  let next_server = require("next/server");
4
3
 
5
4
  //#region src/proxy/multipleProxies.ts
@@ -1 +1 @@
1
- {"version":3,"file":"multipleProxies.cjs","names":["NextResponse"],"sources":["../../../src/proxy/multipleProxies.ts"],"sourcesContent":["import {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\n\n/**\n * Utility to combine multiple Next.js proxies into one.\n *\n * It executes proxies in order, passing each result as the `response` argument\n * to the next proxy. Routing instructions (redirects / rewrites) and custom\n * response headers are merged across the entire chain, so a later proxy that\n * returns `NextResponse.next()` does not accidentally discard a rewrite set by\n * an earlier proxy.\n *\n * @example\n * import { multipleProxies, intlayerProxy } from \"next-intlayer/proxy\";\n * import { NextResponse } from \"next/server\";\n *\n * const authMiddleware = (req: NextRequest) => {\n * if (!req.cookies.get(\"token\")) {\n * return NextResponse.redirect(new URL(\"/login\", req.url));\n * }\n * return NextResponse.next();\n * };\n *\n * export default multipleProxies([\n * intlayerProxy,\n * authMiddleware,\n * ]);\n *\n * @param proxies - An array of proxy functions to execute in order.\n * @returns A single proxy function that runs all provided proxies.\n */\nexport const multipleProxies =\n (\n proxies: ((\n req: NextRequest,\n event?: NextFetchEvent,\n response?: NextResponse\n ) => NextResponse | Promise<NextResponse>)[]\n ) =>\n async (req: NextRequest, event?: NextFetchEvent, response?: NextResponse) => {\n // Snapshots of each proxy's response headers, collected in order.\n const proxyHeaders: Headers[] = [];\n let finalStatus = 200;\n let redirectLocation: string | null = null;\n\n // Each proxy receives the previous proxy's result so it can inspect or\n // augment it. Start with the caller-supplied response (or a plain next()).\n let currentResponse: NextResponse = response ?? NextResponse.next();\n\n for (const proxy of proxies) {\n const result = await proxy(req, event, currentResponse);\n\n // Bail immediately on server errors.\n if (result.status >= 500) {\n return result;\n }\n\n // Track the strongest redirect in the chain.\n if (result.status >= 300 && result.status < 400) {\n finalStatus = result.status;\n const location = result.headers.get('location');\n if (location) redirectLocation = location;\n }\n\n // Snapshot headers *now* to avoid later mutations to the same object\n // corrupting already-recorded entries from earlier proxies.\n proxyHeaders.push(new Headers(result.headers));\n currentResponse = result;\n }\n\n // ── Merge all collected headers ───────────────────────────────────────────\n\n // mergedHeaders: response headers visible to the browser / Next.js routing.\n const mergedHeaders = new Headers();\n // transmittedHeaders: request headers forwarded to the next route handler.\n const transmittedHeaders = new Headers(req.headers);\n\n proxyHeaders.forEach((headers) => {\n for (const [key, value] of headers.entries()) {\n // Routing headers must not be concatenated — last writer wins.\n if (\n key === 'x-middleware-rewrite' ||\n key === 'x-middleware-request-redirect'\n ) {\n mergedHeaders.set(key, value);\n } else {\n mergedHeaders.append(key, value);\n }\n\n // x-middleware-request-<name> → forwarded as <name> to route handlers.\n if (key.startsWith('x-middleware-request-')) {\n const stripped = key.slice('x-middleware-request-'.length);\n transmittedHeaders.set(stripped, value);\n }\n }\n });\n\n // ── Construct the final response ──────────────────────────────────────────\n\n const redirectHeader = mergedHeaders.get('x-middleware-request-redirect');\n const rewriteHeader = mergedHeaders.get('x-middleware-rewrite');\n\n let finalResponse: NextResponse;\n\n if (redirectHeader || redirectLocation) {\n const rawRedirect = (redirectHeader ?? redirectLocation) as string;\n const target = new URL(rawRedirect, req.url);\n // Prevent open redirect: strip to same-origin path/search/hash if the\n // resolved origin differs from the request origin.\n const safeTarget =\n target.origin === req.nextUrl.origin\n ? target\n : new URL(\n `${target.pathname}${target.search}${target.hash}`,\n req.url\n );\n\n finalResponse = NextResponse.redirect(safeTarget, {\n status: finalStatus >= 300 ? finalStatus : 307,\n });\n } else if (rewriteHeader) {\n finalResponse = NextResponse.rewrite(new URL(rewriteHeader, req.url), {\n request: { headers: transmittedHeaders },\n });\n } else {\n finalResponse = NextResponse.next({\n request: { headers: transmittedHeaders },\n });\n }\n\n // Copy all accumulated custom response headers onto the final response,\n // skipping internal Next.js routing headers (already handled above).\n mergedHeaders.forEach((value, key) => {\n if (\n key !== 'x-middleware-rewrite' &&\n key !== 'x-middleware-request-redirect' &&\n !key.startsWith('x-middleware-request-') &&\n key !== 'location'\n ) {\n finalResponse.headers.set(key, value);\n }\n });\n\n return finalResponse;\n };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,mBAET,YAMF,OAAO,KAAkB,OAAwB,aAA4B;CAE3E,MAAM,eAA0B,EAAE;CAClC,IAAI,cAAc;CAClB,IAAI,mBAAkC;CAItC,IAAI,kBAAgC,YAAYA,yBAAa,MAAM;AAEnE,MAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,SAAS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J,eAAc,SAAS,OAAO,QAAQ;AACpC,MACE,QAAQ,0BACR,QAAQ,mCACR,CAAC,IAAI,WAAW,wBAAwB,IACxC,QAAQ,WAER,eAAc,QAAQ,IAAI,KAAK,MAAM;GAEvC;AAEF,QAAO"}
1
+ {"version":3,"file":"multipleProxies.cjs","names":["NextResponse"],"sources":["../../../src/proxy/multipleProxies.ts"],"sourcesContent":["import {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\n\n/**\n * Utility to combine multiple Next.js proxies into one.\n *\n * It executes proxies in order, passing each result as the `response` argument\n * to the next proxy. Routing instructions (redirects / rewrites) and custom\n * response headers are merged across the entire chain, so a later proxy that\n * returns `NextResponse.next()` does not accidentally discard a rewrite set by\n * an earlier proxy.\n *\n * @example\n * import { multipleProxies, intlayerProxy } from \"next-intlayer/proxy\";\n * import { NextResponse } from \"next/server\";\n *\n * const authMiddleware = (req: NextRequest) => {\n * if (!req.cookies.get(\"token\")) {\n * return NextResponse.redirect(new URL(\"/login\", req.url));\n * }\n * return NextResponse.next();\n * };\n *\n * export default multipleProxies([\n * intlayerProxy,\n * authMiddleware,\n * ]);\n *\n * @param proxies - An array of proxy functions to execute in order.\n * @returns A single proxy function that runs all provided proxies.\n */\nexport const multipleProxies =\n (\n proxies: ((\n req: NextRequest,\n event?: NextFetchEvent,\n response?: NextResponse\n ) => NextResponse | Promise<NextResponse>)[]\n ) =>\n async (req: NextRequest, event?: NextFetchEvent, response?: NextResponse) => {\n // Snapshots of each proxy's response headers, collected in order.\n const proxyHeaders: Headers[] = [];\n let finalStatus = 200;\n let redirectLocation: string | null = null;\n\n // Each proxy receives the previous proxy's result so it can inspect or\n // augment it. Start with the caller-supplied response (or a plain next()).\n let currentResponse: NextResponse = response ?? NextResponse.next();\n\n for (const proxy of proxies) {\n const result = await proxy(req, event, currentResponse);\n\n // Bail immediately on server errors.\n if (result.status >= 500) {\n return result;\n }\n\n // Track the strongest redirect in the chain.\n if (result.status >= 300 && result.status < 400) {\n finalStatus = result.status;\n const location = result.headers.get('location');\n if (location) redirectLocation = location;\n }\n\n // Snapshot headers *now* to avoid later mutations to the same object\n // corrupting already-recorded entries from earlier proxies.\n proxyHeaders.push(new Headers(result.headers));\n currentResponse = result;\n }\n\n // ── Merge all collected headers ───────────────────────────────────────────\n\n // mergedHeaders: response headers visible to the browser / Next.js routing.\n const mergedHeaders = new Headers();\n // transmittedHeaders: request headers forwarded to the next route handler.\n const transmittedHeaders = new Headers(req.headers);\n\n proxyHeaders.forEach((headers) => {\n for (const [key, value] of headers.entries()) {\n // Routing headers must not be concatenated — last writer wins.\n if (\n key === 'x-middleware-rewrite' ||\n key === 'x-middleware-request-redirect'\n ) {\n mergedHeaders.set(key, value);\n } else {\n mergedHeaders.append(key, value);\n }\n\n // x-middleware-request-<name> → forwarded as <name> to route handlers.\n if (key.startsWith('x-middleware-request-')) {\n const stripped = key.slice('x-middleware-request-'.length);\n transmittedHeaders.set(stripped, value);\n }\n }\n });\n\n // ── Construct the final response ──────────────────────────────────────────\n\n const redirectHeader = mergedHeaders.get('x-middleware-request-redirect');\n const rewriteHeader = mergedHeaders.get('x-middleware-rewrite');\n\n let finalResponse: NextResponse;\n\n if (redirectHeader || redirectLocation) {\n const rawRedirect = (redirectHeader ?? redirectLocation) as string;\n const target = new URL(rawRedirect, req.url);\n // Prevent open redirect: strip to same-origin path/search/hash if the\n // resolved origin differs from the request origin.\n const safeTarget =\n target.origin === req.nextUrl.origin\n ? target\n : new URL(\n `${target.pathname}${target.search}${target.hash}`,\n req.url\n );\n\n finalResponse = NextResponse.redirect(safeTarget, {\n status: finalStatus >= 300 ? finalStatus : 307,\n });\n } else if (rewriteHeader) {\n finalResponse = NextResponse.rewrite(new URL(rewriteHeader, req.url), {\n request: { headers: transmittedHeaders },\n });\n } else {\n finalResponse = NextResponse.next({\n request: { headers: transmittedHeaders },\n });\n }\n\n // Copy all accumulated custom response headers onto the final response,\n // skipping internal Next.js routing headers (already handled above).\n mergedHeaders.forEach((value, key) => {\n if (\n key !== 'x-middleware-rewrite' &&\n key !== 'x-middleware-request-redirect' &&\n !key.startsWith('x-middleware-request-') &&\n key !== 'location'\n ) {\n finalResponse.headers.set(key, value);\n }\n });\n\n return finalResponse;\n };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,mBAET,YAMF,OAAO,KAAkB,OAAwB,aAA4B;CAE3E,MAAM,eAA0B,CAAC;CACjC,IAAI,cAAc;CAClB,IAAI,mBAAkC;CAItC,IAAI,kBAAgC,YAAYA,yBAAa,KAAK;CAElE,KAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,SAAS,MAAM,MAAM,KAAK,OAAO,eAAe;EAGtD,IAAI,OAAO,UAAU,KACnB,OAAO;EAIT,IAAI,OAAO,UAAU,OAAO,OAAO,SAAS,KAAK;GAC/C,cAAc,OAAO;GACrB,MAAM,WAAW,OAAO,QAAQ,IAAI,UAAU;GAC9C,IAAI,UAAU,mBAAmB;EACnC;EAIA,aAAa,KAAK,IAAI,QAAQ,OAAO,OAAO,CAAC;EAC7C,kBAAkB;CACpB;CAKA,MAAM,gBAAgB,IAAI,QAAQ;CAElC,MAAM,qBAAqB,IAAI,QAAQ,IAAI,OAAO;CAElD,aAAa,SAAS,YAAY;EAChC,KAAK,MAAM,CAAC,KAAK,UAAU,QAAQ,QAAQ,GAAG;GAE5C,IACE,QAAQ,0BACR,QAAQ,iCAER,cAAc,IAAI,KAAK,KAAK;QAE5B,cAAc,OAAO,KAAK,KAAK;GAIjC,IAAI,IAAI,WAAW,uBAAuB,GAAG;IAC3C,MAAM,WAAW,IAAI,MAAM,EAA8B;IACzD,mBAAmB,IAAI,UAAU,KAAK;GACxC;EACF;CACF,CAAC;CAID,MAAM,iBAAiB,cAAc,IAAI,+BAA+B;CACxE,MAAM,gBAAgB,cAAc,IAAI,sBAAsB;CAE9D,IAAI;CAEJ,IAAI,kBAAkB,kBAAkB;EAEtC,MAAM,SAAS,IAAI,IADE,kBAAkB,kBACH,IAAI,GAAG;EAG3C,MAAM,aACJ,OAAO,WAAW,IAAI,QAAQ,SAC1B,SACA,IAAI,IACF,GAAG,OAAO,WAAW,OAAO,SAAS,OAAO,QAC5C,IAAI,GACN;EAEN,gBAAgBA,yBAAa,SAAS,YAAY,EAChD,QAAQ,eAAe,MAAM,cAAc,IAC7C,CAAC;CACH,OAAO,IAAI,eACT,gBAAgBA,yBAAa,QAAQ,IAAI,IAAI,eAAe,IAAI,GAAG,GAAG,EACpE,SAAS,EAAE,SAAS,mBAAmB,EACzC,CAAC;MAED,gBAAgBA,yBAAa,KAAK,EAChC,SAAS,EAAE,SAAS,mBAAmB,EACzC,CAAC;CAKH,cAAc,SAAS,OAAO,QAAQ;EACpC,IACE,QAAQ,0BACR,QAAQ,mCACR,CAAC,IAAI,WAAW,uBAAuB,KACvC,QAAQ,YAER,cAAc,QAAQ,IAAI,KAAK,KAAK;CAExC,CAAC;CAED,OAAO;AACT"}
@@ -1,5 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
2
  let _intlayer_core_localization = require("@intlayer/core/localization");
4
3
  let _intlayer_core_utils = require("@intlayer/core/utils");
5
4
  let _intlayer_config_built = require("@intlayer/config/built");
@@ -1 +1 @@
1
- {"version":3,"file":"getLocale.cjs","names":["internationalization","DEFAULT_LOCALE"],"sources":["../../../src/server/getLocale.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { cookies, headers } from 'next/headers.js';\n\n// Helper function to extract locale from headers/cookies\n/**\n * Helper function to extract the current locale from Next.js headers and cookies.\n *\n * This function is designed to be used in Server Components, Server Actions, or Route Handlers\n * to determine the locale preferred by the user or stored in their preferences.\n *\n * @returns A promise that resolves to the detected `Locale`.\n *\n * @example\n * ```tsx\n * import { getLocale } from 'next-intlayer/server';\n *\n * export default async function MyServerComponent() {\n * const locale = await getLocale();\n * // ...\n * }\n * ```\n */\nexport const getLocale = async (): Promise<Locale> => {\n const defaultLocale = internationalization?.defaultLocale ?? DEFAULT_LOCALE;\n\n // Try locale from header\n const headersList = await headers();\n const cookiesList = await cookies();\n\n const storedLocale = getLocaleFromStorageServer({\n getCookie: (name: string) => cookiesList.get(name)?.value ?? null,\n getHeader: (name: string) => headersList.get(name) ?? null,\n });\n\n if (storedLocale) return storedLocale as Locale;\n\n // Fallback to Accept-Language negotiation\n const negotiatorHeaders: Record<string, string> = {};\n headersList.forEach((value, key) => {\n negotiatorHeaders[key] = value;\n });\n\n const userFallbackLocale = localeDetector(negotiatorHeaders);\n if (userFallbackLocale) return userFallbackLocale as Locale;\n\n // Default locale\n return defaultLocale;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,YAAY,YAA6B;CACpD,MAAM,gBAAgBA,6CAAsB,iBAAiBC;CAG7D,MAAM,cAAc,oCAAe;CACnC,MAAM,cAAc,oCAAe;CAEnC,MAAM,oEAA0C;EAC9C,YAAY,SAAiB,YAAY,IAAI,KAAK,EAAE,SAAS;EAC7D,YAAY,SAAiB,YAAY,IAAI,KAAK,IAAI;EACvD,CAAC;AAEF,KAAI,aAAc,QAAO;CAGzB,MAAM,oBAA4C,EAAE;AACpD,aAAY,SAAS,OAAO,QAAQ;AAClC,oBAAkB,OAAO;GACzB;CAEF,MAAM,qEAAoC,kBAAkB;AAC5D,KAAI,mBAAoB,QAAO;AAG/B,QAAO"}
1
+ {"version":3,"file":"getLocale.cjs","names":["internationalization","DEFAULT_LOCALE"],"sources":["../../../src/server/getLocale.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { cookies, headers } from 'next/headers.js';\n\n// Helper function to extract locale from headers/cookies\n/**\n * Helper function to extract the current locale from Next.js headers and cookies.\n *\n * This function is designed to be used in Server Components, Server Actions, or Route Handlers\n * to determine the locale preferred by the user or stored in their preferences.\n *\n * @returns A promise that resolves to the detected `Locale`.\n *\n * @example\n * ```tsx\n * import { getLocale } from 'next-intlayer/server';\n *\n * export default async function MyServerComponent() {\n * const locale = await getLocale();\n * // ...\n * }\n * ```\n */\nexport const getLocale = async (): Promise<Locale> => {\n const defaultLocale = internationalization?.defaultLocale ?? DEFAULT_LOCALE;\n\n // Try locale from header\n const headersList = await headers();\n const cookiesList = await cookies();\n\n const storedLocale = getLocaleFromStorageServer({\n getCookie: (name: string) => cookiesList.get(name)?.value ?? null,\n getHeader: (name: string) => headersList.get(name) ?? null,\n });\n\n if (storedLocale) return storedLocale as Locale;\n\n // Fallback to Accept-Language negotiation\n const negotiatorHeaders: Record<string, string> = {};\n headersList.forEach((value, key) => {\n negotiatorHeaders[key] = value;\n });\n\n const userFallbackLocale = localeDetector(negotiatorHeaders);\n if (userFallbackLocale) return userFallbackLocale as Locale;\n\n // Default locale\n return defaultLocale;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,YAAY,YAA6B;CACpD,MAAM,gBAAgBA,6CAAsB,iBAAiBC;CAG7D,MAAM,cAAc,mCAAc;CAClC,MAAM,cAAc,mCAAc;CAElC,MAAM,oEAA0C;EAC9C,YAAY,SAAiB,YAAY,IAAI,IAAI,CAAC,EAAE,SAAS;EAC7D,YAAY,SAAiB,YAAY,IAAI,IAAI,KAAK;CACxD,CAAC;CAED,IAAI,cAAc,OAAO;CAGzB,MAAM,oBAA4C,CAAC;CACnD,YAAY,SAAS,OAAO,QAAQ;EAClC,kBAAkB,OAAO;CAC3B,CAAC;CAED,MAAM,qEAAoC,iBAAiB;CAC3D,IAAI,oBAAoB,OAAO;CAG/B,OAAO;AACT"}
@@ -1,5 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
2
  const require_server_getLocale = require('./getLocale.cjs');
4
3
  const require_server_withIntlayer = require('./withIntlayer.cjs');
5
4
  let react_intlayer_server = require("react-intlayer/server");
@@ -1,5 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
2
  const require_server_useIntlayer = require('./useIntlayer.cjs');
4
3
  let react_intlayer_server = require("react-intlayer/server");
5
4
 
@@ -1 +1 @@
1
- {"version":3,"file":"useDictionary.cjs","names":["safeUseLocale"],"sources":["../../../src/server/useDictionary.ts"],"sourcesContent":["import type {\n Dictionary,\n DictionarySelector,\n DictionarySelectorForGroup,\n QualifiedDictionaryGroup,\n} from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { useDictionary as useDictionaryBase } from 'react-intlayer/server';\nimport { safeUseLocale } from './useIntlayer';\n\n/**\n * On the server side, hook that transforms a dictionary (or qualified\n * dictionary group) and returns the content for the given locale or selector.\n *\n * If the locale is not provided, it will use the locale from the server context.\n */\nexport const useDictionary = <\n const T extends Dictionary | QualifiedDictionaryGroup,\n const A extends\n | LocalesValues\n | DictionarySelectorForGroup<T> = DeclaredLocales,\n>(\n dictionary: T,\n localeOrSelector?: A\n): ReturnType<typeof useDictionaryBase<T, A>> => {\n const storedLocale = safeUseLocale();\n\n return useDictionaryBase<T, A>(dictionary, localeOrSelector, storedLocale);\n};\n"],"mappings":";;;;;;;;;;;;AAmBA,MAAa,iBAMX,YACA,qBAC+C;AAG/C,iDAA+B,YAAY,kBAFtBA,0CAEoD,CAAC"}
1
+ {"version":3,"file":"useDictionary.cjs","names":["safeUseLocale"],"sources":["../../../src/server/useDictionary.ts"],"sourcesContent":["import type {\n Dictionary,\n DictionarySelector,\n DictionarySelectorForGroup,\n QualifiedDictionaryGroup,\n} from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { useDictionary as useDictionaryBase } from 'react-intlayer/server';\nimport { safeUseLocale } from './useIntlayer';\n\n/**\n * On the server side, hook that transforms a dictionary (or qualified\n * dictionary group) and returns the content for the given locale or selector.\n *\n * If the locale is not provided, it will use the locale from the server context.\n */\nexport const useDictionary = <\n const T extends Dictionary | QualifiedDictionaryGroup,\n const A extends\n | LocalesValues\n | DictionarySelectorForGroup<T> = DeclaredLocales,\n>(\n dictionary: T,\n localeOrSelector?: A\n): ReturnType<typeof useDictionaryBase<T, A>> => {\n const storedLocale = safeUseLocale();\n\n return useDictionaryBase<T, A>(dictionary, localeOrSelector, storedLocale);\n};\n"],"mappings":";;;;;;;;;;;AAmBA,MAAa,iBAMX,YACA,qBAC+C;CAG/C,gDAA+B,YAAY,kBAFtBA,yCAEmD,CAAC;AAC3E"}
@@ -1,5 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
2
  const require_server_getLocale = require('./getLocale.cjs');
4
3
  let react_intlayer_server = require("react-intlayer/server");
5
4
 
@@ -1 +1 @@
1
- {"version":3,"file":"useDictionaryAsync.cjs","names":["getLocale"],"sources":["../../../src/server/useDictionaryAsync.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n StrictModeLocaleMap,\n} from '@intlayer/types/module_augmentation';\nimport { useDictionaryAsync as useDictionaryAsyncBase } from 'react-intlayer/server';\nimport { getLocale } from './getLocale';\n\n/**\n * On the server side, Hook that transform a dictionary and return the content\n *\n * If the locale is not provided, it will use the locale from the server context\n */\nexport const useDictionaryAsync = async <\n const T extends Dictionary,\n const L extends DeclaredLocales = DeclaredLocales,\n>(\n dictionaryPromise: StrictModeLocaleMap<() => Promise<T>>,\n locale?: L\n): ReturnType<typeof useDictionaryAsyncBase<T, L>> => {\n const storedLocale = await getLocale();\n\n return useDictionaryAsyncBase<T, L>(dictionaryPromise, locale, storedLocale);\n};\n"],"mappings":";;;;;;;;;;;AAaA,MAAa,qBAAqB,OAIhC,mBACA,WACoD;AAGpD,sDAAoC,mBAAmB,QAAQ,MAFpCA,oCAAW,CAEsC"}
1
+ {"version":3,"file":"useDictionaryAsync.cjs","names":["getLocale"],"sources":["../../../src/server/useDictionaryAsync.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n StrictModeLocaleMap,\n} from '@intlayer/types/module_augmentation';\nimport { useDictionaryAsync as useDictionaryAsyncBase } from 'react-intlayer/server';\nimport { getLocale } from './getLocale';\n\n/**\n * On the server side, Hook that transform a dictionary and return the content\n *\n * If the locale is not provided, it will use the locale from the server context\n */\nexport const useDictionaryAsync = async <\n const T extends Dictionary,\n const L extends DeclaredLocales = DeclaredLocales,\n>(\n dictionaryPromise: StrictModeLocaleMap<() => Promise<T>>,\n locale?: L\n): ReturnType<typeof useDictionaryAsyncBase<T, L>> => {\n const storedLocale = await getLocale();\n\n return useDictionaryAsyncBase<T, L>(dictionaryPromise, locale, storedLocale);\n};\n"],"mappings":";;;;;;;;;;AAaA,MAAa,qBAAqB,OAIhC,mBACA,WACoD;CAGpD,qDAAoC,mBAAmB,QAAQ,MAFpCA,mCAAU,CAEsC;AAC7E"}
@@ -1,5 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
2
  const require_server_useIntlayer = require('./useIntlayer.cjs');
4
3
  let react_intlayer_server = require("react-intlayer/server");
5
4
 
@@ -1 +1 @@
1
- {"version":3,"file":"useDictionaryDynamic.cjs","names":["safeUseLocale"],"sources":["../../../src/server/useDictionaryDynamic.ts"],"sourcesContent":["import type { QualifiedDynamicLoaderMap } from '@intlayer/core/dictionaryManipulator';\nimport type {\n Dictionary,\n DictionarySelector,\n} from '@intlayer/types/dictionary';\nimport type {\n LocalesValues,\n StrictModeLocaleMap,\n} from '@intlayer/types/module_augmentation';\nimport { useDictionaryDynamic as useDictionaryDynamicBase } from 'react-intlayer/server';\nimport { safeUseLocale } from './useIntlayer';\n\n/**\n * On the server side, hook that lazily loads a dictionary (plain or qualified)\n * and returns the content for the given locale or selector.\n *\n * If the locale is not provided, it will use the locale from the server context.\n */\nexport const useDictionaryDynamic = <\n const T extends Dictionary,\n const A extends LocalesValues | DictionarySelector = LocalesValues,\n>(\n dictionaryPromise:\n | StrictModeLocaleMap<() => Promise<T>>\n | QualifiedDynamicLoaderMap,\n key: string,\n localeOrSelector?: A\n): ReturnType<typeof useDictionaryDynamicBase<T, A>> => {\n const storedLocale = safeUseLocale();\n\n return useDictionaryDynamicBase<T, A>(\n dictionaryPromise,\n key,\n localeOrSelector,\n storedLocale\n );\n};\n"],"mappings":";;;;;;;;;;;;AAkBA,MAAa,wBAIX,mBAGA,KACA,qBACsD;AAGtD,wDACE,mBACA,KACA,kBALmBA,0CAMP,CACb"}
1
+ {"version":3,"file":"useDictionaryDynamic.cjs","names":["safeUseLocale"],"sources":["../../../src/server/useDictionaryDynamic.ts"],"sourcesContent":["import type { QualifiedDynamicLoaderMap } from '@intlayer/core/dictionaryManipulator';\nimport type {\n Dictionary,\n DictionarySelector,\n} from '@intlayer/types/dictionary';\nimport type {\n LocalesValues,\n StrictModeLocaleMap,\n} from '@intlayer/types/module_augmentation';\nimport { useDictionaryDynamic as useDictionaryDynamicBase } from 'react-intlayer/server';\nimport { safeUseLocale } from './useIntlayer';\n\n/**\n * On the server side, hook that lazily loads a dictionary (plain or qualified)\n * and returns the content for the given locale or selector.\n *\n * If the locale is not provided, it will use the locale from the server context.\n */\nexport const useDictionaryDynamic = <\n const T extends Dictionary,\n const A extends LocalesValues | DictionarySelector = LocalesValues,\n>(\n dictionaryPromise:\n | StrictModeLocaleMap<() => Promise<T>>\n | QualifiedDynamicLoaderMap,\n key: string,\n localeOrSelector?: A\n): ReturnType<typeof useDictionaryDynamicBase<T, A>> => {\n const storedLocale = safeUseLocale();\n\n return useDictionaryDynamicBase<T, A>(\n dictionaryPromise,\n key,\n localeOrSelector,\n storedLocale\n );\n};\n"],"mappings":";;;;;;;;;;;AAkBA,MAAa,wBAIX,mBAGA,KACA,qBACsD;CAGtD,uDACE,mBACA,KACA,kBALmBA,yCAMR,CACb;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"useIntlayer.cjs","names":["React","getLocale"],"sources":["../../../src/server/useIntlayer.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n DictionarySelectorForKey,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport React from 'react';\nimport { useIntlayer as useIntlayerBase } from 'react-intlayer/server';\nimport { getLocale } from './getLocale';\n\nconst getCachedLocale =\n typeof React.cache === 'function' ? React.cache(getLocale) : getLocale;\n\nexport const safeUseLocale = (): Locale | undefined => {\n // getLocale returns a Promise based on your TS error\n const localeData = getCachedLocale() as Promise<Locale> | Locale;\n\n if (localeData instanceof Promise) {\n if (typeof React.use === 'function') {\n return React.use(localeData); // Safely unwraps in React 19+\n }\n\n // React < 19 cannot synchronously unwrap Promises in hooks.\n // Return undefined to trigger the localeTarget fallback.\n return undefined;\n }\n\n return localeData;\n};\n\n/**\n * On the server side, hook that picks one dictionary by its key and returns the\n * content for the given locale or selector (`{ item }`, `{ variant }`,\n * optionally combined with `locale`).\n *\n * If the locale is not provided, it will use the locale from the server context.\n */\nexport const useIntlayer = <\n const T extends DictionaryKeys,\n const A extends LocalesValues | DictionarySelectorForKey<T> = DeclaredLocales,\n>(\n key: T,\n localeOrSelector?: A\n): ReturnType<typeof useIntlayerBase<T, A>> => {\n const storedLocale = safeUseLocale();\n\n return useIntlayerBase<T, A>(key, localeOrSelector, storedLocale);\n};\n"],"mappings":";;;;;;;;AAWA,MAAM,kBACJ,OAAOA,cAAM,UAAU,aAAaA,cAAM,MAAMC,mCAAU,GAAGA;AAE/D,MAAa,sBAA0C;CAErD,MAAM,aAAa,iBAAiB;AAEpC,KAAI,sBAAsB,SAAS;AACjC,MAAI,OAAOD,cAAM,QAAQ,WACvB,QAAOA,cAAM,IAAI,WAAW;AAK9B;;AAGF,QAAO;;;;;;;;;AAUT,MAAa,eAIX,KACA,qBAC6C;AAG7C,+CAA6B,KAAK,kBAFb,eAE2C,CAAC"}
1
+ {"version":3,"file":"useIntlayer.cjs","names":["React","getLocale"],"sources":["../../../src/server/useIntlayer.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n DictionarySelectorForKey,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport React from 'react';\nimport { useIntlayer as useIntlayerBase } from 'react-intlayer/server';\nimport { getLocale } from './getLocale';\n\nconst getCachedLocale =\n typeof React.cache === 'function' ? React.cache(getLocale) : getLocale;\n\nexport const safeUseLocale = (): Locale | undefined => {\n // getLocale returns a Promise based on your TS error\n const localeData = getCachedLocale() as Promise<Locale> | Locale;\n\n if (localeData instanceof Promise) {\n if (typeof React.use === 'function') {\n return React.use(localeData); // Safely unwraps in React 19+\n }\n\n // React < 19 cannot synchronously unwrap Promises in hooks.\n // Return undefined to trigger the localeTarget fallback.\n return undefined;\n }\n\n return localeData;\n};\n\n/**\n * On the server side, hook that picks one dictionary by its key and returns the\n * content for the given locale or selector (`{ item }`, `{ variant }`,\n * optionally combined with `locale`).\n *\n * If the locale is not provided, it will use the locale from the server context.\n */\nexport const useIntlayer = <\n const T extends DictionaryKeys,\n const A extends LocalesValues | DictionarySelectorForKey<T> = DeclaredLocales,\n>(\n key: T,\n localeOrSelector?: A\n): ReturnType<typeof useIntlayerBase<T, A>> => {\n const storedLocale = safeUseLocale();\n\n return useIntlayerBase<T, A>(key, localeOrSelector, storedLocale);\n};\n"],"mappings":";;;;;;;;AAWA,MAAM,kBACJ,OAAOA,cAAM,UAAU,aAAaA,cAAM,MAAMC,kCAAS,IAAIA;AAE/D,MAAa,sBAA0C;CAErD,MAAM,aAAa,gBAAgB;CAEnC,IAAI,sBAAsB,SAAS;EACjC,IAAI,OAAOD,cAAM,QAAQ,YACvB,OAAOA,cAAM,IAAI,UAAU;EAK7B;CACF;CAEA,OAAO;AACT;;;;;;;;AASA,MAAa,eAIX,KACA,qBAC6C;CAG7C,8CAA6B,KAAK,kBAFb,cAE0C,CAAC;AAClE"}
@@ -2,9 +2,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
3
  let _intlayer_config_defaultValues = require("@intlayer/config/defaultValues");
4
4
  let node_path = require("node:path");
5
- let _intlayer_chokidar_build = require("@intlayer/chokidar/build");
6
- let _intlayer_chokidar_cli = require("@intlayer/chokidar/cli");
7
- let _intlayer_chokidar_utils = require("@intlayer/chokidar/utils");
8
5
  let _intlayer_config_colors = require("@intlayer/config/colors");
9
6
  _intlayer_config_colors = require_runtime.__toESM(_intlayer_config_colors);
10
7
  let _intlayer_config_envVars = require("@intlayer/config/envVars");
@@ -12,6 +9,9 @@ let _intlayer_config_logger = require("@intlayer/config/logger");
12
9
  let _intlayer_config_node = require("@intlayer/config/node");
13
10
  let _intlayer_config_utils = require("@intlayer/config/utils");
14
11
  let _intlayer_dictionaries_entry = require("@intlayer/dictionaries-entry");
12
+ let _intlayer_engine_build = require("@intlayer/engine/build");
13
+ let _intlayer_engine_cli = require("@intlayer/engine/cli");
14
+ let _intlayer_engine_utils = require("@intlayer/engine/utils");
15
15
  let _intlayer_webpack = require("@intlayer/webpack");
16
16
  let defu = require("defu");
17
17
  let next_package_json = require("next/package.json");
@@ -66,7 +66,7 @@ const getPruneConfig = (intlayerConfig, isBuildCommand, isTurbopackEnabled, isDe
66
66
  if (optimize === void 0 && !isBuildCommand) return {};
67
67
  if (!isGteNext13) return {};
68
68
  const isSwcPluginAvailable = getIsSwcPluginAvailable(intlayerConfig);
69
- (0, _intlayer_chokidar_utils.runOnce)((0, node_path.join)(baseDir, ".intlayer", "cache", "intlayer-prune-plugin-enabled.lock"), () => {
69
+ (0, _intlayer_engine_utils.runOnce)((0, node_path.join)(baseDir, ".intlayer", "cache", "intlayer-prune-plugin-enabled.lock"), () => {
70
70
  if (isSwcPluginAvailable) logger([
71
71
  `Build optimization ${(0, _intlayer_config_logger.colorize)("enabled", _intlayer_config_colors.GREEN)}`,
72
72
  (0, _intlayer_config_logger.colorize)(`(import mode:`, _intlayer_config_colors.GREY_DARK),
@@ -80,7 +80,7 @@ const getPruneConfig = (intlayerConfig, isBuildCommand, isTurbopackEnabled, isDe
80
80
  (0, _intlayer_config_logger.colorize)("https://intlayer.org/docs/bundle-optimization", _intlayer_config_colors.GREY_LIGHT)
81
81
  ]);
82
82
  }, { cacheTimeoutMs: 1e3 * 30 });
83
- (0, _intlayer_chokidar_utils.runOnce)((0, node_path.join)(baseDir, ".intlayer", "cache", "intlayer-compiler-plugin-enabled.lock"), () => {
83
+ (0, _intlayer_engine_utils.runOnce)((0, node_path.join)(baseDir, ".intlayer", "cache", "intlayer-compiler-plugin-enabled.lock"), () => {
84
84
  if (getIsBabelExtractPluginAvailable(intlayerConfig)) {
85
85
  let isEnabled = intlayerConfig.compiler?.enabled ?? true;
86
86
  if (isEnabled === "build-only") isEnabled = !isDevCommand;
@@ -94,7 +94,7 @@ const getPruneConfig = (intlayerConfig, isBuildCommand, isTurbopackEnabled, isDe
94
94
  const unmergedDictionariesEntryPath = (0, node_path.join)(mainDir, "unmerged_dictionaries.mjs");
95
95
  const fetchDictionariesEntryPath = (0, node_path.join)(mainDir, "fetch_dictionaries.mjs");
96
96
  const filesList = [
97
- ...(0, _intlayer_chokidar_utils.buildComponentFilesList)(intlayerConfig),
97
+ ...(0, _intlayer_engine_utils.buildComponentFilesList)(intlayerConfig),
98
98
  dictionariesEntryPath,
99
99
  unmergedDictionariesEntryPath
100
100
  ];
@@ -129,6 +129,35 @@ const getCommandsEvent = () => {
129
129
  };
130
130
  };
131
131
  /**
132
+ * Pin the env file used to resolve the Intlayer configuration to the Next.js
133
+ * command being run (`dev` → `development`, `build`/`start` → `production`).
134
+ *
135
+ * Next.js loads the config file in several processes during a single command
136
+ * (the main `build` process plus one or more Turbopack/webpack workers), and
137
+ * `process.env.NODE_ENV` is not guaranteed to hold the same value in all of
138
+ * them. Since `getConfiguration` falls back to `NODE_ENV` to pick its env file
139
+ * (`.env.development.local` vs `.env.production.local`), those processes could
140
+ * otherwise resolve *different* env values (e.g. `applicationURL`,
141
+ * `INTLAYER_CLIENT_ID`). The resulting configuration would differ between
142
+ * processes, defeating the `isCachedConfigurationUpToDate` check and forcing a
143
+ * redundant full dictionary rebuild.
144
+ *
145
+ * Passing an explicit `env` keeps configuration resolution deterministic across
146
+ * every process of the command. An `env` already set by the caller is
147
+ * respected, and when the command cannot be determined we fall back to
148
+ * `getConfiguration`'s own default (i.e. leave `env` unset).
149
+ */
150
+ const resolveConfigOptions = (configOptions) => {
151
+ if (configOptions?.env) return configOptions;
152
+ const { isDevCommand, isBuildCommand, isStartCommand } = getCommandsEvent();
153
+ const env = isDevCommand ? "development" : isBuildCommand || isStartCommand ? "production" : void 0;
154
+ if (!env) return configOptions;
155
+ return {
156
+ ...configOptions,
157
+ env
158
+ };
159
+ };
160
+ /**
132
161
  * A Next.js plugin that adds the intlayer configuration to the webpack configuration
133
162
  * and sets the environment variables
134
163
  *
@@ -141,8 +170,9 @@ const getCommandsEvent = () => {
141
170
  */
142
171
  const withIntlayerSync = (nextConfig = {}, configOptions) => {
143
172
  if (typeof nextConfig !== "object") nextConfig = {};
144
- const intlayerConfig = (0, _intlayer_config_node.getConfiguration)(configOptions);
145
- (0, _intlayer_chokidar_cli.logConfigDetails)(configOptions);
173
+ const resolvedConfigOptions = resolveConfigOptions(configOptions);
174
+ const intlayerConfig = (0, _intlayer_config_node.getConfiguration)(resolvedConfigOptions);
175
+ (0, _intlayer_engine_cli.logConfigDetails)(resolvedConfigOptions);
146
176
  const appLogger = (0, _intlayer_config_logger.getAppLogger)(intlayerConfig);
147
177
  const { isGteNext13, isGteNext15, isGteNext16, isTurbopackStable } = getNextVersionFlags(intlayerConfig);
148
178
  const isTurbopackEnabledFromCommand = isGteNext16 ? !process.env["npm_lifecycle_script"]?.includes("--webpack") : process.env["npm_lifecycle_script"]?.includes("--turbo");
@@ -166,7 +196,7 @@ const withIntlayerSync = (nextConfig = {}, configOptions) => {
166
196
  "chokidar",
167
197
  "fsevents",
168
198
  "recast",
169
- "@intlayer/chokidar",
199
+ "@intlayer/engine",
170
200
  "@intlayer/webpack"
171
201
  ];
172
202
  let env = {};
@@ -216,7 +246,7 @@ const withIntlayerSync = (nextConfig = {}, configOptions) => {
216
246
  const { isServer, nextRuntime } = options;
217
247
  if (typeof nextConfig.webpack === "function") config = nextConfig.webpack(config, options);
218
248
  if (config.externals === false) config.externals = [];
219
- const externalExact = new Set([
249
+ const externalExact = /* @__PURE__ */ new Set([
220
250
  "esbuild",
221
251
  "module",
222
252
  "fs",
@@ -224,7 +254,7 @@ const withIntlayerSync = (nextConfig = {}, configOptions) => {
224
254
  "fsevents",
225
255
  "recast"
226
256
  ]);
227
- const externalPrefixes = ["@intlayer/chokidar", "@intlayer/webpack"];
257
+ const externalPrefixes = ["@intlayer/engine", "@intlayer/webpack"];
228
258
  config.externals.push(({ request }, callback) => {
229
259
  if (request && (externalExact.has(request) || externalPrefixes.some((prefix) => request === prefix || request.startsWith(`${prefix}/`)))) return callback(null, `commonjs ${request}`);
230
260
  callback(null);
@@ -267,14 +297,16 @@ const withIntlayerSync = (nextConfig = {}, configOptions) => {
267
297
  const withIntlayer = async (nextConfig = {}, configOptions) => {
268
298
  const { isBuildCommand, isDevCommand, isStartCommand } = getCommandsEvent();
269
299
  process.env.INTLAYER_IS_DEV_COMMAND = isDevCommand ? "true" : "false";
270
- const intlayerConfig = (0, _intlayer_config_node.getConfiguration)(configOptions);
300
+ const resolvedConfigOptions = resolveConfigOptions(configOptions);
301
+ const intlayerConfig = (0, _intlayer_config_node.getConfiguration)(resolvedConfigOptions);
271
302
  const { mode } = intlayerConfig.build;
272
- if (!isStartCommand && (isDevCommand || isBuildCommand || mode === "auto")) await (0, _intlayer_chokidar_build.prepareIntlayer)(intlayerConfig, {
303
+ if (!isStartCommand && (isDevCommand || isBuildCommand || mode === "auto")) await (0, _intlayer_engine_build.prepareIntlayer)(intlayerConfig, {
273
304
  clean: isBuildCommand,
274
305
  cacheTimeoutMs: isBuildCommand ? 1e3 * 30 : 1e3 * 60 * 60,
275
306
  env: isBuildCommand ? "prod" : "dev"
276
307
  });
277
- return withIntlayerSync(await nextConfig, configOptions);
308
+ const nextConfigResolved = await nextConfig;
309
+ return withIntlayerSync(nextConfigResolved, resolvedConfigOptions);
278
310
  };
279
311
 
280
312
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"withIntlayer.cjs","names":["nextPackageJSON","ANSIColors","IMPORT_MODE","IntlayerPlugin"],"sources":["../../../src/server/withIntlayer.ts"],"sourcesContent":["import { join, relative, resolve } from 'node:path';\nimport { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { logConfigDetails } from '@intlayer/chokidar/cli';\nimport { buildComponentFilesList, runOnce } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { IMPORT_MODE } from '@intlayer/config/defaultValues';\nimport {\n formatDictionarySelectorEnvVar,\n formatNodeTypeToEnvVar,\n getConfigEnvVars,\n} from '@intlayer/config/envVars';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n compareVersions,\n getAlias,\n getHasDictionarySelector,\n getProjectRequire,\n getUnusedNodeTypes,\n normalizePath,\n} from '@intlayer/config/utils';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { IntlayerPlugin } from '@intlayer/webpack';\nimport { defu } from 'defu';\nimport type { NextConfig } from 'next';\nimport type { NextJsWebpackConfig } from 'next/dist/server/config-shared';\nimport nextPackageJSON from 'next/package.json' with { type: 'json' };\n\n/**\n * Resolve the Next.js version from the *user's* project at runtime.\n * A static `import from 'next/package.json'` would resolve relative to\n * next-intlayer's own node_modules, which may differ in a monorepo.\n */\nconst getNextVersionFlags = (intlayerConfig: IntlayerConfig) => {\n let nextVersion = nextPackageJSON.version;\n\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n const pkg = requireFunction('next/package.json') as { version: string };\n nextVersion = pkg.version;\n } catch {\n // keep default\n }\n\n return {\n isGteNext13: compareVersions(nextVersion, '≥', '13.0.0'),\n isGteNext15: compareVersions(nextVersion, '≥', '15.0.0'),\n isGteNext16: compareVersions(nextVersion, '≥', '16.0.0'),\n isTurbopackStable: compareVersions(nextVersion, '≥', '15.3.0'),\n };\n};\n\n// Check if SWC plugin is available\nconst getIsSwcPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/swc');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\n// Check if Babel plugin is available\nconst getIsBabelExtractPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/babel');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\nconst resolvePluginPath = (\n pluginPath: string,\n intlayerConfig: IntlayerConfig,\n isTurbopackEnabled: boolean\n): string => {\n const requireFunction = intlayerConfig.build?.require ?? getProjectRequire();\n const pluginPathResolved = requireFunction?.resolve(pluginPath);\n\n if (isTurbopackEnabled)\n // Relative path for turbopack\n return normalizePath(`./${relative(process.cwd(), pluginPathResolved)}`);\n\n // Absolute path for webpack\n return pluginPathResolved;\n};\n\nconst getPruneConfig = (\n intlayerConfig: IntlayerConfig,\n isBuildCommand: boolean,\n isTurbopackEnabled: boolean,\n isDevCommand: boolean,\n isGteNext13: boolean,\n swcExtraCallers?: SwcExtraCallerConfig[]\n): Partial<NextConfig> => {\n const { optimize } = intlayerConfig.build;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n const {\n dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.system;\n const logger = getAppLogger(intlayerConfig);\n\n if (optimize === false) {\n return {};\n }\n if (optimize === undefined && !isBuildCommand) {\n return {};\n }\n\n if (!isGteNext13) return {};\n\n const isSwcPluginAvailable = getIsSwcPluginAvailable(intlayerConfig);\n\n runOnce(\n join(baseDir, '.intlayer', 'cache', 'intlayer-prune-plugin-enabled.lock'),\n () => {\n if (isSwcPluginAvailable) {\n logger([\n `Build optimization ${colorize('enabled', ANSIColors.GREEN)}`,\n colorize(`(import mode:`, ANSIColors.GREY_DARK),\n colorize(importMode ?? IMPORT_MODE, ANSIColors.BLUE),\n colorize(`)`, ANSIColors.GREY_DARK),\n ]);\n } else {\n logger([\n colorize('Recommended: Install', ANSIColors.GREY),\n colorize('@intlayer/swc', ANSIColors.GREY_LIGHT),\n colorize(\n 'package to enable build optimization. See documentation:',\n ANSIColors.GREY\n ),\n colorize(\n 'https://intlayer.org/docs/bundle-optimization',\n ANSIColors.GREY_LIGHT\n ),\n ]);\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-compiler-plugin-enabled.lock'\n ),\n () => {\n const isBabelExtractPluginAvailable =\n getIsBabelExtractPluginAvailable(intlayerConfig);\n\n if (isBabelExtractPluginAvailable) {\n let isEnabled = intlayerConfig.compiler?.enabled ?? true;\n\n if (isEnabled === 'build-only') {\n isEnabled = !isDevCommand;\n }\n\n if (isEnabled) {\n logger('Intlayer compiler enabled');\n } else {\n logger('Intlayer compiler disabled');\n }\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n if (!isSwcPluginAvailable) {\n return {};\n }\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n\n const fetchDictionariesEntryPath = join(mainDir, 'fetch_dictionaries.mjs');\n\n const filesListPattern = buildComponentFilesList(intlayerConfig);\n\n const filesList = [\n ...filesListPattern,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n ];\n\n const dictionaries = getDictionaries(intlayerConfig);\n\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> = {};\n\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ?? importMode ?? IMPORT_MODE;\n });\n\n return {\n experimental: {\n swcPlugins: [\n [\n resolvePluginPath(\n '@intlayer/swc',\n intlayerConfig,\n isTurbopackEnabled\n ),\n {\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n fetchDictionariesEntryPath,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n dictionaryModeMap,\n extraCallers: swcExtraCallers ?? [],\n },\n ],\n ],\n },\n };\n};\n\nconst getCommandsEvent = () => {\n const lifecycleEvent = process.env['npm_lifecycle_event'];\n const lifecycleScript = process.env['npm_lifecycle_script'] ?? '';\n\n const isDevCommand =\n lifecycleEvent === 'dev' ||\n process.argv.some((arg) => arg === 'dev') ||\n /(^|\\s)(next\\s+)?dev(\\s|$)/.test(lifecycleScript);\n\n const isBuildCommand =\n lifecycleEvent === 'build' ||\n process.argv.some((arg) => arg === 'build') ||\n /(^|\\s)(next\\s+)?build(\\s|$)/.test(lifecycleScript);\n\n const isStartCommand =\n lifecycleEvent === 'start' ||\n process.argv.some((arg) => arg === 'start') ||\n /(^|\\s)(next\\s+)?start(\\s|$)/.test(lifecycleScript);\n\n return {\n isDevCommand,\n isBuildCommand,\n isStartCommand,\n };\n};\n\ntype WebpackParams = Parameters<NextJsWebpackConfig>;\n\ntype SwcExtraCallerConfig = {\n callerName: string;\n importSources: string[];\n namespaceArgIndex: number;\n staticReplacement: string;\n dynamicReplacement: string;\n};\n\ntype WithIntlayerOptions = GetConfigurationOptions & {\n enableTurbopack?: boolean;\n swcExtraCallers?: SwcExtraCallerConfig[];\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayerSync(nextConfig)\n * ```\n */\nexport const withIntlayerSync = <T extends Partial<NextConfig>>(\n nextConfig: T = {} as T,\n configOptions?: WithIntlayerOptions\n): NextConfig & T => {\n if (typeof nextConfig !== 'object') {\n nextConfig = {} as T;\n }\n\n const intlayerConfig = getConfiguration(configOptions);\n\n logConfigDetails(configOptions);\n\n const appLogger = getAppLogger(intlayerConfig);\n\n const { isGteNext13, isGteNext15, isGteNext16, isTurbopackStable } =\n getNextVersionFlags(intlayerConfig);\n\n const isTurbopackEnabledFromCommand = isGteNext16\n ? // Next@16 enables turbopack by default; disable with --webpack\n !process.env['npm_lifecycle_script']?.includes('--webpack')\n : // Next@15 uses --turbopack, Next@14 uses --turbo\n process.env['npm_lifecycle_script']?.includes('--turbo');\n\n const isTurbopackEnabled =\n configOptions?.enableTurbopack ?? isTurbopackEnabledFromCommand;\n\n if (isTurbopackEnabled && typeof nextConfig.webpack !== 'undefined') {\n appLogger(\n 'Turbopack is enabled but a custom webpack config is present. It will be ignored.'\n );\n }\n\n const { isBuildCommand, isDevCommand } = getCommandsEvent();\n\n // Only provide turbo-specific config if user explicitly sets it\n const turboConfig = {\n resolveAlias: getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => `./${value}`, // prefix by './' to consider the path as relative to the project root. This is necessary for turbopack to work correctly.\n }),\n\n rules: {\n '*.node': {\n as: '*.node',\n loaders: ['node-loader'],\n },\n },\n };\n\n const serverExternalPackages = [\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n '@intlayer/chokidar',\n '@intlayer/webpack',\n ];\n\n let env: Record<string, string> = {};\n\n if (isBuildCommand) {\n const dictionaries = getDictionaries(intlayerConfig);\n\n if (Object.keys(dictionaries).length === 0) {\n appLogger('No dictionaries found. Please check your configuration.', {\n isVerbose: true,\n });\n }\n\n const unusedNodeTypes = getUnusedNodeTypes(dictionaries);\n\n if (unusedNodeTypes && unusedNodeTypes.length > 0) {\n appLogger(\n [\n 'Filtering out unused logic:',\n unusedNodeTypes\n .filter(\n (key) => !['reactNode', 'solidNode', 'preactNode'].includes(key)\n )\n .map((key) => colorize(key, ANSIColors.BLUE))\n .join(', '),\n ],\n {\n isVerbose: true,\n }\n );\n }\n\n env = {\n ...env,\n\n // Tree shacking based on unused node types\n ...formatNodeTypeToEnvVar(unusedNodeTypes),\n\n // Tree shacking the dictionary selector logic\n // (collections / variants)\n ...formatDictionarySelectorEnvVar(getHasDictionarySelector(dictionaries)),\n\n // Tree shacking based on config\n ...getConfigEnvVars(intlayerConfig),\n };\n }\n\n const getNewConfig = (): Partial<NextConfig> => {\n let config: Partial<NextConfig> = {\n env,\n };\n\n if (isGteNext15) {\n config = {\n ...config,\n serverExternalPackages,\n };\n }\n\n if (isGteNext13 && !isGteNext15) {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n serverComponentsExternalPackages: serverExternalPackages,\n },\n };\n }\n\n if (isTurbopackEnabled) {\n if (isGteNext15 && isTurbopackStable) {\n config = {\n ...config,\n turbopack: turboConfig,\n };\n } else {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n // @ts-ignore exist in next@14\n turbo: turboConfig,\n },\n };\n }\n } else {\n config = {\n ...config,\n webpack: (config: WebpackParams['0'], options: WebpackParams[1]) => {\n // Only add Intlayer plugin on server side (node runtime)\n const { isServer, nextRuntime } = options;\n\n // If the user has defined their own webpack config, call it\n if (typeof nextConfig.webpack === 'function') {\n config = nextConfig.webpack(config, options);\n }\n\n // Rspack set external as false by default\n // Overwrite it to allow pushing the desired externals\n if (config.externals === false) {\n config.externals = [];\n }\n\n // Mark server-only modules as externals (function form handles subpaths)\n const externalExact = new Set([\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n ]);\n const externalPrefixes = ['@intlayer/chokidar', '@intlayer/webpack'];\n config.externals.push(\n (\n { request }: { request?: string },\n callback: (err: Error | null, result?: string) => void\n ) => {\n if (\n request &&\n (externalExact.has(request) ||\n externalPrefixes.some(\n (prefix) =>\n request === prefix || request.startsWith(`${prefix}/`)\n ))\n ) {\n return callback(null, `commonjs ${request}`);\n }\n callback(null);\n }\n );\n\n // Use `node-loader` for any `.node` files\n config.module.rules.push({\n test: /\\.node$/,\n loader: 'node-loader',\n });\n\n // Always alias on the server (node/edge) for stability.\n // On the client, alias only when not using live sync.\n config.resolve.alias = {\n ...config.resolve.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value), // get absolute path\n }),\n };\n\n // Activate watch mode webpack plugin\n if (isDevCommand && isServer && nextRuntime === 'nodejs') {\n // Optional as rspack not support plugin yet\n config.plugins.push(new IntlayerPlugin(intlayerConfig));\n }\n\n return config;\n },\n };\n }\n\n return config;\n };\n\n const pruneConfig: Partial<NextConfig> = getPruneConfig(\n intlayerConfig,\n isBuildCommand,\n isTurbopackEnabled ?? false,\n isDevCommand,\n isGteNext13,\n configOptions?.swcExtraCallers\n );\n\n const intlayerNextConfig: Partial<NextConfig> = defu(\n getNewConfig(),\n pruneConfig\n );\n\n // Merge the new config with the user's config\n const result = defu(intlayerNextConfig, nextConfig) as NextConfig & T;\n\n return result;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayer(nextConfig)\n * ```\n *\n * > Node withIntlayer is a promise function. Use withIntlayerSync instead if you want to use it synchronously.\n * > Using the promise allows to prepare the intlayer dictionaries before the build starts.\n *\n */\nexport const withIntlayer = async <T extends NextConfig | Partial<NextConfig>>(\n nextConfig: T | Promise<T> = {} as T,\n configOptions?: WithIntlayerOptions\n): Promise<NextConfig & T> => {\n const { isBuildCommand, isDevCommand, isStartCommand } = getCommandsEvent();\n\n process.env.INTLAYER_IS_DEV_COMMAND = isDevCommand ? 'true' : 'false';\n\n const intlayerConfig = getConfiguration(configOptions);\n\n const { mode } = intlayerConfig.build;\n\n // Only call prepareIntlayer during `dev` or `build` (not during `start`)\n // If prod: clean and rebuild once\n // If dev: rebuild only once if it's more than 1 hour since last rebuild\n if (!isStartCommand && (isDevCommand || isBuildCommand || mode === 'auto')) {\n // prepareIntlayer use runOnce to ensure to run only once because will run twice on client and server side otherwise\n await prepareIntlayer(intlayerConfig, {\n clean: isBuildCommand,\n cacheTimeoutMs: isBuildCommand\n ? 1000 * 30 // 30 seconds for build (to ensure to rebuild all dictionaries)\n : 1000 * 60 * 60, // 1 hour for dev (default cache timeout)\n env: isBuildCommand ? 'prod' : 'dev',\n });\n }\n\n const nextConfigResolved = await nextConfig;\n\n return withIntlayerSync(nextConfigResolved, configOptions);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,uBAAuB,mBAAmC;CAC9D,IAAI,cAAcA,0BAAgB;AAElC,KAAI;AAIF,iBAFE,eAAe,OAAO,0DAA8B,EAC1B,oBAC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B,YAAY,gBAAgB,SAE9C,QAAO,QAAQ,KAAK,IAAIE,iCAAe,eAAe,CAAC;AAGzD,WAAO;;GAEV;AAGH,SAAO;;CAGT,MAAM,cAAmC,eACvC,gBACA,gBACA,sBAAsB,OACtB,cACA,aACA,eAAe,gBAChB;AAUD,sCAPE,cAAc,EACd,YAIoC,EAAE,WAE3B;;;;;;;;;;;;;;;;;AAkBf,MAAa,eAAe,OAC1B,aAA6B,EAAE,EAC/B,kBAC4B;CAC5B,MAAM,EAAE,gBAAgB,cAAc,mBAAmB,kBAAkB;AAE3E,SAAQ,IAAI,0BAA0B,eAAe,SAAS;CAE9D,MAAM,6DAAkC,cAAc;CAEtD,MAAM,EAAE,SAAS,eAAe;AAKhC,KAAI,CAAC,mBAAmB,gBAAgB,kBAAkB,SAAS,QAEjE,qDAAsB,gBAAgB;EACpC,OAAO;EACP,gBAAgB,iBACZ,MAAO,KACP,MAAO,KAAK;EAChB,KAAK,iBAAiB,SAAS;EAChC,CAAC;AAKJ,QAAO,iBAAiB,MAFS,YAEW,cAAc"}
1
+ {"version":3,"file":"withIntlayer.cjs","names":["nextPackageJSON","ANSIColors","IMPORT_MODE","IntlayerPlugin"],"sources":["../../../src/server/withIntlayer.ts"],"sourcesContent":["import { join, relative, resolve } from 'node:path';\nimport type { SwcExtraCallerConfig } from '@intlayer/config/callers';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { IMPORT_MODE } from '@intlayer/config/defaultValues';\nimport {\n formatDictionarySelectorEnvVar,\n formatNodeTypeToEnvVar,\n getConfigEnvVars,\n} from '@intlayer/config/envVars';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n compareVersions,\n getAlias,\n getHasDictionarySelector,\n getProjectRequire,\n getUnusedNodeTypes,\n normalizePath,\n} from '@intlayer/config/utils';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport { prepareIntlayer } from '@intlayer/engine/build';\nimport { logConfigDetails } from '@intlayer/engine/cli';\nimport { buildComponentFilesList, runOnce } from '@intlayer/engine/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { IntlayerPlugin } from '@intlayer/webpack';\nimport { defu } from 'defu';\nimport type { NextConfig } from 'next';\nimport type { NextJsWebpackConfig } from 'next/dist/server/config-shared';\nimport nextPackageJSON from 'next/package.json' with { type: 'json' };\n\n/**\n * Resolve the Next.js version from the *user's* project at runtime.\n * A static `import from 'next/package.json'` would resolve relative to\n * next-intlayer's own node_modules, which may differ in a monorepo.\n */\nconst getNextVersionFlags = (intlayerConfig: IntlayerConfig) => {\n let nextVersion = nextPackageJSON.version;\n\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n const pkg = requireFunction('next/package.json') as { version: string };\n nextVersion = pkg.version;\n } catch {\n // keep default\n }\n\n return {\n isGteNext13: compareVersions(nextVersion, '≥', '13.0.0'),\n isGteNext15: compareVersions(nextVersion, '≥', '15.0.0'),\n isGteNext16: compareVersions(nextVersion, '≥', '16.0.0'),\n isTurbopackStable: compareVersions(nextVersion, '≥', '15.3.0'),\n };\n};\n\n// Check if SWC plugin is available\nconst getIsSwcPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/swc');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\n// Check if Babel plugin is available\nconst getIsBabelExtractPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/babel');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\nconst resolvePluginPath = (\n pluginPath: string,\n intlayerConfig: IntlayerConfig,\n isTurbopackEnabled: boolean\n): string => {\n const requireFunction = intlayerConfig.build?.require ?? getProjectRequire();\n const pluginPathResolved = requireFunction?.resolve(pluginPath);\n\n if (isTurbopackEnabled)\n // Relative path for turbopack\n return normalizePath(`./${relative(process.cwd(), pluginPathResolved)}`);\n\n // Absolute path for webpack\n return pluginPathResolved;\n};\n\nconst getPruneConfig = (\n intlayerConfig: IntlayerConfig,\n isBuildCommand: boolean,\n isTurbopackEnabled: boolean,\n isDevCommand: boolean,\n isGteNext13: boolean,\n swcExtraCallers?: SwcExtraCallerConfig[]\n): Partial<NextConfig> => {\n const { optimize } = intlayerConfig.build;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n const {\n dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.system;\n const logger = getAppLogger(intlayerConfig);\n\n if (optimize === false) {\n return {};\n }\n if (optimize === undefined && !isBuildCommand) {\n return {};\n }\n\n if (!isGteNext13) return {};\n\n const isSwcPluginAvailable = getIsSwcPluginAvailable(intlayerConfig);\n\n runOnce(\n join(baseDir, '.intlayer', 'cache', 'intlayer-prune-plugin-enabled.lock'),\n () => {\n if (isSwcPluginAvailable) {\n logger([\n `Build optimization ${colorize('enabled', ANSIColors.GREEN)}`,\n colorize(`(import mode:`, ANSIColors.GREY_DARK),\n colorize(importMode ?? IMPORT_MODE, ANSIColors.BLUE),\n colorize(`)`, ANSIColors.GREY_DARK),\n ]);\n } else {\n logger([\n colorize('Recommended: Install', ANSIColors.GREY),\n colorize('@intlayer/swc', ANSIColors.GREY_LIGHT),\n colorize(\n 'package to enable build optimization. See documentation:',\n ANSIColors.GREY\n ),\n colorize(\n 'https://intlayer.org/docs/bundle-optimization',\n ANSIColors.GREY_LIGHT\n ),\n ]);\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-compiler-plugin-enabled.lock'\n ),\n () => {\n const isBabelExtractPluginAvailable =\n getIsBabelExtractPluginAvailable(intlayerConfig);\n\n if (isBabelExtractPluginAvailable) {\n let isEnabled = intlayerConfig.compiler?.enabled ?? true;\n\n if (isEnabled === 'build-only') {\n isEnabled = !isDevCommand;\n }\n\n if (isEnabled) {\n logger('Intlayer compiler enabled');\n } else {\n logger('Intlayer compiler disabled');\n }\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n if (!isSwcPluginAvailable) {\n return {};\n }\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n\n const fetchDictionariesEntryPath = join(mainDir, 'fetch_dictionaries.mjs');\n\n const filesListPattern = buildComponentFilesList(intlayerConfig);\n\n const filesList = [\n ...filesListPattern,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n ];\n\n const dictionaries = getDictionaries(intlayerConfig);\n\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> = {};\n\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ?? importMode ?? IMPORT_MODE;\n });\n\n return {\n experimental: {\n swcPlugins: [\n [\n resolvePluginPath(\n '@intlayer/swc',\n intlayerConfig,\n isTurbopackEnabled\n ),\n {\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n fetchDictionariesEntryPath,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n dictionaryModeMap,\n extraCallers: swcExtraCallers ?? [],\n },\n ],\n ],\n },\n };\n};\n\nconst getCommandsEvent = () => {\n const lifecycleEvent = process.env['npm_lifecycle_event'];\n const lifecycleScript = process.env['npm_lifecycle_script'] ?? '';\n\n const isDevCommand =\n lifecycleEvent === 'dev' ||\n process.argv.some((arg) => arg === 'dev') ||\n /(^|\\s)(next\\s+)?dev(\\s|$)/.test(lifecycleScript);\n\n const isBuildCommand =\n lifecycleEvent === 'build' ||\n process.argv.some((arg) => arg === 'build') ||\n /(^|\\s)(next\\s+)?build(\\s|$)/.test(lifecycleScript);\n\n const isStartCommand =\n lifecycleEvent === 'start' ||\n process.argv.some((arg) => arg === 'start') ||\n /(^|\\s)(next\\s+)?start(\\s|$)/.test(lifecycleScript);\n\n return {\n isDevCommand,\n isBuildCommand,\n isStartCommand,\n };\n};\n\ntype WebpackParams = Parameters<NextJsWebpackConfig>;\n\ntype WithIntlayerOptions = GetConfigurationOptions & {\n enableTurbopack?: boolean;\n swcExtraCallers?: SwcExtraCallerConfig[];\n};\n\n/**\n * Pin the env file used to resolve the Intlayer configuration to the Next.js\n * command being run (`dev` → `development`, `build`/`start` → `production`).\n *\n * Next.js loads the config file in several processes during a single command\n * (the main `build` process plus one or more Turbopack/webpack workers), and\n * `process.env.NODE_ENV` is not guaranteed to hold the same value in all of\n * them. Since `getConfiguration` falls back to `NODE_ENV` to pick its env file\n * (`.env.development.local` vs `.env.production.local`), those processes could\n * otherwise resolve *different* env values (e.g. `applicationURL`,\n * `INTLAYER_CLIENT_ID`). The resulting configuration would differ between\n * processes, defeating the `isCachedConfigurationUpToDate` check and forcing a\n * redundant full dictionary rebuild.\n *\n * Passing an explicit `env` keeps configuration resolution deterministic across\n * every process of the command. An `env` already set by the caller is\n * respected, and when the command cannot be determined we fall back to\n * `getConfiguration`'s own default (i.e. leave `env` unset).\n */\nconst resolveConfigOptions = (\n configOptions?: WithIntlayerOptions\n): WithIntlayerOptions | undefined => {\n // Respect an explicit override from the caller (idempotent on re-entry).\n if (configOptions?.env) return configOptions;\n\n const { isDevCommand, isBuildCommand, isStartCommand } = getCommandsEvent();\n\n const env = isDevCommand\n ? 'development'\n : isBuildCommand || isStartCommand\n ? 'production'\n : undefined;\n\n if (!env) return configOptions;\n\n return {\n ...configOptions,\n env,\n };\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayerSync(nextConfig)\n * ```\n */\nexport const withIntlayerSync = <T extends Partial<NextConfig>>(\n nextConfig: T = {} as T,\n configOptions?: WithIntlayerOptions\n): NextConfig & T => {\n if (typeof nextConfig !== 'object') {\n nextConfig = {} as T;\n }\n\n const resolvedConfigOptions = resolveConfigOptions(configOptions);\n\n const intlayerConfig = getConfiguration(resolvedConfigOptions);\n\n logConfigDetails(resolvedConfigOptions);\n\n const appLogger = getAppLogger(intlayerConfig);\n\n const { isGteNext13, isGteNext15, isGteNext16, isTurbopackStable } =\n getNextVersionFlags(intlayerConfig);\n\n const isTurbopackEnabledFromCommand = isGteNext16\n ? // Next@16 enables turbopack by default; disable with --webpack\n !process.env['npm_lifecycle_script']?.includes('--webpack')\n : // Next@15 uses --turbopack, Next@14 uses --turbo\n process.env['npm_lifecycle_script']?.includes('--turbo');\n\n const isTurbopackEnabled =\n configOptions?.enableTurbopack ?? isTurbopackEnabledFromCommand;\n\n if (isTurbopackEnabled && typeof nextConfig.webpack !== 'undefined') {\n appLogger(\n 'Turbopack is enabled but a custom webpack config is present. It will be ignored.'\n );\n }\n\n const { isBuildCommand, isDevCommand } = getCommandsEvent();\n\n // Only provide turbo-specific config if user explicitly sets it\n const turboConfig = {\n resolveAlias: getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => `./${value}`, // prefix by './' to consider the path as relative to the project root. This is necessary for turbopack to work correctly.\n }),\n\n rules: {\n '*.node': {\n as: '*.node',\n loaders: ['node-loader'],\n },\n },\n };\n\n const serverExternalPackages = [\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n '@intlayer/engine',\n '@intlayer/webpack',\n ];\n\n let env: Record<string, string> = {};\n\n if (isBuildCommand) {\n const dictionaries = getDictionaries(intlayerConfig);\n\n if (Object.keys(dictionaries).length === 0) {\n appLogger('No dictionaries found. Please check your configuration.', {\n isVerbose: true,\n });\n }\n\n const unusedNodeTypes = getUnusedNodeTypes(dictionaries);\n\n if (unusedNodeTypes && unusedNodeTypes.length > 0) {\n appLogger(\n [\n 'Filtering out unused logic:',\n unusedNodeTypes\n .filter(\n (key) => !['reactNode', 'solidNode', 'preactNode'].includes(key)\n )\n .map((key) => colorize(key, ANSIColors.BLUE))\n .join(', '),\n ],\n {\n isVerbose: true,\n }\n );\n }\n\n env = {\n ...env,\n\n // Tree shacking based on unused node types\n ...formatNodeTypeToEnvVar(unusedNodeTypes),\n\n // Tree shacking the dictionary selector logic\n // (collections / variants)\n ...formatDictionarySelectorEnvVar(getHasDictionarySelector(dictionaries)),\n\n // Tree shacking based on config\n ...getConfigEnvVars(intlayerConfig),\n };\n }\n\n const getNewConfig = (): Partial<NextConfig> => {\n let config: Partial<NextConfig> = {\n env,\n };\n\n if (isGteNext15) {\n config = {\n ...config,\n serverExternalPackages,\n };\n }\n\n if (isGteNext13 && !isGteNext15) {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n serverComponentsExternalPackages: serverExternalPackages,\n },\n };\n }\n\n if (isTurbopackEnabled) {\n if (isGteNext15 && isTurbopackStable) {\n config = {\n ...config,\n turbopack: turboConfig,\n };\n } else {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n // @ts-ignore exist in next@14\n turbo: turboConfig,\n },\n };\n }\n } else {\n config = {\n ...config,\n webpack: (config: WebpackParams['0'], options: WebpackParams[1]) => {\n // Only add Intlayer plugin on server side (node runtime)\n const { isServer, nextRuntime } = options;\n\n // If the user has defined their own webpack config, call it\n if (typeof nextConfig.webpack === 'function') {\n config = nextConfig.webpack(config, options);\n }\n\n // Rspack set external as false by default\n // Overwrite it to allow pushing the desired externals\n if (config.externals === false) {\n config.externals = [];\n }\n\n // Mark server-only modules as externals (function form handles subpaths)\n const externalExact = new Set([\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n ]);\n const externalPrefixes = ['@intlayer/engine', '@intlayer/webpack'];\n config.externals.push(\n (\n { request }: { request?: string },\n callback: (err: Error | null, result?: string) => void\n ) => {\n if (\n request &&\n (externalExact.has(request) ||\n externalPrefixes.some(\n (prefix) =>\n request === prefix || request.startsWith(`${prefix}/`)\n ))\n ) {\n return callback(null, `commonjs ${request}`);\n }\n callback(null);\n }\n );\n\n // Use `node-loader` for any `.node` files\n config.module.rules.push({\n test: /\\.node$/,\n loader: 'node-loader',\n });\n\n // Always alias on the server (node/edge) for stability.\n // On the client, alias only when not using live sync.\n config.resolve.alias = {\n ...config.resolve.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value), // get absolute path\n }),\n };\n\n // Activate watch mode webpack plugin\n if (isDevCommand && isServer && nextRuntime === 'nodejs') {\n // Optional as rspack not support plugin yet\n config.plugins.push(new IntlayerPlugin(intlayerConfig));\n }\n\n return config;\n },\n };\n }\n\n return config;\n };\n\n const pruneConfig: Partial<NextConfig> = getPruneConfig(\n intlayerConfig,\n isBuildCommand,\n isTurbopackEnabled ?? false,\n isDevCommand,\n isGteNext13,\n configOptions?.swcExtraCallers\n );\n\n const intlayerNextConfig: Partial<NextConfig> = defu(\n getNewConfig(),\n pruneConfig\n );\n\n // Merge the new config with the user's config\n const result = defu(intlayerNextConfig, nextConfig) as NextConfig & T;\n\n return result;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayer(nextConfig)\n * ```\n *\n * > Node withIntlayer is a promise function. Use withIntlayerSync instead if you want to use it synchronously.\n * > Using the promise allows to prepare the intlayer dictionaries before the build starts.\n *\n */\nexport const withIntlayer = async <T extends NextConfig | Partial<NextConfig>>(\n nextConfig: T | Promise<T> = {} as T,\n configOptions?: WithIntlayerOptions\n): Promise<NextConfig & T> => {\n const { isBuildCommand, isDevCommand, isStartCommand } = getCommandsEvent();\n\n process.env.INTLAYER_IS_DEV_COMMAND = isDevCommand ? 'true' : 'false';\n\n const resolvedConfigOptions = resolveConfigOptions(configOptions);\n\n const intlayerConfig = getConfiguration(resolvedConfigOptions);\n\n const { mode } = intlayerConfig.build;\n\n // Only call prepareIntlayer during `dev` or `build` (not during `start`)\n // If prod: clean and rebuild once\n // If dev: rebuild only once if it's more than 1 hour since last rebuild\n if (!isStartCommand && (isDevCommand || isBuildCommand || mode === 'auto')) {\n // prepareIntlayer use runOnce to ensure to run only once because will run twice on client and server side otherwise\n await prepareIntlayer(intlayerConfig, {\n clean: isBuildCommand,\n cacheTimeoutMs: isBuildCommand\n ? 1000 * 30 // 30 seconds for build (to ensure to rebuild all dictionaries)\n : 1000 * 60 * 60, // 1 hour for dev (default cache timeout)\n env: isBuildCommand ? 'prod' : 'dev',\n });\n }\n\n const nextConfigResolved = await nextConfig;\n\n return withIntlayerSync(nextConfigResolved, resolvedConfigOptions);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAM,uBAAuB,mBAAmC;CAC9D,IAAI,cAAcA,0BAAgB;CAElC,IAAI;EAIF,eAFE,eAAe,OAAO,yDAA6B,EAC1B,CAAC,mBACZ,CAAC,CAAC;CACpB,QAAQ,CAER;CAEA,OAAO;EACL,yDAA6B,aAAa,KAAK,QAAQ;EACvD,yDAA6B,aAAa,KAAK,QAAQ;EACvD,yDAA6B,aAAa,KAAK,QAAQ;EACvD,+DAAmC,aAAa,KAAK,QAAQ;CAC/D;AACF;AAGA,MAAM,2BAA2B,mBAAmC;CAClE,IAAI;EAGF,CADE,eAAe,OAAO,yDAA6B,EACtC,CAAC,QAAQ,eAAe;EACvC,OAAO;CACT,SAAS,IAAI;EACX,OAAO;CACT;AACF;AAGA,MAAM,oCAAoC,mBAAmC;CAC3E,IAAI;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,KAAK;KAC7C,CAAC;IACH;IAGA,IAAI,gBAAgB,YAAY,gBAAgB,UAE9C,OAAO,QAAQ,KAAK,IAAIE,iCAAe,cAAc,CAAC;IAGxD,OAAO;GACT;EACF;EAGF,OAAO;CACT;CAEA,MAAM,cAAmC,eACvC,gBACA,gBACA,sBAAsB,OACtB,cACA,aACA,eAAe,eACjB;CAUA,qCAPE,aAAa,GACb,WAImC,GAAG,UAE5B;AACd;;;;;;;;;;;;;;;;AAiBA,MAAa,eAAe,OAC1B,aAA6B,CAAC,GAC9B,kBAC4B;CAC5B,MAAM,EAAE,gBAAgB,cAAc,mBAAmB,iBAAiB;CAE1E,QAAQ,IAAI,0BAA0B,eAAe,SAAS;CAE9D,MAAM,wBAAwB,qBAAqB,aAAa;CAEhE,MAAM,6DAAkC,qBAAqB;CAE7D,MAAM,EAAE,SAAS,eAAe;CAKhC,IAAI,CAAC,mBAAmB,gBAAgB,kBAAkB,SAAS,SAEjE,kDAAsB,gBAAgB;EACpC,OAAO;EACP,gBAAgB,iBACZ,MAAO,KACP,MAAO,KAAK;EAChB,KAAK,iBAAiB,SAAS;CACjC,CAAC;CAGH,MAAM,qBAAqB,MAAM;CAEjC,OAAO,iBAAiB,oBAAoB,qBAAqB;AACnE"}
@@ -1 +1 @@
1
- {"version":3,"file":"IntlayerClientProvider.mjs","names":[],"sources":["../../../src/client/IntlayerClientProvider.tsx"],"sourcesContent":["'use client';\n\nimport type { FC } from 'react';\n\nimport { IntlayerProvider, type IntlayerProviderProps } from 'react-intlayer';\n\nexport type IntlayerClientProviderProps = IntlayerProviderProps;\n\n/**\n * Provider for client-side components in Next.js.\n *\n * This component wraps the `IntlayerProvider` from `react-intlayer` and is intended\n * to be used within Next.js App Router client components.\n *\n * @param props - The provider props.\n * @returns The provider component.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { IntlayerClientProvider } from 'next-intlayer';\n *\n * export default function ClientLayout({ children, locale }) {\n * return (\n * <IntlayerClientProvider locale={locale}>\n * {children}\n * </IntlayerClientProvider>\n * );\n * }\n * ```\n */\nexport const IntlayerClientProvider: FC<IntlayerProviderProps> = (props) => (\n <IntlayerProvider {...props} />\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,0BAAqD,UAChE,oBAAC,kBAAD,EAAkB,GAAI,OAAS"}
1
+ {"version":3,"file":"IntlayerClientProvider.mjs","names":[],"sources":["../../../src/client/IntlayerClientProvider.tsx"],"sourcesContent":["'use client';\n\nimport type { FC } from 'react';\n\nimport { IntlayerProvider, type IntlayerProviderProps } from 'react-intlayer';\n\nexport type IntlayerClientProviderProps = IntlayerProviderProps;\n\n/**\n * Provider for client-side components in Next.js.\n *\n * This component wraps the `IntlayerProvider` from `react-intlayer` and is intended\n * to be used within Next.js App Router client components.\n *\n * @param props - The provider props.\n * @returns The provider component.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { IntlayerClientProvider } from 'next-intlayer';\n *\n * export default function ClientLayout({ children, locale }) {\n * return (\n * <IntlayerClientProvider locale={locale}>\n * {children}\n * </IntlayerClientProvider>\n * );\n * }\n * ```\n */\nexport const IntlayerClientProvider: FC<IntlayerProviderProps> = (props) => (\n <IntlayerProvider {...props} />\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,0BAAqD,UAChE,oBAAC,kBAAD,EAAkB,GAAI,MAAQ"}
@@ -39,7 +39,8 @@ const useLocale = ({ onChange = "replace", onLocaleChange, isCookieEnabled } = {
39
39
  ...useLocale$1({
40
40
  onLocaleChange: useCallback((locale) => {
41
41
  if (!onChange) return;
42
- const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale, { currentDomain: process.env.INTLAYER_ROUTING_DOMAINS !== "false" && typeof window !== "undefined" ? window.location.hostname : void 0 });
42
+ const currentDomain = process.env.INTLAYER_ROUTING_DOMAINS !== "false" && typeof window !== "undefined" ? window.location.hostname : void 0;
43
+ const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale, { currentDomain });
43
44
  if (typeof onChange === "function") {
44
45
  onChange({
45
46
  locale,
@@ -1 +1 @@
1
- {"version":3,"file":"useLocale.mjs","names":["usePathname","useLocaleReact"],"sources":["../../../src/client/useLocale.ts"],"sourcesContent":["'use client';\n\nimport { getLocalizedUrl } from '@intlayer/core/localization';\nimport { checkIsURLAbsolute } from '@intlayer/core/utils';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { useRouter } from 'next/navigation.js';\nimport { useCallback } from 'react';\nimport {\n type UseLocaleResult as UseLocaleResultReact,\n useLocale as useLocaleReact,\n} from 'react-intlayer';\nimport { usePathname } from './usePathname';\n\nexport type UseLocaleProps = {\n isCookieEnabled?: boolean;\n onLocaleChange?: (locale: DeclaredLocales) => void;\n onChange?:\n | 'replace'\n | 'push'\n | 'none'\n | ((params: { locale: LocalesValues; path: string }) => void);\n};\n\nexport type UseLocaleResult = UseLocaleResultReact & {\n pathWithoutLocale: string;\n};\n\n/**\n * Hook to manage the current locale in Next.js App Router.\n *\n * This hook extends the base `useLocale` from `react-intlayer` by adding\n * Next.js-specific navigation logic for locale changes.\n *\n * @param props - Optional properties to configure locale change behavior.\n * @returns An object containing the current locale, path without locale, and functions to update the locale.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { useLocale } from 'next-intlayer';\n *\n * const LocaleSwitcher = () => {\n * const { setLocale } = useLocale({ onChange: 'push' });\n *\n * return (\n * <button onClick={() => setLocale('fr')}>Switch to French</button>\n * );\n * };\n * ```\n */\nexport const useLocale = ({\n onChange = 'replace',\n onLocaleChange,\n isCookieEnabled,\n}: UseLocaleProps = {}): UseLocaleResult => {\n const { replace, push } = useRouter();\n const pathWithoutLocale = usePathname();\n\n const redirectionFunction = useCallback(\n (locale: LocalesValues) => {\n if (!onChange) return;\n\n const currentDomain =\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n typeof window !== 'undefined'\n ? window.location.hostname\n : undefined;\n\n const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale, {\n currentDomain,\n });\n\n if (typeof onChange === 'function') {\n onChange({ locale, path: pathWithLocale });\n return;\n }\n\n // Cross-domain navigation: the Next.js router cannot navigate to a\n // different origin, so fall back to a full page load.\n if (\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n checkIsURLAbsolute(pathWithLocale)\n ) {\n try {\n const parsed = new URL(pathWithLocale);\n if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {\n window.location.href = pathWithLocale;\n }\n } catch {\n // Malformed URL — skip redirect\n }\n return;\n }\n\n if (onChange === 'replace') {\n replace(pathWithLocale);\n }\n if (onChange === 'push') {\n push(pathWithLocale);\n }\n\n onLocaleChange?.(locale as DeclaredLocales);\n },\n [replace, push, pathWithoutLocale, onChange, onLocaleChange]\n );\n\n const reactLocaleHook = useLocaleReact({\n onLocaleChange: redirectionFunction,\n isCookieEnabled,\n });\n\n return {\n ...reactLocaleHook,\n pathWithoutLocale,\n } as UseLocaleResult;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,MAAa,aAAa,EACxB,WAAW,WACX,gBACA,oBACkB,EAAE,KAAsB;CAC1C,MAAM,EAAE,SAAS,SAAS,WAAW;CACrC,MAAM,oBAAoBA,eAAa;AAuDvC,QAAO;EACL,GANsBC,YAAe;GACrC,gBAjD0B,aACzB,WAA0B;AACzB,QAAI,CAAC,SAAU;IAQf,MAAM,iBAAiB,gBAAgB,mBAAmB,QAAQ,EAChE,eANA,QAAQ,IAAI,6BAA6B,WACzC,OAAO,WAAW,cACd,OAAO,SAAS,WAChB,QAIL,CAAC;AAEF,QAAI,OAAO,aAAa,YAAY;AAClC,cAAS;MAAE;MAAQ,MAAM;MAAgB,CAAC;AAC1C;;AAKF,QACE,QAAQ,IAAI,6BAA6B,WACzC,mBAAmB,eAAe,EAClC;AACA,SAAI;MACF,MAAM,SAAS,IAAI,IAAI,eAAe;AACtC,UAAI,OAAO,aAAa,WAAW,OAAO,aAAa,SACrD,QAAO,SAAS,OAAO;aAEnB;AAGR;;AAGF,QAAI,aAAa,UACf,SAAQ,eAAe;AAEzB,QAAI,aAAa,OACf,MAAK,eAAe;AAGtB,qBAAiB,OAA0B;MAE7C;IAAC;IAAS;IAAM;IAAmB;IAAU;IAAe,CAIzB;GACnC;GACD,CAGmB;EAClB;EACD"}
1
+ {"version":3,"file":"useLocale.mjs","names":["usePathname","useLocaleReact"],"sources":["../../../src/client/useLocale.ts"],"sourcesContent":["'use client';\n\nimport { getLocalizedUrl } from '@intlayer/core/localization';\nimport { checkIsURLAbsolute } from '@intlayer/core/utils';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { useRouter } from 'next/navigation.js';\nimport { useCallback } from 'react';\nimport {\n type UseLocaleResult as UseLocaleResultReact,\n useLocale as useLocaleReact,\n} from 'react-intlayer';\nimport { usePathname } from './usePathname';\n\nexport type UseLocaleProps = {\n isCookieEnabled?: boolean;\n onLocaleChange?: (locale: DeclaredLocales) => void;\n onChange?:\n | 'replace'\n | 'push'\n | 'none'\n | ((params: { locale: LocalesValues; path: string }) => void);\n};\n\nexport type UseLocaleResult = UseLocaleResultReact & {\n pathWithoutLocale: string;\n};\n\n/**\n * Hook to manage the current locale in Next.js App Router.\n *\n * This hook extends the base `useLocale` from `react-intlayer` by adding\n * Next.js-specific navigation logic for locale changes.\n *\n * @param props - Optional properties to configure locale change behavior.\n * @returns An object containing the current locale, path without locale, and functions to update the locale.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { useLocale } from 'next-intlayer';\n *\n * const LocaleSwitcher = () => {\n * const { setLocale } = useLocale({ onChange: 'push' });\n *\n * return (\n * <button onClick={() => setLocale('fr')}>Switch to French</button>\n * );\n * };\n * ```\n */\nexport const useLocale = ({\n onChange = 'replace',\n onLocaleChange,\n isCookieEnabled,\n}: UseLocaleProps = {}): UseLocaleResult => {\n const { replace, push } = useRouter();\n const pathWithoutLocale = usePathname();\n\n const redirectionFunction = useCallback(\n (locale: LocalesValues) => {\n if (!onChange) return;\n\n const currentDomain =\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n typeof window !== 'undefined'\n ? window.location.hostname\n : undefined;\n\n const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale, {\n currentDomain,\n });\n\n if (typeof onChange === 'function') {\n onChange({ locale, path: pathWithLocale });\n return;\n }\n\n // Cross-domain navigation: the Next.js router cannot navigate to a\n // different origin, so fall back to a full page load.\n if (\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n checkIsURLAbsolute(pathWithLocale)\n ) {\n try {\n const parsed = new URL(pathWithLocale);\n if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {\n window.location.href = pathWithLocale;\n }\n } catch {\n // Malformed URL — skip redirect\n }\n return;\n }\n\n if (onChange === 'replace') {\n replace(pathWithLocale);\n }\n if (onChange === 'push') {\n push(pathWithLocale);\n }\n\n onLocaleChange?.(locale as DeclaredLocales);\n },\n [replace, push, pathWithoutLocale, onChange, onLocaleChange]\n );\n\n const reactLocaleHook = useLocaleReact({\n onLocaleChange: redirectionFunction,\n isCookieEnabled,\n });\n\n return {\n ...reactLocaleHook,\n pathWithoutLocale,\n } as UseLocaleResult;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,MAAa,aAAa,EACxB,WAAW,WACX,gBACA,oBACkB,CAAC,MAAuB;CAC1C,MAAM,EAAE,SAAS,SAAS,UAAU;CACpC,MAAM,oBAAoBA,cAAY;CAuDtC,OAAO;EACL,GANsBC,YAAe;GACrC,gBAjD0B,aACzB,WAA0B;IACzB,IAAI,CAAC,UAAU;IAEf,MAAM,gBACJ,QAAQ,IAAI,6BAA6B,WACzC,OAAO,WAAW,cACd,OAAO,SAAS,WAChB;IAEN,MAAM,iBAAiB,gBAAgB,mBAAmB,QAAQ,EAChE,cACF,CAAC;IAED,IAAI,OAAO,aAAa,YAAY;KAClC,SAAS;MAAE;MAAQ,MAAM;KAAe,CAAC;KACzC;IACF;IAIA,IACE,QAAQ,IAAI,6BAA6B,WACzC,mBAAmB,cAAc,GACjC;KACA,IAAI;MACF,MAAM,SAAS,IAAI,IAAI,cAAc;MACrC,IAAI,OAAO,aAAa,WAAW,OAAO,aAAa,UACrD,OAAO,SAAS,OAAO;KAE3B,QAAQ,CAER;KACA;IACF;IAEA,IAAI,aAAa,WACf,QAAQ,cAAc;IAExB,IAAI,aAAa,QACf,KAAK,cAAc;IAGrB,iBAAiB,MAAyB;GAC5C,GACA;IAAC;IAAS;IAAM;IAAmB;IAAU;GAAc,CAIzB;GAClC;EACF,CAGmB;EACjB;CACF;AACF"}
@@ -33,7 +33,8 @@ const useLocalePageRouter = ({ onLocaleChange, isCookieEnabled } = {}) => {
33
33
  return {
34
34
  ...useLocale({
35
35
  onLocaleChange: useCallback((locale) => {
36
- push(getLocalizedUrl(pathWithoutLocale, locale));
36
+ const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale);
37
+ push(pathWithLocale);
37
38
  onLocaleChange?.(locale);
38
39
  return reload();
39
40
  }, [
@@ -1 +1 @@
1
- {"version":3,"file":"useLocalePageRouter.mjs","names":["useLocaleReact"],"sources":["../../../src/client/useLocalePageRouter.ts"],"sourcesContent":["'use client';\n\nimport {\n getLocalizedUrl,\n getPathWithoutLocale,\n} from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { useRouter } from 'next/router.js';\nimport { useCallback, useMemo } from 'react';\nimport { useLocale as useLocaleReact } from 'react-intlayer';\nimport type { UseLocaleProps, UseLocaleResult } from './useLocale';\n\n/**\n * Hook to manage the current locale in Next.js Page Router.\n *\n * This hook provides locale management functionality tailored for the Next.js Page Router,\n * handling redirections and page reloads upon locale changes.\n *\n * @returns An object containing the current locale, path without locale, and functions to update the locale.\n *\n * @example\n * ```tsx\n * import { useLocalePageRouter } from 'next-intlayer';\n *\n * const MyComponent = () => {\n * const { setLocale } = useLocalePageRouter();\n *\n * return (\n * <button onClick={() => setLocale('fr')}>Switch to French</button>\n * );\n * };\n * ```\n */\nexport const useLocalePageRouter = ({\n onLocaleChange,\n isCookieEnabled,\n}: UseLocaleProps = {}): UseLocaleResult => {\n const { push, pathname, reload } = useRouter();\n const pathWithoutLocale = useMemo(\n () => getPathWithoutLocale(pathname),\n [pathname]\n );\n\n const redirectionFunction = useCallback(\n (locale: LocalesValues) => {\n const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale);\n\n push(pathWithLocale);\n\n onLocaleChange?.(locale as Locale);\n\n return reload();\n },\n [pathWithoutLocale, onLocaleChange, reload]\n );\n\n const reactLocaleHook = useLocaleReact({\n onLocaleChange: redirectionFunction,\n isCookieEnabled,\n });\n\n return {\n ...reactLocaleHook,\n pathWithoutLocale,\n } as UseLocaleResult;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,uBAAuB,EAClC,gBACA,oBACkB,EAAE,KAAsB;CAC1C,MAAM,EAAE,MAAM,UAAU,WAAW,WAAW;CAC9C,MAAM,oBAAoB,cAClB,qBAAqB,SAAS,EACpC,CAAC,SAAS,CACX;AAoBD,QAAO;EACL,GANsBA,UAAe;GACrC,gBAd0B,aACzB,WAA0B;AAGzB,SAFuB,gBAAgB,mBAAmB,OAEvC,CAAC;AAEpB,qBAAiB,OAAiB;AAElC,WAAO,QAAQ;MAEjB;IAAC;IAAmB;IAAgB;IAAO,CAIR;GACnC;GACD,CAGmB;EAClB;EACD"}
1
+ {"version":3,"file":"useLocalePageRouter.mjs","names":["useLocaleReact"],"sources":["../../../src/client/useLocalePageRouter.ts"],"sourcesContent":["'use client';\n\nimport {\n getLocalizedUrl,\n getPathWithoutLocale,\n} from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { useRouter } from 'next/router.js';\nimport { useCallback, useMemo } from 'react';\nimport { useLocale as useLocaleReact } from 'react-intlayer';\nimport type { UseLocaleProps, UseLocaleResult } from './useLocale';\n\n/**\n * Hook to manage the current locale in Next.js Page Router.\n *\n * This hook provides locale management functionality tailored for the Next.js Page Router,\n * handling redirections and page reloads upon locale changes.\n *\n * @returns An object containing the current locale, path without locale, and functions to update the locale.\n *\n * @example\n * ```tsx\n * import { useLocalePageRouter } from 'next-intlayer';\n *\n * const MyComponent = () => {\n * const { setLocale } = useLocalePageRouter();\n *\n * return (\n * <button onClick={() => setLocale('fr')}>Switch to French</button>\n * );\n * };\n * ```\n */\nexport const useLocalePageRouter = ({\n onLocaleChange,\n isCookieEnabled,\n}: UseLocaleProps = {}): UseLocaleResult => {\n const { push, pathname, reload } = useRouter();\n const pathWithoutLocale = useMemo(\n () => getPathWithoutLocale(pathname),\n [pathname]\n );\n\n const redirectionFunction = useCallback(\n (locale: LocalesValues) => {\n const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale);\n\n push(pathWithLocale);\n\n onLocaleChange?.(locale as Locale);\n\n return reload();\n },\n [pathWithoutLocale, onLocaleChange, reload]\n );\n\n const reactLocaleHook = useLocaleReact({\n onLocaleChange: redirectionFunction,\n isCookieEnabled,\n });\n\n return {\n ...reactLocaleHook,\n pathWithoutLocale,\n } as UseLocaleResult;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,uBAAuB,EAClC,gBACA,oBACkB,CAAC,MAAuB;CAC1C,MAAM,EAAE,MAAM,UAAU,WAAW,UAAU;CAC7C,MAAM,oBAAoB,cAClB,qBAAqB,QAAQ,GACnC,CAAC,QAAQ,CACX;CAoBA,OAAO;EACL,GANsBA,UAAe;GACrC,gBAd0B,aACzB,WAA0B;IACzB,MAAM,iBAAiB,gBAAgB,mBAAmB,MAAM;IAEhE,KAAK,cAAc;IAEnB,iBAAiB,MAAgB;IAEjC,OAAO,OAAO;GAChB,GACA;IAAC;IAAmB;IAAgB;GAAM,CAIR;GAClC;EACF,CAGmB;EACjB;CACF;AACF"}
@@ -29,7 +29,8 @@ const usePathname = () => {
29
29
  const nextPathname = usePathname$1();
30
30
  const [searchParams, setSearchParams] = useState("");
31
31
  useEffect(() => {
32
- setSearchParams(typeof window !== "undefined" ? window.location.search : "");
32
+ const search = typeof window !== "undefined" ? window.location.search : "";
33
+ setSearchParams(search);
33
34
  }, [nextPathname]);
34
35
  const fullPath = searchParams ? `${nextPathname}${searchParams}` : nextPathname;
35
36
  return useMemo(() => getPathWithoutLocale(fullPath), [fullPath]);
@@ -1 +1 @@
1
- {"version":3,"file":"usePathname.mjs","names":["useNextPathname"],"sources":["../../../src/client/usePathname.ts"],"sourcesContent":["'use client';\n\nimport { getPathWithoutLocale } from '@intlayer/core/localization';\nimport { usePathname as useNextPathname } from 'next/navigation.js';\nimport { useEffect, useMemo, useState } from 'react';\n\n/**\n * Next.js hook that returns the current pathname with the locale segment removed.\n *\n * Wraps Next.js `usePathname()` so it re-renders on client navigations and\n * appends any search parameters before stripping the locale prefix.\n *\n * @returns The current pathname without the locale prefix.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { usePathname } from 'next-intlayer';\n *\n * const NavItem = ({ href }: { href: string }) => {\n * const pathname = usePathname();\n * return <a className={pathname === href ? 'active' : ''}>{href}</a>;\n * };\n * ```\n */\nexport const usePathname = (): string => {\n const nextPathname = useNextPathname();\n const [searchParams, setSearchParams] = useState<string>('');\n\n useEffect(() => {\n const search = typeof window !== 'undefined' ? window.location.search : '';\n setSearchParams(search);\n }, [nextPathname]);\n\n const fullPath = searchParams\n ? `${nextPathname}${searchParams}`\n : nextPathname;\n\n return useMemo(() => getPathWithoutLocale(fullPath), [fullPath]);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,oBAA4B;CACvC,MAAM,eAAeA,eAAiB;CACtC,MAAM,CAAC,cAAc,mBAAmB,SAAiB,GAAG;AAE5D,iBAAgB;AAEd,kBADe,OAAO,WAAW,cAAc,OAAO,SAAS,SAAS,GACjD;IACtB,CAAC,aAAa,CAAC;CAElB,MAAM,WAAW,eACb,GAAG,eAAe,iBAClB;AAEJ,QAAO,cAAc,qBAAqB,SAAS,EAAE,CAAC,SAAS,CAAC"}
1
+ {"version":3,"file":"usePathname.mjs","names":["useNextPathname"],"sources":["../../../src/client/usePathname.ts"],"sourcesContent":["'use client';\n\nimport { getPathWithoutLocale } from '@intlayer/core/localization';\nimport { usePathname as useNextPathname } from 'next/navigation.js';\nimport { useEffect, useMemo, useState } from 'react';\n\n/**\n * Next.js hook that returns the current pathname with the locale segment removed.\n *\n * Wraps Next.js `usePathname()` so it re-renders on client navigations and\n * appends any search parameters before stripping the locale prefix.\n *\n * @returns The current pathname without the locale prefix.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { usePathname } from 'next-intlayer';\n *\n * const NavItem = ({ href }: { href: string }) => {\n * const pathname = usePathname();\n * return <a className={pathname === href ? 'active' : ''}>{href}</a>;\n * };\n * ```\n */\nexport const usePathname = (): string => {\n const nextPathname = useNextPathname();\n const [searchParams, setSearchParams] = useState<string>('');\n\n useEffect(() => {\n const search = typeof window !== 'undefined' ? window.location.search : '';\n setSearchParams(search);\n }, [nextPathname]);\n\n const fullPath = searchParams\n ? `${nextPathname}${searchParams}`\n : nextPathname;\n\n return useMemo(() => getPathWithoutLocale(fullPath), [fullPath]);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,oBAA4B;CACvC,MAAM,eAAeA,cAAgB;CACrC,MAAM,CAAC,cAAc,mBAAmB,SAAiB,EAAE;CAE3D,gBAAgB;EACd,MAAM,SAAS,OAAO,WAAW,cAAc,OAAO,SAAS,SAAS;EACxE,gBAAgB,MAAM;CACxB,GAAG,CAAC,YAAY,CAAC;CAEjB,MAAM,WAAW,eACb,GAAG,eAAe,iBAClB;CAEJ,OAAO,cAAc,qBAAqB,QAAQ,GAAG,CAAC,QAAQ,CAAC;AACjE"}
@@ -1 +1 @@
1
- {"version":3,"file":"generateStaticParams.mjs","names":[],"sources":["../../src/generateStaticParams.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\n\nconst { locales } = internationalization;\n\n/**\n * Generates static parameters for Next.js's dynamic routes based on the configured locales.\n *\n * This function is typically used in Next.js App Router for `generateStaticParams`\n * to ensure all supported locales are pre-rendered at build time.\n *\n * @returns An array of objects containing the `locale` parameter for each configured locale.\n *\n * @example\n * ```tsx\n * // app/[locale]/layout.tsx\n * export { generateStaticParams } from 'next-intlayer';\n *\n * export default async function RootLayout({ children, params }) {\n * // ...\n * }\n * ```\n */\nexport const generateStaticParams = () => locales.map((locale) => ({ locale }));\n"],"mappings":";;;AAEA,MAAM,EAAE,YAAY;;;;;;;;;;;;;;;;;;;AAoBpB,MAAa,6BAA6B,QAAQ,KAAK,YAAY,EAAE,QAAQ,EAAE"}
1
+ {"version":3,"file":"generateStaticParams.mjs","names":[],"sources":["../../src/generateStaticParams.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\n\nconst { locales } = internationalization;\n\n/**\n * Generates static parameters for Next.js's dynamic routes based on the configured locales.\n *\n * This function is typically used in Next.js App Router for `generateStaticParams`\n * to ensure all supported locales are pre-rendered at build time.\n *\n * @returns An array of objects containing the `locale` parameter for each configured locale.\n *\n * @example\n * ```tsx\n * // app/[locale]/layout.tsx\n * export { generateStaticParams } from 'next-intlayer';\n *\n * export default async function RootLayout({ children, params }) {\n * // ...\n * }\n * ```\n */\nexport const generateStaticParams = () => locales.map((locale) => ({ locale }));\n"],"mappings":";;;AAEA,MAAM,EAAE,YAAY;;;;;;;;;;;;;;;;;;;AAoBpB,MAAa,6BAA6B,QAAQ,KAAK,YAAY,EAAE,OAAO,EAAE"}