@intlayer/i18next 9.0.0-canary.16 → 9.0.0-canary.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/createInstance.mjs +2 -1
- package/dist/esm/createInstance.mjs.map +1 -1
- package/dist/esm/resolveTranslation.mjs +1 -1
- package/dist/esm/resolveTranslation.mjs.map +1 -1
- package/dist/types/createInstance.d.ts +0 -1
- package/dist/types/createInstance.d.ts.map +1 -1
- package/dist/types/getDictionary.d.ts +0 -1
- package/dist/types/getDictionary.d.ts.map +1 -1
- package/dist/types/getDictionaryDynamic.d.ts +0 -1
- package/dist/types/getDictionaryDynamic.d.ts.map +1 -1
- package/dist/types/index.d.ts +0 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/plugin/index.d.ts +0 -1
- package/dist/types/plugin/index.d.ts.map +1 -1
- package/dist/types/resolveTranslation.d.ts +14 -17
- package/dist/types/resolveTranslation.d.ts.map +1 -1
- package/dist/types/typedTranslation.d.ts +9 -6
- package/dist/types/typedTranslation.d.ts.map +1 -1
- package/package.json +12 -12
|
@@ -132,7 +132,8 @@ const createInstance = (instanceOptions = {}) => {
|
|
|
132
132
|
const fixedLng = Array.isArray(lng) ? lng[0] ?? currentLanguage : lng ?? currentLanguage;
|
|
133
133
|
const fixedNS = ns ?? defaultNS;
|
|
134
134
|
return (key, opts) => {
|
|
135
|
-
|
|
135
|
+
const fullKey = keyPrefix ? `${keyPrefix}.${key}` : key;
|
|
136
|
+
return resolveKey(fixedLng, fixedNS, fullKey, opts);
|
|
136
137
|
};
|
|
137
138
|
}),
|
|
138
139
|
use(module) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createInstance.mjs","names":[],"sources":["../../src/createInstance.ts"],"sourcesContent":["import { internationalization, log } from '@intlayer/config/built';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport { getIntlayer } from '@intlayer/core/interpreter';\nimport { navigatePath, resolveMessage } from '@intlayer/core/messageFormat';\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type {\n createInstance as _createInstance,\n i18n as I18nInterface,\n InitOptions,\n TOptions,\n} from 'i18next';\nimport {\n getInterpolationValues,\n resolveTranslation,\n} from './resolveTranslation';\nimport type { TypedGetFixedT } from './typedTranslation';\n\nexport type { TypedGetFixedT } from './typedTranslation';\n\ntype EventHandler = (...args: unknown[]) => void;\n\nconst warnIgnoredResources = (location: string) => {\n const appLogger = getAppLogger({ log });\n appLogger(\n `${colorize(location, ANSIColors.CYAN)}: the ${colorize('`resources`', ANSIColors.CYAN)} option is ignored when using ${colorize('@intlayer/i18next', ANSIColors.MAGENTA)} — translations are served from the compiled intlayer dictionaries instead. Remove the resource imports and the ${colorize('`resources`', ANSIColors.CYAN)} option to reduce your bundle size.`\n );\n};\n\nexport const createInstance: typeof _createInstance = (\n instanceOptions: InitOptions = {}\n): I18nInterface => {\n if ((instanceOptions as Record<string, unknown>).resources !== undefined) {\n warnIgnoredResources('createInstance');\n }\n\n const config = internationalization;\n\n let currentLanguage: string =\n (instanceOptions.lng as string) ?? config?.defaultLocale ?? 'en';\n\n let defaultNS: string =\n (instanceOptions.defaultNS as string) ??\n (Array.isArray(instanceOptions.ns)\n ? (instanceOptions.ns[0] as string)\n : (instanceOptions.ns as string)) ??\n 'translation';\n\n const listeners = new Map<string, Set<EventHandler>>();\n let initialized = false;\n\n const emit = (event: string, ...args: unknown[]) => {\n listeners.get(event)?.forEach((h) => {\n h(...args);\n });\n };\n\n const getSeparators = () => ({\n keySeparator:\n (instanceOptions.keySeparator as string | false | undefined) ?? '.',\n nsSeparator:\n (instanceOptions.nsSeparator as string | false | undefined) ?? ':',\n });\n\n /**\n * Resolves a key through the full i18next pipeline (namespace prefix,\n * `ns` option, plural/context suffixes, `$t()` nesting, interpolation).\n * Falls back to the interpolated `defaultValue`, then to the key itself.\n */\n const resolveKey = (\n lang: string,\n ns: string,\n key: string,\n opts?: TOptions | string\n ): string => {\n const options =\n typeof opts === 'string' ? { defaultValue: opts } : (opts as TOptions);\n\n const resolved = resolveTranslation({\n locale: lang as LocalesValues,\n namespace: ns,\n key,\n options,\n ...getSeparators(),\n });\n\n if (resolved !== undefined) return resolved as string;\n\n const defaultValue = (options as Record<string, unknown> | undefined)\n ?.defaultValue;\n if (typeof defaultValue === 'string') {\n return resolveMessage(\n defaultValue,\n getInterpolationValues(options),\n lang as LocalesValues,\n 'i18next'\n );\n }\n\n return key;\n };\n\n const instance = {\n get language() {\n return currentLanguage;\n },\n get languages() {\n return (config?.locales?.map(String) ?? [\n currentLanguage,\n ]) as readonly string[];\n },\n get resolvedLanguage() {\n return currentLanguage;\n },\n get isInitialized() {\n return initialized;\n },\n isInitializing: false,\n initializedStoreOnce: false,\n initializedLanguageOnce: false,\n options: instanceOptions,\n modules: {} as I18nInterface['modules'],\n services: {} as I18nInterface['services'],\n store: {} as I18nInterface['store'],\n format: ((value: unknown) => String(value)) as I18nInterface['format'],\n\n async init(optionsOrCb?: unknown, cb?: unknown) {\n const opts =\n typeof optionsOrCb === 'function'\n ? {}\n : ((optionsOrCb ?? {}) as Record<string, unknown>);\n if (opts.resources !== undefined) {\n warnIgnoredResources('i18next.init');\n }\n if (opts.lng) currentLanguage = opts.lng as string;\n if (opts.defaultNS) defaultNS = opts.defaultNS as string;\n else if (opts.ns)\n defaultNS = Array.isArray(opts.ns)\n ? (opts.ns[0] as string)\n : (opts.ns as string);\n initialized = true;\n emit('initialized', opts);\n const t = instance.t.bind(instance);\n const callback = typeof optionsOrCb === 'function' ? optionsOrCb : cb;\n (callback as ((err: unknown, t: unknown) => void) | undefined)?.(null, t);\n return t as unknown as Promise<I18nInterface['t']>;\n },\n\n t(\n key: unknown,\n optionsOrDefaultValue?: unknown,\n extraOpts?: unknown\n ): unknown {\n const options =\n typeof optionsOrDefaultValue === 'string'\n ? {\n defaultValue: optionsOrDefaultValue,\n ...((extraOpts ?? {}) as Record<string, unknown>),\n }\n : (optionsOrDefaultValue as TOptions | undefined);\n const keys: string[] = Array.isArray(key)\n ? (key as string[])\n : [String(key)];\n for (const candidateKey of keys) {\n const result = resolveTranslation({\n locale: currentLanguage as LocalesValues,\n namespace: defaultNS,\n key: candidateKey,\n options,\n ...getSeparators(),\n });\n if (result !== undefined) return result;\n }\n\n const defaultValue = (options as Record<string, unknown> | undefined)\n ?.defaultValue;\n if (typeof defaultValue === 'string') {\n return resolveMessage(\n defaultValue,\n getInterpolationValues(options),\n currentLanguage as LocalesValues,\n 'i18next'\n );\n }\n\n return defaultValue ?? (Array.isArray(key) ? key[key.length - 1] : key);\n },\n\n async changeLanguage(lng?: string, cb?: unknown) {\n const prev = currentLanguage;\n if (lng) currentLanguage = lng;\n emit('languageChanged', currentLanguage, prev);\n const t = instance.t.bind(instance);\n (cb as ((err: unknown, t: unknown) => void) | undefined)?.(null, t);\n return t as unknown as Promise<I18nInterface['t']>;\n },\n\n exists(key: string, options?: unknown): boolean {\n return (\n resolveTranslation({\n locale: currentLanguage as LocalesValues,\n namespace: defaultNS,\n key,\n options: options as TOptions,\n ...getSeparators(),\n }) !== undefined\n );\n },\n\n /**\n * Returns a `t()` function bound to a fixed locale and namespace.\n * When `ns` matches a registered intlayer dictionary key, the returned\n * function's `key` parameter is typed to only accept valid dot-notation\n * paths for that dictionary, and its return type is resolved from the\n * content at that path. With a `keyPrefix`, keys are relative dot-paths\n * under the prefix.\n *\n * @example\n * ```ts\n * const tAbout = i18n.getFixedT(null, 'about');\n * tAbout('counter.label'); // ✓ typed key and return value\n * ```\n */\n getFixedT: ((\n lng: string | readonly string[] | null,\n ns?: string | null,\n keyPrefix?: string\n ) => {\n const fixedLng = Array.isArray(lng)\n ? ((lng[0] as string) ?? currentLanguage)\n : ((lng as string) ?? currentLanguage);\n const fixedNS = ns ?? defaultNS;\n return (key: string, opts?: TOptions): string => {\n const fullKey = keyPrefix ? `${keyPrefix}.${key}` : key;\n return resolveKey(fixedLng, fixedNS, fullKey, opts);\n };\n }) as TypedGetFixedT,\n\n use(module: unknown) {\n (module as { init?: (i18n: I18nInterface) => void })?.init?.(\n instance as unknown as I18nInterface\n );\n return instance as unknown as I18nInterface;\n },\n\n on(event: string, handler: EventHandler) {\n if (!listeners.has(event)) listeners.set(event, new Set());\n listeners.get(event)!.add(handler);\n return instance as unknown as I18nInterface;\n },\n\n once(event: string, handler: EventHandler) {\n const wrapper: EventHandler = (...args) => {\n handler(...args);\n instance.off(event, wrapper);\n };\n instance.on(event, wrapper);\n return instance as unknown as I18nInterface;\n },\n\n off(event: string, handler?: EventHandler) {\n if (!handler) listeners.delete(event);\n else listeners.get(event)?.delete(handler);\n },\n\n emit(eventName: string, ...args: unknown[]) {\n emit(eventName, ...args);\n },\n\n createInstance(opts?: InitOptions, _cb?: unknown) {\n return createInstance({ ...instanceOptions, ...opts });\n },\n\n cloneInstance(opts?: Record<string, unknown>, _cb?: unknown) {\n return createInstance({ ...instanceOptions, ...opts });\n },\n\n dir(lng?: string): 'ltr' | 'rtl' {\n const rtl = ['ar', 'he', 'fa', 'ur', 'ps', 'yi', 'dv', 'ug'];\n return rtl.some((l) => (lng ?? currentLanguage).startsWith(l))\n ? 'rtl'\n : 'ltr';\n },\n\n setDefaultNamespace(ns: string) {\n defaultNS = ns;\n },\n\n hasLoadedNamespace(ns: string | readonly string[]): boolean {\n try {\n getIntlayer(\n (Array.isArray(ns) ? ns[0] : ns) as DictionaryKeys,\n currentLanguage as LocalesValues\n );\n return true;\n } catch {\n return false;\n }\n },\n\n async loadNamespaces(_ns: unknown) {},\n async loadLanguages(_lngs: unknown) {},\n loadResources(_cb?: unknown) {},\n async reloadResources() {},\n\n getDataByLanguage(_lng: string) {\n return undefined;\n },\n\n getResource(lng: string, ns: string, key: string): unknown {\n try {\n return navigatePath(\n getIntlayer(ns as DictionaryKeys, lng as LocalesValues),\n key\n );\n } catch {\n return undefined;\n }\n },\n\n addResource: () => instance as unknown as I18nInterface,\n addResources: () => instance as unknown as I18nInterface,\n addResourceBundle: () => instance as unknown as I18nInterface,\n hasResourceBundle: () => false,\n getResourceBundle: () => undefined,\n removeResourceBundle: () => instance as unknown as I18nInterface,\n\n toJSON() {\n return {\n options: instanceOptions,\n store: {} as I18nInterface['store'],\n language: currentLanguage,\n languages: (config?.locales?.map(String) ?? [\n currentLanguage,\n ]) as readonly string[],\n resolvedLanguage: currentLanguage,\n };\n },\n };\n\n return instance as unknown as I18nInterface;\n};\n"],"mappings":";;;;;;;;AAyBA,MAAM,wBAAwB,aAAqB;CAEjD,AADkB,aAAa,EAAE,IAAI,CAC7B,CAAC,CACP,GAAG,SAAS,UAAU,WAAW,IAAI,EAAE,QAAQ,SAAS,eAAe,WAAW,IAAI,EAAE,gCAAgC,SAAS,qBAAqB,WAAW,OAAO,EAAE,kHAAkH,SAAS,eAAe,WAAW,IAAI,EAAE,oCACvU;AACF;AAEA,MAAa,kBACX,kBAA+B,CAAC,MACd;CAClB,IAAK,gBAA4C,cAAc,QAC7D,qBAAqB,gBAAgB;CAGvC,MAAM,SAAS;CAEf,IAAI,kBACD,gBAAgB,OAAkB,QAAQ,iBAAiB;CAE9D,IAAI,YACD,gBAAgB,cAChB,MAAM,QAAQ,gBAAgB,EAAE,IAC5B,gBAAgB,GAAG,KACnB,gBAAgB,OACrB;CAEF,MAAM,4BAAY,IAAI,IAA+B;CACrD,IAAI,cAAc;CAElB,MAAM,QAAQ,OAAe,GAAG,SAAoB;EAClD,UAAU,IAAI,KAAK,CAAC,EAAE,SAAS,MAAM;GACnC,EAAE,GAAG,IAAI;EACX,CAAC;CACH;CAEA,MAAM,uBAAuB;EAC3B,cACG,gBAAgB,gBAA+C;EAClE,aACG,gBAAgB,eAA8C;CACnE;;;;;;CAOA,MAAM,cACJ,MACA,IACA,KACA,SACW;EACX,MAAM,UACJ,OAAO,SAAS,WAAW,EAAE,cAAc,KAAK,IAAK;EAEvD,MAAM,WAAW,mBAAmB;GAClC,QAAQ;GACR,WAAW;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ACT"}
|
|
1
|
+
{"version":3,"file":"createInstance.mjs","names":[],"sources":["../../src/createInstance.ts"],"sourcesContent":["import { internationalization, log } from '@intlayer/config/built';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport { getIntlayer } from '@intlayer/core/interpreter';\nimport { navigatePath, resolveMessage } from '@intlayer/core/messageFormat';\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type {\n createInstance as _createInstance,\n i18n as I18nInterface,\n InitOptions,\n TOptions,\n} from 'i18next';\nimport {\n getInterpolationValues,\n resolveTranslation,\n} from './resolveTranslation';\nimport type { TypedGetFixedT } from './typedTranslation';\n\nexport type { TypedGetFixedT } from './typedTranslation';\n\ntype EventHandler = (...args: unknown[]) => void;\n\nconst warnIgnoredResources = (location: string) => {\n const appLogger = getAppLogger({ log });\n appLogger(\n `${colorize(location, ANSIColors.CYAN)}: the ${colorize('`resources`', ANSIColors.CYAN)} option is ignored when using ${colorize('@intlayer/i18next', ANSIColors.MAGENTA)} — translations are served from the compiled intlayer dictionaries instead. Remove the resource imports and the ${colorize('`resources`', ANSIColors.CYAN)} option to reduce your bundle size.`\n );\n};\n\nexport const createInstance: typeof _createInstance = (\n instanceOptions: InitOptions = {}\n): I18nInterface => {\n if ((instanceOptions as Record<string, unknown>).resources !== undefined) {\n warnIgnoredResources('createInstance');\n }\n\n const config = internationalization;\n\n let currentLanguage: string =\n (instanceOptions.lng as string) ?? config?.defaultLocale ?? 'en';\n\n let defaultNS: string =\n (instanceOptions.defaultNS as string) ??\n (Array.isArray(instanceOptions.ns)\n ? (instanceOptions.ns[0] as string)\n : (instanceOptions.ns as string)) ??\n 'translation';\n\n const listeners = new Map<string, Set<EventHandler>>();\n let initialized = false;\n\n const emit = (event: string, ...args: unknown[]) => {\n listeners.get(event)?.forEach((h) => {\n h(...args);\n });\n };\n\n const getSeparators = () => ({\n keySeparator:\n (instanceOptions.keySeparator as string | false | undefined) ?? '.',\n nsSeparator:\n (instanceOptions.nsSeparator as string | false | undefined) ?? ':',\n });\n\n /**\n * Resolves a key through the full i18next pipeline (namespace prefix,\n * `ns` option, plural/context suffixes, `$t()` nesting, interpolation).\n * Falls back to the interpolated `defaultValue`, then to the key itself.\n */\n const resolveKey = (\n lang: string,\n ns: string,\n key: string,\n opts?: TOptions | string\n ): string => {\n const options =\n typeof opts === 'string' ? { defaultValue: opts } : (opts as TOptions);\n\n const resolved = resolveTranslation({\n locale: lang as LocalesValues,\n namespace: ns,\n key,\n options,\n ...getSeparators(),\n });\n\n if (resolved !== undefined) return resolved as string;\n\n const defaultValue = (options as Record<string, unknown> | undefined)\n ?.defaultValue;\n if (typeof defaultValue === 'string') {\n return resolveMessage(\n defaultValue,\n getInterpolationValues(options),\n lang as LocalesValues,\n 'i18next'\n );\n }\n\n return key;\n };\n\n const instance = {\n get language() {\n return currentLanguage;\n },\n get languages() {\n return (config?.locales?.map(String) ?? [\n currentLanguage,\n ]) as readonly string[];\n },\n get resolvedLanguage() {\n return currentLanguage;\n },\n get isInitialized() {\n return initialized;\n },\n isInitializing: false,\n initializedStoreOnce: false,\n initializedLanguageOnce: false,\n options: instanceOptions,\n modules: {} as I18nInterface['modules'],\n services: {} as I18nInterface['services'],\n store: {} as I18nInterface['store'],\n format: ((value: unknown) => String(value)) as I18nInterface['format'],\n\n async init(optionsOrCb?: unknown, cb?: unknown) {\n const opts =\n typeof optionsOrCb === 'function'\n ? {}\n : ((optionsOrCb ?? {}) as Record<string, unknown>);\n if (opts.resources !== undefined) {\n warnIgnoredResources('i18next.init');\n }\n if (opts.lng) currentLanguage = opts.lng as string;\n if (opts.defaultNS) defaultNS = opts.defaultNS as string;\n else if (opts.ns)\n defaultNS = Array.isArray(opts.ns)\n ? (opts.ns[0] as string)\n : (opts.ns as string);\n initialized = true;\n emit('initialized', opts);\n const t = instance.t.bind(instance);\n const callback = typeof optionsOrCb === 'function' ? optionsOrCb : cb;\n (callback as ((err: unknown, t: unknown) => void) | undefined)?.(null, t);\n return t as unknown as Promise<I18nInterface['t']>;\n },\n\n t(\n key: unknown,\n optionsOrDefaultValue?: unknown,\n extraOpts?: unknown\n ): unknown {\n const options =\n typeof optionsOrDefaultValue === 'string'\n ? {\n defaultValue: optionsOrDefaultValue,\n ...((extraOpts ?? {}) as Record<string, unknown>),\n }\n : (optionsOrDefaultValue as TOptions | undefined);\n const keys: string[] = Array.isArray(key)\n ? (key as string[])\n : [String(key)];\n for (const candidateKey of keys) {\n const result = resolveTranslation({\n locale: currentLanguage as LocalesValues,\n namespace: defaultNS,\n key: candidateKey,\n options,\n ...getSeparators(),\n });\n if (result !== undefined) return result;\n }\n\n const defaultValue = (options as Record<string, unknown> | undefined)\n ?.defaultValue;\n if (typeof defaultValue === 'string') {\n return resolveMessage(\n defaultValue,\n getInterpolationValues(options),\n currentLanguage as LocalesValues,\n 'i18next'\n );\n }\n\n return defaultValue ?? (Array.isArray(key) ? key[key.length - 1] : key);\n },\n\n async changeLanguage(lng?: string, cb?: unknown) {\n const prev = currentLanguage;\n if (lng) currentLanguage = lng;\n emit('languageChanged', currentLanguage, prev);\n const t = instance.t.bind(instance);\n (cb as ((err: unknown, t: unknown) => void) | undefined)?.(null, t);\n return t as unknown as Promise<I18nInterface['t']>;\n },\n\n exists(key: string, options?: unknown): boolean {\n return (\n resolveTranslation({\n locale: currentLanguage as LocalesValues,\n namespace: defaultNS,\n key,\n options: options as TOptions,\n ...getSeparators(),\n }) !== undefined\n );\n },\n\n /**\n * Returns a `t()` function bound to a fixed locale and namespace.\n * When `ns` matches a registered intlayer dictionary key, the returned\n * function's `key` parameter is typed to only accept valid dot-notation\n * paths for that dictionary, and its return type is resolved from the\n * content at that path. With a `keyPrefix`, keys are relative dot-paths\n * under the prefix.\n *\n * @example\n * ```ts\n * const tAbout = i18n.getFixedT(null, 'about');\n * tAbout('counter.label'); // ✓ typed key and return value\n * ```\n */\n getFixedT: ((\n lng: string | readonly string[] | null,\n ns?: string | null,\n keyPrefix?: string\n ) => {\n const fixedLng = Array.isArray(lng)\n ? ((lng[0] as string) ?? currentLanguage)\n : ((lng as string) ?? currentLanguage);\n const fixedNS = ns ?? defaultNS;\n return (key: string, opts?: TOptions): string => {\n const fullKey = keyPrefix ? `${keyPrefix}.${key}` : key;\n return resolveKey(fixedLng, fixedNS, fullKey, opts);\n };\n }) as TypedGetFixedT,\n\n use(module: unknown) {\n (module as { init?: (i18n: I18nInterface) => void })?.init?.(\n instance as unknown as I18nInterface\n );\n return instance as unknown as I18nInterface;\n },\n\n on(event: string, handler: EventHandler) {\n if (!listeners.has(event)) listeners.set(event, new Set());\n listeners.get(event)!.add(handler);\n return instance as unknown as I18nInterface;\n },\n\n once(event: string, handler: EventHandler) {\n const wrapper: EventHandler = (...args) => {\n handler(...args);\n instance.off(event, wrapper);\n };\n instance.on(event, wrapper);\n return instance as unknown as I18nInterface;\n },\n\n off(event: string, handler?: EventHandler) {\n if (!handler) listeners.delete(event);\n else listeners.get(event)?.delete(handler);\n },\n\n emit(eventName: string, ...args: unknown[]) {\n emit(eventName, ...args);\n },\n\n createInstance(opts?: InitOptions, _cb?: unknown) {\n return createInstance({ ...instanceOptions, ...opts });\n },\n\n cloneInstance(opts?: Record<string, unknown>, _cb?: unknown) {\n return createInstance({ ...instanceOptions, ...opts });\n },\n\n dir(lng?: string): 'ltr' | 'rtl' {\n const rtl = ['ar', 'he', 'fa', 'ur', 'ps', 'yi', 'dv', 'ug'];\n return rtl.some((l) => (lng ?? currentLanguage).startsWith(l))\n ? 'rtl'\n : 'ltr';\n },\n\n setDefaultNamespace(ns: string) {\n defaultNS = ns;\n },\n\n hasLoadedNamespace(ns: string | readonly string[]): boolean {\n try {\n getIntlayer(\n (Array.isArray(ns) ? ns[0] : ns) as DictionaryKeys,\n currentLanguage as LocalesValues\n );\n return true;\n } catch {\n return false;\n }\n },\n\n async loadNamespaces(_ns: unknown) {},\n async loadLanguages(_lngs: unknown) {},\n loadResources(_cb?: unknown) {},\n async reloadResources() {},\n\n getDataByLanguage(_lng: string) {\n return undefined;\n },\n\n getResource(lng: string, ns: string, key: string): unknown {\n try {\n return navigatePath(\n getIntlayer(ns as DictionaryKeys, lng as LocalesValues),\n key\n );\n } catch {\n return undefined;\n }\n },\n\n addResource: () => instance as unknown as I18nInterface,\n addResources: () => instance as unknown as I18nInterface,\n addResourceBundle: () => instance as unknown as I18nInterface,\n hasResourceBundle: () => false,\n getResourceBundle: () => undefined,\n removeResourceBundle: () => instance as unknown as I18nInterface,\n\n toJSON() {\n return {\n options: instanceOptions,\n store: {} as I18nInterface['store'],\n language: currentLanguage,\n languages: (config?.locales?.map(String) ?? [\n currentLanguage,\n ]) as readonly string[],\n resolvedLanguage: currentLanguage,\n };\n },\n };\n\n return instance as unknown as I18nInterface;\n};\n"],"mappings":";;;;;;;;AAyBA,MAAM,wBAAwB,aAAqB;CAEjD,AADkB,aAAa,EAAE,IAAI,CAC7B,CAAC,CACP,GAAG,SAAS,UAAU,WAAW,IAAI,EAAE,QAAQ,SAAS,eAAe,WAAW,IAAI,EAAE,gCAAgC,SAAS,qBAAqB,WAAW,OAAO,EAAE,kHAAkH,SAAS,eAAe,WAAW,IAAI,EAAE,oCACvU;AACF;AAEA,MAAa,kBACX,kBAA+B,CAAC,MACd;CAClB,IAAK,gBAA4C,cAAc,QAC7D,qBAAqB,gBAAgB;CAGvC,MAAM,SAAS;CAEf,IAAI,kBACD,gBAAgB,OAAkB,QAAQ,iBAAiB;CAE9D,IAAI,YACD,gBAAgB,cAChB,MAAM,QAAQ,gBAAgB,EAAE,IAC5B,gBAAgB,GAAG,KACnB,gBAAgB,OACrB;CAEF,MAAM,4BAAY,IAAI,IAA+B;CACrD,IAAI,cAAc;CAElB,MAAM,QAAQ,OAAe,GAAG,SAAoB;EAClD,UAAU,IAAI,KAAK,CAAC,EAAE,SAAS,MAAM;GACnC,EAAE,GAAG,IAAI;EACX,CAAC;CACH;CAEA,MAAM,uBAAuB;EAC3B,cACG,gBAAgB,g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B,yBAAyB;EACzB,yBAAyB;EACzB,yBAAyB;EACzB,4BAA4B;EAE5B,SAAS;GACP,OAAO;IACL,SAAS;IACT,OAAO,CAAC;IACR,UAAU;IACV,WAAY,QAAQ,SAAS,IAAI,MAAM,KAAK,CAC1C,eACF;IACA,kBAAkB;GACpB;EACF;CACF;CAEA,OAAO;AACT"}
|
|
@@ -15,7 +15,7 @@ import { getDictionaries } from "@intlayer/dictionaries-entry";
|
|
|
15
15
|
* (`useTranslation`, `<Trans>`).
|
|
16
16
|
*/
|
|
17
17
|
/** Option keys that are control flags, never interpolation values. */
|
|
18
|
-
const CONTROL_OPTION_KEYS = new Set([
|
|
18
|
+
const CONTROL_OPTION_KEYS = /* @__PURE__ */ new Set([
|
|
19
19
|
"defaultValue",
|
|
20
20
|
"ns",
|
|
21
21
|
"lng",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolveTranslation.mjs","names":[],"sources":["../../src/resolveTranslation.ts"],"sourcesContent":["import { getIntlayer } from '@intlayer/core/interpreter';\nimport {\n type MessageValues,\n navigatePath,\n resolveMessage,\n} from '@intlayer/core/messageFormat';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type { TOptions } from 'i18next';\n\n/**\n * Shared i18next-dialect translation resolution.\n *\n * Implements the i18next lookup pipeline on top of intlayer dictionaries:\n * namespace prefix (`ns:key`), `ns` option override, plural suffixes\n * (`key_one`, `key_other`, …) via `Intl.PluralRules`, context suffixes\n * (`key_male`), `$t()` nesting, `defaultValue` and `{{var}}` interpolation.\n *\n * Used by `@intlayer/i18next` (instance `t`) and `@intlayer/react-i18next`\n * (`useTranslation`, `<Trans>`).\n */\n\n/** Option keys that are control flags, never interpolation values. */\nconst CONTROL_OPTION_KEYS = new Set([\n 'defaultValue',\n 'ns',\n 'lng',\n 'lngs',\n 'fallbackLng',\n 'returnObjects',\n 'returnDetails',\n 'keySeparator',\n 'nsSeparator',\n 'ordinal',\n 'postProcess',\n 'postProcessPassResolved',\n 'interpolation',\n 'replace',\n 'joinArrays',\n 'nsMode',\n 'keyPrefix',\n]);\n\n/** Maximum `$t()` nesting recursion depth. */\nconst MAX_NESTING_DEPTH = 5;\n\n/**\n * Canonical key of the single dictionary produced when a JSON source pattern\n * has no `{{key}}` segment (one file holds the whole namespace, e.g.\n * `./src/i18n/{{locale}}.json`). Used as the fallback namespace so i18next's\n * default `translation` namespace resolves against the whole-file dictionary.\n */\nconst ROOT_DICTIONARY_KEY = 'index';\n\n/**\n * Reads a dictionary from the runtime registry, returning `undefined` when the\n * namespace is not a registered dictionary.\n *\n * `getIntlayer` never throws for a missing key — in development it returns a\n * path-stringifying fallback proxy — so a plain `getIntlayer` call cannot tell\n * \"missing namespace\" apart from \"resolved content\". The registry membership\n * check makes the distinction explicit before resolving.\n */\nconst getDictionaryOrUndefined = (\n namespace: DictionaryKeys,\n locale: LocalesValues\n): unknown => {\n if (!(namespace in getDictionaries())) return undefined;\n\n return getIntlayer(namespace, locale);\n};\n\n/**\n * Builds the ordered list of key candidates following i18next's resolution\n * order: context + plural → context → plural → exact key.\n */\nconst buildKeyCandidates = (\n path: string,\n locale: string,\n count: number | undefined,\n context: string | undefined,\n ordinal: boolean\n): string[] => {\n const candidates: string[] = [];\n\n const pluralCategory =\n count === undefined\n ? undefined\n : new Intl.PluralRules(locale, {\n type: ordinal ? 'ordinal' : 'cardinal',\n }).select(count);\n\n if (context) {\n if (pluralCategory) {\n if (ordinal) {\n candidates.push(`${path}_${context}_ordinal_${pluralCategory}`);\n }\n candidates.push(`${path}_${context}_${pluralCategory}`);\n if (count !== 1) candidates.push(`${path}_${context}_plural`);\n }\n candidates.push(`${path}_${context}`);\n }\n\n if (pluralCategory) {\n if (ordinal) candidates.push(`${path}_ordinal_${pluralCategory}`);\n candidates.push(`${path}_${pluralCategory}`);\n // Legacy i18next v3 JSON suffix\n if (count !== 1) candidates.push(`${path}_plural`);\n }\n\n candidates.push(path);\n\n return candidates;\n};\n\n/** Extracts interpolation values from i18next `t()` options. */\nexport const getInterpolationValues = (options?: TOptions): MessageValues => {\n if (!options || typeof options !== 'object') return {};\n\n const replace = (options as { replace?: MessageValues }).replace;\n if (replace) {\n // `count` and `context` are always interpolatable, even with `replace`\n const values: MessageValues = { ...replace };\n if (options.count !== undefined) values.count ??= options.count;\n if (options.context !== undefined) values.context ??= options.context;\n return values;\n }\n\n const values: MessageValues = {};\n for (const [optionKey, optionValue] of Object.entries(options)) {\n if (!CONTROL_OPTION_KEYS.has(optionKey)) values[optionKey] = optionValue;\n }\n return values;\n};\n\nexport type ResolveTranslationParams = {\n /** Locale to resolve against. */\n locale: LocalesValues;\n /** Default namespace (dictionary key) when the key has no `ns:` prefix. */\n namespace: string;\n /** The translation key, possibly `ns:path.to.key`. */\n key: string;\n /** i18next `t()` options (interpolation values, count, context, …). */\n options?: TOptions;\n /** Custom key separator (`init({ keySeparator })`). */\n keySeparator?: string | false;\n /** Custom namespace separator (`init({ nsSeparator })`). */\n nsSeparator?: string | false;\n /** Internal `$t()` nesting recursion depth. */\n depth?: number;\n /**\n * Pre-resolved content of the `namespace` dictionary for `locale`.\n *\n * Supplied by the build-optimized `useDictionary` / `getDictionary`\n * variants, where the dictionary is imported at build time instead of read\n * from the runtime registry. Only used when the call resolves to the\n * default `namespace` without a locale override — cross-namespace\n * (`other:key`, `{ ns }`) and `{ lng }` lookups still go through\n * `getIntlayer`.\n */\n dictionaryContent?: unknown;\n};\n\n/**\n * Resolves a single translation key the i18next way against intlayer\n * dictionaries.\n *\n * Returns the resolved value: a string in the common case, or an\n * object/array when `returnObjects: true`. Returns `undefined` when the key\n * cannot be resolved (caller decides between `defaultValue`, fallback keys\n * and key echo).\n */\nexport const resolveTranslation = ({\n locale,\n namespace,\n key,\n options,\n keySeparator = '.',\n nsSeparator = ':',\n depth = 0,\n dictionaryContent,\n}: ResolveTranslationParams): unknown => {\n // Namespace resolution: `ns:` prefix > `ns` option > default namespace\n let targetNamespace = namespace;\n let path = key;\n\n if (nsSeparator !== false && key.includes(nsSeparator)) {\n const separatorIndex = key.indexOf(nsSeparator);\n targetNamespace = key.slice(0, separatorIndex);\n path = key.slice(separatorIndex + nsSeparator.length);\n } else if (options?.ns) {\n targetNamespace = Array.isArray(options.ns)\n ? (options.ns[0] as string)\n : (options.ns as string);\n }\n\n const count = typeof options?.count === 'number' ? options.count : undefined;\n const context =\n options?.context !== undefined ? String(options.context) : undefined;\n const ordinal = options?.ordinal === true;\n\n const resolvedLocale = ((options?.lng as string) ?? locale) as LocalesValues;\n\n let dictionary: unknown;\n if (\n dictionaryContent !== undefined &&\n targetNamespace === namespace &&\n options?.lng === undefined\n ) {\n dictionary = dictionaryContent;\n } else {\n dictionary = getDictionaryOrUndefined(\n targetNamespace as DictionaryKeys,\n resolvedLocale\n );\n\n // i18next's default namespace is `translation`, but a single-file JSON\n // source (no `{{key}}` segment) is loaded as the root `index` dictionary.\n // When the *default* namespace is not itself a registered dictionary, fall\n // back to `index` so `t('login.heroSubtitle')` resolves against the\n // whole-file dictionary. Explicit `ns:` prefixes / `ns` options never fall\n // back, so a genuinely missing namespace still returns `undefined`.\n if (\n dictionary === undefined &&\n targetNamespace === namespace &&\n targetNamespace !== ROOT_DICTIONARY_KEY\n ) {\n dictionary = getDictionaryOrUndefined(\n ROOT_DICTIONARY_KEY as DictionaryKeys,\n resolvedLocale\n );\n }\n\n if (dictionary === undefined) return undefined;\n }\n\n let resolvedValue: unknown;\n for (const candidate of buildKeyCandidates(\n path,\n (options?.lng as string) ?? (locale as string),\n count,\n context,\n ordinal\n )) {\n const value = navigatePath(dictionary, candidate, keySeparator);\n if (value !== null && value !== undefined) {\n resolvedValue = value;\n break;\n }\n }\n\n if (resolvedValue === null || resolvedValue === undefined) return undefined;\n\n // `returnObjects: true` — return the raw subtree\n if (\n options?.returnObjects &&\n typeof resolvedValue === 'object' &&\n resolvedValue !== null\n ) {\n return resolvedValue;\n }\n\n const values = getInterpolationValues(options);\n\n let resolved = resolveMessage(\n resolvedValue,\n values,\n ((options?.lng as string) ?? locale) as LocalesValues,\n 'i18next'\n );\n\n // `$t(key)` nesting\n if (depth < MAX_NESTING_DEPTH && resolved.includes('$t(')) {\n resolved = resolved.replace(\n /\\$t\\(\\s*([^),]+?)\\s*(?:,[^)]*)?\\)/g,\n (match, nestedKey: string) => {\n const nestedValue = resolveTranslation({\n locale,\n namespace: targetNamespace,\n key: nestedKey.trim(),\n options,\n keySeparator,\n nsSeparator,\n depth: depth + 1,\n dictionaryContent:\n targetNamespace === namespace ? dictionaryContent : undefined,\n });\n return typeof nestedValue === 'string' ? nestedValue : match;\n }\n );\n }\n\n return resolved;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AA0BA,MAAM,sBAAsB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,oBAAoB;;;;;;;AAQ1B,MAAM,sBAAsB;;;;;;;;;;AAW5B,MAAM,4BACJ,WACA,WACY;CACZ,IAAI,EAAE,aAAa,gBAAgB,IAAI,OAAO;CAE9C,OAAO,YAAY,WAAW,MAAM;AACtC;;;;;AAMA,MAAM,sBACJ,MACA,QACA,OACA,SACA,YACa;CACb,MAAM,aAAuB,CAAC;CAE9B,MAAM,iBACJ,UAAU,SACN,SACA,IAAI,KAAK,YAAY,QAAQ,EAC3B,MAAM,UAAU,YAAY,WAC9B,CAAC,CAAC,CAAC,OAAO,KAAK;CAErB,IAAI,SAAS;EACX,IAAI,gBAAgB;GAClB,IAAI,SACF,WAAW,KAAK,GAAG,KAAK,GAAG,QAAQ,WAAW,gBAAgB;GAEhE,WAAW,KAAK,GAAG,KAAK,GAAG,QAAQ,GAAG,gBAAgB;GACtD,IAAI,UAAU,GAAG,WAAW,KAAK,GAAG,KAAK,GAAG,QAAQ,QAAQ;EAC9D;EACA,WAAW,KAAK,GAAG,KAA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AAM,UAAU,SAAS,YAAY;CAErC,MAAM,iBAAmB,SAAS,OAAkB;CAEpD,IAAI;CACJ,IACE,sBAAsB,UACtB,oBAAoB,aACpB,SAAS,QAAQ,QAEjB,aAAa;MACR;EACL,aAAa,yBACX,iBACA,cACF;EAQA,IACE,eAAe,UACf,oBAAoB,aACpB,oBAAoB,qBAEpB,aAAa,yBACX,qBACA,cACF;EAGF,IAAI,eAAe,QAAW,OAAO;CACvC;CAEA,IAAI;CACJ,KAAK,MAAM,aAAa,mBACtB,MACC,SAAS,OAAmB,QAC7B,OACA,SACA,OACF,GAAG;EACD,MAAM,QAAQ,aAAa,YAAY,WAAW,YAAY;EAC9D,IAAI,UAAU,QAAQ,UAAU,QAAW;GACzC,gBAAgB;GAChB;EACF;CACF;CAEA,IAAI,kBAAkB,QAAQ,kBAAkB,QAAW,OAAO;CAGlE,IACE,SAAS,iBACT,OAAO,kBAAkB,YACzB,kBAAkB,MAElB,OAAO;CAGT,MAAM,SAAS,uBAAuB,OAAO;CAE7C,IAAI,WAAW,eACb,eACA,QACE,SAAS,OAAkB,QAC7B,SACF;CAGA,IAAI,QAAQ,qBAAqB,SAAS,SAAS,KAAK,GACtD,WAAW,SAAS,QAClB,uCACC,OAAO,cAAsB;EAC5B,MAAM,cAAc,mBAAmB;GACrC;GACA,WAAW;GACX,KAAK,UAAU,KAAK;GACpB;GACA;GACA;GACA,OAAO,QAAQ;GACf,mBACE,oBAAoB,YAAY,oBAAoB;EACxD,CAAC;EACD,OAAO,OAAO,gBAAgB,WAAW,cAAc;CACzD,CACF;CAGF,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"resolveTranslation.mjs","names":[],"sources":["../../src/resolveTranslation.ts"],"sourcesContent":["import { getIntlayer } from '@intlayer/core/interpreter';\nimport {\n type MessageValues,\n navigatePath,\n resolveMessage,\n} from '@intlayer/core/messageFormat';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type { TOptions } from 'i18next';\n\n/**\n * Shared i18next-dialect translation resolution.\n *\n * Implements the i18next lookup pipeline on top of intlayer dictionaries:\n * namespace prefix (`ns:key`), `ns` option override, plural suffixes\n * (`key_one`, `key_other`, …) via `Intl.PluralRules`, context suffixes\n * (`key_male`), `$t()` nesting, `defaultValue` and `{{var}}` interpolation.\n *\n * Used by `@intlayer/i18next` (instance `t`) and `@intlayer/react-i18next`\n * (`useTranslation`, `<Trans>`).\n */\n\n/** Option keys that are control flags, never interpolation values. */\nconst CONTROL_OPTION_KEYS = new Set([\n 'defaultValue',\n 'ns',\n 'lng',\n 'lngs',\n 'fallbackLng',\n 'returnObjects',\n 'returnDetails',\n 'keySeparator',\n 'nsSeparator',\n 'ordinal',\n 'postProcess',\n 'postProcessPassResolved',\n 'interpolation',\n 'replace',\n 'joinArrays',\n 'nsMode',\n 'keyPrefix',\n]);\n\n/** Maximum `$t()` nesting recursion depth. */\nconst MAX_NESTING_DEPTH = 5;\n\n/**\n * Canonical key of the single dictionary produced when a JSON source pattern\n * has no `{{key}}` segment (one file holds the whole namespace, e.g.\n * `./src/i18n/{{locale}}.json`). Used as the fallback namespace so i18next's\n * default `translation` namespace resolves against the whole-file dictionary.\n */\nconst ROOT_DICTIONARY_KEY = 'index';\n\n/**\n * Reads a dictionary from the runtime registry, returning `undefined` when the\n * namespace is not a registered dictionary.\n *\n * `getIntlayer` never throws for a missing key — in development it returns a\n * path-stringifying fallback proxy — so a plain `getIntlayer` call cannot tell\n * \"missing namespace\" apart from \"resolved content\". The registry membership\n * check makes the distinction explicit before resolving.\n */\nconst getDictionaryOrUndefined = (\n namespace: DictionaryKeys,\n locale: LocalesValues\n): unknown => {\n if (!(namespace in getDictionaries())) return undefined;\n\n return getIntlayer(namespace, locale);\n};\n\n/**\n * Builds the ordered list of key candidates following i18next's resolution\n * order: context + plural → context → plural → exact key.\n */\nconst buildKeyCandidates = (\n path: string,\n locale: string,\n count: number | undefined,\n context: string | undefined,\n ordinal: boolean\n): string[] => {\n const candidates: string[] = [];\n\n const pluralCategory =\n count === undefined\n ? undefined\n : new Intl.PluralRules(locale, {\n type: ordinal ? 'ordinal' : 'cardinal',\n }).select(count);\n\n if (context) {\n if (pluralCategory) {\n if (ordinal) {\n candidates.push(`${path}_${context}_ordinal_${pluralCategory}`);\n }\n candidates.push(`${path}_${context}_${pluralCategory}`);\n if (count !== 1) candidates.push(`${path}_${context}_plural`);\n }\n candidates.push(`${path}_${context}`);\n }\n\n if (pluralCategory) {\n if (ordinal) candidates.push(`${path}_ordinal_${pluralCategory}`);\n candidates.push(`${path}_${pluralCategory}`);\n // Legacy i18next v3 JSON suffix\n if (count !== 1) candidates.push(`${path}_plural`);\n }\n\n candidates.push(path);\n\n return candidates;\n};\n\n/** Extracts interpolation values from i18next `t()` options. */\nexport const getInterpolationValues = (options?: TOptions): MessageValues => {\n if (!options || typeof options !== 'object') return {};\n\n const replace = (options as { replace?: MessageValues }).replace;\n if (replace) {\n // `count` and `context` are always interpolatable, even with `replace`\n const values: MessageValues = { ...replace };\n if (options.count !== undefined) values.count ??= options.count;\n if (options.context !== undefined) values.context ??= options.context;\n return values;\n }\n\n const values: MessageValues = {};\n for (const [optionKey, optionValue] of Object.entries(options)) {\n if (!CONTROL_OPTION_KEYS.has(optionKey)) values[optionKey] = optionValue;\n }\n return values;\n};\n\nexport type ResolveTranslationParams = {\n /** Locale to resolve against. */\n locale: LocalesValues;\n /** Default namespace (dictionary key) when the key has no `ns:` prefix. */\n namespace: string;\n /** The translation key, possibly `ns:path.to.key`. */\n key: string;\n /** i18next `t()` options (interpolation values, count, context, …). */\n options?: TOptions;\n /** Custom key separator (`init({ keySeparator })`). */\n keySeparator?: string | false;\n /** Custom namespace separator (`init({ nsSeparator })`). */\n nsSeparator?: string | false;\n /** Internal `$t()` nesting recursion depth. */\n depth?: number;\n /**\n * Pre-resolved content of the `namespace` dictionary for `locale`.\n *\n * Supplied by the build-optimized `useDictionary` / `getDictionary`\n * variants, where the dictionary is imported at build time instead of read\n * from the runtime registry. Only used when the call resolves to the\n * default `namespace` without a locale override — cross-namespace\n * (`other:key`, `{ ns }`) and `{ lng }` lookups still go through\n * `getIntlayer`.\n */\n dictionaryContent?: unknown;\n};\n\n/**\n * Resolves a single translation key the i18next way against intlayer\n * dictionaries.\n *\n * Returns the resolved value: a string in the common case, or an\n * object/array when `returnObjects: true`. Returns `undefined` when the key\n * cannot be resolved (caller decides between `defaultValue`, fallback keys\n * and key echo).\n */\nexport const resolveTranslation = ({\n locale,\n namespace,\n key,\n options,\n keySeparator = '.',\n nsSeparator = ':',\n depth = 0,\n dictionaryContent,\n}: ResolveTranslationParams): unknown => {\n // Namespace resolution: `ns:` prefix > `ns` option > default namespace\n let targetNamespace = namespace;\n let path = key;\n\n if (nsSeparator !== false && key.includes(nsSeparator)) {\n const separatorIndex = key.indexOf(nsSeparator);\n targetNamespace = key.slice(0, separatorIndex);\n path = key.slice(separatorIndex + nsSeparator.length);\n } else if (options?.ns) {\n targetNamespace = Array.isArray(options.ns)\n ? (options.ns[0] as string)\n : (options.ns as string);\n }\n\n const count = typeof options?.count === 'number' ? options.count : undefined;\n const context =\n options?.context !== undefined ? String(options.context) : undefined;\n const ordinal = options?.ordinal === true;\n\n const resolvedLocale = ((options?.lng as string) ?? locale) as LocalesValues;\n\n let dictionary: unknown;\n if (\n dictionaryContent !== undefined &&\n targetNamespace === namespace &&\n options?.lng === undefined\n ) {\n dictionary = dictionaryContent;\n } else {\n dictionary = getDictionaryOrUndefined(\n targetNamespace as DictionaryKeys,\n resolvedLocale\n );\n\n // i18next's default namespace is `translation`, but a single-file JSON\n // source (no `{{key}}` segment) is loaded as the root `index` dictionary.\n // When the *default* namespace is not itself a registered dictionary, fall\n // back to `index` so `t('login.heroSubtitle')` resolves against the\n // whole-file dictionary. Explicit `ns:` prefixes / `ns` options never fall\n // back, so a genuinely missing namespace still returns `undefined`.\n if (\n dictionary === undefined &&\n targetNamespace === namespace &&\n targetNamespace !== ROOT_DICTIONARY_KEY\n ) {\n dictionary = getDictionaryOrUndefined(\n ROOT_DICTIONARY_KEY as DictionaryKeys,\n resolvedLocale\n );\n }\n\n if (dictionary === undefined) return undefined;\n }\n\n let resolvedValue: unknown;\n for (const candidate of buildKeyCandidates(\n path,\n (options?.lng as string) ?? (locale as string),\n count,\n context,\n ordinal\n )) {\n const value = navigatePath(dictionary, candidate, keySeparator);\n if (value !== null && value !== undefined) {\n resolvedValue = value;\n break;\n }\n }\n\n if (resolvedValue === null || resolvedValue === undefined) return undefined;\n\n // `returnObjects: true` — return the raw subtree\n if (\n options?.returnObjects &&\n typeof resolvedValue === 'object' &&\n resolvedValue !== null\n ) {\n return resolvedValue;\n }\n\n const values = getInterpolationValues(options);\n\n let resolved = resolveMessage(\n resolvedValue,\n values,\n ((options?.lng as string) ?? locale) as LocalesValues,\n 'i18next'\n );\n\n // `$t(key)` nesting\n if (depth < MAX_NESTING_DEPTH && resolved.includes('$t(')) {\n resolved = resolved.replace(\n /\\$t\\(\\s*([^),]+?)\\s*(?:,[^)]*)?\\)/g,\n (match, nestedKey: string) => {\n const nestedValue = resolveTranslation({\n locale,\n namespace: targetNamespace,\n key: nestedKey.trim(),\n options,\n keySeparator,\n nsSeparator,\n depth: depth + 1,\n dictionaryContent:\n targetNamespace === namespace ? dictionaryContent : undefined,\n });\n return typeof nestedValue === 'string' ? nestedValue : match;\n }\n );\n }\n\n return resolved;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AA0BA,MAAM,sCAAsB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,oBAAoB;;;;;;;AAQ1B,MAAM,sBAAsB;;;;;;;;;;AAW5B,MAAM,4BACJ,WACA,WACY;CACZ,IAAI,EAAE,aAAa,gBAAgB,IAAI,OAAO;CAE9C,OAAO,YAAY,WAAW,MAAM;AACtC;;;;;AAMA,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,MAAM,cAAc,mBAAmB;GACrC;GACA,WAAW;GACX,KAAK,UAAU,KAAK;GACpB;GACA;GACA;GACA,OAAO,QAAQ;GACf,mBACE,oBAAoB,YAAY,oBAAoB;EACxD,CAAC;EACD,OAAO,OAAO,gBAAgB,WAAW,cAAc;CACzD,CACF;CAGF,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createInstance.d.ts","names":[],"sources":["../../src/createInstance.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"createInstance.d.ts","names":[],"sources":["../../src/createInstance.ts"],"mappings":";;;cAgCa,uBAAuB"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { ScopedTFunction, TypedTFunction } from "./typedTranslation.js";
|
|
2
2
|
import { DictionaryKeys, LocalesValues } from "@intlayer/types/module_augmentation";
|
|
3
3
|
import { Dictionary } from "@intlayer/types/dictionary";
|
|
4
|
-
|
|
5
4
|
//#region src/getDictionary.d.ts
|
|
6
5
|
/**
|
|
7
6
|
* Overload set for {@link getDictionary}: without a key prefix the returned
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getDictionary.d.ts","names":[],"sources":["../../src/getDictionary.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"getDictionary.d.ts","names":[],"sources":["../../src/getDictionary.ts"],"mappings":";;;;;;;;;KAgBK;GACF,UAAU,YACT,YAAY,GACZ,SAAS,gBACR,eAAe,WAAW;GAC5B,UAAU,YAAY,uBACrB,YAAY,GACZ,QAAQ,2BACR,WAAW,SACV,gBAAgB,WAAW,gBAAgB;;;;;;;;;;;;;;;;;;cAmBnC,eAmBP"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { ScopedTFunction, TypedTFunction } from "./typedTranslation.js";
|
|
2
2
|
import { DictionaryKeys, LocalesValues, StrictModeLocaleMap } from "@intlayer/types/module_augmentation";
|
|
3
3
|
import { Dictionary } from "@intlayer/types/dictionary";
|
|
4
|
-
|
|
5
4
|
//#region src/getDictionaryDynamic.d.ts
|
|
6
5
|
/**
|
|
7
6
|
* Overload set for {@link getDictionaryDynamic}: without a key prefix the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getDictionaryDynamic.d.ts","names":[],"sources":["../../src/getDictionaryDynamic.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"getDictionaryDynamic.d.ts","names":[],"sources":["../../src/getDictionaryDynamic.ts"],"mappings":";;;;;;;;;KAiBK;GACF,UAAU,YAAY,UAAU,gBAC/B,mBAAmB,0BAA0B,QAAQ,KACrD,KAAK,GACL,SAAS,gBACR,QAAQ,eAAe;GACzB,UAAU,YAAY,UAAU,gBAAgB,uBAC/C,mBAAmB,0BAA0B,QAAQ,KACrD,KAAK,GACL,QAAQ,2BACR,WAAW,SACV,QAAQ,gBAAgB,GAAG;;;;;;;;;;;;;cAcnB,sBA6BP"}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -4,7 +4,6 @@ import { getDictionary } from "./getDictionary.js";
|
|
|
4
4
|
import { getDictionaryDynamic } from "./getDictionaryDynamic.js";
|
|
5
5
|
import { ResolveTranslationParams, getInterpolationValues, resolveTranslation } from "./resolveTranslation.js";
|
|
6
6
|
import { InitOptions, TFunction, TOptions, changeLanguage as changeLanguage$1, dir as dir$1, exists as exists$1, hasLoadedNamespace as hasLoadedNamespace$1, i18n, i18n as i18n$1, init as init$1, loadLanguages as loadLanguages$1, loadNamespaces as loadNamespaces$1, loadResources as loadResources$1, reloadResources as reloadResources$1, setDefaultNamespace as setDefaultNamespace$1, t as t$1, use as use$1 } from "i18next";
|
|
7
|
-
|
|
8
7
|
//#region src/index.d.ts
|
|
9
8
|
declare const i18next: i18n$1;
|
|
10
9
|
declare const dir: typeof dir$1;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/index.ts"],"mappings":";;;;;;;cAiCM,SAAS;cAMF,YAAY;cACZ,aAAa;cACb,sBAAsB;cAEtB,wBAAwB;cAExB,YAAY;cACZ,uBAAuB;;;;;;;;;;;;;cAevB,WAAW;cAIX,UAAU;cACV,eAAe;cACf,4BAA4B;cAE5B,2BAA2B;cAE3B,uBAAuB;cAEvB,sBAAsB;;;;;;cAQtB,kBAAe"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/plugin/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/plugin/index.ts"],"mappings":";;;cASa,oBAAiB,UAClB,kBAAkB,iBAC3B"}
|
|
@@ -1,17 +1,23 @@
|
|
|
1
1
|
import { TOptions } from "i18next";
|
|
2
2
|
import { LocalesValues } from "@intlayer/types/module_augmentation";
|
|
3
3
|
import { MessageValues } from "@intlayer/core/messageFormat";
|
|
4
|
-
|
|
5
4
|
//#region src/resolveTranslation.d.ts
|
|
6
5
|
/** Extracts interpolation values from i18next `t()` options. */
|
|
7
6
|
declare const getInterpolationValues: (options?: TOptions) => MessageValues;
|
|
8
7
|
type ResolveTranslationParams = {
|
|
9
|
-
/** Locale to resolve against. */
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
8
|
+
/** Locale to resolve against. */
|
|
9
|
+
locale: LocalesValues;
|
|
10
|
+
/** Default namespace (dictionary key) when the key has no `ns:` prefix. */
|
|
11
|
+
namespace: string;
|
|
12
|
+
/** The translation key, possibly `ns:path.to.key`. */
|
|
13
|
+
key: string;
|
|
14
|
+
/** i18next `t()` options (interpolation values, count, context, …). */
|
|
15
|
+
options?: TOptions;
|
|
16
|
+
/** Custom key separator (`init({ keySeparator })`). */
|
|
17
|
+
keySeparator?: string | false;
|
|
18
|
+
/** Custom namespace separator (`init({ nsSeparator })`). */
|
|
19
|
+
nsSeparator?: string | false;
|
|
20
|
+
/** Internal `$t()` nesting recursion depth. */
|
|
15
21
|
depth?: number;
|
|
16
22
|
/**
|
|
17
23
|
* Pre-resolved content of the `namespace` dictionary for `locale`.
|
|
@@ -34,16 +40,7 @@ type ResolveTranslationParams = {
|
|
|
34
40
|
* cannot be resolved (caller decides between `defaultValue`, fallback keys
|
|
35
41
|
* and key echo).
|
|
36
42
|
*/
|
|
37
|
-
declare const resolveTranslation: ({
|
|
38
|
-
locale,
|
|
39
|
-
namespace,
|
|
40
|
-
key,
|
|
41
|
-
options,
|
|
42
|
-
keySeparator,
|
|
43
|
-
nsSeparator,
|
|
44
|
-
depth,
|
|
45
|
-
dictionaryContent
|
|
46
|
-
}: ResolveTranslationParams) => unknown;
|
|
43
|
+
declare const resolveTranslation: ({ locale, namespace, key, options, keySeparator, nsSeparator, depth, dictionaryContent }: ResolveTranslationParams) => unknown;
|
|
47
44
|
//#endregion
|
|
48
45
|
export { ResolveTranslationParams, getInterpolationValues, resolveTranslation };
|
|
49
46
|
//# sourceMappingURL=resolveTranslation.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolveTranslation.d.ts","names":[],"sources":["../../src/resolveTranslation.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"resolveTranslation.d.ts","names":[],"sources":["../../src/resolveTranslation.ts"],"mappings":";;;;;cAuHa,yBAAsB,UAAc,aAAW;KAmBhD;;EAEV,QAAQ;;EAER;;EAEA;;EAEA,UAAU;;EAEV;;EAEA;;EAEA;;;;;;;;;;;EAWA;;;;;;;;;;;cAYW,uBAAkB,QAAA,WAAA,KAAA,SAAA,cAAA,aAAA,OAAA,qBAS5B"}
|
|
@@ -2,7 +2,6 @@ import { TOptions } from "i18next";
|
|
|
2
2
|
import { GetNestingResult } from "@intlayer/core/interpreter";
|
|
3
3
|
import { ValidDotPathsFor } from "@intlayer/core/transpiler";
|
|
4
4
|
import { DictionaryKeys } from "@intlayer/types/module_augmentation";
|
|
5
|
-
|
|
6
5
|
//#region src/typedTranslation.d.ts
|
|
7
6
|
/**
|
|
8
7
|
* The interpreter-resolved content type at dot-path `P` of dictionary `N` —
|
|
@@ -19,7 +18,7 @@ type TranslatedValue<N extends DictionaryKeys, P> = ContentAtPath<N, P> extends
|
|
|
19
18
|
* The dot-paths of dictionary `N` relative to the key prefix `Prefix`
|
|
20
19
|
* (`getFixedT(null, 'about', 'counter')` → paths under `about.counter`).
|
|
21
20
|
*/
|
|
22
|
-
type ScopedDotPaths<N extends DictionaryKeys, Prefix extends string> = ValidDotPathsFor<N> extends infer AllPaths ? AllPaths extends `${Prefix}.${infer RelativePath}` ? RelativePath : never : never;
|
|
21
|
+
type ScopedDotPaths<N extends DictionaryKeys, Prefix extends string> = ValidDotPathsFor<N> extends (infer AllPaths) ? AllPaths extends `${Prefix}.${infer RelativePath}` ? RelativePath : never : never;
|
|
23
22
|
/**
|
|
24
23
|
* Fully-typed i18next `t()` bound to the dictionary namespace `N`.
|
|
25
24
|
*
|
|
@@ -28,9 +27,11 @@ type ScopedDotPaths<N extends DictionaryKeys, Prefix extends string> = ValidDotP
|
|
|
28
27
|
* content subtree is returned instead of a string.
|
|
29
28
|
*/
|
|
30
29
|
type TypedTFunction<N extends DictionaryKeys> = {
|
|
31
|
-
/** Returns the raw content subtree at `key` (i18next `returnObjects`).
|
|
30
|
+
/** Returns the raw content subtree at `key` (i18next `returnObjects`). */
|
|
31
|
+
<P extends ValidDotPathsFor<N>>(key: P | P[], options: TOptions & {
|
|
32
32
|
returnObjects: true;
|
|
33
|
-
}): ContentAtPath<N, P>;
|
|
33
|
+
}): ContentAtPath<N, P>;
|
|
34
|
+
/** Translate a key, with optional default value and interpolation options. */
|
|
34
35
|
<P extends ValidDotPathsFor<N>>(key: P | P[], optionsOrDefaultValue?: TOptions | string, extraOptions?: TOptions): TranslatedValue<N, P>;
|
|
35
36
|
};
|
|
36
37
|
/**
|
|
@@ -39,9 +40,11 @@ type TypedTFunction<N extends DictionaryKeys> = {
|
|
|
39
40
|
* types are resolved against the absolute path in the dictionary.
|
|
40
41
|
*/
|
|
41
42
|
type ScopedTFunction<N extends DictionaryKeys, Prefix extends string> = {
|
|
42
|
-
/** Returns the raw content subtree at `key` (i18next `returnObjects`).
|
|
43
|
+
/** Returns the raw content subtree at `key` (i18next `returnObjects`). */
|
|
44
|
+
<P extends ScopedDotPaths<N, Prefix>>(key: P | P[], options: TOptions & {
|
|
43
45
|
returnObjects: true;
|
|
44
|
-
}): ContentAtPath<N, `${Prefix}.${P}`>;
|
|
46
|
+
}): ContentAtPath<N, `${Prefix}.${P}`>;
|
|
47
|
+
/** Translate a scoped key, with optional default value and options. */
|
|
45
48
|
<P extends ScopedDotPaths<N, Prefix>>(key: P | P[], optionsOrDefaultValue?: TOptions | string, extraOptions?: TOptions): TranslatedValue<N, `${Prefix}.${P}`>;
|
|
46
49
|
};
|
|
47
50
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typedTranslation.d.ts","names":[],"sources":["../../src/typedTranslation.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"typedTranslation.d.ts","names":[],"sources":["../../src/typedTranslation.ts"],"mappings":";;;;;;;;;KASY,cAAc,UAAU,gBAAgB,KAAK,iBAAiB,GAAG;;;;;;KAOjE,gBAAgB,UAAU,gBAAgB,KACpD,cAAc,GAAG,oBAAoB,cAAc,GAAG;;;;;KAM5C,eAAe,UAAU,gBAAgB,yBACnD,iBAAiB,kBAAiB,YAC9B,oBAAoB,gBAAgB,iBAClC;;;;;;;;KAWI,eAAe,UAAU;;GAElC,UAAU,iBAAiB,IAC1B,KAAK,IAAI,KACT,SAAS;IAAa;MACrB,cAAc,GAAG;;GAEnB,UAAU,iBAAiB,IAC1B,KAAK,IAAI,KACT,wBAAwB,mBACxB,eAAe,WACd,gBAAgB,GAAG;;;;;;;KAQZ,gBAAgB,UAAU,gBAAgB;;GAEnD,UAAU,eAAe,GAAG,SAC3B,KAAK,IAAI,KACT,SAAS;IAAa;MACrB,cAAc,MAAM,UAAU;;GAEhC,UAAU,eAAe,GAAG,SAC3B,KAAK,IAAI,KACT,wBAAwB,mBACxB,eAAe,WACd,gBAAgB,MAAM,UAAU;;;;;;KAOzB;GACT,UAAU,gBAAgB,uBACzB,wCACA,IAAI,sBACJ,WAAW,SACV,gBAAgB,GAAG;GACrB,UAAU,gBACT,wCACA,KAAK,WACJ,eAAe"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intlayer/i18next",
|
|
3
|
-
"version": "9.0.0-canary.
|
|
3
|
+
"version": "9.0.0-canary.19",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "i18next API adapter for intlayer — drop-in compatibility layer that exposes the i18next interface while using @intlayer/core under the hood",
|
|
6
6
|
"keywords": [
|
|
@@ -74,23 +74,23 @@
|
|
|
74
74
|
"typecheck": "tsc --noEmit --project tsconfig.types.json"
|
|
75
75
|
},
|
|
76
76
|
"dependencies": {
|
|
77
|
-
"@intlayer/config": "9.0.0-canary.
|
|
78
|
-
"@intlayer/core": "9.0.0-canary.
|
|
79
|
-
"@intlayer/dictionaries-entry": "9.0.0-canary.
|
|
80
|
-
"@intlayer/engine": "9.0.0-canary.
|
|
81
|
-
"@intlayer/types": "9.0.0-canary.
|
|
82
|
-
"vite-intlayer": "9.0.0-canary.
|
|
77
|
+
"@intlayer/config": "9.0.0-canary.19",
|
|
78
|
+
"@intlayer/core": "9.0.0-canary.19",
|
|
79
|
+
"@intlayer/dictionaries-entry": "9.0.0-canary.19",
|
|
80
|
+
"@intlayer/engine": "9.0.0-canary.19",
|
|
81
|
+
"@intlayer/types": "9.0.0-canary.19",
|
|
82
|
+
"vite-intlayer": "9.0.0-canary.19"
|
|
83
83
|
},
|
|
84
84
|
"devDependencies": {
|
|
85
|
-
"@types/node": "
|
|
85
|
+
"@types/node": "26.1.1",
|
|
86
86
|
"@utils/ts-config": "1.0.4",
|
|
87
87
|
"@utils/ts-config-types": "1.0.4",
|
|
88
88
|
"@utils/tsdown-config": "1.0.4",
|
|
89
|
-
"i18next": "26.3.
|
|
89
|
+
"i18next": "26.3.6",
|
|
90
90
|
"rimraf": "6.1.3",
|
|
91
|
-
"tsdown": "0.22.
|
|
92
|
-
"typescript": "
|
|
93
|
-
"vite": "8.1.
|
|
91
|
+
"tsdown": "0.22.12",
|
|
92
|
+
"typescript": "7.0.2",
|
|
93
|
+
"vite": "8.1.5",
|
|
94
94
|
"vitest": "4.1.10"
|
|
95
95
|
},
|
|
96
96
|
"peerDependencies": {
|