gt-next 11.2.1 → 11.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/config.d.ts.map +1 -1
  3. package/dist/config.js +2 -7
  4. package/dist/config.js.map +1 -1
  5. package/dist/config.mjs +4 -9
  6. package/dist/config.mjs.map +1 -1
  7. package/dist/errors/createErrors.d.ts +0 -1
  8. package/dist/errors/createErrors.d.ts.map +1 -1
  9. package/dist/errors/createErrors.js +0 -2
  10. package/dist/errors/createErrors.js.map +1 -1
  11. package/dist/errors/createErrors.mjs +1 -2
  12. package/dist/errors/createErrors.mjs.map +1 -1
  13. package/dist/middleware-dir/createNextMiddleware.d.ts +6 -1
  14. package/dist/middleware-dir/createNextMiddleware.d.ts.map +1 -1
  15. package/dist/middleware-dir/createNextMiddleware.js +51 -21
  16. package/dist/middleware-dir/createNextMiddleware.js.map +1 -1
  17. package/dist/middleware-dir/createNextMiddleware.mjs +52 -22
  18. package/dist/middleware-dir/createNextMiddleware.mjs.map +1 -1
  19. package/dist/middleware-dir/utils.d.ts +1 -1
  20. package/dist/middleware-dir/utils.d.ts.map +1 -1
  21. package/dist/middleware-dir/utils.js +8 -13
  22. package/dist/middleware-dir/utils.js.map +1 -1
  23. package/dist/middleware-dir/utils.mjs +8 -13
  24. package/dist/middleware-dir/utils.mjs.map +1 -1
  25. package/dist/middleware.d.ts +1 -1
  26. package/dist/middleware.d.ts.map +1 -1
  27. package/dist/plugin/constants.d.ts +1 -0
  28. package/dist/plugin/constants.d.ts.map +1 -1
  29. package/dist/plugin/constants.js +2 -0
  30. package/dist/plugin/constants.js.map +1 -1
  31. package/dist/plugin/constants.mjs +2 -1
  32. package/dist/plugin/constants.mjs.map +1 -1
  33. package/dist/plugin/getStableNextVersionInfo.d.ts +1 -0
  34. package/dist/plugin/getStableNextVersionInfo.d.ts.map +1 -1
  35. package/dist/plugin/getStableNextVersionInfo.js +2 -0
  36. package/dist/plugin/getStableNextVersionInfo.js.map +1 -1
  37. package/dist/plugin/getStableNextVersionInfo.mjs +3 -2
  38. package/dist/plugin/getStableNextVersionInfo.mjs.map +1 -1
  39. package/dist/provider/GTProvider.d.ts.map +1 -1
  40. package/dist/provider/GTProvider.js +10 -5
  41. package/dist/provider/GTProvider.js.map +1 -1
  42. package/dist/provider/GTProvider.mjs +10 -5
  43. package/dist/provider/GTProvider.mjs.map +1 -1
  44. package/dist/request/localeValidation.js +2 -2
  45. package/dist/request/localeValidation.js.map +1 -1
  46. package/dist/request/localeValidation.mjs +2 -2
  47. package/dist/request/localeValidation.mjs.map +1 -1
  48. package/dist/utils/client-boundary.d.ts +4 -1
  49. package/dist/utils/client-boundary.d.ts.map +1 -1
  50. package/dist/utils/client-boundary.js +14 -10
  51. package/dist/utils/client-boundary.js.map +1 -1
  52. package/dist/utils/client-boundary.mjs +14 -10
  53. package/dist/utils/client-boundary.mjs.map +1 -1
  54. package/package.json +8 -8
@@ -3,12 +3,11 @@ import "../utils/cookies.mjs";
3
3
  import { compilePathRegex, pathnameMatchesRegex } from "../utils/pathRegex.mjs";
4
4
  import { applyTrailingSlash, normalizePathname } from "./pathname.mjs";
5
5
  import { createUnsupportedLocalesWarning } from "../errors/middleware.mjs";
6
- import { createPathToSharedPathMap } from "./createPathMatcher.mjs";
6
+ import { createPathMatcher, createPathToSharedPathMap } from "./createPathMatcher.mjs";
7
7
  import { getSharedPath } from "./matchPath.mjs";
8
8
  import { getLocaleFromRequest, getLocalizedPath, getResponse, replaceDynamicSegments } from "./utils.mjs";
9
9
  import { libraryDefaultLocale } from "generaltranslation/internal";
10
10
  import { defaultLocaleCookieName, defaultResetLocaleCookieName } from "@generaltranslation/react-core/pure";
11
- import { isSameDialect, standardizeLocale } from "@generaltranslation/format";
12
11
  import { GTRuntime } from "generaltranslation/runtime";
13
12
  import { NextResponse } from "next/server.js";
14
13
  //#region src/middleware-dir/createNextMiddleware.ts
@@ -23,12 +22,14 @@ const NEXT_JS_SOURCE_MAP_PATH = "/__nextjs_source-map";
23
22
  *
24
23
  * @param {boolean} [config.localeRouting=true] - Flag to enable or disable automatic locale-based routing.
25
24
  * @param {boolean} [config.prefixDefaultLocale=false] - Flag to enable or disable prefixing the default locale to the pathname, i.e., /en/about -> /about
25
+ * @param {boolean} [config.enableSmartRouting=true] - Keep automatic locale negotiation. Disable to treat returning visitors' unprefixed URLs as default-locale routes.
26
26
  * @param {boolean} [config.ignoreSourceMaps=true] - Flag to enable or disable ignoring source maps
27
27
  * @param {PathConfig} [config.pathConfig] - Path configuration for locale routing
28
28
  * @param {RouteOverrides} [config.routeOverrides] - Locale-relative paths to rewrite from /{locale}/{path} to /{locale}/{locale}/{path}
29
+ * @param {LocaleRoutes} [config.localeRoutes] - Shared paths available per locale; other paths fall back to the default locale
29
30
  * @returns {function} - A middleware function that processes the request and response.
30
31
  */
31
- function createNextMiddleware({ localeRouting = true, prefixDefaultLocale = false, ignoreSourceMaps = true, pathConfig = {}, routeOverrides = {} } = {}) {
32
+ function createNextMiddleware({ localeRouting = true, prefixDefaultLocale = false, enableSmartRouting = true, ignoreSourceMaps = true, pathConfig = {}, routeOverrides = {}, localeRoutes = {} } = {}) {
32
33
  const pathRegex = compilePathRegex(process.env._GENERALTRANSLATION_PATH_REGEX);
33
34
  let envParams;
34
35
  if (process.env._GENERALTRANSLATION_I18N_CONFIG_PARAMS) try {
@@ -37,11 +38,17 @@ function createNextMiddleware({ localeRouting = true, prefixDefaultLocale = fals
37
38
  console.error(`gt-next middleware:`, error);
38
39
  }
39
40
  const gt = new GTRuntime({ customMapping: envParams?.customMapping });
40
- const gtServicesEnabled = process.env._GENERALTRANSLATION_GT_SERVICES_ENABLED === "true";
41
41
  const defaultLocale = envParams?.defaultLocale || libraryDefaultLocale;
42
- const locales = envParams?.locales || [defaultLocale];
43
- const canonicalLocales = Object.values(envParams?.customMapping || {}).filter((locale) => typeof locale === "object" && locale !== null && "code" in locale && typeof locale.code === "string" && locale.code.length > 0).map((locale) => locale.code);
44
- locales.push(...canonicalLocales);
42
+ const locales = Array.from(new Set([defaultLocale, ...envParams?.locales || []]));
43
+ const resolvedConfigLocales = /* @__PURE__ */ new Map();
44
+ const determineLocaleWithCache = (locale) => {
45
+ const cached = resolvedConfigLocales.get(locale);
46
+ if (cached !== void 0) return cached;
47
+ const resolved = gt.determineLocale(locale, locales) ?? locale;
48
+ resolvedConfigLocales.set(locale, resolved);
49
+ return resolved;
50
+ };
51
+ const resolvePathConfigLocale = process.env._GENERALTRANSLATION_GT_SERVICES_ENABLED === "true" ? determineLocaleWithCache : (locale) => locale;
45
52
  const headersAndCookies = envParams?.headersAndCookies || {};
46
53
  const localeRoutingEnabledCookieName = headersAndCookies?.localeRoutingEnabledCookieName || "generaltranslation.locale-routing-enabled";
47
54
  const referrerLocaleCookieName = headersAndCookies?.referrerLocaleCookieName || "generaltranslation.referrer-locale";
@@ -54,20 +61,23 @@ function createNextMiddleware({ localeRouting = true, prefixDefaultLocale = fals
54
61
  pathConfig = Object.entries(pathConfig).reduce((acc, [sharedPath, localizedPath]) => {
55
62
  if (typeof localizedPath === "string") acc[sharedPath] = localizedPath;
56
63
  else acc[sharedPath] = Object.entries(localizedPath).reduce((acc, [locale, localizedPath]) => {
57
- acc[gtServicesEnabled ? standardizeLocale(locale) : locale] = localizedPath;
64
+ acc[resolvePathConfigLocale(locale)] = localizedPath;
58
65
  return acc;
59
66
  }, {});
60
67
  return acc;
61
68
  }, {});
69
+ const { pathToSharedPath, defaultLocalePaths } = createPathToSharedPathMap(Object.fromEntries(Object.entries(pathConfig).map(([sharedPath, localizedPath]) => [sharedPath, typeof localizedPath === "string" ? Object.fromEntries(locales.map((locale) => [determineLocaleWithCache(locale), localizedPath === "" ? "/" : localizedPath])) : localizedPath])), prefixDefaultLocale, defaultLocale);
62
70
  routeOverrides = Object.entries(routeOverrides).reduce((acc, [locale, paths]) => {
63
- acc[gtServicesEnabled ? standardizeLocale(locale) : locale] = paths;
71
+ acc[resolvePathConfigLocale(locale)] = paths;
64
72
  return acc;
65
73
  }, {});
66
74
  const routeOverridePathMaps = Object.entries(routeOverrides).reduce((acc, [locale, paths]) => {
67
75
  acc[locale] = createPathToSharedPathMap(Object.fromEntries(paths.map((path) => [path, path])), true, defaultLocale).pathToSharedPath;
68
76
  return acc;
69
77
  }, {});
70
- const { pathToSharedPath, defaultLocalePaths } = createPathToSharedPathMap(pathConfig, prefixDefaultLocale, defaultLocale);
78
+ const localeRoutePathMaps = new Map(Object.entries(localeRoutes).map(([locale, paths]) => {
79
+ return [determineLocaleWithCache(locale), createPathMatcher(paths.map((path) => [path, path]))];
80
+ }));
71
81
  /**
72
82
  * Processes the incoming request to determine the user's locale and sets a locale cookie.
73
83
  * Optionally redirects the user based on the locale if locale-based routing is enabled.
@@ -84,7 +94,9 @@ function createNextMiddleware({ localeRouting = true, prefixDefaultLocale = fals
84
94
  function middleware(req) {
85
95
  if (!pathnameMatchesRegex(req.nextUrl.pathname, pathRegex)) return NextResponse.next();
86
96
  if (ignoreSourceMaps && req.nextUrl.pathname.startsWith(NEXT_JS_SOURCE_MAP_PATH)) return NextResponse.next();
87
- const { userLocale, pathnameLocale, unstandardizedPathnameLocale, clearResetCookie } = getLocaleFromRequest(req, defaultLocale, locales, localeRouting, gtServicesEnabled, prefixDefaultLocale, defaultLocalePaths, referrerLocaleCookieName, localeCookieName, resetLocaleCookieName, gt);
97
+ const { userLocale: requestedLocale, pathnameLocale: pathnameRoutingLocale, unstandardizedPathnameLocale, clearResetCookie } = getLocaleFromRequest(req, defaultLocale, locales, localeRouting, prefixDefaultLocale, defaultLocalePaths, referrerLocaleCookieName, localeCookieName, resetLocaleCookieName, gt, enableSmartRouting);
98
+ let userLocale = requestedLocale;
99
+ const pathnameLocale = pathnameRoutingLocale;
88
100
  const headerList = new Headers(req.headers);
89
101
  const responseConfig = {
90
102
  originalUrl: req.nextUrl,
@@ -101,11 +113,15 @@ function createNextMiddleware({ localeRouting = true, prefixDefaultLocale = fals
101
113
  type: "rewrite",
102
114
  ...responseConfig
103
115
  });
104
- const getRedirectResponse = (responsePath) => getResponse({
105
- responsePath,
106
- type: "redirect",
107
- ...responseConfig
108
- });
116
+ const getRedirectResponse = (responsePath) => {
117
+ const response = getResponse({
118
+ responsePath,
119
+ type: "redirect",
120
+ ...responseConfig
121
+ });
122
+ if (!enableSmartRouting && !prefixDefaultLocale && pathnameLocale === defaultLocale && userLocale === defaultLocale && req.headers.get("sec-fetch-dest") === "document" && !req.cookies.has(localeCookieName)) response.cookies.set(localeCookieName, defaultLocale);
123
+ return response;
124
+ };
109
125
  const getNextResponse = () => getResponse({
110
126
  type: "next",
111
127
  ...responseConfig
@@ -115,25 +131,39 @@ function createNextMiddleware({ localeRouting = true, prefixDefaultLocale = fals
115
131
  const standardizedPathname = pathnameLocale && pathnameLocale !== unstandardizedPathnameLocale ? pathname.replace(new RegExp(`^/${unstandardizedPathnameLocale}`), `/${pathnameLocale}`) : pathname;
116
132
  const sharedPathMatch = getSharedPath(standardizedPathname, pathToSharedPath, pathnameLocale);
117
133
  const sharedPath = sharedPathMatch?.sharedPath;
134
+ const localeRoutePathMap = localeRoutePathMaps.get(userLocale);
135
+ if (userLocale !== defaultLocale && localeRoutePathMap) {
136
+ const sharedPagePath = sharedPathMatch ? replaceDynamicSegments(sharedPathMatch.matchedPathname, sharedPath || "/", sharedPathMatch.pathTemplate) : (pathnameLocale ? standardizedPathname.slice(pathnameLocale.length + 1) : standardizedPathname) || "/";
137
+ if (getSharedPath(sharedPagePath, localeRoutePathMap, void 0) === void 0) {
138
+ const defaultPath = sharedPath !== void 0 ? getLocalizedPath(sharedPath, defaultLocale, pathConfig) : void 0;
139
+ const fallbackPath = defaultPath !== void 0 && sharedPathMatch ? replaceDynamicSegments(sharedPathMatch.matchedPathname, defaultPath, sharedPathMatch.pathTemplate) : `/${defaultLocale}${sharedPagePath === "/" ? "" : sharedPagePath}`;
140
+ const publicFallbackPath = applyTrailingSlash(standardizedPathname, prefixDefaultLocale ? fallbackPath : fallbackPath.slice(defaultLocale.length + 1) || "/");
141
+ userLocale = defaultLocale;
142
+ responseConfig.userLocale = defaultLocale;
143
+ const fallbackUrl = new URL(req.nextUrl);
144
+ fallbackUrl.pathname = publicFallbackPath;
145
+ if (fallbackUrl.pathname !== pathname) return getRedirectResponse(publicFallbackPath);
146
+ }
147
+ }
118
148
  const sharedPathWithParameters = sharedPathMatch !== void 0 ? applyTrailingSlash(standardizedPathname, replaceDynamicSegments(sharedPathMatch.matchedPathname, `/${userLocale}${sharedPath}`, sharedPathMatch.pathTemplate)) : void 0;
119
149
  const localizedPath = sharedPath !== void 0 ? getLocalizedPath(sharedPath, userLocale, pathConfig) : void 0;
120
150
  const localizedPathWithParameters = localizedPath !== void 0 && sharedPathMatch !== void 0 ? applyTrailingSlash(standardizedPathname, replaceDynamicSegments(sharedPathMatch.matchedPathname, localizedPath, sharedPathMatch.pathTemplate)) : void 0;
121
- const pagePath = (sharedPathWithParameters?.replace(new RegExp(`^/${userLocale}`), "") ?? (pathnameLocale ? standardizedPathname.replace(new RegExp(`^/${userLocale}`), "") : standardizedPathname)) || "/";
151
+ const pagePath = (sharedPathWithParameters?.slice(userLocale.length + 1) ?? (pathnameLocale ? standardizedPathname.slice(pathnameLocale.length + 1) : standardizedPathname)) || "/";
122
152
  const routeOverridePathMap = routeOverridePathMaps[userLocale];
123
153
  const routeOverridePath = (routeOverridePathMap ? getSharedPath(pagePath, routeOverridePathMap, void 0) : void 0) !== void 0 ? applyTrailingSlash(standardizedPathname, `/${userLocale}/${userLocale}${pagePath === "/" ? "" : pagePath}`) : void 0;
124
154
  if (localizedPathWithParameters === void 0) {
125
- if (!prefixDefaultLocale && isSameDialect(userLocale, defaultLocale)) if (pathnameLocale) {
126
- if (clearResetCookie) return getRedirectResponse(pathname.replace(new RegExp(`^/${unstandardizedPathnameLocale}`), ``) || "/");
155
+ if (!prefixDefaultLocale && userLocale === defaultLocale) if (pathnameLocale) {
156
+ if (clearResetCookie || !enableSmartRouting) return getRedirectResponse(pathname.slice(unstandardizedPathnameLocale.length + 1) || "/");
127
157
  } else return getRewriteResponse(routeOverridePath || `/${userLocale}${pathname}`);
128
158
  else if (!pathnameLocale) return getRedirectResponse(`/${userLocale}${pathname}`);
129
159
  if (pathnameLocale && userLocale !== unstandardizedPathnameLocale) return getRedirectResponse(pathname.replace(new RegExp(`^/${unstandardizedPathnameLocale}`), `/${userLocale}`));
130
160
  if (routeOverridePath) return getRewriteResponse(routeOverridePath);
131
161
  return getNextResponse();
132
162
  }
133
- if (!prefixDefaultLocale && isSameDialect(userLocale, defaultLocale)) if (pathnameLocale) {
134
- if (clearResetCookie) return getRedirectResponse(localizedPathWithParameters.replace(new RegExp(`^/${userLocale}`), ``) || "/");
163
+ if (!prefixDefaultLocale && userLocale === defaultLocale) if (pathnameLocale) {
164
+ if (clearResetCookie || !enableSmartRouting) return getRedirectResponse(localizedPathWithParameters.slice(userLocale.length + 1) || "/");
135
165
  } else {
136
- const localizedPublicPath = localizedPathWithParameters.replace(new RegExp(`^/${userLocale}`), "") || "/";
166
+ const localizedPublicPath = localizedPathWithParameters.slice(userLocale.length + 1) || "/";
137
167
  if (!pathnameLocale && normalizePathname(localizedPublicPath) !== normalizePathname(pathname)) return getRedirectResponse(localizedPublicPath);
138
168
  return getRewriteResponse(routeOverridePath || sharedPathWithParameters);
139
169
  }
@@ -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,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,oBACJ,QAAQ,IAAI,4CAA4C;CAG1D,MAAM,gBACJ,WAAW,iBAAiB;CAC9B,MAAM,UAAoB,WAAW,WAAW,CAAC,cAAc;CAG/D,MAAM,mBAAmB,OAAO,OAAO,WAAW,iBAAiB,EAAE,CAAC,CACnE,QACE,WACC,OAAO,WAAW,YAClB,WAAW,QACX,UAAU,UACV,OAAO,OAAO,SAAS,YACvB,OAAO,KAAK,SAAS,EACxB,CACA,KAAK,WAAW,OAAO,KAAK;AAC/B,SAAQ,KAAK,GAAG,iBAAiB;CAGjC,MAAM,oBAAoB,WAAW,qBAAqB,EAAE;CAC5D,MAAM,iCACJ,mBAAmB,kCAAA;CAErB,MAAM,2BACJ,mBAAmB,4BAAA;CAErB,MAAM,mBACJ,mBAAmB,oBAAoB;CACzC,MAAM,wBACJ,mBAAmB,yBAAyB;CAC9C,MAAM,mBACJ,mBAAmB,oBAAA;AAErB,KAAI,CAAC,GAAG,cAAc,cAAc,CAClC,OAAM,IAAI,MACR,sCAAsC,cAAc,0BACrD;CAEH,MAAM,iBAAiB,QAAQ,QAAQ,WAAW,CAAC,GAAG,cAAc,OAAO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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,cAAc,YAAY,cAAc,CAGlE,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"}
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.enableSmartRouting=true] - Keep automatic locale negotiation. Disable to treat returning visitors' unprefixed URLs as default-locale routes.\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 enableSmartRouting = true,\n ignoreSourceMaps = true,\n pathConfig = {},\n routeOverrides = {},\n localeRoutes = {},\n}: {\n localeRouting?: boolean;\n prefixDefaultLocale?: boolean;\n enableSmartRouting?: 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 enableSmartRouting\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 const response = getResponse({\n responsePath,\n type: 'redirect',\n ...responseConfig,\n });\n if (\n !enableSmartRouting &&\n !prefixDefaultLocale &&\n pathnameLocale === defaultLocale &&\n userLocale === defaultLocale &&\n req.headers.get('sec-fetch-dest') === 'document' &&\n !req.cookies.has(localeCookieName)\n ) {\n // Preserve explicit /en intent across a first document redirect.\n // Background fetches and returning visits must not change the cookie.\n response.cookies.set(localeCookieName, defaultLocale);\n }\n return response;\n };\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: explicit default locale or setLocale (/en/customers -> /customers)\n if (clearResetCookie || !enableSmartRouting) {\n return getRedirectResponse(\n pathname.slice(\n (unstandardizedPathnameLocale as string).length + 1\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: explicit default locale or setLocale (/en/blog -> /blog)\n if (clearResetCookie || !enableSmartRouting) {\n return getRedirectResponse(\n localizedPathWithParameters.slice(userLocale.length + 1) || '/'\n );\n }\n } else {\n const localizedPublicPath =\n localizedPathWithParameters.slice(userLocale.length + 1) || '/';\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;;;;;;;;;;;;;;;;;;AA8BhC,SAAgB,qBAAqB,EACnC,gBAAgB,MAChB,sBAAsB,OACtB,qBAAqB,MACrB,mBAAmB,MACnB,aAAa,EAAE,EACf,iBAAiB,EAAE,EACnB,eAAe,EAAE,KASf,EAAE,EAAE;CACN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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,oBAAoB,CAAC,mBACvB,QAAO,oBACL,4BAA4B,MAAM,WAAW,SAAS,EAAE,IAAI,IAC7D;UAEE;IACL,MAAM,sBACJ,4BAA4B,MAAM,WAAW,SAAS,EAAE,IAAI;AAG9D,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, gtServicesEnabled: boolean, prefixDefaultLocale: boolean, defaultLocalePaths: PathMatcher, referrerLocaleCookieName: string, localeCookieName: string, resetLocaleCookieName: string, gt: GTRuntime): {
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, enableSmartRouting?: boolean): {
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;AAExD,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,MAAM,CAAC;IACnB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,UAAU,EAAE,OAAO,CAAC;IACpB,aAAa,EAAE,OAAO,CAAC;IACvB,8BAA8B,EAAE,MAAM,CAAC;IACvC,qBAAqB,EAAE,MAAM,CAAC;IAC9B,gBAAgB,EAAE,MAAM,CAAC;CAC1B,CAAC;AAeF,mEAAmE;AACnE,wBAAgB,WAAW,CAAC,EAC1B,IAAI,EACJ,WAAW,EACX,YAAmC,EACnC,UAAU,EACV,gBAAgB,EAChB,UAAU,EACV,aAAa,EACb,8BAA8B,EAC9B,qBAAqB,EACrB,gBAAgB,GACjB,EAAE,cAAc,GAAG,YAAY,CAAC,OAAO,CAAC,CAwCxC;AAED;;GAEG;A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AClB,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,UAAU,GACrB,MAAM,GAAG,SAAS,CAapB;AAeD;;GAEG;AACH,wBAAgB,oBAAoB,CAClC,GAAG,EAAE,WAAW,EAChB,aAAa,EAAE,MAAM,EACrB,eAAe,EAAE,MAAM,EAAE,EACzB,aAAa,EAAE,OAAO,EACtB,mBAAmB,EAAE,OAAO,EAC5B,kBAAkB,EAAE,WAAW,EAC/B,wBAAwB,EAAE,MAAM,EAChC,gBAAgB,EAAE,MAAM,EACxB,qBAAqB,EAAE,MAAM,EAC7B,EAAE,EAAE,SAAS,EACb,kBAAkB,UAAO,GACxB;IACD,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,EAAE,MAAM,GAAG,SAAS,CAAC;IACnC,4BAA4B,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACxD,gBAAgB,EAAE,OAAO,CAAC;CAC3B,CA0FA"}
@@ -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, gtServicesEnabled, prefixDefaultLocale, defaultLocalePaths, referrerLocaleCookieName, localeCookieName, resetLocaleCookieName, gt) {
95
+ function getLocaleFromRequest(req, defaultLocale, approvedLocales, localeRouting, prefixDefaultLocale, defaultLocalePaths, referrerLocaleCookieName, localeCookieName, resetLocaleCookieName, gt, enableSmartRouting = true) {
97
96
  const headerList = new Headers(req.headers);
98
97
  const candidates = [];
99
98
  let clearResetCookie = false;
@@ -101,31 +100,27 @@ function getLocaleFromRequest(req, defaultLocale, approvedLocales, localeRouting
101
100
  let pathnameLocale, unstandardizedPathnameLocale;
102
101
  if (localeRouting) {
103
102
  unstandardizedPathnameLocale = extractLocale(pathname);
104
- const extractedLocale = gtServicesEnabled ? (0, _generaltranslation_format.standardizeLocale)(unstandardizedPathnameLocale || "") : unstandardizedPathnameLocale;
105
- if (extractedLocale && gt.isValidLocale(extractedLocale) && gt.determineLocale([extractedLocale], approvedLocales)) {
106
- const determinedLocale = gt.determineLocale([extractedLocale], approvedLocales);
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
- if (localeRouting && !prefixDefaultLocale && !pathnameLocale && inDefaultLocalePaths(pathname, defaultLocalePaths)) candidates.push(defaultLocale);
114
108
  const cookieLocale = req.cookies.get(localeCookieName);
109
+ const preferDefaultLocale = !enableSmartRouting && localeRouting && !prefixDefaultLocale;
110
+ if (localeRouting && !prefixDefaultLocale && !pathnameLocale && (preferDefaultLocale ? Boolean(cookieLocale?.value) : inDefaultLocalePaths(pathname, defaultLocalePaths))) candidates.push(defaultLocale);
115
111
  if (cookieLocale?.value && gt.isValidLocale(cookieLocale?.value)) if (req.cookies.get(resetLocaleCookieName)?.value) {
116
112
  candidates.unshift(cookieLocale.value);
117
113
  clearResetCookie = true;
118
114
  } else candidates.push(cookieLocale.value);
119
115
  const referrerLocaleCookie = req.cookies.get(referrerLocaleCookieName);
120
- if (referrerLocaleCookie?.value && gt.isValidLocale(referrerLocaleCookie.value) && !clearResetCookie) {
116
+ if (referrerLocaleCookie?.value && gt.isValidLocale(referrerLocaleCookie.value) && !clearResetCookie && (!preferDefaultLocale || cookieLocale?.value)) {
121
117
  const referrerLocale = referrerLocaleCookie.value;
122
118
  if (gt.determineLocale([referrerLocale], approvedLocales)) candidates.push(referrerLocale);
123
119
  }
124
120
  if (process.env._GENERALTRANSLATION_IGNORE_BROWSER_LOCALES === "false") candidates.push(...(0, gt_i18n_internal.parseAcceptLanguage)(headerList.get("accept-language")));
125
121
  candidates.push(defaultLocale);
126
- const unstandardizedUserLocale = gt.determineLocale(candidates.filter((locale) => gt.isValidLocale(locale)), approvedLocales) || defaultLocale;
127
122
  return {
128
- userLocale: gtServicesEnabled ? (0, _generaltranslation_format.standardizeLocale)(unstandardizedUserLocale) : unstandardizedUserLocale,
123
+ userLocale: gt.determineLocale(candidates.filter((locale) => gt.isValidLocale(locale)), approvedLocales) || defaultLocale,
129
124
  pathnameLocale,
130
125
  unstandardizedPathnameLocale,
131
126
  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;CAExC,IAAI;AACJ,KAAI,SAAS,OACX,YAAWC,eAAAA,aAAa,KAAK,EAC3B,SAAS,EACP,SAAS,YACV,EACF,CAAC;MACG;EAGL,MAAM,cAAc,IAAI,IAAI,YAAY;AACxC,cAAY,WAAW;AACvB,gBAAc,aAAa,YA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BAAqB,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 enableSmartRouting = true\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 const cookieLocale = req.cookies.get(localeCookieName);\n const preferDefaultLocale =\n !enableSmartRouting && localeRouting && !prefixDefaultLocale;\n // With smart routing disabled, returning visitors choose the default locale\n // by visiting an unprefixed URL.\n // First visits still negotiate their language; explicit resets override below.\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 (preferDefaultLocale\n ? Boolean(cookieLocale?.value) // skip this condition when preferDefaultLocale is true and first request (no cookieLocale)\n : inDefaultLocalePaths(pathname, defaultLocalePaths))\n ) {\n candidates.push(defaultLocale); // will override other candidates\n }\n\n // Check cookie locale\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 (!preferDefaultLocale || cookieLocale?.value) // skip this condition when preferDefaultLocale is true and first request (no cookieLocale)\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,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AI,eAAgB,YAAW,KAAK,eAAe;;;CAIvD,MAAM,eAAe,IAAI,QAAQ,IAAI,iBAAiB;CACtD,MAAM,sBACJ,CAAC,sBAAsB,iBAAiB,CAAC;AAK3C,KACE,iBACA,CAAC,uBACD,CAAC,mBACA,sBACG,QAAQ,cAAc,MAAM,GAC5B,qBAAqB,UAAU,mBAAmB,EAEtD,YAAW,KAAK,cAAc;AAIhC,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,qBACA,CAAC,uBAAuB,cAAc,QACvC;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, gtServicesEnabled, prefixDefaultLocale, defaultLocalePaths, referrerLocaleCookieName, localeCookieName, resetLocaleCookieName, gt) {
93
+ function getLocaleFromRequest(req, defaultLocale, approvedLocales, localeRouting, prefixDefaultLocale, defaultLocalePaths, referrerLocaleCookieName, localeCookieName, resetLocaleCookieName, gt, enableSmartRouting = true) {
95
94
  const headerList = new Headers(req.headers);
96
95
  const candidates = [];
97
96
  let clearResetCookie = false;
@@ -99,31 +98,27 @@ function getLocaleFromRequest(req, defaultLocale, approvedLocales, localeRouting
99
98
  let pathnameLocale, unstandardizedPathnameLocale;
100
99
  if (localeRouting) {
101
100
  unstandardizedPathnameLocale = extractLocale(pathname);
102
- const extractedLocale = gtServicesEnabled ? standardizeLocale(unstandardizedPathnameLocale || "") : unstandardizedPathnameLocale;
103
- if (extractedLocale && gt.isValidLocale(extractedLocale) && gt.determineLocale([extractedLocale], approvedLocales)) {
104
- const determinedLocale = gt.determineLocale([extractedLocale], approvedLocales);
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
- if (localeRouting && !prefixDefaultLocale && !pathnameLocale && inDefaultLocalePaths(pathname, defaultLocalePaths)) candidates.push(defaultLocale);
112
106
  const cookieLocale = req.cookies.get(localeCookieName);
107
+ const preferDefaultLocale = !enableSmartRouting && localeRouting && !prefixDefaultLocale;
108
+ if (localeRouting && !prefixDefaultLocale && !pathnameLocale && (preferDefaultLocale ? Boolean(cookieLocale?.value) : inDefaultLocalePaths(pathname, defaultLocalePaths))) candidates.push(defaultLocale);
113
109
  if (cookieLocale?.value && gt.isValidLocale(cookieLocale?.value)) if (req.cookies.get(resetLocaleCookieName)?.value) {
114
110
  candidates.unshift(cookieLocale.value);
115
111
  clearResetCookie = true;
116
112
  } else candidates.push(cookieLocale.value);
117
113
  const referrerLocaleCookie = req.cookies.get(referrerLocaleCookieName);
118
- if (referrerLocaleCookie?.value && gt.isValidLocale(referrerLocaleCookie.value) && !clearResetCookie) {
114
+ if (referrerLocaleCookie?.value && gt.isValidLocale(referrerLocaleCookie.value) && !clearResetCookie && (!preferDefaultLocale || cookieLocale?.value)) {
119
115
  const referrerLocale = referrerLocaleCookie.value;
120
116
  if (gt.determineLocale([referrerLocale], approvedLocales)) candidates.push(referrerLocale);
121
117
  }
122
118
  if (process.env._GENERALTRANSLATION_IGNORE_BROWSER_LOCALES === "false") candidates.push(...parseAcceptLanguage(headerList.get("accept-language")));
123
119
  candidates.push(defaultLocale);
124
- const unstandardizedUserLocale = gt.determineLocale(candidates.filter((locale) => gt.isValidLocale(locale)), approvedLocales) || defaultLocale;
125
120
  return {
126
- userLocale: gtServicesEnabled ? standardizeLocale(unstandardizedUserLocale) : unstandardizedUserLocale,
121
+ userLocale: gt.determineLocale(candidates.filter((locale) => gt.isValidLocale(locale)), approvedLocales) || defaultLocale,
127
122
  pathnameLocale,
128
123
  unstandardizedPathnameLocale,
129
124
  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,SAAg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mB,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,GAAG,oBAAoB,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,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 enableSmartRouting = true\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 const cookieLocale = req.cookies.get(localeCookieName);\n const preferDefaultLocale =\n !enableSmartRouting && localeRouting && !prefixDefaultLocale;\n // With smart routing disabled, returning visitors choose the default locale\n // by visiting an unprefixed URL.\n // First visits still negotiate their language; explicit resets override below.\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 (preferDefaultLocale\n ? Boolean(cookieLocale?.value) // skip this condition when preferDefaultLocale is true and first request (no cookieLocale)\n : inDefaultLocalePaths(pathname, defaultLocalePaths))\n ) {\n candidates.push(defaultLocale); // will override other candidates\n }\n\n // Check cookie locale\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 (!preferDefaultLocale || cookieLocale?.value) // skip this condition when preferDefaultLocale is true and first request (no cookieLocale)\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,MACrB,mBAAmB,IAAI,IA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AI,eAAgB,YAAW,KAAK,eAAe;;;CAIvD,MAAM,eAAe,IAAI,QAAQ,IAAI,iBAAiB;CACtD,MAAM,sBACJ,CAAC,sBAAsB,iBAAiB,CAAC;AAK3C,KACE,iBACA,CAAC,uBACD,CAAC,mBACA,sBACG,QAAQ,cAAc,MAAM,GAC5B,qBAAqB,UAAU,mBAAmB,EAEtD,YAAW,KAAK,cAAc;AAIhC,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,qBACA,CAAC,uBAAuB,cAAc,QACvC;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"}
@@ -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
@@ -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,EAAE,cAAc,EAAE,MAAM,uCAAuC,CAAC"}
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"}
@@ -7,4 +7,5 @@ export declare const ROOT_PARAM_STABILITY: {
7
7
  stable: string;
8
8
  };
9
9
  export declare const STABLE_TURBO_CONFIG_VERSION = "15.3.0";
10
+ export declare const LOCALE_REFRESH_SUPPORT = "16.1.0";
10
11
  //# sourceMappingURL=constants.d.ts.map
@@ -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"}
@@ -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"}