index.d.ts 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  1. type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;
  2. type MergeBy<T, K> = Omit<T, keyof K> & K;
  3. export interface FallbackLngObjList {
  4. [language: string]: readonly string[];
  5. }
  6. export type FallbackLng =
  7. | string
  8. | readonly string[]
  9. | FallbackLngObjList
  10. | ((code: string) => string | readonly string[] | FallbackLngObjList);
  11. export type FormatFunction = (
  12. value: any,
  13. format?: string,
  14. lng?: string,
  15. options?: InterpolationOptions & { [key: string]: any },
  16. ) => string;
  17. export interface InterpolationOptions {
  18. /**
  19. * Format function see formatting for details
  20. * @default noop
  21. */
  22. format?: FormatFunction;
  23. /**
  24. * Used to separate format from interpolation value
  25. * @default ','
  26. */
  27. formatSeparator?: string;
  28. /**
  29. * Escape function
  30. * @default str => str
  31. */
  32. escape?(str: string): string;
  33. /**
  34. * Always format interpolated values.
  35. * @default false
  36. */
  37. alwaysFormat?: boolean;
  38. /**
  39. * Escape passed in values to avoid xss injection
  40. * @default true
  41. */
  42. escapeValue?: boolean;
  43. /**
  44. * If true, then value passed into escape function is not casted to string, use with custom escape function that does its own type check
  45. * @default false
  46. */
  47. useRawValueToEscape?: boolean;
  48. /**
  49. * Prefix for interpolation
  50. * @default '{{'
  51. */
  52. prefix?: string;
  53. /**
  54. * Suffix for interpolation
  55. * @default '}}'
  56. */
  57. suffix?: string;
  58. /**
  59. * Escaped prefix for interpolation (regexSafe)
  60. * @default undefined
  61. */
  62. prefixEscaped?: string;
  63. /**
  64. * Escaped suffix for interpolation (regexSafe)
  65. * @default undefined
  66. */
  67. suffixEscaped?: string;
  68. /**
  69. * Suffix to unescaped mode
  70. * @default undefined
  71. */
  72. unescapeSuffix?: string;
  73. /**
  74. * Prefix to unescaped mode
  75. * @default '-'
  76. */
  77. unescapePrefix?: string;
  78. /**
  79. * Prefix for nesting
  80. * @default '$t('
  81. */
  82. nestingPrefix?: string;
  83. /**
  84. * Suffix for nesting
  85. * @default ')'
  86. */
  87. nestingSuffix?: string;
  88. /**
  89. * Escaped prefix for nesting (regexSafe)
  90. * @default undefined
  91. */
  92. nestingPrefixEscaped?: string;
  93. /**
  94. * Escaped suffix for nesting (regexSafe)
  95. * @default undefined
  96. */
  97. nestingSuffixEscaped?: string;
  98. /**
  99. * Separates options from key
  100. * @default ','
  101. */
  102. nestingOptionsSeparator?: string;
  103. /**
  104. * Global variables to use in interpolation replacements
  105. * @default undefined
  106. */
  107. defaultVariables?: { [index: string]: any };
  108. /**
  109. * After how many interpolation runs to break out before throwing a stack overflow
  110. * @default 1000
  111. */
  112. maxReplaces?: number;
  113. /**
  114. * If true, it will skip to interpolate the variables
  115. * @default false
  116. */
  117. skipOnVariables?: boolean;
  118. }
  119. export interface ReactOptions {
  120. /**
  121. * Set to true if you like to wait for loaded in every translated hoc
  122. * @default false
  123. */
  124. wait?: boolean;
  125. /**
  126. * Set it to fallback to let passed namespaces to translated hoc act as fallbacks
  127. * @default 'default'
  128. */
  129. nsMode?: 'default' | 'fallback';
  130. /**
  131. * Set it to the default parent element created by the Trans component.
  132. * @default 'div'
  133. */
  134. defaultTransParent?: string;
  135. /**
  136. * Set which events trigger a re-render, can be set to false or string of events
  137. * @default 'languageChanged'
  138. */
  139. bindI18n?: string | false;
  140. /**
  141. * Set which events on store trigger a re-render, can be set to false or string of events
  142. * @default ''
  143. */
  144. bindI18nStore?: string | false;
  145. /**
  146. * Set fallback value for Trans components without children
  147. * @default undefined
  148. */
  149. transEmptyNodeValue?: string;
  150. /**
  151. * Set it to false if you do not want to use Suspense
  152. * @default true
  153. */
  154. useSuspense?: boolean;
  155. /**
  156. * Function to generate an i18nKey from the defaultValue (or Trans children)
  157. * when no key is provided.
  158. * By default, the defaultValue (Trans text) itself is used as the key.
  159. * If you want to require keys for all translations, supply a function
  160. * that always throws an error.
  161. * @default undefined
  162. */
  163. hashTransKey?(defaultValue: TOptionsBase['defaultValue']): TOptionsBase['defaultValue'];
  164. /**
  165. * Convert eg. <br/> found in translations to a react component of type br
  166. * @default true
  167. */
  168. transSupportBasicHtmlNodes?: boolean;
  169. /**
  170. * Which nodes not to convert in defaultValue generation in the Trans component.
  171. * @default ['br', 'strong', 'i', 'p']
  172. */
  173. transKeepBasicHtmlNodesFor?: readonly string[];
  174. /**
  175. * Wrap text nodes in a user-specified element.
  176. * @default ''
  177. */
  178. transWrapTextNodes?: string;
  179. }
  180. /**
  181. * This interface can be augmented by users to add types to `i18next` default PluginOptions.
  182. */
  183. export interface PluginOptions {}
  184. interface DefaultPluginOptions {
  185. /**
  186. * Options for language detection - check documentation of plugin
  187. * @default undefined
  188. */
  189. detection?: object;
  190. /**
  191. * Options for backend - check documentation of plugin
  192. * @default undefined
  193. */
  194. backend?: object;
  195. /**
  196. * Options for cache layer - check documentation of plugin
  197. * @default undefined
  198. */
  199. cache?: object;
  200. /**
  201. * Options for i18n message format - check documentation of plugin
  202. * @default undefined
  203. */
  204. i18nFormat?: object;
  205. }
  206. export interface InitOptions extends MergeBy<DefaultPluginOptions, PluginOptions> {
  207. /**
  208. * Logs info level to console output. Helps finding issues with loading not working.
  209. * @default false
  210. */
  211. debug?: boolean;
  212. /**
  213. * Resources to initialize with (if not using loading or not appending using addResourceBundle)
  214. * @default undefined
  215. */
  216. resources?: Resource;
  217. /**
  218. * Allow initializing with bundled resources while using a backend to load non bundled ones.
  219. * @default false
  220. */
  221. partialBundledLanguages?: boolean;
  222. /**
  223. * Language to use (overrides language detection)
  224. * @default undefined
  225. */
  226. lng?: string;
  227. /**
  228. * Language to use if translations in user language are not available.
  229. * @default 'dev'
  230. */
  231. fallbackLng?: false | FallbackLng;
  232. /**
  233. * DEPRECATED use supportedLngs
  234. * @default false
  235. */
  236. whitelist?: false | readonly string[];
  237. /**
  238. * DEPRECTADED use nonExplicitSupportedLngs
  239. * @default false
  240. */
  241. nonExplicitWhitelist?: boolean;
  242. /**
  243. * Array of allowed languages
  244. * @default false
  245. */
  246. supportedLngs?: false | readonly string[];
  247. /**
  248. * If true will pass eg. en-US if finding en in supportedLngs
  249. * @default false
  250. */
  251. nonExplicitSupportedLngs?: boolean;
  252. /**
  253. * Language codes to lookup, given set language is
  254. * 'en-US': 'all' --> ['en-US', 'en', 'dev'],
  255. * 'currentOnly' --> 'en-US',
  256. * 'languageOnly' --> 'en'
  257. * @default 'all'
  258. */
  259. load?: 'all' | 'currentOnly' | 'languageOnly';
  260. /**
  261. * Array of languages to preload. Important on server-side to assert translations are loaded before rendering views.
  262. * @default false
  263. */
  264. preload?: false | readonly string[];
  265. /**
  266. * Language will be lowercased eg. en-US --> en-us
  267. * @default false
  268. */
  269. lowerCaseLng?: boolean;
  270. /**
  271. * Language will be lowercased EN --> en while leaving full locales like en-US
  272. * @default false
  273. */
  274. cleanCode?: boolean;
  275. /**
  276. * String or array of namespaces to load
  277. * @default 'translation'
  278. */
  279. ns?: string | readonly string[];
  280. /**
  281. * Default namespace used if not passed to translation function
  282. * @default 'translation'
  283. */
  284. defaultNS?: string;
  285. /**
  286. * String or array of namespaces to lookup key if not found in given namespace.
  287. * @default false
  288. */
  289. fallbackNS?: false | string | readonly string[];
  290. /**
  291. * Calls save missing key function on backend if key not found
  292. * @default false
  293. */
  294. saveMissing?: boolean;
  295. /**
  296. * Experimental: enable to update default values using the saveMissing
  297. * (Works only if defaultValue different from translated value.
  298. * Only useful on initial development or when keeping code as source of truth not changing values outside of code.
  299. * Only supported if backend supports it already)
  300. * @default false
  301. */
  302. updateMissing?: boolean;
  303. /**
  304. * @default 'fallback'
  305. */
  306. saveMissingTo?: 'current' | 'all' | 'fallback';
  307. /**
  308. * Used to not fallback to the key as default value, when using saveMissing functionality.
  309. * i.e. when using with i18next-http-backend this will result in having a key with an empty string value.
  310. * @default false
  311. */
  312. missingKeyNoValueFallbackToKey?: boolean;
  313. /**
  314. * Used for custom missing key handling (needs saveMissing set to true!)
  315. * @default false
  316. */
  317. missingKeyHandler?:
  318. | false
  319. | ((
  320. lngs: readonly string[],
  321. ns: string,
  322. key: string,
  323. fallbackValue: string,
  324. updateMissing: boolean,
  325. options: any,
  326. ) => void);
  327. /**
  328. * Receives a key that was not found in `t()` and returns a value, that will be returned by `t()`
  329. * @default noop
  330. */
  331. parseMissingKeyHandler?(key: string): any;
  332. /**
  333. * Appends namespace to missing key
  334. * @default false
  335. */
  336. appendNamespaceToMissingKey?: boolean;
  337. /**
  338. * Gets called in case a interpolation value is undefined. This method will not be called if the value is empty string or null
  339. * @default noop
  340. */
  341. missingInterpolationHandler?: (text: string, value: any, options: InitOptions) => any;
  342. /**
  343. * Will use 'plural' as suffix for languages only having 1 plural form, setting it to false will suffix all with numbers
  344. * @default true
  345. */
  346. simplifyPluralSuffix?: boolean;
  347. /**
  348. * String or array of postProcessors to apply per default
  349. * @default false
  350. */
  351. postProcess?: false | string | readonly string[];
  352. /**
  353. * passthrough the resolved object including 'usedNS', 'usedLang' etc into options object of postprocessors as 'i18nResolved' property
  354. * @default false
  355. */
  356. postProcessPassResolved?: boolean;
  357. /**
  358. * Allows null values as valid translation
  359. * @default true
  360. */
  361. returnNull?: boolean;
  362. /**
  363. * Allows empty string as valid translation
  364. * @default true
  365. */
  366. returnEmptyString?: boolean;
  367. /**
  368. * Allows objects as valid translation result
  369. * @default false
  370. */
  371. returnObjects?: boolean;
  372. /**
  373. * Gets called if object was passed in as key but returnObjects was set to false
  374. * @default noop
  375. */
  376. returnedObjectHandler?(key: string, value: string, options: any): void;
  377. /**
  378. * Char, eg. '\n' that arrays will be joined by
  379. * @default false
  380. */
  381. joinArrays?: false | string;
  382. /**
  383. * Sets defaultValue
  384. * @default args => ({ defaultValue: args[1] })
  385. */
  386. overloadTranslationOptionHandler?(args: string[]): TOptions;
  387. /**
  388. * @see https://www.i18next.com/interpolation.html
  389. */
  390. interpolation?: InterpolationOptions;
  391. /**
  392. * Options for react - check documentation of plugin
  393. * @default undefined
  394. */
  395. react?: ReactOptions;
  396. /**
  397. * Triggers resource loading in init function inside a setTimeout (default async behaviour).
  398. * Set it to false if your backend loads resources sync - that way calling i18next.t after
  399. * init is possible without relaying on the init callback.
  400. * @default true
  401. */
  402. initImmediate?: boolean;
  403. /**
  404. * Char to separate keys
  405. * @default '.'
  406. */
  407. keySeparator?: false | string;
  408. /**
  409. * Char to split namespace from key
  410. * @default ':'
  411. */
  412. nsSeparator?: false | string;
  413. /**
  414. * Char to split plural from key
  415. * @default '_'
  416. */
  417. pluralSeparator?: string;
  418. /**
  419. * Char to split context from key
  420. * @default '_'
  421. */
  422. contextSeparator?: string;
  423. /**
  424. * Prefixes the namespace to the returned key when using `cimode`
  425. * @default false
  426. */
  427. appendNamespaceToCIMode?: boolean;
  428. /**
  429. * Compatibility JSON version
  430. * @default 'v3'
  431. */
  432. compatibilityJSON?: 'v1' | 'v2' | 'v3';
  433. /**
  434. * Options for https://github.com/locize/locize-editor
  435. * @default undefined
  436. */
  437. editor?: {
  438. /**
  439. * Enable on init without the need of adding querystring locize=true
  440. * @default false
  441. */
  442. enabled?: boolean;
  443. /**
  444. * If set to false you will need to open the editor via API
  445. * @default true
  446. */
  447. autoOpen?: boolean;
  448. /**
  449. * Enable by adding querystring locize=true; can be set to another value or turned off by setting to false
  450. * @default 'locize'
  451. */
  452. enableByQS?: string | false;
  453. /**
  454. * Turn on/off by pressing key combination. Combine this with `toggleKeyCode`
  455. * @default 'ctrlKey'
  456. */
  457. toggleKeyModifier?: 'ctrlKey' | 'metaKey' | 'altKey' | 'shiftKey';
  458. /**
  459. * Turn on/off by pressing key combination. Combine this with `toggleKeyModifier`
  460. * @default 24 (x)
  461. */
  462. toggleKeyCode?: number;
  463. /**
  464. * Use lng in editor taken from query string, eg. if running with lng=cimode (i18next, locize)
  465. * @default 'useLng'
  466. */
  467. lngOverrideQS?: string;
  468. /**
  469. * Use lng in editor, eg. if running with lng=cimode (i18next, locize)
  470. * @default null
  471. */
  472. lngOverride?: string | null;
  473. /**
  474. * How the editor will open.
  475. * Setting to window will open a new window/tab instead
  476. * @default 'iframe'
  477. */
  478. mode?: 'iframe' | 'window';
  479. /**
  480. * Styles to adapt layout in iframe mode to your website layout.
  481. * This will add a style to the `<iframe>`
  482. * @default 'z-index: 2000; position: fixed; top: 0; right: 0; bottom: 0; width: 600px; box-shadow: -3px 0 5px 0 rgba(0,0,0,0.5);'
  483. */
  484. iframeContainerStyle?: string;
  485. /**
  486. * Styles to adapt layout in iframe mode to your website layout.
  487. * This will add a style to the parent of `<iframe>`
  488. * @default 'height: 100%; width: 600px; border: none;'
  489. */
  490. iframeStyle?: string;
  491. /**
  492. * Styles to adapt layout in iframe mode to your website layout.
  493. * This will add a style to `<body>`
  494. * @default 'margin-right: 605px;'
  495. */
  496. bodyStyle?: string;
  497. /**
  498. * Handle when locize saved the edited translations, eg. reload website
  499. * @default noop
  500. */
  501. onEditorSaved?: (lng: null, ns: string | readonly string[]) => void;
  502. };
  503. /**
  504. * Options for https://github.com/locize/locize-lastused
  505. * @default undefined
  506. */
  507. locizeLastUsed?: {
  508. /**
  509. * The id of your locize project
  510. */
  511. projectId: string;
  512. /**
  513. * An api key if you want to send missing keys
  514. */
  515. apiKey?: string;
  516. /**
  517. * The reference language of your project
  518. * @default 'en'
  519. */
  520. referenceLng?: string;
  521. /**
  522. * Version
  523. * @default 'latest'
  524. */
  525. version?: string;
  526. /**
  527. * Debounce interval to send data in milliseconds
  528. * @default 90000
  529. */
  530. debounceSubmit?: number;
  531. /**
  532. * Hostnames that are allowed to send last used data.
  533. * Please keep those to your local system, staging, test servers (not production)
  534. * @default ['localhost']
  535. */
  536. allowedHosts?: readonly string[];
  537. };
  538. /**
  539. * Automatically lookup for a flat key if a nested key is not found an vice-versa
  540. * @default true
  541. */
  542. ignoreJSONStructure?: boolean;
  543. }
  544. export interface TOptionsBase {
  545. /**
  546. * Default value to return if a translation was not found
  547. */
  548. defaultValue?: any;
  549. /**
  550. * Count value used for plurals
  551. */
  552. count?: number;
  553. /**
  554. * Used for contexts (eg. male\female)
  555. */
  556. context?: any;
  557. /**
  558. * Object with vars for interpolation - or put them directly in options
  559. */
  560. replace?: any;
  561. /**
  562. * Override language to use
  563. */
  564. lng?: string;
  565. /**
  566. * Override languages to use
  567. */
  568. lngs?: readonly string[];
  569. /**
  570. * Override language to lookup key if not found see fallbacks for details
  571. */
  572. fallbackLng?: FallbackLng;
  573. /**
  574. * Override namespaces (string or array)
  575. */
  576. ns?: string | readonly string[];
  577. /**
  578. * Override char to separate keys
  579. */
  580. keySeparator?: false | string;
  581. /**
  582. * Override char to split namespace from key
  583. */
  584. nsSeparator?: false | string;
  585. /**
  586. * Accessing an object not a translation string (can be set globally too)
  587. */
  588. returnObjects?: boolean;
  589. /**
  590. * Char, eg. '\n' that arrays will be joined by (can be set globally too)
  591. */
  592. joinArrays?: string;
  593. /**
  594. * String or array of postProcessors to apply see interval plurals as a sample
  595. */
  596. postProcess?: string | readonly string[];
  597. /**
  598. * Override interpolation options
  599. */
  600. interpolation?: InterpolationOptions;
  601. }
  602. /**
  603. * indexer that is open to any value
  604. */
  605. export type StringMap = { [key: string]: any };
  606. /**
  607. * Options that allow open ended values for interpolation unless type is provided.
  608. */
  609. export type TOptions<TInterpolationMap extends object = StringMap> = TOptionsBase &
  610. TInterpolationMap;
  611. export type Callback = (error: any, t: TFunction) => void;
  612. /**
  613. * Uses similar args as the t function and returns true if a key exists.
  614. */
  615. export interface ExistsFunction<
  616. TKeys extends string = string,
  617. TInterpolationMap extends object = StringMap
  618. > {
  619. (key: TKeys | TKeys[], options?: TOptions<TInterpolationMap>): boolean;
  620. }
  621. export interface WithT {
  622. // Expose parameterized t in the i18next interface hierarchy
  623. t: TFunction;
  624. }
  625. export type TFunctionResult = string | object | Array<string | object> | undefined | null;
  626. export type TFunctionKeys = string | TemplateStringsArray;
  627. export interface TFunction {
  628. // basic usage
  629. <
  630. TResult extends TFunctionResult = string,
  631. TKeys extends TFunctionKeys = string,
  632. TInterpolationMap extends object = StringMap
  633. >(
  634. key: TKeys | TKeys[],
  635. options?: TOptions<TInterpolationMap> | string,
  636. ): TResult;
  637. // overloaded usage
  638. <
  639. TResult extends TFunctionResult = string,
  640. TKeys extends TFunctionKeys = string,
  641. TInterpolationMap extends object = StringMap
  642. >(
  643. key: TKeys | TKeys[],
  644. defaultValue?: string,
  645. options?: TOptions<TInterpolationMap> | string,
  646. ): TResult;
  647. }
  648. export interface Resource {
  649. [language: string]: ResourceLanguage;
  650. }
  651. export interface ResourceLanguage {
  652. [namespace: string]: ResourceKey;
  653. }
  654. export type ResourceKey =
  655. | string
  656. | {
  657. [key: string]: any;
  658. };
  659. export interface Interpolator {
  660. init(options: InterpolationOptions, reset: boolean): undefined;
  661. reset(): undefined;
  662. resetRegExp(): undefined;
  663. interpolate(str: string, data: object, lng: string, options: InterpolationOptions): string;
  664. nest(str: string, fc: (...args: any[]) => any, options: InterpolationOptions): string;
  665. }
  666. export class ResourceStore {
  667. constructor(data: Resource, options: InitOptions);
  668. public data: Resource;
  669. public options: InitOptions;
  670. /**
  671. * Gets fired when resources got added or removed
  672. */
  673. on(event: 'added' | 'removed', callback: (lng: string, ns: string) => void): void;
  674. /**
  675. * Remove event listener
  676. * removes all callback when callback not specified
  677. */
  678. off(event: 'added' | 'removed', callback?: (lng: string, ns: string) => void): void;
  679. }
  680. export interface Services {
  681. backendConnector: any;
  682. i18nFormat: any;
  683. interpolator: Interpolator;
  684. languageDetector: any;
  685. languageUtils: any;
  686. logger: any;
  687. pluralResolver: any;
  688. resourceStore: ResourceStore;
  689. }
  690. export type ModuleType =
  691. | 'backend'
  692. | 'logger'
  693. | 'languageDetector'
  694. | 'postProcessor'
  695. | 'i18nFormat'
  696. | '3rdParty';
  697. export interface Module {
  698. type: ModuleType;
  699. }
  700. export type CallbackError = Error | null | undefined;
  701. export type ReadCallback = (
  702. err: CallbackError,
  703. data: ResourceKey | boolean | null | undefined,
  704. ) => void;
  705. export type MultiReadCallback = (err: CallbackError, data: Resource | null | undefined) => void;
  706. /**
  707. * Used to load data for i18next.
  708. * Can be provided as a singleton or as a prototype constructor (preferred for supporting multiple instances of i18next).
  709. * For singleton set property `type` to `'backend'` For a prototype constructor set static property.
  710. */
  711. export interface BackendModule<TOptions = object> extends Module {
  712. type: 'backend';
  713. init(services: Services, backendOptions: TOptions, i18nextOptions: InitOptions): void;
  714. read(language: string, namespace: string, callback: ReadCallback): void;
  715. /** Save the missing translation */
  716. create?(
  717. languages: readonly string[],
  718. namespace: string,
  719. key: string,
  720. fallbackValue: string,
  721. ): void;
  722. /** Load multiple languages and namespaces. For backends supporting multiple resources loading */
  723. readMulti?(
  724. languages: readonly string[],
  725. namespaces: readonly string[],
  726. callback: MultiReadCallback,
  727. ): void;
  728. /** Store the translation. For backends acting as cache layer */
  729. save?(language: string, namespace: string, data: ResourceLanguage): void;
  730. }
  731. /**
  732. * Used to detect language in user land.
  733. * Can be provided as a singleton or as a prototype constructor (preferred for supporting multiple instances of i18next).
  734. * For singleton set property `type` to `'languageDetector'` For a prototype constructor set static property.
  735. */
  736. export interface LanguageDetectorModule extends Module {
  737. type: 'languageDetector';
  738. init(services: Services, detectorOptions: object, i18nextOptions: InitOptions): void;
  739. /** Must return detected language */
  740. detect(): string | readonly string[] | undefined;
  741. cacheUserLanguage(lng: string): void;
  742. }
  743. /**
  744. * Used to detect language in user land.
  745. * Can be provided as a singleton or as a prototype constructor (preferred for supporting multiple instances of i18next).
  746. * For singleton set property `type` to `'languageDetector'` For a prototype constructor set static property.
  747. */
  748. export interface LanguageDetectorAsyncModule extends Module {
  749. type: 'languageDetector';
  750. /** Set to true to enable async detection */
  751. async: true;
  752. init(services: Services, detectorOptions: object, i18nextOptions: InitOptions): void;
  753. /** Must call callback passing detected language */
  754. detect(callback: (lng: string | readonly string[] | undefined) => void): void;
  755. cacheUserLanguage(lng: string): void;
  756. }
  757. /**
  758. * Used to extend or manipulate the translated values before returning them in `t` function.
  759. * Need to be a singleton object.
  760. */
  761. export interface PostProcessorModule extends Module {
  762. /** Unique name */
  763. name: string;
  764. type: 'postProcessor';
  765. process(value: string, key: string, options: TOptions, translator: any): string;
  766. }
  767. /**
  768. * Override the built-in console logger.
  769. * Do not need to be a prototype function.
  770. */
  771. export interface LoggerModule extends Module {
  772. type: 'logger';
  773. log(...args: any[]): void;
  774. warn(...args: any[]): void;
  775. error(...args: any[]): void;
  776. }
  777. export interface I18nFormatModule extends Module {
  778. type: 'i18nFormat';
  779. }
  780. export interface ThirdPartyModule extends Module {
  781. type: '3rdParty';
  782. init(i18next: i18n): void;
  783. }
  784. export interface Modules {
  785. backend?: BackendModule;
  786. logger?: LoggerModule;
  787. languageDetector?: LanguageDetectorModule | LanguageDetectorAsyncModule;
  788. i18nFormat?: I18nFormatModule;
  789. external: ThirdPartyModule[];
  790. }
  791. // helper to identify class https://stackoverflow.com/a/45983481/2363935
  792. export interface Newable<T> {
  793. new (...args: any[]): T;
  794. }
  795. export interface NewableModule<T extends Module> extends Newable<T> {
  796. type: T['type'];
  797. }
  798. export interface i18n {
  799. // Expose parameterized t in the i18next interface hierarchy
  800. t: TFunction;
  801. /**
  802. * The default of the i18next module is an i18next instance ready to be initialized by calling init.
  803. * You can create additional instances using the createInstance function.
  804. *
  805. * @param options - Initial options.
  806. * @param callback - will be called after all translations were loaded or with an error when failed (in case of using a backend).
  807. */
  808. init(callback?: Callback): Promise<TFunction>;
  809. init(options: InitOptions, callback?: Callback): Promise<TFunction>;
  810. loadResources(callback?: (err: any) => void): void;
  811. /**
  812. * The use function is there to load additional plugins to i18next.
  813. * For available module see the plugins page and don't forget to read the documentation of the plugin.
  814. *
  815. * @param module Accepts a class or object
  816. */
  817. use<T extends Module>(module: T | NewableModule<T> | Newable<T>): this;
  818. /**
  819. * List of modules used
  820. */
  821. modules: Modules;
  822. /**
  823. * Internal container for all used plugins and implementation details like languageUtils, pluralResolvers, etc.
  824. */
  825. services: Services;
  826. /**
  827. * Internal container for translation resources
  828. */
  829. store: ResourceStore;
  830. /**
  831. * Uses similar args as the t function and returns true if a key exists.
  832. */
  833. exists: ExistsFunction;
  834. /**
  835. * Returns a resource data by language.
  836. */
  837. getDataByLanguage(lng: string): { translation: { [key: string]: string } } | undefined;
  838. /**
  839. * Returns a t function that defaults to given language or namespace.
  840. * Both params could be arrays of languages or namespaces and will be treated as fallbacks in that case.
  841. * 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.
  842. *
  843. * Accepts optional keyPrefix that will be automatically applied to returned t function.
  844. */
  845. getFixedT(
  846. lng: string | readonly string[],
  847. ns?: string | readonly string[],
  848. keyPrefix?: string,
  849. ): TFunction;
  850. getFixedT(lng: null, ns: string | readonly string[] | null, keyPrefix?: string): TFunction;
  851. /**
  852. * Changes the language. The callback will be called as soon translations were loaded or an error occurs while loading.
  853. * HINT: For easy testing - setting lng to 'cimode' will set t function to always return the key.
  854. */
  855. changeLanguage(lng?: string, callback?: Callback): Promise<TFunction>;
  856. /**
  857. * Is set to the current detected or set language.
  858. * If you need the primary used language depending on your configuration (supportedLngs, load) you will prefer using i18next.languages[0].
  859. */
  860. language: string;
  861. /**
  862. * Is set to an array of language-codes that will be used it order to lookup the translation value.
  863. */
  864. languages: readonly string[];
  865. /**
  866. * Loads additional namespaces not defined in init options.
  867. */
  868. loadNamespaces(ns: string | readonly string[], callback?: Callback): Promise<void>;
  869. /**
  870. * Loads additional languages not defined in init options (preload).
  871. */
  872. loadLanguages(lngs: string | readonly string[], callback?: Callback): Promise<void>;
  873. /**
  874. * 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.
  875. */
  876. reloadResources(
  877. lngs?: string | readonly string[],
  878. ns?: string | readonly string[],
  879. callback?: () => void,
  880. ): Promise<void>;
  881. reloadResources(lngs: null, ns: string | readonly string[], callback?: () => void): Promise<void>;
  882. /**
  883. * Changes the default namespace.
  884. */
  885. setDefaultNamespace(ns: string): void;
  886. /**
  887. * Returns rtl or ltr depending on languages read direction.
  888. */
  889. dir(lng?: string): 'ltr' | 'rtl';
  890. /**
  891. * Exposes interpolation.format function added on init.
  892. */
  893. format: FormatFunction;
  894. /**
  895. * Will return a new i18next instance.
  896. * Please read the options page for details on configuration options.
  897. * Providing a callback will automatically call init.
  898. * The callback will be called after all translations were loaded or with an error when failed (in case of using a backend).
  899. */
  900. createInstance(options?: InitOptions, callback?: Callback): i18n;
  901. /**
  902. * Creates a clone of the current instance. Shares store, plugins and initial configuration.
  903. * Can be used to create an instance sharing storage but being independent on set language or namespaces.
  904. */
  905. cloneInstance(options?: InitOptions, callback?: Callback): i18n;
  906. /**
  907. * Gets fired after initialization.
  908. */
  909. on(event: 'initialized', callback: (options: InitOptions) => void): void;
  910. /**
  911. * Gets fired on loaded resources.
  912. */
  913. on(event: 'loaded', callback: (loaded: { [language: string]: readonly string[] }) => void): void;
  914. /**
  915. * Gets fired if loading resources failed.
  916. */
  917. on(event: 'failedLoading', callback: (lng: string, ns: string, msg: string) => void): void;
  918. /**
  919. * Gets fired on accessing a key not existing.
  920. */
  921. on(
  922. event: 'missingKey',
  923. callback: (lngs: readonly string[], namespace: string, key: string, res: string) => void,
  924. ): void;
  925. /**
  926. * Gets fired when resources got added or removed.
  927. */
  928. on(event: 'added' | 'removed', callback: (lng: string, ns: string) => void): void;
  929. /**
  930. * Gets fired when changeLanguage got called.
  931. */
  932. on(event: 'languageChanged', callback: (lng: string) => void): void;
  933. /**
  934. * Event listener
  935. */
  936. on(event: string, listener: (...args: any[]) => void): void;
  937. /**
  938. * Remove event listener
  939. * removes all callback when callback not specified
  940. */
  941. off(event: string, listener?: (...args: any[]) => void): void;
  942. /**
  943. * Gets one value by given key.
  944. */
  945. getResource(
  946. lng: string,
  947. ns: string,
  948. key: string,
  949. options?: Pick<InitOptions, 'keySeparator' | 'ignoreJSONStructure'>,
  950. ): any;
  951. /**
  952. * Adds one key/value.
  953. */
  954. addResource(
  955. lng: string,
  956. ns: string,
  957. key: string,
  958. value: string,
  959. options?: { keySeparator?: string; silent?: boolean },
  960. ): i18n;
  961. /**
  962. * Adds multiple key/values.
  963. */
  964. addResources(lng: string, ns: string, resources: any): i18n;
  965. /**
  966. * Adds a complete bundle.
  967. * Setting deep param to true will extend existing translations in that file.
  968. * Setting overwrite to true it will overwrite existing translations in that file.
  969. */
  970. addResourceBundle(
  971. lng: string,
  972. ns: string,
  973. resources: any,
  974. deep?: boolean,
  975. overwrite?: boolean,
  976. ): i18n;
  977. /**
  978. * Checks if a resource bundle exists.
  979. */
  980. hasResourceBundle(lng: string, ns: string): boolean;
  981. /**
  982. * Returns a resource bundle.
  983. */
  984. getResourceBundle(lng: string, ns: string): any;
  985. /**
  986. * Removes an existing bundle.
  987. */
  988. removeResourceBundle(lng: string, ns: string): i18n;
  989. /**
  990. * Current options
  991. */
  992. options: InitOptions;
  993. /**
  994. * Is initialized
  995. */
  996. isInitialized: boolean;
  997. /**
  998. * Emit event
  999. */
  1000. emit(eventName: string): void;
  1001. }
  1002. declare const i18next: i18n;
  1003. export default i18next;