gt-next 11.2.1 → 11.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +2 -7
- package/dist/config.js.map +1 -1
- package/dist/config.mjs +4 -9
- package/dist/config.mjs.map +1 -1
- package/dist/errors/createErrors.d.ts +0 -1
- package/dist/errors/createErrors.d.ts.map +1 -1
- package/dist/errors/createErrors.js +0 -2
- package/dist/errors/createErrors.js.map +1 -1
- package/dist/errors/createErrors.mjs +1 -2
- package/dist/errors/createErrors.mjs.map +1 -1
- package/dist/middleware-dir/createNextMiddleware.d.ts +4 -1
- package/dist/middleware-dir/createNextMiddleware.d.ts.map +1 -1
- package/dist/middleware-dir/createNextMiddleware.js +38 -13
- package/dist/middleware-dir/createNextMiddleware.js.map +1 -1
- package/dist/middleware-dir/createNextMiddleware.mjs +39 -14
- package/dist/middleware-dir/createNextMiddleware.mjs.map +1 -1
- package/dist/middleware-dir/utils.d.ts +1 -1
- package/dist/middleware-dir/utils.d.ts.map +1 -1
- package/dist/middleware-dir/utils.js +5 -11
- package/dist/middleware-dir/utils.js.map +1 -1
- package/dist/middleware-dir/utils.mjs +5 -11
- package/dist/middleware-dir/utils.mjs.map +1 -1
- package/dist/middleware.d.ts +1 -1
- package/dist/middleware.d.ts.map +1 -1
- package/dist/plugin/constants.d.ts +1 -0
- package/dist/plugin/constants.d.ts.map +1 -1
- package/dist/plugin/constants.js +2 -0
- package/dist/plugin/constants.js.map +1 -1
- package/dist/plugin/constants.mjs +2 -1
- package/dist/plugin/constants.mjs.map +1 -1
- package/dist/plugin/getStableNextVersionInfo.d.ts +1 -0
- package/dist/plugin/getStableNextVersionInfo.d.ts.map +1 -1
- package/dist/plugin/getStableNextVersionInfo.js +2 -0
- package/dist/plugin/getStableNextVersionInfo.js.map +1 -1
- package/dist/plugin/getStableNextVersionInfo.mjs +3 -2
- package/dist/plugin/getStableNextVersionInfo.mjs.map +1 -1
- package/dist/provider/GTProvider.d.ts.map +1 -1
- package/dist/provider/GTProvider.js +10 -5
- package/dist/provider/GTProvider.js.map +1 -1
- package/dist/provider/GTProvider.mjs +10 -5
- package/dist/provider/GTProvider.mjs.map +1 -1
- package/dist/request/localeValidation.js +2 -2
- package/dist/request/localeValidation.js.map +1 -1
- package/dist/request/localeValidation.mjs +2 -2
- package/dist/request/localeValidation.mjs.map +1 -1
- package/dist/utils/client-boundary.d.ts +4 -1
- package/dist/utils/client-boundary.d.ts.map +1 -1
- package/dist/utils/client-boundary.js +14 -10
- package/dist/utils/client-boundary.js.map +1 -1
- package/dist/utils/client-boundary.mjs +14 -10
- package/dist/utils/client-boundary.mjs.map +1 -1
- package/package.json +8 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createNextMiddleware.mjs","names":[],"sources":["../../src/middleware-dir/createNextMiddleware.ts"],"sourcesContent":["import { applyTrailingSlash } from './pathname';\nimport { isSameDialect, standardizeLocale } from '@generaltranslation/format';\nimport { GTRuntime } from 'generaltranslation/runtime';\nimport { libraryDefaultLocale } from 'generaltranslation/internal';\nimport { createUnsupportedLocalesWarning } from '../errors/middleware';\nimport { NextResponse } from 'next/server';\nimport type { NextRequest } from 'next/server';\nimport {\n defaultLocaleRoutingEnabledCookieName,\n defaultReferrerLocaleCookieName,\n} from '../utils/cookies';\nimport {\n defaultLocaleCookieName,\n defaultResetLocaleCookieName,\n} from '@generaltranslation/react-core/pure';\nimport {\n normalizePathname,\n getSharedPath,\n replaceDynamicSegments,\n getLocalizedPath,\n createPathToSharedPathMap,\n getLocaleFromRequest,\n getResponse,\n ResponseConfig,\n type PathConfig,\n type PathMatcher,\n} from './utils';\nimport { defaultLocaleHeaderName } from '../utils/headers';\nimport type { CustomMapping } from '@generaltranslation/format/types';\nimport type { HeadersAndCookies } from '../config-dir/props/withGTConfigProps';\nimport { compilePathRegex, pathnameMatchesRegex } from '../utils/pathRegex';\n\nconst NEXT_JS_SOURCE_MAP_PATH = '/__nextjs_source-map';\n\ntype MiddlewareEnvConfig = {\n customMapping?: CustomMapping;\n defaultLocale?: string;\n locales?: string[];\n headersAndCookies?: HeadersAndCookies;\n};\n\nexport type RouteOverrides = Record<string, readonly string[]>;\n\n/**\n * Middleware factory to create a Next.js middleware for i18n routing and locale detection.\n *\n * This middleware sets a cookie based on the locale derived from several sources\n * such as the request pathname, referer, or 'Accept-Language' header.\n * If locale routing is enabled, it redirects to the localized pathname and\n * updates the locale cookie.\n *\n * @param {boolean} [config.localeRouting=true] - Flag to enable or disable automatic locale-based routing.\n * @param {boolean} [config.prefixDefaultLocale=false] - Flag to enable or disable prefixing the default locale to the pathname, i.e., /en/about -> /about\n * @param {boolean} [config.ignoreSourceMaps=true] - Flag to enable or disable ignoring source maps\n * @param {PathConfig} [config.pathConfig] - Path configuration for locale routing\n * @param {RouteOverrides} [config.routeOverrides] - Locale-relative paths to rewrite from /{locale}/{path} to /{locale}/{locale}/{path}\n * @returns {function} - A middleware function that processes the request and response.\n */\nexport function createNextMiddleware({\n localeRouting = true,\n prefixDefaultLocale = false,\n ignoreSourceMaps = true,\n pathConfig = {},\n routeOverrides = {},\n}: {\n localeRouting?: boolean;\n prefixDefaultLocale?: boolean;\n ignoreSourceMaps?: boolean;\n pathConfig?: PathConfig;\n routeOverrides?: RouteOverrides;\n} = {}) {\n const pathRegex = compilePathRegex(\n process.env._GENERALTRANSLATION_PATH_REGEX\n );\n\n // i18n config\n let envParams: MiddlewareEnvConfig | undefined;\n if (process.env._GENERALTRANSLATION_I18N_CONFIG_PARAMS) {\n try {\n envParams = JSON.parse(\n process.env._GENERALTRANSLATION_I18N_CONFIG_PARAMS\n );\n } catch (error) {\n console.error(`gt-next middleware:`, error);\n }\n }\n\n // gt instance\n const gt = new GTRuntime({\n customMapping: envParams?.customMapping,\n });\n\n // using gt services\n const gtServicesEnabled =\n process.env._GENERALTRANSLATION_GT_SERVICES_ENABLED === 'true';\n\n // i18n config\n const defaultLocale: string =\n envParams?.defaultLocale || libraryDefaultLocale;\n const locales: string[] = envParams?.locales || [defaultLocale];\n\n // add canonical locales\n const canonicalLocales = Object.values(envParams?.customMapping || {})\n .filter(\n (locale): locale is { code: string } =>\n typeof locale === 'object' &&\n locale !== null &&\n 'code' in locale &&\n typeof locale.code === 'string' &&\n locale.code.length > 0\n )\n .map((locale) => locale.code);\n locales.push(...canonicalLocales);\n\n // cookies and header names\n const headersAndCookies = envParams?.headersAndCookies || {};\n const localeRoutingEnabledCookieName =\n headersAndCookies?.localeRoutingEnabledCookieName ||\n defaultLocaleRoutingEnabledCookieName;\n const referrerLocaleCookieName =\n headersAndCookies?.referrerLocaleCookieName ||\n defaultReferrerLocaleCookieName;\n const localeCookieName =\n headersAndCookies?.localeCookieName || defaultLocaleCookieName;\n const resetLocaleCookieName =\n headersAndCookies?.resetLocaleCookieName || defaultResetLocaleCookieName;\n const localeHeaderName =\n headersAndCookies?.localeHeaderName || defaultLocaleHeaderName;\n\n if (!gt.isValidLocale(defaultLocale))\n throw new Error(\n `gt-next middleware: defaultLocale \"${defaultLocale}\" is not a valid locale.`\n );\n\n const warningLocales = locales.filter((locale) => !gt.isValidLocale(locale));\n if (warningLocales.length)\n console.warn(createUnsupportedLocalesWarning(warningLocales));\n\n // ---------- PRE-PROCESSING PATHS ---------- //\n\n // Standardize pathConfig paths\n pathConfig = Object.entries(pathConfig).reduce<PathConfig>(\n (acc, [sharedPath, localizedPath]) => {\n if (typeof localizedPath === 'string') {\n acc[sharedPath] = localizedPath;\n } else {\n acc[sharedPath] = Object.entries(localizedPath).reduce<{\n [key: string]: string;\n }>((acc, [locale, localizedPath]) => {\n acc[gtServicesEnabled ? standardizeLocale(locale) : locale] =\n localizedPath;\n return acc;\n }, {});\n }\n return acc;\n },\n {}\n );\n\n // Standardize routeOverrides locales\n routeOverrides = Object.entries(routeOverrides).reduce<RouteOverrides>(\n (acc, [locale, paths]) => {\n acc[gtServicesEnabled ? standardizeLocale(locale) : locale] = paths;\n return acc;\n },\n {}\n );\n\n // Create the route override path mapping\n const routeOverridePathMaps = Object.entries(routeOverrides).reduce<\n Record<string, PathMatcher>\n >((acc, [locale, paths]) => {\n const overridePathConfig = Object.fromEntries(\n paths.map((path) => [path, path])\n );\n acc[locale] = createPathToSharedPathMap(\n overridePathConfig,\n true,\n defaultLocale\n ).pathToSharedPath;\n return acc;\n }, {});\n\n // Create the path mapping\n const { pathToSharedPath, defaultLocalePaths } = createPathToSharedPathMap(\n pathConfig,\n prefixDefaultLocale,\n defaultLocale\n );\n\n /**\n * Processes the incoming request to determine the user's locale and sets a locale cookie.\n * Optionally redirects the user based on the locale if locale-based routing is enabled.\n *\n * - Checks if the request URL contains a locale.\n * - Falls back to the referer URL for locale if needed.\n * - If no locale is found in the URL or referer, it checks the 'Accept-Language' header.\n * - Sets a cookie with the detected or default locale.\n * - Redirects to the correct locale route if locale routing is enabled.\n *\n * @param {NextRequest} req - The incoming request object, containing URL and headers.\n * @returns {NextResponse} - The Next.js response, either continuing the request or redirecting to the localized URL.\n */\n function middleware(req: NextRequest) {\n if (!pathnameMatchesRegex(req.nextUrl.pathname, pathRegex)) {\n return NextResponse.next();\n }\n\n // Ignore source maps\n if (\n ignoreSourceMaps &&\n req.nextUrl.pathname.startsWith(NEXT_JS_SOURCE_MAP_PATH)\n ) {\n return NextResponse.next();\n }\n\n // ---------- LOCALE DETECTION ---------- //\n\n const {\n userLocale,\n pathnameLocale,\n unstandardizedPathnameLocale,\n clearResetCookie,\n } = getLocaleFromRequest(\n req,\n defaultLocale,\n locales,\n localeRouting,\n gtServicesEnabled,\n prefixDefaultLocale,\n defaultLocalePaths,\n referrerLocaleCookieName,\n localeCookieName,\n resetLocaleCookieName,\n gt\n );\n\n const headerList = new Headers(req.headers);\n\n const responseConfig: Omit<ResponseConfig, 'type'> = {\n originalUrl: req.nextUrl,\n headerList,\n userLocale,\n clearResetCookie,\n localeRouting,\n localeRoutingEnabledCookieName,\n resetLocaleCookieName,\n localeHeaderName,\n };\n\n const getRewriteResponse = (responsePath: string) =>\n getResponse({ responsePath, type: 'rewrite', ...responseConfig });\n\n const getRedirectResponse = (responsePath: string) =>\n getResponse({ responsePath, type: 'redirect', ...responseConfig });\n\n const getNextResponse = () =>\n getResponse({ type: 'next', ...responseConfig });\n\n if (localeRouting) {\n // ---------- GET PATHS ---------- //\n\n // get pathname\n const { pathname } = req.nextUrl;\n\n // standardize pathname (ie, /tg/welcome -> /fil/welcome), (/blog -> /blog)\n const standardizedPathname =\n pathnameLocale && pathnameLocale !== unstandardizedPathnameLocale\n ? pathname.replace(\n new RegExp(`^/${unstandardizedPathnameLocale}`),\n `/${pathnameLocale}`\n )\n : pathname;\n\n // Get the shared path for the unprefixed pathname\n const sharedPathMatch = getSharedPath(\n standardizedPathname,\n pathToSharedPath,\n pathnameLocale\n );\n const sharedPath = sharedPathMatch?.sharedPath;\n\n // Get shared path with parameters (/en/dashboard/1/custom), for rewriting localized paths\n const sharedPathWithParameters =\n sharedPathMatch !== undefined\n ? applyTrailingSlash(\n standardizedPathname,\n replaceDynamicSegments(\n sharedPathMatch.matchedPathname,\n `/${userLocale}${sharedPath}`,\n sharedPathMatch.pathTemplate\n )\n )\n : undefined;\n\n // Localized path (/en/blog, /fr/fr-about, /fr/dashboard/[id]/custom)\n const localizedPath =\n sharedPath !== undefined\n ? getLocalizedPath(sharedPath, userLocale, pathConfig)\n : undefined;\n\n // Combine localized path with dynamic parameters (/en/blog, /fr/fr-about, /fr/dashboard/1/fr-custom)\n const localizedPathWithParameters =\n localizedPath !== undefined && sharedPathMatch !== undefined\n ? applyTrailingSlash(\n standardizedPathname,\n replaceDynamicSegments(\n sharedPathMatch.matchedPathname,\n localizedPath,\n sharedPathMatch.pathTemplate\n )\n )\n : undefined;\n\n const pagePath =\n (sharedPathWithParameters?.replace(new RegExp(`^/${userLocale}`), '') ??\n (pathnameLocale\n ? standardizedPathname.replace(new RegExp(`^/${userLocale}`), '')\n : standardizedPathname)) ||\n '/';\n const routeOverridePathMap = routeOverridePathMaps[userLocale];\n const routeOverrideMatch = routeOverridePathMap\n ? getSharedPath(pagePath, routeOverridePathMap, undefined)\n : undefined;\n const routeOverridePath =\n routeOverrideMatch !== undefined\n ? applyTrailingSlash(\n standardizedPathname,\n `/${userLocale}/${userLocale}${pagePath === '/' ? '' : pagePath}`\n )\n : undefined;\n\n // ---------- ROUTING LOGIC ---------- //\n\n // ----- CASE: no localized path exists ----- //\n\n if (localizedPathWithParameters === undefined) {\n // --- CASE: remove defaultLocale prefix --- //\n\n if (!prefixDefaultLocale && isSameDialect(userLocale, defaultLocale)) {\n if (pathnameLocale) {\n // REDIRECT CASE: used setLocale (/fr/customers -> /customers) (/en/customers -> /customers)\n if (clearResetCookie) {\n return getRedirectResponse(\n pathname.replace(\n new RegExp(`^/${unstandardizedPathnameLocale}`),\n ``\n ) || '/'\n );\n }\n } else {\n // REWRITE CASE: no pathnameLocale (/customers -> /en/customers)\n return getRewriteResponse(\n routeOverridePath || `/${userLocale}${pathname}`\n );\n }\n }\n\n // --- CASE: defaultLocale prefix --- //\n // REDIRECT CASE: no pathnameLocale (ie, /customers -> /fr/customers)\n else if (!pathnameLocale) {\n return getRedirectResponse(`/${userLocale}${pathname}`);\n }\n\n // REDIRECT CASE: wrong pathnameLocale (ie, /fr/customers -> /en/customers) (this usually happens after a locale switch)\n if (pathnameLocale && userLocale !== unstandardizedPathnameLocale) {\n return getRedirectResponse(\n pathname.replace(\n new RegExp(`^/${unstandardizedPathnameLocale}`),\n `/${userLocale}`\n )\n );\n }\n\n // BASE CASE: has pathnameLocale and it's correct\n if (routeOverridePath) {\n return getRewriteResponse(routeOverridePath);\n }\n return getNextResponse();\n }\n\n // ----- CASE: localized path exists ----- //\n\n if (!prefixDefaultLocale && isSameDialect(userLocale, defaultLocale)) {\n // --- CASE: remove defaultLocale prefix --- //\n\n if (pathnameLocale) {\n // REDIRECT CASE: remove locale prefix when setLocale is used (/en/blog -> /blog) (/fr/fr-about -> /en-about)\n if (clearResetCookie) {\n return getRedirectResponse(\n localizedPathWithParameters.replace(\n new RegExp(`^/${userLocale}`),\n ``\n ) || '/'\n );\n }\n } else {\n const localizedPublicPath =\n localizedPathWithParameters.replace(\n new RegExp(`^/${userLocale}`),\n ''\n ) || '/';\n\n // REDIRECT CASE: unprefixed pathname is wrong (/about -> /en-about)\n if (\n !pathnameLocale &&\n normalizePathname(localizedPublicPath) !==\n normalizePathname(pathname)\n ) {\n return getRedirectResponse(localizedPublicPath);\n }\n\n // REWRITE CASE: displaying correct path (/blog -> /en/blog)\n return getRewriteResponse(\n routeOverridePath || (sharedPathWithParameters as string)\n );\n }\n }\n\n // --- CASE: add defaultLocale prefix --- //\n\n // REDIRECT CASE: incorrect pathnameLocale\n if (\n normalizePathname(pathname) !==\n normalizePathname(localizedPathWithParameters)\n ) {\n return getRedirectResponse(localizedPathWithParameters);\n }\n\n if (routeOverridePath) {\n return getRewriteResponse(routeOverridePath);\n }\n\n // REWRITE CASE: displaying correct localized path, which is the same as the shared path (/fil/blog => /fil/blog) (/fr/fr-dashboard/1/fr-custom => /fr/dashboard/1/custom)\n // Next.js route identity preserves Unicode spelling, even when lookup\n // considers the public alias and shared path canonically equivalent.\n const rewriteUrl = new URL(\n sharedPathWithParameters as string,\n req.nextUrl\n );\n if (\n req.nextUrl.pathname !== rewriteUrl.pathname // no rewrite needed if it's already the shared path\n ) {\n // convert to shared path with dynamic parameters\n return getRewriteResponse(sharedPathWithParameters as string);\n }\n }\n\n // BASE CASE\n return getNextResponse();\n }\n\n return middleware;\n}\n"],"mappings":";;;;;;;;;;;;;;AAgCA,MAAM,0BAA0B;;;;;;;;;;;;;;;;AA0BhC,SAAgB,qBAAqB,EACnC,gBAAgB,MAChB,sBAAsB,OACtB,mBAAmB,MACnB,aAAa,EAAE,EACf,iBAAiB,EAAE,KAOjB,EAAE,EAAE;CACN,MAAM,YAAY,iBAChB,QAAQ,IAAI,+BACb;CAGD,IAAI;AACJ,KAAI,QAAQ,IAAI,u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,QAAO,oBACL,4BAA4B,QAC1B,IAAI,OAAO,KAAK,aAAa,EAC7B,GACD,IAAI,IACN;UAEE;IACL,MAAM,sBACJ,4BAA4B,QAC1B,IAAI,OAAO,KAAK,aAAa,EAC7B,GACD,IAAI;AAGP,QACE,CAAC,kBACD,kBAAkB,oBAAoB,KACpC,kBAAkB,SAAS,CAE7B,QAAO,oBAAoB,oBAAoB;AAIjD,WAAO,mBACL,qBAAsB,yBACvB;;AAOL,OACE,kBAAkB,SAAS,KAC3B,kBAAkB,4BAA4B,CAE9C,QAAO,oBAAoB,4BAA4B;AAGzD,OAAI,kBACF,QAAO,mBAAmB,kBAAkB;GAM9C,MAAM,aAAa,IAAI,IACrB,0BACA,IAAI,QACL;AACD,OACE,IAAI,QAAQ,aAAa,WAAW,SAGpC,QAAO,mBAAmB,yBAAmC;;AAKjE,SAAO,iBAAiB;;AAG1B,QAAO"}
|
|
1
|
+
{"version":3,"file":"createNextMiddleware.mjs","names":[],"sources":["../../src/middleware-dir/createNextMiddleware.ts"],"sourcesContent":["import { applyTrailingSlash } from './pathname';\nimport { GTRuntime } from 'generaltranslation/runtime';\nimport { libraryDefaultLocale } from 'generaltranslation/internal';\nimport { createUnsupportedLocalesWarning } from '../errors/middleware';\nimport { NextResponse } from 'next/server';\nimport type { NextRequest } from 'next/server';\nimport {\n defaultLocaleRoutingEnabledCookieName,\n defaultReferrerLocaleCookieName,\n} from '../utils/cookies';\nimport {\n defaultLocaleCookieName,\n defaultResetLocaleCookieName,\n} from '@generaltranslation/react-core/pure';\nimport {\n normalizePathname,\n getSharedPath,\n replaceDynamicSegments,\n getLocalizedPath,\n createPathToSharedPathMap,\n createPathMatcher,\n getLocaleFromRequest,\n getResponse,\n ResponseConfig,\n type PathConfig,\n type PathMatcher,\n} from './utils';\nimport { defaultLocaleHeaderName } from '../utils/headers';\nimport type { CustomMapping } from '@generaltranslation/format/types';\nimport type { HeadersAndCookies } from '../config-dir/props/withGTConfigProps';\nimport { compilePathRegex, pathnameMatchesRegex } from '../utils/pathRegex';\n\nconst NEXT_JS_SOURCE_MAP_PATH = '/__nextjs_source-map';\n\ntype MiddlewareEnvConfig = {\n customMapping?: CustomMapping;\n defaultLocale?: string;\n locales?: string[];\n headersAndCookies?: HeadersAndCookies;\n};\n\nexport type RouteOverrides = Record<string, readonly string[]>;\n\nexport type LocaleRoutes = Record<string, readonly string[]>;\n\n/**\n * Middleware factory to create a Next.js middleware for i18n routing and locale detection.\n *\n * This middleware sets a cookie based on the locale derived from several sources\n * such as the request pathname, referer, or 'Accept-Language' header.\n * If locale routing is enabled, it redirects to the localized pathname and\n * updates the locale cookie.\n *\n * @param {boolean} [config.localeRouting=true] - Flag to enable or disable automatic locale-based routing.\n * @param {boolean} [config.prefixDefaultLocale=false] - Flag to enable or disable prefixing the default locale to the pathname, i.e., /en/about -> /about\n * @param {boolean} [config.ignoreSourceMaps=true] - Flag to enable or disable ignoring source maps\n * @param {PathConfig} [config.pathConfig] - Path configuration for locale routing\n * @param {RouteOverrides} [config.routeOverrides] - Locale-relative paths to rewrite from /{locale}/{path} to /{locale}/{locale}/{path}\n * @param {LocaleRoutes} [config.localeRoutes] - Shared paths available per locale; other paths fall back to the default locale\n * @returns {function} - A middleware function that processes the request and response.\n */\nexport function createNextMiddleware({\n localeRouting = true,\n prefixDefaultLocale = false,\n ignoreSourceMaps = true,\n pathConfig = {},\n routeOverrides = {},\n localeRoutes = {},\n}: {\n localeRouting?: boolean;\n prefixDefaultLocale?: boolean;\n ignoreSourceMaps?: boolean;\n pathConfig?: PathConfig;\n routeOverrides?: RouteOverrides;\n localeRoutes?: LocaleRoutes;\n} = {}) {\n const pathRegex = compilePathRegex(\n process.env._GENERALTRANSLATION_PATH_REGEX\n );\n\n // i18n config\n let envParams: MiddlewareEnvConfig | undefined;\n if (process.env._GENERALTRANSLATION_I18N_CONFIG_PARAMS) {\n try {\n envParams = JSON.parse(\n process.env._GENERALTRANSLATION_I18N_CONFIG_PARAMS\n );\n } catch (error) {\n console.error(`gt-next middleware:`, error);\n }\n }\n\n // gt instance\n const gt = new GTRuntime({\n customMapping: envParams?.customMapping,\n });\n\n // Configured spellings are the identity used by routes, cookies and caches.\n const defaultLocale: string =\n envParams?.defaultLocale || libraryDefaultLocale;\n const locales = Array.from(\n new Set([defaultLocale, ...(envParams?.locales || [])])\n );\n // Route entries repeat locale keys. Resolve each key once per factory instead\n // of rebuilding the full locale-resolution index for every route/locale pair.\n const resolvedConfigLocales = new Map<string, string>();\n const determineLocaleWithCache = (locale: string) => {\n const cached = resolvedConfigLocales.get(locale);\n if (cached !== undefined) return cached;\n const resolved = gt.determineLocale(locale, locales) ?? locale;\n resolvedConfigLocales.set(locale, resolved);\n return resolved;\n };\n const resolvePathConfigLocale =\n process.env._GENERALTRANSLATION_GT_SERVICES_ENABLED === 'true'\n ? determineLocaleWithCache\n : (locale: string) => locale;\n\n // cookies and header names\n const headersAndCookies = envParams?.headersAndCookies || {};\n const localeRoutingEnabledCookieName =\n headersAndCookies?.localeRoutingEnabledCookieName ||\n defaultLocaleRoutingEnabledCookieName;\n const referrerLocaleCookieName =\n headersAndCookies?.referrerLocaleCookieName ||\n defaultReferrerLocaleCookieName;\n const localeCookieName =\n headersAndCookies?.localeCookieName || defaultLocaleCookieName;\n const resetLocaleCookieName =\n headersAndCookies?.resetLocaleCookieName || defaultResetLocaleCookieName;\n const localeHeaderName =\n headersAndCookies?.localeHeaderName || defaultLocaleHeaderName;\n\n if (!gt.isValidLocale(defaultLocale))\n throw new Error(\n `gt-next middleware: defaultLocale \"${defaultLocale}\" is not a valid locale.`\n );\n\n const warningLocales = locales.filter((locale) => !gt.isValidLocale(locale));\n if (warningLocales.length)\n console.warn(createUnsupportedLocalesWarning(warningLocales));\n\n // ---------- PRE-PROCESSING PATHS ---------- //\n\n // --- localized routes --- //\n // Resolve pathConfig keys to the configured locale spelling.\n pathConfig = Object.entries(pathConfig).reduce<PathConfig>(\n (acc, [sharedPath, localizedPath]) => {\n if (typeof localizedPath === 'string') {\n acc[sharedPath] = localizedPath;\n } else {\n acc[sharedPath] = Object.entries(localizedPath).reduce<{\n [key: string]: string;\n }>((acc, [locale, localizedPath]) => {\n acc[resolvePathConfigLocale(locale)] = localizedPath;\n return acc;\n }, {});\n }\n return acc;\n },\n {}\n );\n\n // String aliases apply to every locale, including the default locale.\n // Expand a copy for lookup while retaining string target semantics in routing.\n const matcherPathConfig = Object.fromEntries(\n Object.entries(pathConfig).map(([sharedPath, localizedPath]) => [\n sharedPath,\n typeof localizedPath === 'string'\n ? Object.fromEntries(\n locales.map((locale) => [\n determineLocaleWithCache(locale),\n localizedPath === '' ? '/' : localizedPath,\n ])\n )\n : localizedPath,\n ])\n );\n\n // Create the path mapping\n const { pathToSharedPath, defaultLocalePaths } = createPathToSharedPathMap(\n matcherPathConfig,\n prefixDefaultLocale,\n defaultLocale\n );\n\n // --- route overrides --- //\n // Resolve routeOverrides keys to the configured locale spelling.\n routeOverrides = Object.entries(routeOverrides).reduce<RouteOverrides>(\n (acc, [locale, paths]) => {\n acc[resolvePathConfigLocale(locale)] = paths;\n return acc;\n },\n {}\n );\n\n // Create the route override path mapping\n const routeOverridePathMaps = Object.entries(routeOverrides).reduce<\n Record<string, PathMatcher>\n >((acc, [locale, paths]) => {\n const overridePathConfig = Object.fromEntries(\n paths.map((path) => [path, path])\n );\n acc[locale] = createPathToSharedPathMap(\n overridePathConfig,\n true,\n defaultLocale\n ).pathToSharedPath;\n return acc;\n }, {});\n\n // --- locale routes --- //\n // Compile availability separately from aliases and overrides so it cannot\n // change route precedence. An empty list deliberately matches nothing.\n const localeRoutePathMaps = new Map(\n Object.entries(localeRoutes).map(([locale, paths]) => {\n // Match request resolution so equivalent spellings use the same map key.\n const resolvedLocale = determineLocaleWithCache(locale);\n return [\n resolvedLocale,\n createPathMatcher(paths.map((path) => [path, path])),\n ];\n })\n );\n\n /**\n * Processes the incoming request to determine the user's locale and sets a locale cookie.\n * Optionally redirects the user based on the locale if locale-based routing is enabled.\n *\n * - Checks if the request URL contains a locale.\n * - Falls back to the referer URL for locale if needed.\n * - If no locale is found in the URL or referer, it checks the 'Accept-Language' header.\n * - Sets a cookie with the detected or default locale.\n * - Redirects to the correct locale route if locale routing is enabled.\n *\n * @param {NextRequest} req - The incoming request object, containing URL and headers.\n * @returns {NextResponse} - The Next.js response, either continuing the request or redirecting to the localized URL.\n */\n function middleware(req: NextRequest) {\n if (!pathnameMatchesRegex(req.nextUrl.pathname, pathRegex)) {\n return NextResponse.next();\n }\n\n // Ignore source maps\n if (\n ignoreSourceMaps &&\n req.nextUrl.pathname.startsWith(NEXT_JS_SOURCE_MAP_PATH)\n ) {\n return NextResponse.next();\n }\n\n // ---------- LOCALE DETECTION ---------- //\n\n const {\n userLocale: requestedLocale,\n pathnameLocale: pathnameRoutingLocale,\n unstandardizedPathnameLocale,\n clearResetCookie,\n } = getLocaleFromRequest(\n req,\n defaultLocale,\n locales,\n localeRouting,\n prefixDefaultLocale,\n defaultLocalePaths,\n referrerLocaleCookieName,\n localeCookieName,\n resetLocaleCookieName,\n gt\n );\n\n let userLocale = requestedLocale;\n const pathnameLocale = pathnameRoutingLocale;\n const headerList = new Headers(req.headers);\n\n const responseConfig: Omit<ResponseConfig, 'type'> = {\n originalUrl: req.nextUrl,\n headerList,\n userLocale,\n clearResetCookie,\n localeRouting,\n localeRoutingEnabledCookieName,\n resetLocaleCookieName,\n localeHeaderName,\n };\n\n const getRewriteResponse = (responsePath: string) =>\n getResponse({ responsePath, type: 'rewrite', ...responseConfig });\n\n const getRedirectResponse = (responsePath: string) =>\n getResponse({ responsePath, type: 'redirect', ...responseConfig });\n\n const getNextResponse = () =>\n getResponse({ type: 'next', ...responseConfig });\n\n if (localeRouting) {\n // ---------- GET PATHS ---------- //\n\n // get pathname\n const { pathname } = req.nextUrl;\n\n // standardize pathname (ie, /tg/welcome -> /fil/welcome), (/blog -> /blog)\n const standardizedPathname =\n pathnameLocale && pathnameLocale !== unstandardizedPathnameLocale\n ? pathname.replace(\n new RegExp(`^/${unstandardizedPathnameLocale}`),\n `/${pathnameLocale}`\n )\n : pathname;\n\n // Get the shared path for the unprefixed pathname\n const sharedPathMatch = getSharedPath(\n standardizedPathname,\n pathToSharedPath,\n pathnameLocale\n );\n const sharedPath = sharedPathMatch?.sharedPath;\n\n // Return early for a locale route that does not exist\n const localeRoutePathMap = localeRoutePathMaps.get(userLocale);\n if (userLocale !== defaultLocale && localeRoutePathMap) {\n // Resolve the shared page path without a locale prefix (e.g. /blog/hello).\n // Strip the URL's locale, which may differ from the newly selected locale.\n const sharedPagePath = sharedPathMatch\n ? replaceDynamicSegments(\n sharedPathMatch.matchedPathname,\n sharedPath || '/',\n sharedPathMatch.pathTemplate\n )\n : (pathnameLocale\n ? standardizedPathname.slice(pathnameLocale.length + 1)\n : standardizedPathname) || '/';\n\n // If the path does not exist, redirect to the default locale path\n if (\n getSharedPath(sharedPagePath, localeRoutePathMap, undefined) ===\n undefined\n ) {\n // Get the path to redirect to\n const defaultPath =\n sharedPath !== undefined\n ? getLocalizedPath(sharedPath, defaultLocale, pathConfig)\n : undefined;\n const fallbackPath =\n defaultPath !== undefined && sharedPathMatch\n ? replaceDynamicSegments(\n sharedPathMatch.matchedPathname,\n defaultPath,\n sharedPathMatch.pathTemplate\n )\n : `/${defaultLocale}${sharedPagePath === '/' ? '' : sharedPagePath}`;\n const publicFallbackPath = applyTrailingSlash(\n standardizedPathname,\n prefixDefaultLocale\n ? fallbackPath\n : fallbackPath.slice(defaultLocale.length + 1) || '/'\n );\n\n // The default locale is terminal, even if the preference/reset cookie\n // still requests an unavailable locale on the redirected request.\n userLocale = defaultLocale;\n responseConfig.userLocale = defaultLocale;\n const fallbackUrl = new URL(req.nextUrl);\n fallbackUrl.pathname = publicFallbackPath;\n if (fallbackUrl.pathname !== pathname) {\n return getRedirectResponse(publicFallbackPath);\n }\n // Already at the fallback URL: use normal default-locale routing below,\n // including its alias/override rewrite, instead of redirecting to itself.\n }\n }\n\n // Get shared path with parameters (/en/dashboard/1/custom), for rewriting localized paths\n const sharedPathWithParameters =\n sharedPathMatch !== undefined\n ? applyTrailingSlash(\n standardizedPathname,\n replaceDynamicSegments(\n sharedPathMatch.matchedPathname,\n `/${userLocale}${sharedPath}`,\n sharedPathMatch.pathTemplate\n )\n )\n : undefined;\n\n // Localized path (/en/blog, /fr/fr-about, /fr/dashboard/[id]/custom)\n const localizedPath =\n sharedPath !== undefined\n ? getLocalizedPath(sharedPath, userLocale, pathConfig)\n : undefined;\n\n // Combine localized path with dynamic parameters (/en/blog, /fr/fr-about, /fr/dashboard/1/fr-custom)\n const localizedPathWithParameters =\n localizedPath !== undefined && sharedPathMatch !== undefined\n ? applyTrailingSlash(\n standardizedPathname,\n replaceDynamicSegments(\n sharedPathMatch.matchedPathname,\n localizedPath,\n sharedPathMatch.pathTemplate\n )\n )\n : undefined;\n\n const pagePath =\n (sharedPathWithParameters?.slice(userLocale.length + 1) ??\n (pathnameLocale\n ? standardizedPathname.slice(pathnameLocale.length + 1)\n : standardizedPathname)) ||\n '/';\n const routeOverridePathMap = routeOverridePathMaps[userLocale];\n const routeOverrideMatch = routeOverridePathMap\n ? getSharedPath(pagePath, routeOverridePathMap, undefined)\n : undefined;\n const routeOverridePath =\n routeOverrideMatch !== undefined\n ? applyTrailingSlash(\n standardizedPathname,\n `/${userLocale}/${userLocale}${pagePath === '/' ? '' : pagePath}`\n )\n : undefined;\n\n // ---------- ROUTING LOGIC ---------- //\n\n // ----- CASE: no localized path exists ----- //\n\n if (localizedPathWithParameters === undefined) {\n // --- CASE: remove defaultLocale prefix --- //\n\n if (!prefixDefaultLocale && userLocale === defaultLocale) {\n if (pathnameLocale) {\n // REDIRECT CASE: used setLocale (/fr/customers -> /customers) (/en/customers -> /customers)\n if (clearResetCookie) {\n return getRedirectResponse(\n pathname.replace(\n new RegExp(`^/${unstandardizedPathnameLocale}`),\n ``\n ) || '/'\n );\n }\n } else {\n // REWRITE CASE: no pathnameLocale (/customers -> /en/customers)\n return getRewriteResponse(\n routeOverridePath || `/${userLocale}${pathname}`\n );\n }\n }\n\n // --- CASE: defaultLocale prefix --- //\n // REDIRECT CASE: no pathnameLocale (ie, /customers -> /fr/customers)\n else if (!pathnameLocale) {\n return getRedirectResponse(`/${userLocale}${pathname}`);\n }\n\n // REDIRECT CASE: wrong pathnameLocale (ie, /fr/customers -> /en/customers) (this usually happens after a locale switch)\n if (pathnameLocale && userLocale !== unstandardizedPathnameLocale) {\n return getRedirectResponse(\n pathname.replace(\n new RegExp(`^/${unstandardizedPathnameLocale}`),\n `/${userLocale}`\n )\n );\n }\n\n // BASE CASE: has pathnameLocale and it's correct\n if (routeOverridePath) {\n return getRewriteResponse(routeOverridePath);\n }\n return getNextResponse();\n }\n\n // ----- CASE: localized path exists ----- //\n\n if (!prefixDefaultLocale && userLocale === defaultLocale) {\n // --- CASE: remove defaultLocale prefix --- //\n\n if (pathnameLocale) {\n // REDIRECT CASE: remove locale prefix when setLocale is used (/en/blog -> /blog) (/fr/fr-about -> /en-about)\n if (clearResetCookie) {\n return getRedirectResponse(\n localizedPathWithParameters.replace(\n new RegExp(`^/${userLocale}`),\n ``\n ) || '/'\n );\n }\n } else {\n const localizedPublicPath =\n localizedPathWithParameters.replace(\n new RegExp(`^/${userLocale}`),\n ''\n ) || '/';\n\n // REDIRECT CASE: unprefixed pathname is wrong (/about -> /en-about)\n if (\n !pathnameLocale &&\n normalizePathname(localizedPublicPath) !==\n normalizePathname(pathname)\n ) {\n return getRedirectResponse(localizedPublicPath);\n }\n\n // REWRITE CASE: displaying correct path (/blog -> /en/blog)\n return getRewriteResponse(\n routeOverridePath || (sharedPathWithParameters as string)\n );\n }\n }\n\n // --- CASE: add defaultLocale prefix --- //\n\n // REDIRECT CASE: incorrect pathnameLocale\n if (\n normalizePathname(pathname) !==\n normalizePathname(localizedPathWithParameters)\n ) {\n return getRedirectResponse(localizedPathWithParameters);\n }\n\n if (routeOverridePath) {\n return getRewriteResponse(routeOverridePath);\n }\n\n // REWRITE CASE: displaying correct localized path, which is the same as the shared path (/fil/blog => /fil/blog) (/fr/fr-dashboard/1/fr-custom => /fr/dashboard/1/custom)\n // Next.js route identity preserves Unicode spelling, even when lookup\n // considers the public alias and shared path canonically equivalent.\n const rewriteUrl = new URL(\n sharedPathWithParameters as string,\n req.nextUrl\n );\n if (\n req.nextUrl.pathname !== rewriteUrl.pathname // no rewrite needed if it's already the shared path\n ) {\n // convert to shared path with dynamic parameters\n return getRewriteResponse(sharedPathWithParameters as string);\n }\n }\n\n // BASE CASE\n return getNextResponse();\n }\n\n return middleware;\n}\n"],"mappings":";;;;;;;;;;;;;AAgCA,MAAM,0BAA0B;;;;;;;;;;;;;;;;;AA6BhC,SAAgB,qBAAqB,EACnC,gBAAgB,MAChB,sBAAsB,OACtB,mBAAmB,MACnB,aAAa,EAAE,EACf,iBAAiB,EAAE,EACnB,eAAe,EAAE,KAQf,EAAE,EAAE;CACN,MAAM,YAAY,iBAChB,QAAQ,IAAI,+BACb;CAGD,IAAI;AACJ,KAAI,QAAQ,IAAI,uCACd,KAAI;AACF,cAAY,KAAK,MACf,QAAQ,IAAI,uCACb;UACM,OAAO;AACd,UAAQ,MAAM,uBAAuB,MAAM;;CAK/C,MAAM,KAAK,IAAI,UAAU,EACvB,eAAe,WAAW,eAC3B,CAAC;CAGF,MAAM,gBACJ,WAAW,iBAAiB;CAC9B,MAAM,UAAU,MAAM,KACpB,IAAI,IAAI,CAAC,eAAe,GAAI,WAAW,WAAW,EAAE,CAAE,CAAC,CACxD;CAGD,MAAM,wCAAwB,IAAI,KAAqB;CACvD,MAAM,4BAA4B,WAAmB;EACnD,MAAM,SAAS,sBAAsB,IAAI,OAAO;AAChD,MAAI,WAAW,KAAA,EAAW,QAAO;EACjC,MAAM,WAAW,GAAG,gBAAgB,QAAQ,QAAQ,IAAI;AACxD,wBAAsB,IAAI,QAAQ,SAAS;AAC3C,SAAO;;CAET,MAAM,0BACJ,QAAQ,IAAI,4CAA4C,SACpD,4BACC,WAAmB;CAG1B,MAAM,oB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nB,mBACE,sBACA,IAAI,WAAW,GAAG,aAAa,aAAa,MAAM,KAAK,WACxD,GACD,KAAA;AAMN,OAAI,gCAAgC,KAAA,GAAW;AAG7C,QAAI,CAAC,uBAAuB,eAAe,cACzC,KAAI;SAEE,iBACF,QAAO,oBACL,SAAS,QACP,IAAI,OAAO,KAAK,+BAA+B,EAC/C,GACD,IAAI,IACN;UAIH,QAAO,mBACL,qBAAqB,IAAI,aAAa,WACvC;aAMI,CAAC,eACR,QAAO,oBAAoB,IAAI,aAAa,WAAW;AAIzD,QAAI,kBAAkB,eAAe,6BACnC,QAAO,oBACL,SAAS,QACP,IAAI,OAAO,KAAK,+BAA+B,EAC/C,IAAI,aACL,CACF;AAIH,QAAI,kBACF,QAAO,mBAAmB,kBAAkB;AAE9C,WAAO,iBAAiB;;AAK1B,OAAI,CAAC,uBAAuB,eAAe,cAGzC,KAAI;QAEE,iBACF,QAAO,oBACL,4BAA4B,QAC1B,IAAI,OAAO,KAAK,aAAa,EAC7B,GACD,IAAI,IACN;UAEE;IACL,MAAM,sBACJ,4BAA4B,QAC1B,IAAI,OAAO,KAAK,aAAa,EAC7B,GACD,IAAI;AAGP,QACE,CAAC,kBACD,kBAAkB,oBAAoB,KACpC,kBAAkB,SAAS,CAE7B,QAAO,oBAAoB,oBAAoB;AAIjD,WAAO,mBACL,qBAAsB,yBACvB;;AAOL,OACE,kBAAkB,SAAS,KAC3B,kBAAkB,4BAA4B,CAE9C,QAAO,oBAAoB,4BAA4B;AAGzD,OAAI,kBACF,QAAO,mBAAmB,kBAAkB;GAM9C,MAAM,aAAa,IAAI,IACrB,0BACA,IAAI,QACL;AACD,OACE,IAAI,QAAQ,aAAa,WAAW,SAGpC,QAAO,mBAAmB,yBAAmC;;AAKjE,SAAO,iBAAiB;;AAG1B,QAAO"}
|
|
@@ -38,7 +38,7 @@ export declare function getLocalizedPath(sharedPath: string, locale: string, pat
|
|
|
38
38
|
/**
|
|
39
39
|
* Resolves the request locale from its pathname, cookies, and headers.
|
|
40
40
|
*/
|
|
41
|
-
export declare function getLocaleFromRequest(req: NextRequest, defaultLocale: string, approvedLocales: string[], localeRouting: boolean,
|
|
41
|
+
export declare function getLocaleFromRequest(req: NextRequest, defaultLocale: string, approvedLocales: string[], localeRouting: boolean, prefixDefaultLocale: boolean, defaultLocalePaths: PathMatcher, referrerLocaleCookieName: string, localeCookieName: string, resetLocaleCookieName: string, gt: GTRuntime): {
|
|
42
42
|
userLocale: string;
|
|
43
43
|
pathnameLocale: string | undefined;
|
|
44
44
|
unstandardizedPathnameLocale: string | null | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/middleware-dir/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/middleware-dir/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAExD,OAAO,EACL,iBAAiB,EACjB,yBAAyB,EAEzB,iBAAiB,EACjB,KAAK,UAAU,EACf,KAAK,WAAW,EACjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAG5C,OAAO,EACL,iBAAiB,EACjB,yBAAyB,EACzB,aAAa,EACb,iBAAiB,GAClB,CAAC;AACF,YAAY,EAAE,UAAU,EAAE,WAAW,EAAE,CAAC;AAExC,MAAM,MAAM,cAAc,GAAG;IAC3B,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,UAAU,CAAC;IACtC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,OAAO,CAAC;IACrB,UAAU,EAAE,M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cAAc,EAAE,MAAM,GAAG,SAAS,CAAC;IACnC,4BAA4B,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACxD,gBAAgB,EAAE,OAAO,CAAC;CAC3B,CAkFA"}
|
|
@@ -3,7 +3,6 @@ require("../_virtual/_rolldown/runtime.js");
|
|
|
3
3
|
const require_middleware_dir_pathname = require("./pathname.js");
|
|
4
4
|
const require_middleware_dir_createPathMatcher = require("./createPathMatcher.js");
|
|
5
5
|
const require_middleware_dir_matchPath = require("./matchPath.js");
|
|
6
|
-
let _generaltranslation_format = require("@generaltranslation/format");
|
|
7
6
|
let gt_i18n_internal = require("gt-i18n/internal");
|
|
8
7
|
let next_server_js = require("next/server.js");
|
|
9
8
|
//#region src/middleware-dir/utils.ts
|
|
@@ -93,7 +92,7 @@ function inDefaultLocalePaths(pathname, defaultLocalePaths) {
|
|
|
93
92
|
/**
|
|
94
93
|
* Resolves the request locale from its pathname, cookies, and headers.
|
|
95
94
|
*/
|
|
96
|
-
function getLocaleFromRequest(req, defaultLocale, approvedLocales, localeRouting,
|
|
95
|
+
function getLocaleFromRequest(req, defaultLocale, approvedLocales, localeRouting, prefixDefaultLocale, defaultLocalePaths, referrerLocaleCookieName, localeCookieName, resetLocaleCookieName, gt) {
|
|
97
96
|
const headerList = new Headers(req.headers);
|
|
98
97
|
const candidates = [];
|
|
99
98
|
let clearResetCookie = false;
|
|
@@ -101,13 +100,9 @@ function getLocaleFromRequest(req, defaultLocale, approvedLocales, localeRouting
|
|
|
101
100
|
let pathnameLocale, unstandardizedPathnameLocale;
|
|
102
101
|
if (localeRouting) {
|
|
103
102
|
unstandardizedPathnameLocale = extractLocale(pathname);
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
if (determinedLocale) {
|
|
108
|
-
pathnameLocale = gt.resolveAliasLocale(determinedLocale);
|
|
109
|
-
candidates.push(pathnameLocale);
|
|
110
|
-
}
|
|
103
|
+
if (unstandardizedPathnameLocale && gt.isValidLocale(unstandardizedPathnameLocale)) {
|
|
104
|
+
pathnameLocale = gt.determineLocale(unstandardizedPathnameLocale, approvedLocales);
|
|
105
|
+
if (pathnameLocale) candidates.push(pathnameLocale);
|
|
111
106
|
}
|
|
112
107
|
}
|
|
113
108
|
if (localeRouting && !prefixDefaultLocale && !pathnameLocale && inDefaultLocalePaths(pathname, defaultLocalePaths)) candidates.push(defaultLocale);
|
|
@@ -123,9 +118,8 @@ function getLocaleFromRequest(req, defaultLocale, approvedLocales, localeRouting
|
|
|
123
118
|
}
|
|
124
119
|
if (process.env._GENERALTRANSLATION_IGNORE_BROWSER_LOCALES === "false") candidates.push(...(0, gt_i18n_internal.parseAcceptLanguage)(headerList.get("accept-language")));
|
|
125
120
|
candidates.push(defaultLocale);
|
|
126
|
-
const unstandardizedUserLocale = gt.determineLocale(candidates.filter((locale) => gt.isValidLocale(locale)), approvedLocales) || defaultLocale;
|
|
127
121
|
return {
|
|
128
|
-
userLocale:
|
|
122
|
+
userLocale: gt.determineLocale(candidates.filter((locale) => gt.isValidLocale(locale)), approvedLocales) || defaultLocale,
|
|
129
123
|
pathnameLocale,
|
|
130
124
|
unstandardizedPathnameLocale,
|
|
131
125
|
clearResetCookie
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":["applyTrailingSlash","NextResponse","stripTrailingSlashes","getDynamicSegmentType","getSharedPath"],"sources":["../../src/middleware-dir/utils.ts"],"sourcesContent":["import { NextRequest, NextResponse } from 'next/server';\nimport { standardizeLocale } from '@generaltranslation/format';\nimport { GTRuntime } from 'generaltranslation/runtime';\nimport { NextURL } from 'next/dist/server/web/next-url';\nimport { parseAcceptLanguage } from 'gt-i18n/internal';\nimport {\n createPathMatcher,\n createPathToSharedPathMap,\n getDynamicSegmentType,\n normalizePathname,\n type PathConfig,\n type PathMatcher,\n} from './createPathMatcher';\nimport { getSharedPath } from './matchPath';\nimport { applyTrailingSlash, stripTrailingSlashes } from './pathname';\n\nexport {\n createPathMatcher,\n createPathToSharedPathMap,\n getSharedPath,\n normalizePathname,\n};\nexport type { PathConfig, PathMatcher };\n\nexport type ResponseConfig = {\n type: 'next' | 'rewrite' | 'redirect';\n responsePath?: string;\n originalUrl: NextURL;\n userLocale: string;\n clearResetCookie: boolean;\n headerList: Headers;\n localeRouting: boolean;\n localeRoutingEnabledCookieName: string;\n resetLocaleCookieName: string;\n localeHeaderName: string;\n};\n\nfunction applyBasePath(responseUrl: URL, originalUrl: NextURL) {\n const { basePath } = originalUrl;\n if (!basePath || responseUrl.origin !== originalUrl.origin) {\n return;\n }\n // Middleware targets are app-relative, even when a route repeats the base path.\n // Preserve the request's slash style when targeting the app root.\n responseUrl.pathname =\n responseUrl.pathname === '/'\n ? applyTrailingSlash(new URL(originalUrl).pathname, basePath)\n : `${basePath}${responseUrl.pathname}`;\n}\n\n/** Creates a middleware response and attaches GT routing state. */\nexport function getResponse({\n type,\n originalUrl,\n responsePath = originalUrl.pathname,\n userLocale,\n clearResetCookie,\n headerList,\n localeRouting,\n localeRoutingEnabledCookieName,\n resetLocaleCookieName,\n localeHeaderName,\n}: ResponseConfig): NextResponse<unknown> {\n // Get Response\n let response;\n if (type === 'next') {\n response = NextResponse.next({\n request: {\n headers: headerList,\n },\n });\n } else {\n // Assign the pathname to preserve the request origin: resolving a path\n // starting with // or /\\ as a URL can turn it into an external destination.\n const responseUrl = new URL(originalUrl);\n responseUrl.pathname = responsePath;\n applyBasePath(responseUrl, originalUrl);\n responseUrl.search = originalUrl.search;\n response =\n type === 'rewrite'\n ? NextResponse.rewrite(responseUrl, {\n request: {\n headers: headerList,\n },\n })\n : NextResponse.redirect(responseUrl);\n }\n\n // Set Headers & Cookies\n response.headers.set(localeHeaderName, userLocale);\n response.cookies.set(\n localeRoutingEnabledCookieName,\n localeRouting.toString()\n );\n // Clear the setLocale reset cookie once it has been processed. The locale\n // cookie must be kept: the client re-reads it on every render, and deleting\n // it here races with concurrent prefetch responses after a locale switch,\n // dropping client components back to the browser's default locale.\n if (clearResetCookie && type !== 'redirect') {\n response.cookies.delete(resetLocaleCookieName);\n }\n return response;\n}\n\n/**\n * Extracts the locale from the given pathname.\n */\nexport function extractLocale(pathname: string): string | null {\n const matches = pathname.match(/^\\/([^/]+)(?:\\/|$)/);\n return matches ? matches[1] : null;\n}\n\n/**\n * Extracts dynamic parameters from a path based on a shared path pattern.\n */\nexport function extractDynamicParams(\n templatePath: string,\n path: string\n): string[] {\n if (!templatePath.includes('[')) return [];\n\n const params: string[] = [];\n const pathSegments = stripTrailingSlashes(path).split('/');\n const sharedSegments = templatePath.split('/');\n\n sharedSegments.forEach((segment, index) => {\n const segmentType = getDynamicSegmentType(segment);\n if (segmentType === 'catch-all' || segmentType === 'optional-catch-all') {\n params.push(pathSegments.slice(index).join('/'));\n } else if (segmentType === 'dynamic') {\n params.push(pathSegments[index]);\n }\n });\n\n return params;\n}\n\n/**\n * Replaces dynamic segments in a path with their actual values.\n */\nexport function replaceDynamicSegments(\n path: string,\n templatePath: string,\n sourceTemplatePath = templatePath\n): string {\n if (!templatePath.includes('[')) {\n return applyTrailingSlash(path, templatePath);\n }\n\n const params = extractDynamicParams(sourceTemplatePath, path);\n let paramIndex = 0;\n const resultSegments: string[] = [];\n\n for (const segment of templatePath.split('/')) {\n const segmentType = getDynamicSegmentType(segment);\n if (!segmentType) {\n resultSegments.push(segment);\n continue;\n }\n\n const param = params[paramIndex++];\n if (segmentType === 'optional-catch-all' && !param) continue;\n if (!param) {\n resultSegments.push(segment);\n continue;\n }\n if (segmentType === 'catch-all' || segmentType === 'optional-catch-all') {\n resultSegments.push(...param.split('/'));\n } else {\n resultSegments.push(param);\n }\n }\n\n return applyTrailingSlash(path, resultSegments.join('/') || '/');\n}\n\n/**\n * Gets the full localized path given a shared path and locale.\n */\nexport function getLocalizedPath(\n sharedPath: string,\n locale: string,\n pathConfig: PathConfig\n): string | undefined {\n const localizedPath = pathConfig[sharedPath];\n let path: string | undefined;\n\n if (typeof localizedPath === 'string') {\n path = `/${locale}${localizedPath}`;\n } else if (typeof localizedPath === 'object') {\n path = localizedPath[locale]\n ? `/${locale}${localizedPath[locale]}`\n : `/${locale}${sharedPath}`;\n }\n\n return path;\n}\n\n/**\n * Checks whether a pathname matches an unprefixed default-locale path.\n */\nfunction inDefaultLocalePaths(\n pathname: string,\n defaultLocalePaths: PathMatcher\n): boolean {\n return (\n getSharedPath(pathname, defaultLocalePaths, undefined)?.sharedPath !==\n undefined\n );\n}\n\n/**\n * Resolves the request locale from its pathname, cookies, and headers.\n */\nexport function getLocaleFromRequest(\n req: NextRequest,\n defaultLocale: string,\n approvedLocales: string[],\n localeRouting: boolean,\n gtServicesEnabled: boolean,\n prefixDefaultLocale: boolean,\n defaultLocalePaths: PathMatcher,\n referrerLocaleCookieName: string,\n localeCookieName: string,\n resetLocaleCookieName: string,\n gt: GTRuntime\n): {\n userLocale: string;\n pathnameLocale: string | undefined;\n unstandardizedPathnameLocale: string | null | undefined;\n clearResetCookie: boolean;\n} {\n const headerList = new Headers(req.headers);\n const candidates: string[] = [];\n let clearResetCookie = false;\n const { pathname } = req.nextUrl;\n\n // Check pathname locales\n let pathnameLocale, unstandardizedPathnameLocale;\n if (localeRouting) {\n unstandardizedPathnameLocale = extractLocale(pathname);\n const extractedLocale = gtServicesEnabled\n ? standardizeLocale(unstandardizedPathnameLocale || '')\n : unstandardizedPathnameLocale;\n\n if (\n extractedLocale &&\n gt.isValidLocale(extractedLocale) &&\n gt.determineLocale([extractedLocale], approvedLocales)\n ) {\n const determinedLocale = gt.determineLocale(\n [extractedLocale],\n approvedLocales\n );\n if (determinedLocale) {\n pathnameLocale = gt.resolveAliasLocale(determinedLocale);\n candidates.push(pathnameLocale);\n }\n }\n }\n\n // Check pathname for a customized unprefixed default locale path (e.g. /en-about , /en-dashboard/1/en-custom)\n if (\n localeRouting &&\n !prefixDefaultLocale &&\n !pathnameLocale &&\n inDefaultLocalePaths(pathname, defaultLocalePaths)\n ) {\n candidates.push(defaultLocale); // will override other candidates\n }\n\n // Check cookie locale\n const cookieLocale = req.cookies.get(localeCookieName);\n if (cookieLocale?.value && gt.isValidLocale(cookieLocale?.value)) {\n const resetCookie = req.cookies.get(resetLocaleCookieName);\n if (resetCookie?.value) {\n // Add this back in when we support custom getLocale\n // addedCustomLocale\n // ? candidates.splice(1, 0, cookieLocale.value)\n // : candidates.unshift(cookieLocale.value);\n candidates.unshift(cookieLocale.value);\n clearResetCookie = true;\n } else {\n candidates.push(cookieLocale.value);\n }\n }\n\n // Check referrer locale\n const referrerLocaleCookie = req.cookies.get(referrerLocaleCookieName);\n if (\n referrerLocaleCookie?.value &&\n gt.isValidLocale(referrerLocaleCookie.value) &&\n !clearResetCookie\n ) {\n const referrerLocale = referrerLocaleCookie.value;\n if (gt.determineLocale([referrerLocale], approvedLocales)) {\n candidates.push(referrerLocale);\n }\n }\n\n // Get locales from accept-language header\n if (process.env._GENERALTRANSLATION_IGNORE_BROWSER_LOCALES === 'false') {\n candidates.push(...parseAcceptLanguage(headerList.get('accept-language')));\n }\n\n // Get default locale\n candidates.push(defaultLocale);\n\n // determine userLocale\n const unstandardizedUserLocale =\n gt.determineLocale(\n candidates.filter((locale) => gt.isValidLocale(locale)),\n approvedLocales\n ) || defaultLocale;\n const userLocale = gtServicesEnabled\n ? standardizeLocale(unstandardizedUserLocale)\n : unstandardizedUserLocale;\n\n return {\n userLocale,\n pathnameLocale,\n unstandardizedPathnameLocale,\n clearResetCookie,\n };\n}\n"],"mappings":";;;;;;;;;AAqCA,SAAS,cAAc,aAAkB,aAAsB;CAC7D,MAAM,EAAE,aAAa;AACrB,KAAI,CAAC,YAAY,YAAY,WAAW,YAAY,OAClD;AAIF,aAAY,WACV,YAAY,aAAa,MACrBA,gCAAAA,mBAAmB,IAAI,IAAI,YAAY,CAAC,UAAU,SAAS,GAC3D,GAAG,WAAW,YAAY;;;AAIlC,SAAgB,YAAY,EAC1B,MACA,aACA,eAAe,YAAY,UAC3B,YACA,kBACA,YACA,eACA,gCACA,uBACA,oBACwC;C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AM,mBAAmB,GAAG,gBAC1B,CAAC,gBAAgB,EACjB,gBACD;AACD,OAAI,kBAAkB;AACpB,qBAAiB,GAAG,mBAAmB,iBAAiB;AACxD,eAAW,KAAK,eAAe;;;;AAMrC,KACE,iBACA,CAAC,uBACD,CAAC,kBACD,qBAAqB,UAAU,mBAAmB,CAElD,YAAW,KAAK,cAAc;CAIhC,MAAM,eAAe,IAAI,QAAQ,IAAI,iBAAiB;AACtD,KAAI,cAAc,SAAS,GAAG,cAAc,cAAc,MAAM,CAE9D,KADoB,IAAI,QAAQ,IAAI,sBACrB,EAAE,OAAO;AAKtB,aAAW,QAAQ,aAAa,MAAM;AACtC,qBAAmB;OAEnB,YAAW,KAAK,aAAa,MAAM;CAKvC,MAAM,uBAAuB,IAAI,QAAQ,IAAI,yBAAyB;AACtE,KACE,sBAAsB,SACtB,GAAG,cAAc,qBAAqB,MAAM,IAC5C,CAAC,kBACD;EACA,MAAM,iBAAiB,qBAAqB;AAC5C,MAAI,GAAG,gBAAgB,CAAC,eAAe,EAAE,gBAAgB,CACvD,YAAW,KAAK,eAAe;;AAKnC,KAAI,QAAQ,IAAI,+CAA+C,QAC7D,YAAW,KAAK,IAAA,GAAA,iBAAA,qBAAuB,WAAW,IAAI,kBAAkB,CAAC,CAAC;AAI5E,YAAW,KAAK,cAAc;CAG9B,MAAM,2BACJ,GAAG,gBACD,WAAW,QAAQ,WAAW,GAAG,cAAc,OAAO,CAAC,EACvD,gBACD,IAAI;AAKP,QAAO;EACL,YALiB,qBAAA,GAAA,2BAAA,mBACG,yBAAyB,GAC3C;EAIF;EACA;EACA;EACD"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":["applyTrailingSlash","NextResponse","stripTrailingSlashes","getDynamicSegmentType","getSharedPath"],"sources":["../../src/middleware-dir/utils.ts"],"sourcesContent":["import { NextRequest, NextResponse } from 'next/server';\nimport { GTRuntime } from 'generaltranslation/runtime';\nimport { NextURL } from 'next/dist/server/web/next-url';\nimport { parseAcceptLanguage } from 'gt-i18n/internal';\nimport {\n createPathMatcher,\n createPathToSharedPathMap,\n getDynamicSegmentType,\n normalizePathname,\n type PathConfig,\n type PathMatcher,\n} from './createPathMatcher';\nimport { getSharedPath } from './matchPath';\nimport { applyTrailingSlash, stripTrailingSlashes } from './pathname';\n\nexport {\n createPathMatcher,\n createPathToSharedPathMap,\n getSharedPath,\n normalizePathname,\n};\nexport type { PathConfig, PathMatcher };\n\nexport type ResponseConfig = {\n type: 'next' | 'rewrite' | 'redirect';\n responsePath?: string;\n originalUrl: NextURL;\n userLocale: string;\n clearResetCookie: boolean;\n headerList: Headers;\n localeRouting: boolean;\n localeRoutingEnabledCookieName: string;\n resetLocaleCookieName: string;\n localeHeaderName: string;\n};\n\nfunction applyBasePath(responseUrl: URL, originalUrl: NextURL) {\n const { basePath } = originalUrl;\n if (!basePath || responseUrl.origin !== originalUrl.origin) {\n return;\n }\n // Middleware targets are app-relative, even when a route repeats the base path.\n // Preserve the request's slash style when targeting the app root.\n responseUrl.pathname =\n responseUrl.pathname === '/'\n ? applyTrailingSlash(new URL(originalUrl).pathname, basePath)\n : `${basePath}${responseUrl.pathname}`;\n}\n\n/** Creates a middleware response and attaches GT routing state. */\nexport function getResponse({\n type,\n originalUrl,\n responsePath = originalUrl.pathname,\n userLocale,\n clearResetCookie,\n headerList,\n localeRouting,\n localeRoutingEnabledCookieName,\n resetLocaleCookieName,\n localeHeaderName,\n}: ResponseConfig): NextResponse<unknown> {\n // Get Response\n let response;\n if (type === 'next') {\n response = NextResponse.next({\n request: {\n headers: headerList,\n },\n });\n } else {\n // Assign the pathname to preserve the request origin: resolving a path\n // starting with // or /\\ as a URL can turn it into an external destination.\n const responseUrl = new URL(originalUrl);\n responseUrl.pathname = responsePath;\n applyBasePath(responseUrl, originalUrl);\n responseUrl.search = originalUrl.search;\n response =\n type === 'rewrite'\n ? NextResponse.rewrite(responseUrl, {\n request: {\n headers: headerList,\n },\n })\n : NextResponse.redirect(responseUrl);\n }\n\n // Set Headers & Cookies\n response.headers.set(localeHeaderName, userLocale);\n response.cookies.set(\n localeRoutingEnabledCookieName,\n localeRouting.toString()\n );\n // Clear the setLocale reset cookie once it has been processed. The locale\n // cookie must be kept: the client re-reads it on every render, and deleting\n // it here races with concurrent prefetch responses after a locale switch,\n // dropping client components back to the browser's default locale.\n if (clearResetCookie && type !== 'redirect') {\n response.cookies.delete(resetLocaleCookieName);\n }\n return response;\n}\n\n/**\n * Extracts the locale from the given pathname.\n */\nexport function extractLocale(pathname: string): string | null {\n const matches = pathname.match(/^\\/([^/]+)(?:\\/|$)/);\n return matches ? matches[1] : null;\n}\n\n/**\n * Extracts dynamic parameters from a path based on a shared path pattern.\n */\nexport function extractDynamicParams(\n templatePath: string,\n path: string\n): string[] {\n if (!templatePath.includes('[')) return [];\n\n const params: string[] = [];\n const pathSegments = stripTrailingSlashes(path).split('/');\n const sharedSegments = templatePath.split('/');\n\n sharedSegments.forEach((segment, index) => {\n const segmentType = getDynamicSegmentType(segment);\n if (segmentType === 'catch-all' || segmentType === 'optional-catch-all') {\n params.push(pathSegments.slice(index).join('/'));\n } else if (segmentType === 'dynamic') {\n params.push(pathSegments[index]);\n }\n });\n\n return params;\n}\n\n/**\n * Replaces dynamic segments in a path with their actual values.\n */\nexport function replaceDynamicSegments(\n path: string,\n templatePath: string,\n sourceTemplatePath = templatePath\n): string {\n if (!templatePath.includes('[')) {\n return applyTrailingSlash(path, templatePath);\n }\n\n const params = extractDynamicParams(sourceTemplatePath, path);\n let paramIndex = 0;\n const resultSegments: string[] = [];\n\n for (const segment of templatePath.split('/')) {\n const segmentType = getDynamicSegmentType(segment);\n if (!segmentType) {\n resultSegments.push(segment);\n continue;\n }\n\n const param = params[paramIndex++];\n if (segmentType === 'optional-catch-all' && !param) continue;\n if (!param) {\n resultSegments.push(segment);\n continue;\n }\n if (segmentType === 'catch-all' || segmentType === 'optional-catch-all') {\n resultSegments.push(...param.split('/'));\n } else {\n resultSegments.push(param);\n }\n }\n\n return applyTrailingSlash(path, resultSegments.join('/') || '/');\n}\n\n/**\n * Gets the full localized path given a shared path and locale.\n */\nexport function getLocalizedPath(\n sharedPath: string,\n locale: string,\n pathConfig: PathConfig\n): string | undefined {\n const localizedPath = pathConfig[sharedPath];\n let path: string | undefined;\n\n if (typeof localizedPath === 'string') {\n path = `/${locale}${localizedPath}`;\n } else if (typeof localizedPath === 'object') {\n path = localizedPath[locale]\n ? `/${locale}${localizedPath[locale]}`\n : `/${locale}${sharedPath}`;\n }\n\n return path;\n}\n\n/**\n * Checks whether a pathname matches an unprefixed default-locale path.\n */\nfunction inDefaultLocalePaths(\n pathname: string,\n defaultLocalePaths: PathMatcher\n): boolean {\n return (\n getSharedPath(pathname, defaultLocalePaths, undefined)?.sharedPath !==\n undefined\n );\n}\n\n/**\n * Resolves the request locale from its pathname, cookies, and headers.\n */\nexport function getLocaleFromRequest(\n req: NextRequest,\n defaultLocale: string,\n approvedLocales: string[],\n localeRouting: boolean,\n prefixDefaultLocale: boolean,\n defaultLocalePaths: PathMatcher,\n referrerLocaleCookieName: string,\n localeCookieName: string,\n resetLocaleCookieName: string,\n gt: GTRuntime\n): {\n userLocale: string;\n pathnameLocale: string | undefined;\n unstandardizedPathnameLocale: string | null | undefined;\n clearResetCookie: boolean;\n} {\n const headerList = new Headers(req.headers);\n const candidates: string[] = [];\n let clearResetCookie = false;\n const { pathname } = req.nextUrl;\n\n // Check pathname locales\n let pathnameLocale, unstandardizedPathnameLocale;\n if (localeRouting) {\n unstandardizedPathnameLocale = extractLocale(pathname);\n if (\n unstandardizedPathnameLocale &&\n gt.isValidLocale(unstandardizedPathnameLocale)\n ) {\n pathnameLocale = gt.determineLocale(\n unstandardizedPathnameLocale,\n approvedLocales\n );\n if (pathnameLocale) candidates.push(pathnameLocale);\n }\n }\n\n // Check pathname for a customized unprefixed default locale path (e.g. /en-about , /en-dashboard/1/en-custom)\n if (\n localeRouting &&\n !prefixDefaultLocale &&\n !pathnameLocale &&\n inDefaultLocalePaths(pathname, defaultLocalePaths)\n ) {\n candidates.push(defaultLocale); // will override other candidates\n }\n\n // Check cookie locale\n const cookieLocale = req.cookies.get(localeCookieName);\n if (cookieLocale?.value && gt.isValidLocale(cookieLocale?.value)) {\n const resetCookie = req.cookies.get(resetLocaleCookieName);\n if (resetCookie?.value) {\n // Add this back in when we support custom getLocale\n // addedCustomLocale\n // ? candidates.splice(1, 0, cookieLocale.value)\n // : candidates.unshift(cookieLocale.value);\n candidates.unshift(cookieLocale.value);\n clearResetCookie = true;\n } else {\n candidates.push(cookieLocale.value);\n }\n }\n\n // Check referrer locale\n const referrerLocaleCookie = req.cookies.get(referrerLocaleCookieName);\n if (\n referrerLocaleCookie?.value &&\n gt.isValidLocale(referrerLocaleCookie.value) &&\n !clearResetCookie\n ) {\n const referrerLocale = referrerLocaleCookie.value;\n if (gt.determineLocale([referrerLocale], approvedLocales)) {\n candidates.push(referrerLocale);\n }\n }\n\n // Get locales from accept-language header\n if (process.env._GENERALTRANSLATION_IGNORE_BROWSER_LOCALES === 'false') {\n candidates.push(...parseAcceptLanguage(headerList.get('accept-language')));\n }\n\n // Get default locale\n candidates.push(defaultLocale);\n\n // determine userLocale\n const userLocale =\n gt.determineLocale(\n candidates.filter((locale) => gt.isValidLocale(locale)),\n approvedLocales\n ) || defaultLocale;\n\n return {\n userLocale,\n pathnameLocale,\n unstandardizedPathnameLocale,\n clearResetCookie,\n };\n}\n"],"mappings":";;;;;;;;AAoCA,SAAS,cAAc,aAAkB,aAAsB;CAC7D,MAAM,EAAE,aAAa;AACrB,KAAI,CAAC,YAAY,YAAY,WAAW,YAAY,OAClD;AAIF,aAAY,WACV,YAAY,aAAa,MACrBA,gCAAAA,mBAAmB,IAAI,IAAI,YAAY,CAAC,UAAU,SAAS,GAC3D,GAAG,WAAW,YAAY;;;AAIlC,SAAgB,YAAY,EAC1B,MACA,aACA,eAAe,YAAY,UAC3B,YACA,kBACA,YACA,eACA,gCACA,uBACA,oBACwC;CAExC,IAAI;AACJ,KAAI,SA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AAK,cAAc;CAIhC,MAAM,eAAe,IAAI,QAAQ,IAAI,iBAAiB;AACtD,KAAI,cAAc,SAAS,GAAG,cAAc,cAAc,MAAM,CAE9D,KADoB,IAAI,QAAQ,IAAI,sBACrB,EAAE,OAAO;AAKtB,aAAW,QAAQ,aAAa,MAAM;AACtC,qBAAmB;OAEnB,YAAW,KAAK,aAAa,MAAM;CAKvC,MAAM,uBAAuB,IAAI,QAAQ,IAAI,yBAAyB;AACtE,KACE,sBAAsB,SACtB,GAAG,cAAc,qBAAqB,MAAM,IAC5C,CAAC,kBACD;EACA,MAAM,iBAAiB,qBAAqB;AAC5C,MAAI,GAAG,gBAAgB,CAAC,eAAe,EAAE,gBAAgB,CACvD,YAAW,KAAK,eAAe;;AAKnC,KAAI,QAAQ,IAAI,+CAA+C,QAC7D,YAAW,KAAK,IAAA,GAAA,iBAAA,qBAAuB,WAAW,IAAI,kBAAkB,CAAC,CAAC;AAI5E,YAAW,KAAK,cAAc;AAS9B,QAAO;EACL,YANA,GAAG,gBACD,WAAW,QAAQ,WAAW,GAAG,cAAc,OAAO,CAAC,EACvD,gBACD,IAAI;EAIL;EACA;EACA;EACD"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { applyTrailingSlash, normalizePathname, stripTrailingSlashes } from "./pathname.mjs";
|
|
2
2
|
import { createPathMatcher, createPathToSharedPathMap, getDynamicSegmentType } from "./createPathMatcher.mjs";
|
|
3
3
|
import { getSharedPath } from "./matchPath.mjs";
|
|
4
|
-
import { standardizeLocale } from "@generaltranslation/format";
|
|
5
4
|
import { parseAcceptLanguage } from "gt-i18n/internal";
|
|
6
5
|
import { NextResponse } from "next/server.js";
|
|
7
6
|
//#region src/middleware-dir/utils.ts
|
|
@@ -91,7 +90,7 @@ function inDefaultLocalePaths(pathname, defaultLocalePaths) {
|
|
|
91
90
|
/**
|
|
92
91
|
* Resolves the request locale from its pathname, cookies, and headers.
|
|
93
92
|
*/
|
|
94
|
-
function getLocaleFromRequest(req, defaultLocale, approvedLocales, localeRouting,
|
|
93
|
+
function getLocaleFromRequest(req, defaultLocale, approvedLocales, localeRouting, prefixDefaultLocale, defaultLocalePaths, referrerLocaleCookieName, localeCookieName, resetLocaleCookieName, gt) {
|
|
95
94
|
const headerList = new Headers(req.headers);
|
|
96
95
|
const candidates = [];
|
|
97
96
|
let clearResetCookie = false;
|
|
@@ -99,13 +98,9 @@ function getLocaleFromRequest(req, defaultLocale, approvedLocales, localeRouting
|
|
|
99
98
|
let pathnameLocale, unstandardizedPathnameLocale;
|
|
100
99
|
if (localeRouting) {
|
|
101
100
|
unstandardizedPathnameLocale = extractLocale(pathname);
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
if (determinedLocale) {
|
|
106
|
-
pathnameLocale = gt.resolveAliasLocale(determinedLocale);
|
|
107
|
-
candidates.push(pathnameLocale);
|
|
108
|
-
}
|
|
101
|
+
if (unstandardizedPathnameLocale && gt.isValidLocale(unstandardizedPathnameLocale)) {
|
|
102
|
+
pathnameLocale = gt.determineLocale(unstandardizedPathnameLocale, approvedLocales);
|
|
103
|
+
if (pathnameLocale) candidates.push(pathnameLocale);
|
|
109
104
|
}
|
|
110
105
|
}
|
|
111
106
|
if (localeRouting && !prefixDefaultLocale && !pathnameLocale && inDefaultLocalePaths(pathname, defaultLocalePaths)) candidates.push(defaultLocale);
|
|
@@ -121,9 +116,8 @@ function getLocaleFromRequest(req, defaultLocale, approvedLocales, localeRouting
|
|
|
121
116
|
}
|
|
122
117
|
if (process.env._GENERALTRANSLATION_IGNORE_BROWSER_LOCALES === "false") candidates.push(...parseAcceptLanguage(headerList.get("accept-language")));
|
|
123
118
|
candidates.push(defaultLocale);
|
|
124
|
-
const unstandardizedUserLocale = gt.determineLocale(candidates.filter((locale) => gt.isValidLocale(locale)), approvedLocales) || defaultLocale;
|
|
125
119
|
return {
|
|
126
|
-
userLocale:
|
|
120
|
+
userLocale: gt.determineLocale(candidates.filter((locale) => gt.isValidLocale(locale)), approvedLocales) || defaultLocale,
|
|
127
121
|
pathnameLocale,
|
|
128
122
|
unstandardizedPathnameLocale,
|
|
129
123
|
clearResetCookie
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.mjs","names":[],"sources":["../../src/middleware-dir/utils.ts"],"sourcesContent":["import { NextRequest, NextResponse } from 'next/server';\nimport { standardizeLocale } from '@generaltranslation/format';\nimport { GTRuntime } from 'generaltranslation/runtime';\nimport { NextURL } from 'next/dist/server/web/next-url';\nimport { parseAcceptLanguage } from 'gt-i18n/internal';\nimport {\n createPathMatcher,\n createPathToSharedPathMap,\n getDynamicSegmentType,\n normalizePathname,\n type PathConfig,\n type PathMatcher,\n} from './createPathMatcher';\nimport { getSharedPath } from './matchPath';\nimport { applyTrailingSlash, stripTrailingSlashes } from './pathname';\n\nexport {\n createPathMatcher,\n createPathToSharedPathMap,\n getSharedPath,\n normalizePathname,\n};\nexport type { PathConfig, PathMatcher };\n\nexport type ResponseConfig = {\n type: 'next' | 'rewrite' | 'redirect';\n responsePath?: string;\n originalUrl: NextURL;\n userLocale: string;\n clearResetCookie: boolean;\n headerList: Headers;\n localeRouting: boolean;\n localeRoutingEnabledCookieName: string;\n resetLocaleCookieName: string;\n localeHeaderName: string;\n};\n\nfunction applyBasePath(responseUrl: URL, originalUrl: NextURL) {\n const { basePath } = originalUrl;\n if (!basePath || responseUrl.origin !== originalUrl.origin) {\n return;\n }\n // Middleware targets are app-relative, even when a route repeats the base path.\n // Preserve the request's slash style when targeting the app root.\n responseUrl.pathname =\n responseUrl.pathname === '/'\n ? applyTrailingSlash(new URL(originalUrl).pathname, basePath)\n : `${basePath}${responseUrl.pathname}`;\n}\n\n/** Creates a middleware response and attaches GT routing state. */\nexport function getResponse({\n type,\n originalUrl,\n responsePath = originalUrl.pathname,\n userLocale,\n clearResetCookie,\n headerList,\n localeRouting,\n localeRoutingEnabledCookieName,\n resetLocaleCookieName,\n localeHeaderName,\n}: ResponseConfig): NextResponse<unknown> {\n // Get Response\n let response;\n if (type === 'next') {\n response = NextResponse.next({\n request: {\n headers: headerList,\n },\n });\n } else {\n // Assign the pathname to preserve the request origin: resolving a path\n // starting with // or /\\ as a URL can turn it into an external destination.\n const responseUrl = new URL(originalUrl);\n responseUrl.pathname = responsePath;\n applyBasePath(responseUrl, originalUrl);\n responseUrl.search = originalUrl.search;\n response =\n type === 'rewrite'\n ? NextResponse.rewrite(responseUrl, {\n request: {\n headers: headerList,\n },\n })\n : NextResponse.redirect(responseUrl);\n }\n\n // Set Headers & Cookies\n response.headers.set(localeHeaderName, userLocale);\n response.cookies.set(\n localeRoutingEnabledCookieName,\n localeRouting.toString()\n );\n // Clear the setLocale reset cookie once it has been processed. The locale\n // cookie must be kept: the client re-reads it on every render, and deleting\n // it here races with concurrent prefetch responses after a locale switch,\n // dropping client components back to the browser's default locale.\n if (clearResetCookie && type !== 'redirect') {\n response.cookies.delete(resetLocaleCookieName);\n }\n return response;\n}\n\n/**\n * Extracts the locale from the given pathname.\n */\nexport function extractLocale(pathname: string): string | null {\n const matches = pathname.match(/^\\/([^/]+)(?:\\/|$)/);\n return matches ? matches[1] : null;\n}\n\n/**\n * Extracts dynamic parameters from a path based on a shared path pattern.\n */\nexport function extractDynamicParams(\n templatePath: string,\n path: string\n): string[] {\n if (!templatePath.includes('[')) return [];\n\n const params: string[] = [];\n const pathSegments = stripTrailingSlashes(path).split('/');\n const sharedSegments = templatePath.split('/');\n\n sharedSegments.forEach((segment, index) => {\n const segmentType = getDynamicSegmentType(segment);\n if (segmentType === 'catch-all' || segmentType === 'optional-catch-all') {\n params.push(pathSegments.slice(index).join('/'));\n } else if (segmentType === 'dynamic') {\n params.push(pathSegments[index]);\n }\n });\n\n return params;\n}\n\n/**\n * Replaces dynamic segments in a path with their actual values.\n */\nexport function replaceDynamicSegments(\n path: string,\n templatePath: string,\n sourceTemplatePath = templatePath\n): string {\n if (!templatePath.includes('[')) {\n return applyTrailingSlash(path, templatePath);\n }\n\n const params = extractDynamicParams(sourceTemplatePath, path);\n let paramIndex = 0;\n const resultSegments: string[] = [];\n\n for (const segment of templatePath.split('/')) {\n const segmentType = getDynamicSegmentType(segment);\n if (!segmentType) {\n resultSegments.push(segment);\n continue;\n }\n\n const param = params[paramIndex++];\n if (segmentType === 'optional-catch-all' && !param) continue;\n if (!param) {\n resultSegments.push(segment);\n continue;\n }\n if (segmentType === 'catch-all' || segmentType === 'optional-catch-all') {\n resultSegments.push(...param.split('/'));\n } else {\n resultSegments.push(param);\n }\n }\n\n return applyTrailingSlash(path, resultSegments.join('/') || '/');\n}\n\n/**\n * Gets the full localized path given a shared path and locale.\n */\nexport function getLocalizedPath(\n sharedPath: string,\n locale: string,\n pathConfig: PathConfig\n): string | undefined {\n const localizedPath = pathConfig[sharedPath];\n let path: string | undefined;\n\n if (typeof localizedPath === 'string') {\n path = `/${locale}${localizedPath}`;\n } else if (typeof localizedPath === 'object') {\n path = localizedPath[locale]\n ? `/${locale}${localizedPath[locale]}`\n : `/${locale}${sharedPath}`;\n }\n\n return path;\n}\n\n/**\n * Checks whether a pathname matches an unprefixed default-locale path.\n */\nfunction inDefaultLocalePaths(\n pathname: string,\n defaultLocalePaths: PathMatcher\n): boolean {\n return (\n getSharedPath(pathname, defaultLocalePaths, undefined)?.sharedPath !==\n undefined\n );\n}\n\n/**\n * Resolves the request locale from its pathname, cookies, and headers.\n */\nexport function getLocaleFromRequest(\n req: NextRequest,\n defaultLocale: string,\n approvedLocales: string[],\n localeRouting: boolean,\n gtServicesEnabled: boolean,\n prefixDefaultLocale: boolean,\n defaultLocalePaths: PathMatcher,\n referrerLocaleCookieName: string,\n localeCookieName: string,\n resetLocaleCookieName: string,\n gt: GTRuntime\n): {\n userLocale: string;\n pathnameLocale: string | undefined;\n unstandardizedPathnameLocale: string | null | undefined;\n clearResetCookie: boolean;\n} {\n const headerList = new Headers(req.headers);\n const candidates: string[] = [];\n let clearResetCookie = false;\n const { pathname } = req.nextUrl;\n\n // Check pathname locales\n let pathnameLocale, unstandardizedPathnameLocale;\n if (localeRouting) {\n unstandardizedPathnameLocale = extractLocale(pathname);\n const extractedLocale = gtServicesEnabled\n ? standardizeLocale(unstandardizedPathnameLocale || '')\n : unstandardizedPathnameLocale;\n\n if (\n extractedLocale &&\n gt.isValidLocale(extractedLocale) &&\n gt.determineLocale([extractedLocale], approvedLocales)\n ) {\n const determinedLocale = gt.determineLocale(\n [extractedLocale],\n approvedLocales\n );\n if (determinedLocale) {\n pathnameLocale = gt.resolveAliasLocale(determinedLocale);\n candidates.push(pathnameLocale);\n }\n }\n }\n\n // Check pathname for a customized unprefixed default locale path (e.g. /en-about , /en-dashboard/1/en-custom)\n if (\n localeRouting &&\n !prefixDefaultLocale &&\n !pathnameLocale &&\n inDefaultLocalePaths(pathname, defaultLocalePaths)\n ) {\n candidates.push(defaultLocale); // will override other candidates\n }\n\n // Check cookie locale\n const cookieLocale = req.cookies.get(localeCookieName);\n if (cookieLocale?.value && gt.isValidLocale(cookieLocale?.value)) {\n const resetCookie = req.cookies.get(resetLocaleCookieName);\n if (resetCookie?.value) {\n // Add this back in when we support custom getLocale\n // addedCustomLocale\n // ? candidates.splice(1, 0, cookieLocale.value)\n // : candidates.unshift(cookieLocale.value);\n candidates.unshift(cookieLocale.value);\n clearResetCookie = true;\n } else {\n candidates.push(cookieLocale.value);\n }\n }\n\n // Check referrer locale\n const referrerLocaleCookie = req.cookies.get(referrerLocaleCookieName);\n if (\n referrerLocaleCookie?.value &&\n gt.isValidLocale(referrerLocaleCookie.value) &&\n !clearResetCookie\n ) {\n const referrerLocale = referrerLocaleCookie.value;\n if (gt.determineLocale([referrerLocale], approvedLocales)) {\n candidates.push(referrerLocale);\n }\n }\n\n // Get locales from accept-language header\n if (process.env._GENERALTRANSLATION_IGNORE_BROWSER_LOCALES === 'false') {\n candidates.push(...parseAcceptLanguage(headerList.get('accept-language')));\n }\n\n // Get default locale\n candidates.push(defaultLocale);\n\n // determine userLocale\n const unstandardizedUserLocale =\n gt.determineLocale(\n candidates.filter((locale) => gt.isValidLocale(locale)),\n approvedLocales\n ) || defaultLocale;\n const userLocale = gtServicesEnabled\n ? standardizeLocale(unstandardizedUserLocale)\n : unstandardizedUserLocale;\n\n return {\n userLocale,\n pathnameLocale,\n unstandardizedPathnameLocale,\n clearResetCookie,\n };\n}\n"],"mappings":";;;;;;;AAqCA,SAAS,cAAc,aAAkB,aAAsB;CAC7D,MAAM,EAAE,aAAa;AACrB,KAAI,CAAC,YAAY,YAAY,WAAW,YAAY,OAClD;AAIF,aAAY,WACV,YAAY,aAAa,MACrB,mBAAmB,IAAI,IAAI,YAAY,CAAC,UAAU,SAAS,GAC3D,GAAG,WAAW,YAAY;;;AAIlC,SAAgB,YAAY,EAC1B,MACA,aACA,eAAe,YAAY,UAC3B,YACA,kBACA,YACA,eACA,gCACA,uBACA,oBACwC;CAExC,IAAI;AACJ,KAAI,SAAS,OACX,YAAW,aAAa,KAAK,EAC3B,SAAS,EACP,SAAS,YACV,EACF,CAAC;MACG;EAGL,MAAM,cAAc,IAAI,IAAI,YAAY;AACxC,cAAY,WAAW;AACvB,gBAAc,aAAa,YAAY;AACvC,cAAY,SAAS,YAAY;AACjC,aACE,SAAS,YACL,aAAa,QAAQ,aAAa,EAChC,SAAS,EACP,SAAS,YACV,EACF,CAAC,GACF,aAAa,SAAS,YAAY;;AAI1C,UAAS,QAAQ,IAAI,kBAAkB,WAAW;AAClD,UAAS,QAAQ,IACf,gCACA,cAAc,UAAU,CACzB;AAKD,KAAI,oBAAoB,SAAS,WAC/B,UAAS,QAAQ,OAAO,sBAAsB;AAEhD,QAAO;;;;;AAMT,SAAgB,cAAc,UAAiC;CAC7D,MAAM,UAAU,SAAS,MAAM,qBAAqB;AACpD,QAAO,UAAU,QAAQ,KAAK;;;;;AAMhC,SAAgB,qBACd,cACA,MACU;AACV,KAAI,CAAC,aAAa,SAAS,IAAI,CAAE,QAAO,EAAE;CAE1C,MAAM,SAAmB,EAAE;CAC3B,MAAM,eAAe,qBAAqB,KAAK,C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MAAM,2BACJ,GAAG,gBACD,WAAW,QAAQ,WAAW,GAAG,cAAc,OAAO,CAAC,EACvD,gBACD,IAAI;AAKP,QAAO;EACL,YALiB,oBACf,kBAAkB,yBAAyB,GAC3C;EAIF;EACA;EACA;EACD"}
|
|
1
|
+
{"version":3,"file":"utils.mjs","names":[],"sources":["../../src/middleware-dir/utils.ts"],"sourcesContent":["import { NextRequest, NextResponse } from 'next/server';\nimport { GTRuntime } from 'generaltranslation/runtime';\nimport { NextURL } from 'next/dist/server/web/next-url';\nimport { parseAcceptLanguage } from 'gt-i18n/internal';\nimport {\n createPathMatcher,\n createPathToSharedPathMap,\n getDynamicSegmentType,\n normalizePathname,\n type PathConfig,\n type PathMatcher,\n} from './createPathMatcher';\nimport { getSharedPath } from './matchPath';\nimport { applyTrailingSlash, stripTrailingSlashes } from './pathname';\n\nexport {\n createPathMatcher,\n createPathToSharedPathMap,\n getSharedPath,\n normalizePathname,\n};\nexport type { PathConfig, PathMatcher };\n\nexport type ResponseConfig = {\n type: 'next' | 'rewrite' | 'redirect';\n responsePath?: string;\n originalUrl: NextURL;\n userLocale: string;\n clearResetCookie: boolean;\n headerList: Headers;\n localeRouting: boolean;\n localeRoutingEnabledCookieName: string;\n resetLocaleCookieName: string;\n localeHeaderName: string;\n};\n\nfunction applyBasePath(responseUrl: URL, originalUrl: NextURL) {\n const { basePath } = originalUrl;\n if (!basePath || responseUrl.origin !== originalUrl.origin) {\n return;\n }\n // Middleware targets are app-relative, even when a route repeats the base path.\n // Preserve the request's slash style when targeting the app root.\n responseUrl.pathname =\n responseUrl.pathname === '/'\n ? applyTrailingSlash(new URL(originalUrl).pathname, basePath)\n : `${basePath}${responseUrl.pathname}`;\n}\n\n/** Creates a middleware response and attaches GT routing state. */\nexport function getResponse({\n type,\n originalUrl,\n responsePath = originalUrl.pathname,\n userLocale,\n clearResetCookie,\n headerList,\n localeRouting,\n localeRoutingEnabledCookieName,\n resetLocaleCookieName,\n localeHeaderName,\n}: ResponseConfig): NextResponse<unknown> {\n // Get Response\n let response;\n if (type === 'next') {\n response = NextResponse.next({\n request: {\n headers: headerList,\n },\n });\n } else {\n // Assign the pathname to preserve the request origin: resolving a path\n // starting with // or /\\ as a URL can turn it into an external destination.\n const responseUrl = new URL(originalUrl);\n responseUrl.pathname = responsePath;\n applyBasePath(responseUrl, originalUrl);\n responseUrl.search = originalUrl.search;\n response =\n type === 'rewrite'\n ? NextResponse.rewrite(responseUrl, {\n request: {\n headers: headerList,\n },\n })\n : NextResponse.redirect(responseUrl);\n }\n\n // Set Headers & Cookies\n response.headers.set(localeHeaderName, userLocale);\n response.cookies.set(\n localeRoutingEnabledCookieName,\n localeRouting.toString()\n );\n // Clear the setLocale reset cookie once it has been processed. The locale\n // cookie must be kept: the client re-reads it on every render, and deleting\n // it here races with concurrent prefetch responses after a locale switch,\n // dropping client components back to the browser's default locale.\n if (clearResetCookie && type !== 'redirect') {\n response.cookies.delete(resetLocaleCookieName);\n }\n return response;\n}\n\n/**\n * Extracts the locale from the given pathname.\n */\nexport function extractLocale(pathname: string): string | null {\n const matches = pathname.match(/^\\/([^/]+)(?:\\/|$)/);\n return matches ? matches[1] : null;\n}\n\n/**\n * Extracts dynamic parameters from a path based on a shared path pattern.\n */\nexport function extractDynamicParams(\n templatePath: string,\n path: string\n): string[] {\n if (!templatePath.includes('[')) return [];\n\n const params: string[] = [];\n const pathSegments = stripTrailingSlashes(path).split('/');\n const sharedSegments = templatePath.split('/');\n\n sharedSegments.forEach((segment, index) => {\n const segmentType = getDynamicSegmentType(segment);\n if (segmentType === 'catch-all' || segmentType === 'optional-catch-all') {\n params.push(pathSegments.slice(index).join('/'));\n } else if (segmentType === 'dynamic') {\n params.push(pathSegments[index]);\n }\n });\n\n return params;\n}\n\n/**\n * Replaces dynamic segments in a path with their actual values.\n */\nexport function replaceDynamicSegments(\n path: string,\n templatePath: string,\n sourceTemplatePath = templatePath\n): string {\n if (!templatePath.includes('[')) {\n return applyTrailingSlash(path, templatePath);\n }\n\n const params = extractDynamicParams(sourceTemplatePath, path);\n let paramIndex = 0;\n const resultSegments: string[] = [];\n\n for (const segment of templatePath.split('/')) {\n const segmentType = getDynamicSegmentType(segment);\n if (!segmentType) {\n resultSegments.push(segment);\n continue;\n }\n\n const param = params[paramIndex++];\n if (segmentType === 'optional-catch-all' && !param) continue;\n if (!param) {\n resultSegments.push(segment);\n continue;\n }\n if (segmentType === 'catch-all' || segmentType === 'optional-catch-all') {\n resultSegments.push(...param.split('/'));\n } else {\n resultSegments.push(param);\n }\n }\n\n return applyTrailingSlash(path, resultSegments.join('/') || '/');\n}\n\n/**\n * Gets the full localized path given a shared path and locale.\n */\nexport function getLocalizedPath(\n sharedPath: string,\n locale: string,\n pathConfig: PathConfig\n): string | undefined {\n const localizedPath = pathConfig[sharedPath];\n let path: string | undefined;\n\n if (typeof localizedPath === 'string') {\n path = `/${locale}${localizedPath}`;\n } else if (typeof localizedPath === 'object') {\n path = localizedPath[locale]\n ? `/${locale}${localizedPath[locale]}`\n : `/${locale}${sharedPath}`;\n }\n\n return path;\n}\n\n/**\n * Checks whether a pathname matches an unprefixed default-locale path.\n */\nfunction inDefaultLocalePaths(\n pathname: string,\n defaultLocalePaths: PathMatcher\n): boolean {\n return (\n getSharedPath(pathname, defaultLocalePaths, undefined)?.sharedPath !==\n undefined\n );\n}\n\n/**\n * Resolves the request locale from its pathname, cookies, and headers.\n */\nexport function getLocaleFromRequest(\n req: NextRequest,\n defaultLocale: string,\n approvedLocales: string[],\n localeRouting: boolean,\n prefixDefaultLocale: boolean,\n defaultLocalePaths: PathMatcher,\n referrerLocaleCookieName: string,\n localeCookieName: string,\n resetLocaleCookieName: string,\n gt: GTRuntime\n): {\n userLocale: string;\n pathnameLocale: string | undefined;\n unstandardizedPathnameLocale: string | null | undefined;\n clearResetCookie: boolean;\n} {\n const headerList = new Headers(req.headers);\n const candidates: string[] = [];\n let clearResetCookie = false;\n const { pathname } = req.nextUrl;\n\n // Check pathname locales\n let pathnameLocale, unstandardizedPathnameLocale;\n if (localeRouting) {\n unstandardizedPathnameLocale = extractLocale(pathname);\n if (\n unstandardizedPathnameLocale &&\n gt.isValidLocale(unstandardizedPathnameLocale)\n ) {\n pathnameLocale = gt.determineLocale(\n unstandardizedPathnameLocale,\n approvedLocales\n );\n if (pathnameLocale) candidates.push(pathnameLocale);\n }\n }\n\n // Check pathname for a customized unprefixed default locale path (e.g. /en-about , /en-dashboard/1/en-custom)\n if (\n localeRouting &&\n !prefixDefaultLocale &&\n !pathnameLocale &&\n inDefaultLocalePaths(pathname, defaultLocalePaths)\n ) {\n candidates.push(defaultLocale); // will override other candidates\n }\n\n // Check cookie locale\n const cookieLocale = req.cookies.get(localeCookieName);\n if (cookieLocale?.value && gt.isValidLocale(cookieLocale?.value)) {\n const resetCookie = req.cookies.get(resetLocaleCookieName);\n if (resetCookie?.value) {\n // Add this back in when we support custom getLocale\n // addedCustomLocale\n // ? candidates.splice(1, 0, cookieLocale.value)\n // : candidates.unshift(cookieLocale.value);\n candidates.unshift(cookieLocale.value);\n clearResetCookie = true;\n } else {\n candidates.push(cookieLocale.value);\n }\n }\n\n // Check referrer locale\n const referrerLocaleCookie = req.cookies.get(referrerLocaleCookieName);\n if (\n referrerLocaleCookie?.value &&\n gt.isValidLocale(referrerLocaleCookie.value) &&\n !clearResetCookie\n ) {\n const referrerLocale = referrerLocaleCookie.value;\n if (gt.determineLocale([referrerLocale], approvedLocales)) {\n candidates.push(referrerLocale);\n }\n }\n\n // Get locales from accept-language header\n if (process.env._GENERALTRANSLATION_IGNORE_BROWSER_LOCALES === 'false') {\n candidates.push(...parseAcceptLanguage(headerList.get('accept-language')));\n }\n\n // Get default locale\n candidates.push(defaultLocale);\n\n // determine userLocale\n const userLocale =\n gt.determineLocale(\n candidates.filter((locale) => gt.isValidLocale(locale)),\n approvedLocales\n ) || defaultLocale;\n\n return {\n userLocale,\n pathnameLocale,\n unstandardizedPathnameLocale,\n clearResetCookie,\n };\n}\n"],"mappings":";;;;;;AAoCA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gB;AACpB,KAAI,eAAe;AACjB,iCAA+B,cAAc,SAAS;AACtD,MACE,gCACA,GAAG,cAAc,6BAA6B,EAC9C;AACA,oBAAiB,GAAG,gBAClB,8BACA,gBACD;AACD,OAAI,eAAgB,YAAW,KAAK,eAAe;;;AAKvD,KACE,iBACA,CAAC,uBACD,CAAC,kBACD,qBAAqB,UAAU,mBAAmB,CAElD,YAAW,KAAK,cAAc;CAIhC,MAAM,eAAe,IAAI,QAAQ,IAAI,iBAAiB;AACtD,KAAI,cAAc,SAAS,GAAG,cAAc,cAAc,MAAM,CAE9D,KADoB,IAAI,QAAQ,IAAI,sBACrB,EAAE,OAAO;AAKtB,aAAW,QAAQ,aAAa,MAAM;AACtC,qBAAmB;OAEnB,YAAW,KAAK,aAAa,MAAM;CAKvC,MAAM,uBAAuB,IAAI,QAAQ,IAAI,yBAAyB;AACtE,KACE,sBAAsB,SACtB,GAAG,cAAc,qBAAqB,MAAM,IAC5C,CAAC,kBACD;EACA,MAAM,iBAAiB,qBAAqB;AAC5C,MAAI,GAAG,gBAAgB,CAAC,eAAe,EAAE,gBAAgB,CACvD,YAAW,KAAK,eAAe;;AAKnC,KAAI,QAAQ,IAAI,+CAA+C,QAC7D,YAAW,KAAK,GAAG,oBAAoB,WAAW,IAAI,kBAAkB,CAAC,CAAC;AAI5E,YAAW,KAAK,cAAc;AAS9B,QAAO;EACL,YANA,GAAG,gBACD,WAAW,QAAQ,WAAW,GAAG,cAAc,OAAO,CAAC,EACvD,gBACD,IAAI;EAIL;EACA;EACA;EACD"}
|
package/dist/middleware.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export { createNextMiddleware } from './middleware-dir/createNextMiddleware';
|
|
2
|
-
export type { RouteOverrides } from './middleware-dir/createNextMiddleware';
|
|
2
|
+
export type { RouteOverrides, LocaleRoutes, } from './middleware-dir/createNextMiddleware';
|
|
3
3
|
//# sourceMappingURL=middleware.d.ts.map
|
package/dist/middleware.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../src/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAC7E,YAAY,
|
|
1
|
+
{"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../src/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAC7E,YAAY,EACV,cAAc,EACd,YAAY,GACb,MAAM,uCAAuC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/plugin/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,oBAAoB,WAAW,CAAC;AAE7C,eAAO,MAAM,kBAAkB,WAAW,CAAC;AAG3C,eAAO,MAAM,oBAAoB;;;;;CAKhC,CAAC;AAEF,eAAO,MAAM,2BAA2B,WAAW,CAAC"}
|
|
1
|
+
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/plugin/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,oBAAoB,WAAW,CAAC;AAE7C,eAAO,MAAM,kBAAkB,WAAW,CAAC;AAG3C,eAAO,MAAM,oBAAoB;;;;;CAKhC,CAAC;AAEF,eAAO,MAAM,2BAA2B,WAAW,CAAC;AAEpD,eAAO,MAAM,sBAAsB,WAAW,CAAC"}
|
package/dist/plugin/constants.js
CHANGED
|
@@ -9,8 +9,10 @@ const ROOT_PARAM_STABILITY = {
|
|
|
9
9
|
stable: "16.3.0"
|
|
10
10
|
};
|
|
11
11
|
const STABLE_TURBO_CONFIG_VERSION = "15.3.0";
|
|
12
|
+
const LOCALE_REFRESH_SUPPORT = "16.1.0";
|
|
12
13
|
//#endregion
|
|
13
14
|
exports.BABEL_PLUGIN_SUPPORT = BABEL_PLUGIN_SUPPORT;
|
|
15
|
+
exports.LOCALE_REFRESH_SUPPORT = LOCALE_REFRESH_SUPPORT;
|
|
14
16
|
exports.ROOT_PARAM_STABILITY = ROOT_PARAM_STABILITY;
|
|
15
17
|
exports.STABLE_TURBO_CONFIG_VERSION = STABLE_TURBO_CONFIG_VERSION;
|
|
16
18
|
exports.SWC_PLUGIN_SUPPORT = SWC_PLUGIN_SUPPORT;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","names":[],"sources":["../../src/plugin/constants.ts"],"sourcesContent":["export const BABEL_PLUGIN_SUPPORT = '17.0.0';\n\nexport const SWC_PLUGIN_SUPPORT = '16.1.0';\n\n// Minimum Next versions for feature-specific plugin behavior.\nexport const ROOT_PARAM_STABILITY = {\n unsupported: '0.0.0',\n unstable: '15.2.0',\n experimental: '15.5.0',\n stable: '16.3.0',\n};\n\nexport const STABLE_TURBO_CONFIG_VERSION = '15.3.0';\n"],"mappings":";;AAAA,MAAa,uBAAuB;AAEpC,MAAa,qBAAqB;AAGlC,MAAa,uBAAuB;CAClC,aAAa;CACb,UAAU;CACV,cAAc;CACd,QAAQ;CACT;AAED,MAAa,8BAA8B"}
|
|
1
|
+
{"version":3,"file":"constants.js","names":[],"sources":["../../src/plugin/constants.ts"],"sourcesContent":["export const BABEL_PLUGIN_SUPPORT = '17.0.0';\n\nexport const SWC_PLUGIN_SUPPORT = '16.1.0';\n\n// Minimum Next versions for feature-specific plugin behavior.\nexport const ROOT_PARAM_STABILITY = {\n unsupported: '0.0.0',\n unstable: '15.2.0',\n experimental: '15.5.0',\n stable: '16.3.0',\n};\n\nexport const STABLE_TURBO_CONFIG_VERSION = '15.3.0';\n\nexport const LOCALE_REFRESH_SUPPORT = '16.1.0';\n"],"mappings":";;AAAA,MAAa,uBAAuB;AAEpC,MAAa,qBAAqB;AAGlC,MAAa,uBAAuB;CAClC,aAAa;CACb,UAAU;CACV,cAAc;CACd,QAAQ;CACT;AAED,MAAa,8BAA8B;AAE3C,MAAa,yBAAyB"}
|
|
@@ -8,7 +8,8 @@ const ROOT_PARAM_STABILITY = {
|
|
|
8
8
|
stable: "16.3.0"
|
|
9
9
|
};
|
|
10
10
|
const STABLE_TURBO_CONFIG_VERSION = "15.3.0";
|
|
11
|
+
const LOCALE_REFRESH_SUPPORT = "16.1.0";
|
|
11
12
|
//#endregion
|
|
12
|
-
export { BABEL_PLUGIN_SUPPORT, ROOT_PARAM_STABILITY, STABLE_TURBO_CONFIG_VERSION, SWC_PLUGIN_SUPPORT };
|
|
13
|
+
export { BABEL_PLUGIN_SUPPORT, LOCALE_REFRESH_SUPPORT, ROOT_PARAM_STABILITY, STABLE_TURBO_CONFIG_VERSION, SWC_PLUGIN_SUPPORT };
|
|
13
14
|
|
|
14
15
|
//# sourceMappingURL=constants.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.mjs","names":[],"sources":["../../src/plugin/constants.ts"],"sourcesContent":["export const BABEL_PLUGIN_SUPPORT = '17.0.0';\n\nexport const SWC_PLUGIN_SUPPORT = '16.1.0';\n\n// Minimum Next versions for feature-specific plugin behavior.\nexport const ROOT_PARAM_STABILITY = {\n unsupported: '0.0.0',\n unstable: '15.2.0',\n experimental: '15.5.0',\n stable: '16.3.0',\n};\n\nexport const STABLE_TURBO_CONFIG_VERSION = '15.3.0';\n"],"mappings":";AAAA,MAAa,uBAAuB;AAEpC,MAAa,qBAAqB;AAGlC,MAAa,uBAAuB;CAClC,aAAa;CACb,UAAU;CACV,cAAc;CACd,QAAQ;CACT;AAED,MAAa,8BAA8B"}
|
|
1
|
+
{"version":3,"file":"constants.mjs","names":[],"sources":["../../src/plugin/constants.ts"],"sourcesContent":["export const BABEL_PLUGIN_SUPPORT = '17.0.0';\n\nexport const SWC_PLUGIN_SUPPORT = '16.1.0';\n\n// Minimum Next versions for feature-specific plugin behavior.\nexport const ROOT_PARAM_STABILITY = {\n unsupported: '0.0.0',\n unstable: '15.2.0',\n experimental: '15.5.0',\n stable: '16.3.0',\n};\n\nexport const STABLE_TURBO_CONFIG_VERSION = '15.3.0';\n\nexport const LOCALE_REFRESH_SUPPORT = '16.1.0';\n"],"mappings":";AAAA,MAAa,uBAAuB;AAEpC,MAAa,qBAAqB;AAGlC,MAAa,uBAAuB;CAClC,aAAa;CACb,UAAU;CACV,cAAc;CACd,QAAQ;CACT;AAED,MAAa,8BAA8B;AAE3C,MAAa,yBAAyB"}
|
|
@@ -14,4 +14,5 @@ export declare function getRootParamStability(nextVersion: string): RootParam;
|
|
|
14
14
|
export declare const rootParamStability: RootParam;
|
|
15
15
|
export declare const swcPluginCompatible: boolean;
|
|
16
16
|
export declare const babelPluginCompatible: boolean;
|
|
17
|
+
export declare const localeRefreshSupported: boolean;
|
|
17
18
|
//# sourceMappingURL=getStableNextVersionInfo.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getStableNextVersionInfo.d.ts","sourceRoot":"","sources":["../../src/plugin/getStableNextVersionInfo.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"getStableNextVersionInfo.d.ts","sourceRoot":"","sources":["../../src/plugin/getStableNextVersionInfo.ts"],"names":[],"mappings":"AA0EA;;;GAGG;AACH,eAAO,MAAM,iBAAiB,SAG7B,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG,aAAa,GAAG,UAAU,GAAG,cAAc,GAAG,QAAQ,CAAC;AAE/E;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,CAepE;AAED,eAAO,MAAM,kBAAkB,WAA0C,CAAC;AAE1E,eAAO,MAAM,mBAAmB,SAG/B,CAAC;AAGF,eAAO,MAAM,qBAAqB,SAGjC,CAAC;AAIF,eAAO,MAAM,sBAAsB,SAGlC,CAAC"}
|
|
@@ -70,9 +70,11 @@ function getRootParamStability(nextVersion) {
|
|
|
70
70
|
const rootParamStability = getRootParamStability(getNextVersion());
|
|
71
71
|
const swcPluginCompatible = comparePackageVersion(getNextVersion(), require_plugin_constants.SWC_PLUGIN_SUPPORT);
|
|
72
72
|
const babelPluginCompatible = comparePackageVersion(getReactVersion(), require_plugin_constants.BABEL_PLUGIN_SUPPORT);
|
|
73
|
+
const localeRefreshSupported = comparePackageVersion(getNextVersion(), require_plugin_constants.LOCALE_REFRESH_SUPPORT);
|
|
73
74
|
//#endregion
|
|
74
75
|
exports.babelPluginCompatible = babelPluginCompatible;
|
|
75
76
|
exports.getRootParamStability = getRootParamStability;
|
|
77
|
+
exports.localeRefreshSupported = localeRefreshSupported;
|
|
76
78
|
exports.rootParamStability = rootParamStability;
|
|
77
79
|
exports.swcPluginCompatible = swcPluginCompatible;
|
|
78
80
|
exports.turboConfigStable = turboConfigStable;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getStableNextVersionInfo.js","names":["createUnresolvedNextVersionError","createUnresolvedReactVersionError","STABLE_TURBO_CONFIG_VERSION","ROOT_PARAM_STABILITY","SWC_PLUGIN_SUPPORT","BABEL_PLUGIN_SUPPORT"],"sources":["../../src/plugin/getStableNextVersionInfo.ts"],"sourcesContent":["import {\n createUnresolvedNextVersionError,\n createUnresolvedReactVersionError,\n} from '../errors/createErrors';\nimport {\n BABEL_PLUGIN_SUPPORT,\n ROOT_PARAM_STABILITY,\n STABLE_TURBO_CONFIG_VERSION,\n SWC_PLUGIN_SUPPORT,\n} from './constants';\n\n/**\n * Get the next version of the package.\n */\nfunction getPackageVersion(packageName: string): string {\n const packageJsonPath = `${packageName}/package.json`;\n\n try {\n const resolvedPackageJsonPath = require.resolve(packageJsonPath, {\n paths: [process.cwd()],\n });\n return require(resolvedPackageJsonPath).version;\n } catch (_error) {\n return require(packageJsonPath).version;\n }\n}\n\nfunction getNextVersion(): string {\n try {\n return getPackageVersion('next');\n } catch (error) {\n throw new Error(createUnresolvedNextVersionError(error as Error));\n }\n}\n\n/**\n * Get the react version of the package.\n * I am wary of dynamic imports\n */\nfunction getReactVersion(): string {\n try {\n return getPackageVersion('react');\n } catch (error) {\n throw new Error(createUnresolvedReactVersionError(error as Error));\n }\n}\n\n/**\n * Compare two package versions.\n *\n * @param a - The first version.\n * @param b - The second version.\n * @returns True if a is greater than or equal to b, false otherwise.\n */\nfunction comparePackageVersion(a: string, b: string): boolean {\n const aParts = a.split('.');\n const bParts = b.split('.');\n\n for (let i = 0; i < aParts.length; i++) {\n const aPart = Number(aParts[i]) || 0;\n const bPart = Number(bParts[i]) || 0;\n\n if (aPart > bPart) {\n return true;\n } else if (aPart < bPart) {\n return false;\n }\n }\n\n // If all parts are equal, return true\n return true;\n}\n\n/**\n * Starting at version next@15.3.0 experimental field in turbo config was deprecated.\n * Shout out to next-intl: https://github.com/amannn/next-intl/pull/1850\n */\nexport const turboConfigStable = comparePackageVersion(\n getNextVersion(),\n STABLE_TURBO_CONFIG_VERSION\n);\n\nexport type RootParam = 'unsupported' | 'unstable' | 'experimental' | 'stable';\n\n/**\n * Classify the stability of root params for a Next.js version.\n *\n * @param nextVersion - The Next.js version to classify.\n * @returns The root params stability tier for the supplied version.\n */\nexport function getRootParamStability(nextVersion: string): RootParam {\n // Check stable before experimental because each threshold is a lower bound.\n if (comparePackageVersion(nextVersion, ROOT_PARAM_STABILITY.stable)) {\n return 'stable';\n }\n\n if (comparePackageVersion(nextVersion, ROOT_PARAM_STABILITY.experimental)) {\n return 'experimental';\n }\n\n if (comparePackageVersion(nextVersion, ROOT_PARAM_STABILITY.unstable)) {\n return 'unstable';\n }\n\n return 'unsupported';\n}\n\nexport const rootParamStability = getRootParamStability(getNextVersion());\n\nexport const swcPluginCompatible = comparePackageVersion(\n getNextVersion(),\n SWC_PLUGIN_SUPPORT\n);\n\n// disable babel plugin if using react <= 16\nexport const babelPluginCompatible = comparePackageVersion(\n getReactVersion(),\n BABEL_PLUGIN_SUPPORT\n);\n"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"getStableNextVersionInfo.js","names":["createUnresolvedNextVersionError","createUnresolvedReactVersionError","STABLE_TURBO_CONFIG_VERSION","ROOT_PARAM_STABILITY","SWC_PLUGIN_SUPPORT","BABEL_PLUGIN_SUPPORT","LOCALE_REFRESH_SUPPORT"],"sources":["../../src/plugin/getStableNextVersionInfo.ts"],"sourcesContent":["import {\n createUnresolvedNextVersionError,\n createUnresolvedReactVersionError,\n} from '../errors/createErrors';\nimport {\n BABEL_PLUGIN_SUPPORT,\n LOCALE_REFRESH_SUPPORT,\n ROOT_PARAM_STABILITY,\n STABLE_TURBO_CONFIG_VERSION,\n SWC_PLUGIN_SUPPORT,\n} from './constants';\n\n/**\n * Get the next version of the package.\n */\nfunction getPackageVersion(packageName: string): string {\n const packageJsonPath = `${packageName}/package.json`;\n\n try {\n const resolvedPackageJsonPath = require.resolve(packageJsonPath, {\n paths: [process.cwd()],\n });\n return require(resolvedPackageJsonPath).version;\n } catch (_error) {\n return require(packageJsonPath).version;\n }\n}\n\nfunction getNextVersion(): string {\n try {\n return getPackageVersion('next');\n } catch (error) {\n throw new Error(createUnresolvedNextVersionError(error as Error));\n }\n}\n\n/**\n * Get the react version of the package.\n * I am wary of dynamic imports\n */\nfunction getReactVersion(): string {\n try {\n return getPackageVersion('react');\n } catch (error) {\n throw new Error(createUnresolvedReactVersionError(error as Error));\n }\n}\n\n/**\n * Compare two package versions.\n *\n * @param a - The first version.\n * @param b - The second version.\n * @returns True if a is greater than or equal to b, false otherwise.\n */\nfunction comparePackageVersion(a: string, b: string): boolean {\n const aParts = a.split('.');\n const bParts = b.split('.');\n\n for (let i = 0; i < aParts.length; i++) {\n const aPart = Number(aParts[i]) || 0;\n const bPart = Number(bParts[i]) || 0;\n\n if (aPart > bPart) {\n return true;\n } else if (aPart < bPart) {\n return false;\n }\n }\n\n // If all parts are equal, return true\n return true;\n}\n\n/**\n * Starting at version next@15.3.0 experimental field in turbo config was deprecated.\n * Shout out to next-intl: https://github.com/amannn/next-intl/pull/1850\n */\nexport const turboConfigStable = comparePackageVersion(\n getNextVersion(),\n STABLE_TURBO_CONFIG_VERSION\n);\n\nexport type RootParam = 'unsupported' | 'unstable' | 'experimental' | 'stable';\n\n/**\n * Classify the stability of root params for a Next.js version.\n *\n * @param nextVersion - The Next.js version to classify.\n * @returns The root params stability tier for the supplied version.\n */\nexport function getRootParamStability(nextVersion: string): RootParam {\n // Check stable before experimental because each threshold is a lower bound.\n if (comparePackageVersion(nextVersion, ROOT_PARAM_STABILITY.stable)) {\n return 'stable';\n }\n\n if (comparePackageVersion(nextVersion, ROOT_PARAM_STABILITY.experimental)) {\n return 'experimental';\n }\n\n if (comparePackageVersion(nextVersion, ROOT_PARAM_STABILITY.unstable)) {\n return 'unstable';\n }\n\n return 'unsupported';\n}\n\nexport const rootParamStability = getRootParamStability(getNextVersion());\n\nexport const swcPluginCompatible = comparePackageVersion(\n getNextVersion(),\n SWC_PLUGIN_SUPPORT\n);\n\n// disable babel plugin if using react <= 16\nexport const babelPluginCompatible = comparePackageVersion(\n getReactVersion(),\n BABEL_PLUGIN_SUPPORT\n);\n\n// Older refresh reducers can retain a stale layout after middleware redirects.\n// Related refresh/redirect issue: https://github.com/vercel/next.js/issues/65970\nexport const localeRefreshSupported = comparePackageVersion(\n getNextVersion(),\n LOCALE_REFRESH_SUPPORT\n);\n"],"mappings":";;;;;;;AAeA,SAAS,kBAAkB,aAA6B;CACtD,MAAM,kBAAkB,GAAG,YAAY;AAEvC,KAAI;EACF,MAAM,0BAA0B,QAAQ,QAAQ,iBAAiB,EAC/D,OAAO,CAAC,QAAQ,KAAK,CAAC,EACvB,CAAC;AACF,SAAO,QAAQ,wBAAwB,CAAC;UACjC,QAAQ;AACf,SAAO,QAAQ,gBAAgB,CAAC;;;AAIpC,SAAS,iBAAyB;AAChC,KAAI;AACF,SAAO,kBAAkB,OAAO;UACzB,OAAO;AACd,QAAM,IAAI,MAAMA,4BAAAA,iCAAiC,MAAe,CAAC;;;;;;;AAQrE,SAAS,kBAA0B;AACjC,KAAI;AACF,SAAO,kBAAkB,QAAQ;UAC1B,OAAO;AACd,QAAM,IAAI,MAAMC,4BAAAA,kCAAkC,MAAe,CAAC;;;;;;;;;;AAWtE,SAAS,sBAAsB,GAAW,GAAoB;CAC5D,MAAM,SAAS,EAAE,MAAM,IAAI;CAC3B,MAAM,SAAS,EAAE,MAAM,IAAI;AAE3B,MAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;EACtC,MAAM,QAAQ,OAAO,OAAO,GAAG,IAAI;EACnC,MAAM,QAAQ,OAAO,OAAO,GAAG,IAAI;AAEnC,MAAI,QAAQ,MACV,QAAO;WACE,QAAQ,MACjB,QAAO;;AAKX,QAAO;;;;;;AAOT,MAAa,oBAAoB,sBAC/B,gBAAgB,EAChBC,yBAAAA,4BACD;;;;;;;AAUD,SAAgB,sBAAsB,aAAgC;AAEpE,KAAI,sBAAsB,aAAaC,yBAAAA,qBAAqB,OAAO,CACjE,QAAO;AAGT,KAAI,sBAAsB,aAAaA,yBAAAA,qBAAqB,aAAa,CACvE,QAAO;AAGT,KAAI,sBAAsB,aAAaA,yBAAAA,qBAAqB,SAAS,CACnE,QAAO;AAGT,QAAO;;AAGT,MAAa,qBAAqB,sBAAsB,gBAAgB,CAAC;AAEzE,MAAa,sBAAsB,sBACjC,gBAAgB,EAChBC,yBAAAA,mBACD;AAGD,MAAa,wBAAwB,sBACnC,iBAAiB,EACjBC,yBAAAA,qBACD;AAID,MAAa,yBAAyB,sBACpC,gBAAgB,EAChBC,yBAAAA,uBACD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BABEL_PLUGIN_SUPPORT, ROOT_PARAM_STABILITY, STABLE_TURBO_CONFIG_VERSION, SWC_PLUGIN_SUPPORT } from "./constants.mjs";
|
|
1
|
+
import { BABEL_PLUGIN_SUPPORT, LOCALE_REFRESH_SUPPORT, ROOT_PARAM_STABILITY, STABLE_TURBO_CONFIG_VERSION, SWC_PLUGIN_SUPPORT } from "./constants.mjs";
|
|
2
2
|
import { createUnresolvedNextVersionError, createUnresolvedReactVersionError } from "../errors/createErrors.mjs";
|
|
3
3
|
//#region src/plugin/getStableNextVersionInfo.ts
|
|
4
4
|
/**
|
|
@@ -69,7 +69,8 @@ function getRootParamStability(nextVersion) {
|
|
|
69
69
|
const rootParamStability = getRootParamStability(getNextVersion());
|
|
70
70
|
const swcPluginCompatible = comparePackageVersion(getNextVersion(), SWC_PLUGIN_SUPPORT);
|
|
71
71
|
const babelPluginCompatible = comparePackageVersion(getReactVersion(), BABEL_PLUGIN_SUPPORT);
|
|
72
|
+
const localeRefreshSupported = comparePackageVersion(getNextVersion(), LOCALE_REFRESH_SUPPORT);
|
|
72
73
|
//#endregion
|
|
73
|
-
export { babelPluginCompatible, getRootParamStability, rootParamStability, swcPluginCompatible, turboConfigStable };
|
|
74
|
+
export { babelPluginCompatible, getRootParamStability, localeRefreshSupported, rootParamStability, swcPluginCompatible, turboConfigStable };
|
|
74
75
|
|
|
75
76
|
//# sourceMappingURL=getStableNextVersionInfo.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getStableNextVersionInfo.mjs","names":[],"sources":["../../src/plugin/getStableNextVersionInfo.ts"],"sourcesContent":["import {\n createUnresolvedNextVersionError,\n createUnresolvedReactVersionError,\n} from '../errors/createErrors';\nimport {\n BABEL_PLUGIN_SUPPORT,\n ROOT_PARAM_STABILITY,\n STABLE_TURBO_CONFIG_VERSION,\n SWC_PLUGIN_SUPPORT,\n} from './constants';\n\n/**\n * Get the next version of the package.\n */\nfunction getPackageVersion(packageName: string): string {\n const packageJsonPath = `${packageName}/package.json`;\n\n try {\n const resolvedPackageJsonPath = require.resolve(packageJsonPath, {\n paths: [process.cwd()],\n });\n return require(resolvedPackageJsonPath).version;\n } catch (_error) {\n return require(packageJsonPath).version;\n }\n}\n\nfunction getNextVersion(): string {\n try {\n return getPackageVersion('next');\n } catch (error) {\n throw new Error(createUnresolvedNextVersionError(error as Error));\n }\n}\n\n/**\n * Get the react version of the package.\n * I am wary of dynamic imports\n */\nfunction getReactVersion(): string {\n try {\n return getPackageVersion('react');\n } catch (error) {\n throw new Error(createUnresolvedReactVersionError(error as Error));\n }\n}\n\n/**\n * Compare two package versions.\n *\n * @param a - The first version.\n * @param b - The second version.\n * @returns True if a is greater than or equal to b, false otherwise.\n */\nfunction comparePackageVersion(a: string, b: string): boolean {\n const aParts = a.split('.');\n const bParts = b.split('.');\n\n for (let i = 0; i < aParts.length; i++) {\n const aPart = Number(aParts[i]) || 0;\n const bPart = Number(bParts[i]) || 0;\n\n if (aPart > bPart) {\n return true;\n } else if (aPart < bPart) {\n return false;\n }\n }\n\n // If all parts are equal, return true\n return true;\n}\n\n/**\n * Starting at version next@15.3.0 experimental field in turbo config was deprecated.\n * Shout out to next-intl: https://github.com/amannn/next-intl/pull/1850\n */\nexport const turboConfigStable = comparePackageVersion(\n getNextVersion(),\n STABLE_TURBO_CONFIG_VERSION\n);\n\nexport type RootParam = 'unsupported' | 'unstable' | 'experimental' | 'stable';\n\n/**\n * Classify the stability of root params for a Next.js version.\n *\n * @param nextVersion - The Next.js version to classify.\n * @returns The root params stability tier for the supplied version.\n */\nexport function getRootParamStability(nextVersion: string): RootParam {\n // Check stable before experimental because each threshold is a lower bound.\n if (comparePackageVersion(nextVersion, ROOT_PARAM_STABILITY.stable)) {\n return 'stable';\n }\n\n if (comparePackageVersion(nextVersion, ROOT_PARAM_STABILITY.experimental)) {\n return 'experimental';\n }\n\n if (comparePackageVersion(nextVersion, ROOT_PARAM_STABILITY.unstable)) {\n return 'unstable';\n }\n\n return 'unsupported';\n}\n\nexport const rootParamStability = getRootParamStability(getNextVersion());\n\nexport const swcPluginCompatible = comparePackageVersion(\n getNextVersion(),\n SWC_PLUGIN_SUPPORT\n);\n\n// disable babel plugin if using react <= 16\nexport const babelPluginCompatible = comparePackageVersion(\n getReactVersion(),\n BABEL_PLUGIN_SUPPORT\n);\n"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"getStableNextVersionInfo.mjs","names":[],"sources":["../../src/plugin/getStableNextVersionInfo.ts"],"sourcesContent":["import {\n createUnresolvedNextVersionError,\n createUnresolvedReactVersionError,\n} from '../errors/createErrors';\nimport {\n BABEL_PLUGIN_SUPPORT,\n LOCALE_REFRESH_SUPPORT,\n ROOT_PARAM_STABILITY,\n STABLE_TURBO_CONFIG_VERSION,\n SWC_PLUGIN_SUPPORT,\n} from './constants';\n\n/**\n * Get the next version of the package.\n */\nfunction getPackageVersion(packageName: string): string {\n const packageJsonPath = `${packageName}/package.json`;\n\n try {\n const resolvedPackageJsonPath = require.resolve(packageJsonPath, {\n paths: [process.cwd()],\n });\n return require(resolvedPackageJsonPath).version;\n } catch (_error) {\n return require(packageJsonPath).version;\n }\n}\n\nfunction getNextVersion(): string {\n try {\n return getPackageVersion('next');\n } catch (error) {\n throw new Error(createUnresolvedNextVersionError(error as Error));\n }\n}\n\n/**\n * Get the react version of the package.\n * I am wary of dynamic imports\n */\nfunction getReactVersion(): string {\n try {\n return getPackageVersion('react');\n } catch (error) {\n throw new Error(createUnresolvedReactVersionError(error as Error));\n }\n}\n\n/**\n * Compare two package versions.\n *\n * @param a - The first version.\n * @param b - The second version.\n * @returns True if a is greater than or equal to b, false otherwise.\n */\nfunction comparePackageVersion(a: string, b: string): boolean {\n const aParts = a.split('.');\n const bParts = b.split('.');\n\n for (let i = 0; i < aParts.length; i++) {\n const aPart = Number(aParts[i]) || 0;\n const bPart = Number(bParts[i]) || 0;\n\n if (aPart > bPart) {\n return true;\n } else if (aPart < bPart) {\n return false;\n }\n }\n\n // If all parts are equal, return true\n return true;\n}\n\n/**\n * Starting at version next@15.3.0 experimental field in turbo config was deprecated.\n * Shout out to next-intl: https://github.com/amannn/next-intl/pull/1850\n */\nexport const turboConfigStable = comparePackageVersion(\n getNextVersion(),\n STABLE_TURBO_CONFIG_VERSION\n);\n\nexport type RootParam = 'unsupported' | 'unstable' | 'experimental' | 'stable';\n\n/**\n * Classify the stability of root params for a Next.js version.\n *\n * @param nextVersion - The Next.js version to classify.\n * @returns The root params stability tier for the supplied version.\n */\nexport function getRootParamStability(nextVersion: string): RootParam {\n // Check stable before experimental because each threshold is a lower bound.\n if (comparePackageVersion(nextVersion, ROOT_PARAM_STABILITY.stable)) {\n return 'stable';\n }\n\n if (comparePackageVersion(nextVersion, ROOT_PARAM_STABILITY.experimental)) {\n return 'experimental';\n }\n\n if (comparePackageVersion(nextVersion, ROOT_PARAM_STABILITY.unstable)) {\n return 'unstable';\n }\n\n return 'unsupported';\n}\n\nexport const rootParamStability = getRootParamStability(getNextVersion());\n\nexport const swcPluginCompatible = comparePackageVersion(\n getNextVersion(),\n SWC_PLUGIN_SUPPORT\n);\n\n// disable babel plugin if using react <= 16\nexport const babelPluginCompatible = comparePackageVersion(\n getReactVersion(),\n BABEL_PLUGIN_SUPPORT\n);\n\n// Older refresh reducers can retain a stale layout after middleware redirects.\n// Related refresh/redirect issue: https://github.com/vercel/next.js/issues/65970\nexport const localeRefreshSupported = comparePackageVersion(\n getNextVersion(),\n LOCALE_REFRESH_SUPPORT\n);\n"],"mappings":";;;;;;AAeA,SAAS,kBAAkB,aAA6B;CACtD,MAAM,kBAAkB,GAAG,YAAY;AAEvC,KAAI;EACF,MAAM,0BAA0B,QAAQ,QAAQ,iBAAiB,EAC/D,OAAO,CAAC,QAAQ,KAAK,CAAC,EACvB,CAAC;AACF,SAAO,QAAQ,wBAAwB,CAAC;UACjC,QAAQ;AACf,SAAO,QAAQ,gBAAgB,CAAC;;;AAIpC,SAAS,iBAAyB;AAChC,KAAI;AACF,SAAO,kBAAkB,OAAO;UACzB,OAAO;AACd,QAAM,IAAI,MAAM,iCAAiC,MAAe,CAAC;;;;;;;AAQrE,SAAS,kBAA0B;AACjC,KAAI;AACF,SAAO,kBAAkB,QAAQ;UAC1B,OAAO;AACd,QAAM,IAAI,MAAM,kCAAkC,MAAe,CAAC;;;;;;;;;;AAWtE,SAAS,sBAAsB,GAAW,GAAoB;CAC5D,MAAM,SAAS,EAAE,MAAM,IAAI;CAC3B,MAAM,SAAS,EAAE,MAAM,IAAI;AAE3B,MAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;EACtC,MAAM,QAAQ,OAAO,OAAO,GAAG,IAAI;EACnC,MAAM,QAAQ,OAAO,OAAO,GAAG,IAAI;AAEnC,MAAI,QAAQ,MACV,QAAO;WACE,QAAQ,MACjB,QAAO;;AAKX,QAAO;;;;;;AAOT,MAAa,oBAAoB,sBAC/B,gBAAgB,EAChB,4BACD;;;;;;;AAUD,SAAgB,sBAAsB,aAAgC;AAEpE,KAAI,sBAAsB,aAAa,qBAAqB,OAAO,CACjE,QAAO;AAGT,KAAI,sBAAsB,aAAa,qBAAqB,aAAa,CACvE,QAAO;AAGT,KAAI,sBAAsB,aAAa,qBAAqB,SAAS,CACnE,QAAO;AAGT,QAAO;;AAGT,MAAa,qBAAqB,sBAAsB,gBAAgB,CAAC;AAEzE,MAAa,sBAAsB,sBACjC,gBAAgB,EAChB,mBACD;AAGD,MAAa,wBAAwB,sBACnC,iBAAiB,EACjB,qBACD;AAID,MAAa,yBAAyB,sBACpC,gBAAgB,EAChB,uBACD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GTProvider.d.ts","sourceRoot":"","sources":["../../src/provider/GTProvider.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAMtD,wBAAsB,UAAU,CAAC,EAAE,QAAQ,EAAE,EAAE,eAAe,
|
|
1
|
+
{"version":3,"file":"GTProvider.d.ts","sourceRoot":"","sources":["../../src/provider/GTProvider.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAMtD,wBAAsB,UAAU,CAAC,EAAE,QAAQ,EAAE,EAAE,eAAe,oDAiC7D"}
|
|
@@ -16,12 +16,17 @@ async function GTProvider({ children }) {
|
|
|
16
16
|
const enableI18n = await require_request_getEnableI18n.getEnableI18n();
|
|
17
17
|
const translationsSnapshotPromise = i18nConfig.requiresTranslation(locale) ? i18nCache.loadTranslations(locale) : Promise.resolve({});
|
|
18
18
|
const dictionariesSnapshotPromise = i18nCache.loadDictionaries(locale);
|
|
19
|
+
const translationsSnapshot = { [locale]: await translationsSnapshotPromise };
|
|
20
|
+
const dictionariesSnapshot = await dictionariesSnapshotPromise;
|
|
19
21
|
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___utils_client_boundary_js.Client_GTProvider, {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
22
|
+
supportsLocaleRefresh: process.env._GENERALTRANSLATION_LOCALE_REFRESH_SUPPORTED === "true",
|
|
23
|
+
conditions: {
|
|
24
|
+
locale,
|
|
25
|
+
region,
|
|
26
|
+
enableI18n
|
|
27
|
+
},
|
|
28
|
+
translations: translationsSnapshot,
|
|
29
|
+
dictionaries: dictionariesSnapshot,
|
|
25
30
|
children
|
|
26
31
|
});
|
|
27
32
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GTProvider.js","names":["getNextI18nCache","getLocale","getRegion","getEnableI18n","Client_GTProvider"],"sources":["../../src/provider/GTProvider.tsx"],"sourcesContent":["import { getLocale } from '../request/getLocale';\nimport { getRegion } from '../request/getRegion';\nimport type { GTProviderProps } from '../utils/types';\nimport { Client_GTProvider } from '../utils/client-boundary';\nimport { getNextI18nCache } from '../i18n-cache/NextI18nCache';\nimport { getI18nConfig } from 'gt-i18n/internal';\nimport { getEnableI18n } from '../request/getEnableI18n';\n\nexport async function GTProvider({ children }: GTProviderProps) {\n // ---------- SETUP ---------- //\n const i18nCache = getNextI18nCache();\n const i18nConfig = getI18nConfig();\n const locale = await getLocale();\n const region = await getRegion();\n const enableI18n = await getEnableI18n();\n const translationRequired = i18nConfig.requiresTranslation(locale);\n\n // ----- FETCH TRANSLATIONS FROM CACHE ----- //\n\n const translationsSnapshotPromise = translationRequired\n ? i18nCache.loadTranslations(locale)\n : Promise.resolve({});\n\n const dictionariesSnapshotPromise = i18nCache.loadDictionaries(locale);\n\n // Block until cache check resolves\n const translationsSnapshot = { [locale]: await translationsSnapshotPromise };\n const dictionariesSnapshot = await dictionariesSnapshotPromise;\n\n return (\n <Client_GTProvider\n
|
|
1
|
+
{"version":3,"file":"GTProvider.js","names":["getNextI18nCache","getLocale","getRegion","getEnableI18n","Client_GTProvider"],"sources":["../../src/provider/GTProvider.tsx"],"sourcesContent":["import { getLocale } from '../request/getLocale';\nimport { getRegion } from '../request/getRegion';\nimport type { GTProviderProps } from '../utils/types';\nimport { Client_GTProvider } from '../utils/client-boundary';\nimport { getNextI18nCache } from '../i18n-cache/NextI18nCache';\nimport { getI18nConfig } from 'gt-i18n/internal';\nimport { getEnableI18n } from '../request/getEnableI18n';\n\nexport async function GTProvider({ children }: GTProviderProps) {\n // ---------- SETUP ---------- //\n const i18nCache = getNextI18nCache();\n const i18nConfig = getI18nConfig();\n const locale = await getLocale();\n const region = await getRegion();\n const enableI18n = await getEnableI18n();\n const translationRequired = i18nConfig.requiresTranslation(locale);\n\n // ----- FETCH TRANSLATIONS FROM CACHE ----- //\n\n const translationsSnapshotPromise = translationRequired\n ? i18nCache.loadTranslations(locale)\n : Promise.resolve({});\n\n const dictionariesSnapshotPromise = i18nCache.loadDictionaries(locale);\n\n // Block until cache check resolves\n const translationsSnapshot = { [locale]: await translationsSnapshotPromise };\n const dictionariesSnapshot = await dictionariesSnapshotPromise;\n\n return (\n <Client_GTProvider\n supportsLocaleRefresh={\n process.env._GENERALTRANSLATION_LOCALE_REFRESH_SUPPORTED === 'true'\n }\n conditions={{ locale, region, enableI18n }}\n translations={translationsSnapshot}\n dictionaries={dictionariesSnapshot}\n >\n {children}\n </Client_GTProvider>\n );\n}\n"],"mappings":";;;;;;;;;;AAQA,eAAsB,WAAW,EAAE,YAA6B;CAE9D,MAAM,YAAYA,iCAAAA,kBAAkB;CACpC,MAAM,cAAA,GAAA,iBAAA,gBAA4B;CAClC,MAAM,SAAS,MAAMC,0BAAAA,WAAW;CAChC,MAAM,SAAS,MAAMC,0BAAAA,WAAW;CAChC,MAAM,aAAa,MAAMC,8BAAAA,eAAe;CAKxC,MAAM,8BAJsB,WAAW,oBAAoB,OAIJ,GACnD,UAAU,iBAAiB,OAAO,GAClC,QAAQ,QAAQ,EAAE,CAAC;CAEvB,MAAM,8BAA8B,UAAU,iBAAiB,OAAO;CAGtE,MAAM,uBAAuB,GAAG,SAAS,MAAM,6BAA6B;CAC5E,MAAM,uBAAuB,MAAM;AAEnC,QACE,iBAAA,GAAA,kBAAA,KAACC,4BAAAA,mBAAD;EACE,uBACE,QAAQ,IAAI,iDAAiD;EAE/D,YAAY;GAAE;GAAQ;GAAQ;GAAY;EAC1C,cAAc;EACd,cAAc;EAEb;EACiB,CAAA"}
|
|
@@ -14,12 +14,17 @@ async function GTProvider({ children }) {
|
|
|
14
14
|
const enableI18n = await getEnableI18n();
|
|
15
15
|
const translationsSnapshotPromise = i18nConfig.requiresTranslation(locale) ? i18nCache.loadTranslations(locale) : Promise.resolve({});
|
|
16
16
|
const dictionariesSnapshotPromise = i18nCache.loadDictionaries(locale);
|
|
17
|
+
const translationsSnapshot = { [locale]: await translationsSnapshotPromise };
|
|
18
|
+
const dictionariesSnapshot = await dictionariesSnapshotPromise;
|
|
17
19
|
return /* @__PURE__ */ jsx(Client_GTProvider, {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
20
|
+
supportsLocaleRefresh: process.env._GENERALTRANSLATION_LOCALE_REFRESH_SUPPORTED === "true",
|
|
21
|
+
conditions: {
|
|
22
|
+
locale,
|
|
23
|
+
region,
|
|
24
|
+
enableI18n
|
|
25
|
+
},
|
|
26
|
+
translations: translationsSnapshot,
|
|
27
|
+
dictionaries: dictionariesSnapshot,
|
|
23
28
|
children
|
|
24
29
|
});
|
|
25
30
|
}
|