express-intlayer 8.1.2 → 8.1.3

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.
@@ -1,130 +1,2 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- let _intlayer_chokidar = require("@intlayer/chokidar");
3
- let _intlayer_config = require("@intlayer/config");
4
- let _intlayer_core = require("@intlayer/core");
5
- let cls_hooked = require("cls-hooked");
6
-
7
- //#region src/index.ts
8
- const configuration = (0, _intlayer_config.getConfiguration)();
9
- const { internationalization } = configuration;
10
- /**
11
- * Retrieves the locale from storage (cookies, localStorage, sessionStorage).
12
- */
13
- const getStorageLocale = (req) => (0, _intlayer_core.getLocaleFromStorage)({
14
- getCookie: (name) => req.cookies?.[name],
15
- getHeader: (name) => req.headers?.[name]
16
- });
17
- const appNamespace = (0, cls_hooked.createNamespace)("app");
18
- (0, _intlayer_chokidar.prepareIntlayer)(configuration);
19
- const translateFunction = (_req, res, _next) => (content, locale) => {
20
- const { locale: currentLocale, defaultLocale } = res.locals;
21
- const targetLocale = locale ?? currentLocale;
22
- if (typeof content === "undefined") return "";
23
- if (typeof content === "string") return content;
24
- if (typeof content?.[targetLocale] === "undefined") if (typeof content?.[defaultLocale] === "undefined") return content;
25
- else return (0, _intlayer_core.getTranslation)(content, defaultLocale);
26
- return (0, _intlayer_core.getTranslation)(content, targetLocale);
27
- };
28
- /**
29
- * Express middleware that detects the user's locale and populates `res.locals` with Intlayer data.
30
- *
31
- * It performs:
32
- * 1. Locale detection from cookies, headers, or default settings.
33
- * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into `res.locals`.
34
- * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.
35
- *
36
- * @returns An Express middleware function.
37
- *
38
- * @example
39
- * ```ts
40
- * import express from 'express';
41
- * import { intlayer } from 'express-intlayer';
42
- *
43
- * const app = express();
44
- * app.use(intlayer());
45
- * ```
46
- */
47
- const intlayer = () => async (req, res, next) => {
48
- const localeFromStorage = getStorageLocale(req);
49
- const negotiatorHeaders = {};
50
- if (req && typeof req.headers === "object") {
51
- for (const key in req.headers) if (typeof req.headers[key] === "string") negotiatorHeaders[key] = req.headers[key];
52
- }
53
- const localeDetected = (0, _intlayer_core.localeDetector)(negotiatorHeaders, internationalization.locales, internationalization.defaultLocale);
54
- res.locals.locale_storage = localeFromStorage;
55
- res.locals.locale_detected = localeDetected;
56
- res.locals.locale = localeFromStorage ?? localeDetected;
57
- res.locals.defaultLocale = internationalization.defaultLocale;
58
- const t = translateFunction(req, res, next);
59
- const getIntlayer = (key, localeArg = localeDetected, ...props) => (0, _intlayer_core.getIntlayer)(key, localeArg, ...props);
60
- const getDictionary = (key, localeArg = localeDetected, ...props) => (0, _intlayer_core.getDictionary)(key, localeArg, ...props);
61
- res.locals.t = t;
62
- res.locals.getIntlayer = getIntlayer;
63
- res.locals.getDictionary = getDictionary;
64
- appNamespace.run(() => {
65
- appNamespace.set("t", t);
66
- appNamespace.set("getIntlayer", getIntlayer);
67
- appNamespace.set("getDictionary", getDictionary);
68
- next();
69
- });
70
- };
71
- /**
72
- * Translation function to retrieve content for the current locale.
73
- *
74
- * This function works within the request lifecycle managed by the `intlayer` middleware.
75
- *
76
- * @param content - A map of locales to content.
77
- * @param locale - Optional locale override.
78
- * @returns The translated content.
79
- *
80
- * @example
81
- * ```ts
82
- * import { t } from 'express-intlayer';
83
- *
84
- * app.get('/', (req, res) => {
85
- * const greeting = t({
86
- * en: 'Hello',
87
- * fr: 'Bonjour',
88
- * });
89
- * res.send(greeting);
90
- * });
91
- * ```
92
- */
93
- const t = (content, locale) => {
94
- try {
95
- if (typeof appNamespace === "undefined") throw new Error("Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.");
96
- if (typeof appNamespace.get("t") !== "function") throw new Error("Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.");
97
- return appNamespace.get("t")(content, locale);
98
- } catch (error) {
99
- if (process.env.NODE_ENV === "development") console.error(error.message);
100
- return (0, _intlayer_core.getTranslation)(content, locale ?? internationalization.defaultLocale);
101
- }
102
- };
103
- const getIntlayer = (...args) => {
104
- try {
105
- if (typeof appNamespace === "undefined") throw new Error("Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.");
106
- if (typeof appNamespace.get("getIntlayer") !== "function") throw new Error("Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.");
107
- return appNamespace.get("getIntlayer")(...args);
108
- } catch (error) {
109
- if (process.env.NODE_ENV === "development") console.error(error.message);
110
- return (0, _intlayer_core.getIntlayer)(...args);
111
- }
112
- };
113
- const getDictionary = (...args) => {
114
- try {
115
- if (typeof appNamespace === "undefined") throw new Error("Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.");
116
- if (typeof appNamespace.get("getDictionary") !== "function") throw new Error("Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.");
117
- return appNamespace.get("getDictionary")(...args);
118
- } catch (error) {
119
- if (process.env.NODE_ENV === "development") console.error(error.message);
120
- return (0, _intlayer_core.getDictionary)(...args);
121
- }
122
- };
123
-
124
- //#endregion
125
- exports.getDictionary = getDictionary;
126
- exports.getIntlayer = getIntlayer;
127
- exports.intlayer = intlayer;
128
- exports.t = t;
129
- exports.translateFunction = translateFunction;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require(`@intlayer/chokidar/build`),t=require(`@intlayer/config/node`),n=require(`@intlayer/core/interpreter`),r=require(`@intlayer/core/localization`),i=require(`@intlayer/core/utils`),a=require(`cls-hooked`);const o=(0,t.getConfiguration)(),{internationalization:s}=o,c=e=>(0,i.getLocaleFromStorage)({getCookie:t=>e.cookies?.[t],getHeader:t=>e.headers?.[t]}),l=(0,a.createNamespace)(`app`);(0,e.prepareIntlayer)(o);const u=(e,t,r)=>(e,r)=>{let{locale:i,defaultLocale:a}=t.locals,o=r??i;return e===void 0?``:typeof e==`string`?e:e?.[o]===void 0?e?.[a]===void 0?e:(0,n.getTranslation)(e,a):(0,n.getTranslation)(e,o)},d=()=>async(e,t,i)=>{let a=c(e),o={};if(e&&typeof e.headers==`object`)for(let t in e.headers)typeof e.headers[t]==`string`&&(o[t]=e.headers[t]);let d=(0,r.localeDetector)(o,s.locales,s.defaultLocale);t.locals.locale_storage=a,t.locals.locale_detected=d,t.locals.locale=a??d,t.locals.defaultLocale=s.defaultLocale;let f=u(e,t,i),p=(e,t=d,...r)=>(0,n.getIntlayer)(e,t,...r),m=(e,t=d,...r)=>(0,n.getDictionary)(e,t,...r);t.locals.t=f,t.locals.getIntlayer=p,t.locals.getDictionary=m,l.run(()=>{l.set(`t`,f),l.set(`getIntlayer`,p),l.set(`getDictionary`,m),i()})},f=(e,t)=>{try{if(l===void 0)throw Error("Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.");if(typeof l.get(`t`)!=`function`)throw Error(`Using the import { t } from "express-intlayer" is not supported in your environment. Use the res.locals.t syntax instead.`);return l.get(`t`)(e,t)}catch(r){return process.env.NODE_ENV===`development`&&console.error(r.message),(0,n.getTranslation)(e,t??s.defaultLocale)}},p=(...e)=>{try{if(l===void 0)throw Error("Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.");if(typeof l.get(`getIntlayer`)!=`function`)throw Error(`Using the import { t } from "express-intlayer" is not supported in your environment. Use the res.locals.t syntax instead.`);return l.get(`getIntlayer`)(...e)}catch(t){return process.env.NODE_ENV===`development`&&console.error(t.message),(0,n.getIntlayer)(...e)}},m=(...e)=>{try{if(l===void 0)throw Error("Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.");if(typeof l.get(`getDictionary`)!=`function`)throw Error(`Using the import { t } from "express-intlayer" is not supported in your environment. Use the res.locals.t syntax instead.`);return l.get(`getDictionary`)(...e)}catch(t){return process.env.NODE_ENV===`development`&&console.error(t.message),(0,n.getDictionary)(...e)}};exports.getDictionary=m,exports.getIntlayer=p,exports.intlayer=d,exports.t=f,exports.translateFunction=u;
130
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":[],"sources":["../../src/index.ts"],"sourcesContent":["import { prepareIntlayer } from '@intlayer/chokidar';\nimport { getConfiguration } from '@intlayer/config';\nimport {\n getDictionary as getDictionaryFunction,\n getIntlayer as getIntlayerFunction,\n getLocaleFromStorage,\n getTranslation,\n localeDetector,\n} from '@intlayer/core';\nimport type { Locale, StrictModeLocaleMap } from '@intlayer/types';\nimport { createNamespace } from 'cls-hooked';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\n\nconst configuration = getConfiguration();\nconst { internationalization } = configuration;\n\n/**\n * Retrieves the locale from storage (cookies, localStorage, sessionStorage).\n */\nconst getStorageLocale = (req: Request): Locale | undefined =>\n getLocaleFromStorage({\n getCookie: (name: string) => req.cookies?.[name],\n getHeader: (name: string) => req.headers?.[name] as string | undefined,\n });\n\nconst appNamespace = createNamespace('app');\n\nprepareIntlayer(configuration);\n\nexport const translateFunction =\n (_req: Request, res: Response, _next?: NextFunction) =>\n <T extends string>(\n content: StrictModeLocaleMap<T> | string,\n locale?: Locale\n ): T => {\n const { locale: currentLocale, defaultLocale } = res.locals as {\n locale: Locale;\n defaultLocale: Locale;\n };\n\n const targetLocale = locale ?? currentLocale;\n\n if (typeof content === 'undefined') {\n return '' as unknown as T;\n }\n\n if (typeof content === 'string') {\n return content as unknown as T;\n }\n\n if (\n typeof content?.[\n targetLocale as unknown as keyof StrictModeLocaleMap<T>\n ] === 'undefined'\n ) {\n if (\n typeof content?.[\n defaultLocale as unknown as keyof StrictModeLocaleMap<T>\n ] === 'undefined'\n ) {\n return content as unknown as T;\n } else {\n return getTranslation(content, defaultLocale);\n }\n }\n\n return getTranslation(content, targetLocale);\n };\n\n/**\n * Express middleware that detects the user's locale and populates `res.locals` with Intlayer data.\n *\n * It performs:\n * 1. Locale detection from cookies, headers, or default settings.\n * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into `res.locals`.\n * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.\n *\n * @returns An Express middleware function.\n *\n * @example\n * ```ts\n * import express from 'express';\n * import { intlayer } from 'express-intlayer';\n *\n * const app = express();\n * app.use(intlayer());\n * ```\n */\nexport const intlayer = (): RequestHandler => async (req, res, next) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(req);\n // Interpret browser locale\n\n const negotiatorHeaders: Record<string, string> = {};\n\n // // Check if req.headers exists and is an object\n if (req && typeof req.headers === 'object') {\n // Copy all headers from the request to negotiatorHeaders\n for (const key in req.headers) {\n if (typeof req.headers[key] === 'string') {\n negotiatorHeaders[key] = req.headers[key];\n }\n }\n }\n\n const localeDetected = localeDetector(\n negotiatorHeaders,\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n res.locals.locale_storage = localeFromStorage;\n res.locals.locale_detected = localeDetected;\n res.locals.locale = localeFromStorage ?? localeDetected;\n res.locals.defaultLocale = internationalization.defaultLocale;\n\n const t = translateFunction(req, res, next);\n\n const getIntlayer: typeof getIntlayerFunction = (\n key,\n localeArg = localeDetected as Parameters<typeof getIntlayerFunction>[1],\n ...props\n ) => getIntlayerFunction(key, localeArg, ...props);\n\n const getDictionary: typeof getDictionaryFunction = (\n key,\n localeArg = localeDetected as Parameters<typeof getDictionaryFunction>[1],\n ...props\n ) => getDictionaryFunction(key, localeArg, ...props);\n\n res.locals.t = t;\n res.locals.getIntlayer = getIntlayer;\n res.locals.getDictionary = getDictionary;\n\n appNamespace.run(() => {\n appNamespace.set('t', t);\n appNamespace.set('getIntlayer', getIntlayer);\n appNamespace.set('getDictionary', getDictionary);\n\n next();\n });\n};\n\n/**\n * Translation function to retrieve content for the current locale.\n *\n * This function works within the request lifecycle managed by the `intlayer` middleware.\n *\n * @param content - A map of locales to content.\n * @param locale - Optional locale override.\n * @returns The translated content.\n *\n * @example\n * ```ts\n * import { t } from 'express-intlayer';\n *\n * app.get('/', (req, res) => {\n * const greeting = t({\n * en: 'Hello',\n * fr: 'Bonjour',\n * });\n * res.send(greeting);\n * });\n * ```\n */\nexport const t = <Content = string>(\n content: StrictModeLocaleMap<Content>,\n locale?: Locale\n): Content => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('t') !== 'function') {\n throw new Error(\n 'Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.'\n );\n }\n\n return appNamespace.get('t')(content, locale);\n } catch (error) {\n if (process.env.NODE_ENV === 'development') {\n console.error((error as Error).message);\n }\n\n return getTranslation(\n content,\n locale ?? internationalization.defaultLocale\n );\n }\n};\n\nexport const getIntlayer: typeof getIntlayerFunction = (...args) => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('getIntlayer') !== 'function') {\n throw new Error(\n 'Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.'\n );\n }\n\n return appNamespace.get('getIntlayer')(...args);\n } catch (error) {\n if (process.env.NODE_ENV === 'development') {\n console.error((error as Error).message);\n }\n return getIntlayerFunction(...args);\n }\n};\n\nexport const getDictionary: typeof getDictionaryFunction = (...args) => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('getDictionary') !== 'function') {\n throw new Error(\n 'Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.'\n );\n }\n\n return appNamespace.get('getDictionary')(...args);\n } catch (error) {\n if (process.env.NODE_ENV === 'development') {\n console.error((error as Error).message);\n }\n return getDictionaryFunction(...args);\n }\n};\n"],"mappings":";;;;;;;AAaA,MAAM,wDAAkC;AACxC,MAAM,EAAE,yBAAyB;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AE;AACxB,eAAa,IAAI,eAAe,YAAY;AAC5C,eAAa,IAAI,iBAAiB,cAAc;AAEhD,QAAM;GACN;;;;;;;;;;;;;;;;;;;;;;;;AAyBJ,MAAa,KACX,SACA,WACY;AACZ,KAAI;AACF,MAAI,OAAO,iBAAiB,YAC1B,OAAM,IAAI,MACR,qGACD;AAGH,MAAI,OAAO,aAAa,IAAI,IAAI,KAAK,WACnC,OAAM,IAAI,MACR,8HACD;AAGH,SAAO,aAAa,IAAI,IAAI,CAAC,SAAS,OAAO;UACtC,OAAO;AACd,MAAI,QAAQ,IAAI,aAAa,cAC3B,SAAQ,MAAO,MAAgB,QAAQ;AAGzC,4CACE,SACA,UAAU,qBAAqB,cAChC;;;AAIL,MAAa,eAA2C,GAAG,SAAS;AAClE,KAAI;AACF,MAAI,OAAO,iBAAiB,YAC1B,OAAM,IAAI,MACR,qGACD;AAGH,MAAI,OAAO,aAAa,IAAI,cAAc,KAAK,WAC7C,OAAM,IAAI,MACR,8HACD;AAGH,SAAO,aAAa,IAAI,cAAc,CAAC,GAAG,KAAK;UACxC,OAAO;AACd,MAAI,QAAQ,IAAI,aAAa,cAC3B,SAAQ,MAAO,MAAgB,QAAQ;AAEzC,yCAA2B,GAAG,KAAK;;;AAIvC,MAAa,iBAA+C,GAAG,SAAS;AACtE,KAAI;AACF,MAAI,OAAO,iBAAiB,YAC1B,OAAM,IAAI,MACR,qGACD;AAGH,MAAI,OAAO,aAAa,IAAI,gBAAgB,KAAK,WAC/C,OAAM,IAAI,MACR,8HACD;AAGH,SAAO,aAAa,IAAI,gBAAgB,CAAC,GAAG,KAAK;UAC1C,OAAO;AACd,MAAI,QAAQ,IAAI,aAAa,cAC3B,SAAQ,MAAO,MAAgB,QAAQ;AAEzC,2CAA6B,GAAG,KAAK"}
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../../src/index.ts"],"sourcesContent":["import { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { getConfiguration } from '@intlayer/config/node';\nimport {\n getDictionary as getDictionaryFunction,\n getIntlayer as getIntlayerFunction,\n getTranslation,\n} from '@intlayer/core/interpreter';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorage } from '@intlayer/core/utils';\nimport type { Locale, StrictModeLocaleMap } from '@intlayer/types';\nimport { createNamespace } from 'cls-hooked';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\n\nconst configuration = getConfiguration();\nconst { internationalization } = configuration;\n\n/**\n * Retrieves the locale from storage (cookies, localStorage, sessionStorage).\n */\nconst getStorageLocale = (req: Request): Locale | undefined =>\n getLocaleFromStorage({\n getCookie: (name: string) => req.cookies?.[name],\n getHeader: (name: string) => req.headers?.[name] as string | undefined,\n });\n\nconst appNamespace = createNamespace('app');\n\nprepareIntlayer(configuration);\n\nexport const translateFunction =\n (_req: Request, res: Response, _next?: NextFunction) =>\n <T extends string>(\n content: StrictModeLocaleMap<T> | string,\n locale?: Locale\n ): T => {\n const { locale: currentLocale, defaultLocale } = res.locals as {\n locale: Locale;\n defaultLocale: Locale;\n };\n\n const targetLocale = locale ?? currentLocale;\n\n if (typeof content === 'undefined') {\n return '' as unknown as T;\n }\n\n if (typeof content === 'string') {\n return content as unknown as T;\n }\n\n if (\n typeof content?.[\n targetLocale as unknown as keyof StrictModeLocaleMap<T>\n ] === 'undefined'\n ) {\n if (\n typeof content?.[\n defaultLocale as unknown as keyof StrictModeLocaleMap<T>\n ] === 'undefined'\n ) {\n return content as unknown as T;\n } else {\n return getTranslation(content, defaultLocale);\n }\n }\n\n return getTranslation(content, targetLocale);\n };\n\n/**\n * Express middleware that detects the user's locale and populates `res.locals` with Intlayer data.\n *\n * It performs:\n * 1. Locale detection from cookies, headers, or default settings.\n * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into `res.locals`.\n * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.\n *\n * @returns An Express middleware function.\n *\n * @example\n * ```ts\n * import express from 'express';\n * import { intlayer } from 'express-intlayer';\n *\n * const app = express();\n * app.use(intlayer());\n * ```\n */\nexport const intlayer = (): RequestHandler => async (req, res, next) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(req);\n // Interpret browser locale\n\n const negotiatorHeaders: Record<string, string> = {};\n\n // // Check if req.headers exists and is an object\n if (req && typeof req.headers === 'object') {\n // Copy all headers from the request to negotiatorHeaders\n for (const key in req.headers) {\n if (typeof req.headers[key] === 'string') {\n negotiatorHeaders[key] = req.headers[key];\n }\n }\n }\n\n const localeDetected = localeDetector(\n negotiatorHeaders,\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n res.locals.locale_storage = localeFromStorage;\n res.locals.locale_detected = localeDetected;\n res.locals.locale = localeFromStorage ?? localeDetected;\n res.locals.defaultLocale = internationalization.defaultLocale;\n\n const t = translateFunction(req, res, next);\n\n const getIntlayer: typeof getIntlayerFunction = (\n key,\n localeArg = localeDetected as Parameters<typeof getIntlayerFunction>[1],\n ...props\n ) => getIntlayerFunction(key, localeArg, ...props);\n\n const getDictionary: typeof getDictionaryFunction = (\n key,\n localeArg = localeDetected as Parameters<typeof getDictionaryFunction>[1],\n ...props\n ) => getDictionaryFunction(key, localeArg, ...props);\n\n res.locals.t = t;\n res.locals.getIntlayer = getIntlayer;\n res.locals.getDictionary = getDictionary;\n\n appNamespace.run(() => {\n appNamespace.set('t', t);\n appNamespace.set('getIntlayer', getIntlayer);\n appNamespace.set('getDictionary', getDictionary);\n\n next();\n });\n};\n\n/**\n * Translation function to retrieve content for the current locale.\n *\n * This function works within the request lifecycle managed by the `intlayer` middleware.\n *\n * @param content - A map of locales to content.\n * @param locale - Optional locale override.\n * @returns The translated content.\n *\n * @example\n * ```ts\n * import { t } from 'express-intlayer';\n *\n * app.get('/', (req, res) => {\n * const greeting = t({\n * en: 'Hello',\n * fr: 'Bonjour',\n * });\n * res.send(greeting);\n * });\n * ```\n */\nexport const t = <Content = string>(\n content: StrictModeLocaleMap<Content>,\n locale?: Locale\n): Content => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('t') !== 'function') {\n throw new Error(\n 'Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.'\n );\n }\n\n return appNamespace.get('t')(content, locale);\n } catch (error) {\n if (process.env.NODE_ENV === 'development') {\n console.error((error as Error).message);\n }\n\n return getTranslation(\n content,\n locale ?? internationalization.defaultLocale\n );\n }\n};\n\nexport const getIntlayer: typeof getIntlayerFunction = (...args) => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('getIntlayer') !== 'function') {\n throw new Error(\n 'Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.'\n );\n }\n\n return appNamespace.get('getIntlayer')(...args);\n } catch (error) {\n if (process.env.NODE_ENV === 'development') {\n console.error((error as Error).message);\n }\n return getIntlayerFunction(...args);\n }\n};\n\nexport const getDictionary: typeof getDictionaryFunction = (...args) => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('getDictionary') !== 'function') {\n throw new Error(\n 'Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.'\n );\n }\n\n return appNamespace.get('getDictionary')(...args);\n } catch (error) {\n if (process.env.NODE_ENV === 'development') {\n console.error((error as Error).message);\n }\n return getDictionaryFunction(...args);\n }\n};\n"],"mappings":"2RAaA,MAAM,GAAA,EAAA,EAAA,mBAAkC,CAClC,CAAE,wBAAyB,EAK3B,EAAoB,IAAA,EAAA,EAAA,sBACH,CACnB,UAAY,GAAiB,EAAI,UAAU,GAC3C,UAAY,GAAiB,EAAI,UAAU,GAC5C,CAAC,CAEE,GAAA,EAA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AAa,IAAI,IAAI,EAAK,WACnC,MAAU,MACR,4HACD,CAGH,OAAO,EAAa,IAAI,IAAI,CAAC,EAAS,EAAO,OACtC,EAAO,CAKd,OAJI,QAAQ,IAAI,WAAa,eAC3B,QAAQ,MAAO,EAAgB,QAAQ,EAGzC,EAAA,EAAA,gBACE,EACA,GAAU,EAAqB,cAChC,GAIQ,GAA2C,GAAG,IAAS,CAClE,GAAI,CACF,GAAW,IAAiB,OAC1B,MAAU,MACR,qGACD,CAGH,GAAI,OAAO,EAAa,IAAI,cAAc,EAAK,WAC7C,MAAU,MACR,4HACD,CAGH,OAAO,EAAa,IAAI,cAAc,CAAC,GAAG,EAAK,OACxC,EAAO,CAId,OAHI,QAAQ,IAAI,WAAa,eAC3B,QAAQ,MAAO,EAAgB,QAAQ,EAEzC,EAAA,EAAA,aAA2B,GAAG,EAAK,GAI1B,GAA+C,GAAG,IAAS,CACtE,GAAI,CACF,GAAW,IAAiB,OAC1B,MAAU,MACR,qGACD,CAGH,GAAI,OAAO,EAAa,IAAI,gBAAgB,EAAK,WAC/C,MAAU,MACR,4HACD,CAGH,OAAO,EAAa,IAAI,gBAAgB,CAAC,GAAG,EAAK,OAC1C,EAAO,CAId,OAHI,QAAQ,IAAI,WAAa,eAC3B,QAAQ,MAAO,EAAgB,QAAQ,EAEzC,EAAA,EAAA,eAA6B,GAAG,EAAK"}
@@ -1,125 +1,2 @@
1
- import { prepareIntlayer } from "@intlayer/chokidar";
2
- import { getConfiguration } from "@intlayer/config";
3
- import { getDictionary as getDictionary$1, getIntlayer as getIntlayer$1, getLocaleFromStorage, getTranslation, localeDetector } from "@intlayer/core";
4
- import { createNamespace } from "cls-hooked";
5
-
6
- //#region src/index.ts
7
- const configuration = getConfiguration();
8
- const { internationalization } = configuration;
9
- /**
10
- * Retrieves the locale from storage (cookies, localStorage, sessionStorage).
11
- */
12
- const getStorageLocale = (req) => getLocaleFromStorage({
13
- getCookie: (name) => req.cookies?.[name],
14
- getHeader: (name) => req.headers?.[name]
15
- });
16
- const appNamespace = createNamespace("app");
17
- prepareIntlayer(configuration);
18
- const translateFunction = (_req, res, _next) => (content, locale) => {
19
- const { locale: currentLocale, defaultLocale } = res.locals;
20
- const targetLocale = locale ?? currentLocale;
21
- if (typeof content === "undefined") return "";
22
- if (typeof content === "string") return content;
23
- if (typeof content?.[targetLocale] === "undefined") if (typeof content?.[defaultLocale] === "undefined") return content;
24
- else return getTranslation(content, defaultLocale);
25
- return getTranslation(content, targetLocale);
26
- };
27
- /**
28
- * Express middleware that detects the user's locale and populates `res.locals` with Intlayer data.
29
- *
30
- * It performs:
31
- * 1. Locale detection from cookies, headers, or default settings.
32
- * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into `res.locals`.
33
- * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.
34
- *
35
- * @returns An Express middleware function.
36
- *
37
- * @example
38
- * ```ts
39
- * import express from 'express';
40
- * import { intlayer } from 'express-intlayer';
41
- *
42
- * const app = express();
43
- * app.use(intlayer());
44
- * ```
45
- */
46
- const intlayer = () => async (req, res, next) => {
47
- const localeFromStorage = getStorageLocale(req);
48
- const negotiatorHeaders = {};
49
- if (req && typeof req.headers === "object") {
50
- for (const key in req.headers) if (typeof req.headers[key] === "string") negotiatorHeaders[key] = req.headers[key];
51
- }
52
- const localeDetected = localeDetector(negotiatorHeaders, internationalization.locales, internationalization.defaultLocale);
53
- res.locals.locale_storage = localeFromStorage;
54
- res.locals.locale_detected = localeDetected;
55
- res.locals.locale = localeFromStorage ?? localeDetected;
56
- res.locals.defaultLocale = internationalization.defaultLocale;
57
- const t = translateFunction(req, res, next);
58
- const getIntlayer = (key, localeArg = localeDetected, ...props) => getIntlayer$1(key, localeArg, ...props);
59
- const getDictionary = (key, localeArg = localeDetected, ...props) => getDictionary$1(key, localeArg, ...props);
60
- res.locals.t = t;
61
- res.locals.getIntlayer = getIntlayer;
62
- res.locals.getDictionary = getDictionary;
63
- appNamespace.run(() => {
64
- appNamespace.set("t", t);
65
- appNamespace.set("getIntlayer", getIntlayer);
66
- appNamespace.set("getDictionary", getDictionary);
67
- next();
68
- });
69
- };
70
- /**
71
- * Translation function to retrieve content for the current locale.
72
- *
73
- * This function works within the request lifecycle managed by the `intlayer` middleware.
74
- *
75
- * @param content - A map of locales to content.
76
- * @param locale - Optional locale override.
77
- * @returns The translated content.
78
- *
79
- * @example
80
- * ```ts
81
- * import { t } from 'express-intlayer';
82
- *
83
- * app.get('/', (req, res) => {
84
- * const greeting = t({
85
- * en: 'Hello',
86
- * fr: 'Bonjour',
87
- * });
88
- * res.send(greeting);
89
- * });
90
- * ```
91
- */
92
- const t = (content, locale) => {
93
- try {
94
- if (typeof appNamespace === "undefined") throw new Error("Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.");
95
- if (typeof appNamespace.get("t") !== "function") throw new Error("Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.");
96
- return appNamespace.get("t")(content, locale);
97
- } catch (error) {
98
- console.error(error.message);
99
- return getTranslation(content, locale ?? internationalization.defaultLocale);
100
- }
101
- };
102
- const getIntlayer = (...args) => {
103
- try {
104
- if (typeof appNamespace === "undefined") throw new Error("Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.");
105
- if (typeof appNamespace.get("getIntlayer") !== "function") throw new Error("Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.");
106
- return appNamespace.get("getIntlayer")(...args);
107
- } catch (error) {
108
- console.error(error.message);
109
- return getIntlayer$1(...args);
110
- }
111
- };
112
- const getDictionary = (...args) => {
113
- try {
114
- if (typeof appNamespace === "undefined") throw new Error("Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.");
115
- if (typeof appNamespace.get("getDictionary") !== "function") throw new Error("Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.");
116
- return appNamespace.get("getDictionary")(...args);
117
- } catch (error) {
118
- console.error(error.message);
119
- return getDictionary$1(...args);
120
- }
121
- };
122
-
123
- //#endregion
124
- export { getDictionary, getIntlayer, intlayer, t, translateFunction };
1
+ import{prepareIntlayer as e}from"@intlayer/chokidar/build";import{getConfiguration as t}from"@intlayer/config/node";import{getDictionary as n,getIntlayer as r,getTranslation as i}from"@intlayer/core/interpreter";import{localeDetector as a}from"@intlayer/core/localization";import{getLocaleFromStorage as o}from"@intlayer/core/utils";import{createNamespace as s}from"cls-hooked";const c=t(),{internationalization:l}=c,u=e=>o({getCookie:t=>e.cookies?.[t],getHeader:t=>e.headers?.[t]}),d=s(`app`);e(c);const f=(e,t,n)=>(e,n)=>{let{locale:r,defaultLocale:a}=t.locals,o=n??r;return e===void 0?``:typeof e==`string`?e:e?.[o]===void 0?e?.[a]===void 0?e:i(e,a):i(e,o)},p=()=>async(e,t,i)=>{let o=u(e),s={};if(e&&typeof e.headers==`object`)for(let t in e.headers)typeof e.headers[t]==`string`&&(s[t]=e.headers[t]);let c=a(s,l.locales,l.defaultLocale);t.locals.locale_storage=o,t.locals.locale_detected=c,t.locals.locale=o??c,t.locals.defaultLocale=l.defaultLocale;let p=f(e,t,i),m=(e,t=c,...n)=>r(e,t,...n),h=(e,t=c,...r)=>n(e,t,...r);t.locals.t=p,t.locals.getIntlayer=m,t.locals.getDictionary=h,d.run(()=>{d.set(`t`,p),d.set(`getIntlayer`,m),d.set(`getDictionary`,h),i()})},m=(e,t)=>{try{if(d===void 0)throw Error("Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.");if(typeof d.get(`t`)!=`function`)throw Error(`Using the import { t } from "express-intlayer" is not supported in your environment. Use the res.locals.t syntax instead.`);return d.get(`t`)(e,t)}catch{return i(e,t??l.defaultLocale)}},h=(...e)=>{try{if(d===void 0)throw Error("Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.");if(typeof d.get(`getIntlayer`)!=`function`)throw Error(`Using the import { t } from "express-intlayer" is not supported in your environment. Use the res.locals.t syntax instead.`);return d.get(`getIntlayer`)(...e)}catch{return r(...e)}},g=(...e)=>{try{if(d===void 0)throw Error("Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.");if(typeof d.get(`getDictionary`)!=`function`)throw Error(`Using the import { t } from "express-intlayer" is not supported in your environment. Use the res.locals.t syntax instead.`);return d.get(`getDictionary`)(...e)}catch{return n(...e)}};export{g as getDictionary,h as getIntlayer,p as intlayer,m as t,f as translateFunction};
125
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["getIntlayerFunction","getDictionaryFunction"],"sources":["../../src/index.ts"],"sourcesContent":["import { prepareIntlayer } from '@intlayer/chokidar';\nimport { getConfiguration } from '@intlayer/config';\nimport {\n getDictionary as getDictionaryFunction,\n getIntlayer as getIntlayerFunction,\n getLocaleFromStorage,\n getTranslation,\n localeDetector,\n} from '@intlayer/core';\nimport type { Locale, StrictModeLocaleMap } from '@intlayer/types';\nimport { createNamespace } from 'cls-hooked';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\n\nconst configuration = getConfiguration();\nconst { internationalization } = configuration;\n\n/**\n * Retrieves the locale from storage (cookies, localStorage, sessionStorage).\n */\nconst getStorageLocale = (req: Request): Locale | undefined =>\n getLocaleFromStorage({\n getCookie: (name: string) => req.cookies?.[name],\n getHeader: (name: string) => req.headers?.[name] as string | undefined,\n });\n\nconst appNamespace = createNamespace('app');\n\nprepareIntlayer(configuration);\n\nexport const translateFunction =\n (_req: Request, res: Response, _next?: NextFunction) =>\n <T extends string>(\n content: StrictModeLocaleMap<T> | string,\n locale?: Locale\n ): T => {\n const { locale: currentLocale, defaultLocale } = res.locals as {\n locale: Locale;\n defaultLocale: Locale;\n };\n\n const targetLocale = locale ?? currentLocale;\n\n if (typeof content === 'undefined') {\n return '' as unknown as T;\n }\n\n if (typeof content === 'string') {\n return content as unknown as T;\n }\n\n if (\n typeof content?.[\n targetLocale as unknown as keyof StrictModeLocaleMap<T>\n ] === 'undefined'\n ) {\n if (\n typeof content?.[\n defaultLocale as unknown as keyof StrictModeLocaleMap<T>\n ] === 'undefined'\n ) {\n return content as unknown as T;\n } else {\n return getTranslation(content, defaultLocale);\n }\n }\n\n return getTranslation(content, targetLocale);\n };\n\n/**\n * Express middleware that detects the user's locale and populates `res.locals` with Intlayer data.\n *\n * It performs:\n * 1. Locale detection from cookies, headers, or default settings.\n * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into `res.locals`.\n * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.\n *\n * @returns An Express middleware function.\n *\n * @example\n * ```ts\n * import express from 'express';\n * import { intlayer } from 'express-intlayer';\n *\n * const app = express();\n * app.use(intlayer());\n * ```\n */\nexport const intlayer = (): RequestHandler => async (req, res, next) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(req);\n // Interpret browser locale\n\n const negotiatorHeaders: Record<string, string> = {};\n\n // // Check if req.headers exists and is an object\n if (req && typeof req.headers === 'object') {\n // Copy all headers from the request to negotiatorHeaders\n for (const key in req.headers) {\n if (typeof req.headers[key] === 'string') {\n negotiatorHeaders[key] = req.headers[key];\n }\n }\n }\n\n const localeDetected = localeDetector(\n negotiatorHeaders,\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n res.locals.locale_storage = localeFromStorage;\n res.locals.locale_detected = localeDetected;\n res.locals.locale = localeFromStorage ?? localeDetected;\n res.locals.defaultLocale = internationalization.defaultLocale;\n\n const t = translateFunction(req, res, next);\n\n const getIntlayer: typeof getIntlayerFunction = (\n key,\n localeArg = localeDetected as Parameters<typeof getIntlayerFunction>[1],\n ...props\n ) => getIntlayerFunction(key, localeArg, ...props);\n\n const getDictionary: typeof getDictionaryFunction = (\n key,\n localeArg = localeDetected as Parameters<typeof getDictionaryFunction>[1],\n ...props\n ) => getDictionaryFunction(key, localeArg, ...props);\n\n res.locals.t = t;\n res.locals.getIntlayer = getIntlayer;\n res.locals.getDictionary = getDictionary;\n\n appNamespace.run(() => {\n appNamespace.set('t', t);\n appNamespace.set('getIntlayer', getIntlayer);\n appNamespace.set('getDictionary', getDictionary);\n\n next();\n });\n};\n\n/**\n * Translation function to retrieve content for the current locale.\n *\n * This function works within the request lifecycle managed by the `intlayer` middleware.\n *\n * @param content - A map of locales to content.\n * @param locale - Optional locale override.\n * @returns The translated content.\n *\n * @example\n * ```ts\n * import { t } from 'express-intlayer';\n *\n * app.get('/', (req, res) => {\n * const greeting = t({\n * en: 'Hello',\n * fr: 'Bonjour',\n * });\n * res.send(greeting);\n * });\n * ```\n */\nexport const t = <Content = string>(\n content: StrictModeLocaleMap<Content>,\n locale?: Locale\n): Content => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('t') !== 'function') {\n throw new Error(\n 'Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.'\n );\n }\n\n return appNamespace.get('t')(content, locale);\n } catch (error) {\n if (process.env.NODE_ENV === 'development') {\n console.error((error as Error).message);\n }\n\n return getTranslation(\n content,\n locale ?? internationalization.defaultLocale\n );\n }\n};\n\nexport const getIntlayer: typeof getIntlayerFunction = (...args) => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('getIntlayer') !== 'function') {\n throw new Error(\n 'Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.'\n );\n }\n\n return appNamespace.get('getIntlayer')(...args);\n } catch (error) {\n if (process.env.NODE_ENV === 'development') {\n console.error((error as Error).message);\n }\n return getIntlayerFunction(...args);\n }\n};\n\nexport const getDictionary: typeof getDictionaryFunction = (...args) => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('getDictionary') !== 'function') {\n throw new Error(\n 'Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.'\n );\n }\n\n return appNamespace.get('getDictionary')(...args);\n } catch (error) {\n if (process.env.NODE_ENV === 'development') {\n console.error((error as Error).message);\n }\n return getDictionaryFunction(...args);\n }\n};\n"],"mappings":";;;;;;AAaA,MAAM,gBAAgB,kBAAkB;AACxC,MAAM,EAAE,yBAAyB;;;;AAKjC,MAAM,oBAAoB,QACxB,qBAAqB;CACnB,YAAY,SAAiB,IAAI,UAAU;CAC3C,YAAY,SAAiB,IAAI,UAAU;CAC5C,CAAC;AAEJ,MAAM,eAAe,gBAAgB,MAAM;AAE3C,gBAAgB,cAAc;AAE9B,MAAa,qBACV,MAAe,KAAe,WAE7B,SACA,WACM;CACN,MAAM,EAAE,QAAQ,eAAe,kBAAkB,IAAI;CAKrD,MAAM,eAAe,UAAU;AAE/B,KAAI,OAAO,YAAY,YACrB,QAAO;AAGT,KAAI,OAAO,YAAY,SACrB,QAAO;AAGT,KACE,OAAO,UACL,kBACI,YAEN,KACE,OAAO,UACL,mBACI,YAEN,QAAO;KAEP,QAAO,eAAe,SAAS,cAAc;AAIjD,QAAO,eAAe,SAAS,aAAa;;;;;;;;;;;;;;;;;;;;;AAsBhD,MAAa,iBAAiC,OAAO,KAAK,KAAK,SAAS;CAEtE,MAAM,oBAAoB,iBAAiB,IAAI;CAG/C,MAAM,oBAA4C,EAAE;AAGpD,KAAI,OAAO,OAAO,IAAI,YAAY,UAEhC;OAAK,MAAM,OAAO,IAAI,QACpB,KAAI,OAAO,IAAI,QAAQ,SAAS,SAC9B,mBAAkB,OAAO,IAAI,QAAQ;;CAK3C,MAAM,iBAAiB,eACrB,mBACA,qBAAqB,SACrB,qBAAqB,cACtB;AAED,KAAI,OAAO,iBAAiB;AAC5B,KAAI,OAAO,kBAAkB;AAC7B,KAAI,OAAO,SAAS,qBAAqB;AACzC,KAAI,OAAO,gBAAgB,qBAAqB;CAEhD,MAAM,IAAI,kBA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AgB,CAAC,GAAG,KAAK;UAC1C,OAAO;AAEZ,UAAQ,MAAO,MAAgB,QAAQ;AAEzC,SAAOC,gBAAsB,GAAG,KAAK"}
1
+ {"version":3,"file":"index.mjs","names":["getIntlayerFunction","getDictionaryFunction"],"sources":["../../src/index.ts"],"sourcesContent":["import { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { getConfiguration } from '@intlayer/config/node';\nimport {\n getDictionary as getDictionaryFunction,\n getIntlayer as getIntlayerFunction,\n getTranslation,\n} from '@intlayer/core/interpreter';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorage } from '@intlayer/core/utils';\nimport type { Locale, StrictModeLocaleMap } from '@intlayer/types';\nimport { createNamespace } from 'cls-hooked';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\n\nconst configuration = getConfiguration();\nconst { internationalization } = configuration;\n\n/**\n * Retrieves the locale from storage (cookies, localStorage, sessionStorage).\n */\nconst getStorageLocale = (req: Request): Locale | undefined =>\n getLocaleFromStorage({\n getCookie: (name: string) => req.cookies?.[name],\n getHeader: (name: string) => req.headers?.[name] as string | undefined,\n });\n\nconst appNamespace = createNamespace('app');\n\nprepareIntlayer(configuration);\n\nexport const translateFunction =\n (_req: Request, res: Response, _next?: NextFunction) =>\n <T extends string>(\n content: StrictModeLocaleMap<T> | string,\n locale?: Locale\n ): T => {\n const { locale: currentLocale, defaultLocale } = res.locals as {\n locale: Locale;\n defaultLocale: Locale;\n };\n\n const targetLocale = locale ?? currentLocale;\n\n if (typeof content === 'undefined') {\n return '' as unknown as T;\n }\n\n if (typeof content === 'string') {\n return content as unknown as T;\n }\n\n if (\n typeof content?.[\n targetLocale as unknown as keyof StrictModeLocaleMap<T>\n ] === 'undefined'\n ) {\n if (\n typeof content?.[\n defaultLocale as unknown as keyof StrictModeLocaleMap<T>\n ] === 'undefined'\n ) {\n return content as unknown as T;\n } else {\n return getTranslation(content, defaultLocale);\n }\n }\n\n return getTranslation(content, targetLocale);\n };\n\n/**\n * Express middleware that detects the user's locale and populates `res.locals` with Intlayer data.\n *\n * It performs:\n * 1. Locale detection from cookies, headers, or default settings.\n * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into `res.locals`.\n * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.\n *\n * @returns An Express middleware function.\n *\n * @example\n * ```ts\n * import express from 'express';\n * import { intlayer } from 'express-intlayer';\n *\n * const app = express();\n * app.use(intlayer());\n * ```\n */\nexport const intlayer = (): RequestHandler => async (req, res, next) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(req);\n // Interpret browser locale\n\n const negotiatorHeaders: Record<string, string> = {};\n\n // // Check if req.headers exists and is an object\n if (req && typeof req.headers === 'object') {\n // Copy all headers from the request to negotiatorHeaders\n for (const key in req.headers) {\n if (typeof req.headers[key] === 'string') {\n negotiatorHeaders[key] = req.headers[key];\n }\n }\n }\n\n const localeDetected = localeDetector(\n negotiatorHeaders,\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n res.locals.locale_storage = localeFromStorage;\n res.locals.locale_detected = localeDetected;\n res.locals.locale = localeFromStorage ?? localeDetected;\n res.locals.defaultLocale = internationalization.defaultLocale;\n\n const t = translateFunction(req, res, next);\n\n const getIntlayer: typeof getIntlayerFunction = (\n key,\n localeArg = localeDetected as Parameters<typeof getIntlayerFunction>[1],\n ...props\n ) => getIntlayerFunction(key, localeArg, ...props);\n\n const getDictionary: typeof getDictionaryFunction = (\n key,\n localeArg = localeDetected as Parameters<typeof getDictionaryFunction>[1],\n ...props\n ) => getDictionaryFunction(key, localeArg, ...props);\n\n res.locals.t = t;\n res.locals.getIntlayer = getIntlayer;\n res.locals.getDictionary = getDictionary;\n\n appNamespace.run(() => {\n appNamespace.set('t', t);\n appNamespace.set('getIntlayer', getIntlayer);\n appNamespace.set('getDictionary', getDictionary);\n\n next();\n });\n};\n\n/**\n * Translation function to retrieve content for the current locale.\n *\n * This function works within the request lifecycle managed by the `intlayer` middleware.\n *\n * @param content - A map of locales to content.\n * @param locale - Optional locale override.\n * @returns The translated content.\n *\n * @example\n * ```ts\n * import { t } from 'express-intlayer';\n *\n * app.get('/', (req, res) => {\n * const greeting = t({\n * en: 'Hello',\n * fr: 'Bonjour',\n * });\n * res.send(greeting);\n * });\n * ```\n */\nexport const t = <Content = string>(\n content: StrictModeLocaleMap<Content>,\n locale?: Locale\n): Content => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('t') !== 'function') {\n throw new Error(\n 'Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.'\n );\n }\n\n return appNamespace.get('t')(content, locale);\n } catch (error) {\n if (process.env.NODE_ENV === 'development') {\n console.error((error as Error).message);\n }\n\n return getTranslation(\n content,\n locale ?? internationalization.defaultLocale\n );\n }\n};\n\nexport const getIntlayer: typeof getIntlayerFunction = (...args) => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('getIntlayer') !== 'function') {\n throw new Error(\n 'Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.'\n );\n }\n\n return appNamespace.get('getIntlayer')(...args);\n } catch (error) {\n if (process.env.NODE_ENV === 'development') {\n console.error((error as Error).message);\n }\n return getIntlayerFunction(...args);\n }\n};\n\nexport const getDictionary: typeof getDictionaryFunction = (...args) => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('getDictionary') !== 'function') {\n throw new Error(\n 'Using the import { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax instead.'\n );\n }\n\n return appNamespace.get('getDictionary')(...args);\n } catch (error) {\n if (process.env.NODE_ENV === 'development') {\n console.error((error as Error).message);\n }\n return getDictionaryFunction(...args);\n }\n};\n"],"mappings":"0XAaA,MAAM,EAAgB,GAAkB,CAClC,CAAE,wBAAyB,EAK3B,EAAoB,GACxB,EAAqB,CACnB,UAAY,GAAiB,EAAI,UAAU,GAC3C,UAAY,GAAiB,EAAI,UAAU,GAC5C,CAAC,CAEE,EAAe,EAAgB,MAAM,CAE3C,EAAgB,EAAc,CAE9B,MAAa,GACV,EAAe,EAAe,KAE7B,EACA,IACM,CACN,GAAM,CAAE,OAAQ,EAAe,iBAAkB,EAAI,OAK/C,EAAe,GAAU,EA0B/B,OAxBW,IAAY,OACd,GAGL,OAAO,GAAY,SACd,EAIA,IACL,KACI,OAGG,IACL,KACI,OAEC,EAEA,EAAe,EAAS,EAAc,CAI1C,EAAe,EAAS,EAAa,EAsBnC,MAAiC,MAAO,EAAK,EAAK,IAAS,CAEtE,IAAM,EAAoB,EAAiB,EAAI,CAGzC,EAA4C,EAAE,CAGpD,GAAI,GAAO,OAAO,EAAI,SAAY,aAE3B,IAAM,KAAO,EAAI,QAChB,OAAO,EAAI,QAAQ,IAAS,WAC9B,EAAkB,GAAO,EAAI,QAAQ,IAK3C,IAAM,EAAiB,EACrB,EACA,EAAqB,QACrB,EAAqB,cACtB,CAED,EAAI,OAAO,eAAiB,EAC5B,EAAI,OAAO,gBAAkB,EAC7B,EAAI,OAAO,OAAS,GAAqB,EACzC,EAAI,OAAO,cAAgB,EAAqB,cAEhD,IAAM,EAAI,EAAkB,EAAK,EAAK,EAAK,CAErC,GACJ,EACA,EAAY,EACZ,GAAG,IACAA,EAAoB,EAAK,EAAW,GAAG,EAAM,CAE5C,GACJ,EACA,EAAY,EACZ,GAAG,IACAC,EAAsB,EAAK,EAAW,GAAG,EAAM,CAEpD,EAAI,OAAO,EAAI,EACf,EAAI,OAAO,YAAc,EACzB,EAAI,OAAO,cAAgB,EAE3B,EAAa,QAAU,CACrB,EAAa,IAAI,IAAK,EAAE,CACxB,EAAa,IAAI,cAAe,EAAY,CAC5C,EAAa,IAAI,gBAAiB,EAAc,CAEhD,GAAM,EACN,EAyBS,GACX,EACA,IACY,CACZ,GAAI,CACF,GAAW,IAAiB,OAC1B,MAAU,MACR,qGACD,CAGH,GAAI,OAAO,EAAa,IAAI,IAAI,EAAK,WACnC,MAAU,MACR,4HACD,CAGH,OAAO,EAAa,IAAI,IAAI,CAAC,EAAS,EAAO,MAC/B,CAKd,OAAO,EACL,EACA,GAAU,EAAqB,cAChC,GAIQ,GAA2C,GAAG,IAAS,CAClE,GAAI,CACF,GAAW,IAAiB,OAC1B,MAAU,MACR,qGACD,CAGH,GAAI,OAAO,EAAa,IAAI,cAAc,EAAK,WAC7C,MAAU,MACR,4HACD,CAGH,OAAO,EAAa,IAAI,cAAc,CAAC,GAAG,EAAK,MACjC,CAId,OAAOD,EAAoB,GAAG,EAAK,GAI1B,GAA+C,GAAG,IAAS,CACtE,GAAI,CACF,GAAW,IAAiB,OAC1B,MAAU,MACR,qGACD,CAGH,GAAI,OAAO,EAAa,IAAI,gBAAgB,EAAK,WAC/C,MAAU,MACR,4HACD,CAGH,OAAO,EAAa,IAAI,gBAAgB,CAAC,GAAG,EAAK,MACnC,CAId,OAAOC,EAAsB,GAAG,EAAK"}
@@ -1,4 +1,4 @@
1
- import { getDictionary as getDictionary$1, getIntlayer as getIntlayer$1 } from "@intlayer/core";
1
+ import { getDictionary as getDictionary$1, getIntlayer as getIntlayer$1 } from "@intlayer/core/interpreter";
2
2
  import { Locale, StrictModeLocaleMap } from "@intlayer/types";
3
3
  import { NextFunction, Request, RequestHandler, Response } from "express";
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-intlayer",
3
- "version": "8.1.2",
3
+ "version": "8.1.3",
4
4
  "private": false,
5
5
  "description": "Manage internationalization i18n in a simple way for express application.",
6
6
  "keywords": [
@@ -76,12 +76,12 @@
76
76
  "typecheck": "tsc --noEmit --project tsconfig.types.json"
77
77
  },
78
78
  "dependencies": {
79
- "@intlayer/chokidar": "8.1.2",
80
- "@intlayer/config": "8.1.2",
81
- "@intlayer/core": "8.1.2",
82
- "@intlayer/types": "8.1.2",
79
+ "@intlayer/chokidar": "8.1.3",
80
+ "@intlayer/config": "8.1.3",
81
+ "@intlayer/core": "8.1.3",
82
+ "@intlayer/types": "8.1.3",
83
83
  "cls-hooked": "4.2.2",
84
- "intlayer": "8.1.2"
84
+ "intlayer": "8.1.3"
85
85
  },
86
86
  "devDependencies": {
87
87
  "@types/cls-hooked": "4.3.9",