index.v4.d.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. // Internal Helpers
  2. import type { $Dictionary, $NormalizeIntoArray } from './typescript/helpers.js';
  3. import type {
  4. DefaultNamespace,
  5. FlatNamespace,
  6. FormatFunction,
  7. InitOptions,
  8. InterpolationOptions,
  9. Namespace,
  10. Resource,
  11. ResourceKey,
  12. ResourceLanguage,
  13. TOptions,
  14. } from './typescript/options.js';
  15. import type { KeyPrefix, TFunction } from './typescript/t.v4.js';
  16. export interface WithT<Ns extends Namespace = DefaultNamespace> {
  17. // Expose parameterized t in the i18next interface hierarchy
  18. t: TFunction<Ns>;
  19. }
  20. export interface Interpolator {
  21. init(options: InterpolationOptions, reset: boolean): undefined;
  22. reset(): undefined;
  23. resetRegExp(): undefined;
  24. interpolate(str: string, data: object, lng: string, options: InterpolationOptions): string;
  25. nest(str: string, fc: (...args: any[]) => any, options: InterpolationOptions): string;
  26. }
  27. export class ResourceStore {
  28. constructor(data: Resource, options: InitOptions);
  29. public data: Resource;
  30. public options: InitOptions;
  31. /**
  32. * Gets fired when resources got added or removed
  33. */
  34. on(event: 'added' | 'removed', callback: (lng: string, ns: string) => void): void;
  35. /**
  36. * Remove event listener
  37. * removes all callback when callback not specified
  38. */
  39. off(event: 'added' | 'removed', callback?: (lng: string, ns: string) => void): void;
  40. }
  41. export interface Formatter {
  42. init(services: Services, i18nextOptions: InitOptions): void;
  43. add(name: string, fc: (value: any, lng: string | undefined, options: any) => string): void;
  44. addCached(
  45. name: string,
  46. fc: (lng: string | undefined, options: any) => (value: any) => string,
  47. ): void;
  48. format: FormatFunction;
  49. }
  50. export interface Services {
  51. backendConnector: any;
  52. i18nFormat: any;
  53. interpolator: Interpolator;
  54. languageDetector: any;
  55. languageUtils: any;
  56. logger: any;
  57. pluralResolver: any;
  58. resourceStore: ResourceStore;
  59. formatter?: Formatter;
  60. }
  61. export type ModuleType =
  62. | 'backend'
  63. | 'logger'
  64. | 'languageDetector'
  65. | 'postProcessor'
  66. | 'i18nFormat'
  67. | 'formatter'
  68. | '3rdParty';
  69. export interface Module {
  70. type: ModuleType;
  71. }
  72. export type CallbackError = Error | string | null | undefined;
  73. export type ReadCallback = (
  74. err: CallbackError,
  75. data: ResourceKey | boolean | null | undefined,
  76. ) => void;
  77. export type MultiReadCallback = (err: CallbackError, data: Resource | null | undefined) => void;
  78. /**
  79. * Used to load data for i18next.
  80. * Can be provided as a singleton or as a prototype constructor (preferred for supporting multiple instances of i18next).
  81. * For singleton set property `type` to `'backend'` For a prototype constructor set static property.
  82. */
  83. export interface BackendModule<Options = object> extends Module {
  84. type: 'backend';
  85. init(services: Services, backendOptions: Options, i18nextOptions: InitOptions): void;
  86. read(language: string, namespace: string, callback: ReadCallback): void;
  87. /** Save the missing translation */
  88. create?(
  89. languages: readonly string[],
  90. namespace: string,
  91. key: string,
  92. fallbackValue: string,
  93. ): void;
  94. /** Load multiple languages and namespaces. For backends supporting multiple resources loading */
  95. readMulti?(
  96. languages: readonly string[],
  97. namespaces: readonly string[],
  98. callback: MultiReadCallback,
  99. ): void;
  100. /** Store the translation. For backends acting as cache layer */
  101. save?(language: string, namespace: string, data: ResourceLanguage): void;
  102. }
  103. /**
  104. * Used to detect language in user land.
  105. * Can be provided as a singleton or as a prototype constructor (preferred for supporting multiple instances of i18next).
  106. * For singleton set property `type` to `'languageDetector'` For a prototype constructor set static property.
  107. */
  108. export interface LanguageDetectorModule extends Module {
  109. type: 'languageDetector';
  110. init?(services: Services, detectorOptions: object, i18nextOptions: InitOptions): void;
  111. /** Must return detected language */
  112. detect(): string | readonly string[] | undefined;
  113. cacheUserLanguage?(lng: string): void;
  114. }
  115. /**
  116. * Used to detect language in user land.
  117. * Can be provided as a singleton or as a prototype constructor (preferred for supporting multiple instances of i18next).
  118. * For singleton set property `type` to `'languageDetector'` For a prototype constructor set static property.
  119. */
  120. export interface LanguageDetectorAsyncModule extends Module {
  121. type: 'languageDetector';
  122. /** Set to true to enable async detection */
  123. async: true;
  124. init?(services: Services, detectorOptions: object, i18nextOptions: InitOptions): void;
  125. /** Must call callback passing detected language or return a Promise */
  126. detect(
  127. callback: (lng: string | readonly string[] | undefined) => void | undefined,
  128. ): void | Promise<string | readonly string[] | undefined>;
  129. cacheUserLanguage?(lng: string): void | Promise<void>;
  130. }
  131. /**
  132. * Used to extend or manipulate the translated values before returning them in `t` function.
  133. * Need to be a singleton object.
  134. */
  135. export interface PostProcessorModule extends Module {
  136. /** Unique name */
  137. name: string;
  138. type: 'postProcessor';
  139. process(value: string, key: string | string[], options: TOptions, translator: any): string;
  140. }
  141. /**
  142. * Override the built-in console logger.
  143. * Do not need to be a prototype function.
  144. */
  145. export interface LoggerModule extends Module {
  146. type: 'logger';
  147. log(...args: any[]): void;
  148. warn(...args: any[]): void;
  149. error(...args: any[]): void;
  150. }
  151. export interface I18nFormatModule extends Module {
  152. type: 'i18nFormat';
  153. }
  154. export interface FormatterModule extends Module, Formatter {
  155. type: 'formatter';
  156. }
  157. export interface ThirdPartyModule extends Module {
  158. type: '3rdParty';
  159. init(i18next: i18n): void;
  160. }
  161. export interface Modules {
  162. backend?: BackendModule;
  163. logger?: LoggerModule;
  164. languageDetector?: LanguageDetectorModule | LanguageDetectorAsyncModule;
  165. i18nFormat?: I18nFormatModule;
  166. formatter?: FormatterModule;
  167. external: ThirdPartyModule[];
  168. }
  169. // helper to identify class https://stackoverflow.com/a/45983481/2363935
  170. export interface Newable<T> {
  171. new (...args: any[]): T;
  172. }
  173. export interface NewableModule<T extends Module> extends Newable<T> {
  174. type: T['type'];
  175. }
  176. export type Callback = (error: any, t: TFunction) => void;
  177. /**
  178. * Uses similar args as the t function and returns true if a key exists.
  179. */
  180. export interface ExistsFunction<
  181. TKeys extends string = string,
  182. TInterpolationMap extends object = $Dictionary,
  183. > {
  184. (key: TKeys | TKeys[], options?: TOptions<TInterpolationMap>): boolean;
  185. }
  186. export interface CloneOptions extends InitOptions {
  187. /**
  188. * Will create a new instance of the resource store and import the existing translation resources.
  189. * This way it will not shared the resource store instance.
  190. * @default false
  191. */
  192. forkResourceStore?: boolean;
  193. }
  194. export interface CustomInstanceExtensions {}
  195. // Used just here to exclude `DefaultNamespace` which can be both string or array from `FlatNamespace`
  196. // in TFunction declaration below.
  197. // Due to this only very special usage I'm not moving this inside helpers.
  198. type InferArrayValuesElseReturnType<T> = T extends (infer A)[] ? A : T;
  199. // eslint-disable-next-line @typescript-eslint/naming-convention
  200. export interface i18n extends CustomInstanceExtensions {
  201. // Expose parameterized t in the i18next interface hierarchy
  202. t: TFunction<
  203. [
  204. ...$NormalizeIntoArray<DefaultNamespace>,
  205. ...Exclude<FlatNamespace, InferArrayValuesElseReturnType<DefaultNamespace>>[],
  206. ]
  207. >;
  208. /**
  209. * The default of the i18next module is an i18next instance ready to be initialized by calling init.
  210. * You can create additional instances using the createInstance function.
  211. *
  212. * @param options - Initial options.
  213. * @param callback - will be called after all translations were loaded or with an error when failed (in case of using a backend).
  214. */
  215. init(callback?: Callback): Promise<TFunction>;
  216. init<T>(options: InitOptions<T>, callback?: Callback): Promise<TFunction>;
  217. loadResources(callback?: (err: any) => void): void;
  218. /**
  219. * The use function is there to load additional plugins to i18next.
  220. * For available module see the plugins page and don't forget to read the documentation of the plugin.
  221. *
  222. * @param module Accepts a class or object
  223. */
  224. use<T extends Module>(module: T | NewableModule<T> | Newable<T>): this;
  225. /**
  226. * List of modules used
  227. */
  228. modules: Modules;
  229. /**
  230. * Internal container for all used plugins and implementation details like languageUtils, pluralResolvers, etc.
  231. */
  232. services: Services;
  233. /**
  234. * Internal container for translation resources
  235. */
  236. store: ResourceStore;
  237. /**
  238. * Uses similar args as the t function and returns true if a key exists.
  239. */
  240. exists: ExistsFunction;
  241. /**
  242. * Returns a resource data by language.
  243. */
  244. getDataByLanguage(lng: string): { [key: string]: { [key: string]: string } } | undefined;
  245. /**
  246. * Returns a t function that defaults to given language or namespace.
  247. * Both params could be arrays of languages or namespaces and will be treated as fallbacks in that case.
  248. * On the returned function you can like in the t function override the languages or namespaces by passing them in options or by prepending namespace.
  249. *
  250. * Accepts optional keyPrefix that will be automatically applied to returned t function.
  251. */
  252. getFixedT<
  253. Ns extends Namespace | null = DefaultNamespace,
  254. TKPrefix extends KeyPrefix<ActualNs> = undefined,
  255. ActualNs extends Namespace = Ns extends null ? DefaultNamespace : Ns,
  256. >(
  257. ...args:
  258. | [lng: string | readonly string[], ns?: Ns, keyPrefix?: TKPrefix]
  259. | [lng: null, ns: Ns, keyPrefix?: TKPrefix]
  260. ): TFunction<ActualNs, TKPrefix>;
  261. /**
  262. * Changes the language. The callback will be called as soon translations were loaded or an error occurs while loading.
  263. * HINT: For easy testing - setting lng to 'cimode' will set t function to always return the key.
  264. */
  265. changeLanguage(lng?: string, callback?: Callback): Promise<TFunction>;
  266. /**
  267. * Is set to the current detected or set language.
  268. * If you need the primary used language depending on your configuration (supportedLngs, load) you will prefer using i18next.languages[0].
  269. */
  270. language: string;
  271. /**
  272. * Is set to an array of language-codes that will be used it order to lookup the translation value.
  273. */
  274. languages: readonly string[];
  275. /**
  276. * Is set to the current resolved language.
  277. * It can be used as primary used language, for example in a language switcher.
  278. */
  279. resolvedLanguage?: string;
  280. /**
  281. * Checks if namespace has loaded yet.
  282. * i.e. used by react-i18next
  283. */
  284. hasLoadedNamespace(
  285. ns: string | readonly string[],
  286. options?: {
  287. lng?: string | readonly string[];
  288. fallbackLng?: InitOptions['fallbackLng'];
  289. /**
  290. * if `undefined` is returned default checks are performed.
  291. */
  292. precheck?: (
  293. i18n: i18n,
  294. /**
  295. * Check if the language namespace provided are not in loading status:
  296. * returns `true` if load is completed successfully or with an error.
  297. */
  298. loadNotPending: (
  299. lng: string | readonly string[],
  300. ns: string | readonly string[],
  301. ) => boolean,
  302. ) => boolean | undefined;
  303. },
  304. ): boolean;
  305. /**
  306. * Loads additional namespaces not defined in init options.
  307. */
  308. loadNamespaces(ns: string | readonly string[], callback?: Callback): Promise<void>;
  309. /**
  310. * Loads additional languages not defined in init options (preload).
  311. */
  312. loadLanguages(lngs: string | readonly string[], callback?: Callback): Promise<void>;
  313. /**
  314. * Reloads resources on given state. Optionally you can pass an array of languages and namespaces as params if you don't want to reload all.
  315. */
  316. reloadResources(
  317. lngs?: string | readonly string[],
  318. ns?: string | readonly string[],
  319. callback?: () => void,
  320. ): Promise<void>;
  321. reloadResources(lngs: null, ns: string | readonly string[], callback?: () => void): Promise<void>;
  322. /**
  323. * Changes the default namespace.
  324. */
  325. setDefaultNamespace(ns: string): void;
  326. /**
  327. * Returns rtl or ltr depending on languages read direction.
  328. */
  329. dir(lng?: string): 'ltr' | 'rtl';
  330. /**
  331. * Exposes interpolation.format function added on init.
  332. */
  333. format: FormatFunction;
  334. /**
  335. * Will return a new i18next instance.
  336. * Please read the options page for details on configuration options.
  337. * Providing a callback will automatically call init.
  338. * The callback will be called after all translations were loaded or with an error when failed (in case of using a backend).
  339. */
  340. createInstance(options?: InitOptions, callback?: Callback): i18n;
  341. /**
  342. * Creates a clone of the current instance. Shares store, plugins and initial configuration.
  343. * Can be used to create an instance sharing storage but being independent on set language or namespaces.
  344. */
  345. cloneInstance(options?: CloneOptions, callback?: Callback): i18n;
  346. /**
  347. * Gets fired after initialization.
  348. */
  349. on(event: 'initialized', callback: (options: InitOptions) => void): void;
  350. /**
  351. * Gets fired on loaded resources.
  352. */
  353. on(
  354. event: 'loaded',
  355. callback: (loaded: { [language: string]: { [namespace: string]: boolean } }) => void,
  356. ): void;
  357. /**
  358. * Gets fired if loading resources failed.
  359. */
  360. on(event: 'failedLoading', callback: (lng: string, ns: string, msg: string) => void): void;
  361. /**
  362. * Gets fired on accessing a key not existing.
  363. */
  364. on(
  365. event: 'missingKey',
  366. callback: (lngs: readonly string[], namespace: string, key: string, res: string) => void,
  367. ): void;
  368. /**
  369. * Gets fired when resources got added or removed.
  370. */
  371. on(event: 'added' | 'removed', callback: (lng: string, ns: string) => void): void;
  372. /**
  373. * Gets fired when changeLanguage got called.
  374. */
  375. on(event: 'languageChanged', callback: (lng: string) => void): void;
  376. /**
  377. * Event listener
  378. */
  379. on(event: string, listener: (...args: any[]) => void): void;
  380. /**
  381. * Remove event listener
  382. * removes all callback when callback not specified
  383. */
  384. off(event: string, listener?: (...args: any[]) => void): void;
  385. /**
  386. * Gets one value by given key.
  387. */
  388. getResource(
  389. lng: string,
  390. ns: string,
  391. key: string,
  392. options?: Pick<InitOptions, 'keySeparator' | 'ignoreJSONStructure'>,
  393. ): any;
  394. /**
  395. * Adds one key/value.
  396. */
  397. addResource(
  398. lng: string,
  399. ns: string,
  400. key: string,
  401. value: string,
  402. options?: { keySeparator?: string; silent?: boolean },
  403. ): i18n;
  404. /**
  405. * Adds multiple key/values.
  406. */
  407. addResources(lng: string, ns: string, resources: any): i18n;
  408. /**
  409. * Adds a complete bundle.
  410. * Setting deep param to true will extend existing translations in that file.
  411. * Setting overwrite to true it will overwrite existing translations in that file.
  412. */
  413. addResourceBundle(
  414. lng: string,
  415. ns: string,
  416. resources: any,
  417. deep?: boolean,
  418. overwrite?: boolean,
  419. ): i18n;
  420. /**
  421. * Checks if a resource bundle exists.
  422. */
  423. hasResourceBundle(lng: string, ns: string): boolean;
  424. /**
  425. * Returns a resource bundle.
  426. */
  427. getResourceBundle(lng: string, ns: string): any;
  428. /**
  429. * Removes an existing bundle.
  430. */
  431. removeResourceBundle(lng: string, ns: string): i18n;
  432. /**
  433. * Current options
  434. */
  435. options: InitOptions;
  436. /**
  437. * Is initialized
  438. */
  439. isInitialized: boolean;
  440. /**
  441. * Is initializing
  442. */
  443. isInitializing: boolean;
  444. /**
  445. * Store was initialized
  446. */
  447. initializedStoreOnce: boolean;
  448. /**
  449. * Language was initialized
  450. */
  451. initializedLanguageOnce: boolean;
  452. /**
  453. * Emit event
  454. */
  455. emit(eventName: string, ...args: any[]): void;
  456. }
  457. // export type * from './typescript/options.js';
  458. export type {
  459. // we need to explicitely export some types, to prevent some issues with next-i18next and interpolation variable validation, etc...
  460. FallbackLngObjList,
  461. FallbackLng,
  462. InitOptions,
  463. TypeOptions,
  464. CustomTypeOptions,
  465. CustomPluginOptions,
  466. PluginOptions,
  467. FormatFunction,
  468. InterpolationOptions,
  469. ReactOptions,
  470. ResourceKey,
  471. ResourceLanguage,
  472. Resource,
  473. TOptions,
  474. Namespace,
  475. DefaultNamespace,
  476. FlatNamespace,
  477. } from './typescript/options.js';
  478. // export type * from './typescript/t.v4.js';
  479. export type {
  480. TFunction,
  481. ParseKeys,
  482. TFunctionReturn,
  483. TFunctionDetailedResult,
  484. KeyPrefix,
  485. } from './typescript/t.v4.js';
  486. declare const i18next: i18n;
  487. export default i18next;
  488. export const createInstance: i18n['createInstance'];
  489. export const dir: i18n['dir'];
  490. export const init: i18n['init'];
  491. export const loadResources: i18n['loadResources'];
  492. export const reloadResources: i18n['reloadResources'];
  493. export const use: i18n['use'];
  494. export const changeLanguage: i18n['changeLanguage'];
  495. export const getFixedT: i18n['getFixedT'];
  496. export const t: i18n['t'];
  497. export const exists: i18n['exists'];
  498. export const setDefaultNamespace: i18n['setDefaultNamespace'];
  499. export const hasLoadedNamespace: i18n['hasLoadedNamespace'];
  500. export const loadNamespaces: i18n['loadNamespaces'];
  501. export const loadLanguages: i18n['loadLanguages'];