express-intlayer 9.5.12 → 9.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,44 +1,55 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ let node_async_hooks = require("node:async_hooks");
3
+ let _intlayer_config_built = require("@intlayer/config/built");
2
4
  let _intlayer_config_node = require("@intlayer/config/node");
3
5
  let _intlayer_core_interpreter = require("@intlayer/core/interpreter");
4
6
  let _intlayer_core_localization = require("@intlayer/core/localization");
5
7
  let _intlayer_core_utils = require("@intlayer/core/utils");
6
8
  let _intlayer_engine_build = require("@intlayer/engine/build");
7
- let cls_hooked = require("cls-hooked");
8
9
 
9
10
  //#region src/index.ts
10
11
  let debug = () => {};
11
- const configuration = (0, _intlayer_config_node.getConfiguration)();
12
- const { internationalization } = configuration;
13
12
  if (process.env.NODE_ENV === "development") debug = (msg) => console.debug(msg);
14
13
  /**
15
- * Retrieves the locale from storage (cookies, localStorage, sessionStorage).
14
+ * Reads a single-valued request header.
16
15
  */
17
- const getStorageLocale = (req) => (0, _intlayer_core_utils.getLocaleFromStorageServer)({
18
- getCookie: (name) => req.cookies?.[name],
19
- getHeader: (name) => req.headers?.[name]
20
- });
21
- const appNamespace = (0, cls_hooked.createNamespace)("app");
22
- (0, _intlayer_core_interpreter.registerAmbientLocaleResolver)(() => appNamespace.get("locale"));
23
- (0, _intlayer_engine_build.prepareIntlayerServer)(configuration, { label: "express-intlayer" });
24
- const translateFunction = (_req, res, _next) => (content, locale) => {
25
- const { locale: currentLocale, defaultLocale } = res.locals;
26
- const targetLocale = locale ?? currentLocale;
27
- if (typeof content === "undefined") return "";
28
- if (typeof content === "string") return content;
29
- if (typeof content?.[targetLocale] === "undefined") {
30
- if (typeof content?.[defaultLocale] === "undefined") return content;
31
- else return (0, _intlayer_core_interpreter.getTranslation)(content, defaultLocale);
32
- }
33
- return (0, _intlayer_core_interpreter.getTranslation)(content, targetLocale);
16
+ const getHeader = (req, name) => {
17
+ const value = req.headers[name];
18
+ return Array.isArray(value) ? value.join(",") : value;
34
19
  };
35
20
  /**
21
+ * Retrieves the locale from storage (cookies, headers).
22
+ *
23
+ * Parsed cookies need `cookie-parser`: the raw header is read otherwise.
24
+ */
25
+ const getStorageLocale = (req) => {
26
+ const parsedCookies = req.cookies;
27
+ return (0, _intlayer_core_utils.getLocaleFromStorageServer)({
28
+ getCookie: (name) => parsedCookies ? parsedCookies[name] : (0, _intlayer_core_utils.getCookie)(name, req.headers.cookie ?? ""),
29
+ getHeader: (name) => getHeader(req, name)
30
+ });
31
+ };
32
+ /**
33
+ * Request-scoped Intlayer context.
34
+ *
35
+ * `AsyncLocalStorage` rather than `cls-hooked`: the latter relies on
36
+ * `async_hooks.createHook`, which Bun does not implement, and is several times
37
+ * slower on Node.
38
+ */
39
+ const intlayerStorage = new node_async_hooks.AsyncLocalStorage();
40
+ (0, _intlayer_core_interpreter.registerAmbientLocaleResolver)(() => intlayerStorage.getStore()?.locale);
41
+ (0, _intlayer_engine_build.prepareIntlayerServer)((0, _intlayer_config_node.getConfiguration)(), { label: "express-intlayer" });
42
+ /**
43
+ * Builds the translation function bound to the locale stored in `res.locals`.
44
+ */
45
+ const translateFunction = (_req, res, _next) => (content, locale) => typeof content === "string" ? content : (0, _intlayer_core_interpreter.getTranslation)(content, locale ?? res.locals.locale, _intlayer_config_built.internationalization.defaultLocale);
46
+ /**
36
47
  * Express middleware that detects the user's locale and populates `res.locals` with Intlayer data.
37
48
  *
38
49
  * It performs:
39
50
  * 1. Locale detection from cookies, headers, or default settings.
40
51
  * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into `res.locals`.
41
- * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.
52
+ * 3. Sets up an `AsyncLocalStorage` context for accessing these functions anywhere in the request lifecycle.
42
53
  *
43
54
  * @returns An Express middleware function.
44
55
  *
@@ -51,31 +62,26 @@ const translateFunction = (_req, res, _next) => (content, locale) => {
51
62
  * app.use(intlayer());
52
63
  * ```
53
64
  */
54
- const intlayer = () => async (req, res, next) => {
65
+ const intlayer = () => (req, res, next) => {
55
66
  const localeFromStorage = getStorageLocale(req);
56
- const negotiatorHeaders = {};
57
- if (req && typeof req.headers === "object") {
58
- for (const key in req.headers) if (typeof req.headers[key] === "string") negotiatorHeaders[key] = req.headers[key];
59
- }
60
- const localeDetected = (0, _intlayer_core_localization.localeDetector)(negotiatorHeaders, internationalization.locales, internationalization.defaultLocale);
67
+ const localeDetected = (0, _intlayer_core_localization.localeDetector)({ "accept-language": getHeader(req, "accept-language") }, _intlayer_config_built.internationalization.locales, _intlayer_config_built.internationalization.defaultLocale);
61
68
  res.locals.locale_storage = localeFromStorage;
62
69
  res.locals.locale_detected = localeDetected;
63
70
  const locale = localeFromStorage ?? localeDetected;
64
71
  res.locals.locale = locale;
65
- res.locals.defaultLocale = internationalization.defaultLocale;
72
+ res.locals.defaultLocale = _intlayer_config_built.internationalization.defaultLocale;
66
73
  const t = translateFunction(req, res, next);
67
74
  const getIntlayer = (key, localeArg, ...props) => (0, _intlayer_core_interpreter.getIntlayer)(key, localeArg ?? locale, ...props);
68
75
  const getDictionary = (key, localeArg, ...props) => (0, _intlayer_core_interpreter.getDictionary)(key, localeArg ?? locale, ...props);
69
76
  res.locals.t = t;
70
77
  res.locals.getIntlayer = getIntlayer;
71
78
  res.locals.getDictionary = getDictionary;
72
- appNamespace.run(() => {
73
- appNamespace.set("locale", locale);
74
- appNamespace.set("t", t);
75
- appNamespace.set("getIntlayer", getIntlayer);
76
- appNamespace.set("getDictionary", getDictionary);
77
- next();
78
- });
79
+ intlayerStorage.run({
80
+ locale,
81
+ t,
82
+ getIntlayer,
83
+ getDictionary
84
+ }, next);
79
85
  };
80
86
  /**
81
87
  * Translation function to retrieve content for the current locale.
@@ -100,34 +106,28 @@ const intlayer = () => async (req, res, next) => {
100
106
  * ```
101
107
  */
102
108
  const t = (content, locale) => {
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("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.");
106
- return appNamespace.get("t")(content, locale);
107
- } catch (error) {
108
- debug(error.message);
109
- return (0, _intlayer_core_interpreter.getTranslation)(content, locale ?? internationalization.defaultLocale);
109
+ const context = intlayerStorage.getStore();
110
+ if (!context) {
111
+ debug("Using the import { t } from \"express-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the res.locals.t syntax instead.");
112
+ return (0, _intlayer_core_interpreter.getTranslation)(content, locale ?? _intlayer_config_built.internationalization.defaultLocale);
110
113
  }
114
+ return context.t(content, locale);
111
115
  };
112
116
  const getIntlayer = (...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("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.");
116
- return appNamespace.get("getIntlayer")(...args);
117
- } catch (error) {
118
- debug(error.message);
117
+ const context = intlayerStorage.getStore();
118
+ if (!context) {
119
+ debug("Using the import { getIntlayer } from \"express-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the res.locals.getIntlayer syntax instead.");
119
120
  return (0, _intlayer_core_interpreter.getIntlayer)(...args);
120
121
  }
122
+ return context.getIntlayer(...args);
121
123
  };
122
124
  const getDictionary = (...args) => {
123
- try {
124
- if (typeof appNamespace === "undefined") throw new Error("Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.");
125
- 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.");
126
- return appNamespace.get("getDictionary")(...args);
127
- } catch (error) {
128
- debug(error.message);
125
+ const context = intlayerStorage.getStore();
126
+ if (!context) {
127
+ debug("Using the import { getDictionary } from \"express-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the res.locals.getDictionary syntax instead.");
129
128
  return (0, _intlayer_core_interpreter.getDictionary)(...args);
130
129
  }
130
+ return context.getDictionary(...args);
131
131
  };
132
132
 
133
133
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["getConfiguration","getLocaleFromStorageServer","createNamespace","registerAmbientLocaleResolver","prepareIntlayerServer","getTranslation","localeDetector","getIntlayerFunction","getDictionaryFunction"],"sources":["../../src/index.ts"],"sourcesContent":["import { getConfiguration } from '@intlayer/config/node';\nimport {\n getDictionary as getDictionaryFunction,\n getIntlayer as getIntlayerFunction,\n getTranslation,\n registerAmbientLocaleResolver,\n} from '@intlayer/core/interpreter';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport { prepareIntlayerServer } from '@intlayer/engine/build';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { StrictModeLocaleMap } from '@intlayer/types/module_augmentation';\nimport { createNamespace } from 'cls-hooked';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\n\n// Zero-cost fallback, will be updated with console logger in dev mode\nlet debug: (message: string) => void = () => {};\n\nconst configuration = getConfiguration();\nconst { internationalization } = configuration;\n\nif (process.env['NODE_ENV'] === 'development') {\n debug = (msg: string) => console.debug(msg);\n}\n\n/**\n * Retrieves the locale from storage (cookies, localStorage, sessionStorage).\n */\nconst getStorageLocale = (req: Request): Locale | undefined =>\n getLocaleFromStorageServer({\n getCookie: (name: string) => req.cookies?.[name],\n getHeader: (name: string) => req.headers?.[name] as string | undefined,\n });\n\nconst appNamespace = createNamespace('app');\n\n// Lets a bare `getIntlayer` / `getDictionary` from any Intlayer package resolve\n// to the locale of the request being handled.\nregisterAmbientLocaleResolver(() => appNamespace.get('locale'));\n\nprepareIntlayerServer(configuration, { label: 'express-intlayer' });\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 const locale = localeFromStorage ?? localeDetected;\n\n res.locals.locale = locale;\n res.locals.defaultLocale = internationalization.defaultLocale;\n\n const t = translateFunction(req, res, next);\n\n const getIntlayer: typeof getIntlayerFunction = (key, localeArg, ...props) =>\n getIntlayerFunction(\n key,\n (localeArg ?? locale) as typeof localeArg,\n ...props\n );\n\n const getDictionary: typeof getDictionaryFunction = (\n key,\n localeArg,\n ...props\n ) =>\n getDictionaryFunction(\n key,\n (localeArg ?? locale) as typeof localeArg,\n ...props\n );\n\n res.locals.t = t;\n res.locals.getIntlayer = getIntlayer;\n res.locals.getDictionary = getDictionary;\n\n appNamespace.run(() => {\n appNamespace.set('locale', locale);\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 debug((error as Error).message);\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 debug((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 debug((error as Error).message);\n\n return getDictionaryFunction(...args);\n }\n};\n"],"mappings":";;;;;;;;;AAgBA,IAAI,cAAyC,CAAC;AAE9C,MAAM,oBAAgBA,wCAAiB;AACvC,MAAM,EAAE,yBAAyB;AAEjC,6BAAgC,eAC9B,SAAS,QAAgB,QAAQ,MAAM,GAAG;;;;AAM5C,MAAM,oBAAoB,YACxBC,iDAA2B;CACzB,YAAY,SAAiB,IAAI,UAAU;CAC3C,YAAY,SAAiB,IAAI,UAAU;AAC7C,CAAC;AAEH,MAAM,mBAAeC,4BAAgB,KAAK;IAI1CC,gEAAoC,aAAa,IAAI,QAAQ,CAAC;IAE9DC,8CAAsB,eAAe,EAAE,OAAO,mBAAmB,CAAC;AAElE,MAAa,qBACV,MAAe,KAAe,WAE7B,SACA,WACM;CACN,MAAM,EAAE,QAAQ,eAAe,kBAAkB,IAAI;CAKrD,MAAM,eAAe,UAAU;CAE/B,IAAI,OAAO,YAAY,aACrB,OAAO;CAGT,IAAI,OAAO,YAAY,UACrB,OAAO;CAGT,IACE,OAAO,UACL,kBACI,aACN;EACA,IACE,OAAO,UACL,mBACI,aAEN,OAAO;OAEP,WAAOC,2CAAe,SAAS,aAAa;CAEhD;CAEA,WAAOA,2CAAe,SAAS,YAAY;AAC7C;;;;;;;;;;;;;;;;;;;;AAqBF,MAAa,iBAAiC,OAAO,KAAK,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AA2C,GAAG,SAAS;CAClE,IAAI;EACF,IAAI,OAAO,iBAAiB,aAC1B,MAAM,IAAI,MACR,oGACF;EAGF,IAAI,OAAO,aAAa,IAAI,aAAa,MAAM,YAC7C,MAAM,IAAI,MACR,6HACF;EAGF,OAAO,aAAa,IAAI,aAAa,CAAC,CAAC,GAAG,IAAI;CAChD,SAAS,OAAO;EACd,MAAO,MAAgB,OAAO;EAE9B,WAAOE,wCAAoB,GAAG,IAAI;CACpC;AACF;AAEA,MAAa,iBAA+C,GAAG,SAAS;CACtE,IAAI;EACF,IAAI,OAAO,iBAAiB,aAC1B,MAAM,IAAI,MACR,oGACF;EAGF,IAAI,OAAO,aAAa,IAAI,eAAe,MAAM,YAC/C,MAAM,IAAI,MACR,6HACF;EAGF,OAAO,aAAa,IAAI,eAAe,CAAC,CAAC,GAAG,IAAI;CAClD,SAAS,OAAO;EACd,MAAO,MAAgB,OAAO;EAE9B,WAAOC,0CAAsB,GAAG,IAAI;CACtC;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["getLocaleFromStorageServer","getCookie","AsyncLocalStorage","registerAmbientLocaleResolver","prepareIntlayerServer","getConfiguration","getTranslation","internationalization","localeDetector","getIntlayerFunction","getDictionaryFunction"],"sources":["../../src/index.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { internationalization } from '@intlayer/config/built';\nimport { getConfiguration } from '@intlayer/config/node';\nimport {\n getDictionary as getDictionaryFunction,\n getIntlayer as getIntlayerFunction,\n getTranslation,\n registerAmbientLocaleResolver,\n} from '@intlayer/core/interpreter';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getCookie, getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport { prepareIntlayerServer } from '@intlayer/engine/build';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { StrictModeLocaleMap } from '@intlayer/types/module_augmentation';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\n\n// Zero-cost fallback, will be updated with console logger in dev mode\nlet debug: (message: string) => void = () => {};\n\nif (process.env['NODE_ENV'] === 'development') {\n debug = (msg: string) => console.debug(msg);\n}\n\n/**\n * Reads a single-valued request header.\n */\nconst getHeader = (req: Request, name: string): string | undefined => {\n const value = req.headers[name];\n\n return Array.isArray(value) ? value.join(',') : value;\n};\n\n/**\n * Retrieves the locale from storage (cookies, headers).\n *\n * Parsed cookies need `cookie-parser`: the raw header is read otherwise.\n */\nconst getStorageLocale = (req: Request): Locale | undefined => {\n const parsedCookies = req.cookies as Record<string, string> | undefined;\n\n return getLocaleFromStorageServer({\n getCookie: (name: string) =>\n parsedCookies\n ? parsedCookies[name]\n : getCookie(name, req.headers.cookie ?? ''),\n getHeader: (name: string) => getHeader(req, name),\n });\n};\n\n/**\n * Intlayer helpers bound to the request being handled.\n */\ntype IntlayerRequestContext = {\n locale: Locale;\n t: ReturnType<typeof translateFunction>;\n getIntlayer: typeof getIntlayerFunction;\n getDictionary: typeof getDictionaryFunction;\n};\n\n/**\n * Request-scoped Intlayer context.\n *\n * `AsyncLocalStorage` rather than `cls-hooked`: the latter relies on\n * `async_hooks.createHook`, which Bun does not implement, and is several times\n * slower on Node.\n */\nconst intlayerStorage = new AsyncLocalStorage<IntlayerRequestContext>();\n\n// Lets a bare `getIntlayer` / `getDictionary` from any Intlayer package resolve\n// to the locale of the request being handled.\nregisterAmbientLocaleResolver(() => intlayerStorage.getStore()?.locale);\n\nprepareIntlayerServer(getConfiguration(), { label: 'express-intlayer' });\n\n/**\n * Builds the translation function bound to the locale stored in `res.locals`.\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 typeof content === 'string'\n ? (content as T)\n : getTranslation(\n content,\n locale ?? (res.locals.locale as Locale),\n internationalization.defaultLocale\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 an `AsyncLocalStorage` context 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 => (req, res, next) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(req);\n\n // Interpret browser locale\n const localeDetected = localeDetector(\n { 'accept-language': getHeader(req, 'accept-language') },\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n res.locals.locale_storage = localeFromStorage;\n res.locals.locale_detected = localeDetected;\n const locale = localeFromStorage ?? localeDetected;\n\n res.locals.locale = locale;\n res.locals.defaultLocale = internationalization.defaultLocale;\n\n const t = translateFunction(req, res, next);\n\n const getIntlayer: typeof getIntlayerFunction = (key, localeArg, ...props) =>\n getIntlayerFunction(\n key,\n (localeArg ?? locale) as typeof localeArg,\n ...props\n );\n\n const getDictionary: typeof getDictionaryFunction = (\n key,\n localeArg,\n ...props\n ) =>\n getDictionaryFunction(\n key,\n (localeArg ?? locale) as typeof localeArg,\n ...props\n );\n\n res.locals.t = t;\n res.locals.getIntlayer = getIntlayer;\n res.locals.getDictionary = getDictionary;\n\n intlayerStorage.run({ locale, t, getIntlayer, getDictionary }, next);\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 const context = intlayerStorage.getStore();\n\n if (!context) {\n debug(\n 'Using the import { t } from \"express-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the res.locals.t syntax instead.'\n );\n\n return getTranslation(\n content,\n locale ?? internationalization.defaultLocale\n );\n }\n\n return context.t(content as StrictModeLocaleMap<string>, locale) as Content;\n};\n\nexport const getIntlayer: typeof getIntlayerFunction = (...args) => {\n const context = intlayerStorage.getStore();\n\n if (!context) {\n debug(\n 'Using the import { getIntlayer } from \"express-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the res.locals.getIntlayer syntax instead.'\n );\n\n return getIntlayerFunction(...args);\n }\n\n return context.getIntlayer(...args);\n};\n\nexport const getDictionary: typeof getDictionaryFunction = (...args) => {\n const context = intlayerStorage.getStore();\n\n if (!context) {\n debug(\n 'Using the import { getDictionary } from \"express-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the res.locals.getDictionary syntax instead.'\n );\n\n return getDictionaryFunction(...args);\n }\n\n return context.getDictionary(...args);\n};\n"],"mappings":";;;;;;;;;;AAiBA,IAAI,cAAyC,CAAC;AAE9C,6BAAgC,eAC9B,SAAS,QAAgB,QAAQ,MAAM,GAAG;;;;AAM5C,MAAM,aAAa,KAAc,SAAqC;CACpE,MAAM,QAAQ,IAAI,QAAQ;CAE1B,OAAO,MAAM,QAAQ,KAAK,IAAI,MAAM,KAAK,GAAG,IAAI;AAClD;;;;;;AAOA,MAAM,oBAAoB,QAAqC;CAC7D,MAAM,gBAAgB,IAAI;CAE1B,WAAOA,iDAA2B;EAChC,YAAY,SACV,gBACI,cAAc,YACdC,gCAAU,MAAM,IAAI,QAAQ,UAAU,EAAE;EAC9C,YAAY,SAAiB,UAAU,KAAK,IAAI;CAClD,CAAC;AACH;;;;;;;;AAmBA,MAAM,kBAAkB,IAAIC,mCAA0C;IAItEC,gEAAoC,gBAAgB,SAAS,CAAC,EAAE,MAAM;IAEtEC,kDAAsBC,wCAAiB,GAAG,EAAE,OAAO,mBAAmB,CAAC;;;;AAKvE,MAAa,qBACV,MAAe,KAAe,WAE7B,SACA,WAEA,OAAO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B,SAAS;CAEzC,IAAI,CAAC,SAAS;EACZ,MACE,4KACF;EAEA,WAAOC,0CAAsB,GAAG,IAAI;CACtC;CAEA,OAAO,QAAQ,cAAc,GAAG,IAAI;AACtC"}
@@ -1,43 +1,54 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { internationalization } from "@intlayer/config/built";
1
3
  import { getConfiguration } from "@intlayer/config/node";
2
4
  import { getDictionary as getDictionary$1, getIntlayer as getIntlayer$1, getTranslation, registerAmbientLocaleResolver } from "@intlayer/core/interpreter";
3
5
  import { localeDetector } from "@intlayer/core/localization";
4
- import { getLocaleFromStorageServer } from "@intlayer/core/utils";
6
+ import { getCookie, getLocaleFromStorageServer } from "@intlayer/core/utils";
5
7
  import { prepareIntlayerServer } from "@intlayer/engine/build";
6
- import { createNamespace } from "cls-hooked";
7
8
 
8
9
  //#region src/index.ts
9
10
  let debug = () => {};
10
- const configuration = getConfiguration();
11
- const { internationalization } = configuration;
12
11
  if (process.env.NODE_ENV === "development") debug = (msg) => console.debug(msg);
13
12
  /**
14
- * Retrieves the locale from storage (cookies, localStorage, sessionStorage).
13
+ * Reads a single-valued request header.
15
14
  */
16
- const getStorageLocale = (req) => getLocaleFromStorageServer({
17
- getCookie: (name) => req.cookies?.[name],
18
- getHeader: (name) => req.headers?.[name]
19
- });
20
- const appNamespace = createNamespace("app");
21
- registerAmbientLocaleResolver(() => appNamespace.get("locale"));
22
- prepareIntlayerServer(configuration, { label: "express-intlayer" });
23
- const translateFunction = (_req, res, _next) => (content, locale) => {
24
- const { locale: currentLocale, defaultLocale } = res.locals;
25
- const targetLocale = locale ?? currentLocale;
26
- if (typeof content === "undefined") return "";
27
- if (typeof content === "string") return content;
28
- if (typeof content?.[targetLocale] === "undefined") {
29
- if (typeof content?.[defaultLocale] === "undefined") return content;
30
- else return getTranslation(content, defaultLocale);
31
- }
32
- return getTranslation(content, targetLocale);
15
+ const getHeader = (req, name) => {
16
+ const value = req.headers[name];
17
+ return Array.isArray(value) ? value.join(",") : value;
33
18
  };
34
19
  /**
20
+ * Retrieves the locale from storage (cookies, headers).
21
+ *
22
+ * Parsed cookies need `cookie-parser`: the raw header is read otherwise.
23
+ */
24
+ const getStorageLocale = (req) => {
25
+ const parsedCookies = req.cookies;
26
+ return getLocaleFromStorageServer({
27
+ getCookie: (name) => parsedCookies ? parsedCookies[name] : getCookie(name, req.headers.cookie ?? ""),
28
+ getHeader: (name) => getHeader(req, name)
29
+ });
30
+ };
31
+ /**
32
+ * Request-scoped Intlayer context.
33
+ *
34
+ * `AsyncLocalStorage` rather than `cls-hooked`: the latter relies on
35
+ * `async_hooks.createHook`, which Bun does not implement, and is several times
36
+ * slower on Node.
37
+ */
38
+ const intlayerStorage = new AsyncLocalStorage();
39
+ registerAmbientLocaleResolver(() => intlayerStorage.getStore()?.locale);
40
+ prepareIntlayerServer(getConfiguration(), { label: "express-intlayer" });
41
+ /**
42
+ * Builds the translation function bound to the locale stored in `res.locals`.
43
+ */
44
+ const translateFunction = (_req, res, _next) => (content, locale) => typeof content === "string" ? content : getTranslation(content, locale ?? res.locals.locale, internationalization.defaultLocale);
45
+ /**
35
46
  * Express middleware that detects the user's locale and populates `res.locals` with Intlayer data.
36
47
  *
37
48
  * It performs:
38
49
  * 1. Locale detection from cookies, headers, or default settings.
39
50
  * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into `res.locals`.
40
- * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.
51
+ * 3. Sets up an `AsyncLocalStorage` context for accessing these functions anywhere in the request lifecycle.
41
52
  *
42
53
  * @returns An Express middleware function.
43
54
  *
@@ -50,13 +61,9 @@ const translateFunction = (_req, res, _next) => (content, locale) => {
50
61
  * app.use(intlayer());
51
62
  * ```
52
63
  */
53
- const intlayer = () => async (req, res, next) => {
64
+ const intlayer = () => (req, res, next) => {
54
65
  const localeFromStorage = getStorageLocale(req);
55
- const negotiatorHeaders = {};
56
- if (req && typeof req.headers === "object") {
57
- for (const key in req.headers) if (typeof req.headers[key] === "string") negotiatorHeaders[key] = req.headers[key];
58
- }
59
- const localeDetected = localeDetector(negotiatorHeaders, internationalization.locales, internationalization.defaultLocale);
66
+ const localeDetected = localeDetector({ "accept-language": getHeader(req, "accept-language") }, internationalization.locales, internationalization.defaultLocale);
60
67
  res.locals.locale_storage = localeFromStorage;
61
68
  res.locals.locale_detected = localeDetected;
62
69
  const locale = localeFromStorage ?? localeDetected;
@@ -68,13 +75,12 @@ const intlayer = () => async (req, res, next) => {
68
75
  res.locals.t = t;
69
76
  res.locals.getIntlayer = getIntlayer;
70
77
  res.locals.getDictionary = getDictionary;
71
- appNamespace.run(() => {
72
- appNamespace.set("locale", locale);
73
- appNamespace.set("t", t);
74
- appNamespace.set("getIntlayer", getIntlayer);
75
- appNamespace.set("getDictionary", getDictionary);
76
- next();
77
- });
78
+ intlayerStorage.run({
79
+ locale,
80
+ t,
81
+ getIntlayer,
82
+ getDictionary
83
+ }, next);
78
84
  };
79
85
  /**
80
86
  * Translation function to retrieve content for the current locale.
@@ -99,34 +105,28 @@ const intlayer = () => async (req, res, next) => {
99
105
  * ```
100
106
  */
101
107
  const t = (content, locale) => {
102
- try {
103
- if (typeof appNamespace === "undefined") throw new Error("Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.");
104
- 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.");
105
- return appNamespace.get("t")(content, locale);
106
- } catch (error) {
107
- debug(error.message);
108
+ const context = intlayerStorage.getStore();
109
+ if (!context) {
110
+ debug("Using the import { t } from \"express-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the res.locals.t syntax instead.");
108
111
  return getTranslation(content, locale ?? internationalization.defaultLocale);
109
112
  }
113
+ return context.t(content, locale);
110
114
  };
111
115
  const getIntlayer = (...args) => {
112
- try {
113
- if (typeof appNamespace === "undefined") throw new Error("Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.");
114
- 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.");
115
- return appNamespace.get("getIntlayer")(...args);
116
- } catch (error) {
117
- debug(error.message);
116
+ const context = intlayerStorage.getStore();
117
+ if (!context) {
118
+ debug("Using the import { getIntlayer } from \"express-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the res.locals.getIntlayer syntax instead.");
118
119
  return getIntlayer$1(...args);
119
120
  }
121
+ return context.getIntlayer(...args);
120
122
  };
121
123
  const getDictionary = (...args) => {
122
- try {
123
- if (typeof appNamespace === "undefined") throw new Error("Intlayer is not initialized. Add the `app.use(intlayer());` middleware before using this function.");
124
- 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.");
125
- return appNamespace.get("getDictionary")(...args);
126
- } catch (error) {
127
- debug(error.message);
124
+ const context = intlayerStorage.getStore();
125
+ if (!context) {
126
+ debug("Using the import { getDictionary } from \"express-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the res.locals.getDictionary syntax instead.");
128
127
  return getDictionary$1(...args);
129
128
  }
129
+ return context.getDictionary(...args);
130
130
  };
131
131
 
132
132
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["getIntlayerFunction","getDictionaryFunction"],"sources":["../../src/index.ts"],"sourcesContent":["import { getConfiguration } from '@intlayer/config/node';\nimport {\n getDictionary as getDictionaryFunction,\n getIntlayer as getIntlayerFunction,\n getTranslation,\n registerAmbientLocaleResolver,\n} from '@intlayer/core/interpreter';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport { prepareIntlayerServer } from '@intlayer/engine/build';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { StrictModeLocaleMap } from '@intlayer/types/module_augmentation';\nimport { createNamespace } from 'cls-hooked';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\n\n// Zero-cost fallback, will be updated with console logger in dev mode\nlet debug: (message: string) => void = () => {};\n\nconst configuration = getConfiguration();\nconst { internationalization } = configuration;\n\nif (process.env['NODE_ENV'] === 'development') {\n debug = (msg: string) => console.debug(msg);\n}\n\n/**\n * Retrieves the locale from storage (cookies, localStorage, sessionStorage).\n */\nconst getStorageLocale = (req: Request): Locale | undefined =>\n getLocaleFromStorageServer({\n getCookie: (name: string) => req.cookies?.[name],\n getHeader: (name: string) => req.headers?.[name] as string | undefined,\n });\n\nconst appNamespace = createNamespace('app');\n\n// Lets a bare `getIntlayer` / `getDictionary` from any Intlayer package resolve\n// to the locale of the request being handled.\nregisterAmbientLocaleResolver(() => appNamespace.get('locale'));\n\nprepareIntlayerServer(configuration, { label: 'express-intlayer' });\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 const locale = localeFromStorage ?? localeDetected;\n\n res.locals.locale = locale;\n res.locals.defaultLocale = internationalization.defaultLocale;\n\n const t = translateFunction(req, res, next);\n\n const getIntlayer: typeof getIntlayerFunction = (key, localeArg, ...props) =>\n getIntlayerFunction(\n key,\n (localeArg ?? locale) as typeof localeArg,\n ...props\n );\n\n const getDictionary: typeof getDictionaryFunction = (\n key,\n localeArg,\n ...props\n ) =>\n getDictionaryFunction(\n key,\n (localeArg ?? locale) as typeof localeArg,\n ...props\n );\n\n res.locals.t = t;\n res.locals.getIntlayer = getIntlayer;\n res.locals.getDictionary = getDictionary;\n\n appNamespace.run(() => {\n appNamespace.set('locale', locale);\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 debug((error as Error).message);\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 debug((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 debug((error as Error).message);\n\n return getDictionaryFunction(...args);\n }\n};\n"],"mappings":";;;;;;;;AAgBA,IAAI,cAAyC,CAAC;AAE9C,MAAM,gBAAgB,iBAAiB;AACvC,MAAM,EAAE,yBAAyB;AAEjC,6BAAgC,eAC9B,SAAS,QAAgB,QAAQ,MAAM,GAAG;;;;AAM5C,MAAM,oBAAoB,QACxB,2BAA2B;CACzB,YAAY,SAAiB,IAAI,UAAU;CAC3C,YAAY,SAAiB,IAAI,UAAU;AA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Aa,UAAU;EACrB,aAAa,IAAI,UAAU,MAAM;EACjC,aAAa,IAAI,KAAK,CAAC;EACvB,aAAa,IAAI,eAAe,WAAW;EAC3C,aAAa,IAAI,iBAAiB,aAAa;EAE/C,KAAK;CACP,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,KACX,SACA,WACY;CACZ,IAAI;EACF,IAAI,OAAO,iBAAiB,aAC1B,MAAM,IAAI,MACR,oGACF;EAGF,IAAI,OAAO,aAAa,IAAI,GAAG,MAAM,YACnC,MAAM,IAAI,MACR,6HACF;EAGF,OAAO,aAAa,IAAI,GAAG,CAAC,CAAC,SAAS,MAAM;CAC9C,SAAS,OAAO;EACd,MAAO,MAAgB,OAAO;EAE9B,OAAO,eACL,SACA,UAAU,qBAAqB,aACjC;CACF;AACF;AAEA,MAAa,eAA2C,GAAG,SAAS;CAClE,IAAI;EACF,IAAI,OAAO,iBAAiB,aAC1B,MAAM,IAAI,MACR,oGACF;EAGF,IAAI,OAAO,aAAa,IAAI,aAAa,MAAM,YAC7C,MAAM,IAAI,MACR,6HACF;EAGF,OAAO,aAAa,IAAI,aAAa,CAAC,CAAC,GAAG,IAAI;CAChD,SAAS,OAAO;EACd,MAAO,MAAgB,OAAO;EAE9B,OAAOD,cAAoB,GAAG,IAAI;CACpC;AACF;AAEA,MAAa,iBAA+C,GAAG,SAAS;CACtE,IAAI;EACF,IAAI,OAAO,iBAAiB,aAC1B,MAAM,IAAI,MACR,oGACF;EAGF,IAAI,OAAO,aAAa,IAAI,eAAe,MAAM,YAC/C,MAAM,IAAI,MACR,6HACF;EAGF,OAAO,aAAa,IAAI,eAAe,CAAC,CAAC,GAAG,IAAI;CAClD,SAAS,OAAO;EACd,MAAO,MAAgB,OAAO;EAE9B,OAAOC,gBAAsB,GAAG,IAAI;CACtC;AACF"}
1
+ {"version":3,"file":"index.mjs","names":["getIntlayerFunction","getDictionaryFunction"],"sources":["../../src/index.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { internationalization } from '@intlayer/config/built';\nimport { getConfiguration } from '@intlayer/config/node';\nimport {\n getDictionary as getDictionaryFunction,\n getIntlayer as getIntlayerFunction,\n getTranslation,\n registerAmbientLocaleResolver,\n} from '@intlayer/core/interpreter';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getCookie, getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport { prepareIntlayerServer } from '@intlayer/engine/build';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { StrictModeLocaleMap } from '@intlayer/types/module_augmentation';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\n\n// Zero-cost fallback, will be updated with console logger in dev mode\nlet debug: (message: string) => void = () => {};\n\nif (process.env['NODE_ENV'] === 'development') {\n debug = (msg: string) => console.debug(msg);\n}\n\n/**\n * Reads a single-valued request header.\n */\nconst getHeader = (req: Request, name: string): string | undefined => {\n const value = req.headers[name];\n\n return Array.isArray(value) ? value.join(',') : value;\n};\n\n/**\n * Retrieves the locale from storage (cookies, headers).\n *\n * Parsed cookies need `cookie-parser`: the raw header is read otherwise.\n */\nconst getStorageLocale = (req: Request): Locale | undefined => {\n const parsedCookies = req.cookies as Record<string, string> | undefined;\n\n return getLocaleFromStorageServer({\n getCookie: (name: string) =>\n parsedCookies\n ? parsedCookies[name]\n : getCookie(name, req.headers.cookie ?? ''),\n getHeader: (name: string) => getHeader(req, name),\n });\n};\n\n/**\n * Intlayer helpers bound to the request being handled.\n */\ntype IntlayerRequestContext = {\n locale: Locale;\n t: ReturnType<typeof translateFunction>;\n getIntlayer: typeof getIntlayerFunction;\n getDictionary: typeof getDictionaryFunction;\n};\n\n/**\n * Request-scoped Intlayer context.\n *\n * `AsyncLocalStorage` rather than `cls-hooked`: the latter relies on\n * `async_hooks.createHook`, which Bun does not implement, and is several times\n * slower on Node.\n */\nconst intlayerStorage = new AsyncLocalStorage<IntlayerRequestContext>();\n\n// Lets a bare `getIntlayer` / `getDictionary` from any Intlayer package resolve\n// to the locale of the request being handled.\nregisterAmbientLocaleResolver(() => intlayerStorage.getStore()?.locale);\n\nprepareIntlayerServer(getConfiguration(), { label: 'express-intlayer' });\n\n/**\n * Builds the translation function bound to the locale stored in `res.locals`.\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 typeof content === 'string'\n ? (content as T)\n : getTranslation(\n content,\n locale ?? (res.locals.locale as Locale),\n internationalization.defaultLocale\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 an `AsyncLocalStorage` context 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 => (req, res, next) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(req);\n\n // Interpret browser locale\n const localeDetected = localeDetector(\n { 'accept-language': getHeader(req, 'accept-language') },\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n res.locals.locale_storage = localeFromStorage;\n res.locals.locale_detected = localeDetected;\n const locale = localeFromStorage ?? localeDetected;\n\n res.locals.locale = locale;\n res.locals.defaultLocale = internationalization.defaultLocale;\n\n const t = translateFunction(req, res, next);\n\n const getIntlayer: typeof getIntlayerFunction = (key, localeArg, ...props) =>\n getIntlayerFunction(\n key,\n (localeArg ?? locale) as typeof localeArg,\n ...props\n );\n\n const getDictionary: typeof getDictionaryFunction = (\n key,\n localeArg,\n ...props\n ) =>\n getDictionaryFunction(\n key,\n (localeArg ?? locale) as typeof localeArg,\n ...props\n );\n\n res.locals.t = t;\n res.locals.getIntlayer = getIntlayer;\n res.locals.getDictionary = getDictionary;\n\n intlayerStorage.run({ locale, t, getIntlayer, getDictionary }, next);\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 const context = intlayerStorage.getStore();\n\n if (!context) {\n debug(\n 'Using the import { t } from \"express-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the res.locals.t syntax instead.'\n );\n\n return getTranslation(\n content,\n locale ?? internationalization.defaultLocale\n );\n }\n\n return context.t(content as StrictModeLocaleMap<string>, locale) as Content;\n};\n\nexport const getIntlayer: typeof getIntlayerFunction = (...args) => {\n const context = intlayerStorage.getStore();\n\n if (!context) {\n debug(\n 'Using the import { getIntlayer } from \"express-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the res.locals.getIntlayer syntax instead.'\n );\n\n return getIntlayerFunction(...args);\n }\n\n return context.getIntlayer(...args);\n};\n\nexport const getDictionary: typeof getDictionaryFunction = (...args) => {\n const context = intlayerStorage.getStore();\n\n if (!context) {\n debug(\n 'Using the import { getDictionary } from \"express-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the res.locals.getDictionary syntax instead.'\n );\n\n return getDictionaryFunction(...args);\n }\n\n return context.getDictionary(...args);\n};\n"],"mappings":";;;;;;;;;AAiBA,IAAI,cAAyC,CAAC;AAE9C,6BAAgC,eAC9B,SAAS,QAAgB,QAAQ,MAAM,GAAG;;;;AAM5C,MAAM,aAAa,KAAc,SAAqC;CACpE,MAAM,QAAQ,IAAI,QAAQ;CAE1B,OAAO,MAAM,QAAQ,KAAK,IAAI,MAAM,KAAK,GAAG,IAAI;AAClD;;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AAU,gBAAgB,SAAS;CAEzC,IAAI,CAAC,SAAS;EACZ,MACE,oJACF;EAEA,OAAO,eACL,SACA,UAAU,qBAAqB,aACjC;CACF;CAEA,OAAO,QAAQ,EAAE,SAAwC,MAAM;AACjE;AAEA,MAAa,eAA2C,GAAG,SAAS;CAClE,MAAM,UAAU,gBAAgB,SAAS;CAEzC,IAAI,CAAC,SAAS;EACZ,MACE,wKACF;EAEA,OAAOD,cAAoB,GAAG,IAAI;CACpC;CAEA,OAAO,QAAQ,YAAY,GAAG,IAAI;AACpC;AAEA,MAAa,iBAA+C,GAAG,SAAS;CACtE,MAAM,UAAU,gBAAgB,SAAS;CAEzC,IAAI,CAAC,SAAS;EACZ,MACE,4KACF;EAEA,OAAOC,gBAAsB,GAAG,IAAI;CACtC;CAEA,OAAO,QAAQ,cAAc,GAAG,IAAI;AACtC"}
@@ -3,6 +3,9 @@ import { Locale } from "@intlayer/types/allLocales";
3
3
  import { StrictModeLocaleMap } from "@intlayer/types/module_augmentation";
4
4
  import { NextFunction, Request, RequestHandler, Response } from "express";
5
5
  //#region src/index.d.ts
6
+ /**
7
+ * Builds the translation function bound to the locale stored in `res.locals`.
8
+ */
6
9
  export declare const translateFunction: (_req: Request, res: Response, _next?: NextFunction) => <T extends string>(content: StrictModeLocaleMap<T> | string, locale?: Locale) => T;
7
10
  /**
8
11
  * Express middleware that detects the user's locale and populates `res.locals` with Intlayer data.
@@ -10,7 +13,7 @@ export declare const translateFunction: (_req: Request, res: Response, _next?: N
10
13
  * It performs:
11
14
  * 1. Locale detection from cookies, headers, or default settings.
12
15
  * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into `res.locals`.
13
- * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.
16
+ * 3. Sets up an `AsyncLocalStorage` context for accessing these functions anywhere in the request lifecycle.
14
17
  *
15
18
  * @returns An Express middleware function.
16
19
  *
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/index.ts"],"mappings":";;;;;qBA0Ca,oBAAiB,MACrB,SAAO,KAAO,UAAQ,QAAU,kBACtC,kBAAgB,SACN,oBAAoB,aAAW,SAC/B,WACR;;;;;;;;;;;;;;;;;;;;qBAsDQ,gBAAe;;;;;;;;;;;;;;;;;;;;;;;qBAsFf,IAAK,kBAAgB,SACvB,oBAAoB,UAAQ,SAC5B,WACR;qBAyBU,oBAAoB;qBAsBpB,sBAAsB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/index.ts"],"mappings":";;;;;;;;qBA6Ea,oBAAiB,MACrB,SAAO,KAAO,UAAQ,QAAU,kBACtC,kBAAgB,SACN,oBAAoB,aAAW,SAC/B,WACR;;;;;;;;;;;;;;;;;;;;qBA4BQ,gBAAe;;;;;;;;;;;;;;;;;;;;;;;qBAmEf,IAAK,kBAAgB,SACvB,oBAAoB,UAAQ,SAC5B,WACR;qBAiBU,oBAAoB;qBAcpB,sBAAsB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-intlayer",
3
- "version": "9.5.12",
3
+ "version": "9.7.0",
4
4
  "private": false,
5
5
  "description": "Manage internationalization i18n in a simple way for express application.",
6
6
  "keywords": [
@@ -76,16 +76,14 @@
76
76
  "typecheck": "tsc --noEmit --project tsconfig.types.json"
77
77
  },
78
78
  "dependencies": {
79
- "@intlayer/config": "9.5.12",
80
- "@intlayer/core": "9.5.12",
81
- "@intlayer/engine": "9.5.12",
82
- "@intlayer/types": "9.5.12",
83
- "cls-hooked": "4.2.2"
79
+ "@intlayer/config": "9.7.0",
80
+ "@intlayer/core": "9.7.0",
81
+ "@intlayer/engine": "9.7.0",
82
+ "@intlayer/types": "9.7.0"
84
83
  },
85
84
  "devDependencies": {
86
- "@types/cls-hooked": "4.3.9",
87
85
  "@types/express": "5.0.6",
88
- "@types/node": "^22",
86
+ "@types/node": "^26",
89
87
  "@utils/ts-config": "1.0.4",
90
88
  "@utils/ts-config-types": "1.0.4",
91
89
  "@utils/tsdown-config": "1.0.4",
@@ -93,7 +91,7 @@
93
91
  "rimraf": "6.1.3",
94
92
  "tsdown": "0.23.0",
95
93
  "typescript": "7.0.2",
96
- "vitest": "5.0.2"
94
+ "vitest": "5.0.3"
97
95
  },
98
96
  "engines": {
99
97
  "node": ">=14.18"