UNPKG

vite-intlayer

Version:

A Vite plugin for seamless internationalization (i18n), providing locale detection, redirection, and environment-based configuration

1 lines 14.5 kB
{"version":3,"sources":["../../src/intlayerMiddlewarePlugin.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'http';\nimport { parse } from 'url';\nimport { getConfiguration, type Locales } from '@intlayer/config';\nimport { localeDetector } from '@intlayer/core';\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 // 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"],"mappings":"AACA,SAAS,aAAa;AACtB,SAAS,wBAAsC;AAC/C,SAAS,sBAAsB;AAe/B,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,Y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