next-intlayer 9.1.3 → 9.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/proxy/intlayerProxy.cjs +17 -6
- package/dist/cjs/proxy/intlayerProxy.cjs.map +1 -1
- package/dist/cjs/server/prepareSwcOptimization.cjs +190 -0
- package/dist/cjs/server/prepareSwcOptimization.cjs.map +1 -0
- package/dist/cjs/server/swcPluginCompatibility.cjs +57 -0
- package/dist/cjs/server/swcPluginCompatibility.cjs.map +1 -0
- package/dist/cjs/server/withIntlayer.cjs +64 -17
- package/dist/cjs/server/withIntlayer.cjs.map +1 -1
- package/dist/esm/proxy/intlayerProxy.mjs +18 -8
- package/dist/esm/proxy/intlayerProxy.mjs.map +1 -1
- package/dist/esm/server/prepareSwcOptimization.mjs +185 -0
- package/dist/esm/server/prepareSwcOptimization.mjs.map +1 -0
- package/dist/esm/server/swcPluginCompatibility.mjs +55 -0
- package/dist/esm/server/swcPluginCompatibility.mjs.map +1 -0
- package/dist/esm/server/withIntlayer.mjs +63 -18
- package/dist/esm/server/withIntlayer.mjs.map +1 -1
- package/dist/types/proxy/intlayerProxy.d.ts.map +1 -1
- package/dist/types/server/prepareSwcOptimization.d.ts +67 -0
- package/dist/types/server/prepareSwcOptimization.d.ts.map +1 -0
- package/dist/types/server/swcPluginCompatibility.d.ts +52 -0
- package/dist/types/server/swcPluginCompatibility.d.ts.map +1 -0
- package/dist/types/server/withIntlayer.d.ts +12 -1
- package/dist/types/server/withIntlayer.d.ts.map +1 -1
- package/package.json +11 -10
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
|
+
const require_server_prepareSwcOptimization = require('./prepareSwcOptimization.cjs');
|
|
4
|
+
const require_server_swcPluginCompatibility = require('./swcPluginCompatibility.cjs');
|
|
3
5
|
let _intlayer_config_defaultValues = require("@intlayer/config/defaultValues");
|
|
6
|
+
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
4
7
|
let node_path = require("node:path");
|
|
5
8
|
let _intlayer_config_colors = require("@intlayer/config/colors");
|
|
6
9
|
_intlayer_config_colors = require_runtime.__toESM(_intlayer_config_colors);
|
|
7
10
|
let _intlayer_config_envVars = require("@intlayer/config/envVars");
|
|
8
|
-
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
9
11
|
let _intlayer_config_node = require("@intlayer/config/node");
|
|
10
12
|
let _intlayer_config_utils = require("@intlayer/config/utils");
|
|
13
|
+
let _intlayer_core_dictionaryManipulator = require("@intlayer/core/dictionaryManipulator");
|
|
11
14
|
let _intlayer_dictionaries_entry = require("@intlayer/dictionaries-entry");
|
|
12
15
|
let _intlayer_engine_build = require("@intlayer/engine/build");
|
|
13
16
|
let _intlayer_engine_cli = require("@intlayer/engine/cli");
|
|
@@ -29,10 +32,16 @@ const getNextVersionFlags = (intlayerConfig) => {
|
|
|
29
32
|
nextVersion = (intlayerConfig.build?.require ?? (0, _intlayer_config_utils.getProjectRequire)())("next/package.json").version;
|
|
30
33
|
} catch {}
|
|
31
34
|
return {
|
|
35
|
+
nextVersion,
|
|
32
36
|
isGteNext13: (0, _intlayer_config_utils.compareVersions)(nextVersion, "≥", "13.0.0"),
|
|
33
37
|
isGteNext15: (0, _intlayer_config_utils.compareVersions)(nextVersion, "≥", "15.0.0"),
|
|
34
38
|
isGteNext16: (0, _intlayer_config_utils.compareVersions)(nextVersion, "≥", "16.0.0"),
|
|
35
|
-
isTurbopackStable: (0, _intlayer_config_utils.compareVersions)(nextVersion, "≥", "15.3.0")
|
|
39
|
+
isTurbopackStable: (0, _intlayer_config_utils.compareVersions)(nextVersion, "≥", "15.3.0"),
|
|
40
|
+
/**
|
|
41
|
+
* Whether this Next.js release can load the `@intlayer/swc` Wasm plugin.
|
|
42
|
+
* See {@link MINIMUM_SWC_PLUGIN_NEXT_VERSION}.
|
|
43
|
+
*/
|
|
44
|
+
isSwcPluginSupported: require_server_swcPluginCompatibility.getIsSwcPluginSupported(nextVersion)
|
|
36
45
|
};
|
|
37
46
|
};
|
|
38
47
|
const getIsSwcPluginAvailable = (intlayerConfig) => {
|
|
@@ -56,8 +65,9 @@ const resolvePluginPath = (pluginPath, intlayerConfig, isTurbopackEnabled) => {
|
|
|
56
65
|
if (isTurbopackEnabled) return (0, _intlayer_config_utils.normalizePath)(`./${(0, node_path.relative)(process.cwd(), pluginPathResolved)}`);
|
|
57
66
|
return pluginPathResolved;
|
|
58
67
|
};
|
|
59
|
-
const getPruneConfig = (intlayerConfig, isBuildCommand, isTurbopackEnabled, isDevCommand, isGteNext13, swcExtraCallers) => {
|
|
60
|
-
const { optimize } = intlayerConfig.build;
|
|
68
|
+
const getPruneConfig = ({ intlayerConfig, isBuildCommand, isTurbopackEnabled, isDevCommand, isGteNext13, isSwcPluginSupported, nextVersion, swcExtraCallers, fieldRenameMap }) => {
|
|
69
|
+
const { optimize, minify, purge } = intlayerConfig.build;
|
|
70
|
+
const editorEnabled = intlayerConfig.editor.enabled;
|
|
61
71
|
const importMode = intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;
|
|
62
72
|
const { dictionariesDir, unmergedDictionariesDir, dynamicDictionariesDir, fetchDictionariesDir, mainDir } = intlayerConfig.system;
|
|
63
73
|
const { baseDir } = intlayerConfig.system;
|
|
@@ -67,13 +77,25 @@ const getPruneConfig = (intlayerConfig, isBuildCommand, isTurbopackEnabled, isDe
|
|
|
67
77
|
if (!isGteNext13) return {};
|
|
68
78
|
const isSwcPluginAvailable = getIsSwcPluginAvailable(intlayerConfig);
|
|
69
79
|
(0, _intlayer_engine_utils.runOnce)((0, node_path.join)(baseDir, ".intlayer", "cache", "intlayer-prune-plugin-enabled.lock"), () => {
|
|
70
|
-
if (isSwcPluginAvailable) logger([
|
|
71
|
-
`Build optimization ${(0, _intlayer_config_logger.colorize)("
|
|
72
|
-
(0, _intlayer_config_logger.colorize)(
|
|
73
|
-
(0, _intlayer_config_logger.colorize)(
|
|
74
|
-
(0, _intlayer_config_logger.colorize)(
|
|
75
|
-
|
|
76
|
-
|
|
80
|
+
if (isSwcPluginAvailable && !isSwcPluginSupported) logger([
|
|
81
|
+
`Build optimization ${(0, _intlayer_config_logger.colorize)("disabled", _intlayer_config_colors.GREY_DARK)}:`,
|
|
82
|
+
(0, _intlayer_config_logger.colorize)("@intlayer/swc", _intlayer_config_colors.GREY_LIGHT),
|
|
83
|
+
(0, _intlayer_config_logger.colorize)(`cannot run on Next.js ${nextVersion} — its bundled SWC predates the`, _intlayer_config_colors.GREY),
|
|
84
|
+
(0, _intlayer_config_logger.colorize)("stable Wasm plugin ABI. Upgrade to Next.js", _intlayer_config_colors.GREY),
|
|
85
|
+
(0, _intlayer_config_logger.colorize)(require_server_swcPluginCompatibility.MINIMUM_SWC_PLUGIN_NEXT_VERSION, _intlayer_config_colors.BLUE),
|
|
86
|
+
(0, _intlayer_config_logger.colorize)("or later to enable it.", _intlayer_config_colors.GREY)
|
|
87
|
+
], { level: "warn" });
|
|
88
|
+
else if (isSwcPluginAvailable) {
|
|
89
|
+
logger([
|
|
90
|
+
`Build optimization ${(0, _intlayer_config_logger.colorize)("enabled", _intlayer_config_colors.GREEN)}`,
|
|
91
|
+
(0, _intlayer_config_logger.colorize)(`(import mode:`, _intlayer_config_colors.GREY_DARK),
|
|
92
|
+
(0, _intlayer_config_logger.colorize)(importMode ?? _intlayer_config_defaultValues.IMPORT_MODE, _intlayer_config_colors.BLUE),
|
|
93
|
+
(0, _intlayer_config_logger.colorize)(`)`, _intlayer_config_colors.GREY_DARK)
|
|
94
|
+
]);
|
|
95
|
+
const isPurgePipelineEnabled = !editorEnabled && !swcExtraCallers?.length && require_server_prepareSwcOptimization.getIsPurgePipelineAvailable(intlayerConfig);
|
|
96
|
+
if (isPurgePipelineEnabled && minify) logger(`Dictionary minification ${(0, _intlayer_config_logger.colorize)("enabled", _intlayer_config_colors.GREEN)}`);
|
|
97
|
+
if (isPurgePipelineEnabled && purge) logger(`Dictionary purge unused keys ${(0, _intlayer_config_logger.colorize)("enabled", _intlayer_config_colors.GREEN)}`);
|
|
98
|
+
} else logger([
|
|
77
99
|
(0, _intlayer_config_logger.colorize)("Recommended: Install", _intlayer_config_colors.GREY),
|
|
78
100
|
(0, _intlayer_config_logger.colorize)("@intlayer/swc", _intlayer_config_colors.GREY_LIGHT),
|
|
79
101
|
(0, _intlayer_config_logger.colorize)("package to enable build optimization. See documentation:", _intlayer_config_colors.GREY),
|
|
@@ -85,10 +107,9 @@ const getPruneConfig = (intlayerConfig, isBuildCommand, isTurbopackEnabled, isDe
|
|
|
85
107
|
let isEnabled = intlayerConfig.compiler?.enabled ?? true;
|
|
86
108
|
if (isEnabled === "build-only") isEnabled = !isDevCommand;
|
|
87
109
|
if (isEnabled) logger("Intlayer compiler enabled");
|
|
88
|
-
else logger("Intlayer compiler disabled");
|
|
89
110
|
}
|
|
90
111
|
}, { cacheTimeoutMs: 1e3 * 30 });
|
|
91
|
-
if (!isSwcPluginAvailable) return {};
|
|
112
|
+
if (!isSwcPluginAvailable || !isSwcPluginSupported) return {};
|
|
92
113
|
const dictionariesEntryPath = (0, node_path.join)(mainDir, "dictionaries.mjs");
|
|
93
114
|
const dynamicDictionariesEntryPath = (0, node_path.join)(mainDir, "dynamic_dictionaries.mjs");
|
|
94
115
|
const unmergedDictionariesEntryPath = (0, node_path.join)(mainDir, "unmerged_dictionaries.mjs");
|
|
@@ -103,6 +124,7 @@ const getPruneConfig = (intlayerConfig, isBuildCommand, isTurbopackEnabled, isDe
|
|
|
103
124
|
Object.values(dictionaries).forEach((dictionary) => {
|
|
104
125
|
dictionaryModeMap[dictionary.key] = dictionary.importMode ?? importMode ?? _intlayer_config_defaultValues.IMPORT_MODE;
|
|
105
126
|
});
|
|
127
|
+
const nestingDictionaryKeys = [...(0, _intlayer_core_dictionaryManipulator.getNestedDictionaryGraph)(Object.values(dictionaries)).keys()];
|
|
106
128
|
return { experimental: { swcPlugins: [[resolvePluginPath("@intlayer/swc", intlayerConfig, isTurbopackEnabled), {
|
|
107
129
|
dictionariesDir,
|
|
108
130
|
dictionariesEntryPath,
|
|
@@ -115,8 +137,11 @@ const getPruneConfig = (intlayerConfig, isBuildCommand, isTurbopackEnabled, isDe
|
|
|
115
137
|
importMode,
|
|
116
138
|
filesList,
|
|
117
139
|
replaceDictionaryEntry: true,
|
|
140
|
+
nestingDictionaryKeys,
|
|
118
141
|
dictionaryModeMap,
|
|
119
|
-
extraCallers: swcExtraCallers ?? []
|
|
142
|
+
extraCallers: swcExtraCallers ?? [],
|
|
143
|
+
fieldRenameMap: fieldRenameMap ?? {},
|
|
144
|
+
logLevel: require_server_prepareSwcOptimization.resolveSwcLogLevel(intlayerConfig)
|
|
120
145
|
}]] } };
|
|
121
146
|
};
|
|
122
147
|
const getCommandsEvent = () => {
|
|
@@ -174,7 +199,7 @@ const withIntlayerSync = (nextConfig = {}, configOptions) => {
|
|
|
174
199
|
const intlayerConfig = (0, _intlayer_config_node.getConfiguration)(resolvedConfigOptions);
|
|
175
200
|
(0, _intlayer_engine_cli.logConfigDetails)(resolvedConfigOptions);
|
|
176
201
|
const appLogger = (0, _intlayer_config_logger.getAppLogger)(intlayerConfig);
|
|
177
|
-
const { isGteNext13, isGteNext15, isGteNext16, isTurbopackStable } = getNextVersionFlags(intlayerConfig);
|
|
202
|
+
const { nextVersion, isGteNext13, isGteNext15, isGteNext16, isTurbopackStable, isSwcPluginSupported } = getNextVersionFlags(intlayerConfig);
|
|
178
203
|
const isTurbopackEnabledFromCommand = isGteNext16 ? !process.env["npm_lifecycle_script"]?.includes("--webpack") : process.env["npm_lifecycle_script"]?.includes("--turbo");
|
|
179
204
|
const isTurbopackEnabled = configOptions?.enableTurbopack ?? isTurbopackEnabledFromCommand;
|
|
180
205
|
if (isTurbopackEnabled && typeof nextConfig.webpack !== "undefined") appLogger("Turbopack is enabled but a custom webpack config is present. It will be ignored.");
|
|
@@ -212,6 +237,7 @@ const withIntlayerSync = (nextConfig = {}, configOptions) => {
|
|
|
212
237
|
env = {
|
|
213
238
|
...env,
|
|
214
239
|
...(0, _intlayer_config_envVars.formatNodeTypeToEnvVar)(unusedNodeTypes),
|
|
240
|
+
...(0, _intlayer_config_envVars.formatOptimizedNestingEnvVar)(intlayerConfig.build.optimize !== false),
|
|
215
241
|
...(0, _intlayer_config_envVars.formatDictionarySelectorEnvVar)((0, _intlayer_config_utils.getHasDictionarySelector)(dictionaries)),
|
|
216
242
|
...(0, _intlayer_config_envVars.getConfigEnvVars)(intlayerConfig)
|
|
217
243
|
};
|
|
@@ -276,7 +302,17 @@ const withIntlayerSync = (nextConfig = {}, configOptions) => {
|
|
|
276
302
|
};
|
|
277
303
|
return config;
|
|
278
304
|
};
|
|
279
|
-
const pruneConfig = getPruneConfig(
|
|
305
|
+
const pruneConfig = getPruneConfig({
|
|
306
|
+
intlayerConfig,
|
|
307
|
+
isBuildCommand,
|
|
308
|
+
isTurbopackEnabled: isTurbopackEnabled ?? false,
|
|
309
|
+
isDevCommand,
|
|
310
|
+
isGteNext13,
|
|
311
|
+
isSwcPluginSupported,
|
|
312
|
+
nextVersion,
|
|
313
|
+
swcExtraCallers: configOptions?.swcExtraCallers,
|
|
314
|
+
fieldRenameMap: configOptions?.fieldRenameMap
|
|
315
|
+
});
|
|
280
316
|
return (0, defu.defu)((0, defu.defu)(getNewConfig(), pruneConfig), nextConfig);
|
|
281
317
|
};
|
|
282
318
|
/**
|
|
@@ -305,11 +341,22 @@ const withIntlayer = async (nextConfig = {}, configOptions) => {
|
|
|
305
341
|
cacheTimeoutMs: isBuildCommand ? 1e3 * 30 : 1e3 * 60 * 60,
|
|
306
342
|
env: isBuildCommand ? "prod" : "dev"
|
|
307
343
|
});
|
|
344
|
+
const { isSwcPluginSupported } = getNextVersionFlags(intlayerConfig);
|
|
345
|
+
const fieldRenameMap = isBuildCommand ? await require_server_prepareSwcOptimization.prepareSwcOptimization(intlayerConfig, {
|
|
346
|
+
configOptions: resolvedConfigOptions,
|
|
347
|
+
swcExtraCallers: configOptions?.swcExtraCallers,
|
|
348
|
+
isSwcPluginUsable: isSwcPluginSupported && getIsSwcPluginAvailable(intlayerConfig)
|
|
349
|
+
}) : {};
|
|
308
350
|
const nextConfigResolved = await nextConfig;
|
|
309
|
-
return withIntlayerSync(nextConfigResolved,
|
|
351
|
+
return withIntlayerSync(nextConfigResolved, {
|
|
352
|
+
...resolvedConfigOptions,
|
|
353
|
+
fieldRenameMap
|
|
354
|
+
});
|
|
310
355
|
};
|
|
311
356
|
|
|
312
357
|
//#endregion
|
|
358
|
+
exports.MINIMUM_SWC_PLUGIN_NEXT_VERSION = require_server_swcPluginCompatibility.MINIMUM_SWC_PLUGIN_NEXT_VERSION;
|
|
359
|
+
exports.getIsSwcPluginSupported = require_server_swcPluginCompatibility.getIsSwcPluginSupported;
|
|
313
360
|
exports.withIntlayer = withIntlayer;
|
|
314
361
|
exports.withIntlayerSync = withIntlayerSync;
|
|
315
362
|
//# sourceMappingURL=withIntlayer.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"withIntlayer.cjs","names":["nextPackageJSON","ANSIColors","IMPORT_MODE","IntlayerPlugin"],"sources":["../../../src/server/withIntlayer.ts"],"sourcesContent":["import { join, relative, resolve } from 'node:path';\nimport type { SwcExtraCallerConfig } from '@intlayer/config/callers';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { IMPORT_MODE } from '@intlayer/config/defaultValues';\nimport {\n formatDictionarySelectorEnvVar,\n formatNodeTypeToEnvVar,\n getConfigEnvVars,\n} from '@intlayer/config/envVars';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n compareVersions,\n getAlias,\n getHasDictionarySelector,\n getProjectRequire,\n getUnusedNodeTypes,\n normalizePath,\n} from '@intlayer/config/utils';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport { prepareIntlayer } from '@intlayer/engine/build';\nimport { logConfigDetails } from '@intlayer/engine/cli';\nimport { buildComponentFilesList, runOnce } from '@intlayer/engine/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { IntlayerPlugin } from '@intlayer/webpack';\nimport { defu } from 'defu';\nimport type { NextConfig } from 'next';\nimport type { NextJsWebpackConfig } from 'next/dist/server/config-shared';\nimport nextPackageJSON from 'next/package.json' with { type: 'json' };\n\n/**\n * Resolve the Next.js version from the *user's* project at runtime.\n * A static `import from 'next/package.json'` would resolve relative to\n * next-intlayer's own node_modules, which may differ in a monorepo.\n */\nconst getNextVersionFlags = (intlayerConfig: IntlayerConfig) => {\n let nextVersion = nextPackageJSON.version;\n\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n const pkg = requireFunction('next/package.json') as { version: string };\n nextVersion = pkg.version;\n } catch {\n // keep default\n }\n\n return {\n isGteNext13: compareVersions(nextVersion, '≥', '13.0.0'),\n isGteNext15: compareVersions(nextVersion, '≥', '15.0.0'),\n isGteNext16: compareVersions(nextVersion, '≥', '16.0.0'),\n isTurbopackStable: compareVersions(nextVersion, '≥', '15.3.0'),\n };\n};\n\n// Check if SWC plugin is available\nconst getIsSwcPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/swc');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\n// Check if Babel plugin is available\nconst getIsBabelExtractPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/babel');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\nconst resolvePluginPath = (\n pluginPath: string,\n intlayerConfig: IntlayerConfig,\n isTurbopackEnabled: boolean\n): string => {\n const requireFunction = intlayerConfig.build?.require ?? getProjectRequire();\n const pluginPathResolved = requireFunction?.resolve(pluginPath);\n\n if (isTurbopackEnabled)\n // Relative path for turbopack\n return normalizePath(`./${relative(process.cwd(), pluginPathResolved)}`);\n\n // Absolute path for webpack\n return pluginPathResolved;\n};\n\nconst getPruneConfig = (\n intlayerConfig: IntlayerConfig,\n isBuildCommand: boolean,\n isTurbopackEnabled: boolean,\n isDevCommand: boolean,\n isGteNext13: boolean,\n swcExtraCallers?: SwcExtraCallerConfig[]\n): Partial<NextConfig> => {\n const { optimize } = intlayerConfig.build;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n const {\n dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.system;\n const logger = getAppLogger(intlayerConfig);\n\n if (optimize === false) {\n return {};\n }\n if (optimize === undefined && !isBuildCommand) {\n return {};\n }\n\n if (!isGteNext13) return {};\n\n const isSwcPluginAvailable = getIsSwcPluginAvailable(intlayerConfig);\n\n runOnce(\n join(baseDir, '.intlayer', 'cache', 'intlayer-prune-plugin-enabled.lock'),\n () => {\n if (isSwcPluginAvailable) {\n logger([\n `Build optimization ${colorize('enabled', ANSIColors.GREEN)}`,\n colorize(`(import mode:`, ANSIColors.GREY_DARK),\n colorize(importMode ?? IMPORT_MODE, ANSIColors.BLUE),\n colorize(`)`, ANSIColors.GREY_DARK),\n ]);\n } else {\n logger([\n colorize('Recommended: Install', ANSIColors.GREY),\n colorize('@intlayer/swc', ANSIColors.GREY_LIGHT),\n colorize(\n 'package to enable build optimization. See documentation:',\n ANSIColors.GREY\n ),\n colorize(\n 'https://intlayer.org/docs/bundle-optimization',\n ANSIColors.GREY_LIGHT\n ),\n ]);\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-compiler-plugin-enabled.lock'\n ),\n () => {\n const isBabelExtractPluginAvailable =\n getIsBabelExtractPluginAvailable(intlayerConfig);\n\n if (isBabelExtractPluginAvailable) {\n let isEnabled = intlayerConfig.compiler?.enabled ?? true;\n\n if (isEnabled === 'build-only') {\n isEnabled = !isDevCommand;\n }\n\n if (isEnabled) {\n logger('Intlayer compiler enabled');\n } else {\n logger('Intlayer compiler disabled');\n }\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n if (!isSwcPluginAvailable) {\n return {};\n }\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n\n const fetchDictionariesEntryPath = join(mainDir, 'fetch_dictionaries.mjs');\n\n const filesListPattern = buildComponentFilesList(intlayerConfig);\n\n const filesList = [\n ...filesListPattern,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n ];\n\n const dictionaries = getDictionaries(intlayerConfig);\n\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> = {};\n\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ?? importMode ?? IMPORT_MODE;\n });\n\n return {\n experimental: {\n swcPlugins: [\n [\n resolvePluginPath(\n '@intlayer/swc',\n intlayerConfig,\n isTurbopackEnabled\n ),\n {\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n fetchDictionariesEntryPath,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n dictionaryModeMap,\n extraCallers: swcExtraCallers ?? [],\n },\n ],\n ],\n },\n };\n};\n\nconst getCommandsEvent = () => {\n const lifecycleEvent = process.env['npm_lifecycle_event'];\n const lifecycleScript = process.env['npm_lifecycle_script'] ?? '';\n\n const isDevCommand =\n lifecycleEvent === 'dev' ||\n process.argv.some((arg) => arg === 'dev') ||\n /(^|\\s)(next\\s+)?dev(\\s|$)/.test(lifecycleScript);\n\n const isBuildCommand =\n lifecycleEvent === 'build' ||\n process.argv.some((arg) => arg === 'build') ||\n /(^|\\s)(next\\s+)?build(\\s|$)/.test(lifecycleScript);\n\n const isStartCommand =\n lifecycleEvent === 'start' ||\n process.argv.some((arg) => arg === 'start') ||\n /(^|\\s)(next\\s+)?start(\\s|$)/.test(lifecycleScript);\n\n return {\n isDevCommand,\n isBuildCommand,\n isStartCommand,\n };\n};\n\ntype WebpackParams = Parameters<NextJsWebpackConfig>;\n\ntype WithIntlayerOptions = GetConfigurationOptions & {\n enableTurbopack?: boolean;\n swcExtraCallers?: SwcExtraCallerConfig[];\n};\n\n/**\n * Pin the env file used to resolve the Intlayer configuration to the Next.js\n * command being run (`dev` → `development`, `build`/`start` → `production`).\n *\n * Next.js loads the config file in several processes during a single command\n * (the main `build` process plus one or more Turbopack/webpack workers), and\n * `process.env.NODE_ENV` is not guaranteed to hold the same value in all of\n * them. Since `getConfiguration` falls back to `NODE_ENV` to pick its env file\n * (`.env.development.local` vs `.env.production.local`), those processes could\n * otherwise resolve *different* env values (e.g. `applicationURL`,\n * `INTLAYER_CLIENT_ID`). The resulting configuration would differ between\n * processes, defeating the `isCachedConfigurationUpToDate` check and forcing a\n * redundant full dictionary rebuild.\n *\n * Passing an explicit `env` keeps configuration resolution deterministic across\n * every process of the command. An `env` already set by the caller is\n * respected, and when the command cannot be determined we fall back to\n * `getConfiguration`'s own default (i.e. leave `env` unset).\n */\nconst resolveConfigOptions = (\n configOptions?: WithIntlayerOptions\n): WithIntlayerOptions | undefined => {\n // Respect an explicit override from the caller (idempotent on re-entry).\n if (configOptions?.env) return configOptions;\n\n const { isDevCommand, isBuildCommand, isStartCommand } = getCommandsEvent();\n\n const env = isDevCommand\n ? 'development'\n : isBuildCommand || isStartCommand\n ? 'production'\n : undefined;\n\n if (!env) return configOptions;\n\n return {\n ...configOptions,\n env,\n };\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayerSync(nextConfig)\n * ```\n */\nexport const withIntlayerSync = <T extends Partial<NextConfig>>(\n nextConfig: T = {} as T,\n configOptions?: WithIntlayerOptions\n): NextConfig & T => {\n if (typeof nextConfig !== 'object') {\n nextConfig = {} as T;\n }\n\n const resolvedConfigOptions = resolveConfigOptions(configOptions);\n\n const intlayerConfig = getConfiguration(resolvedConfigOptions);\n\n logConfigDetails(resolvedConfigOptions);\n\n const appLogger = getAppLogger(intlayerConfig);\n\n const { isGteNext13, isGteNext15, isGteNext16, isTurbopackStable } =\n getNextVersionFlags(intlayerConfig);\n\n const isTurbopackEnabledFromCommand = isGteNext16\n ? // Next@16 enables turbopack by default; disable with --webpack\n !process.env['npm_lifecycle_script']?.includes('--webpack')\n : // Next@15 uses --turbopack, Next@14 uses --turbo\n process.env['npm_lifecycle_script']?.includes('--turbo');\n\n const isTurbopackEnabled =\n configOptions?.enableTurbopack ?? isTurbopackEnabledFromCommand;\n\n if (isTurbopackEnabled && typeof nextConfig.webpack !== 'undefined') {\n appLogger(\n 'Turbopack is enabled but a custom webpack config is present. It will be ignored.'\n );\n }\n\n const { isBuildCommand, isDevCommand } = getCommandsEvent();\n\n // Only provide turbo-specific config if user explicitly sets it\n const turboConfig = {\n resolveAlias: getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => `./${value}`, // prefix by './' to consider the path as relative to the project root. This is necessary for turbopack to work correctly.\n }),\n\n rules: {\n '*.node': {\n as: '*.node',\n loaders: ['node-loader'],\n },\n },\n };\n\n const serverExternalPackages = [\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n '@intlayer/engine',\n '@intlayer/webpack',\n ];\n\n let env: Record<string, string> = {};\n\n if (isBuildCommand) {\n const dictionaries = getDictionaries(intlayerConfig);\n\n if (Object.keys(dictionaries).length === 0) {\n appLogger('No dictionaries found. Please check your configuration.', {\n isVerbose: true,\n });\n }\n\n const unusedNodeTypes = getUnusedNodeTypes(dictionaries);\n\n if (unusedNodeTypes && unusedNodeTypes.length > 0) {\n appLogger(\n [\n 'Filtering out unused logic:',\n unusedNodeTypes\n .filter(\n (key) => !['reactNode', 'solidNode', 'preactNode'].includes(key)\n )\n .map((key) => colorize(key, ANSIColors.BLUE))\n .join(', '),\n ],\n {\n isVerbose: true,\n }\n );\n }\n\n env = {\n ...env,\n\n // Tree shacking based on unused node types\n ...formatNodeTypeToEnvVar(unusedNodeTypes),\n\n // Tree shacking the dictionary selector logic\n // (collections / variants)\n ...formatDictionarySelectorEnvVar(getHasDictionarySelector(dictionaries)),\n\n // Tree shacking based on config\n ...getConfigEnvVars(intlayerConfig),\n };\n }\n\n const getNewConfig = (): Partial<NextConfig> => {\n let config: Partial<NextConfig> = {\n env,\n };\n\n if (isGteNext15) {\n config = {\n ...config,\n serverExternalPackages,\n };\n }\n\n if (isGteNext13 && !isGteNext15) {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n serverComponentsExternalPackages: serverExternalPackages,\n },\n };\n }\n\n if (isTurbopackEnabled) {\n if (isGteNext15 && isTurbopackStable) {\n config = {\n ...config,\n turbopack: turboConfig,\n };\n } else {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n // @ts-ignore exist in next@14\n turbo: turboConfig,\n },\n };\n }\n } else {\n config = {\n ...config,\n webpack: (config: WebpackParams['0'], options: WebpackParams[1]) => {\n // Only add Intlayer plugin on server side (node runtime)\n const { isServer, nextRuntime } = options;\n\n // If the user has defined their own webpack config, call it\n if (typeof nextConfig.webpack === 'function') {\n config = nextConfig.webpack(config, options);\n }\n\n // Rspack set external as false by default\n // Overwrite it to allow pushing the desired externals\n if (config.externals === false) {\n config.externals = [];\n }\n\n // Mark server-only modules as externals (function form handles subpaths)\n const externalExact = new Set([\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n ]);\n const externalPrefixes = ['@intlayer/engine', '@intlayer/webpack'];\n config.externals.push(\n (\n { request }: { request?: string },\n callback: (err: Error | null, result?: string) => void\n ) => {\n if (\n request &&\n (externalExact.has(request) ||\n externalPrefixes.some(\n (prefix) =>\n request === prefix || request.startsWith(`${prefix}/`)\n ))\n ) {\n return callback(null, `commonjs ${request}`);\n }\n callback(null);\n }\n );\n\n // Use `node-loader` for any `.node` files\n config.module.rules.push({\n test: /\\.node$/,\n loader: 'node-loader',\n });\n\n // Always alias on the server (node/edge) for stability.\n // On the client, alias only when not using live sync.\n config.resolve.alias = {\n ...config.resolve.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value), // get absolute path\n }),\n };\n\n // Activate watch mode webpack plugin\n if (isDevCommand && isServer && nextRuntime === 'nodejs') {\n // Optional as rspack not support plugin yet\n config.plugins.push(new IntlayerPlugin(intlayerConfig));\n }\n\n return config;\n },\n };\n }\n\n return config;\n };\n\n const pruneConfig: Partial<NextConfig> = getPruneConfig(\n intlayerConfig,\n isBuildCommand,\n isTurbopackEnabled ?? false,\n isDevCommand,\n isGteNext13,\n configOptions?.swcExtraCallers\n );\n\n const intlayerNextConfig: Partial<NextConfig> = defu(\n getNewConfig(),\n pruneConfig\n );\n\n // Merge the new config with the user's config\n const result = defu(intlayerNextConfig, nextConfig) as NextConfig & T;\n\n return result;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayer(nextConfig)\n * ```\n *\n * > Node withIntlayer is a promise function. Use withIntlayerSync instead if you want to use it synchronously.\n * > Using the promise allows to prepare the intlayer dictionaries before the build starts.\n *\n */\nexport const withIntlayer = async <T extends NextConfig | Partial<NextConfig>>(\n nextConfig: T | Promise<T> = {} as T,\n configOptions?: WithIntlayerOptions\n): Promise<NextConfig & T> => {\n const { isBuildCommand, isDevCommand, isStartCommand } = getCommandsEvent();\n\n process.env.INTLAYER_IS_DEV_COMMAND = isDevCommand ? 'true' : 'false';\n\n const resolvedConfigOptions = resolveConfigOptions(configOptions);\n\n const intlayerConfig = getConfiguration(resolvedConfigOptions);\n\n const { mode } = intlayerConfig.build;\n\n // Only call prepareIntlayer during `dev` or `build` (not during `start`)\n // If prod: clean and rebuild once\n // If dev: rebuild only once if it's more than 1 hour since last rebuild\n if (!isStartCommand && (isDevCommand || isBuildCommand || mode === 'auto')) {\n // prepareIntlayer use runOnce to ensure to run only once because will run twice on client and server side otherwise\n await prepareIntlayer(intlayerConfig, {\n clean: isBuildCommand,\n cacheTimeoutMs: isBuildCommand\n ? 1000 * 30 // 30 seconds for build (to ensure to rebuild all dictionaries)\n : 1000 * 60 * 60, // 1 hour for dev (default cache timeout)\n env: isBuildCommand ? 'prod' : 'dev',\n });\n }\n\n const nextConfigResolved = await nextConfig;\n\n return withIntlayerSync(nextConfigResolved, resolvedConfigOptions);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAM,uBAAuB,mBAAmC;CAC9D,IAAI,cAAcA,0BAAgB;CAElC,IAAI;EAIF,eAFE,eAAe,OAAO,yDAA6B,EAC1B,CAAC,mBACZ,CAAC,CAAC;CACpB,QAAQ,CAER;CAEA,OAAO;EACL,yDAA6B,aAAa,KAAK,QAAQ;EACvD,yDAA6B,aAAa,KAAK,QAAQ;EACvD,yDAA6B,aAAa,KAAK,QAAQ;EACvD,+DAAmC,aAAa,KAAK,QAAQ;CAC/D;AACF;AAGA,MAAM,2BAA2B,mBAAmC;CAClE,IAAI;EAGF,CADE,eAAe,OAAO,yDAA6B,EACtC,CAAC,QAAQ,eAAe;EACvC,OAAO;CACT,SAAS,IAAI;EACX,OAAO;CACT;AACF;AAGA,MAA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AY;MACV,eAAe;MACf,YAAY,iCAA0B,KAAK;KAC7C,CAAC;IACH;IAGA,IAAI,gBAAgB,YAAY,gBAAgB,UAE9C,OAAO,QAAQ,KAAK,IAAIE,iCAAe,cAAc,CAAC;IAGxD,OAAO;GACT;EACF;EAGF,OAAO;CACT;CAEA,MAAM,cAAmC,eACvC,gBACA,gBACA,sBAAsB,OACtB,cACA,aACA,eAAe,eACjB;CAUA,qCAPE,aAAa,GACb,WAImC,GAAG,UAE5B;AACd;;;;;;;;;;;;;;;;AAiBA,MAAa,eAAe,OAC1B,aAA6B,CAAC,GAC9B,kBAC4B;CAC5B,MAAM,EAAE,gBAAgB,cAAc,mBAAmB,iBAAiB;CAE1E,QAAQ,IAAI,0BAA0B,eAAe,SAAS;CAE9D,MAAM,wBAAwB,qBAAqB,aAAa;CAEhE,MAAM,6DAAkC,qBAAqB;CAE7D,MAAM,EAAE,SAAS,eAAe;CAKhC,IAAI,CAAC,mBAAmB,gBAAgB,kBAAkB,SAAS,SAEjE,kDAAsB,gBAAgB;EACpC,OAAO;EACP,gBAAgB,iBACZ,MAAO,KACP,MAAO,KAAK;EAChB,KAAK,iBAAiB,SAAS;CACjC,CAAC;CAGH,MAAM,qBAAqB,MAAM;CAEjC,OAAO,iBAAiB,oBAAoB,qBAAqB;AACnE"}
|
|
1
|
+
{"version":3,"file":"withIntlayer.cjs","names":["nextPackageJSON","getIsSwcPluginSupported","ANSIColors","MINIMUM_SWC_PLUGIN_NEXT_VERSION","IMPORT_MODE","getIsPurgePipelineAvailable","resolveSwcLogLevel","IntlayerPlugin","prepareSwcOptimization"],"sources":["../../../src/server/withIntlayer.ts"],"sourcesContent":["import { join, relative, resolve } from 'node:path';\nimport type { SwcExtraCallerConfig } from '@intlayer/config/callers';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { IMPORT_MODE } from '@intlayer/config/defaultValues';\nimport {\n formatDictionarySelectorEnvVar,\n formatNodeTypeToEnvVar,\n formatOptimizedNestingEnvVar,\n getConfigEnvVars,\n} from '@intlayer/config/envVars';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n compareVersions,\n getAlias,\n getHasDictionarySelector,\n getProjectRequire,\n getUnusedNodeTypes,\n normalizePath,\n} from '@intlayer/config/utils';\nimport { getNestedDictionaryGraph } from '@intlayer/core/dictionaryManipulator';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport { prepareIntlayer } from '@intlayer/engine/build';\nimport { logConfigDetails } from '@intlayer/engine/cli';\nimport { buildComponentFilesList, runOnce } from '@intlayer/engine/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { IntlayerPlugin } from '@intlayer/webpack';\nimport { defu } from 'defu';\nimport type { NextConfig } from 'next';\nimport type { NextJsWebpackConfig } from 'next/dist/server/config-shared';\nimport nextPackageJSON from 'next/package.json' with { type: 'json' };\nimport {\n type FieldRenameMapByDictionaryKey,\n getIsPurgePipelineAvailable,\n prepareSwcOptimization,\n resolveSwcLogLevel,\n} from './prepareSwcOptimization';\nimport {\n getIsSwcPluginSupported,\n MINIMUM_SWC_PLUGIN_NEXT_VERSION,\n} from './swcPluginCompatibility';\n\nexport {\n getIsSwcPluginSupported,\n MINIMUM_SWC_PLUGIN_NEXT_VERSION,\n} from './swcPluginCompatibility';\n\n/**\n * Resolve the Next.js version from the *user's* project at runtime.\n * A static `import from 'next/package.json'` would resolve relative to\n * next-intlayer's own node_modules, which may differ in a monorepo.\n */\nconst getNextVersionFlags = (intlayerConfig: IntlayerConfig) => {\n let nextVersion = nextPackageJSON.version;\n\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n const pkg = requireFunction('next/package.json') as { version: string };\n nextVersion = pkg.version;\n } catch {\n // keep default\n }\n\n return {\n nextVersion,\n isGteNext13: compareVersions(nextVersion, '≥', '13.0.0'),\n isGteNext15: compareVersions(nextVersion, '≥', '15.0.0'),\n isGteNext16: compareVersions(nextVersion, '≥', '16.0.0'),\n isTurbopackStable: compareVersions(nextVersion, '≥', '15.3.0'),\n /**\n * Whether this Next.js release can load the `@intlayer/swc` Wasm plugin.\n * See {@link MINIMUM_SWC_PLUGIN_NEXT_VERSION}.\n */\n isSwcPluginSupported: getIsSwcPluginSupported(nextVersion),\n };\n};\n\n// Check if SWC plugin is available\nconst getIsSwcPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/swc');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\n// Check if Babel plugin is available\nconst getIsBabelExtractPluginAvailable = (intlayerConfig: IntlayerConfig) => {\n try {\n const requireFunction =\n intlayerConfig.build?.require ?? getProjectRequire();\n requireFunction.resolve('@intlayer/babel');\n return true;\n } catch (_e) {\n return false;\n }\n};\n\nconst resolvePluginPath = (\n pluginPath: string,\n intlayerConfig: IntlayerConfig,\n isTurbopackEnabled: boolean\n): string => {\n const requireFunction = intlayerConfig.build?.require ?? getProjectRequire();\n const pluginPathResolved = requireFunction?.resolve(pluginPath);\n\n if (isTurbopackEnabled)\n // Relative path for turbopack\n return normalizePath(`./${relative(process.cwd(), pluginPathResolved)}`);\n\n // Absolute path for webpack\n return pluginPathResolved;\n};\n\ntype GetPruneConfigParams = {\n intlayerConfig: IntlayerConfig;\n isBuildCommand: boolean;\n isTurbopackEnabled: boolean;\n isDevCommand: boolean;\n isGteNext13: boolean;\n /** Whether the resolved Next.js version can load the Wasm plugin. */\n isSwcPluginSupported: boolean;\n /** Resolved Next.js version, reported when the plugin has to stand down. */\n nextVersion: string;\n swcExtraCallers?: SwcExtraCallerConfig[];\n fieldRenameMap?: FieldRenameMapByDictionaryKey;\n};\n\nconst getPruneConfig = ({\n intlayerConfig,\n isBuildCommand,\n isTurbopackEnabled,\n isDevCommand,\n isGteNext13,\n isSwcPluginSupported,\n nextVersion,\n swcExtraCallers,\n fieldRenameMap,\n}: GetPruneConfigParams): Partial<NextConfig> => {\n const { optimize, minify, purge } = intlayerConfig.build;\n const editorEnabled = intlayerConfig.editor.enabled;\n const importMode =\n intlayerConfig.build.importMode ?? intlayerConfig.dictionary?.importMode;\n const {\n dictionariesDir,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = intlayerConfig.system;\n const { baseDir } = intlayerConfig.system;\n const logger = getAppLogger(intlayerConfig);\n\n if (optimize === false) {\n return {};\n }\n if (optimize === undefined && !isBuildCommand) {\n return {};\n }\n\n if (!isGteNext13) return {};\n\n const isSwcPluginAvailable = getIsSwcPluginAvailable(intlayerConfig);\n\n runOnce(\n join(baseDir, '.intlayer', 'cache', 'intlayer-prune-plugin-enabled.lock'),\n () => {\n if (isSwcPluginAvailable && !isSwcPluginSupported) {\n logger(\n [\n `Build optimization ${colorize('disabled', ANSIColors.GREY_DARK)}:`,\n colorize('@intlayer/swc', ANSIColors.GREY_LIGHT),\n colorize(\n `cannot run on Next.js ${nextVersion} — its bundled SWC predates the`,\n ANSIColors.GREY\n ),\n colorize(\n 'stable Wasm plugin ABI. Upgrade to Next.js',\n ANSIColors.GREY\n ),\n colorize(MINIMUM_SWC_PLUGIN_NEXT_VERSION, ANSIColors.BLUE),\n colorize('or later to enable it.', ANSIColors.GREY),\n ],\n { level: 'warn' }\n );\n } else if (isSwcPluginAvailable) {\n logger([\n `Build optimization ${colorize('enabled', ANSIColors.GREEN)}`,\n colorize(`(import mode:`, ANSIColors.GREY_DARK),\n colorize(importMode ?? IMPORT_MODE, ANSIColors.BLUE),\n colorize(`)`, ANSIColors.GREY_DARK),\n ]);\n\n // The purge / minify pipeline stands down — with its own explanation —\n // when the editor needs full dictionary content, when compat-adapter\n // callers hide call sites from the usage analyser, or when\n // `@intlayer/babel` (which runs it) is not resolvable.\n const isPurgePipelineEnabled =\n !editorEnabled &&\n !swcExtraCallers?.length &&\n getIsPurgePipelineAvailable(intlayerConfig);\n\n if (isPurgePipelineEnabled && minify) {\n logger(\n `Dictionary minification ${colorize('enabled', ANSIColors.GREEN)}`\n );\n }\n\n if (isPurgePipelineEnabled && purge) {\n logger(\n `Dictionary purge unused keys ${colorize('enabled', ANSIColors.GREEN)}`\n );\n }\n } else {\n logger([\n colorize('Recommended: Install', ANSIColors.GREY),\n colorize('@intlayer/swc', ANSIColors.GREY_LIGHT),\n colorize(\n 'package to enable build optimization. See documentation:',\n ANSIColors.GREY\n ),\n colorize(\n 'https://intlayer.org/docs/bundle-optimization',\n ANSIColors.GREY_LIGHT\n ),\n ]);\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n runOnce(\n join(\n baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-compiler-plugin-enabled.lock'\n ),\n () => {\n const isBabelExtractPluginAvailable =\n getIsBabelExtractPluginAvailable(intlayerConfig);\n\n if (isBabelExtractPluginAvailable) {\n let isEnabled = intlayerConfig.compiler?.enabled ?? true;\n\n if (isEnabled === 'build-only') {\n isEnabled = !isDevCommand;\n }\n\n // Only the enabled state is reported: disabling the compiler is an\n // explicit configuration choice, so announcing it on every build adds\n // noise without telling the user anything they did not ask for.\n if (isEnabled) {\n logger('Intlayer compiler enabled');\n }\n }\n },\n {\n cacheTimeoutMs: 1000 * 30, // 30 seconds\n }\n );\n\n // Registering the plugin on a host that cannot load it is not a degraded\n // build but a failed one: SWC aborts with `failed to invoke plugin`. Standing\n // down leaves the app running off the runtime dictionary registry, which the\n // transform would otherwise have emptied.\n if (!isSwcPluginAvailable || !isSwcPluginSupported) {\n return {};\n }\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n\n const fetchDictionariesEntryPath = join(mainDir, 'fetch_dictionaries.mjs');\n\n const filesListPattern = buildComponentFilesList(intlayerConfig);\n\n const filesList = [\n ...filesListPattern,\n dictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n unmergedDictionariesEntryPath, // should add dictionariesEntryPath to replace it by a empty object if import made dynamic\n ];\n\n const dictionaries = getDictionaries(intlayerConfig);\n\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> = {};\n\n (Object.values(dictionaries) as Dictionary[]).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ?? importMode ?? IMPORT_MODE;\n });\n\n // Dictionaries holding `nest()` references: their static import is re-pointed\n // at the companion module carrying the nest targets.\n const nestingDictionaryKeys = [\n ...getNestedDictionaryGraph(Object.values(dictionaries)).keys(),\n ];\n\n return {\n experimental: {\n swcPlugins: [\n [\n resolvePluginPath(\n '@intlayer/swc',\n intlayerConfig,\n isTurbopackEnabled\n ),\n {\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n fetchDictionariesEntryPath,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n nestingDictionaryKeys,\n dictionaryModeMap,\n extraCallers: swcExtraCallers ?? [],\n // Rewrites `content.title` → `content.a` to match the compiled\n // dictionaries the `build.minify` pass already renamed.\n fieldRenameMap: fieldRenameMap ?? {},\n logLevel: resolveSwcLogLevel(intlayerConfig),\n },\n ],\n ],\n },\n };\n};\n\nconst getCommandsEvent = () => {\n const lifecycleEvent = process.env['npm_lifecycle_event'];\n const lifecycleScript = process.env['npm_lifecycle_script'] ?? '';\n\n const isDevCommand =\n lifecycleEvent === 'dev' ||\n process.argv.some((arg) => arg === 'dev') ||\n /(^|\\s)(next\\s+)?dev(\\s|$)/.test(lifecycleScript);\n\n const isBuildCommand =\n lifecycleEvent === 'build' ||\n process.argv.some((arg) => arg === 'build') ||\n /(^|\\s)(next\\s+)?build(\\s|$)/.test(lifecycleScript);\n\n const isStartCommand =\n lifecycleEvent === 'start' ||\n process.argv.some((arg) => arg === 'start') ||\n /(^|\\s)(next\\s+)?start(\\s|$)/.test(lifecycleScript);\n\n return {\n isDevCommand,\n isBuildCommand,\n isStartCommand,\n };\n};\n\ntype WebpackParams = Parameters<NextJsWebpackConfig>;\n\ntype WithIntlayerOptions = GetConfigurationOptions & {\n enableTurbopack?: boolean;\n swcExtraCallers?: SwcExtraCallerConfig[];\n\n /**\n * Field-rename tables produced by the purge / minify pipeline, forwarded to\n * the `@intlayer/swc` plugin so it rewrites source accesses to match the\n * renamed dictionaries.\n *\n * @internal Set by {@link withIntlayer}; `withIntlayerSync` on its own runs\n * no dictionary rewrite, so it leaves this unset and no rename is applied.\n */\n fieldRenameMap?: FieldRenameMapByDictionaryKey;\n};\n\n/**\n * Pin the env file used to resolve the Intlayer configuration to the Next.js\n * command being run (`dev` → `development`, `build`/`start` → `production`).\n *\n * Next.js loads the config file in several processes during a single command\n * (the main `build` process plus one or more Turbopack/webpack workers), and\n * `process.env.NODE_ENV` is not guaranteed to hold the same value in all of\n * them. Since `getConfiguration` falls back to `NODE_ENV` to pick its env file\n * (`.env.development.local` vs `.env.production.local`), those processes could\n * otherwise resolve *different* env values (e.g. `applicationURL`,\n * `INTLAYER_CLIENT_ID`). The resulting configuration would differ between\n * processes, defeating the `isCachedConfigurationUpToDate` check and forcing a\n * redundant full dictionary rebuild.\n *\n * Passing an explicit `env` keeps configuration resolution deterministic across\n * every process of the command. An `env` already set by the caller is\n * respected, and when the command cannot be determined we fall back to\n * `getConfiguration`'s own default (i.e. leave `env` unset).\n */\nconst resolveConfigOptions = (\n configOptions?: WithIntlayerOptions\n): WithIntlayerOptions | undefined => {\n // Respect an explicit override from the caller (idempotent on re-entry).\n if (configOptions?.env) return configOptions;\n\n const { isDevCommand, isBuildCommand, isStartCommand } = getCommandsEvent();\n\n const env = isDevCommand\n ? 'development'\n : isBuildCommand || isStartCommand\n ? 'production'\n : undefined;\n\n if (!env) return configOptions;\n\n return {\n ...configOptions,\n env,\n };\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayerSync(nextConfig)\n * ```\n */\nexport const withIntlayerSync = <T extends Partial<NextConfig>>(\n nextConfig: T = {} as T,\n configOptions?: WithIntlayerOptions\n): NextConfig & T => {\n if (typeof nextConfig !== 'object') {\n nextConfig = {} as T;\n }\n\n const resolvedConfigOptions = resolveConfigOptions(configOptions);\n\n const intlayerConfig = getConfiguration(resolvedConfigOptions);\n\n logConfigDetails(resolvedConfigOptions);\n\n const appLogger = getAppLogger(intlayerConfig);\n\n const {\n nextVersion,\n isGteNext13,\n isGteNext15,\n isGteNext16,\n isTurbopackStable,\n isSwcPluginSupported,\n } = getNextVersionFlags(intlayerConfig);\n\n const isTurbopackEnabledFromCommand = isGteNext16\n ? // Next@16 enables turbopack by default; disable with --webpack\n !process.env['npm_lifecycle_script']?.includes('--webpack')\n : // Next@15 uses --turbopack, Next@14 uses --turbo\n process.env['npm_lifecycle_script']?.includes('--turbo');\n\n const isTurbopackEnabled =\n configOptions?.enableTurbopack ?? isTurbopackEnabledFromCommand;\n\n if (isTurbopackEnabled && typeof nextConfig.webpack !== 'undefined') {\n appLogger(\n 'Turbopack is enabled but a custom webpack config is present. It will be ignored.'\n );\n }\n\n const { isBuildCommand, isDevCommand } = getCommandsEvent();\n\n // Only provide turbo-specific config if user explicitly sets it\n const turboConfig = {\n resolveAlias: getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => `./${value}`, // prefix by './' to consider the path as relative to the project root. This is necessary for turbopack to work correctly.\n }),\n\n rules: {\n '*.node': {\n as: '*.node',\n loaders: ['node-loader'],\n },\n },\n };\n\n const serverExternalPackages = [\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n '@intlayer/engine',\n '@intlayer/webpack',\n ];\n\n let env: Record<string, string> = {};\n\n if (isBuildCommand) {\n const dictionaries = getDictionaries(intlayerConfig);\n\n if (Object.keys(dictionaries).length === 0) {\n appLogger('No dictionaries found. Please check your configuration.', {\n isVerbose: true,\n });\n }\n\n const unusedNodeTypes = getUnusedNodeTypes(dictionaries);\n\n if (unusedNodeTypes && unusedNodeTypes.length > 0) {\n appLogger(\n [\n 'Filtering out unused logic:',\n unusedNodeTypes\n .filter(\n (key) => !['reactNode', 'solidNode', 'preactNode'].includes(key)\n )\n .map((key) => colorize(key, ANSIColors.BLUE))\n .join(', '),\n ],\n {\n isVerbose: true,\n }\n );\n }\n\n env = {\n ...env,\n\n // Tree shacking based on unused node types\n ...formatNodeTypeToEnvVar(unusedNodeTypes),\n\n // Selects the local `nest()` resolver, which reads the nest targets\n // attached to each dictionary by the optimize transform instead of the\n // registry that transform empties.\n ...formatOptimizedNestingEnvVar(intlayerConfig.build.optimize !== false),\n\n // Tree shacking the dictionary selector logic\n // (collections / variants)\n ...formatDictionarySelectorEnvVar(getHasDictionarySelector(dictionaries)),\n\n // Tree shacking based on config\n ...getConfigEnvVars(intlayerConfig),\n };\n }\n\n const getNewConfig = (): Partial<NextConfig> => {\n let config: Partial<NextConfig> = {\n env,\n };\n\n if (isGteNext15) {\n config = {\n ...config,\n serverExternalPackages,\n };\n }\n\n if (isGteNext13 && !isGteNext15) {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n serverComponentsExternalPackages: serverExternalPackages,\n },\n };\n }\n\n if (isTurbopackEnabled) {\n if (isGteNext15 && isTurbopackStable) {\n config = {\n ...config,\n turbopack: turboConfig,\n };\n } else {\n config = {\n ...config,\n experimental: {\n ...(config?.experimental ?? {}),\n // @ts-ignore exist in next@14\n turbo: turboConfig,\n },\n };\n }\n } else {\n config = {\n ...config,\n webpack: (config: WebpackParams['0'], options: WebpackParams[1]) => {\n // Only add Intlayer plugin on server side (node runtime)\n const { isServer, nextRuntime } = options;\n\n // If the user has defined their own webpack config, call it\n if (typeof nextConfig.webpack === 'function') {\n config = nextConfig.webpack(config, options);\n }\n\n // Rspack set external as false by default\n // Overwrite it to allow pushing the desired externals\n if (config.externals === false) {\n config.externals = [];\n }\n\n // Mark server-only modules as externals (function form handles subpaths)\n const externalExact = new Set([\n 'esbuild',\n 'module',\n 'fs',\n 'chokidar',\n 'fsevents',\n 'recast',\n ]);\n const externalPrefixes = ['@intlayer/engine', '@intlayer/webpack'];\n config.externals.push(\n (\n { request }: { request?: string },\n callback: (err: Error | null, result?: string) => void\n ) => {\n if (\n request &&\n (externalExact.has(request) ||\n externalPrefixes.some(\n (prefix) =>\n request === prefix || request.startsWith(`${prefix}/`)\n ))\n ) {\n return callback(null, `commonjs ${request}`);\n }\n callback(null);\n }\n );\n\n // Use `node-loader` for any `.node` files\n config.module.rules.push({\n test: /\\.node$/,\n loader: 'node-loader',\n });\n\n // Always alias on the server (node/edge) for stability.\n // On the client, alias only when not using live sync.\n config.resolve.alias = {\n ...config.resolve.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value), // get absolute path\n }),\n };\n\n // Activate watch mode webpack plugin\n if (isDevCommand && isServer && nextRuntime === 'nodejs') {\n // Optional as rspack not support plugin yet\n config.plugins.push(new IntlayerPlugin(intlayerConfig));\n }\n\n return config;\n },\n };\n }\n\n return config;\n };\n\n const pruneConfig: Partial<NextConfig> = getPruneConfig({\n intlayerConfig,\n isBuildCommand,\n isTurbopackEnabled: isTurbopackEnabled ?? false,\n isDevCommand,\n isGteNext13,\n isSwcPluginSupported,\n nextVersion,\n swcExtraCallers: configOptions?.swcExtraCallers,\n fieldRenameMap: configOptions?.fieldRenameMap,\n });\n\n const intlayerNextConfig: Partial<NextConfig> = defu(\n getNewConfig(),\n pruneConfig\n );\n\n // Merge the new config with the user's config\n const result = defu(intlayerNextConfig, nextConfig) as NextConfig & T;\n\n return result;\n};\n\n/**\n * A Next.js plugin that adds the intlayer configuration to the webpack configuration\n * and sets the environment variables\n *\n * Usage:\n *\n * ```ts\n * // next.config.js\n * export default withIntlayer(nextConfig)\n * ```\n *\n * > Node withIntlayer is a promise function. Use withIntlayerSync instead if you want to use it synchronously.\n * > Using the promise allows to prepare the intlayer dictionaries before the build starts.\n *\n */\nexport const withIntlayer = async <T extends NextConfig | Partial<NextConfig>>(\n nextConfig: T | Promise<T> = {} as T,\n configOptions?: WithIntlayerOptions\n): Promise<NextConfig & T> => {\n const { isBuildCommand, isDevCommand, isStartCommand } = getCommandsEvent();\n\n process.env.INTLAYER_IS_DEV_COMMAND = isDevCommand ? 'true' : 'false';\n\n const resolvedConfigOptions = resolveConfigOptions(configOptions);\n\n const intlayerConfig = getConfiguration(resolvedConfigOptions);\n\n const { mode } = intlayerConfig.build;\n\n // Only call prepareIntlayer during `dev` or `build` (not during `start`)\n // If prod: clean and rebuild once\n // If dev: rebuild only once if it's more than 1 hour since last rebuild\n if (!isStartCommand && (isDevCommand || isBuildCommand || mode === 'auto')) {\n // prepareIntlayer use runOnce to ensure to run only once because will run twice on client and server side otherwise\n await prepareIntlayer(intlayerConfig, {\n clean: isBuildCommand,\n cacheTimeoutMs: isBuildCommand\n ? 1000 * 30 // 30 seconds for build (to ensure to rebuild all dictionaries)\n : 1000 * 60 * 60, // 1 hour for dev (default cache timeout)\n env: isBuildCommand ? 'prod' : 'dev',\n });\n }\n\n // Remove unused content fields and rename the remaining ones to short\n // aliases, then hand the rename tables to `withIntlayerSync` so the SWC\n // plugin rewrites the matching source accesses. Only meaningful for a\n // production build — the optimize pipeline is off during `next dev`.\n //\n // `isSwcPluginUsable` gates the dictionary rewrite on the plugin actually\n // running: it is the only half that fixes up the source, so minifying without\n // it would leave the code reading field names the dictionaries no longer have.\n const { isSwcPluginSupported } = getNextVersionFlags(intlayerConfig);\n\n const fieldRenameMap = isBuildCommand\n ? await prepareSwcOptimization(intlayerConfig, {\n configOptions: resolvedConfigOptions,\n swcExtraCallers: configOptions?.swcExtraCallers,\n isSwcPluginUsable:\n isSwcPluginSupported && getIsSwcPluginAvailable(intlayerConfig),\n })\n : {};\n\n const nextConfigResolved = await nextConfig;\n\n return withIntlayerSync(nextConfigResolved, {\n ...resolvedConfigOptions,\n fieldRenameMap,\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAM,uBAAuB,mBAAmC;CAC9D,IAAI,cAAcA,0BAAgB;CAElC,IAAI;EAIF,eAFE,eAAe,OAAO,yDAA6B,EAC1B,CAAC,mBACZ,CAAC,CAAC;CACpB,QAAQ,CAER;CAEA,OAAO;EACL;EACA,yDAA6B,aAAa,KAAK,QAAQ;EACvD,yDAA6B,aAAa,KAAK,QAAQ;EACvD,yDAA6B,aAAa,KAAK,QAAQ;EACvD,+DAAmC,aAAa,KAAK,QAAQ;;;;;EAK7D,sBAAsBC,8DAAwB,WAAW;CAC3D;AACF;AAGA,MAAM,2BAA2B,mBAAmC;CAClE,IAAI;EAGF,CADE,eAAe,OAAO,yDAA6B,EACtC,CAAC,QAAQ,eAAe;EACvC,OAAO;CACT,SAAS,IAAI;EACX,OAAO;CACT;AACF;AAGA,MAAM,oCAAoC,mBAAmC;CAC3E,IAAI;EAGF,CADE,eAAe,OAAO,yDAA6B,EACtC,CAAC,QAAQ,iBAAiB;EACzC,OAAO;CACT,SAAS,IAAI;EACX,OAAO;CACT;AACF;AAEA,MAAM,qBACJ,YACA,gBACA,uBACW;CAEX,MAAM,sBADkB,eAAe,OAAO,yDAA6B,EACjC,EAAE,QAAQ,UAAU;CAE9D,IAAI,oBAEF,iDAAqB,6BAAc,QAAQ,IAAI,GAAG,kBAAkB,GAAG;CAGzE,OAAO;AACT;AAgBA,MAAM,kBAAkB,EACtB,gBACA,gBACA,oBACA,cACA,aACA,sBACA,aACA,iBACA,qBAC+C;CAC/C,MAAM,EAAE,UAAU,QAAQ,UAAU,eAAe;CACnD,MAAM,gBAAgB,eAAe,OAAO;CAC5C,MAAM,aACJ,eAAe,MAAM,cAAc,eAAe,YAAY;CAChE,MAAM,EACJ,iBACA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B;EAC1C,GAAG;EACH;CACF,CAAC;AACH"}
|
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import { localeDetector as localeDetector$1 } from "./localeDetector.mjs";
|
|
2
|
-
import { getCanonicalPath, getDomainHostname, getDomainOrigin, getInternalPath, getLocaleFromDomain, getLocalizedPath, getRewriteRules } from "@intlayer/core/localization";
|
|
2
|
+
import { formatProxyEnabledMessage, getCanonicalPath, getDomainHostname, getDomainOrigin, getInternalPath, getLocaleFromDomain, getLocalizedPath, getRewriteRules, isProxyStorageLocaleEnabled, resolveProxyMode } from "@intlayer/core/localization";
|
|
3
3
|
import { getLocaleFromStorageServer, setLocaleInStorageServer } from "@intlayer/core/utils";
|
|
4
|
-
import { internationalization, routing } from "@intlayer/config/built";
|
|
4
|
+
import { internationalization, log, routing } from "@intlayer/config/built";
|
|
5
5
|
import { ROUTING_MODE } from "@intlayer/config/defaultValues";
|
|
6
|
+
import { getAppLogger } from "@intlayer/config/logger";
|
|
6
7
|
import { NextResponse } from "next/server";
|
|
7
8
|
|
|
8
9
|
//#region src/proxy/intlayerProxy.ts
|
|
9
10
|
const { locales, defaultLocale } = internationalization ?? {};
|
|
10
11
|
const { basePath, mode, rewrite, domains, enableProxy } = routing ?? {};
|
|
11
|
-
const
|
|
12
|
+
const proxyMode = resolveProxyMode(enableProxy);
|
|
13
|
+
const canUseStorageLocale = isProxyStorageLocaleEnabled(proxyMode, true);
|
|
14
|
+
if (proxyMode !== "disabled") getAppLogger({ log })(formatProxyEnabledMessage(!canUseStorageLocale), { level: "info" });
|
|
12
15
|
const effectiveMode = mode ?? ROUTING_MODE;
|
|
13
16
|
const noPrefix = !(process.env.INTLAYER_ROUTING_MODE && process.env.INTLAYER_ROUTING_MODE !== "no-prefix") && effectiveMode === "no-prefix" || !(process.env.INTLAYER_ROUTING_MODE && process.env.INTLAYER_ROUTING_MODE !== "search-params") && effectiveMode === "search-params";
|
|
14
17
|
const prefixDefault = !(process.env.INTLAYER_ROUTING_MODE && process.env.INTLAYER_ROUTING_MODE !== "prefix-all") && effectiveMode === "prefix-all";
|
|
@@ -69,7 +72,7 @@ const appendLocaleSearchIfNeeded = (search, locale) => {
|
|
|
69
72
|
*
|
|
70
73
|
*/
|
|
71
74
|
const intlayerProxy = (request, _event, _response) => {
|
|
72
|
-
if (
|
|
75
|
+
if (proxyMode === "disabled") return NextResponse.next();
|
|
73
76
|
const pathname = request.nextUrl.pathname;
|
|
74
77
|
const localLocale = getLocalLocale(request);
|
|
75
78
|
if (noPrefix) return handleNoPrefix(request, localLocale, pathname);
|
|
@@ -96,13 +99,20 @@ const intlayerProxy = (request, _event, _response) => {
|
|
|
96
99
|
/**
|
|
97
100
|
* Retrieves the locale from the request cookies if available and valid.
|
|
98
101
|
*
|
|
102
|
+
* Returns `undefined` when the stored locale is not allowed to drive locale
|
|
103
|
+
* resolution (auto mode on a dev server), which makes every caller fall through
|
|
104
|
+
* to `Accept-Language` detection and then the default locale.
|
|
105
|
+
*
|
|
99
106
|
* @param request - The incoming Next.js request object.
|
|
100
107
|
* @returns - The locale found in the cookies, or undefined if not found or invalid.
|
|
101
108
|
*/
|
|
102
|
-
const getLocalLocale = (request) =>
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
109
|
+
const getLocalLocale = (request) => {
|
|
110
|
+
if (!canUseStorageLocale) return void 0;
|
|
111
|
+
return getLocaleFromStorageServer({
|
|
112
|
+
getCookie: (name) => request.cookies.get(name)?.value ?? null,
|
|
113
|
+
getHeader: (name) => request.headers.get(name) ?? null
|
|
114
|
+
});
|
|
115
|
+
};
|
|
106
116
|
/**
|
|
107
117
|
* Handles the case where URLs do not have locale prefixes.
|
|
108
118
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerProxy.mjs","names":["localeDetector"],"sources":["../../../src/proxy/intlayerProxy.ts"],"sourcesContent":["import { internationalization, routing } from '@intlayer/config/built';\nimport { ROUTING_MODE } from '@intlayer/config/defaultValues';\n\n// ── Tree-shake constants ──────────────────────────────────────────────────────\n// When these env vars are injected at build time, bundlers eliminate the\n// branches guarded by these constants.\n\nimport {\n getCanonicalPath,\n getDomainHostname,\n getDomainOrigin,\n getInternalPath,\n getLocaleFromDomain,\n getLocalizedPath,\n getRewriteRules,\n type LocaleDomainMap,\n} from '@intlayer/core/localization';\nimport {\n getLocaleFromStorageServer,\n setLocaleInStorageServer,\n} from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\nimport { localeDetector } from './localeDetector';\n\n/**\n * Controls whether locale detection occurs during Next.js prefetch requests\n * - true: Detect and apply locale during prefetch\n * - false: Use default locale during prefetch (recommended)\n *\n * This setting affects how Next.js handles locale prefetching:\n *\n * Example scenario:\n * - User's browser language is 'fr'\n * - Current page is /fr/about\n * - Link prefetches /about\n *\n * With `detectLocaleOnPrefetchNoPrefix:true`\n * - Prefetch detects 'fr' locale from browser\n * - Redirects prefetch to /fr/about\n *\n * With `detectLocaleOnPrefetchNoPrefix:false` (default)\n * - Prefetch uses default locale\n * - Redirects prefetch to /en/about (assuming 'en' is default)\n *\n * When to use true:\n * - Your app uses non-localized internal links (e.g. <a href=\"/about\">)\n * - You want consistent locale detection behavior between regular and prefetch requests\n *\n * When to use false (default):\n * - Your app uses locale-prefixed links (e.g. <a href=\"/fr/about\">)\n * - You want to optimize prefetching performance\n * - You want to avoid potential redirect loops\n */\nconst DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX = false;\n\nconst { locales, defaultLocale } = internationalization ?? {};\nconst { basePath, mode, rewrite, domains, enableProxy } = routing ?? {};\n\n// Whether the locale-routing proxy is enabled (default: true). When disabled,\n// `intlayerProxy` becomes a pass-through so apps can handle routing themselves.\n// The env var is injected at build time so bundlers can tree-shake this branch.\nconst isProxyEnabled =\n process.env.INTLAYER_ROUTING_ENABLE_PROXY !== 'false' &&\n (enableProxy ?? true);\n\n// Note: cookie names are resolved inside LocaleStorage based on configuration\n\n// Derived flags from routing.mode\nconst effectiveMode = mode ?? ROUTING_MODE;\nconst noPrefix =\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'no-prefix'\n ) &&\n effectiveMode === 'no-prefix') ||\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params'\n ) &&\n effectiveMode === 'search-params');\nconst prefixDefault =\n !(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'prefix-all'\n ) && effectiveMode === 'prefix-all';\n\nconst internalPrefix = !noPrefix;\n\nconst rewriteRules =\n process.env.INTLAYER_ROUTING_REWRITE_RULES !== 'false'\n ? getRewriteRules(rewrite, 'url')\n : undefined;\n\n/**\n * Detects if the request is a prefetch request from Next.js.\n *\n * Next.js prefetch requests are identified by:\n * - purpose: 'prefetch' (standard prefetch header)\n * - next-router-prefetch: '1' (Next.js app-router prefetch)\n *\n * Note: `next-url` and `x-nextjs-data` are intentionally NOT used here.\n * Both are also sent on real client-side navigations (RSC navigation\n * requests and pages-router data requests respectively), so treating them\n * as prefetch would force such navigations to the default locale instead\n * of the user's stored locale.\n *\n * During prefetch, we should ignore cookie-based locale detection\n * to prevent unwanted redirects when users are switching locales.\n *\n * @param request - The incoming Next.js request object.\n * @returns - True if the request is a prefetch request, false otherwise.\n */\nconst isPrefetchRequest = (request: NextRequest): boolean => {\n const purpose = request.headers.get('purpose');\n const nextRouterPrefetch = request.headers.get('next-router-prefetch');\n\n return purpose === 'prefetch' || nextRouterPrefetch === '1';\n};\n\n// Ensure locale is reflected in search params when routing mode is 'search-params'\nconst appendLocaleSearchIfNeeded = (\n search: string | undefined,\n locale: Locale\n): string | undefined => {\n if (\n (process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params') ||\n effectiveMode !== 'search-params'\n )\n return search;\n const params = new URLSearchParams(search ?? '');\n params.set('locale', locale);\n return `?${params.toString()}`;\n};\n\n/**\n * Proxy that handles the internationalization layer\n *\n * Usage:\n *\n * ```ts\n * // ./src/proxy.ts\n *\n * export { intlayerProxy as proxy } from '@intlayer/next/proxy';\n *\n * // applies this proxy only to files in the app directory\n * export const config = {\n * matcher: '/((?!api|static|.*\\\\..*|_next).*)',\n * };\n * ```\n *\n * Main proxy function for handling internationalization.\n *\n * @param request - The incoming Next.js request object.\n * @param event - The Next.js fetch event (optional).\n * @param response - The Next.js response object (optional).\n * @returns - The response to be returned to the client.\n *\n */\nexport const intlayerProxy = (\n request: NextRequest,\n _event?: NextFetchEvent,\n _response?: NextResponse\n): NextResponse => {\n // When the proxy is disabled, pass the request through untouched.\n if (!isProxyEnabled) {\n return NextResponse.next();\n }\n\n const pathname = request.nextUrl.pathname;\n\n const localLocale = getLocalLocale(request);\n\n if (noPrefix) {\n return handleNoPrefix(request, localLocale, pathname);\n }\n\n const pathLocale = getPathLocale(pathname);\n\n // Domain routing: if the path locale is mapped to a different domain, redirect there.\n // e.g. intlayer.org/zh/about → https://intlayer.zh/about\n if (\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n pathLocale &&\n domains\n ) {\n const localeDomain = domains[pathLocale];\n\n if (localeDomain) {\n const domainHost = getDomainHostname(localeDomain);\n\n if (domainHost !== request.nextUrl.hostname) {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n const targetOrigin = getDomainOrigin(localeDomain);\n\n return NextResponse.redirect(\n new URL(`${rawPath}${request.nextUrl.search}`, targetOrigin)\n );\n }\n }\n }\n\n // Domain routing: if the current hostname is exclusively mapped to one locale,\n // treat it as that locale's domain — no URL prefix needed.\n // e.g. intlayer.zh/about → internally rewrite to /zh/about\n if (process.env.INTLAYER_ROUTING_DOMAINS !== 'false' && !pathLocale) {\n const domainLocale = getLocaleFromDomain(\n request.nextUrl.hostname,\n domains as LocaleDomainMap\n );\n\n if (domainLocale) {\n const canonicalPath = getCanonicalPath(\n pathname,\n domainLocale,\n rewriteRules\n );\n\n // Never emit a trailing slash (`/zh/`): Next.js trailing-slash\n // normalisation would redirect it back and forth with this proxy.\n const internalPath = getInternalPath(canonicalPath, domainLocale);\n\n return rewriteUrl(\n request,\n internalPath + (request.nextUrl.search ?? ''),\n domainLocale\n );\n }\n }\n\n return handlePrefix(request, localLocale, pathLocale, pathname);\n};\n\n/**\n * Retrieves the locale from the request cookies if available and valid.\n *\n * @param request - The incoming Next.js request object.\n * @returns - The locale found in the cookies, or undefined if not found or invalid.\n */\nconst getLocalLocale = (request: NextRequest): Locale | undefined =>\n getLocaleFromStorageServer({\n getCookie: (name: string) => request.cookies.get(name)?.value ?? null,\n getHeader: (name: string) => request.headers.get(name) ?? null,\n });\n\n/**\n * Handles the case where URLs do not have locale prefixes.\n */\nconst handleNoPrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n const pathLocale = getPathLocale(pathname);\n\n if (pathLocale) {\n const pathWithoutLocale = pathname.slice(`/${pathLocale}`.length) || '/';\n\n const canonicalPath = getCanonicalPath(\n pathWithoutLocale,\n pathLocale,\n rewriteRules\n );\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n const redirectPath = search\n ? `${canonicalPath}${search}`\n : `${canonicalPath}${request.nextUrl.search ?? ''}`;\n\n // Persist the explicitly-requested locale: stripping the prefix drops the\n // only locale signal from the URL, so without this the follow-up request\n // would fall back to cookie / Accept-Language detection and could resolve\n // a different locale.\n return redirectUrl(request, redirectPath, pathLocale);\n }\n\n if (\n !(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params'\n ) &&\n effectiveMode === 'search-params'\n ) {\n const existingSearchParams = new URLSearchParams(request.nextUrl.search);\n const existingLocale = existingSearchParams.get('locale');\n\n const isExistingValid = locales?.includes(existingLocale as Locale);\n\n let locale = (localLocale ??\n (isExistingValid ? (existingLocale as Locale) : undefined) ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n if (existingLocale === locale) {\n const internalPath = internalPrefix\n ? getInternalPath(canonicalPath, locale as Locale)\n : canonicalPath;\n const rewritePath = `${internalPath}${request.nextUrl.search ?? ''}`;\n return rewriteUrl(request, rewritePath, locale as Locale);\n }\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n // Use original pathname for redirect to preserve user's URL input, just adding params\n const redirectPath = search\n ? `${pathname}${search}`\n : `${pathname}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n // effectiveMode === 'no-prefix'\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n const internalPath = internalPrefix\n ? getInternalPath(canonicalPath, locale as Locale)\n : canonicalPath;\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewritePath, locale as Locale);\n};\n\n/**\n * Checks whether a pathname starts with the given locale as a full path\n * segment (`/fr` or `/fr/...`). A bare `startsWith('/fr')` would also match\n * unrelated paths like `/friends`, causing wrong prefix stripping and\n * self-redirect loops.\n *\n * @param pathname - The pathname to test.\n * @param locale - The locale to look for as the first path segment.\n * @returns - True if the first path segment is exactly the locale.\n */\nconst hasLocaleSegmentPrefix = (pathname: string, locale: Locale): boolean =>\n pathname === `/${locale}` || pathname.startsWith(`/${locale}/`);\n\n/**\n * Extracts the locale from the URL pathname if present.\n *\n * @param pathname - The pathname from the request URL.\n * @returns - The locale found in the pathname, or undefined if not found.\n */\nconst getPathLocale = (pathname: string): Locale | undefined =>\n (locales as Locale[] | undefined)?.find((locale) =>\n hasLocaleSegmentPrefix(pathname, locale)\n );\n\n/**\n * Handles the case where URLs have locale prefixes.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handlePrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n if (!pathLocale) {\n const isPrefetch = isPrefetchRequest(request);\n if (isPrefetch && !DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX) {\n return handleMissingPathLocale(\n request,\n defaultLocale as Locale,\n pathname\n );\n }\n return handleMissingPathLocale(request, localLocale, pathname);\n }\n\n return handleExistingPathLocale(request, pathLocale, pathname);\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handleMissingPathLocale = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n // Determine target localized path for redirection\n // /about + 'fr' -> /a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n const newPath = constructPath(\n locale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, locale)\n );\n\n // Never emit a trailing slash (`/en/` for canonicalPath `/`): Next.js\n // trailing-slash normalisation would redirect it back and forth with this\n // proxy. `getInternalPath` collapses the root path to `/${locale}`.\n return prefixDefault || locale !== defaultLocale\n ? redirectUrl(request, newPath)\n : rewriteUrl(\n request,\n internalPrefix ? getInternalPath(canonicalPath, locale) : canonicalPath,\n locale\n ); // Rewrite must use Canonical\n};\n\n/**\n * Handles requests where the locale exists in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @returns - The response to be returned to the client.\n */\nconst handleExistingPathLocale = (\n request: NextRequest,\n pathLocale: Locale,\n pathname: string\n): NextResponse => {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n\n // 1. Identify the Canonical Path (Internal Next.js path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n // By skipping the forced localLocale check, we allow the explicit pathLocale\n // to take precedence, which correctly updates the header/cookie when navigating.\n\n // Rewrite Logic\n // We must rewrite to the Next.js internal structure: /[locale]/[canonicalPath]\n // Ex: Rewrite /fr/a-propos -> /fr/about\n\n // 2. Redirect to localized path if needed (Canonical -> Localized)\n // Ex: /fr/about -> /fr/a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n const isRewritten =\n typeof targetLocalizedPathResult === 'string'\n ? false\n : targetLocalizedPathResult.isRewritten;\n\n if (isRewritten && targetLocalizedPath !== rawPath) {\n const newPath = constructPath(\n pathLocale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale)\n );\n return redirectUrl(request, newPath);\n }\n\n // Never emit a trailing slash (`/fr/` for the bare `/fr` URL): rewriting\n // `/fr` to `/fr/` makes Next.js issue a trailing-slash normalisation\n // redirect back to `/fr`, which this proxy rewrites again — an infinite\n // redirect loop. `getInternalPath` collapses the root path to `/${locale}`.\n const internalUrl = internalPrefix\n ? getInternalPath(canonicalPath, pathLocale)\n : canonicalPath;\n\n // Only handle redirect if we are strictly managing default locale prefixing\n // Fix: pass `canonicalPath` (the path *without* the locale prefix, e.g. /pricing)\n // instead of `pathname` (the full path including prefix, e.g. /en/pricing).\n // Previously this caused an infinite redirect loop in prefix-no-default mode\n // because handleDefaultLocaleRedirect built the redirect target from its third\n // argument, which reproduced the same URL on every response.\n if (!prefixDefault && pathLocale === defaultLocale) {\n return handleDefaultLocaleRedirect(request, pathLocale, canonicalPath);\n }\n\n const search = request.nextUrl.search;\n return rewriteUrl(request, internalUrl + (search ?? ''), pathLocale);\n};\n\n/**\n * Handles the scenario where the locale in the cookie does not match the locale in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param pathname - The pathname from the request URL.\n * @param pathLocale - The locale extracted from the pathname.\n * @param localLocale - The locale from the cookie.\n * @param basePath - The base path of the application.\n * @returns - The new URL path with the correct locale.\n */\n// Function handleCookieLocaleMismatch was removed because the URL locale should take precedence over the stored locale.\n\n/**\n * The key fix for 404s without [locale] folders\n */\nconst handleDefaultLocaleRedirect = (\n request: NextRequest,\n pathLocale: Locale,\n canonicalPath: string // Internal path (e.g. /about)\n): NextResponse => {\n // Always called with !prefixDefault && pathLocale === defaultLocale (pre-validated by caller).\n // Redirect to strip the default-locale prefix from the URL.\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n const basePathValue = (basePath as string) || '';\n const basePathTrailingSlash = basePathValue.endsWith('/');\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${basePathValue}${basePathTrailingSlash ? '' : '/'}${finalPath}`;\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n // Persist the explicitly-requested default locale. Stripping the prefix\n // (e.g. /es → /) drops the only locale signal from the URL, so without this\n // the follow-up request to the canonical path would fall back to\n // Accept-Language detection and could resolve a different locale (e.g. /en).\n return redirectUrl(\n request,\n fullPath + (searchWithLocale ?? request.nextUrl.search ?? ''),\n pathLocale\n );\n};\n\n/**\n * Constructs a new path by combining the locale, path, basePath, and search parameters.\n *\n * @param locale - The locale to include in the path.\n * @param path - The original path from the request.\n * @param basePath - The base path of the application.\n * @param [search] - The query string from the request URL (optional).\n * @returns - The constructed new path.\n */\nconst constructPath = (\n locale: Locale,\n path: string,\n basePath: string,\n search?: string\n): string => {\n // Remove existing locale prefix from path if it was passed by mistake,\n // though we usually pass localized paths here now.\n const pathWithoutPrefix = hasLocaleSegmentPrefix(path, locale)\n ? path.slice(`/${locale}`.length) || '/'\n : path;\n\n if (\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'no-prefix'\n ) &&\n effectiveMode === 'no-prefix') ||\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params'\n ) &&\n effectiveMode === 'search-params')\n ) {\n // `search` is either undefined or already has a leading '?' (from\n // appendLocaleSearchIfNeeded / request.nextUrl.search), so append as-is.\n return `${pathWithoutPrefix}${search ?? ''}`;\n }\n\n // Prefix handling\n const pathWithLocalePrefix = hasLocaleSegmentPrefix(path, locale)\n ? path\n : `${locale}${path.startsWith('/') ? '' : '/'}${path}`;\n\n const basePathValue = basePath || '';\n const basePathTrailingSlash = basePathValue.endsWith('/');\n const newPath = `${basePathValue}${basePathTrailingSlash ? '' : '/'}${pathWithLocalePrefix}`;\n\n // Clean double slashes\n const cleanPath = newPath.replace(/\\/+/g, '/');\n\n // Never emit a trailing slash (`/fr/` for the root path): the framework's\n // trailing-slash normalisation would redirect it back and forth with this\n // proxy, creating an infinite redirect loop.\n return cleanPath !== '/' && cleanPath.endsWith('/')\n ? cleanPath.slice(0, -1)\n : cleanPath;\n};\n\n/**\n * This handles the internal path Next.js sees.\n * To support optional [locale] folders, we need to decide if we\n * keep the locale prefix or strip it.\n */\nconst rewriteUrl = (\n request: NextRequest,\n newPath: string,\n locale: Locale\n): NextResponse => {\n const search = request.nextUrl.search;\n\n // Next.js strips `basePath` from `request.nextUrl.pathname` before the\n // middleware runs, so every path computed from it (e.g. `/en/about`) lacks\n // the basePath prefix. When we pass that as an absolute path to `new URL`,\n // it replaces the entire path after the origin, silently discarding the\n // basePath (e.g. `new URL('/en/', 'http://host/weather/')` →\n // `http://host/en/`). Prepending the configured basePath restores the\n // correct mount-point so rewrites resolve under the app root.\n const basePathValue = (basePath as string) || '';\n const pathWithBase =\n basePathValue && !newPath.startsWith(basePathValue)\n ? `${basePathValue}${newPath}`\n : newPath;\n\n const pathWithSearch =\n search && !pathWithBase.includes('?')\n ? `${pathWithBase}${search}`\n : pathWithBase;\n\n const requestHeaders = new Headers(request.headers);\n setLocaleInStorageServer(locale, {\n setHeader: (name: string, value: string) => {\n requestHeaders.set(name, value);\n },\n });\n\n const targetUrl = new URL(pathWithSearch, request.url);\n\n // If the target URL is exactly the current request URL,\n // we just want to `next()` to avoid losing headers on a redundant rewrite.\n const response =\n targetUrl.href === request.nextUrl.href\n ? NextResponse.next({\n request: {\n headers: requestHeaders,\n },\n })\n : NextResponse.rewrite(targetUrl, {\n request: {\n headers: requestHeaders,\n },\n });\n\n setLocaleInStorageServer(locale, {\n setHeader: (name: string, value: string) => {\n response.headers.set(name, value);\n },\n });\n return response;\n};\n\n/**\n * Redirects the request to the new path.\n *\n * @param request - The incoming Next.js request object.\n * @param newPath - The new path to redirect to.\n * @param persistLocale - When provided, the locale is written to storage\n * (cookie/header, per config) on the redirect response so the follow-up\n * request resolves the same locale instead of re-running detection.\n * @returns - The redirect response.\n */\nconst redirectUrl = (\n request: NextRequest,\n newPath: string,\n persistLocale?: Locale\n): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n const target = new URL(pathWithSearch, request.url);\n\n // Prevent open redirect: if the resolved origin differs from the request\n // origin, strip it back to a same-origin URL using only the path/search/hash.\n const safeTarget =\n target.origin === request.nextUrl.origin\n ? target\n : new URL(\n `${target.pathname}${target.search}${target.hash}`,\n request.url\n );\n\n const response = NextResponse.redirect(safeTarget);\n\n if (persistLocale) {\n persistLocaleOnResponse(response, persistLocale);\n }\n\n return response;\n};\n\n/**\n * Writes the resolved locale to the outgoing response's storage (cookie and/or\n * header, according to `routing.storage`). Only the cookie survives a client\n * redirect, so this is what carries an explicitly-selected locale across a\n * prefix-stripping redirect. Enabled cookie/header targets are resolved by\n * {@link setLocaleInStorageServer} from the config; disabled ones are no-ops.\n *\n * @param response - The outgoing Next.js response to attach storage to.\n * @param locale - The locale to persist.\n */\nconst persistLocaleOnResponse = (\n response: NextResponse,\n locale: Locale\n): void => {\n setLocaleInStorageServer(locale, {\n setCookieStore: (name, value, attributes) => {\n response.cookies.set(name, value, {\n path: attributes.path,\n domain: attributes.domain,\n expires:\n typeof attributes.expires === 'number'\n ? new Date(attributes.expires)\n : attributes.expires,\n secure: attributes.secure,\n sameSite: attributes.sameSite,\n httpOnly: attributes.httpOnly,\n });\n },\n setHeader: (name, value) => {\n response.headers.set(name, value);\n },\n });\n};\n"],"mappings":";;;;;;;;AA4DA,MAAM,EAAE,SAAS,kBAAkB,wBAAwB,CAAC;AAC5D,MAAM,EAAE,UAAU,MAAM,SAAS,SAAS,gBAAgB,WAAW,CAAC;AAKtE,MAAM,iBACJ,QAAQ,IAAI,kCAAkC,YAC7C,eAAe;AAKlB,MAAM,gBAAgB,QAAQ;AAC9B,MAAM,WACH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"file":"intlayerProxy.mjs","names":["localeDetector"],"sources":["../../../src/proxy/intlayerProxy.ts"],"sourcesContent":["import { internationalization, log, routing } from '@intlayer/config/built';\nimport { ROUTING_MODE } from '@intlayer/config/defaultValues';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n formatProxyEnabledMessage,\n getCanonicalPath,\n getDomainHostname,\n getDomainOrigin,\n getInternalPath,\n getLocaleFromDomain,\n getLocalizedPath,\n getRewriteRules,\n isProxyStorageLocaleEnabled,\n type LocaleDomainMap,\n resolveProxyMode,\n} from '@intlayer/core/localization';\nimport {\n getLocaleFromStorageServer,\n setLocaleInStorageServer,\n} from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport {\n type NextFetchEvent,\n type NextRequest,\n NextResponse,\n} from 'next/server';\nimport { localeDetector } from './localeDetector';\n\n/**\n * Controls whether locale detection occurs during Next.js prefetch requests\n * - true: Detect and apply locale during prefetch\n * - false: Use default locale during prefetch (recommended)\n *\n * This setting affects how Next.js handles locale prefetching:\n *\n * Example scenario:\n * - User's browser language is 'fr'\n * - Current page is /fr/about\n * - Link prefetches /about\n *\n * With `detectLocaleOnPrefetchNoPrefix:true`\n * - Prefetch detects 'fr' locale from browser\n * - Redirects prefetch to /fr/about\n *\n * With `detectLocaleOnPrefetchNoPrefix:false` (default)\n * - Prefetch uses default locale\n * - Redirects prefetch to /en/about (assuming 'en' is default)\n *\n * When to use true:\n * - Your app uses non-localized internal links (e.g. <a href=\"/about\">)\n * - You want consistent locale detection behavior between regular and prefetch requests\n *\n * When to use false (default):\n * - Your app uses locale-prefixed links (e.g. <a href=\"/fr/about\">)\n * - You want to optimize prefetching performance\n * - You want to avoid potential redirect loops\n */\nconst DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX = false;\n\nconst { locales, defaultLocale } = internationalization ?? {};\nconst { basePath, mode, rewrite, domains, enableProxy } = routing ?? {};\n\n// Resolved behaviour of the locale-routing proxy. `disabled` turns\n// `intlayerProxy` into a pass-through so apps can handle routing themselves.\n// The env var backing this is injected at build time so bundlers can tree-shake\n// the guarded branches.\nconst proxyMode = resolveProxyMode(enableProxy);\n\n// Next.js inlines NODE_ENV into every bundle, edge middleware included, so this\n// is both reliable and statically eliminable. `next build` is the only command\n// that injects `INTLAYER_ROUTING_ENABLE_PROXY`, meaning a dev server always\n// reaches `resolveProxyMode` through the configuration value.\n//\n// Matched against `development` rather than \"not production\" on purpose: only\n// `next dev` runs a dev server. Any other value (`test`, a custom staging env)\n// has no dev server in play and must keep the full production behaviour.\nconst isDevServer = process.env.NODE_ENV === 'development';\n\n// In auto mode, a dev server keeps locale routing URL-driven: the stored locale\n// is not used as a redirect source, so a stale cookie cannot keep pulling every\n// navigation to another locale while developing.\nconst canUseStorageLocale = isProxyStorageLocaleEnabled(proxyMode, isDevServer);\n\n// Announce the proxy the way the Vite plugin does on `configureServer`. Next\n// has no server-start hook for middleware, so this runs when the middleware\n// module is first evaluated — at the first request `next dev` routes through\n// it. Restricted to the dev server on purpose: in production this module is\n// re-evaluated on every edge cold start, and the line would be pure noise.\nif (isDevServer && proxyMode !== 'disabled') {\n getAppLogger({ log })(formatProxyEnabledMessage(!canUseStorageLocale), {\n level: 'info',\n });\n}\n\n// Note: cookie names are resolved inside LocaleStorage based on configuration\n\n// Derived flags from routing.mode\nconst effectiveMode = mode ?? ROUTING_MODE;\nconst noPrefix =\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'no-prefix'\n ) &&\n effectiveMode === 'no-prefix') ||\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params'\n ) &&\n effectiveMode === 'search-params');\nconst prefixDefault =\n !(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'prefix-all'\n ) && effectiveMode === 'prefix-all';\n\nconst internalPrefix = !noPrefix;\n\nconst rewriteRules =\n process.env.INTLAYER_ROUTING_REWRITE_RULES !== 'false'\n ? getRewriteRules(rewrite, 'url')\n : undefined;\n\n/**\n * Detects if the request is a prefetch request from Next.js.\n *\n * Next.js prefetch requests are identified by:\n * - purpose: 'prefetch' (standard prefetch header)\n * - next-router-prefetch: '1' (Next.js app-router prefetch)\n *\n * Note: `next-url` and `x-nextjs-data` are intentionally NOT used here.\n * Both are also sent on real client-side navigations (RSC navigation\n * requests and pages-router data requests respectively), so treating them\n * as prefetch would force such navigations to the default locale instead\n * of the user's stored locale.\n *\n * During prefetch, we should ignore cookie-based locale detection\n * to prevent unwanted redirects when users are switching locales.\n *\n * @param request - The incoming Next.js request object.\n * @returns - True if the request is a prefetch request, false otherwise.\n */\nconst isPrefetchRequest = (request: NextRequest): boolean => {\n const purpose = request.headers.get('purpose');\n const nextRouterPrefetch = request.headers.get('next-router-prefetch');\n\n return purpose === 'prefetch' || nextRouterPrefetch === '1';\n};\n\n// Ensure locale is reflected in search params when routing mode is 'search-params'\nconst appendLocaleSearchIfNeeded = (\n search: string | undefined,\n locale: Locale\n): string | undefined => {\n if (\n (process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params') ||\n effectiveMode !== 'search-params'\n )\n return search;\n const params = new URLSearchParams(search ?? '');\n params.set('locale', locale);\n return `?${params.toString()}`;\n};\n\n/**\n * Proxy that handles the internationalization layer\n *\n * Usage:\n *\n * ```ts\n * // ./src/proxy.ts\n *\n * export { intlayerProxy as proxy } from '@intlayer/next/proxy';\n *\n * // applies this proxy only to files in the app directory\n * export const config = {\n * matcher: '/((?!api|static|.*\\\\..*|_next).*)',\n * };\n * ```\n *\n * Main proxy function for handling internationalization.\n *\n * @param request - The incoming Next.js request object.\n * @param event - The Next.js fetch event (optional).\n * @param response - The Next.js response object (optional).\n * @returns - The response to be returned to the client.\n *\n */\nexport const intlayerProxy = (\n request: NextRequest,\n _event?: NextFetchEvent,\n _response?: NextResponse\n): NextResponse => {\n // When the proxy is disabled, pass the request through untouched.\n if (proxyMode === 'disabled') {\n return NextResponse.next();\n }\n\n const pathname = request.nextUrl.pathname;\n\n const localLocale = getLocalLocale(request);\n\n if (noPrefix) {\n return handleNoPrefix(request, localLocale, pathname);\n }\n\n const pathLocale = getPathLocale(pathname);\n\n // Domain routing: if the path locale is mapped to a different domain, redirect there.\n // e.g. intlayer.org/zh/about → https://intlayer.zh/about\n if (\n process.env.INTLAYER_ROUTING_DOMAINS !== 'false' &&\n pathLocale &&\n domains\n ) {\n const localeDomain = domains[pathLocale];\n\n if (localeDomain) {\n const domainHost = getDomainHostname(localeDomain);\n\n if (domainHost !== request.nextUrl.hostname) {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n const targetOrigin = getDomainOrigin(localeDomain);\n\n return NextResponse.redirect(\n new URL(`${rawPath}${request.nextUrl.search}`, targetOrigin)\n );\n }\n }\n }\n\n // Domain routing: if the current hostname is exclusively mapped to one locale,\n // treat it as that locale's domain — no URL prefix needed.\n // e.g. intlayer.zh/about → internally rewrite to /zh/about\n if (process.env.INTLAYER_ROUTING_DOMAINS !== 'false' && !pathLocale) {\n const domainLocale = getLocaleFromDomain(\n request.nextUrl.hostname,\n domains as LocaleDomainMap\n );\n\n if (domainLocale) {\n const canonicalPath = getCanonicalPath(\n pathname,\n domainLocale,\n rewriteRules\n );\n\n // Never emit a trailing slash (`/zh/`): Next.js trailing-slash\n // normalisation would redirect it back and forth with this proxy.\n const internalPath = getInternalPath(canonicalPath, domainLocale);\n\n return rewriteUrl(\n request,\n internalPath + (request.nextUrl.search ?? ''),\n domainLocale\n );\n }\n }\n\n return handlePrefix(request, localLocale, pathLocale, pathname);\n};\n\n/**\n * Retrieves the locale from the request cookies if available and valid.\n *\n * Returns `undefined` when the stored locale is not allowed to drive locale\n * resolution (auto mode on a dev server), which makes every caller fall through\n * to `Accept-Language` detection and then the default locale.\n *\n * @param request - The incoming Next.js request object.\n * @returns - The locale found in the cookies, or undefined if not found or invalid.\n */\nconst getLocalLocale = (request: NextRequest): Locale | undefined => {\n if (!canUseStorageLocale) return undefined;\n\n return getLocaleFromStorageServer({\n getCookie: (name: string) => request.cookies.get(name)?.value ?? null,\n getHeader: (name: string) => request.headers.get(name) ?? null,\n });\n};\n\n/**\n * Handles the case where URLs do not have locale prefixes.\n */\nconst handleNoPrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n const pathLocale = getPathLocale(pathname);\n\n if (pathLocale) {\n const pathWithoutLocale = pathname.slice(`/${pathLocale}`.length) || '/';\n\n const canonicalPath = getCanonicalPath(\n pathWithoutLocale,\n pathLocale,\n rewriteRules\n );\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n const redirectPath = search\n ? `${canonicalPath}${search}`\n : `${canonicalPath}${request.nextUrl.search ?? ''}`;\n\n // Persist the explicitly-requested locale: stripping the prefix drops the\n // only locale signal from the URL, so without this the follow-up request\n // would fall back to cookie / Accept-Language detection and could resolve\n // a different locale.\n return redirectUrl(request, redirectPath, pathLocale);\n }\n\n if (\n !(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params'\n ) &&\n effectiveMode === 'search-params'\n ) {\n const existingSearchParams = new URLSearchParams(request.nextUrl.search);\n const existingLocale = existingSearchParams.get('locale');\n\n const isExistingValid = locales?.includes(existingLocale as Locale);\n\n let locale = (localLocale ??\n (isExistingValid ? (existingLocale as Locale) : undefined) ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n if (existingLocale === locale) {\n const internalPath = internalPrefix\n ? getInternalPath(canonicalPath, locale as Locale)\n : canonicalPath;\n const rewritePath = `${internalPath}${request.nextUrl.search ?? ''}`;\n return rewriteUrl(request, rewritePath, locale as Locale);\n }\n\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n // Use original pathname for redirect to preserve user's URL input, just adding params\n const redirectPath = search\n ? `${pathname}${search}`\n : `${pathname}${request.nextUrl.search ?? ''}`;\n\n return redirectUrl(request, redirectPath);\n }\n\n // effectiveMode === 'no-prefix'\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n const canonicalPath = getCanonicalPath(\n pathname,\n locale as Locale,\n rewriteRules\n );\n\n const internalPath = internalPrefix\n ? getInternalPath(canonicalPath, locale as Locale)\n : canonicalPath;\n const search = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n locale as Locale\n );\n const rewritePath = search\n ? `${internalPath}${search}`\n : `${internalPath}${request.nextUrl.search ?? ''}`;\n\n return rewriteUrl(request, rewritePath, locale as Locale);\n};\n\n/**\n * Checks whether a pathname starts with the given locale as a full path\n * segment (`/fr` or `/fr/...`). A bare `startsWith('/fr')` would also match\n * unrelated paths like `/friends`, causing wrong prefix stripping and\n * self-redirect loops.\n *\n * @param pathname - The pathname to test.\n * @param locale - The locale to look for as the first path segment.\n * @returns - True if the first path segment is exactly the locale.\n */\nconst hasLocaleSegmentPrefix = (pathname: string, locale: Locale): boolean =>\n pathname === `/${locale}` || pathname.startsWith(`/${locale}/`);\n\n/**\n * Extracts the locale from the URL pathname if present.\n *\n * @param pathname - The pathname from the request URL.\n * @returns - The locale found in the pathname, or undefined if not found.\n */\nconst getPathLocale = (pathname: string): Locale | undefined =>\n (locales as Locale[] | undefined)?.find((locale) =>\n hasLocaleSegmentPrefix(pathname, locale)\n );\n\n/**\n * Handles the case where URLs have locale prefixes.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handlePrefix = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n if (!pathLocale) {\n const isPrefetch = isPrefetchRequest(request);\n if (isPrefetch && !DEFAULT_DETECT_LOCALE_ON_PREFETCH_NO_PREFIX) {\n return handleMissingPathLocale(\n request,\n defaultLocale as Locale,\n pathname\n );\n }\n return handleMissingPathLocale(request, localLocale, pathname);\n }\n\n return handleExistingPathLocale(request, pathLocale, pathname);\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathname - The pathname from the request URL.\n * @param basePathTrailingSlash - Indicates if the basePath ends with a slash.\n * @returns - The response to be returned to the client.\n */\nconst handleMissingPathLocale = (\n request: NextRequest,\n localLocale: Locale | undefined,\n pathname: string\n): NextResponse => {\n let locale = (localLocale ??\n localeDetector?.(request) ??\n defaultLocale) as Locale;\n\n if (!locales?.includes(locale as Locale)) {\n locale = defaultLocale as Locale;\n }\n\n // Resolve to canonical path.\n // If user visits /a-propos (implied 'fr'), we resolve to /about\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n // Determine target localized path for redirection\n // /about + 'fr' -> /a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n const newPath = constructPath(\n locale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, locale)\n );\n\n // Never emit a trailing slash (`/en/` for canonicalPath `/`): Next.js\n // trailing-slash normalisation would redirect it back and forth with this\n // proxy. `getInternalPath` collapses the root path to `/${locale}`.\n return prefixDefault || locale !== defaultLocale\n ? redirectUrl(request, newPath)\n : rewriteUrl(\n request,\n internalPrefix ? getInternalPath(canonicalPath, locale) : canonicalPath,\n locale\n ); // Rewrite must use Canonical\n};\n\n/**\n * Handles requests where the locale exists in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param localLocale - The locale from the cookie.\n * @param pathLocale - The locale extracted from the pathname.\n * @param pathname - The pathname from the request URL.\n * @returns - The response to be returned to the client.\n */\nconst handleExistingPathLocale = (\n request: NextRequest,\n pathLocale: Locale,\n pathname: string\n): NextResponse => {\n const rawPath = pathname.slice(`/${pathLocale}`.length) || '/';\n\n // 1. Identify the Canonical Path (Internal Next.js path)\n // Ex: /a-propos (from URL) -> /about (Canonical)\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n\n // By skipping the forced localLocale check, we allow the explicit pathLocale\n // to take precedence, which correctly updates the header/cookie when navigating.\n\n // Rewrite Logic\n // We must rewrite to the Next.js internal structure: /[locale]/[canonicalPath]\n // Ex: Rewrite /fr/a-propos -> /fr/about\n\n // 2. Redirect to localized path if needed (Canonical -> Localized)\n // Ex: /fr/about -> /fr/a-propos\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n const isRewritten =\n typeof targetLocalizedPathResult === 'string'\n ? false\n : targetLocalizedPathResult.isRewritten;\n\n if (isRewritten && targetLocalizedPath !== rawPath) {\n const newPath = constructPath(\n pathLocale,\n targetLocalizedPath,\n basePath as string,\n appendLocaleSearchIfNeeded(request.nextUrl.search, pathLocale)\n );\n return redirectUrl(request, newPath);\n }\n\n // Never emit a trailing slash (`/fr/` for the bare `/fr` URL): rewriting\n // `/fr` to `/fr/` makes Next.js issue a trailing-slash normalisation\n // redirect back to `/fr`, which this proxy rewrites again — an infinite\n // redirect loop. `getInternalPath` collapses the root path to `/${locale}`.\n const internalUrl = internalPrefix\n ? getInternalPath(canonicalPath, pathLocale)\n : canonicalPath;\n\n // Only handle redirect if we are strictly managing default locale prefixing\n // Fix: pass `canonicalPath` (the path *without* the locale prefix, e.g. /pricing)\n // instead of `pathname` (the full path including prefix, e.g. /en/pricing).\n // Previously this caused an infinite redirect loop in prefix-no-default mode\n // because handleDefaultLocaleRedirect built the redirect target from its third\n // argument, which reproduced the same URL on every response.\n if (!prefixDefault && pathLocale === defaultLocale) {\n return handleDefaultLocaleRedirect(request, pathLocale, canonicalPath);\n }\n\n const search = request.nextUrl.search;\n return rewriteUrl(request, internalUrl + (search ?? ''), pathLocale);\n};\n\n/**\n * Handles the scenario where the locale in the cookie does not match the locale in the URL pathname.\n *\n * @param request - The incoming Next.js request object.\n * @param pathname - The pathname from the request URL.\n * @param pathLocale - The locale extracted from the pathname.\n * @param localLocale - The locale from the cookie.\n * @param basePath - The base path of the application.\n * @returns - The new URL path with the correct locale.\n */\n// Function handleCookieLocaleMismatch was removed because the URL locale should take precedence over the stored locale.\n\n/**\n * The key fix for 404s without [locale] folders\n */\nconst handleDefaultLocaleRedirect = (\n request: NextRequest,\n pathLocale: Locale,\n canonicalPath: string // Internal path (e.g. /about)\n): NextResponse => {\n // Always called with !prefixDefault && pathLocale === defaultLocale (pre-validated by caller).\n // Redirect to strip the default-locale prefix from the URL.\n const targetLocalizedPathResult = getLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n const targetLocalizedPath =\n typeof targetLocalizedPathResult === 'string'\n ? targetLocalizedPathResult\n : targetLocalizedPathResult.path;\n\n const basePathValue = (basePath as string) || '';\n const basePathTrailingSlash = basePathValue.endsWith('/');\n let finalPath = targetLocalizedPath;\n if (finalPath.startsWith('/')) finalPath = finalPath.slice(1);\n\n const fullPath = `${basePathValue}${basePathTrailingSlash ? '' : '/'}${finalPath}`;\n\n const searchWithLocale = appendLocaleSearchIfNeeded(\n request.nextUrl.search,\n pathLocale\n );\n\n // Persist the explicitly-requested default locale. Stripping the prefix\n // (e.g. /es → /) drops the only locale signal from the URL, so without this\n // the follow-up request to the canonical path would fall back to\n // Accept-Language detection and could resolve a different locale (e.g. /en).\n return redirectUrl(\n request,\n fullPath + (searchWithLocale ?? request.nextUrl.search ?? ''),\n pathLocale\n );\n};\n\n/**\n * Constructs a new path by combining the locale, path, basePath, and search parameters.\n *\n * @param locale - The locale to include in the path.\n * @param path - The original path from the request.\n * @param basePath - The base path of the application.\n * @param [search] - The query string from the request URL (optional).\n * @returns - The constructed new path.\n */\nconst constructPath = (\n locale: Locale,\n path: string,\n basePath: string,\n search?: string\n): string => {\n // Remove existing locale prefix from path if it was passed by mistake,\n // though we usually pass localized paths here now.\n const pathWithoutPrefix = hasLocaleSegmentPrefix(path, locale)\n ? path.slice(`/${locale}`.length) || '/'\n : path;\n\n if (\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'no-prefix'\n ) &&\n effectiveMode === 'no-prefix') ||\n (!(\n process.env.INTLAYER_ROUTING_MODE &&\n process.env.INTLAYER_ROUTING_MODE !== 'search-params'\n ) &&\n effectiveMode === 'search-params')\n ) {\n // `search` is either undefined or already has a leading '?' (from\n // appendLocaleSearchIfNeeded / request.nextUrl.search), so append as-is.\n return `${pathWithoutPrefix}${search ?? ''}`;\n }\n\n // Prefix handling\n const pathWithLocalePrefix = hasLocaleSegmentPrefix(path, locale)\n ? path\n : `${locale}${path.startsWith('/') ? '' : '/'}${path}`;\n\n const basePathValue = basePath || '';\n const basePathTrailingSlash = basePathValue.endsWith('/');\n const newPath = `${basePathValue}${basePathTrailingSlash ? '' : '/'}${pathWithLocalePrefix}`;\n\n // Clean double slashes\n const cleanPath = newPath.replace(/\\/+/g, '/');\n\n // Never emit a trailing slash (`/fr/` for the root path): the framework's\n // trailing-slash normalisation would redirect it back and forth with this\n // proxy, creating an infinite redirect loop.\n return cleanPath !== '/' && cleanPath.endsWith('/')\n ? cleanPath.slice(0, -1)\n : cleanPath;\n};\n\n/**\n * This handles the internal path Next.js sees.\n * To support optional [locale] folders, we need to decide if we\n * keep the locale prefix or strip it.\n */\nconst rewriteUrl = (\n request: NextRequest,\n newPath: string,\n locale: Locale\n): NextResponse => {\n const search = request.nextUrl.search;\n\n // Next.js strips `basePath` from `request.nextUrl.pathname` before the\n // middleware runs, so every path computed from it (e.g. `/en/about`) lacks\n // the basePath prefix. When we pass that as an absolute path to `new URL`,\n // it replaces the entire path after the origin, silently discarding the\n // basePath (e.g. `new URL('/en/', 'http://host/weather/')` →\n // `http://host/en/`). Prepending the configured basePath restores the\n // correct mount-point so rewrites resolve under the app root.\n const basePathValue = (basePath as string) || '';\n const pathWithBase =\n basePathValue && !newPath.startsWith(basePathValue)\n ? `${basePathValue}${newPath}`\n : newPath;\n\n const pathWithSearch =\n search && !pathWithBase.includes('?')\n ? `${pathWithBase}${search}`\n : pathWithBase;\n\n const requestHeaders = new Headers(request.headers);\n setLocaleInStorageServer(locale, {\n setHeader: (name: string, value: string) => {\n requestHeaders.set(name, value);\n },\n });\n\n const targetUrl = new URL(pathWithSearch, request.url);\n\n // If the target URL is exactly the current request URL,\n // we just want to `next()` to avoid losing headers on a redundant rewrite.\n const response =\n targetUrl.href === request.nextUrl.href\n ? NextResponse.next({\n request: {\n headers: requestHeaders,\n },\n })\n : NextResponse.rewrite(targetUrl, {\n request: {\n headers: requestHeaders,\n },\n });\n\n setLocaleInStorageServer(locale, {\n setHeader: (name: string, value: string) => {\n response.headers.set(name, value);\n },\n });\n return response;\n};\n\n/**\n * Redirects the request to the new path.\n *\n * @param request - The incoming Next.js request object.\n * @param newPath - The new path to redirect to.\n * @param persistLocale - When provided, the locale is written to storage\n * (cookie/header, per config) on the redirect response so the follow-up\n * request resolves the same locale instead of re-running detection.\n * @returns - The redirect response.\n */\nconst redirectUrl = (\n request: NextRequest,\n newPath: string,\n persistLocale?: Locale\n): NextResponse => {\n const search = request.nextUrl.search;\n const pathWithSearch =\n search && !newPath.includes('?') ? `${newPath}${search}` : newPath;\n\n const target = new URL(pathWithSearch, request.url);\n\n // Prevent open redirect: if the resolved origin differs from the request\n // origin, strip it back to a same-origin URL using only the path/search/hash.\n const safeTarget =\n target.origin === request.nextUrl.origin\n ? target\n : new URL(\n `${target.pathname}${target.search}${target.hash}`,\n request.url\n );\n\n const response = NextResponse.redirect(safeTarget);\n\n if (persistLocale) {\n persistLocaleOnResponse(response, persistLocale);\n }\n\n return response;\n};\n\n/**\n * Writes the resolved locale to the outgoing response's storage (cookie and/or\n * header, according to `routing.storage`). Only the cookie survives a client\n * redirect, so this is what carries an explicitly-selected locale across a\n * prefix-stripping redirect. Enabled cookie/header targets are resolved by\n * {@link setLocaleInStorageServer} from the config; disabled ones are no-ops.\n *\n * @param response - The outgoing Next.js response to attach storage to.\n * @param locale - The locale to persist.\n */\nconst persistLocaleOnResponse = (\n response: NextResponse,\n locale: Locale\n): void => {\n setLocaleInStorageServer(locale, {\n setCookieStore: (name, value, attributes) => {\n response.cookies.set(name, value, {\n path: attributes.path,\n domain: attributes.domain,\n expires:\n typeof attributes.expires === 'number'\n ? new Date(attributes.expires)\n : attributes.expires,\n secure: attributes.secure,\n sameSite: attributes.sameSite,\n httpOnly: attributes.httpOnly,\n });\n },\n setHeader: (name, value) => {\n response.headers.set(name, value);\n },\n });\n};\n"],"mappings":";;;;;;;;;AA2DA,MAAM,EAAE,SAAS,kBAAkB,wBAAwB,CAAC;AAC5D,MAAM,EAAE,UAAU,MAAM,SAAS,SAAS,gBAAgB,WAAW,CAAC;AAMtE,MAAM,YAAY,iBAAiB,WAAW;AAe9C,MAAM,sBAAsB,4BAA4B,WAAW,IAAW;AAO9E,IAAmB,cAAc,YAC/B,aAAa,EAAE,IAAI,CAAC,CAAC,CAAC,0BAA0B,CAAC,mBAAmB,GAAG,EACrE,OAAO,OACT,CAAC;AAMH,MAAM,gBAAgB,QAAQ;AAC9B,MAAM,WACH,EACC,QAAQ,IAAI,yBACZ,QAAQ,IAAI,0BAA0B,gBAEtC,kBAAkB,eACnB,EACC,QAAQ,IAAI,yBACZ,QAAQ,IAAI,0BAA0B,oBAEtC,kBAAkB;AACtB,MAAM,gBACJ,EACE,QAAQ,IAAI,yBACZ,QAAQ,I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