hono-intlayer 9.5.11 → 9.6.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,17 +1,16 @@
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
  let hono_cookie = require("hono/cookie");
9
10
 
10
11
  //#region src/index.ts
11
12
  let debug = () => {};
12
- const configuration = (0, _intlayer_config_node.getConfiguration)();
13
- const { internationalization } = configuration;
14
- if (process.env["NODE_ENV"] === "development") debug = (msg) => console.debug(msg);
13
+ if (process.env.NODE_ENV === "development") debug = (msg) => console.debug(msg);
15
14
  /**
16
15
  * Retrieves the locale from storage (cookies, headers).
17
16
  */
@@ -19,27 +18,27 @@ const getStorageLocale = (context) => (0, _intlayer_core_utils.getLocaleFromStor
19
18
  getCookie: (name) => (0, hono_cookie.getCookie)(context, name),
20
19
  getHeader: (name) => context.req.header(name)
21
20
  });
22
- const appNamespace = (0, cls_hooked.createNamespace)("app");
23
- (0, _intlayer_engine_build.prepareIntlayer)(configuration);
24
- const translateFunction = (context) => (content, locale) => {
25
- const currentLocale = context.get("locale");
26
- const defaultLocale = context.get("defaultLocale");
27
- const targetLocale = locale ?? currentLocale;
28
- if (typeof content === "undefined") return "";
29
- if (typeof content === "string") return content;
30
- if (typeof content?.[targetLocale] === "undefined") {
31
- if (typeof content?.[defaultLocale] === "undefined") return content;
32
- else return (0, _intlayer_core_interpreter.getTranslation)(content, defaultLocale);
33
- }
34
- return (0, _intlayer_core_interpreter.getTranslation)(content, targetLocale);
35
- };
21
+ /**
22
+ * Request-scoped Intlayer context.
23
+ *
24
+ * `AsyncLocalStorage` rather than `cls-hooked`: the latter relies on
25
+ * `async_hooks.createHook`, which Bun does not implement, and is several times
26
+ * slower on Node.
27
+ */
28
+ const intlayerStorage = new node_async_hooks.AsyncLocalStorage();
29
+ (0, _intlayer_core_interpreter.registerAmbientLocaleResolver)(() => intlayerStorage.getStore()?.locale);
30
+ (0, _intlayer_engine_build.prepareIntlayerServer)((0, _intlayer_config_node.getConfiguration)(), { label: "hono-intlayer" });
31
+ /**
32
+ * Builds the translation function bound to the locale stored in the Hono context.
33
+ */
34
+ const translateFunction = (context) => (content, locale) => typeof content === "string" ? content : (0, _intlayer_core_interpreter.getTranslation)(content, locale ?? context.get("locale"), _intlayer_config_built.internationalization.defaultLocale);
36
35
  /**
37
36
  * Hono middleware that detects the user's locale and populates context with Intlayer data.
38
37
  *
39
38
  * It performs:
40
39
  * 1. Locale detection from cookies, headers, or default settings.
41
40
  * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into the context.
42
- * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.
41
+ * 3. Sets up an `AsyncLocalStorage` context for accessing these functions anywhere in the request lifecycle.
43
42
  *
44
43
  * @returns A Hono middleware function.
45
44
  *
@@ -52,30 +51,26 @@ const translateFunction = (context) => (content, locale) => {
52
51
  * app.use('*', intlayer());
53
52
  * ```
54
53
  */
55
- const intlayer = () => async (context, next) => {
54
+ const intlayer = () => (context, next) => {
56
55
  const localeFromStorage = getStorageLocale(context);
57
- const negotiatorHeaders = context.req.header();
58
- const localeDetected = (0, _intlayer_core_localization.localeDetector)(negotiatorHeaders, internationalization.locales, internationalization.defaultLocale);
56
+ const localeDetected = (0, _intlayer_core_localization.localeDetector)({ "accept-language": context.req.header("accept-language") }, _intlayer_config_built.internationalization.locales, _intlayer_config_built.internationalization.defaultLocale);
59
57
  const locale = localeFromStorage ?? localeDetected;
60
58
  context.set("locale_storage", localeFromStorage);
61
59
  context.set("locale_detected", localeDetected);
62
60
  context.set("locale", locale);
63
- context.set("defaultLocale", internationalization.defaultLocale);
61
+ context.set("defaultLocale", _intlayer_config_built.internationalization.defaultLocale);
64
62
  const t = translateFunction(context);
65
63
  const getIntlayer = (key, localeArg = locale, ...props) => (0, _intlayer_core_interpreter.getIntlayer)(key, localeArg, ...props);
66
64
  const getDictionary = (key, localeArg = locale, ...props) => (0, _intlayer_core_interpreter.getDictionary)(key, localeArg, ...props);
67
65
  context.set("t", t);
68
66
  context.set("getIntlayer", getIntlayer);
69
67
  context.set("getDictionary", getDictionary);
70
- return new Promise((resolve) => {
71
- appNamespace.run(async () => {
72
- appNamespace.set("t", t);
73
- appNamespace.set("getIntlayer", getIntlayer);
74
- appNamespace.set("getDictionary", getDictionary);
75
- await next();
76
- resolve();
77
- });
78
- });
68
+ return intlayerStorage.run({
69
+ locale,
70
+ t,
71
+ getIntlayer,
72
+ getDictionary
73
+ }, next);
79
74
  };
80
75
  /**
81
76
  * Translation function to retrieve content for the current locale.
@@ -100,34 +95,28 @@ const intlayer = () => async (context, next) => {
100
95
  * ```
101
96
  */
102
97
  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 \"hono-intlayer\" is not supported in your environment. Use the context 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);
98
+ const context = intlayerStorage.getStore();
99
+ if (!context) {
100
+ debug("Using the import { t } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.");
101
+ return (0, _intlayer_core_interpreter.getTranslation)(content, locale ?? _intlayer_config_built.internationalization.defaultLocale);
110
102
  }
103
+ return context.t(content, locale);
111
104
  };
112
105
  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 { getIntlayer } from \"hono-intlayer\" is not supported in your environment. Use the context instead.");
116
- return appNamespace.get("getIntlayer")(...args);
117
- } catch (error) {
118
- debug(error.message);
106
+ const context = intlayerStorage.getStore();
107
+ if (!context) {
108
+ debug("Using the import { getIntlayer } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.");
119
109
  return (0, _intlayer_core_interpreter.getIntlayer)(...args);
120
110
  }
111
+ return context.getIntlayer(...args);
121
112
  };
122
113
  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 { getDictionary } from \"hono-intlayer\" is not supported in your environment. Use the context instead.");
126
- return appNamespace.get("getDictionary")(...args);
127
- } catch (error) {
128
- debug(error.message);
114
+ const context = intlayerStorage.getStore();
115
+ if (!context) {
116
+ debug("Using the import { getDictionary } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.");
129
117
  return (0, _intlayer_core_interpreter.getDictionary)(...args);
130
118
  }
119
+ return context.getDictionary(...args);
131
120
  };
132
121
 
133
122
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["getConfiguration","getLocaleFromStorageServer","getCookie","createNamespace","prepareIntlayer","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} from '@intlayer/core/interpreter';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport { prepareIntlayer } 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 { Context, MiddlewareHandler } from 'hono';\nimport { getCookie } from 'hono/cookie';\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, headers).\n */\nconst getStorageLocale = (context: Context): Locale | undefined =>\n getLocaleFromStorageServer({\n getCookie: (name: string) => getCookie(context, name),\n getHeader: (name: string) => context.req.header(name),\n });\n\nconst appNamespace = createNamespace('app');\n\nprepareIntlayer(configuration);\n\nexport const translateFunction =\n (context: Context) =>\n <T extends string>(\n content: StrictModeLocaleMap<T> | string,\n locale?: Locale\n ): T => {\n const currentLocale = context.get('locale') as Locale;\n const defaultLocale = context.get('defaultLocale') as Locale;\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 * Hono middleware that detects the user's locale and populates context 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 the context.\n * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.\n *\n * @returns A Hono middleware function.\n *\n * @example\n * ```ts\n * import { Hono } from 'hono';\n * import { intlayer } from 'hono-intlayer';\n *\n * const app = new Hono();\n * app.use('*', intlayer());\n * ```\n */\nexport const intlayer =\n (): MiddlewareHandler =>\n async (context: Context, next: () => Promise<void>) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(context);\n\n const negotiatorHeaders: Record<string, string> = context.req.header();\n\n const localeDetected = localeDetector(\n negotiatorHeaders,\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n const locale = localeFromStorage ?? localeDetected;\n\n context.set('locale_storage', localeFromStorage);\n context.set('locale_detected', localeDetected);\n context.set('locale', locale);\n context.set('defaultLocale', internationalization.defaultLocale);\n\n const t = translateFunction(context);\n\n const getIntlayer: typeof getIntlayerFunction = (\n key: Parameters<typeof getIntlayerFunction>[0],\n localeArg = locale as Parameters<typeof getIntlayerFunction>[1],\n ...props: any[]\n ) => getIntlayerFunction(key, localeArg, ...props);\n\n const getDictionary: typeof getDictionaryFunction = (\n key: Parameters<typeof getDictionaryFunction>[0],\n localeArg = locale as Parameters<typeof getDictionaryFunction>[1],\n ...props: any[]\n ) => getDictionaryFunction(key, localeArg, ...props);\n\n context.set('t', t);\n context.set('getIntlayer', getIntlayer);\n context.set('getDictionary', getDictionary);\n\n return new Promise<void>((resolve) => {\n appNamespace.run(async () => {\n appNamespace.set('t', t);\n appNamespace.set('getIntlayer', getIntlayer);\n appNamespace.set('getDictionary', getDictionary);\n\n await next();\n resolve();\n });\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 'hono-intlayer';\n *\n * app.get('/', (c) => {\n * const greeting = t({\n * en: 'Hello',\n * fr: 'Bonjour',\n * });\n * return c.text(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 \"hono-intlayer\" is not supported in your environment. Use the context 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 = (\n ...args: Parameters<typeof getIntlayerFunction>\n) => {\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 { getIntlayer } from \"hono-intlayer\" is not supported in your environment. Use the context 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 = (\n ...args: Parameters<typeof getDictionaryFunction>\n) => {\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 { getDictionary } from \"hono-intlayer\" is not supported in your environment. Use the context 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,IAAI,QAAQ,IAAI,gBAAgB,eAC9B,SAAS,QAAgB,QAAQ,MAAM,GAAG;;;;AAM5C,MAAM,oBAAoB,gBACxBC,iDAA2B;CACzB,YAAY,aAAiBC,uBAAU,SAAS,IAAI;CACpD,YAAY,S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a,IAAI,eAAe,WAAW;GAC3C,aAAa,IAAI,iBAAiB,aAAa;GAE/C,MAAM,KAAK;GACX,QAAQ;EACV,CAAC;CACH,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;AAwBF,MAAa,KACX,SACA,WACY;CACZ,IAAI;EACF,IAAI,OAAO,iBAAiB,aAC1B,MAAM,IAAI,MACR,2GACF;EAGF,IAAI,OAAO,aAAa,IAAI,GAAG,MAAM,YACnC,MAAM,IAAI,MACR,8GACF;EAGF,OAAO,aAAa,IAAI,GAAG,CAAC,CAAC,SAAS,MAAM;CAC9C,SAAS,OAAO;EACd,MAAO,MAAgB,OAAO;EAE9B,WAAOH,2CACL,SACA,UAAU,qBAAqB,aACjC;CACF;AACF;AAEA,MAAa,eACX,GAAG,SACA;CACH,IAAI;EACF,IAAI,OAAO,iBAAiB,aAC1B,MAAM,IAAI,MACR,2GACF;EAGF,IAAI,OAAO,aAAa,IAAI,aAAa,MAAM,YAC7C,MAAM,IAAI,MACR,wHACF;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,iBACX,GAAG,SACA;CACH,IAAI;EACF,IAAI,OAAO,iBAAiB,aAC1B,MAAM,IAAI,MACR,2GACF;EAGF,IAAI,OAAO,aAAa,IAAI,eAAe,MAAM,YAC/C,MAAM,IAAI,MACR,0HACF;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 { 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 { Context, MiddlewareHandler } from 'hono';\nimport { getCookie } from 'hono/cookie';\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 * Retrieves the locale from storage (cookies, headers).\n */\nconst getStorageLocale = (context: Context): Locale | undefined =>\n getLocaleFromStorageServer({\n getCookie: (name: string) => getCookie(context, name),\n getHeader: (name: string) => context.req.header(name),\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: 'hono-intlayer' });\n\n/**\n * Builds the translation function bound to the locale stored in the Hono context.\n */\nexport const translateFunction =\n (context: Context) =>\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 ?? (context.get('locale') as Locale),\n internationalization.defaultLocale\n );\n\n/**\n * Hono middleware that detects the user's locale and populates context 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 the context.\n * 3. Sets up an `AsyncLocalStorage` context for accessing these functions anywhere in the request lifecycle.\n *\n * @returns A Hono middleware function.\n *\n * @example\n * ```ts\n * import { Hono } from 'hono';\n * import { intlayer } from 'hono-intlayer';\n *\n * const app = new Hono();\n * app.use('*', intlayer());\n * ```\n */\nexport const intlayer =\n (): MiddlewareHandler => (context: Context, next: () => Promise<void>) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(context);\n\n const localeDetected = localeDetector(\n { 'accept-language': context.req.header('accept-language') },\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n const locale = localeFromStorage ?? localeDetected;\n\n context.set('locale_storage', localeFromStorage);\n context.set('locale_detected', localeDetected);\n context.set('locale', locale);\n context.set('defaultLocale', internationalization.defaultLocale);\n\n const t = translateFunction(context);\n\n const getIntlayer: typeof getIntlayerFunction = (\n key,\n localeArg = locale as typeof localeArg,\n ...props\n ) => getIntlayerFunction(key, localeArg, ...props);\n\n const getDictionary: typeof getDictionaryFunction = (\n key,\n localeArg = locale as typeof localeArg,\n ...props\n ) => getDictionaryFunction(key, localeArg, ...props);\n\n context.set('t', t);\n context.set('getIntlayer', getIntlayer);\n context.set('getDictionary', getDictionary);\n\n return 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 'hono-intlayer';\n *\n * app.get('/', (c) => {\n * const greeting = t({\n * en: 'Hello',\n * fr: 'Bonjour',\n * });\n * return c.text(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 \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context 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 = (\n ...args: Parameters<typeof getIntlayerFunction>\n) => {\n const context = intlayerStorage.getStore();\n\n if (!context) {\n debug(\n 'Using the import { getIntlayer } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.'\n );\n\n return getIntlayerFunction(...args);\n }\n\n return context.getIntlayer(...args);\n};\n\nexport const getDictionary: typeof getDictionaryFunction = (\n ...args: Parameters<typeof getDictionaryFunction>\n) => {\n const context = intlayerStorage.getStore();\n\n if (!context) {\n debug(\n 'Using the import { getDictionary } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.'\n );\n\n return getDictionaryFunction(...args);\n }\n\n return context.getDictionary(...args);\n};\n"],"mappings":";;;;;;;;;;;AAkBA,IAAI,cAAyC,CAAC;AAE9C,6BAAgC,eAC9B,SAAS,QAAgB,QAAQ,MAAM,GAAG;;;;AAM5C,MAAM,oBAAoB,gBACxBA,iDAA2B;CACzB,YAAY,aAAiBC,uBAAU,SAAS,IAAI;CACpD,YAAY,SAAiB,QAAQ,IAAI,OAAO,IAAI;AACtD,CAAC;;;;;;;;AAmBH,MAAM,kBAAkB,IAAIC,mCAA0C;IAItEC,gEAAoC,gBAAgB,SAAS,CAAC,EAAE,MAAM;IAEtEC,kDAAsBC,wCAAiB,GAAG,EAAE,OAAO,gBAAgB,CAAC;;;;AAKpE,MAAa,qBACV,aAEC,SACA,WAEA,OAAO,YAAY,WACd,cAC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,MAAa,iBACX,GAAG,SACA;CACH,MAAM,UAAU,gBAAgB,SAAS;CAEzC,IAAI,CAAC,SAAS;EACZ,MACE,iJACF;EAEA,WAAOC,0CAAsB,GAAG,IAAI;CACtC;CAEA,OAAO,QAAQ,cAAc,GAAG,IAAI;AACtC"}
@@ -1,16 +1,15 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { internationalization } from "@intlayer/config/built";
1
3
  import { getConfiguration } from "@intlayer/config/node";
2
- import { getDictionary as getDictionary$1, getIntlayer as getIntlayer$1, getTranslation } from "@intlayer/core/interpreter";
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
6
  import { getLocaleFromStorageServer } from "@intlayer/core/utils";
5
- import { prepareIntlayer } from "@intlayer/engine/build";
6
- import { createNamespace } from "cls-hooked";
7
+ import { prepareIntlayerServer } from "@intlayer/engine/build";
7
8
  import { getCookie } from "hono/cookie";
8
9
 
9
10
  //#region src/index.ts
10
11
  let debug = () => {};
11
- const configuration = getConfiguration();
12
- const { internationalization } = configuration;
13
- debug = (msg) => console.debug(msg);
12
+ if (process.env.NODE_ENV === "development") debug = (msg) => console.debug(msg);
14
13
  /**
15
14
  * Retrieves the locale from storage (cookies, headers).
16
15
  */
@@ -18,27 +17,27 @@ const getStorageLocale = (context) => getLocaleFromStorageServer({
18
17
  getCookie: (name) => getCookie(context, name),
19
18
  getHeader: (name) => context.req.header(name)
20
19
  });
21
- const appNamespace = createNamespace("app");
22
- prepareIntlayer(configuration);
23
- const translateFunction = (context) => (content, locale) => {
24
- const currentLocale = context.get("locale");
25
- const defaultLocale = context.get("defaultLocale");
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 getTranslation(content, defaultLocale);
32
- }
33
- return getTranslation(content, targetLocale);
34
- };
20
+ /**
21
+ * Request-scoped Intlayer context.
22
+ *
23
+ * `AsyncLocalStorage` rather than `cls-hooked`: the latter relies on
24
+ * `async_hooks.createHook`, which Bun does not implement, and is several times
25
+ * slower on Node.
26
+ */
27
+ const intlayerStorage = new AsyncLocalStorage();
28
+ registerAmbientLocaleResolver(() => intlayerStorage.getStore()?.locale);
29
+ prepareIntlayerServer(getConfiguration(), { label: "hono-intlayer" });
30
+ /**
31
+ * Builds the translation function bound to the locale stored in the Hono context.
32
+ */
33
+ const translateFunction = (context) => (content, locale) => typeof content === "string" ? content : getTranslation(content, locale ?? context.get("locale"), internationalization.defaultLocale);
35
34
  /**
36
35
  * Hono middleware that detects the user's locale and populates context with Intlayer data.
37
36
  *
38
37
  * It performs:
39
38
  * 1. Locale detection from cookies, headers, or default settings.
40
39
  * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into the context.
41
- * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.
40
+ * 3. Sets up an `AsyncLocalStorage` context for accessing these functions anywhere in the request lifecycle.
42
41
  *
43
42
  * @returns A Hono middleware function.
44
43
  *
@@ -51,10 +50,9 @@ const translateFunction = (context) => (content, locale) => {
51
50
  * app.use('*', intlayer());
52
51
  * ```
53
52
  */
54
- const intlayer = () => async (context, next) => {
53
+ const intlayer = () => (context, next) => {
55
54
  const localeFromStorage = getStorageLocale(context);
56
- const negotiatorHeaders = context.req.header();
57
- const localeDetected = localeDetector(negotiatorHeaders, internationalization.locales, internationalization.defaultLocale);
55
+ const localeDetected = localeDetector({ "accept-language": context.req.header("accept-language") }, internationalization.locales, internationalization.defaultLocale);
58
56
  const locale = localeFromStorage ?? localeDetected;
59
57
  context.set("locale_storage", localeFromStorage);
60
58
  context.set("locale_detected", localeDetected);
@@ -66,15 +64,12 @@ const intlayer = () => async (context, next) => {
66
64
  context.set("t", t);
67
65
  context.set("getIntlayer", getIntlayer);
68
66
  context.set("getDictionary", getDictionary);
69
- return new Promise((resolve) => {
70
- appNamespace.run(async () => {
71
- appNamespace.set("t", t);
72
- appNamespace.set("getIntlayer", getIntlayer);
73
- appNamespace.set("getDictionary", getDictionary);
74
- await next();
75
- resolve();
76
- });
77
- });
67
+ return intlayerStorage.run({
68
+ locale,
69
+ t,
70
+ getIntlayer,
71
+ getDictionary
72
+ }, next);
78
73
  };
79
74
  /**
80
75
  * Translation function to retrieve content for the current locale.
@@ -99,34 +94,28 @@ const intlayer = () => async (context, next) => {
99
94
  * ```
100
95
  */
101
96
  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 \"hono-intlayer\" is not supported in your environment. Use the context instead.");
105
- return appNamespace.get("t")(content, locale);
106
- } catch (error) {
107
- debug(error.message);
97
+ const context = intlayerStorage.getStore();
98
+ if (!context) {
99
+ debug("Using the import { t } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.");
108
100
  return getTranslation(content, locale ?? internationalization.defaultLocale);
109
101
  }
102
+ return context.t(content, locale);
110
103
  };
111
104
  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 { getIntlayer } from \"hono-intlayer\" is not supported in your environment. Use the context instead.");
115
- return appNamespace.get("getIntlayer")(...args);
116
- } catch (error) {
117
- debug(error.message);
105
+ const context = intlayerStorage.getStore();
106
+ if (!context) {
107
+ debug("Using the import { getIntlayer } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.");
118
108
  return getIntlayer$1(...args);
119
109
  }
110
+ return context.getIntlayer(...args);
120
111
  };
121
112
  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 { getDictionary } from \"hono-intlayer\" is not supported in your environment. Use the context instead.");
125
- return appNamespace.get("getDictionary")(...args);
126
- } catch (error) {
127
- debug(error.message);
113
+ const context = intlayerStorage.getStore();
114
+ if (!context) {
115
+ debug("Using the import { getDictionary } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.");
128
116
  return getDictionary$1(...args);
129
117
  }
118
+ return context.getDictionary(...args);
130
119
  };
131
120
 
132
121
  //#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} from '@intlayer/core/interpreter';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport { prepareIntlayer } 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 { Context, MiddlewareHandler } from 'hono';\nimport { getCookie } from 'hono/cookie';\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, headers).\n */\nconst getStorageLocale = (context: Context): Locale | undefined =>\n getLocaleFromStorageServer({\n getCookie: (name: string) => getCookie(context, name),\n getHeader: (name: string) => context.req.header(name),\n });\n\nconst appNamespace = createNamespace('app');\n\nprepareIntlayer(configuration);\n\nexport const translateFunction =\n (context: Context) =>\n <T extends string>(\n content: StrictModeLocaleMap<T> | string,\n locale?: Locale\n ): T => {\n const currentLocale = context.get('locale') as Locale;\n const defaultLocale = context.get('defaultLocale') as Locale;\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 * Hono middleware that detects the user's locale and populates context 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 the context.\n * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.\n *\n * @returns A Hono middleware function.\n *\n * @example\n * ```ts\n * import { Hono } from 'hono';\n * import { intlayer } from 'hono-intlayer';\n *\n * const app = new Hono();\n * app.use('*', intlayer());\n * ```\n */\nexport const intlayer =\n (): MiddlewareHandler =>\n async (context: Context, next: () => Promise<void>) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(context);\n\n const negotiatorHeaders: Record<string, string> = context.req.header();\n\n const localeDetected = localeDetector(\n negotiatorHeaders,\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n const locale = localeFromStorage ?? localeDetected;\n\n context.set('locale_storage', localeFromStorage);\n context.set('locale_detected', localeDetected);\n context.set('locale', locale);\n context.set('defaultLocale', internationalization.defaultLocale);\n\n const t = translateFunction(context);\n\n const getIntlayer: typeof getIntlayerFunction = (\n key: Parameters<typeof getIntlayerFunction>[0],\n localeArg = locale as Parameters<typeof getIntlayerFunction>[1],\n ...props: any[]\n ) => getIntlayerFunction(key, localeArg, ...props);\n\n const getDictionary: typeof getDictionaryFunction = (\n key: Parameters<typeof getDictionaryFunction>[0],\n localeArg = locale as Parameters<typeof getDictionaryFunction>[1],\n ...props: any[]\n ) => getDictionaryFunction(key, localeArg, ...props);\n\n context.set('t', t);\n context.set('getIntlayer', getIntlayer);\n context.set('getDictionary', getDictionary);\n\n return new Promise<void>((resolve) => {\n appNamespace.run(async () => {\n appNamespace.set('t', t);\n appNamespace.set('getIntlayer', getIntlayer);\n appNamespace.set('getDictionary', getDictionary);\n\n await next();\n resolve();\n });\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 'hono-intlayer';\n *\n * app.get('/', (c) => {\n * const greeting = t({\n * en: 'Hello',\n * fr: 'Bonjour',\n * });\n * return c.text(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 \"hono-intlayer\" is not supported in your environment. Use the context 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 = (\n ...args: Parameters<typeof getIntlayerFunction>\n) => {\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 { getIntlayer } from \"hono-intlayer\" is not supported in your environment. Use the context 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 = (\n ...args: Parameters<typeof getDictionaryFunction>\n) => {\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 { getDictionary } from \"hono-intlayer\" is not supported in your environment. Use the context 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;AAG/B,SAAS,QAAgB,QAAQ,MAAM,GAAG;;;;AAM5C,MAAM,oBAAoB,YACxB,2BAA2B;CACzB,YAAY,SAAiB,UAAU,SAAS,IAAI;CACpD,YAAY,SAAiB,QAAQ,IAAI,OAAO,IAAI;AACtD,CAAC;AAEH,MAAM,eAAe,gBAAgB,KAAK;AAE1C,gBAAgB,aAAa;AAE7B,MAAa,qBACV,aAEC,SACA,WACM;CACN,MAAM,gBAAgB,QAAQ,IAAI,QAAQ;CAC1C,MAAM,gBAAgB,QAAQ,IAAI,eAAe;CAEjD,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,OAAO,eAAe,SAAS,aAAa;CAEhD;CAEA,OAAO,eAAe,SAAS,YAAY;AAC7C;;;;;;;;;;;;;;;;;;;;AAqBF,MAAa,iBAEX,OAAO,SAAkB,SAA8B;CAErD,MAAM,oBAAoB,iBAAiB,OAAO;CAElD,MAAM,oBAA4C,QAAQ,I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,MAAM,IAAI,MACR,wHACF;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,iBACX,GAAG,SACA;CACH,IAAI;EACF,IAAI,OAAO,iBAAiB,aAC1B,MAAM,IAAI,MACR,2GACF;EAGF,IAAI,OAAO,aAAa,IAAI,eAAe,MAAM,YAC/C,MAAM,IAAI,MACR,0HACF;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 { 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 { Context, MiddlewareHandler } from 'hono';\nimport { getCookie } from 'hono/cookie';\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 * Retrieves the locale from storage (cookies, headers).\n */\nconst getStorageLocale = (context: Context): Locale | undefined =>\n getLocaleFromStorageServer({\n getCookie: (name: string) => getCookie(context, name),\n getHeader: (name: string) => context.req.header(name),\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: 'hono-intlayer' });\n\n/**\n * Builds the translation function bound to the locale stored in the Hono context.\n */\nexport const translateFunction =\n (context: Context) =>\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 ?? (context.get('locale') as Locale),\n internationalization.defaultLocale\n );\n\n/**\n * Hono middleware that detects the user's locale and populates context 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 the context.\n * 3. Sets up an `AsyncLocalStorage` context for accessing these functions anywhere in the request lifecycle.\n *\n * @returns A Hono middleware function.\n *\n * @example\n * ```ts\n * import { Hono } from 'hono';\n * import { intlayer } from 'hono-intlayer';\n *\n * const app = new Hono();\n * app.use('*', intlayer());\n * ```\n */\nexport const intlayer =\n (): MiddlewareHandler => (context: Context, next: () => Promise<void>) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(context);\n\n const localeDetected = localeDetector(\n { 'accept-language': context.req.header('accept-language') },\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n const locale = localeFromStorage ?? localeDetected;\n\n context.set('locale_storage', localeFromStorage);\n context.set('locale_detected', localeDetected);\n context.set('locale', locale);\n context.set('defaultLocale', internationalization.defaultLocale);\n\n const t = translateFunction(context);\n\n const getIntlayer: typeof getIntlayerFunction = (\n key,\n localeArg = locale as typeof localeArg,\n ...props\n ) => getIntlayerFunction(key, localeArg, ...props);\n\n const getDictionary: typeof getDictionaryFunction = (\n key,\n localeArg = locale as typeof localeArg,\n ...props\n ) => getDictionaryFunction(key, localeArg, ...props);\n\n context.set('t', t);\n context.set('getIntlayer', getIntlayer);\n context.set('getDictionary', getDictionary);\n\n return 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 'hono-intlayer';\n *\n * app.get('/', (c) => {\n * const greeting = t({\n * en: 'Hello',\n * fr: 'Bonjour',\n * });\n * return c.text(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 \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context 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 = (\n ...args: Parameters<typeof getIntlayerFunction>\n) => {\n const context = intlayerStorage.getStore();\n\n if (!context) {\n debug(\n 'Using the import { getIntlayer } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.'\n );\n\n return getIntlayerFunction(...args);\n }\n\n return context.getIntlayer(...args);\n};\n\nexport const getDictionary: typeof getDictionaryFunction = (\n ...args: Parameters<typeof getDictionaryFunction>\n) => {\n const context = intlayerStorage.getStore();\n\n if (!context) {\n debug(\n 'Using the import { getDictionary } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.'\n );\n\n return getDictionaryFunction(...args);\n }\n\n return context.getDictionary(...args);\n};\n"],"mappings":";;;;;;;;;;AAkBA,IAAI,cAAyC,CAAC;AAE9C,6BAAgC,eAC9B,SAAS,QAAgB,QAAQ,MAAM,GAAG;;;;AAM5C,MAAM,oBAAoB,YACxB,2BAA2B;CACzB,YAAY,SAAiB,UAAU,SAAS,IAAI;CACpD,YAAY,SAAiB,QAAQ,IAAI,OAAO,IAAI;AACtD,CAAC;;;;;;;;AAmBH,MAAM,kBAAkB,IAAI,kBAA0C;AAItE,oCAAoC,gBAAgB,SAAS,CAAC,EAAE,MAAM;AAEtE,sBAAsB,iBAAiB,GAAG,EAAE,OAAO,gBAAgB,CAAC;;;;AAKpE,MAAa,qBACV,aAEC,SACA,WAEA,OAAO,YAAY,WACd,UACD,eACE,SACA,UAAW,QAAQ,IAAI,QAAQ,GAC/B,qBAAqB,aACvB;;;;;;;;;;;;;;;;;;;;AAqBR,MAAa,kBACe,SAAkB,SAA8B;CAExE,MAAM,oBAAoB,iBAAiB,OAAO;CAElD,MAAM,iBAAiB,eACrB,EAAE,mBAAmB,QAAQ,IAAI,OAAO,iBAAiB,EAAE,GAC3D,qBAAqB,SACrB,qBAAqB,aACvB;CAEA,MAAM,SAAS,qBAAqB;CAEpC,QAAQ,IAAI,kBAAkB,iBAAiB;CAC/C,QAAQ,IAAI,mBAAmB,cAAc;CAC7C,QAAQ,IAAI,UAAU,MAAM;CAC5B,QAAQ,IAAI,iBAAiB,qBAAqB,aAAa;CAE/D,MAAM,IAAI,kBAAkB,OAAO;CAEnC,MAAM,eACJ,KACA,YAAY,QACZ,GAAG,UACAA,cAAoB,KAAK,WAAW,GAAG,KAAK;CAEjD,MAAM,iBACJ,KACA,YAAY,QACZ,GAAG,UACAC,gBAAsB,KAAK,WAAW,GAAG,KAAK;CAEnD,QAAQ,IAAI,KAAK,CAAC;CAClB,QAAQ,IAAI,eAAe,WAAW;CACtC,QAAQ,IAAI,iBAAiB,aAAa;CAE1C,OAAO,gBAAgB,IAAI;EAAE;EAAQ;EAAG;EAAa;CAAc,GAAG,IAAI;AAC5E;;;;;;;;;;;;;;;;;;;;;;;AAwBF,MAAa,KACX,SACA,WACY;CACZ,MAAM,UAAU,gBAAgB,SAAS;CAEzC,IAAI,CAAC,SAAS;EACZ,MACE,qIACF;EAEA,OAAO,eACL,SACA,UAAU,qBAAqB,aACjC;CACF;CAEA,OAAO,QAAQ,EAAE,SAAwC,MAAM;AACjE;AAEA,MAAa,eACX,GAAG,SACA;CACH,MAAM,UAAU,gBAAgB,SAAS;CAEzC,IAAI,CAAC,SAAS;EACZ,MACE,+IACF;EAEA,OAAOD,cAAoB,GAAG,IAAI;CACpC;CAEA,OAAO,QAAQ,YAAY,GAAG,IAAI;AACpC;AAEA,MAAa,iBACX,GAAG,SACA;CACH,MAAM,UAAU,gBAAgB,SAAS;CAEzC,IAAI,CAAC,SAAS;EACZ,MACE,iJACF;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 { Context, MiddlewareHandler } from "hono";
5
5
  //#region src/index.d.ts
6
+ /**
7
+ * Builds the translation function bound to the locale stored in the Hono context.
8
+ */
6
9
  export declare const translateFunction: (context: Context) => <T extends string>(content: StrictModeLocaleMap<T> | string, locale?: Locale) => T;
7
10
  /**
8
11
  * Hono middleware that detects the user's locale and populates context with Intlayer data.
@@ -10,7 +13,7 @@ export declare const translateFunction: (context: Context) => <T extends string>
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 the context.
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 A Hono middleware function.
16
19
  *
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/index.ts"],"mappings":";;;;;qBAsCa,oBAAiB,SAClB,aACT,kBAAgB,SACN,oBAAoB,aAAW,SAC/B,WACR;;;;;;;;;;;;;;;;;;;;qBAoDQ,gBACP;;;;;;;;;;;;;;;;;;;;;;;qBAwEO,IAAK,kBAAgB,SACvB,oBAAoB,UAAQ,SAC5B,WACR;qBAyBU,oBAAoB;qBAwBpB,sBAAsB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/index.ts"],"mappings":";;;;;;;;qBA6Da,oBAAiB,SAClB,aACT,kBAAgB,SACN,oBAAoB,aAAW,SAC/B,WACR;;;;;;;;;;;;;;;;;;;;qBA4BQ,gBACP;;;;;;;;;;;;;;;;;;;;;;;qBA4DO,IAAK,kBAAgB,SACvB,oBAAoB,UAAQ,SAC5B,WACR;qBAiBU,oBAAoB;qBAgBpB,sBAAsB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hono-intlayer",
3
- "version": "9.5.11",
3
+ "version": "9.6.0",
4
4
  "private": false,
5
5
  "description": "Manage internationalization i18n in a simple way for hono application.",
6
6
  "keywords": [
@@ -76,14 +76,12 @@
76
76
  "typecheck": "tsc --noEmit --project tsconfig.types.json"
77
77
  },
78
78
  "dependencies": {
79
- "@intlayer/config": "9.5.11",
80
- "@intlayer/core": "9.5.11",
81
- "@intlayer/engine": "9.5.11",
82
- "@intlayer/types": "9.5.11",
83
- "cls-hooked": "4.2.2"
79
+ "@intlayer/config": "9.6.0",
80
+ "@intlayer/core": "9.6.0",
81
+ "@intlayer/engine": "9.6.0",
82
+ "@intlayer/types": "9.6.0"
84
83
  },
85
84
  "devDependencies": {
86
- "@types/cls-hooked": "4.3.9",
87
85
  "@types/node": "^22",
88
86
  "@utils/ts-config": "1.0.4",
89
87
  "@utils/ts-config-types": "1.0.4",
@@ -92,7 +90,7 @@
92
90
  "rimraf": "6.1.3",
93
91
  "tsdown": "0.23.0",
94
92
  "typescript": "7.0.2",
95
- "vitest": "5.0.2"
93
+ "vitest": "5.0.3"
96
94
  },
97
95
  "engines": {
98
96
  "node": ">=14.18"