gt-next 11.0.1 → 11.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/dist/errors/createErrors.d.ts +1 -0
- package/dist/errors/createErrors.d.ts.map +1 -1
- package/dist/errors/createErrors.js +8 -0
- package/dist/errors/createErrors.js.map +1 -1
- package/dist/errors/createErrors.mjs +8 -2
- package/dist/errors/createErrors.mjs.map +1 -1
- package/dist/middleware-dir/createNextMiddleware.d.ts +3 -1
- package/dist/middleware-dir/createNextMiddleware.d.ts.map +1 -1
- package/dist/middleware-dir/createNextMiddleware.js +9 -1
- package/dist/middleware-dir/createNextMiddleware.js.map +1 -1
- package/dist/middleware-dir/createNextMiddleware.mjs +10 -2
- package/dist/middleware-dir/createNextMiddleware.mjs.map +1 -1
- package/package.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# gt-next
|
|
2
2
|
|
|
3
|
+
## 11.0.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#1841](https://github.com/generaltranslation/gt/pull/1841) [`ae7eb72`](https://github.com/generaltranslation/gt/commit/ae7eb72ec46ad72fb693521faddc03d4950a3973) Thanks [@ErnestM1234](https://github.com/ErnestM1234)! - Add a `regexFilter` option to `createNextMiddleware` for limiting i18n middleware routing to matching pathnames.
|
|
8
|
+
|
|
9
|
+
- Updated dependencies []:
|
|
10
|
+
- @generaltranslation/react-core@11.0.2
|
|
11
|
+
- gt-react@11.0.2
|
|
12
|
+
|
|
3
13
|
## 11.0.1
|
|
4
14
|
|
|
5
15
|
### Patch Changes
|
|
@@ -15,6 +15,7 @@ export declare const getTranslationsSnapshotRscError: string;
|
|
|
15
15
|
export declare const invalidLocalesError: (locales: string[]) => string;
|
|
16
16
|
export declare const invalidCanonicalLocalesError: (locales: string[]) => string;
|
|
17
17
|
export declare const createInvalidRequestLocaleWarning: (locale: string, defaultLocale: string) => string;
|
|
18
|
+
export declare const createInvalidMiddlewareRegexError: (regexFilter: string, error: unknown) => string;
|
|
18
19
|
export declare const createBadFilepathWarning: (filename: string, dir: string[]) => string;
|
|
19
20
|
export declare const createUnsupportedLocalesWarning: (locales: string[]) => string;
|
|
20
21
|
export declare const projectIdMissingWarn: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createErrors.d.ts","sourceRoot":"","sources":["../../src/errors/createErrors.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"createErrors.d.ts","sourceRoot":"","sources":["../../src/errors/createErrors.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,uBAAuB,QAKlC,CAAC;AAEH,eAAO,MAAM,2BAA2B,GAAI,SAAQ,MAAW,WAK3D,CAAC;AAEL,eAAO,MAAM,2BAA2B,GAAI,SAAQ,MAAW,WAK3D,CAAC;AAEL,eAAO,MAAM,gCAAgC,GAAI,OAAO,KAAK,WAMzD,CAAC;AAEL,eAAO,MAAM,iCAAiC,GAAI,OAAO,KAAK,WAM1D,CAAC;AAEL,eAAO,MAAM,kCAAkC,QAI7C,CAAC;AAEH,eAAO,MAAM,2BAA2B,GAAI,IAAI,MAAM,EAAE,cAAc,MAAM,WAKxE,CAAC;AAEL,eAAO,MAAM,mCAAmC,QAK9C,CAAC;AAEH,eAAO,MAAM,qCAAqC,QAKhD,CAAC;AAEH,eAAO,MAAM,kCAAkC,GAAI,MAAM,MAAM,WAK3D,CAAC;AAEL,eAAO,MAAM,oCAAoC,GAAI,MAAM,MAAM,WAK7D,CAAC;AAEL,eAAO,MAAM,kCAAkC,GAAI,WAAW,MAAM,EAAE,WAKjE,CAAC;AAEN,eAAO,MAAM,cAAc,QAIzB,CAAC;AAEH,eAAO,MAAM,+BAA+B,QAK1C,CAAC;AAEH,eAAO,MAAM,mBAAmB,GAAI,SAAS,MAAM,EAAE,WAMjD,CAAC;AAEL,eAAO,MAAM,4BAA4B,GAAI,SAAS,MAAM,EAAE,WAM1D,CAAC;AAEL,eAAO,MAAM,iCAAiC,GAC5C,QAAQ,MAAM,EACd,eAAe,MAAM,WAOnB,CAAC;AAEL,eAAO,MAAM,iCAAiC,GAC5C,aAAa,MAAM,EACnB,OAAO,OAAO,WAOZ,CAAC;AAIL,eAAO,MAAM,wBAAwB,GAAI,UAAU,MAAM,EAAE,KAAK,MAAM,EAAE,WAIpE,CAAC;AAEL,eAAO,MAAM,+BAA+B,GAAI,SAAS,MAAM,EAAE,WAMhD,CAAC;AAElB,eAAO,MAAM,oBAAoB,QAI/B,CAAC;AAEH,eAAO,MAAM,iBAAiB,QAG5B,CAAC;AAEH,eAAO,MAAM,0BAA0B,GAAI,SAAS,MAAM,EAAE,WACiF,CAAC;AAE9I,eAAO,MAAM,mCAAmC,GAAI,SAAS,MAAM,EAAE,WACkF,CAAC;AAExJ,eAAO,MAAM,iCAAiC,GAAI,MAAM,OAAO,GAAG,KAAK,WAC8B,CAAC;AAEtG,eAAO,MAAM,gCAAgC,QAI3C,CAAC;AAEH,eAAO,MAAM,gCAAgC,QAI3C,CAAC;AAEH,eAAO,MAAM,kCAAkC,GAAI,MAAM,OAAO,GAAG,KAAK,4NAGyD,CAAC;AAElI,eAAO,MAAM,wCAAwC,QAE8C,CAAC;AAEpG,eAAO,MAAM,+BAA+B,0FAA0F,CAAC;AAEvI,eAAO,MAAM,mCAAmC,0JAAyK,CAAC"}
|
|
@@ -3,6 +3,7 @@ require("../_virtual/_rolldown/runtime.js");
|
|
|
3
3
|
const require_errors_diagnostics = require("./diagnostics.js");
|
|
4
4
|
const require_plugin_constants = require("../plugin/constants.js");
|
|
5
5
|
let _generaltranslation_format = require("@generaltranslation/format");
|
|
6
|
+
let generaltranslation_internal = require("generaltranslation/internal");
|
|
6
7
|
//#region src/errors/createErrors.ts
|
|
7
8
|
const remoteTranslationsError = require_errors_diagnostics.createGtNextDiagnostic({
|
|
8
9
|
severity: "Error",
|
|
@@ -91,6 +92,12 @@ const createInvalidRequestLocaleWarning = (locale, defaultLocale) => require_err
|
|
|
91
92
|
wayOut: `The default locale "${defaultLocale}" will be used for this request`,
|
|
92
93
|
fix: "Use a valid BCP 47 locale code, add a custom mapping, or configure the locale in gt-next"
|
|
93
94
|
});
|
|
95
|
+
const createInvalidMiddlewareRegexError = (regexFilter, error) => require_errors_diagnostics.createGtNextDiagnostic({
|
|
96
|
+
severity: "Error",
|
|
97
|
+
whatHappened: `regexFilter "${regexFilter}" is not a valid regular expression`,
|
|
98
|
+
fix: "Pass a valid JavaScript regular expression string to createNextMiddleware()",
|
|
99
|
+
details: (0, generaltranslation_internal.formatDiagnosticErrorDetails)(error)
|
|
100
|
+
});
|
|
94
101
|
const createBadFilepathWarning = (filename, dir) => require_errors_diagnostics.createGtNextDiagnostic({
|
|
95
102
|
whatHappened: `${filename} was found in ${dir.join(" or ")}, which is not supported`,
|
|
96
103
|
fix: "Move it to your project root so gt-next can load it"
|
|
@@ -133,6 +140,7 @@ exports.createBadFilepathWarning = createBadFilepathWarning;
|
|
|
133
140
|
exports.createDictionarySubsetError = createDictionarySubsetError;
|
|
134
141
|
exports.createGTCompilerUnavailableWarning = createGTCompilerUnavailableWarning;
|
|
135
142
|
exports.createGTCompilerUnresolvedWarning = createGTCompilerUnresolvedWarning;
|
|
143
|
+
exports.createInvalidMiddlewareRegexError = createInvalidMiddlewareRegexError;
|
|
136
144
|
exports.createInvalidRequestLocaleWarning = createInvalidRequestLocaleWarning;
|
|
137
145
|
exports.createUnresolvedNextVersionError = createUnresolvedNextVersionError;
|
|
138
146
|
exports.createUnresolvedReactVersionError = createUnresolvedReactVersionError;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createErrors.js","names":["createGtNextDiagnostic","createGtNextPluginDiagnostic","SWC_PLUGIN_SUPPORT","BABEL_PLUGIN_SUPPORT"],"sources":["../../src/errors/createErrors.ts"],"sourcesContent":["// ---- ERRORS ---- //\n\nimport { getLocaleProperties } from '@generaltranslation/format';\nimport {\n createGtNextDiagnostic,\n createGtNextPluginDiagnostic,\n} from './diagnostics';\nimport { BABEL_PLUGIN_SUPPORT, SWC_PLUGIN_SUPPORT } from '../plugin/constants';\n\nexport const remoteTranslationsError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Remote translations could not be loaded',\n fix: 'Check your project ID, API key, and network connection, then try again',\n wayOut: 'Source content will render as a fallback',\n});\n\nexport const customLoadTranslationsError = (locale: string = '') =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `Locally stored translations could not be loaded${locale ? ` for \"${locale}\"` : ''}`,\n fix: 'If you use loadTranslations(), make sure it returns translations for the requested locale',\n });\n\nexport const customLoadDictionaryWarning = (locale: string = '') =>\n createGtNextDiagnostic({\n severity: 'Warning',\n whatHappened: `The local dictionary could not be loaded${locale ? ` for \"${locale}\"` : ''}`,\n fix: 'If you use loadDictionary(), make sure it returns a dictionary for the requested locale',\n });\n\nexport const createUnresolvedNextVersionError = (error: Error) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'The installed Next.js version could not be resolved',\n fix: 'Check that next is installed in this project',\n details: error.message,\n });\n\nexport const createUnresolvedReactVersionError = (error: Error) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'The installed React version could not be resolved',\n fix: 'Check that react is installed in this project',\n details: error.message,\n });\n\nexport const devApiKeyIncludedInProductionError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Production builds cannot use a development API key',\n fix: 'Replace it with a production API key',\n});\n\nexport const createDictionarySubsetError = (id: string, functionName: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `${functionName} with id \"${id}\" could not read a valid dictionary subtree`,\n fix: 'Make sure the id maps to the correct subroute of the dictionary',\n });\n\nexport const unresolvedCustomLoadDictionaryError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened:\n 'loadDictionary() was found during the build but could not be resolved at runtime',\n fix: 'Export a loadDictionary() function from the configured file',\n});\n\nexport const unresolvedCustomLoadTranslationsError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened:\n 'loadTranslations() was found during the build but could not be resolved at runtime',\n fix: 'Export a loadTranslations() function from the configured file',\n});\n\nexport const unresolvedLoadDictionaryBuildError = (path: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The file defining loadDictionary() could not be resolved at ${path}`,\n fix: 'Check the configured path and try again',\n });\n\nexport const unresolvedLoadTranslationsBuildError = (path: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The file defining loadTranslations() could not be resolved at ${path}`,\n fix: 'Check the configured path and try again',\n });\n\nexport const conflictingConfigurationBuildError = (conflicts: string[]) =>\n `gt-next Error: Conflicting configuration${\n conflicts.length > 1 ? 's' : ''\n } detected. Resolve the following conflicts before building your app:\\n${conflicts.join(\n '\\n'\n )}`;\n\nexport const typesFileError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'A types-only entry point was executed at runtime',\n fix: 'Import from the appropriate gt-next runtime entry point instead',\n});\n\nexport const getTranslationsSnapshotRscError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened:\n 'getTranslationsSnapshot() is not available for React Server Components',\n fix: 'Use gt-next build-time translation helpers in the App Router, or call getTranslationsSnapshot() from a Pages Router entry point',\n});\n\nexport const invalidLocalesError = (locales: string[]) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Invalid locale codes in your configuration',\n fix: 'Specify a list of valid locales or use \"customMapping\" to define aliases for the invalid locales',\n details: locales,\n });\n\nexport const invalidCanonicalLocalesError = (locales: string[]) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Invalid canonical locale codes in your configuration',\n fix: 'Use valid BCP 47 locale codes before starting translation',\n details: locales,\n });\n\nexport const createInvalidRequestLocaleWarning = (\n locale: string,\n defaultLocale: string\n) =>\n createGtNextDiagnostic({\n severity: 'Warning',\n whatHappened: `Locale \"${locale}\" is not valid or is not supported by this app`,\n wayOut: `The default locale \"${defaultLocale}\" will be used for this request`,\n fix: 'Use a valid BCP 47 locale code, add a custom mapping, or configure the locale in gt-next',\n });\n\n// ---- WARNINGS ---- //\n\nexport const createBadFilepathWarning = (filename: string, dir: string[]) =>\n createGtNextDiagnostic({\n whatHappened: `${filename} was found in ${dir.join(' or ')}, which is not supported`,\n fix: 'Move it to your project root so gt-next can load it',\n });\n\nexport const createUnsupportedLocalesWarning = (locales: string[]) =>\n `gt-next: The following locales are currently unsupported by our service: ${locales\n .map((locale) => {\n const { name } = getLocaleProperties(locale);\n return `${locale} (${name})`;\n })\n .join(', ')}`;\n\nexport const projectIdMissingWarn = createGtNextDiagnostic({\n whatHappened: 'Runtime translation needs a project ID',\n fix: 'Set GT_PROJECT_ID in your environment or pass projectId to withGTConfig()',\n docsUrl: 'https://generaltranslation.com/dashboard',\n});\n\nexport const APIKeyMissingWarn = createGtNextPluginDiagnostic({\n whatHappened: 'Runtime translation needs a development API key',\n fix: 'Find your development API key at generaltranslation.com/dashboard, or set runtimeUrl to an empty string to disable runtime translation',\n});\n\nexport const standardizedLocalesWarning = (locales: string[]) =>\n `gt-next: The following locales were standardized: ${locales.join(', ')}. Use the standardized codes in your config to avoid this warning.`;\n\nexport const standardizedCanonicalLocalesWarning = (locales: string[]) =>\n `gt-next: The following canonical locales were standardized: ${locales.join(', ')}. Use the standardized codes in your config to avoid this warning.`;\n\nexport const createGTCompilerUnresolvedWarning = (type: 'babel' | 'swc') =>\n `gt-next (plugin): The GT ${type} compiler could not be resolved. Skipping compiler optimizations.`;\n\nexport const customGetLocaleUnresolvedWarning = createGtNextDiagnostic({\n whatHappened: 'Custom getLocale() could not be resolved',\n wayOut: 'gt-next will fall back to default locale detection',\n fix: 'Export a getLocale() function from the configured request file',\n});\n\nexport const customGetRegionUnresolvedWarning = createGtNextDiagnostic({\n whatHappened: 'Custom getRegion() could not be resolved',\n wayOut: 'gt-next will fall back to default region detection',\n fix: 'Export a getRegion() function from the configured request file',\n});\n\nexport const createGTCompilerUnavailableWarning = (type: 'babel' | 'swc') =>\n type === 'swc'\n ? `gt-next (plugin): The GT swc compiler is compatible with < next@${SWC_PLUGIN_SUPPORT}. Skipping compiler optimizations.`\n : `gt-next (plugin): The GT babel compiler requires react@${BABEL_PLUGIN_SUPPORT} or newer. Skipping compiler optimizations.`;\n\nexport const babelCompilerTurbopackUnavailableWarning =\n `gt-next (plugin): The GT babel compiler is not compatible with Turbopack. ` +\n `To use compiler optimizations with Turbopack, set experimentalCompilerOptions: { type: 'swc' }.`;\n\nexport const disablingCompileTimeHashWarning = `gt-next (plugin): Compile-time hash is disabled. Compiler optimizations are inactive.`;\n\nexport const swcPluginCompatibilityChangeWarning = `gt-next (plugin): As of gt-next@6.12.4, SWC plugin support is disabled for Next.js versions prior to ${SWC_PLUGIN_SUPPORT}. Update to the latest version of Next.js.`;\n"],"mappings":";;;;;;AASA,MAAa,0BAA0BA,2BAAAA,uBAAuB;CAC5D,UAAU;CACV,cAAc;CACd,KAAK;CACL,QAAQ;CACT,CAAC;AAEF,MAAa,+BAA+B,SAAiB,OAC3DA,2BAAAA,uBAAuB;CACrB,UAAU;CACV,cAAc,kDAAkD,SAAS,SAAS,OAAO,KAAK;CAC9F,KAAK;CACN,CAAC;AAEJ,MAAa,+BAA+B,SAAiB,OAC3DA,2BAAAA,uBAAuB;CACrB,UAAU;CACV,cAAc,2CAA2C,SAAS,SAAS,OAAO,KAAK;CACvF,KAAK;CACN,CAAC;AAEJ,MAAa,oCAAoC,UAC/CA,2BAAAA,uBAAuB;CACrB,UAAU;CACV,cAAc;CACd,KAAK;CACL,SAAS,MAAM;CAChB,CAAC;AAEJ,MAAa,qCAAqC,UAChDA,2BAAAA,uBAAuB;CACrB,UAAU;CACV,cAAc;CACd,KAAK;CACL,SAAS,MAAM;CAChB,CAAC;AAEJ,MAAa,qCAAqCA,2BAAAA,uBAAuB;CACvE,UAAU;CACV,cAAc;CACd,KAAK;CACN,CAAC;AAEF,MAAa,+BAA+B,IAAY,iBACtDA,2BAAAA,uBAA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M,EAAE,UAAA,GAAA,2BAAA,qBAA6B,OAAO;AAC5C,QAAO,GAAG,OAAO,IAAI,KAAK;EAC1B,CACD,KAAK,KAAK;AAEf,MAAa,uBAAuBA,2BAAAA,uBAAuB;CACzD,cAAc;CACd,KAAK;CACL,SAAS;CACV,CAAC;AAEF,MAAa,oBAAoBC,2BAAAA,6BAA6B;CAC5D,cAAc;CACd,KAAK;CACN,CAAC;AAEF,MAAa,8BAA8B,YACzC,qDAAqD,QAAQ,KAAK,KAAK,CAAC;AAE1E,MAAa,uCAAuC,YAClD,+DAA+D,QAAQ,KAAK,KAAK,CAAC;AAEpF,MAAa,qCAAqC,SAChD,4BAA4B,KAAK;AAEnC,MAAa,mCAAmCD,2BAAAA,uBAAuB;CACrE,cAAc;CACd,QAAQ;CACR,KAAK;CACN,CAAC;AAEF,MAAa,mCAAmCA,2BAAAA,uBAAuB;CACrE,cAAc;CACd,QAAQ;CACR,KAAK;CACN,CAAC;AAEF,MAAa,sCAAsC,SACjD,SAAS,QACL,mEAAmEE,yBAAAA,mBAAmB,sCACtF,0DAA0DC,yBAAAA,qBAAqB;AAErF,MAAa,2CACX;AAGF,MAAa,kCAAkC;AAE/C,MAAa,sCAAsC,wGAAwGD,yBAAAA,mBAAmB"}
|
|
1
|
+
{"version":3,"file":"createErrors.js","names":["createGtNextDiagnostic","createGtNextPluginDiagnostic","SWC_PLUGIN_SUPPORT","BABEL_PLUGIN_SUPPORT"],"sources":["../../src/errors/createErrors.ts"],"sourcesContent":["// ---- ERRORS ---- //\n\nimport { getLocaleProperties } from '@generaltranslation/format';\nimport {\n createGtNextDiagnostic,\n createGtNextPluginDiagnostic,\n formatDiagnosticErrorDetails,\n} from './diagnostics';\nimport { BABEL_PLUGIN_SUPPORT, SWC_PLUGIN_SUPPORT } from '../plugin/constants';\n\nexport const remoteTranslationsError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Remote translations could not be loaded',\n fix: 'Check your project ID, API key, and network connection, then try again',\n wayOut: 'Source content will render as a fallback',\n});\n\nexport const customLoadTranslationsError = (locale: string = '') =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `Locally stored translations could not be loaded${locale ? ` for \"${locale}\"` : ''}`,\n fix: 'If you use loadTranslations(), make sure it returns translations for the requested locale',\n });\n\nexport const customLoadDictionaryWarning = (locale: string = '') =>\n createGtNextDiagnostic({\n severity: 'Warning',\n whatHappened: `The local dictionary could not be loaded${locale ? ` for \"${locale}\"` : ''}`,\n fix: 'If you use loadDictionary(), make sure it returns a dictionary for the requested locale',\n });\n\nexport const createUnresolvedNextVersionError = (error: Error) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'The installed Next.js version could not be resolved',\n fix: 'Check that next is installed in this project',\n details: error.message,\n });\n\nexport const createUnresolvedReactVersionError = (error: Error) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'The installed React version could not be resolved',\n fix: 'Check that react is installed in this project',\n details: error.message,\n });\n\nexport const devApiKeyIncludedInProductionError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Production builds cannot use a development API key',\n fix: 'Replace it with a production API key',\n});\n\nexport const createDictionarySubsetError = (id: string, functionName: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `${functionName} with id \"${id}\" could not read a valid dictionary subtree`,\n fix: 'Make sure the id maps to the correct subroute of the dictionary',\n });\n\nexport const unresolvedCustomLoadDictionaryError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened:\n 'loadDictionary() was found during the build but could not be resolved at runtime',\n fix: 'Export a loadDictionary() function from the configured file',\n});\n\nexport const unresolvedCustomLoadTranslationsError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened:\n 'loadTranslations() was found during the build but could not be resolved at runtime',\n fix: 'Export a loadTranslations() function from the configured file',\n});\n\nexport const unresolvedLoadDictionaryBuildError = (path: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The file defining loadDictionary() could not be resolved at ${path}`,\n fix: 'Check the configured path and try again',\n });\n\nexport const unresolvedLoadTranslationsBuildError = (path: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The file defining loadTranslations() could not be resolved at ${path}`,\n fix: 'Check the configured path and try again',\n });\n\nexport const conflictingConfigurationBuildError = (conflicts: string[]) =>\n `gt-next Error: Conflicting configuration${\n conflicts.length > 1 ? 's' : ''\n } detected. Resolve the following conflicts before building your app:\\n${conflicts.join(\n '\\n'\n )}`;\n\nexport const typesFileError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'A types-only entry point was executed at runtime',\n fix: 'Import from the appropriate gt-next runtime entry point instead',\n});\n\nexport const getTranslationsSnapshotRscError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened:\n 'getTranslationsSnapshot() is not available for React Server Components',\n fix: 'Use gt-next build-time translation helpers in the App Router, or call getTranslationsSnapshot() from a Pages Router entry point',\n});\n\nexport const invalidLocalesError = (locales: string[]) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Invalid locale codes in your configuration',\n fix: 'Specify a list of valid locales or use \"customMapping\" to define aliases for the invalid locales',\n details: locales,\n });\n\nexport const invalidCanonicalLocalesError = (locales: string[]) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Invalid canonical locale codes in your configuration',\n fix: 'Use valid BCP 47 locale codes before starting translation',\n details: locales,\n });\n\nexport const createInvalidRequestLocaleWarning = (\n locale: string,\n defaultLocale: string\n) =>\n createGtNextDiagnostic({\n severity: 'Warning',\n whatHappened: `Locale \"${locale}\" is not valid or is not supported by this app`,\n wayOut: `The default locale \"${defaultLocale}\" will be used for this request`,\n fix: 'Use a valid BCP 47 locale code, add a custom mapping, or configure the locale in gt-next',\n });\n\nexport const createInvalidMiddlewareRegexError = (\n regexFilter: string,\n error: unknown\n) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `regexFilter \"${regexFilter}\" is not a valid regular expression`,\n fix: 'Pass a valid JavaScript regular expression string to createNextMiddleware()',\n details: formatDiagnosticErrorDetails(error),\n });\n\n// ---- WARNINGS ---- //\n\nexport const createBadFilepathWarning = (filename: string, dir: string[]) =>\n createGtNextDiagnostic({\n whatHappened: `${filename} was found in ${dir.join(' or ')}, which is not supported`,\n fix: 'Move it to your project root so gt-next can load it',\n });\n\nexport const createUnsupportedLocalesWarning = (locales: string[]) =>\n `gt-next: The following locales are currently unsupported by our service: ${locales\n .map((locale) => {\n const { name } = getLocaleProperties(locale);\n return `${locale} (${name})`;\n })\n .join(', ')}`;\n\nexport const projectIdMissingWarn = createGtNextDiagnostic({\n whatHappened: 'Runtime translation needs a project ID',\n fix: 'Set GT_PROJECT_ID in your environment or pass projectId to withGTConfig()',\n docsUrl: 'https://generaltranslation.com/dashboard',\n});\n\nexport const APIKeyMissingWarn = createGtNextPluginDiagnostic({\n whatHappened: 'Runtime translation needs a development API key',\n fix: 'Find your development API key at generaltranslation.com/dashboard, or set runtimeUrl to an empty string to disable runtime translation',\n});\n\nexport const standardizedLocalesWarning = (locales: string[]) =>\n `gt-next: The following locales were standardized: ${locales.join(', ')}. Use the standardized codes in your config to avoid this warning.`;\n\nexport const standardizedCanonicalLocalesWarning = (locales: string[]) =>\n `gt-next: The following canonical locales were standardized: ${locales.join(', ')}. Use the standardized codes in your config to avoid this warning.`;\n\nexport const createGTCompilerUnresolvedWarning = (type: 'babel' | 'swc') =>\n `gt-next (plugin): The GT ${type} compiler could not be resolved. Skipping compiler optimizations.`;\n\nexport const customGetLocaleUnresolvedWarning = createGtNextDiagnostic({\n whatHappened: 'Custom getLocale() could not be resolved',\n wayOut: 'gt-next will fall back to default locale detection',\n fix: 'Export a getLocale() function from the configured request file',\n});\n\nexport const customGetRegionUnresolvedWarning = createGtNextDiagnostic({\n whatHappened: 'Custom getRegion() could not be resolved',\n wayOut: 'gt-next will fall back to default region detection',\n fix: 'Export a getRegion() function from the configured request file',\n});\n\nexport const createGTCompilerUnavailableWarning = (type: 'babel' | 'swc') =>\n type === 'swc'\n ? `gt-next (plugin): The GT swc compiler is compatible with < next@${SWC_PLUGIN_SUPPORT}. Skipping compiler optimizations.`\n : `gt-next (plugin): The GT babel compiler requires react@${BABEL_PLUGIN_SUPPORT} or newer. Skipping compiler optimizations.`;\n\nexport const babelCompilerTurbopackUnavailableWarning =\n `gt-next (plugin): The GT babel compiler is not compatible with Turbopack. ` +\n `To use compiler optimizations with Turbopack, set experimentalCompilerOptions: { type: 'swc' }.`;\n\nexport const disablingCompileTimeHashWarning = `gt-next (plugin): Compile-time hash is disabled. Compiler optimizations are inactive.`;\n\nexport const swcPluginCompatibilityChangeWarning = `gt-next (plugin): As of gt-next@6.12.4, SWC plugin support is disabled for Next.js versions prior to ${SWC_PLUGIN_SUPPORT}. Update to the latest version of Next.js.`;\n"],"mappings":";;;;;;;AAUA,MAAa,0BAA0BA,2BAAAA,uBAAuB;CAC5D,UAAU;CACV,cAAc;CACd,KAAK;CACL,QAAQ;CACT,CAAC;AAEF,MAAa,+BAA+B,SAAiB,OAC3DA,2BAAAA,uBAAuB;CACrB,UAAU;CACV,cAAc,kDAAkD,SAAS,SAAS,OAAO,KAAK;CAC9F,KAAK;CACN,CAAC;AAEJ,MAAa,+BAA+B,SAAiB,OAC3DA,2BAAAA,uBAAuB;CACrB,UAAU;CACV,cAAc,2CAA2C,SAAS,SAAS,OAAO,KAAK;CACvF,KAAK;CACN,CAAC;AAEJ,MAAa,oCAAoC,UAC/CA,2BAAAA,uBAAuB;CACrB,UAAU;CACV,cAAc;CACd,KAAK;CACL,SAAS,MAAM;CAChB,CAAC;AAEJ,MAAa,qCAAqC,UAChDA,2BAAAA,uBAAuB;CACrB,UAAU;CACV,cAAc;CACd,KAAK;CACL,SAAS,MAAM;CAChB,CAAC;AAEJ,MAAa,qCAAqCA,2BAAAA,uBAAuB;CACvE,UAAU;CACV,cAAc;CACd,KAAK;CACN,CAAC;AAEF,MAAa,+BAA+B,IAAY,iBACtDA,2BAAAA,uBAAuB;CACrB,UAAU;CACV,cAAc,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AS,gBAAgB,IAAI,KAAK,OAAO,CAAC;CAC3D,KAAK;CACN,CAAC;AAEJ,MAAa,mCAAmC,YAC9C,4EAA4E,QACzE,KAAK,WAAW;CACf,MAAM,EAAE,UAAA,GAAA,2BAAA,qBAA6B,OAAO;AAC5C,QAAO,GAAG,OAAO,IAAI,KAAK;EAC1B,CACD,KAAK,KAAK;AAEf,MAAa,uBAAuBA,2BAAAA,uBAAuB;CACzD,cAAc;CACd,KAAK;CACL,SAAS;CACV,CAAC;AAEF,MAAa,oBAAoBC,2BAAAA,6BAA6B;CAC5D,cAAc;CACd,KAAK;CACN,CAAC;AAEF,MAAa,8BAA8B,YACzC,qDAAqD,QAAQ,KAAK,KAAK,CAAC;AAE1E,MAAa,uCAAuC,YAClD,+DAA+D,QAAQ,KAAK,KAAK,CAAC;AAEpF,MAAa,qCAAqC,SAChD,4BAA4B,KAAK;AAEnC,MAAa,mCAAmCD,2BAAAA,uBAAuB;CACrE,cAAc;CACd,QAAQ;CACR,KAAK;CACN,CAAC;AAEF,MAAa,mCAAmCA,2BAAAA,uBAAuB;CACrE,cAAc;CACd,QAAQ;CACR,KAAK;CACN,CAAC;AAEF,MAAa,sCAAsC,SACjD,SAAS,QACL,mEAAmEE,yBAAAA,mBAAmB,sCACtF,0DAA0DC,yBAAAA,qBAAqB;AAErF,MAAa,2CACX;AAGF,MAAa,kCAAkC;AAE/C,MAAa,sCAAsC,wGAAwGD,yBAAAA,mBAAmB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createGtNextDiagnostic, createGtNextPluginDiagnostic } from "./diagnostics.mjs";
|
|
1
|
+
import { createGtNextDiagnostic, createGtNextPluginDiagnostic, formatDiagnosticErrorDetails } from "./diagnostics.mjs";
|
|
2
2
|
import { BABEL_PLUGIN_SUPPORT, SWC_PLUGIN_SUPPORT } from "../plugin/constants.mjs";
|
|
3
3
|
import { getLocaleProperties } from "@generaltranslation/format";
|
|
4
4
|
//#region src/errors/createErrors.ts
|
|
@@ -89,6 +89,12 @@ const createInvalidRequestLocaleWarning = (locale, defaultLocale) => createGtNex
|
|
|
89
89
|
wayOut: `The default locale "${defaultLocale}" will be used for this request`,
|
|
90
90
|
fix: "Use a valid BCP 47 locale code, add a custom mapping, or configure the locale in gt-next"
|
|
91
91
|
});
|
|
92
|
+
const createInvalidMiddlewareRegexError = (regexFilter, error) => createGtNextDiagnostic({
|
|
93
|
+
severity: "Error",
|
|
94
|
+
whatHappened: `regexFilter "${regexFilter}" is not a valid regular expression`,
|
|
95
|
+
fix: "Pass a valid JavaScript regular expression string to createNextMiddleware()",
|
|
96
|
+
details: formatDiagnosticErrorDetails(error)
|
|
97
|
+
});
|
|
92
98
|
const createBadFilepathWarning = (filename, dir) => createGtNextDiagnostic({
|
|
93
99
|
whatHappened: `${filename} was found in ${dir.join(" or ")}, which is not supported`,
|
|
94
100
|
fix: "Move it to your project root so gt-next can load it"
|
|
@@ -124,6 +130,6 @@ const babelCompilerTurbopackUnavailableWarning = "gt-next (plugin): The GT babel
|
|
|
124
130
|
const disablingCompileTimeHashWarning = `gt-next (plugin): Compile-time hash is disabled. Compiler optimizations are inactive.`;
|
|
125
131
|
const swcPluginCompatibilityChangeWarning = `gt-next (plugin): As of gt-next@6.12.4, SWC plugin support is disabled for Next.js versions prior to ${SWC_PLUGIN_SUPPORT}. Update to the latest version of Next.js.`;
|
|
126
132
|
//#endregion
|
|
127
|
-
export { APIKeyMissingWarn, babelCompilerTurbopackUnavailableWarning, conflictingConfigurationBuildError, createBadFilepathWarning, createDictionarySubsetError, createGTCompilerUnavailableWarning, createGTCompilerUnresolvedWarning, createInvalidRequestLocaleWarning, createUnresolvedNextVersionError, createUnresolvedReactVersionError, createUnsupportedLocalesWarning, customGetLocaleUnresolvedWarning, customGetRegionUnresolvedWarning, customLoadDictionaryWarning, customLoadTranslationsError, devApiKeyIncludedInProductionError, disablingCompileTimeHashWarning, getTranslationsSnapshotRscError, invalidCanonicalLocalesError, invalidLocalesError, projectIdMissingWarn, remoteTranslationsError, standardizedCanonicalLocalesWarning, standardizedLocalesWarning, swcPluginCompatibilityChangeWarning, typesFileError, unresolvedCustomLoadDictionaryError, unresolvedCustomLoadTranslationsError, unresolvedLoadDictionaryBuildError, unresolvedLoadTranslationsBuildError };
|
|
133
|
+
export { APIKeyMissingWarn, babelCompilerTurbopackUnavailableWarning, conflictingConfigurationBuildError, createBadFilepathWarning, createDictionarySubsetError, createGTCompilerUnavailableWarning, createGTCompilerUnresolvedWarning, createInvalidMiddlewareRegexError, createInvalidRequestLocaleWarning, createUnresolvedNextVersionError, createUnresolvedReactVersionError, createUnsupportedLocalesWarning, customGetLocaleUnresolvedWarning, customGetRegionUnresolvedWarning, customLoadDictionaryWarning, customLoadTranslationsError, devApiKeyIncludedInProductionError, disablingCompileTimeHashWarning, getTranslationsSnapshotRscError, invalidCanonicalLocalesError, invalidLocalesError, projectIdMissingWarn, remoteTranslationsError, standardizedCanonicalLocalesWarning, standardizedLocalesWarning, swcPluginCompatibilityChangeWarning, typesFileError, unresolvedCustomLoadDictionaryError, unresolvedCustomLoadTranslationsError, unresolvedLoadDictionaryBuildError, unresolvedLoadTranslationsBuildError };
|
|
128
134
|
|
|
129
135
|
//# sourceMappingURL=createErrors.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createErrors.mjs","names":[],"sources":["../../src/errors/createErrors.ts"],"sourcesContent":["// ---- ERRORS ---- //\n\nimport { getLocaleProperties } from '@generaltranslation/format';\nimport {\n createGtNextDiagnostic,\n createGtNextPluginDiagnostic,\n} from './diagnostics';\nimport { BABEL_PLUGIN_SUPPORT, SWC_PLUGIN_SUPPORT } from '../plugin/constants';\n\nexport const remoteTranslationsError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Remote translations could not be loaded',\n fix: 'Check your project ID, API key, and network connection, then try again',\n wayOut: 'Source content will render as a fallback',\n});\n\nexport const customLoadTranslationsError = (locale: string = '') =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `Locally stored translations could not be loaded${locale ? ` for \"${locale}\"` : ''}`,\n fix: 'If you use loadTranslations(), make sure it returns translations for the requested locale',\n });\n\nexport const customLoadDictionaryWarning = (locale: string = '') =>\n createGtNextDiagnostic({\n severity: 'Warning',\n whatHappened: `The local dictionary could not be loaded${locale ? ` for \"${locale}\"` : ''}`,\n fix: 'If you use loadDictionary(), make sure it returns a dictionary for the requested locale',\n });\n\nexport const createUnresolvedNextVersionError = (error: Error) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'The installed Next.js version could not be resolved',\n fix: 'Check that next is installed in this project',\n details: error.message,\n });\n\nexport const createUnresolvedReactVersionError = (error: Error) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'The installed React version could not be resolved',\n fix: 'Check that react is installed in this project',\n details: error.message,\n });\n\nexport const devApiKeyIncludedInProductionError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Production builds cannot use a development API key',\n fix: 'Replace it with a production API key',\n});\n\nexport const createDictionarySubsetError = (id: string, functionName: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `${functionName} with id \"${id}\" could not read a valid dictionary subtree`,\n fix: 'Make sure the id maps to the correct subroute of the dictionary',\n });\n\nexport const unresolvedCustomLoadDictionaryError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened:\n 'loadDictionary() was found during the build but could not be resolved at runtime',\n fix: 'Export a loadDictionary() function from the configured file',\n});\n\nexport const unresolvedCustomLoadTranslationsError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened:\n 'loadTranslations() was found during the build but could not be resolved at runtime',\n fix: 'Export a loadTranslations() function from the configured file',\n});\n\nexport const unresolvedLoadDictionaryBuildError = (path: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The file defining loadDictionary() could not be resolved at ${path}`,\n fix: 'Check the configured path and try again',\n });\n\nexport const unresolvedLoadTranslationsBuildError = (path: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The file defining loadTranslations() could not be resolved at ${path}`,\n fix: 'Check the configured path and try again',\n });\n\nexport const conflictingConfigurationBuildError = (conflicts: string[]) =>\n `gt-next Error: Conflicting configuration${\n conflicts.length > 1 ? 's' : ''\n } detected. Resolve the following conflicts before building your app:\\n${conflicts.join(\n '\\n'\n )}`;\n\nexport const typesFileError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'A types-only entry point was executed at runtime',\n fix: 'Import from the appropriate gt-next runtime entry point instead',\n});\n\nexport const getTranslationsSnapshotRscError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened:\n 'getTranslationsSnapshot() is not available for React Server Components',\n fix: 'Use gt-next build-time translation helpers in the App Router, or call getTranslationsSnapshot() from a Pages Router entry point',\n});\n\nexport const invalidLocalesError = (locales: string[]) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Invalid locale codes in your configuration',\n fix: 'Specify a list of valid locales or use \"customMapping\" to define aliases for the invalid locales',\n details: locales,\n });\n\nexport const invalidCanonicalLocalesError = (locales: string[]) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Invalid canonical locale codes in your configuration',\n fix: 'Use valid BCP 47 locale codes before starting translation',\n details: locales,\n });\n\nexport const createInvalidRequestLocaleWarning = (\n locale: string,\n defaultLocale: string\n) =>\n createGtNextDiagnostic({\n severity: 'Warning',\n whatHappened: `Locale \"${locale}\" is not valid or is not supported by this app`,\n wayOut: `The default locale \"${defaultLocale}\" will be used for this request`,\n fix: 'Use a valid BCP 47 locale code, add a custom mapping, or configure the locale in gt-next',\n });\n\n// ---- WARNINGS ---- //\n\nexport const createBadFilepathWarning = (filename: string, dir: string[]) =>\n createGtNextDiagnostic({\n whatHappened: `${filename} was found in ${dir.join(' or ')}, which is not supported`,\n fix: 'Move it to your project root so gt-next can load it',\n });\n\nexport const createUnsupportedLocalesWarning = (locales: string[]) =>\n `gt-next: The following locales are currently unsupported by our service: ${locales\n .map((locale) => {\n const { name } = getLocaleProperties(locale);\n return `${locale} (${name})`;\n })\n .join(', ')}`;\n\nexport const projectIdMissingWarn = createGtNextDiagnostic({\n whatHappened: 'Runtime translation needs a project ID',\n fix: 'Set GT_PROJECT_ID in your environment or pass projectId to withGTConfig()',\n docsUrl: 'https://generaltranslation.com/dashboard',\n});\n\nexport const APIKeyMissingWarn = createGtNextPluginDiagnostic({\n whatHappened: 'Runtime translation needs a development API key',\n fix: 'Find your development API key at generaltranslation.com/dashboard, or set runtimeUrl to an empty string to disable runtime translation',\n});\n\nexport const standardizedLocalesWarning = (locales: string[]) =>\n `gt-next: The following locales were standardized: ${locales.join(', ')}. Use the standardized codes in your config to avoid this warning.`;\n\nexport const standardizedCanonicalLocalesWarning = (locales: string[]) =>\n `gt-next: The following canonical locales were standardized: ${locales.join(', ')}. Use the standardized codes in your config to avoid this warning.`;\n\nexport const createGTCompilerUnresolvedWarning = (type: 'babel' | 'swc') =>\n `gt-next (plugin): The GT ${type} compiler could not be resolved. Skipping compiler optimizations.`;\n\nexport const customGetLocaleUnresolvedWarning = createGtNextDiagnostic({\n whatHappened: 'Custom getLocale() could not be resolved',\n wayOut: 'gt-next will fall back to default locale detection',\n fix: 'Export a getLocale() function from the configured request file',\n});\n\nexport const customGetRegionUnresolvedWarning = createGtNextDiagnostic({\n whatHappened: 'Custom getRegion() could not be resolved',\n wayOut: 'gt-next will fall back to default region detection',\n fix: 'Export a getRegion() function from the configured request file',\n});\n\nexport const createGTCompilerUnavailableWarning = (type: 'babel' | 'swc') =>\n type === 'swc'\n ? `gt-next (plugin): The GT swc compiler is compatible with < next@${SWC_PLUGIN_SUPPORT}. Skipping compiler optimizations.`\n : `gt-next (plugin): The GT babel compiler requires react@${BABEL_PLUGIN_SUPPORT} or newer. Skipping compiler optimizations.`;\n\nexport const babelCompilerTurbopackUnavailableWarning =\n `gt-next (plugin): The GT babel compiler is not compatible with Turbopack. ` +\n `To use compiler optimizations with Turbopack, set experimentalCompilerOptions: { type: 'swc' }.`;\n\nexport const disablingCompileTimeHashWarning = `gt-next (plugin): Compile-time hash is disabled. Compiler optimizations are inactive.`;\n\nexport const swcPluginCompatibilityChangeWarning = `gt-next (plugin): As of gt-next@6.12.4, SWC plugin support is disabled for Next.js versions prior to ${SWC_PLUGIN_SUPPORT}. Update to the latest version of Next.js.`;\n"],"mappings":";;;;AASA,MAAa,0BAA0B,uBAAuB;CAC5D,UAAU;CACV,cAAc;CACd,KAAK;CACL,QAAQ;CACT,CAAC;AAEF,MAAa,+BAA+B,SAAiB,OAC3D,uBAAuB;CACrB,UAAU;CACV,cAAc,kDAAkD,SAAS,SAAS,OAAO,KAAK;CAC9F,KAAK;CACN,CAAC;AAEJ,MAAa,+BAA+B,SAAiB,OAC3D,uBAAuB;CACrB,UAAU;CACV,cAAc,2CAA2C,SAAS,SAAS,OAAO,KAAK;CACvF,KAAK;CACN,CAAC;AAEJ,MAAa,oCAAoC,UAC/C,uBAAuB;CACrB,UAAU;CACV,cAAc;CACd,KAAK;CACL,SAAS,MAAM;CAChB,CAAC;AAEJ,MAAa,qCAAqC,UAChD,uBAAuB;CACrB,UAAU;CACV,cAAc;CACd,KAAK;CACL,SAAS,MAAM;CAChB,CAAC;AAEJ,MAAa,qCAAqC,uBAAuB;CACvE,UAAU;CACV,cAAc;CACd,KAAK;CACN,CAAC;AAEF,MAAa,+BAA+B,IAAY,iBACtD,uBAAuB;CACrB,UAAU;CACV,cAAc,GAAG,aAAa,YAAY,GAAG;CAC7C,KAAK;CACN,CAAC;AAEJ,MAAa,sCAAsC,uBAAuB;CACxE,UAAU;CACV,cACE;CACF,KAAK;CACN,CAAC;AAEF,MAAa,wCAAwC,uBAAuB;CAC1E,UAAU;CACV,cACE;CACF,KAAK;CACN,CAAC;AAEF,MAAa,sCAAsC,SACjD,uBAAuB;CACrB,UAAU;CACV,cAAc,+DAA+D;CAC7E,KAAK;CACN,CAAC;AAEJ,MAAa,wCAAwC,SACnD,uBAAuB;CACrB,UAAU;CACV,cAAc,iEAAiE;C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a,mCAAmC,uBAAuB;CACrE,cAAc;CACd,QAAQ;CACR,KAAK;CACN,CAAC;AAEF,MAAa,sCAAsC,SACjD,SAAS,QACL,mEAAmE,mBAAmB,sCACtF,0DAA0D,qBAAqB;AAErF,MAAa,2CACX;AAGF,MAAa,kCAAkC;AAE/C,MAAa,sCAAsC,wGAAwG,mBAAmB"}
|
|
1
|
+
{"version":3,"file":"createErrors.mjs","names":[],"sources":["../../src/errors/createErrors.ts"],"sourcesContent":["// ---- ERRORS ---- //\n\nimport { getLocaleProperties } from '@generaltranslation/format';\nimport {\n createGtNextDiagnostic,\n createGtNextPluginDiagnostic,\n formatDiagnosticErrorDetails,\n} from './diagnostics';\nimport { BABEL_PLUGIN_SUPPORT, SWC_PLUGIN_SUPPORT } from '../plugin/constants';\n\nexport const remoteTranslationsError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Remote translations could not be loaded',\n fix: 'Check your project ID, API key, and network connection, then try again',\n wayOut: 'Source content will render as a fallback',\n});\n\nexport const customLoadTranslationsError = (locale: string = '') =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `Locally stored translations could not be loaded${locale ? ` for \"${locale}\"` : ''}`,\n fix: 'If you use loadTranslations(), make sure it returns translations for the requested locale',\n });\n\nexport const customLoadDictionaryWarning = (locale: string = '') =>\n createGtNextDiagnostic({\n severity: 'Warning',\n whatHappened: `The local dictionary could not be loaded${locale ? ` for \"${locale}\"` : ''}`,\n fix: 'If you use loadDictionary(), make sure it returns a dictionary for the requested locale',\n });\n\nexport const createUnresolvedNextVersionError = (error: Error) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'The installed Next.js version could not be resolved',\n fix: 'Check that next is installed in this project',\n details: error.message,\n });\n\nexport const createUnresolvedReactVersionError = (error: Error) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'The installed React version could not be resolved',\n fix: 'Check that react is installed in this project',\n details: error.message,\n });\n\nexport const devApiKeyIncludedInProductionError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Production builds cannot use a development API key',\n fix: 'Replace it with a production API key',\n});\n\nexport const createDictionarySubsetError = (id: string, functionName: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `${functionName} with id \"${id}\" could not read a valid dictionary subtree`,\n fix: 'Make sure the id maps to the correct subroute of the dictionary',\n });\n\nexport const unresolvedCustomLoadDictionaryError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened:\n 'loadDictionary() was found during the build but could not be resolved at runtime',\n fix: 'Export a loadDictionary() function from the configured file',\n});\n\nexport const unresolvedCustomLoadTranslationsError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened:\n 'loadTranslations() was found during the build but could not be resolved at runtime',\n fix: 'Export a loadTranslations() function from the configured file',\n});\n\nexport const unresolvedLoadDictionaryBuildError = (path: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The file defining loadDictionary() could not be resolved at ${path}`,\n fix: 'Check the configured path and try again',\n });\n\nexport const unresolvedLoadTranslationsBuildError = (path: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The file defining loadTranslations() could not be resolved at ${path}`,\n fix: 'Check the configured path and try again',\n });\n\nexport const conflictingConfigurationBuildError = (conflicts: string[]) =>\n `gt-next Error: Conflicting configuration${\n conflicts.length > 1 ? 's' : ''\n } detected. Resolve the following conflicts before building your app:\\n${conflicts.join(\n '\\n'\n )}`;\n\nexport const typesFileError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'A types-only entry point was executed at runtime',\n fix: 'Import from the appropriate gt-next runtime entry point instead',\n});\n\nexport const getTranslationsSnapshotRscError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened:\n 'getTranslationsSnapshot() is not available for React Server Components',\n fix: 'Use gt-next build-time translation helpers in the App Router, or call getTranslationsSnapshot() from a Pages Router entry point',\n});\n\nexport const invalidLocalesError = (locales: string[]) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Invalid locale codes in your configuration',\n fix: 'Specify a list of valid locales or use \"customMapping\" to define aliases for the invalid locales',\n details: locales,\n });\n\nexport const invalidCanonicalLocalesError = (locales: string[]) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Invalid canonical locale codes in your configuration',\n fix: 'Use valid BCP 47 locale codes before starting translation',\n details: locales,\n });\n\nexport const createInvalidRequestLocaleWarning = (\n locale: string,\n defaultLocale: string\n) =>\n createGtNextDiagnostic({\n severity: 'Warning',\n whatHappened: `Locale \"${locale}\" is not valid or is not supported by this app`,\n wayOut: `The default locale \"${defaultLocale}\" will be used for this request`,\n fix: 'Use a valid BCP 47 locale code, add a custom mapping, or configure the locale in gt-next',\n });\n\nexport const createInvalidMiddlewareRegexError = (\n regexFilter: string,\n error: unknown\n) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `regexFilter \"${regexFilter}\" is not a valid regular expression`,\n fix: 'Pass a valid JavaScript regular expression string to createNextMiddleware()',\n details: formatDiagnosticErrorDetails(error),\n });\n\n// ---- WARNINGS ---- //\n\nexport const createBadFilepathWarning = (filename: string, dir: string[]) =>\n createGtNextDiagnostic({\n whatHappened: `${filename} was found in ${dir.join(' or ')}, which is not supported`,\n fix: 'Move it to your project root so gt-next can load it',\n });\n\nexport const createUnsupportedLocalesWarning = (locales: string[]) =>\n `gt-next: The following locales are currently unsupported by our service: ${locales\n .map((locale) => {\n const { name } = getLocaleProperties(locale);\n return `${locale} (${name})`;\n })\n .join(', ')}`;\n\nexport const projectIdMissingWarn = createGtNextDiagnostic({\n whatHappened: 'Runtime translation needs a project ID',\n fix: 'Set GT_PROJECT_ID in your environment or pass projectId to withGTConfig()',\n docsUrl: 'https://generaltranslation.com/dashboard',\n});\n\nexport const APIKeyMissingWarn = createGtNextPluginDiagnostic({\n whatHappened: 'Runtime translation needs a development API key',\n fix: 'Find your development API key at generaltranslation.com/dashboard, or set runtimeUrl to an empty string to disable runtime translation',\n});\n\nexport const standardizedLocalesWarning = (locales: string[]) =>\n `gt-next: The following locales were standardized: ${locales.join(', ')}. Use the standardized codes in your config to avoid this warning.`;\n\nexport const standardizedCanonicalLocalesWarning = (locales: string[]) =>\n `gt-next: The following canonical locales were standardized: ${locales.join(', ')}. Use the standardized codes in your config to avoid this warning.`;\n\nexport const createGTCompilerUnresolvedWarning = (type: 'babel' | 'swc') =>\n `gt-next (plugin): The GT ${type} compiler could not be resolved. Skipping compiler optimizations.`;\n\nexport const customGetLocaleUnresolvedWarning = createGtNextDiagnostic({\n whatHappened: 'Custom getLocale() could not be resolved',\n wayOut: 'gt-next will fall back to default locale detection',\n fix: 'Export a getLocale() function from the configured request file',\n});\n\nexport const customGetRegionUnresolvedWarning = createGtNextDiagnostic({\n whatHappened: 'Custom getRegion() could not be resolved',\n wayOut: 'gt-next will fall back to default region detection',\n fix: 'Export a getRegion() function from the configured request file',\n});\n\nexport const createGTCompilerUnavailableWarning = (type: 'babel' | 'swc') =>\n type === 'swc'\n ? `gt-next (plugin): The GT swc compiler is compatible with < next@${SWC_PLUGIN_SUPPORT}. Skipping compiler optimizations.`\n : `gt-next (plugin): The GT babel compiler requires react@${BABEL_PLUGIN_SUPPORT} or newer. Skipping compiler optimizations.`;\n\nexport const babelCompilerTurbopackUnavailableWarning =\n `gt-next (plugin): The GT babel compiler is not compatible with Turbopack. ` +\n `To use compiler optimizations with Turbopack, set experimentalCompilerOptions: { type: 'swc' }.`;\n\nexport const disablingCompileTimeHashWarning = `gt-next (plugin): Compile-time hash is disabled. Compiler optimizations are inactive.`;\n\nexport const swcPluginCompatibilityChangeWarning = `gt-next (plugin): As of gt-next@6.12.4, SWC plugin support is disabled for Next.js versions prior to ${SWC_PLUGIN_SUPPORT}. Update to the latest version of Next.js.`;\n"],"mappings":";;;;AAUA,MAAa,0BAA0B,uBAAuB;CAC5D,UAAU;CACV,cAAc;CACd,KAAK;CACL,QAAQ;CACT,CAAC;AAEF,MAAa,+BAA+B,SAAiB,OAC3D,uBAAuB;CACrB,UAAU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
|
|
@@ -11,13 +11,15 @@ import { PathConfig } from './utils';
|
|
|
11
11
|
* @param {boolean} [config.localeRouting=true] - Flag to enable or disable automatic locale-based routing.
|
|
12
12
|
* @param {boolean} [config.prefixDefaultLocale=false] - Flag to enable or disable prefixing the default locale to the pathname, i.e., /en/about -> /about
|
|
13
13
|
* @param {boolean} [config.ignoreSourceMaps=true] - Flag to enable or disable ignoring source maps
|
|
14
|
+
* @param {string} [config.regexFilter] - Regular expression that request pathnames must match for i18n middleware to be applied
|
|
14
15
|
* @param {PathConfig} [config.pathConfig] - Path configuration for locale routing
|
|
15
16
|
* @returns {function} - A middleware function that processes the request and response.
|
|
16
17
|
*/
|
|
17
|
-
export declare function createNextMiddleware({ localeRouting, prefixDefaultLocale, ignoreSourceMaps, pathConfig, }?: {
|
|
18
|
+
export declare function createNextMiddleware({ localeRouting, prefixDefaultLocale, ignoreSourceMaps, regexFilter, pathConfig, }?: {
|
|
18
19
|
localeRouting?: boolean;
|
|
19
20
|
prefixDefaultLocale?: boolean;
|
|
20
21
|
ignoreSourceMaps?: boolean;
|
|
22
|
+
regexFilter?: string;
|
|
21
23
|
pathConfig?: PathConfig;
|
|
22
24
|
}): (req: NextRequest) => NextResponse<unknown>;
|
|
23
25
|
//# sourceMappingURL=createNextMiddleware.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createNextMiddleware.d.ts","sourceRoot":"","sources":["../../src/middleware-dir/createNextMiddleware.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"createNextMiddleware.d.ts","sourceRoot":"","sources":["../../src/middleware-dir/createNextMiddleware.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AASxD,OAAO,EACL,UAAU,EAQX,MAAM,SAAS,CAAC;AAcjB;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,oBAAoB,CAAC,EACnC,aAAoB,EACpB,mBAA2B,EAC3B,gBAAuB,EACvB,WAAW,EACX,UAAe,GAChB,GAAE;IACD,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,UAAU,CAAC;CACpB,SAkHqB,WAAW,2BA6MrC"}
|
|
@@ -22,10 +22,17 @@ const NEXT_JS_SOURCE_MAP_PATH = "/__nextjs_source-map";
|
|
|
22
22
|
* @param {boolean} [config.localeRouting=true] - Flag to enable or disable automatic locale-based routing.
|
|
23
23
|
* @param {boolean} [config.prefixDefaultLocale=false] - Flag to enable or disable prefixing the default locale to the pathname, i.e., /en/about -> /about
|
|
24
24
|
* @param {boolean} [config.ignoreSourceMaps=true] - Flag to enable or disable ignoring source maps
|
|
25
|
+
* @param {string} [config.regexFilter] - Regular expression that request pathnames must match for i18n middleware to be applied
|
|
25
26
|
* @param {PathConfig} [config.pathConfig] - Path configuration for locale routing
|
|
26
27
|
* @returns {function} - A middleware function that processes the request and response.
|
|
27
28
|
*/
|
|
28
|
-
function createNextMiddleware({ localeRouting = true, prefixDefaultLocale = false, ignoreSourceMaps = true, pathConfig = {} } = {}) {
|
|
29
|
+
function createNextMiddleware({ localeRouting = true, prefixDefaultLocale = false, ignoreSourceMaps = true, regexFilter, pathConfig = {} } = {}) {
|
|
30
|
+
let pathFilter;
|
|
31
|
+
if (regexFilter !== void 0) try {
|
|
32
|
+
pathFilter = new RegExp(regexFilter);
|
|
33
|
+
} catch (error) {
|
|
34
|
+
throw new Error(require_errors_createErrors.createInvalidMiddlewareRegexError(regexFilter, error));
|
|
35
|
+
}
|
|
29
36
|
let envParams;
|
|
30
37
|
if (process.env._GENERALTRANSLATION_I18N_CONFIG_PARAMS) try {
|
|
31
38
|
envParams = JSON.parse(process.env._GENERALTRANSLATION_I18N_CONFIG_PARAMS);
|
|
@@ -70,6 +77,7 @@ function createNextMiddleware({ localeRouting = true, prefixDefaultLocale = fals
|
|
|
70
77
|
* @returns {NextResponse} - The Next.js response, either continuing the request or redirecting to the localized URL.
|
|
71
78
|
*/
|
|
72
79
|
function middleware(req) {
|
|
80
|
+
if (pathFilter && !pathFilter.test(req.nextUrl.pathname)) return next_server_js.NextResponse.next();
|
|
73
81
|
if (ignoreSourceMaps && req.nextUrl.pathname.startsWith(NEXT_JS_SOURCE_MAP_PATH)) return next_server_js.NextResponse.next();
|
|
74
82
|
const { userLocale, pathnameLocale, unstandardizedPathnameLocale, clearResetCookie } = require_middleware_dir_utils.getLocaleFromRequest(req, defaultLocale, locales, localeRouting, gtServicesEnabled, prefixDefaultLocale, defaultLocalePaths, referrerLocaleCookieName, localeCookieName, resetLocaleCookieName, gt);
|
|
75
83
|
const headerList = new Headers(req.headers);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createNextMiddleware.js","names":["GTRuntime","libraryDefaultLocale","defaultLocaleCookieName","defaultResetLocaleCookieName","createUnsupportedLocalesWarning","createPathToSharedPathMap","NextResponse","getLocaleFromRequest","getResponse","getSharedPath","replaceDynamicSegments","getLocalizedPath"],"sources":["../../src/middleware-dir/createNextMiddleware.ts"],"sourcesContent":["import { isSameDialect, standardizeLocale } from '@generaltranslation/format';\nimport { GTRuntime } from 'generaltranslation/runtime';\nimport { libraryDefaultLocale } from 'generaltranslation/internal';\nimport { createUnsupportedLocalesWarning } from '../errors/createErrors';\nimport { NextRequest, NextResponse } 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 PathConfig,\n getSharedPath,\n replaceDynamicSegments,\n getLocalizedPath,\n createPathToSharedPathMap,\n getLocaleFromRequest,\n getResponse,\n ResponseConfig,\n} from './utils';\nimport { defaultLocaleHeaderName } from '../utils/headers';\nimport type { CustomMapping } from '@generaltranslation/format/types';\nimport type { HeadersAndCookies } from '../config-dir/props/withGTConfigProps';\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\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 * @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}: {\n localeRouting?: boolean;\n prefixDefaultLocale?: boolean;\n ignoreSourceMaps?: boolean;\n pathConfig?: PathConfig;\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 // 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 // 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 `/${userLocale}`\n )\n : pathname;\n\n // Get the shared path for the unprefixed pathname\n const sharedPath = getSharedPath(\n standardizedPathname,\n pathToSharedPath,\n pathnameLocale\n );\n\n // Get shared path with parameters (/en/dashboard/1/custom), for rewriting localized paths\n const sharedPathWithParameters =\n sharedPath !== undefined\n ? replaceDynamicSegments(\n pathnameLocale\n ? standardizedPathname\n : `/${userLocale}${standardizedPathname}`,\n `/${userLocale}${sharedPath}`\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\n ? replaceDynamicSegments(\n pathnameLocale\n ? standardizedPathname\n : `/${userLocale}${standardizedPathname}`,\n localizedPath\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(`/${userLocale}${pathname}`);\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 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(`^/${unstandardizedPathnameLocale}`),\n ``\n ) || '/'\n );\n }\n } else {\n // REDIRECT CASE: unprefixed pathname is wrong (/about -> /en-about)\n if (\n !pathnameLocale &&\n localizedPathWithParameters !== `/${userLocale}${pathname}`\n ) {\n return getRedirectResponse(\n localizedPathWithParameters.replace(\n new RegExp(`^/${userLocale}`),\n ''\n ) || '/'\n );\n }\n\n // REWRITE CASE: displaying correct path (/blog -> /en/blog)\n return getRewriteResponse(sharedPathWithParameters as string);\n }\n }\n\n // --- CASE: add defaultLocale prefix --- //\n\n // REDIRECT CASE: incorrect pathnameLocale\n if (pathname !== localizedPathWithParameters) {\n return getRedirectResponse(localizedPathWithParameters);\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 if (\n standardizedPathname !== sharedPathWithParameters // 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":";;;;;;;;;;;;AA2BA,MAAM,0BAA0B;;;;;;;;;;;;;;;AAuBhC,SAAgB,qBAAqB,EACnC,gBAAgB,MAChB,sBAAsB,OACtB,mBAAmB,MACnB,aAAa,EAAE,KAMb,EAAE,EAAE;CAEN,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,IAAIA,2BAAAA,UAAU,EACv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L,SAAS,QACP,IAAI,OAAO,KAAK,+BAA+B,EAC/C,GACD,IAAI,IACN;UAIH,QAAO,mBAAmB,IAAI,aAAa,WAAW;aAMjD,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,WAAO,iBAAiB;;AAK1B,OAAI,CAAC,wBAAA,GAAA,2BAAA,eAAqC,YAAY,cAAc,CAGlE,KAAI;QAEE,iBACF,QAAO,oBACL,4BAA4B,QAC1B,IAAI,OAAO,KAAK,+BAA+B,EAC/C,GACD,IAAI,IACN;UAEE;AAEL,QACE,CAAC,kBACD,gCAAgC,IAAI,aAAa,WAEjD,QAAO,oBACL,4BAA4B,QAC1B,IAAI,OAAO,KAAK,aAAa,EAC7B,GACD,IAAI,IACN;AAIH,WAAO,mBAAmB,yBAAmC;;AAOjE,OAAI,aAAa,4BACf,QAAO,oBAAoB,4BAA4B;AAIzD,OACE,yBAAyB,yBAGzB,QAAO,mBAAmB,yBAAmC;;AAKjE,SAAO,iBAAiB;;AAG1B,QAAO"}
|
|
1
|
+
{"version":3,"file":"createNextMiddleware.js","names":["createInvalidMiddlewareRegexError","GTRuntime","libraryDefaultLocale","defaultLocaleCookieName","defaultResetLocaleCookieName","createUnsupportedLocalesWarning","createPathToSharedPathMap","NextResponse","getLocaleFromRequest","getResponse","getSharedPath","replaceDynamicSegments","getLocalizedPath"],"sources":["../../src/middleware-dir/createNextMiddleware.ts"],"sourcesContent":["import { isSameDialect, standardizeLocale } from '@generaltranslation/format';\nimport { GTRuntime } from 'generaltranslation/runtime';\nimport { libraryDefaultLocale } from 'generaltranslation/internal';\nimport {\n createInvalidMiddlewareRegexError,\n createUnsupportedLocalesWarning,\n} from '../errors/createErrors';\nimport { NextRequest, NextResponse } 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 PathConfig,\n getSharedPath,\n replaceDynamicSegments,\n getLocalizedPath,\n createPathToSharedPathMap,\n getLocaleFromRequest,\n getResponse,\n ResponseConfig,\n} from './utils';\nimport { defaultLocaleHeaderName } from '../utils/headers';\nimport type { CustomMapping } from '@generaltranslation/format/types';\nimport type { HeadersAndCookies } from '../config-dir/props/withGTConfigProps';\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\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 {string} [config.regexFilter] - Regular expression that request pathnames must match for i18n middleware to be applied\n * @param {PathConfig} [config.pathConfig] - Path configuration for locale routing\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 regexFilter,\n pathConfig = {},\n}: {\n localeRouting?: boolean;\n prefixDefaultLocale?: boolean;\n ignoreSourceMaps?: boolean;\n regexFilter?: string;\n pathConfig?: PathConfig;\n} = {}) {\n let pathFilter: RegExp | undefined;\n if (regexFilter !== undefined) {\n try {\n pathFilter = new RegExp(regexFilter);\n } catch (error) {\n throw new Error(createInvalidMiddlewareRegexError(regexFilter, error));\n }\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 // 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 (pathFilter && !pathFilter.test(req.nextUrl.pathname)) {\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 `/${userLocale}`\n )\n : pathname;\n\n // Get the shared path for the unprefixed pathname\n const sharedPath = getSharedPath(\n standardizedPathname,\n pathToSharedPath,\n pathnameLocale\n );\n\n // Get shared path with parameters (/en/dashboard/1/custom), for rewriting localized paths\n const sharedPathWithParameters =\n sharedPath !== undefined\n ? replaceDynamicSegments(\n pathnameLocale\n ? standardizedPathname\n : `/${userLocale}${standardizedPathname}`,\n `/${userLocale}${sharedPath}`\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\n ? replaceDynamicSegments(\n pathnameLocale\n ? standardizedPathname\n : `/${userLocale}${standardizedPathname}`,\n localizedPath\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(`/${userLocale}${pathname}`);\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 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(`^/${unstandardizedPathnameLocale}`),\n ``\n ) || '/'\n );\n }\n } else {\n // REDIRECT CASE: unprefixed pathname is wrong (/about -> /en-about)\n if (\n !pathnameLocale &&\n localizedPathWithParameters !== `/${userLocale}${pathname}`\n ) {\n return getRedirectResponse(\n localizedPathWithParameters.replace(\n new RegExp(`^/${userLocale}`),\n ''\n ) || '/'\n );\n }\n\n // REWRITE CASE: displaying correct path (/blog -> /en/blog)\n return getRewriteResponse(sharedPathWithParameters as string);\n }\n }\n\n // --- CASE: add defaultLocale prefix --- //\n\n // REDIRECT CASE: incorrect pathnameLocale\n if (pathname !== localizedPathWithParameters) {\n return getRedirectResponse(localizedPathWithParameters);\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 if (\n standardizedPathname !== sharedPathWithParameters // 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":";;;;;;;;;;;;AA8BA,MAAM,0BAA0B;;;;;;;;;;;;;;;;AAwBhC,SAAgB,qBAAqB,EACnC,gBAAgB,MAChB,sBAAsB,OACtB,mBAAmB,MACnB,aACA,aAAa,EAAE,KAOb,EAAE,EAAE;CACN,IAAI;AACJ,KAAI,gBAAgB,KAAA,EAClB,KAAI;AACF,eAAa,IAAI,OAAO,YAAY;UAC7B,OAAO;AACd,QAAM,IAAI,MAAMA,4BAAAA,kCAAkC,aAAa,MAAM,CAAC;;CAK1E,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,IAAIC,2BAAAA,UAAU,EACvB,eAAe,WAAW,eAC3B,CAAC;CAGF,MAAM,oBACJ,QAAQ,IAAI,4CAA4C;CAG1D,MAAM,gBACJ,WAAW,iBAAiBC,4BAAAA;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,oBAAoBC,oCAAAA;CACzC,MAA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BACD,gCAAgC,IAAI,aAAa,WAEjD,QAAO,oBACL,4BAA4B,QAC1B,IAAI,OAAO,KAAK,aAAa,EAC7B,GACD,IAAI,IACN;AAIH,WAAO,mBAAmB,yBAAmC;;AAOjE,OAAI,aAAa,4BACf,QAAO,oBAAoB,4BAA4B;AAIzD,OACE,yBAAyB,yBAGzB,QAAO,mBAAmB,yBAAmC;;AAKjE,SAAO,iBAAiB;;AAG1B,QAAO"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "../utils/headers.mjs";
|
|
2
2
|
import "../utils/cookies.mjs";
|
|
3
|
-
import { createUnsupportedLocalesWarning } from "../errors/createErrors.mjs";
|
|
3
|
+
import { createInvalidMiddlewareRegexError, createUnsupportedLocalesWarning } from "../errors/createErrors.mjs";
|
|
4
4
|
import { createPathToSharedPathMap, getLocaleFromRequest, getLocalizedPath, getResponse, getSharedPath, replaceDynamicSegments } from "./utils.mjs";
|
|
5
5
|
import { libraryDefaultLocale } from "generaltranslation/internal";
|
|
6
6
|
import { defaultLocaleCookieName, defaultResetLocaleCookieName } from "@generaltranslation/react-core/pure";
|
|
@@ -20,10 +20,17 @@ const NEXT_JS_SOURCE_MAP_PATH = "/__nextjs_source-map";
|
|
|
20
20
|
* @param {boolean} [config.localeRouting=true] - Flag to enable or disable automatic locale-based routing.
|
|
21
21
|
* @param {boolean} [config.prefixDefaultLocale=false] - Flag to enable or disable prefixing the default locale to the pathname, i.e., /en/about -> /about
|
|
22
22
|
* @param {boolean} [config.ignoreSourceMaps=true] - Flag to enable or disable ignoring source maps
|
|
23
|
+
* @param {string} [config.regexFilter] - Regular expression that request pathnames must match for i18n middleware to be applied
|
|
23
24
|
* @param {PathConfig} [config.pathConfig] - Path configuration for locale routing
|
|
24
25
|
* @returns {function} - A middleware function that processes the request and response.
|
|
25
26
|
*/
|
|
26
|
-
function createNextMiddleware({ localeRouting = true, prefixDefaultLocale = false, ignoreSourceMaps = true, pathConfig = {} } = {}) {
|
|
27
|
+
function createNextMiddleware({ localeRouting = true, prefixDefaultLocale = false, ignoreSourceMaps = true, regexFilter, pathConfig = {} } = {}) {
|
|
28
|
+
let pathFilter;
|
|
29
|
+
if (regexFilter !== void 0) try {
|
|
30
|
+
pathFilter = new RegExp(regexFilter);
|
|
31
|
+
} catch (error) {
|
|
32
|
+
throw new Error(createInvalidMiddlewareRegexError(regexFilter, error));
|
|
33
|
+
}
|
|
27
34
|
let envParams;
|
|
28
35
|
if (process.env._GENERALTRANSLATION_I18N_CONFIG_PARAMS) try {
|
|
29
36
|
envParams = JSON.parse(process.env._GENERALTRANSLATION_I18N_CONFIG_PARAMS);
|
|
@@ -68,6 +75,7 @@ function createNextMiddleware({ localeRouting = true, prefixDefaultLocale = fals
|
|
|
68
75
|
* @returns {NextResponse} - The Next.js response, either continuing the request or redirecting to the localized URL.
|
|
69
76
|
*/
|
|
70
77
|
function middleware(req) {
|
|
78
|
+
if (pathFilter && !pathFilter.test(req.nextUrl.pathname)) return NextResponse.next();
|
|
71
79
|
if (ignoreSourceMaps && req.nextUrl.pathname.startsWith(NEXT_JS_SOURCE_MAP_PATH)) return NextResponse.next();
|
|
72
80
|
const { userLocale, pathnameLocale, unstandardizedPathnameLocale, clearResetCookie } = getLocaleFromRequest(req, defaultLocale, locales, localeRouting, gtServicesEnabled, prefixDefaultLocale, defaultLocalePaths, referrerLocaleCookieName, localeCookieName, resetLocaleCookieName, gt);
|
|
73
81
|
const headerList = new Headers(req.headers);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createNextMiddleware.mjs","names":[],"sources":["../../src/middleware-dir/createNextMiddleware.ts"],"sourcesContent":["import { isSameDialect, standardizeLocale } from '@generaltranslation/format';\nimport { GTRuntime } from 'generaltranslation/runtime';\nimport { libraryDefaultLocale } from 'generaltranslation/internal';\nimport { createUnsupportedLocalesWarning } from '../errors/createErrors';\nimport { NextRequest, NextResponse } 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 PathConfig,\n getSharedPath,\n replaceDynamicSegments,\n getLocalizedPath,\n createPathToSharedPathMap,\n getLocaleFromRequest,\n getResponse,\n ResponseConfig,\n} from './utils';\nimport { defaultLocaleHeaderName } from '../utils/headers';\nimport type { CustomMapping } from '@generaltranslation/format/types';\nimport type { HeadersAndCookies } from '../config-dir/props/withGTConfigProps';\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\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 * @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}: {\n localeRouting?: boolean;\n prefixDefaultLocale?: boolean;\n ignoreSourceMaps?: boolean;\n pathConfig?: PathConfig;\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 // 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 // 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 `/${userLocale}`\n )\n : pathname;\n\n // Get the shared path for the unprefixed pathname\n const sharedPath = getSharedPath(\n standardizedPathname,\n pathToSharedPath,\n pathnameLocale\n );\n\n // Get shared path with parameters (/en/dashboard/1/custom), for rewriting localized paths\n const sharedPathWithParameters =\n sharedPath !== undefined\n ? replaceDynamicSegments(\n pathnameLocale\n ? standardizedPathname\n : `/${userLocale}${standardizedPathname}`,\n `/${userLocale}${sharedPath}`\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\n ? replaceDynamicSegments(\n pathnameLocale\n ? standardizedPathname\n : `/${userLocale}${standardizedPathname}`,\n localizedPath\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(`/${userLocale}${pathname}`);\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 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(`^/${unstandardizedPathnameLocale}`),\n ``\n ) || '/'\n );\n }\n } else {\n // REDIRECT CASE: unprefixed pathname is wrong (/about -> /en-about)\n if (\n !pathnameLocale &&\n localizedPathWithParameters !== `/${userLocale}${pathname}`\n ) {\n return getRedirectResponse(\n localizedPathWithParameters.replace(\n new RegExp(`^/${userLocale}`),\n ''\n ) || '/'\n );\n }\n\n // REWRITE CASE: displaying correct path (/blog -> /en/blog)\n return getRewriteResponse(sharedPathWithParameters as string);\n }\n }\n\n // --- CASE: add defaultLocale prefix --- //\n\n // REDIRECT CASE: incorrect pathnameLocale\n if (pathname !== localizedPathWithParameters) {\n return getRedirectResponse(localizedPathWithParameters);\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 if (\n standardizedPathname !== sharedPathWithParameters // 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":";;;;;;;;;;AA2BA,MAAM,0BAA0B;;;;;;;;;;;;;;;AAuBhC,SAAgB,qBAAqB,EACnC,gBA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W;AAG7C,QAAI,CAAC,uBAAuB,cAAc,YAAY,cAAc,CAClE,KAAI;SAEE,iBACF,QAAO,oBACL,SAAS,QACP,IAAI,OAAO,KAAK,+BAA+B,EAC/C,GACD,IAAI,IACN;UAIH,QAAO,mBAAmB,IAAI,aAAa,WAAW;aAMjD,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,WAAO,iBAAiB;;AAK1B,OAAI,CAAC,uBAAuB,cAAc,YAAY,cAAc,CAGlE,KAAI;QAEE,iBACF,QAAO,oBACL,4BAA4B,QAC1B,IAAI,OAAO,KAAK,+BAA+B,EAC/C,GACD,IAAI,IACN;UAEE;AAEL,QACE,CAAC,kBACD,gCAAgC,IAAI,aAAa,WAEjD,QAAO,oBACL,4BAA4B,QAC1B,IAAI,OAAO,KAAK,aAAa,EAC7B,GACD,IAAI,IACN;AAIH,WAAO,mBAAmB,yBAAmC;;AAOjE,OAAI,aAAa,4BACf,QAAO,oBAAoB,4BAA4B;AAIzD,OACE,yBAAyB,yBAGzB,QAAO,mBAAmB,yBAAmC;;AAKjE,SAAO,iBAAiB;;AAG1B,QAAO"}
|
|
1
|
+
{"version":3,"file":"createNextMiddleware.mjs","names":[],"sources":["../../src/middleware-dir/createNextMiddleware.ts"],"sourcesContent":["import { isSameDialect, standardizeLocale } from '@generaltranslation/format';\nimport { GTRuntime } from 'generaltranslation/runtime';\nimport { libraryDefaultLocale } from 'generaltranslation/internal';\nimport {\n createInvalidMiddlewareRegexError,\n createUnsupportedLocalesWarning,\n} from '../errors/createErrors';\nimport { NextRequest, NextResponse } 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 PathConfig,\n getSharedPath,\n replaceDynamicSegments,\n getLocalizedPath,\n createPathToSharedPathMap,\n getLocaleFromRequest,\n getResponse,\n ResponseConfig,\n} from './utils';\nimport { defaultLocaleHeaderName } from '../utils/headers';\nimport type { CustomMapping } from '@generaltranslation/format/types';\nimport type { HeadersAndCookies } from '../config-dir/props/withGTConfigProps';\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\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 {string} [config.regexFilter] - Regular expression that request pathnames must match for i18n middleware to be applied\n * @param {PathConfig} [config.pathConfig] - Path configuration for locale routing\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 regexFilter,\n pathConfig = {},\n}: {\n localeRouting?: boolean;\n prefixDefaultLocale?: boolean;\n ignoreSourceMaps?: boolean;\n regexFilter?: string;\n pathConfig?: PathConfig;\n} = {}) {\n let pathFilter: RegExp | undefined;\n if (regexFilter !== undefined) {\n try {\n pathFilter = new RegExp(regexFilter);\n } catch (error) {\n throw new Error(createInvalidMiddlewareRegexError(regexFilter, error));\n }\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 // 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 (pathFilter && !pathFilter.test(req.nextUrl.pathname)) {\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 `/${userLocale}`\n )\n : pathname;\n\n // Get the shared path for the unprefixed pathname\n const sharedPath = getSharedPath(\n standardizedPathname,\n pathToSharedPath,\n pathnameLocale\n );\n\n // Get shared path with parameters (/en/dashboard/1/custom), for rewriting localized paths\n const sharedPathWithParameters =\n sharedPath !== undefined\n ? replaceDynamicSegments(\n pathnameLocale\n ? standardizedPathname\n : `/${userLocale}${standardizedPathname}`,\n `/${userLocale}${sharedPath}`\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\n ? replaceDynamicSegments(\n pathnameLocale\n ? standardizedPathname\n : `/${userLocale}${standardizedPathname}`,\n localizedPath\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(`/${userLocale}${pathname}`);\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 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(`^/${unstandardizedPathnameLocale}`),\n ``\n ) || '/'\n );\n }\n } else {\n // REDIRECT CASE: unprefixed pathname is wrong (/about -> /en-about)\n if (\n !pathnameLocale &&\n localizedPathWithParameters !== `/${userLocale}${pathname}`\n ) {\n return getRedirectResponse(\n localizedPathWithParameters.replace(\n new RegExp(`^/${userLocale}`),\n ''\n ) || '/'\n );\n }\n\n // REWRITE CASE: displaying correct path (/blog -> /en/blog)\n return getRewriteResponse(sharedPathWithParameters as string);\n }\n }\n\n // --- CASE: add defaultLocale prefix --- //\n\n // REDIRECT CASE: incorrect pathnameLocale\n if (pathname !== localizedPathWithParameters) {\n return getRedirectResponse(localizedPathWithParameters);\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 if (\n standardizedPathname !== sharedPathWithParameters // 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":";;;;;;;;;;AA8BA,MAAM,0BAA0B;;;;;;;;;;;;;;;;AAwBhC,SAAgB,qBAAqB,EACnC,gBAAgB,MAChB,sBAAsB,OACtB,mBAAmB,MACnB,aACA,aAAa,EAAE,KAOb,EAAE,EAAE;CACN,IAAI;AACJ,KAAI,gBAAgB,KAAA,EAClB,KAAI;AACF,eAAa,IAAI,OAAO,YAAY;UAC7B,OAAO;AACd,QAAM,IAAI,MAAM,kCAAkC,aAAa,MAAM,CAAC;;CAK1E,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,cAA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|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gt-next",
|
|
3
|
-
"version": "11.0.
|
|
3
|
+
"version": "11.0.2",
|
|
4
4
|
"description": "A Next.js library for automatic internationalization.",
|
|
5
5
|
"main": "dist/index.server.js",
|
|
6
6
|
"peerDependencies": {
|
|
@@ -22,13 +22,13 @@
|
|
|
22
22
|
"./dist/utils/client-boundary.*"
|
|
23
23
|
],
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@generaltranslation/compiler": "1.3.25",
|
|
26
25
|
"@generaltranslation/format": "0.1.2",
|
|
27
|
-
"@generaltranslation/
|
|
26
|
+
"@generaltranslation/compiler": "1.3.25",
|
|
28
27
|
"@generaltranslation/supported-locales": "2.1.3",
|
|
29
|
-
"
|
|
30
|
-
"
|
|
31
|
-
"gt-i18n": "1.0.1"
|
|
28
|
+
"gt-react": "11.0.2",
|
|
29
|
+
"@generaltranslation/react-core": "11.0.2",
|
|
30
|
+
"gt-i18n": "1.0.1",
|
|
31
|
+
"generaltranslation": "9.0.0"
|
|
32
32
|
},
|
|
33
33
|
"repository": {
|
|
34
34
|
"type": "git",
|