vite-intlayer 6.0.0-canary.4 → 6.0.1
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/index.cjs +7 -19
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/intlayerMiddlewarePlugin.cjs +3 -0
- package/dist/cjs/intlayerMiddlewarePlugin.cjs.map +1 -1
- package/dist/cjs/intlayerPlugin.cjs +3 -0
- package/dist/cjs/intlayerPlugin.cjs.map +1 -1
- package/dist/esm/index.mjs +3 -13
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/intlayerMiddlewarePlugin.mjs +2 -0
- package/dist/esm/intlayerMiddlewarePlugin.mjs.map +1 -1
- package/dist/esm/intlayerPlugin.mjs +2 -0
- package/dist/esm/intlayerPlugin.mjs.map +1 -1
- package/dist/types/index.d.ts +3 -3
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/intlayerMiddlewarePlugin.d.ts +21 -1
- package/dist/types/intlayerMiddlewarePlugin.d.ts.map +1 -1
- package/dist/types/intlayerPlugin.d.ts +15 -1
- package/dist/types/intlayerPlugin.d.ts.map +1 -1
- package/package.json +12 -12
package/dist/cjs/index.cjs
CHANGED
|
@@ -3,10 +3,6 @@ var __defProp = Object.defineProperty;
|
|
|
3
3
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
4
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
5
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
-
var __export = (target, all) => {
|
|
7
|
-
for (var name in all)
|
|
8
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
-
};
|
|
10
6
|
var __copyProps = (to, from, except, desc) => {
|
|
11
7
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
8
|
for (let key of __getOwnPropNames(from))
|
|
@@ -15,25 +11,17 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
11
|
}
|
|
16
12
|
return to;
|
|
17
13
|
};
|
|
14
|
+
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
|
18
15
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
16
|
var index_exports = {};
|
|
20
|
-
__export(index_exports, {
|
|
21
|
-
intlayer: () => import_intlayerPlugin.intlayer,
|
|
22
|
-
intlayerMiddleware: () => import_intlayerMiddlewarePlugin.intlayerMiddleware,
|
|
23
|
-
intlayerMiddlewarePlugin: () => import_intlayerMiddlewarePlugin.intlayerMiddlewarePlugin,
|
|
24
|
-
intlayerPlugin: () => import_intlayerPlugin.intlayerPlugin,
|
|
25
|
-
intlayerPrune: () => import_intlayerPrunePlugin.intlayerPrune
|
|
26
|
-
});
|
|
27
17
|
module.exports = __toCommonJS(index_exports);
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
18
|
+
__reExport(index_exports, require('./intlayerMiddlewarePlugin.cjs'), module.exports);
|
|
19
|
+
__reExport(index_exports, require('./intlayerPlugin.cjs'), module.exports);
|
|
20
|
+
__reExport(index_exports, require('./intlayerPrunePlugin.cjs'), module.exports);
|
|
31
21
|
// Annotate the CommonJS export names for ESM import in node:
|
|
32
22
|
0 && (module.exports = {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
intlayerPlugin,
|
|
37
|
-
intlayerPrune
|
|
23
|
+
...require('./intlayerMiddlewarePlugin.cjs'),
|
|
24
|
+
...require('./intlayerPlugin.cjs'),
|
|
25
|
+
...require('./intlayerPrunePlugin.cjs')
|
|
38
26
|
});
|
|
39
27
|
//# sourceMappingURL=index.cjs.map
|
package/dist/cjs/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './intlayerMiddlewarePlugin';\nexport * from './intlayerPlugin';\nexport * from './intlayerPrunePlugin';\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AAAA;AAAA,0BAAc,uCAAd;AACA,0BAAc,6BADd;AAEA,0BAAc,kCAFd;","names":[]}
|
|
@@ -18,6 +18,7 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
18
18
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
19
|
var intlayerMiddlewarePlugin_exports = {};
|
|
20
20
|
__export(intlayerMiddlewarePlugin_exports, {
|
|
21
|
+
intLayerMiddleware: () => intLayerMiddleware,
|
|
21
22
|
intlayerMiddleware: () => intlayerMiddleware,
|
|
22
23
|
intlayerMiddlewarePlugin: () => intlayerMiddlewarePlugin
|
|
23
24
|
});
|
|
@@ -233,8 +234,10 @@ const handleDefaultLocaleRedirect = ({
|
|
|
233
234
|
return next();
|
|
234
235
|
};
|
|
235
236
|
const intlayerMiddleware = intlayerMiddlewarePlugin;
|
|
237
|
+
const intLayerMiddleware = intlayerMiddlewarePlugin;
|
|
236
238
|
// Annotate the CommonJS export names for ESM import in node:
|
|
237
239
|
0 && (module.exports = {
|
|
240
|
+
intLayerMiddleware,
|
|
238
241
|
intlayerMiddleware,
|
|
239
242
|
intlayerMiddlewarePlugin
|
|
240
243
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/intlayerMiddlewarePlugin.ts"],"sourcesContent":["import { getConfiguration, type Locales } from '@intlayer/config';\nimport { localeDetector } from '@intlayer/core';\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport { parse } from 'url';\n/* @ts-ignore - Vite types error */\nimport type { Connect, Plugin } from 'vite';\n\n// Grab all the config you need.\n// Make sure your config includes the following fields if you want to replicate Next.js logic:\n// - internationalization.locales\n// - internationalization.defaultLocale\n// - middleware.cookieName\n// - middleware.headerName\n// - middleware.prefixDefault\n// - middleware.noPrefix\n// - middleware.serverSetCookie\n// - middleware.basePath\n// - etc.\nconst intlayerConfig = getConfiguration();\nconst { internationalization, middleware } = intlayerConfig;\nconst { locales: supportedLocales, defaultLocale } = internationalization;\n\nconst {\n cookieName,\n headerName,\n prefixDefault,\n noPrefix,\n serverSetCookie,\n basePath = '',\n} = middleware;\n\n/**\n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n */\nexport const intlayerMiddlewarePlugin = (): Plugin => {\n return {\n name: 'vite-intlayer-middleware-plugin',\n configureServer: (server) => {\n server.middlewares.use((req, res, next) => {\n // 1. Bypass assets and special Vite endpoints\n if (\n req.url?.startsWith('/node_modules') ||\n req.url?.startsWith('/@') ||\n req.url?.split('?')[0].match(/\\.[a-z]+$/i) // checks for file extensions\n ) {\n return next();\n }\n\n // 2. Parse original URL for path and query\n const parsedUrl = parse(req.url ?? '/', true);\n const originalPath = parsedUrl.pathname ?? '/';\n\n // 3. Attempt to read the cookie locale\n const cookies = parseCookies(req.headers.cookie ?? '');\n const cookieLocale = getValidLocaleFromCookie(cookies[cookieName]);\n\n // 4. Check if there's a locale prefix in the path\n const pathLocale = getPathLocale(originalPath);\n\n // 5. If noPrefix is true, we skip prefix logic altogether\n if (noPrefix) {\n handleNoPrefix({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n });\n return;\n }\n\n // 6. Otherwise, handle prefix logic\n handlePrefix({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n });\n });\n },\n };\n};\n\n/* --------------------------------------------------------------------\n * Helper & Utility Functions\n * --------------------------------------------------------------------\n */\n\n/**\n * Parses cookies from the Cookie header string into an object.\n */\nconst parseCookies = (cookieHeader: string) => {\n return cookieHeader.split(';').reduce(\n (acc, cookie) => {\n const [key, val] = cookie.trim().split('=');\n acc[key] = val;\n return acc;\n },\n {} as Record<string, string>\n );\n};\n\n/**\n * Checks if the cookie locale is valid and is included in the supported locales.\n */\nconst getValidLocaleFromCookie = (\n locale: string | undefined\n): Locales | undefined => {\n if (locale && supportedLocales.includes(locale as Locales)) {\n return locale as Locales;\n }\n return undefined;\n};\n\n/**\n * Extracts the locale from the URL pathname if present as the first segment.\n */\nconst getPathLocale = (pathname: string): Locales | undefined => {\n // e.g. if pathname is /en/some/page or /en\n // we check if \"en\" is in your supportedLocales\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n if (firstSegment && supportedLocales.includes(firstSegment as Locales)) {\n return firstSegment as Locales;\n }\n return undefined;\n};\n\n/**\n * Writes a 301 redirect response with the given new URL.\n */\nconst redirectUrl = (res: ServerResponse<IncomingMessage>, newUrl: string) => {\n res.writeHead(301, { Location: newUrl });\n return res.end();\n};\n\n/**\n * \"Rewrite\" the request internally by adjusting req.url;\n * we also set the locale in the response header if needed.\n */\nconst rewriteUrl = (\n req: Connect.IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n locale?: Locales\n) => {\n req.url = newUrl;\n // If you want to mimic Next.js's behavior of setting a header for the locale:\n if (locale && headerName) {\n res.setHeader(headerName, locale);\n }\n};\n\n/**\n * Constructs a new path string, optionally including a locale prefix and basePath.\n * - basePath: (e.g., '/myapp')\n * - locale: (e.g., 'en')\n * - currentPath:(e.g., '/products/shoes')\n */\nconst constructPath = (locale: Locales, currentPath: string) => {\n // Ensure basePath always starts with '/', and remove trailing slash if needed\n const cleanBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;\n // If basePath is '/', no trailing slash is needed\n const normalizedBasePath = cleanBasePath === '/' ? '' : cleanBasePath;\n\n // Combine basePath + locale + the rest of the path\n // Example: basePath = '/myapp', locale = 'en', currentPath = '/products' => '/myapp/en/products'\n let newPath = `${normalizedBasePath}/${locale}${currentPath}`;\n\n // Special case: if prefixDefault is false and locale is defaultLocale, remove the locale prefix\n if (!prefixDefault && locale === defaultLocale) {\n newPath = `${normalizedBasePath}${currentPath}`;\n }\n\n return newPath;\n};\n\n/* --------------------------------------------------------------------\n * Handlers that mirror Next.js style logic\n * --------------------------------------------------------------------\n */\n\n/**\n * If `noPrefix` is true, we never prefix the locale in the URL.\n * We simply rewrite the request to the same path, but with the best-chosen locale\n * in a header or cookie if desired.\n */\nconst handleNoPrefix = ({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n cookieLocale?: Locales;\n}) => {\n // Determine the best locale\n let locale = cookieLocale ?? defaultLocale;\n\n // Use fallback to localeDetector if no cookie\n if (!cookieLocale) {\n const detectedLocale = localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n );\n locale = detectedLocale as Locales;\n }\n\n // Just rewrite the URL in-place (no prefix). We do NOT redirect because we do not want to alter the URL.\n rewriteUrl(req, res, originalPath, locale);\n return next();\n};\n\n/**\n * The main prefix logic:\n * - If there's no pathLocale in the URL, we might want to detect & redirect or rewrite\n * - If there is a pathLocale, handle cookie mismatch or default locale special cases\n */\nconst handlePrefix = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale?: Locales;\n cookieLocale?: Locales;\n}) => {\n // 1. If pathLocale is missing, handle\n if (!pathLocale) {\n handleMissingPathLocale({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n });\n return;\n }\n\n // 2. If pathLocale exists, handle possible mismatch with cookie\n handleExistingPathLocale({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n });\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n * We detect a locale from cookie / headers / default, then either redirect or rewrite.\n */\nconst handleMissingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n cookieLocale?: Locales;\n}) => {\n // If navigation comes from the same origin (e.g., via an in-app language switcher),\n // treat unprefixed paths as an explicit intent to view the default locale.\n // This avoids redirecting back to the cookie locale (e.g., '/tr/') when user selects '/'.\n const referer = (req.headers.referer || req.headers.referrer) as\n | string\n | undefined;\n if (referer) {\n try {\n const refererUrl = new URL(referer);\n const host = req.headers.host;\n if (host && refererUrl.host === host) {\n const locale = defaultLocale as Locales;\n const newPath = constructPath(locale, originalPath);\n rewriteUrl(req, res, newPath, locale);\n return next();\n }\n } catch {\n // ignore invalid referer\n }\n }\n\n // 1. Choose the best locale\n let locale = (cookieLocale ??\n localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n )) as Locales;\n\n // 2. If still invalid, fallback\n if (!supportedLocales.includes(locale)) {\n locale = defaultLocale;\n }\n\n // 3. Construct new path\n const newPath = constructPath(locale, originalPath);\n\n // If we always prefix default or if this is not the default locale, do a 301 redirect\n // so that the user sees the locale in the URL.\n if (prefixDefault || locale !== defaultLocale) {\n return redirectUrl(res, newPath);\n }\n\n // If we do NOT prefix the default locale, just rewrite in place\n rewriteUrl(req, res, newPath, locale);\n return next();\n};\n\n/**\n * Handles requests where the locale prefix is present in the pathname.\n * We verify if the cookie locale differs from the path locale; if so, handle.\n */\nconst handleExistingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale: Locales;\n cookieLocale?: Locales;\n}) => {\n // 1. If the cookie locale is set and differs from the path locale,\n // and we're not forcing the cookie to always override\n if (\n cookieLocale &&\n cookieLocale !== pathLocale &&\n serverSetCookie !== 'always'\n ) {\n // We want to swap out the pathLocale with the cookieLocale\n const newPath = originalPath.replace(`/${pathLocale}`, `/${cookieLocale}`);\n const finalPath = constructPath(cookieLocale, newPath.replace(/^\\/+/, '/'));\n return redirectUrl(res, finalPath);\n }\n\n // 2. Otherwise, handle default-locale prefix if needed\n handleDefaultLocaleRedirect({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n });\n};\n\n/**\n * If the path locale is the default locale but we don't want to prefix the default, remove it.\n */\nconst handleDefaultLocaleRedirect = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale: Locales;\n}) => {\n // If we don't prefix default AND the path locale is the default locale -> remove it\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Remove the default locale part from the path\n const newPath = originalPath.replace(`/${defaultLocale}`, '') ?? '/';\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n }\n\n // If we do prefix default or pathLocale != default, keep as is, but rewrite headers\n rewriteUrl(req, res, originalPath, pathLocale);\n return next();\n};\n\n/**\n * @deprecated Rename to intlayerMiddleware instead\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nexport const intlayerMiddleware = intlayerMiddlewarePlugin;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA+C;AAC/C,kBAA+B;AAE/B,iBAAsB;AAetB,MAAM,qBAAiB,gCAAiB;AACxC,MAAM,EAAE,sBAAsB,WAAW,IAAI;AAC7C,MAAM,EAAE,SAAS,kBAAkB,cAAc,IAAI;AAErD,MAAM;AAAA,EACJ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,WAAW;AACb,IAAI;AAKG,MAAM,2BAA2B,MAAc;AACpD,SAAO;AAAA,IACL,MAAM;AAAA,IACN,iBAAiB,CAAC,WAAW;AAC3B,aAAO,YAAY,IAAI,CAAC,KAAK,KAAK,SAAS;AAEzC,YACE,IAAI,KAAK,WAAW,eAAe,KACnC,IAAI,KAAK,WAAW,IAAI,KACxB,IAAI,KAAK,MAAM,GAAG,EAAE,CAAC,EAAE,MAAM,YAAY,GACzC;AACA,iBAAO,KAAK;AAAA,QACd;AAGA,cAAM,gBAA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AO,KAAK;AACd;AAYO,MAAM,qBAAqB;","names":["locale","newPath"]}
|
|
1
|
+
{"version":3,"sources":["../../src/intlayerMiddlewarePlugin.ts"],"sourcesContent":["import { getConfiguration, type Locales } from '@intlayer/config';\nimport { localeDetector } from '@intlayer/core';\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport { parse } from 'url';\n/* @ts-ignore - Vite types error */\nimport type { Connect, Plugin } from 'vite';\n\n// Grab all the config you need.\n// Make sure your config includes the following fields if you want to replicate Next.js logic:\n// - internationalization.locales\n// - internationalization.defaultLocale\n// - middleware.cookieName\n// - middleware.headerName\n// - middleware.prefixDefault\n// - middleware.noPrefix\n// - middleware.serverSetCookie\n// - middleware.basePath\n// - etc.\nconst intlayerConfig = getConfiguration();\nconst { internationalization, middleware } = intlayerConfig;\nconst { locales: supportedLocales, defaultLocale } = internationalization;\n\nconst {\n cookieName,\n headerName,\n prefixDefault,\n noPrefix,\n serverSetCookie,\n basePath = '',\n} = middleware;\n\n/**\n * @deprecated Rename to intlayerMiddleware instead\n *\n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n *\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n */\nexport const intlayerMiddlewarePlugin = (): Plugin => {\n return {\n name: 'vite-intlayer-middleware-plugin',\n configureServer: (server) => {\n server.middlewares.use((req, res, next) => {\n // 1. Bypass assets and special Vite endpoints\n if (\n req.url?.startsWith('/node_modules') ||\n req.url?.startsWith('/@') ||\n req.url?.split('?')[0].match(/\\.[a-z]+$/i) // checks for file extensions\n ) {\n return next();\n }\n\n // 2. Parse original URL for path and query\n const parsedUrl = parse(req.url ?? '/', true);\n const originalPath = parsedUrl.pathname ?? '/';\n\n // 3. Attempt to read the cookie locale\n const cookies = parseCookies(req.headers.cookie ?? '');\n const cookieLocale = getValidLocaleFromCookie(cookies[cookieName]);\n\n // 4. Check if there's a locale prefix in the path\n const pathLocale = getPathLocale(originalPath);\n\n // 5. If noPrefix is true, we skip prefix logic altogether\n if (noPrefix) {\n handleNoPrefix({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n });\n return;\n }\n\n // 6. Otherwise, handle prefix logic\n handlePrefix({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n });\n });\n },\n };\n};\n\n/* --------------------------------------------------------------------\n * Helper & Utility Functions\n * --------------------------------------------------------------------\n */\n\n/**\n * Parses cookies from the Cookie header string into an object.\n */\nconst parseCookies = (cookieHeader: string) => {\n return cookieHeader.split(';').reduce(\n (acc, cookie) => {\n const [key, val] = cookie.trim().split('=');\n acc[key] = val;\n return acc;\n },\n {} as Record<string, string>\n );\n};\n\n/**\n * Checks if the cookie locale is valid and is included in the supported locales.\n */\nconst getValidLocaleFromCookie = (\n locale: string | undefined\n): Locales | undefined => {\n if (locale && supportedLocales.includes(locale as Locales)) {\n return locale as Locales;\n }\n return undefined;\n};\n\n/**\n * Extracts the locale from the URL pathname if present as the first segment.\n */\nconst getPathLocale = (pathname: string): Locales | undefined => {\n // e.g. if pathname is /en/some/page or /en\n // we check if \"en\" is in your supportedLocales\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n if (firstSegment && supportedLocales.includes(firstSegment as Locales)) {\n return firstSegment as Locales;\n }\n return undefined;\n};\n\n/**\n * Writes a 301 redirect response with the given new URL.\n */\nconst redirectUrl = (res: ServerResponse<IncomingMessage>, newUrl: string) => {\n res.writeHead(301, { Location: newUrl });\n return res.end();\n};\n\n/**\n * \"Rewrite\" the request internally by adjusting req.url;\n * we also set the locale in the response header if needed.\n */\nconst rewriteUrl = (\n req: Connect.IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n locale?: Locales\n) => {\n req.url = newUrl;\n // If you want to mimic Next.js's behavior of setting a header for the locale:\n if (locale && headerName) {\n res.setHeader(headerName, locale);\n }\n};\n\n/**\n * Constructs a new path string, optionally including a locale prefix and basePath.\n * - basePath: (e.g., '/myapp')\n * - locale: (e.g., 'en')\n * - currentPath:(e.g., '/products/shoes')\n */\nconst constructPath = (locale: Locales, currentPath: string) => {\n // Ensure basePath always starts with '/', and remove trailing slash if needed\n const cleanBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;\n // If basePath is '/', no trailing slash is needed\n const normalizedBasePath = cleanBasePath === '/' ? '' : cleanBasePath;\n\n // Combine basePath + locale + the rest of the path\n // Example: basePath = '/myapp', locale = 'en', currentPath = '/products' => '/myapp/en/products'\n let newPath = `${normalizedBasePath}/${locale}${currentPath}`;\n\n // Special case: if prefixDefault is false and locale is defaultLocale, remove the locale prefix\n if (!prefixDefault && locale === defaultLocale) {\n newPath = `${normalizedBasePath}${currentPath}`;\n }\n\n return newPath;\n};\n\n/* --------------------------------------------------------------------\n * Handlers that mirror Next.js style logic\n * --------------------------------------------------------------------\n */\n\n/**\n * If `noPrefix` is true, we never prefix the locale in the URL.\n * We simply rewrite the request to the same path, but with the best-chosen locale\n * in a header or cookie if desired.\n */\nconst handleNoPrefix = ({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n cookieLocale?: Locales;\n}) => {\n // Determine the best locale\n let locale = cookieLocale ?? defaultLocale;\n\n // Use fallback to localeDetector if no cookie\n if (!cookieLocale) {\n const detectedLocale = localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n );\n locale = detectedLocale as Locales;\n }\n\n // Just rewrite the URL in-place (no prefix). We do NOT redirect because we do not want to alter the URL.\n rewriteUrl(req, res, originalPath, locale);\n return next();\n};\n\n/**\n * The main prefix logic:\n * - If there's no pathLocale in the URL, we might want to detect & redirect or rewrite\n * - If there is a pathLocale, handle cookie mismatch or default locale special cases\n */\nconst handlePrefix = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale?: Locales;\n cookieLocale?: Locales;\n}) => {\n // 1. If pathLocale is missing, handle\n if (!pathLocale) {\n handleMissingPathLocale({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n });\n return;\n }\n\n // 2. If pathLocale exists, handle possible mismatch with cookie\n handleExistingPathLocale({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n });\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n * We detect a locale from cookie / headers / default, then either redirect or rewrite.\n */\nconst handleMissingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n cookieLocale?: Locales;\n}) => {\n // If navigation comes from the same origin (e.g., via an in-app language switcher),\n // treat unprefixed paths as an explicit intent to view the default locale.\n // This avoids redirecting back to the cookie locale (e.g., '/tr/') when user selects '/'.\n const referer = (req.headers.referer || req.headers.referrer) as\n | string\n | undefined;\n if (referer) {\n try {\n const refererUrl = new URL(referer);\n const host = req.headers.host;\n if (host && refererUrl.host === host) {\n const locale = defaultLocale as Locales;\n const newPath = constructPath(locale, originalPath);\n rewriteUrl(req, res, newPath, locale);\n return next();\n }\n } catch {\n // ignore invalid referer\n }\n }\n\n // 1. Choose the best locale\n let locale = (cookieLocale ??\n localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n )) as Locales;\n\n // 2. If still invalid, fallback\n if (!supportedLocales.includes(locale)) {\n locale = defaultLocale;\n }\n\n // 3. Construct new path\n const newPath = constructPath(locale, originalPath);\n\n // If we always prefix default or if this is not the default locale, do a 301 redirect\n // so that the user sees the locale in the URL.\n if (prefixDefault || locale !== defaultLocale) {\n return redirectUrl(res, newPath);\n }\n\n // If we do NOT prefix the default locale, just rewrite in place\n rewriteUrl(req, res, newPath, locale);\n return next();\n};\n\n/**\n * Handles requests where the locale prefix is present in the pathname.\n * We verify if the cookie locale differs from the path locale; if so, handle.\n */\nconst handleExistingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale: Locales;\n cookieLocale?: Locales;\n}) => {\n // 1. If the cookie locale is set and differs from the path locale,\n // and we're not forcing the cookie to always override\n if (\n cookieLocale &&\n cookieLocale !== pathLocale &&\n serverSetCookie !== 'always'\n ) {\n // We want to swap out the pathLocale with the cookieLocale\n const newPath = originalPath.replace(`/${pathLocale}`, `/${cookieLocale}`);\n const finalPath = constructPath(cookieLocale, newPath.replace(/^\\/+/, '/'));\n return redirectUrl(res, finalPath);\n }\n\n // 2. Otherwise, handle default-locale prefix if needed\n handleDefaultLocaleRedirect({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n });\n};\n\n/**\n * If the path locale is the default locale but we don't want to prefix the default, remove it.\n */\nconst handleDefaultLocaleRedirect = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale: Locales;\n}) => {\n // If we don't prefix default AND the path locale is the default locale -> remove it\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Remove the default locale part from the path\n const newPath = originalPath.replace(`/${defaultLocale}`, '') ?? '/';\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n }\n\n // If we do prefix default or pathLocale != default, keep as is, but rewrite headers\n rewriteUrl(req, res, originalPath, pathLocale);\n return next();\n};\n\n/**\n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nexport const intlayerMiddleware = intlayerMiddlewarePlugin;\n\n/**\n * @deprecated Rename to intlayerMiddleware instead\n * \n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nexport const intLayerMiddleware = intlayerMiddlewarePlugin;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA+C;AAC/C,kBAA+B;AAE/B,iBAAsB;AAetB,MAAM,qBAAiB,gCAAiB;AACxC,MAAM,EAAE,sBAAsB,WAAW,IAAI;AAC7C,MAAM,EAAE,SAAS,kBAAkB,cAAc,IAAI;AAErD,MAAM;AAAA,EACJ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,WAAW;AACb,IAAI;AAYG,MAAM,2BAA2B,MAAc;AACpD,SAAO;AAAA,IACL,MAAM;AAAA,IACN,iBAAiB,CAAC,WAAW;AAC3B,aAAO,YAAY,IAAI,CAAC,KAAK,KAAK,SAAS;AAEzC,YACE,IAAI,KAAK,WAAW,eAAe,KACnC,IAAI,KAAK,WAAW,IAAI,KACxB,IAAI,KAAK,MAAM,GAAG,EAAE,CAAC,EAAE,MAAM,YAAY,GACzC;AACA,iBAAO,KAAK;AAAA,QACd;AAGA,cAAM,gBAAY,kBAAM,IAAI,OAAO,KAAK,IAAI;AAC5C,cAAM,eAAe,UAAU,YAAY;AAG3C,cAAM,UAAU,aAAa,IAAI,QAAQ,UAAU,EAAE;AACrD,cAAM,eAAe,yBAAyB,QAAQ,UAAU,CAAC;AAGjE,cAAM,aAAa,cAAc,YAAY;AAG7C,YAAI,UAAU;AACZ,yBAAe;AAAA,YACb;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UACF,CAAC;AACD;AAAA,QACF;AAGA,qBAAa;AAAA,UACX;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACF,CAAC;AAAA,MACH,CAAC;AAAA,IACH;AAAA,EACF;AACF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C;AAGA,aAAW,KAAK,KAAK,SAAS,MAAM;AACpC,SAAO,KAAK;AACd;AAMA,MAAM,2BAA2B,CAAC;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAOM;AAGJ,MACE,gBACA,iBAAiB,cACjB,oBAAoB,UACpB;AAEA,UAAM,UAAU,aAAa,QAAQ,IAAI,UAAU,IAAI,IAAI,YAAY,EAAE;AACzE,UAAM,YAAY,cAAc,cAAc,QAAQ,QAAQ,QAAQ,GAAG,CAAC;AAC1E,WAAO,YAAY,KAAK,SAAS;AAAA,EACnC;AAGA,8BAA4B;AAAA,IAC1B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACH;AAKA,MAAM,8BAA8B,CAAC;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAMM;AAEJ,MAAI,CAAC,iBAAiB,eAAe,eAAe;AAElD,UAAM,UAAU,aAAa,QAAQ,IAAI,aAAa,IAAI,EAAE,KAAK;AACjE,eAAW,KAAK,KAAK,SAAS,UAAU;AACxC,WAAO,KAAK;AAAA,EACd;AAGA,aAAW,KAAK,KAAK,cAAc,UAAU;AAC7C,SAAO,KAAK;AACd;AAYO,MAAM,qBAAqB;AAc3B,MAAM,qBAAqB;","names":["locale","newPath"]}
|
|
@@ -28,6 +28,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
28
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
29
|
var intlayerPlugin_exports = {};
|
|
30
30
|
__export(intlayerPlugin_exports, {
|
|
31
|
+
intLayerPlugin: () => intLayerPlugin,
|
|
31
32
|
intlayer: () => intlayer,
|
|
32
33
|
intlayerPlugin: () => intlayerPlugin
|
|
33
34
|
});
|
|
@@ -93,8 +94,10 @@ const intlayerPlugin = () => {
|
|
|
93
94
|
return plugins;
|
|
94
95
|
};
|
|
95
96
|
const intlayer = intlayerPlugin;
|
|
97
|
+
const intLayerPlugin = intlayerPlugin;
|
|
96
98
|
// Annotate the CommonJS export names for ESM import in node:
|
|
97
99
|
0 && (module.exports = {
|
|
100
|
+
intLayerPlugin,
|
|
98
101
|
intlayer,
|
|
99
102
|
intlayerPlugin
|
|
100
103
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/intlayerPlugin.ts"],"sourcesContent":["import { prepareIntlayer, runOnce, watch } from '@intlayer/chokidar';\nimport intlayerConfig from '@intlayer/config/built';\nimport { join, resolve } from 'path';\n// @ts-ignore - Fix error Module '\"vite\"' has no exported member\nimport { getAlias, getAppLogger } from '@intlayer/config';\nimport { type PluginOption } from 'vite';\nimport { intlayerPrune } from './intlayerPrunePlugin';\n\n/**\n *\n * A Vite plugin that integrates Intlayer configuration into the build process\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayer() ],\n * });\n * ```\n * */\nexport const intlayerPlugin = (): PluginOption => {\n const { watch: isWatchMode } = intlayerConfig.content;\n const { optimize } = intlayerConfig.build;\n const appLogger = getAppLogger(intlayerConfig);\n\n const plugins: PluginOption[] = [\n {\n name: 'vite-intlayer-plugin',\n\n config: (config) => {\n // Update Vite's resolve alias\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve?.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value),\n }),\n },\n };\n\n if (isWatchMode) {\n // Ajout de l'option optimizeDeps.exclude\n config.optimizeDeps = {\n ...config.optimizeDeps,\n exclude: [\n ...(config.optimizeDeps?.exclude ?? []),\n '@intlayer/dictionaries-entry',\n '@intlayer/config/built',\n ],\n };\n }\n\n return config;\n },\n\n configureServer: async (server) => {\n if (intlayerConfig.content.watch) {\n // Start watching (assuming watch is also async)\n watch({ configuration: intlayerConfig });\n }\n },\n\n buildStart: async () => {\n const sentinelPath = join(\n intlayerConfig.content.baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-prepared.lock'\n );\n\n // Code to run when Vite build starts\n // Only call prepareIntlayer once per server startup\n await runOnce(\n sentinelPath,\n async () => await prepareIntlayer(intlayerConfig),\n () => appLogger('Intlayer prepared')\n );\n },\n },\n ];\n\n // Add Babel transform plugin if enabled\n if (optimize) {\n plugins.push(intlayerPrune(intlayerConfig));\n }\n\n return plugins;\n};\n\n/**\n * @deprecated Rename to intlayer instead\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayer() ],\n * });\n * ```\n */\nexport const
|
|
1
|
+
{"version":3,"sources":["../../src/intlayerPlugin.ts"],"sourcesContent":["import { prepareIntlayer, runOnce, watch } from '@intlayer/chokidar';\nimport intlayerConfig from '@intlayer/config/built';\nimport { join, resolve } from 'path';\n// @ts-ignore - Fix error Module '\"vite\"' has no exported member\nimport { getAlias, getAppLogger } from '@intlayer/config';\nimport { type PluginOption } from 'vite';\nimport { intlayerPrune } from './intlayerPrunePlugin';\n\n/**\n * @deprecated Rename to intlayer instead\n *\n * A Vite plugin that integrates Intlayer configuration into the build process\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayer() ],\n * });\n * ```\n * */\nexport const intlayerPlugin = (): PluginOption => {\n const { watch: isWatchMode } = intlayerConfig.content;\n const { optimize } = intlayerConfig.build;\n const appLogger = getAppLogger(intlayerConfig);\n\n const plugins: PluginOption[] = [\n {\n name: 'vite-intlayer-plugin',\n\n config: (config) => {\n // Update Vite's resolve alias\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve?.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value),\n }),\n },\n };\n\n if (isWatchMode) {\n // Ajout de l'option optimizeDeps.exclude\n config.optimizeDeps = {\n ...config.optimizeDeps,\n exclude: [\n ...(config.optimizeDeps?.exclude ?? []),\n '@intlayer/dictionaries-entry',\n '@intlayer/config/built',\n ],\n };\n }\n\n return config;\n },\n\n configureServer: async (server) => {\n if (intlayerConfig.content.watch) {\n // Start watching (assuming watch is also async)\n watch({ configuration: intlayerConfig });\n }\n },\n\n buildStart: async () => {\n const sentinelPath = join(\n intlayerConfig.content.baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-prepared.lock'\n );\n\n // Code to run when Vite build starts\n // Only call prepareIntlayer once per server startup\n await runOnce(\n sentinelPath,\n async () => await prepareIntlayer(intlayerConfig),\n () => appLogger('Intlayer prepared')\n );\n },\n },\n ];\n\n // Add Babel transform plugin if enabled\n if (optimize) {\n plugins.push(intlayerPrune(intlayerConfig));\n }\n\n return plugins;\n};\n\n/**\n * A Vite plugin that integrates Intlayer configuration into the build process\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayer() ],\n * });\n * ```\n */\nexport const intlayer = intlayerPlugin;\n/**\n * @deprecated Rename to intlayer instead\n *\n * A Vite plugin that integrates Intlayer configuration into the build process\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayer() ],\n * });\n * ```\n */\nexport const intLayerPlugin = intlayerPlugin;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAgD;AAChD,mBAA2B;AAC3B,kBAA8B;AAE9B,oBAAuC;AAEvC,iCAA8B;AAcvB,MAAM,iBAAiB,MAAoB;AAChD,QAAM,EAAE,OAAO,YAAY,IAAI,aAAAA,QAAe;AAC9C,QAAM,EAAE,SAAS,IAAI,aAAAA,QAAe;AACpC,QAAM,gBAAY,4BAAa,aAAAA,OAAc;AAE7C,QAAM,UAA0B;AAAA,IAC9B;AAAA,MACE,MAAM;AAAA,MAEN,QAAQ,CAAC,WAAW;AAElB,eAAO,UAAU;AAAA,UACf,GAAG,OAAO;AAAA,UACV,OAAO;AAAA,YACL,GAAG,OAAO,SAAS;AAAA,YACnB,OAAG,wBAAS;AAAA,cACV,eAAe,aAAAA;AAAA,cACf,WAAW,CAAC,cAAkB,qBAAQ,KAAK;AAAA,YAC7C,CAAC;AAAA,UACH;AAAA,QACF;AAEA,YAAI,aAAa;AAEf,iBAAO,eAAe;AAAA,YACpB,GAAG,OAAO;AAAA,YACV,SAAS;AAAA,cACP,GAAI,OAAO,cAAc,WAAW,CAAC;AAAA,cACrC;AAAA,cACA;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAEA,eAAO;AAAA,MACT;AAAA,MAEA,iBAAiB,OAAO,WAAW;AACjC,YAAI,aAAAA,QAAe,QAAQ,OAAO;AAEhC,qCAAM,EAAE,eAAe,aAAAA,QAAe,CAAC;AAAA,QACzC;AAAA,MACF;AAAA,MAEA,YAAY,YAAY;AACtB,cAAM,mBAAe;AAAA,UACnB,aAAAA,QAAe,QAAQ;AAAA,UACvB;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAIA,kBAAM;AAAA,UACJ;AAAA,UACA,YAAY,UAAM,iCAAgB,aAAAA,OAAc;AAAA,UAChD,MAAM,UAAU,mBAAmB;AAAA,QACrC;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAGA,MAAI,UAAU;AACZ,YAAQ,SAAK,0CAAc,aAAAA,OAAc,CAAC;AAAA,EAC5C;AAEA,SAAO;AACT;AAYO,MAAM,WAAW;AAajB,MAAM,iBAAiB;","names":["intlayerConfig"]}
|
package/dist/esm/index.mjs
CHANGED
|
@@ -1,14 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
} from "./intlayerMiddlewarePlugin.mjs";
|
|
5
|
-
import { intlayer, intlayerPlugin } from "./intlayerPlugin.mjs";
|
|
6
|
-
import { intlayerPrune } from "./intlayerPrunePlugin.mjs";
|
|
7
|
-
export {
|
|
8
|
-
intlayer,
|
|
9
|
-
intlayerMiddleware,
|
|
10
|
-
intlayerMiddlewarePlugin,
|
|
11
|
-
intlayerPlugin,
|
|
12
|
-
intlayerPrune
|
|
13
|
-
};
|
|
1
|
+
export * from "./intlayerMiddlewarePlugin.mjs";
|
|
2
|
+
export * from "./intlayerPlugin.mjs";
|
|
3
|
+
export * from "./intlayerPrunePlugin.mjs";
|
|
14
4
|
//# sourceMappingURL=index.mjs.map
|
package/dist/esm/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './intlayerMiddlewarePlugin';\nexport * from './intlayerPlugin';\nexport * from './intlayerPrunePlugin';\n"],"mappings":"AAAA,cAAc;AACd,cAAc;AACd,cAAc;","names":[]}
|
|
@@ -209,7 +209,9 @@ const handleDefaultLocaleRedirect = ({
|
|
|
209
209
|
return next();
|
|
210
210
|
};
|
|
211
211
|
const intlayerMiddleware = intlayerMiddlewarePlugin;
|
|
212
|
+
const intLayerMiddleware = intlayerMiddlewarePlugin;
|
|
212
213
|
export {
|
|
214
|
+
intLayerMiddleware,
|
|
213
215
|
intlayerMiddleware,
|
|
214
216
|
intlayerMiddlewarePlugin
|
|
215
217
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/intlayerMiddlewarePlugin.ts"],"sourcesContent":["import { getConfiguration, type Locales } from '@intlayer/config';\nimport { localeDetector } from '@intlayer/core';\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport { parse } from 'url';\n/* @ts-ignore - Vite types error */\nimport type { Connect, Plugin } from 'vite';\n\n// Grab all the config you need.\n// Make sure your config includes the following fields if you want to replicate Next.js logic:\n// - internationalization.locales\n// - internationalization.defaultLocale\n// - middleware.cookieName\n// - middleware.headerName\n// - middleware.prefixDefault\n// - middleware.noPrefix\n// - middleware.serverSetCookie\n// - middleware.basePath\n// - etc.\nconst intlayerConfig = getConfiguration();\nconst { internationalization, middleware } = intlayerConfig;\nconst { locales: supportedLocales, defaultLocale } = internationalization;\n\nconst {\n cookieName,\n headerName,\n prefixDefault,\n noPrefix,\n serverSetCookie,\n basePath = '',\n} = middleware;\n\n/**\n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n */\nexport const intlayerMiddlewarePlugin = (): Plugin => {\n return {\n name: 'vite-intlayer-middleware-plugin',\n configureServer: (server) => {\n server.middlewares.use((req, res, next) => {\n // 1. Bypass assets and special Vite endpoints\n if (\n req.url?.startsWith('/node_modules') ||\n req.url?.startsWith('/@') ||\n req.url?.split('?')[0].match(/\\.[a-z]+$/i) // checks for file extensions\n ) {\n return next();\n }\n\n // 2. Parse original URL for path and query\n const parsedUrl = parse(req.url ?? '/', true);\n const originalPath = parsedUrl.pathname ?? '/';\n\n // 3. Attempt to read the cookie locale\n const cookies = parseCookies(req.headers.cookie ?? '');\n const cookieLocale = getValidLocaleFromCookie(cookies[cookieName]);\n\n // 4. Check if there's a locale prefix in the path\n const pathLocale = getPathLocale(originalPath);\n\n // 5. If noPrefix is true, we skip prefix logic altogether\n if (noPrefix) {\n handleNoPrefix({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n });\n return;\n }\n\n // 6. Otherwise, handle prefix logic\n handlePrefix({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n });\n });\n },\n };\n};\n\n/* --------------------------------------------------------------------\n * Helper & Utility Functions\n * --------------------------------------------------------------------\n */\n\n/**\n * Parses cookies from the Cookie header string into an object.\n */\nconst parseCookies = (cookieHeader: string) => {\n return cookieHeader.split(';').reduce(\n (acc, cookie) => {\n const [key, val] = cookie.trim().split('=');\n acc[key] = val;\n return acc;\n },\n {} as Record<string, string>\n );\n};\n\n/**\n * Checks if the cookie locale is valid and is included in the supported locales.\n */\nconst getValidLocaleFromCookie = (\n locale: string | undefined\n): Locales | undefined => {\n if (locale && supportedLocales.includes(locale as Locales)) {\n return locale as Locales;\n }\n return undefined;\n};\n\n/**\n * Extracts the locale from the URL pathname if present as the first segment.\n */\nconst getPathLocale = (pathname: string): Locales | undefined => {\n // e.g. if pathname is /en/some/page or /en\n // we check if \"en\" is in your supportedLocales\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n if (firstSegment && supportedLocales.includes(firstSegment as Locales)) {\n return firstSegment as Locales;\n }\n return undefined;\n};\n\n/**\n * Writes a 301 redirect response with the given new URL.\n */\nconst redirectUrl = (res: ServerResponse<IncomingMessage>, newUrl: string) => {\n res.writeHead(301, { Location: newUrl });\n return res.end();\n};\n\n/**\n * \"Rewrite\" the request internally by adjusting req.url;\n * we also set the locale in the response header if needed.\n */\nconst rewriteUrl = (\n req: Connect.IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n locale?: Locales\n) => {\n req.url = newUrl;\n // If you want to mimic Next.js's behavior of setting a header for the locale:\n if (locale && headerName) {\n res.setHeader(headerName, locale);\n }\n};\n\n/**\n * Constructs a new path string, optionally including a locale prefix and basePath.\n * - basePath: (e.g., '/myapp')\n * - locale: (e.g., 'en')\n * - currentPath:(e.g., '/products/shoes')\n */\nconst constructPath = (locale: Locales, currentPath: string) => {\n // Ensure basePath always starts with '/', and remove trailing slash if needed\n const cleanBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;\n // If basePath is '/', no trailing slash is needed\n const normalizedBasePath = cleanBasePath === '/' ? '' : cleanBasePath;\n\n // Combine basePath + locale + the rest of the path\n // Example: basePath = '/myapp', locale = 'en', currentPath = '/products' => '/myapp/en/products'\n let newPath = `${normalizedBasePath}/${locale}${currentPath}`;\n\n // Special case: if prefixDefault is false and locale is defaultLocale, remove the locale prefix\n if (!prefixDefault && locale === defaultLocale) {\n newPath = `${normalizedBasePath}${currentPath}`;\n }\n\n return newPath;\n};\n\n/* --------------------------------------------------------------------\n * Handlers that mirror Next.js style logic\n * --------------------------------------------------------------------\n */\n\n/**\n * If `noPrefix` is true, we never prefix the locale in the URL.\n * We simply rewrite the request to the same path, but with the best-chosen locale\n * in a header or cookie if desired.\n */\nconst handleNoPrefix = ({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n cookieLocale?: Locales;\n}) => {\n // Determine the best locale\n let locale = cookieLocale ?? defaultLocale;\n\n // Use fallback to localeDetector if no cookie\n if (!cookieLocale) {\n const detectedLocale = localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n );\n locale = detectedLocale as Locales;\n }\n\n // Just rewrite the URL in-place (no prefix). We do NOT redirect because we do not want to alter the URL.\n rewriteUrl(req, res, originalPath, locale);\n return next();\n};\n\n/**\n * The main prefix logic:\n * - If there's no pathLocale in the URL, we might want to detect & redirect or rewrite\n * - If there is a pathLocale, handle cookie mismatch or default locale special cases\n */\nconst handlePrefix = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale?: Locales;\n cookieLocale?: Locales;\n}) => {\n // 1. If pathLocale is missing, handle\n if (!pathLocale) {\n handleMissingPathLocale({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n });\n return;\n }\n\n // 2. If pathLocale exists, handle possible mismatch with cookie\n handleExistingPathLocale({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n });\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n * We detect a locale from cookie / headers / default, then either redirect or rewrite.\n */\nconst handleMissingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n cookieLocale?: Locales;\n}) => {\n // If navigation comes from the same origin (e.g., via an in-app language switcher),\n // treat unprefixed paths as an explicit intent to view the default locale.\n // This avoids redirecting back to the cookie locale (e.g., '/tr/') when user selects '/'.\n const referer = (req.headers.referer || req.headers.referrer) as\n | string\n | undefined;\n if (referer) {\n try {\n const refererUrl = new URL(referer);\n const host = req.headers.host;\n if (host && refererUrl.host === host) {\n const locale = defaultLocale as Locales;\n const newPath = constructPath(locale, originalPath);\n rewriteUrl(req, res, newPath, locale);\n return next();\n }\n } catch {\n // ignore invalid referer\n }\n }\n\n // 1. Choose the best locale\n let locale = (cookieLocale ??\n localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n )) as Locales;\n\n // 2. If still invalid, fallback\n if (!supportedLocales.includes(locale)) {\n locale = defaultLocale;\n }\n\n // 3. Construct new path\n const newPath = constructPath(locale, originalPath);\n\n // If we always prefix default or if this is not the default locale, do a 301 redirect\n // so that the user sees the locale in the URL.\n if (prefixDefault || locale !== defaultLocale) {\n return redirectUrl(res, newPath);\n }\n\n // If we do NOT prefix the default locale, just rewrite in place\n rewriteUrl(req, res, newPath, locale);\n return next();\n};\n\n/**\n * Handles requests where the locale prefix is present in the pathname.\n * We verify if the cookie locale differs from the path locale; if so, handle.\n */\nconst handleExistingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale: Locales;\n cookieLocale?: Locales;\n}) => {\n // 1. If the cookie locale is set and differs from the path locale,\n // and we're not forcing the cookie to always override\n if (\n cookieLocale &&\n cookieLocale !== pathLocale &&\n serverSetCookie !== 'always'\n ) {\n // We want to swap out the pathLocale with the cookieLocale\n const newPath = originalPath.replace(`/${pathLocale}`, `/${cookieLocale}`);\n const finalPath = constructPath(cookieLocale, newPath.replace(/^\\/+/, '/'));\n return redirectUrl(res, finalPath);\n }\n\n // 2. Otherwise, handle default-locale prefix if needed\n handleDefaultLocaleRedirect({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n });\n};\n\n/**\n * If the path locale is the default locale but we don't want to prefix the default, remove it.\n */\nconst handleDefaultLocaleRedirect = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale: Locales;\n}) => {\n // If we don't prefix default AND the path locale is the default locale -> remove it\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Remove the default locale part from the path\n const newPath = originalPath.replace(`/${defaultLocale}`, '') ?? '/';\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n }\n\n // If we do prefix default or pathLocale != default, keep as is, but rewrite headers\n rewriteUrl(req, res, originalPath, pathLocale);\n return next();\n};\n\n/**\n * @deprecated Rename to intlayerMiddleware instead\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nexport const intlayerMiddleware = intlayerMiddlewarePlugin;\n"],"mappings":"AAAA,SAAS,wBAAsC;AAC/C,SAAS,sBAAsB;AAE/B,SAAS,aAAa;AAetB,MAAM,iBAAiB,iBAAiB;AACxC,MAAM,EAAE,sBAAsB,WAAW,IAAI;AAC7C,MAAM,EAAE,SAAS,kBAAkB,cAAc,IAAI;AAErD,MAAM;AAAA,EACJ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,WAAW;AACb,IAAI;AAKG,MAAM,2BAA2B,MAAc;AACpD,SAAO;AAAA,IACL,MAAM;AAAA,IACN,iBAAiB,CAAC,WAAW;AAC3B,aAAO,YAAY,IAAI,CAAC,KAAK,KAAK,SAAS;AAEzC,YACE,IAAI,KAAK,WAAW,eAAe,KACnC,IAAI,KAAK,WAAW,IAAI,KACxB,IAAI,KAAK,MAAM,GAAG,EAAE,CAAC,EAAE,MAAM,YAAY,GACzC;AACA,iBAAO,KAAK;AAAA,QACd;AAGA,cAAM,YAAY,MAAM,IAAI,OAAO,KAAK,IAAI;AAC5C,cAAM,eAAe,UAAU,YAAY;AAG3C,cAAM,UAAU,aAAa,IAAI,QAAQ,UAAU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cesContent":["import { getConfiguration, type Locales } from '@intlayer/config';\nimport { localeDetector } from '@intlayer/core';\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport { parse } from 'url';\n/* @ts-ignore - Vite types error */\nimport type { Connect, Plugin } from 'vite';\n\n// Grab all the config you need.\n// Make sure your config includes the following fields if you want to replicate Next.js logic:\n// - internationalization.locales\n// - internationalization.defaultLocale\n// - middleware.cookieName\n// - middleware.headerName\n// - middleware.prefixDefault\n// - middleware.noPrefix\n// - middleware.serverSetCookie\n// - middleware.basePath\n// - etc.\nconst intlayerConfig = getConfiguration();\nconst { internationalization, middleware } = intlayerConfig;\nconst { locales: supportedLocales, defaultLocale } = internationalization;\n\nconst {\n cookieName,\n headerName,\n prefixDefault,\n noPrefix,\n serverSetCookie,\n basePath = '',\n} = middleware;\n\n/**\n * @deprecated Rename to intlayerMiddleware instead\n *\n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n *\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n */\nexport const intlayerMiddlewarePlugin = (): Plugin => {\n return {\n name: 'vite-intlayer-middleware-plugin',\n configureServer: (server) => {\n server.middlewares.use((req, res, next) => {\n // 1. Bypass assets and special Vite endpoints\n if (\n req.url?.startsWith('/node_modules') ||\n req.url?.startsWith('/@') ||\n req.url?.split('?')[0].match(/\\.[a-z]+$/i) // checks for file extensions\n ) {\n return next();\n }\n\n // 2. Parse original URL for path and query\n const parsedUrl = parse(req.url ?? '/', true);\n const originalPath = parsedUrl.pathname ?? '/';\n\n // 3. Attempt to read the cookie locale\n const cookies = parseCookies(req.headers.cookie ?? '');\n const cookieLocale = getValidLocaleFromCookie(cookies[cookieName]);\n\n // 4. Check if there's a locale prefix in the path\n const pathLocale = getPathLocale(originalPath);\n\n // 5. If noPrefix is true, we skip prefix logic altogether\n if (noPrefix) {\n handleNoPrefix({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n });\n return;\n }\n\n // 6. Otherwise, handle prefix logic\n handlePrefix({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n });\n });\n },\n };\n};\n\n/* --------------------------------------------------------------------\n * Helper & Utility Functions\n * --------------------------------------------------------------------\n */\n\n/**\n * Parses cookies from the Cookie header string into an object.\n */\nconst parseCookies = (cookieHeader: string) => {\n return cookieHeader.split(';').reduce(\n (acc, cookie) => {\n const [key, val] = cookie.trim().split('=');\n acc[key] = val;\n return acc;\n },\n {} as Record<string, string>\n );\n};\n\n/**\n * Checks if the cookie locale is valid and is included in the supported locales.\n */\nconst getValidLocaleFromCookie = (\n locale: string | undefined\n): Locales | undefined => {\n if (locale && supportedLocales.includes(locale as Locales)) {\n return locale as Locales;\n }\n return undefined;\n};\n\n/**\n * Extracts the locale from the URL pathname if present as the first segment.\n */\nconst getPathLocale = (pathname: string): Locales | undefined => {\n // e.g. if pathname is /en/some/page or /en\n // we check if \"en\" is in your supportedLocales\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n if (firstSegment && supportedLocales.includes(firstSegment as Locales)) {\n return firstSegment as Locales;\n }\n return undefined;\n};\n\n/**\n * Writes a 301 redirect response with the given new URL.\n */\nconst redirectUrl = (res: ServerResponse<IncomingMessage>, newUrl: string) => {\n res.writeHead(301, { Location: newUrl });\n return res.end();\n};\n\n/**\n * \"Rewrite\" the request internally by adjusting req.url;\n * we also set the locale in the response header if needed.\n */\nconst rewriteUrl = (\n req: Connect.IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n locale?: Locales\n) => {\n req.url = newUrl;\n // If you want to mimic Next.js's behavior of setting a header for the locale:\n if (locale && headerName) {\n res.setHeader(headerName, locale);\n }\n};\n\n/**\n * Constructs a new path string, optionally including a locale prefix and basePath.\n * - basePath: (e.g., '/myapp')\n * - locale: (e.g., 'en')\n * - currentPath:(e.g., '/products/shoes')\n */\nconst constructPath = (locale: Locales, currentPath: string) => {\n // Ensure basePath always starts with '/', and remove trailing slash if needed\n const cleanBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;\n // If basePath is '/', no trailing slash is needed\n const normalizedBasePath = cleanBasePath === '/' ? '' : cleanBasePath;\n\n // Combine basePath + locale + the rest of the path\n // Example: basePath = '/myapp', locale = 'en', currentPath = '/products' => '/myapp/en/products'\n let newPath = `${normalizedBasePath}/${locale}${currentPath}`;\n\n // Special case: if prefixDefault is false and locale is defaultLocale, remove the locale prefix\n if (!prefixDefault && locale === defaultLocale) {\n newPath = `${normalizedBasePath}${currentPath}`;\n }\n\n return newPath;\n};\n\n/* --------------------------------------------------------------------\n * Handlers that mirror Next.js style logic\n * --------------------------------------------------------------------\n */\n\n/**\n * If `noPrefix` is true, we never prefix the locale in the URL.\n * We simply rewrite the request to the same path, but with the best-chosen locale\n * in a header or cookie if desired.\n */\nconst handleNoPrefix = ({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n cookieLocale?: Locales;\n}) => {\n // Determine the best locale\n let locale = cookieLocale ?? defaultLocale;\n\n // Use fallback to localeDetector if no cookie\n if (!cookieLocale) {\n const detectedLocale = localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n );\n locale = detectedLocale as Locales;\n }\n\n // Just rewrite the URL in-place (no prefix). We do NOT redirect because we do not want to alter the URL.\n rewriteUrl(req, res, originalPath, locale);\n return next();\n};\n\n/**\n * The main prefix logic:\n * - If there's no pathLocale in the URL, we might want to detect & redirect or rewrite\n * - If there is a pathLocale, handle cookie mismatch or default locale special cases\n */\nconst handlePrefix = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale?: Locales;\n cookieLocale?: Locales;\n}) => {\n // 1. If pathLocale is missing, handle\n if (!pathLocale) {\n handleMissingPathLocale({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n });\n return;\n }\n\n // 2. If pathLocale exists, handle possible mismatch with cookie\n handleExistingPathLocale({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n });\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n * We detect a locale from cookie / headers / default, then either redirect or rewrite.\n */\nconst handleMissingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n cookieLocale?: Locales;\n}) => {\n // If navigation comes from the same origin (e.g., via an in-app language switcher),\n // treat unprefixed paths as an explicit intent to view the default locale.\n // This avoids redirecting back to the cookie locale (e.g., '/tr/') when user selects '/'.\n const referer = (req.headers.referer || req.headers.referrer) as\n | string\n | undefined;\n if (referer) {\n try {\n const refererUrl = new URL(referer);\n const host = req.headers.host;\n if (host && refererUrl.host === host) {\n const locale = defaultLocale as Locales;\n const newPath = constructPath(locale, originalPath);\n rewriteUrl(req, res, newPath, locale);\n return next();\n }\n } catch {\n // ignore invalid referer\n }\n }\n\n // 1. Choose the best locale\n let locale = (cookieLocale ??\n localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n )) as Locales;\n\n // 2. If still invalid, fallback\n if (!supportedLocales.includes(locale)) {\n locale = defaultLocale;\n }\n\n // 3. Construct new path\n const newPath = constructPath(locale, originalPath);\n\n // If we always prefix default or if this is not the default locale, do a 301 redirect\n // so that the user sees the locale in the URL.\n if (prefixDefault || locale !== defaultLocale) {\n return redirectUrl(res, newPath);\n }\n\n // If we do NOT prefix the default locale, just rewrite in place\n rewriteUrl(req, res, newPath, locale);\n return next();\n};\n\n/**\n * Handles requests where the locale prefix is present in the pathname.\n * We verify if the cookie locale differs from the path locale; if so, handle.\n */\nconst handleExistingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale: Locales;\n cookieLocale?: Locales;\n}) => {\n // 1. If the cookie locale is set and differs from the path locale,\n // and we're not forcing the cookie to always override\n if (\n cookieLocale &&\n cookieLocale !== pathLocale &&\n serverSetCookie !== 'always'\n ) {\n // We want to swap out the pathLocale with the cookieLocale\n const newPath = originalPath.replace(`/${pathLocale}`, `/${cookieLocale}`);\n const finalPath = constructPath(cookieLocale, newPath.replace(/^\\/+/, '/'));\n return redirectUrl(res, finalPath);\n }\n\n // 2. Otherwise, handle default-locale prefix if needed\n handleDefaultLocaleRedirect({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n });\n};\n\n/**\n * If the path locale is the default locale but we don't want to prefix the default, remove it.\n */\nconst handleDefaultLocaleRedirect = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale: Locales;\n}) => {\n // If we don't prefix default AND the path locale is the default locale -> remove it\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Remove the default locale part from the path\n const newPath = originalPath.replace(`/${defaultLocale}`, '') ?? '/';\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n }\n\n // If we do prefix default or pathLocale != default, keep as is, but rewrite headers\n rewriteUrl(req, res, originalPath, pathLocale);\n return next();\n};\n\n/**\n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nexport const intlayerMiddleware = intlayerMiddlewarePlugin;\n\n/**\n * @deprecated Rename to intlayerMiddleware instead\n * \n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerMiddleware() ],\n * });\n * ```\n */\nex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,MAOM;AAGJ,MACE,gBACA,iBAAiB,cACjB,oBAAoB,UACpB;AAEA,UAAM,UAAU,aAAa,QAAQ,IAAI,UAAU,IAAI,IAAI,YAAY,EAAE;AACzE,UAAM,YAAY,cAAc,cAAc,QAAQ,QAAQ,QAAQ,GAAG,CAAC;AAC1E,WAAO,YAAY,KAAK,SAAS;AAAA,EACnC;AAGA,8BAA4B;AAAA,IAC1B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACH;AAKA,MAAM,8BAA8B,CAAC;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAMM;AAEJ,MAAI,CAAC,iBAAiB,eAAe,eAAe;AAElD,UAAM,UAAU,aAAa,QAAQ,IAAI,aAAa,IAAI,EAAE,KAAK;AACjE,eAAW,KAAK,KAAK,SAAS,UAAU;AACxC,WAAO,KAAK;AAAA,EACd;AAGA,aAAW,KAAK,KAAK,cAAc,UAAU;AAC7C,SAAO,KAAK;AACd;AAYO,MAAM,qBAAqB;AAc3B,MAAM,qBAAqB;","names":["locale","newPath"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/intlayerPlugin.ts"],"sourcesContent":["import { prepareIntlayer, runOnce, watch } from '@intlayer/chokidar';\nimport intlayerConfig from '@intlayer/config/built';\nimport { join, resolve } from 'path';\n// @ts-ignore - Fix error Module '\"vite\"' has no exported member\nimport { getAlias, getAppLogger } from '@intlayer/config';\nimport { type PluginOption } from 'vite';\nimport { intlayerPrune } from './intlayerPrunePlugin';\n\n/**\n *\n * A Vite plugin that integrates Intlayer configuration into the build process\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayer() ],\n * });\n * ```\n * */\nexport const intlayerPlugin = (): PluginOption => {\n const { watch: isWatchMode } = intlayerConfig.content;\n const { optimize } = intlayerConfig.build;\n const appLogger = getAppLogger(intlayerConfig);\n\n const plugins: PluginOption[] = [\n {\n name: 'vite-intlayer-plugin',\n\n config: (config) => {\n // Update Vite's resolve alias\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve?.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value),\n }),\n },\n };\n\n if (isWatchMode) {\n // Ajout de l'option optimizeDeps.exclude\n config.optimizeDeps = {\n ...config.optimizeDeps,\n exclude: [\n ...(config.optimizeDeps?.exclude ?? []),\n '@intlayer/dictionaries-entry',\n '@intlayer/config/built',\n ],\n };\n }\n\n return config;\n },\n\n configureServer: async (server) => {\n if (intlayerConfig.content.watch) {\n // Start watching (assuming watch is also async)\n watch({ configuration: intlayerConfig });\n }\n },\n\n buildStart: async () => {\n const sentinelPath = join(\n intlayerConfig.content.baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-prepared.lock'\n );\n\n // Code to run when Vite build starts\n // Only call prepareIntlayer once per server startup\n await runOnce(\n sentinelPath,\n async () => await prepareIntlayer(intlayerConfig),\n () => appLogger('Intlayer prepared')\n );\n },\n },\n ];\n\n // Add Babel transform plugin if enabled\n if (optimize) {\n plugins.push(intlayerPrune(intlayerConfig));\n }\n\n return plugins;\n};\n\n/**\n * @deprecated Rename to intlayer instead\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayer() ],\n * });\n * ```\n */\nexport const
|
|
1
|
+
{"version":3,"sources":["../../src/intlayerPlugin.ts"],"sourcesContent":["import { prepareIntlayer, runOnce, watch } from '@intlayer/chokidar';\nimport intlayerConfig from '@intlayer/config/built';\nimport { join, resolve } from 'path';\n// @ts-ignore - Fix error Module '\"vite\"' has no exported member\nimport { getAlias, getAppLogger } from '@intlayer/config';\nimport { type PluginOption } from 'vite';\nimport { intlayerPrune } from './intlayerPrunePlugin';\n\n/**\n * @deprecated Rename to intlayer instead\n *\n * A Vite plugin that integrates Intlayer configuration into the build process\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayer() ],\n * });\n * ```\n * */\nexport const intlayerPlugin = (): PluginOption => {\n const { watch: isWatchMode } = intlayerConfig.content;\n const { optimize } = intlayerConfig.build;\n const appLogger = getAppLogger(intlayerConfig);\n\n const plugins: PluginOption[] = [\n {\n name: 'vite-intlayer-plugin',\n\n config: (config) => {\n // Update Vite's resolve alias\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve?.alias,\n ...getAlias({\n configuration: intlayerConfig,\n formatter: (value: string) => resolve(value),\n }),\n },\n };\n\n if (isWatchMode) {\n // Ajout de l'option optimizeDeps.exclude\n config.optimizeDeps = {\n ...config.optimizeDeps,\n exclude: [\n ...(config.optimizeDeps?.exclude ?? []),\n '@intlayer/dictionaries-entry',\n '@intlayer/config/built',\n ],\n };\n }\n\n return config;\n },\n\n configureServer: async (server) => {\n if (intlayerConfig.content.watch) {\n // Start watching (assuming watch is also async)\n watch({ configuration: intlayerConfig });\n }\n },\n\n buildStart: async () => {\n const sentinelPath = join(\n intlayerConfig.content.baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-prepared.lock'\n );\n\n // Code to run when Vite build starts\n // Only call prepareIntlayer once per server startup\n await runOnce(\n sentinelPath,\n async () => await prepareIntlayer(intlayerConfig),\n () => appLogger('Intlayer prepared')\n );\n },\n },\n ];\n\n // Add Babel transform plugin if enabled\n if (optimize) {\n plugins.push(intlayerPrune(intlayerConfig));\n }\n\n return plugins;\n};\n\n/**\n * A Vite plugin that integrates Intlayer configuration into the build process\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayer() ],\n * });\n * ```\n */\nexport const intlayer = intlayerPlugin;\n/**\n * @deprecated Rename to intlayer instead\n *\n * A Vite plugin that integrates Intlayer configuration into the build process\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayer() ],\n * });\n * ```\n */\nexport const intLayerPlugin = intlayerPlugin;\n"],"mappings":"AA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;AAajB,MAAM,iBAAiB;","names":[]}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export
|
|
2
|
-
export
|
|
3
|
-
export
|
|
1
|
+
export * from './intlayerMiddlewarePlugin';
|
|
2
|
+
export * from './intlayerPlugin';
|
|
3
|
+
export * from './intlayerPrunePlugin';
|
|
4
4
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,4BAA4B,CAAC;AAC3C,cAAc,kBAAkB,CAAC;AACjC,cAAc,uBAAuB,CAAC"}
|
|
@@ -1,10 +1,17 @@
|
|
|
1
1
|
import type { Plugin } from 'vite';
|
|
2
2
|
/**
|
|
3
|
+
* @deprecated Rename to intlayerMiddleware instead
|
|
4
|
+
*
|
|
3
5
|
* A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.
|
|
6
|
+
*
|
|
7
|
+
* // Example usage of the plugin in a Vite configuration
|
|
8
|
+
* export default defineConfig({
|
|
9
|
+
* plugins: [ intlayerMiddleware() ],
|
|
10
|
+
* });
|
|
4
11
|
*/
|
|
5
12
|
export declare const intlayerMiddlewarePlugin: () => Plugin;
|
|
6
13
|
/**
|
|
7
|
-
*
|
|
14
|
+
* A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.
|
|
8
15
|
*
|
|
9
16
|
* ```ts
|
|
10
17
|
* // Example usage of the plugin in a Vite configuration
|
|
@@ -14,4 +21,17 @@ export declare const intlayerMiddlewarePlugin: () => Plugin;
|
|
|
14
21
|
* ```
|
|
15
22
|
*/
|
|
16
23
|
export declare const intlayerMiddleware: () => Plugin;
|
|
24
|
+
/**
|
|
25
|
+
* @deprecated Rename to intlayerMiddleware instead
|
|
26
|
+
*
|
|
27
|
+
* A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.
|
|
28
|
+
|
|
29
|
+
* ```ts
|
|
30
|
+
* // Example usage of the plugin in a Vite configuration
|
|
31
|
+
* export default defineConfig({
|
|
32
|
+
* plugins: [ intlayerMiddleware() ],
|
|
33
|
+
* });
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
export declare const intLayerMiddleware: () => Plugin;
|
|
17
37
|
//# sourceMappingURL=intlayerMiddlewarePlugin.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerMiddlewarePlugin.d.ts","sourceRoot":"","sources":["../../src/intlayerMiddlewarePlugin.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAW,MAAM,EAAE,MAAM,MAAM,CAAC;AA0B5C
|
|
1
|
+
{"version":3,"file":"intlayerMiddlewarePlugin.d.ts","sourceRoot":"","sources":["../../src/intlayerMiddlewarePlugin.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAW,MAAM,EAAE,MAAM,MAAM,CAAC;AA0B5C;;;;;;;;;GASG;AACH,eAAO,MAAM,wBAAwB,QAAO,MAiD3C,CAAC;AA4TF;;;;;;;;;GASG;AACH,eAAO,MAAM,kBAAkB,QAvXa,MAuXc,CAAC;AAE3D;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,kBAAkB,QArYa,MAqYc,CAAC"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type PluginOption } from 'vite';
|
|
2
2
|
/**
|
|
3
|
+
* @deprecated Rename to intlayer instead
|
|
3
4
|
*
|
|
4
5
|
* A Vite plugin that integrates Intlayer configuration into the build process
|
|
5
6
|
*
|
|
@@ -12,7 +13,7 @@ import { type PluginOption } from 'vite';
|
|
|
12
13
|
* */
|
|
13
14
|
export declare const intlayerPlugin: () => PluginOption;
|
|
14
15
|
/**
|
|
15
|
-
*
|
|
16
|
+
* A Vite plugin that integrates Intlayer configuration into the build process
|
|
16
17
|
*
|
|
17
18
|
* ```ts
|
|
18
19
|
* // Example usage of the plugin in a Vite configuration
|
|
@@ -22,4 +23,17 @@ export declare const intlayerPlugin: () => PluginOption;
|
|
|
22
23
|
* ```
|
|
23
24
|
*/
|
|
24
25
|
export declare const intlayer: () => PluginOption;
|
|
26
|
+
/**
|
|
27
|
+
* @deprecated Rename to intlayer instead
|
|
28
|
+
*
|
|
29
|
+
* A Vite plugin that integrates Intlayer configuration into the build process
|
|
30
|
+
*
|
|
31
|
+
* ```ts
|
|
32
|
+
* // Example usage of the plugin in a Vite configuration
|
|
33
|
+
* export default defineConfig({
|
|
34
|
+
* plugins: [ intlayer() ],
|
|
35
|
+
* });
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export declare const intLayerPlugin: () => PluginOption;
|
|
25
39
|
//# sourceMappingURL=intlayerPlugin.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlayerPlugin.d.ts","sourceRoot":"","sources":["../../src/intlayerPlugin.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,MAAM,CAAC;AAGzC
|
|
1
|
+
{"version":3,"file":"intlayerPlugin.d.ts","sourceRoot":"","sources":["../../src/intlayerPlugin.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,MAAM,CAAC;AAGzC;;;;;;;;;;;MAWM;AACN,eAAO,MAAM,cAAc,QAAO,YAqEjC,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,QAAQ,QAjFa,YAiFI,CAAC;AACvC;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,cAAc,QA9FO,YA8FU,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vite-intlayer",
|
|
3
|
-
"version": "6.0.
|
|
3
|
+
"version": "6.0.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "A Vite plugin for seamless internationalization (i18n), providing locale detection, redirection, and environment-based configuration",
|
|
6
6
|
"keywords": [
|
|
@@ -58,11 +58,11 @@
|
|
|
58
58
|
"./package.json"
|
|
59
59
|
],
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@intlayer/
|
|
62
|
-
"@intlayer/
|
|
63
|
-
"@intlayer/chokidar": "6.0.
|
|
64
|
-
"@intlayer/
|
|
65
|
-
"@intlayer/
|
|
61
|
+
"@intlayer/core": "6.0.1",
|
|
62
|
+
"@intlayer/config": "6.0.1",
|
|
63
|
+
"@intlayer/chokidar": "6.0.1",
|
|
64
|
+
"@intlayer/dictionaries-entry": "6.0.1",
|
|
65
|
+
"@intlayer/babel": "6.0.1"
|
|
66
66
|
},
|
|
67
67
|
"devDependencies": {
|
|
68
68
|
"@types/node": "^24.2.1",
|
|
@@ -75,17 +75,17 @@
|
|
|
75
75
|
"tsup": "^8.5.0",
|
|
76
76
|
"typescript": "^5.9.2",
|
|
77
77
|
"vitest": "^3.2.4",
|
|
78
|
-
"@utils/eslint-config": "1.0.4",
|
|
79
78
|
"@utils/ts-config": "1.0.4",
|
|
80
79
|
"@utils/ts-config-types": "1.0.4",
|
|
81
|
-
"@utils/tsup-config": "1.0.4"
|
|
80
|
+
"@utils/tsup-config": "1.0.4",
|
|
81
|
+
"@utils/eslint-config": "1.0.4"
|
|
82
82
|
},
|
|
83
83
|
"peerDependencies": {
|
|
84
84
|
"vite": ">=4.0.0",
|
|
85
|
-
"@intlayer/chokidar": "6.0.
|
|
86
|
-
"@intlayer/
|
|
87
|
-
"@intlayer/
|
|
88
|
-
"@intlayer/dictionaries-entry": "6.0.
|
|
85
|
+
"@intlayer/chokidar": "6.0.1",
|
|
86
|
+
"@intlayer/core": "6.0.1",
|
|
87
|
+
"@intlayer/config": "6.0.1",
|
|
88
|
+
"@intlayer/dictionaries-entry": "6.0.1"
|
|
89
89
|
},
|
|
90
90
|
"engines": {
|
|
91
91
|
"node": ">=14.18"
|