@sapphire/plugin-i18next 7.1.3-next.fc8e636 → 7.1.3
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/CHANGELOG.md +16 -0
- package/README.md +0 -1
- package/dist/cjs/index.cjs +2 -2
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +12 -3
- package/dist/cjs/lib/Augmentations.d.cjs +1 -1
- package/dist/cjs/lib/Augmentations.d.cjs.map +1 -1
- package/dist/cjs/lib/InternationalizationHandler.cjs +5 -2
- package/dist/cjs/lib/InternationalizationHandler.cjs.map +1 -1
- package/dist/cjs/lib/functions.cjs +2 -2
- package/dist/cjs/lib/functions.cjs.map +1 -1
- package/dist/cjs/lib/types.cjs +1 -1
- package/dist/cjs/lib/types.cjs.map +1 -1
- package/dist/cjs/register.cjs +2 -3
- package/dist/cjs/register.cjs.map +1 -1
- package/dist/esm/chunk-2JTKI4GS.mjs +1 -1
- package/dist/esm/chunk-2JTKI4GS.mjs.map +1 -1
- package/dist/esm/index.d.mts +12 -3
- package/dist/esm/index.mjs +2 -2
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/lib/Augmentations.d.mjs +1 -1
- package/dist/esm/lib/Augmentations.d.mjs.map +1 -1
- package/dist/esm/lib/InternationalizationHandler.mjs +5 -2
- package/dist/esm/lib/InternationalizationHandler.mjs.map +1 -1
- package/dist/esm/lib/functions.mjs +2 -2
- package/dist/esm/lib/functions.mjs.map +1 -1
- package/dist/esm/lib/types.mjs +1 -1
- package/dist/esm/lib/types.mjs.map +1 -1
- package/dist/esm/register.mjs +2 -3
- package/dist/esm/register.mjs.map +1 -1
- package/package.json +10 -10
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
|
+
# [@sapphire/plugin-i18next@7.1.3](https://github.com/sapphiredev/plugins/compare/@sapphire/plugin-i18next@7.1.2...@sapphire/plugin-i18next@7.1.3) - (2024-11-02)
|
|
6
|
+
|
|
7
|
+
## 🏠 Refactor
|
|
8
|
+
|
|
9
|
+
- **i18next:** Update the dependency to 23.15.1 accounting for typescript changes ([f8b2f60](https://github.com/sapphiredev/plugins/commit/f8b2f608af2119c4419c20089debb9d543ce564d)) ([#629](https://github.com/sapphiredev/plugins/pull/629) by @favna)
|
|
10
|
+
|
|
11
|
+
## 🐛 Bug Fixes
|
|
12
|
+
|
|
13
|
+
- Update sapphire dependencies ([a837459](https://github.com/sapphiredev/plugins/commit/a83745920f0b6eb896c7b9b5c9624dad662f5186))
|
|
14
|
+
- **deps:** Update dependency chokidar to v4 ([e6fdc84](https://github.com/sapphiredev/plugins/commit/e6fdc8494268eec4aba7f06f54e48454b2fabbc0)) ([#626](https://github.com/sapphiredev/plugins/pull/626) by @renovate[bot])
|
|
15
|
+
- Update for latest discord.js ([821ff70](https://github.com/sapphiredev/plugins/commit/821ff705c078888c91cac57a724b3d2f2ed89a82)) ([#622](https://github.com/sapphiredev/plugins/pull/622) by @favna)
|
|
16
|
+
- **deps:** Update all non-major dependencies ([43df709](https://github.com/sapphiredev/plugins/commit/43df70954d837f7b14d62ea9123aca4b1da9ae36)) ([#574](https://github.com/sapphiredev/plugins/pull/574) by @renovate[bot])
|
|
17
|
+
- **deps:** Update all non-major dependencies ([7909d16](https://github.com/sapphiredev/plugins/commit/7909d16fcec9a8e5e9a3f8816c90a26fbc7d1284)) ([#573](https://github.com/sapphiredev/plugins/pull/573) by @renovate[bot])
|
|
18
|
+
- **i18next:** Add overloaded methods and fix tsdoc for those ([5fc4ae9](https://github.com/sapphiredev/plugins/commit/5fc4ae9e908a2453f01634f193dc8db7ed6fd032))
|
|
19
|
+
- **deps:** Update all non-major dependencies ([ee64834](https://github.com/sapphiredev/plugins/commit/ee64834c799a5ac28b1ae172cb19f77a1887f3d4)) ([#546](https://github.com/sapphiredev/plugins/pull/546) by @renovate[bot])
|
|
20
|
+
|
|
5
21
|
# [@sapphire/plugin-i18next@7.1.2](https://github.com/sapphiredev/plugins/compare/@sapphire/plugin-i18next@7.1.2...@sapphire/plugin-i18next@7.1.2) - (2024-02-09)
|
|
6
22
|
|
|
7
23
|
## 🐛 Bug Fixes
|
package/README.md
CHANGED
|
@@ -7,7 +7,6 @@
|
|
|
7
7
|
**Plugin for <a href="https://github.com/sapphiredev/framework">@sapphire/framework</a> to support i18next based internationalization.**
|
|
8
8
|
|
|
9
9
|
[](https://github.com/sapphiredev/plugins/blob/main/LICENSE.md)
|
|
10
|
-
[](https://codecov.io/gh/sapphiredev/plugins)
|
|
11
10
|
[](https://bundlephobia.com/result?p=@sapphire/plugin-in17n)
|
|
12
11
|
[](https://www.npmjs.com/package/@sapphire/plugin-in17n)
|
|
13
12
|
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -10,7 +10,7 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
|
10
10
|
var i18next__default = /*#__PURE__*/_interopDefault(i18next);
|
|
11
11
|
|
|
12
12
|
// src/index.ts
|
|
13
|
-
var version = "7.1.3
|
|
13
|
+
var version = "7.1.3";
|
|
14
14
|
|
|
15
15
|
Object.defineProperty(exports, "i18next", {
|
|
16
16
|
enumerable: true,
|
|
@@ -35,5 +35,5 @@ Object.keys(types_cjs).forEach(function (k) {
|
|
|
35
35
|
get: function () { return types_cjs[k]; }
|
|
36
36
|
});
|
|
37
37
|
});
|
|
38
|
-
//# sourceMappingURL=
|
|
38
|
+
//# sourceMappingURL=index.cjs.map
|
|
39
39
|
//# sourceMappingURL=index.cjs.map
|
package/dist/cjs/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts"],"names":[
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAyBO,IAAM,OAAkB,GAAA","file":"index.cjs","sourcesContent":["import type { InternationalizationHandler } from './lib/InternationalizationHandler';\nimport type { InternationalizationClientOptions } from './lib/types';\n\nexport { default as i18next, type TFunction, type TOptions } from 'i18next';\nexport * from './lib/InternationalizationHandler';\nexport * from './lib/functions';\nexport * from './lib/types';\n\ndeclare module '@sapphire/pieces' {\n\tinterface Container {\n\t\ti18n: InternationalizationHandler;\n\t}\n}\n\ndeclare module 'discord.js' {\n\texport interface ClientOptions extends InternationalizationClientOptions {}\n}\n\n/**\n * The [@sapphire/plugin-i18next](https://github.com/sapphiredev/plugins/blob/main/packages/i18next) version that you are currently using.\n * An example use of this is showing it of in a bot information command.\n *\n * Note to Sapphire developers: This needs to explicitly be `string` so it is not typed as the string that gets replaced by esbuild\n */\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const version: string = '7.1.3';\n"]}
|
package/dist/cjs/index.d.cts
CHANGED
|
@@ -4,9 +4,18 @@ import * as i18next from 'i18next';
|
|
|
4
4
|
import { InitOptions, TFunction, ParseKeys, TOptions, Namespace, DefaultNamespace, TFunctionReturn, AppendKeyPrefix, InterpolationMap, TFunctionReturnOptionalDetails } from 'i18next';
|
|
5
5
|
export { TFunction, TOptions, default as i18next } from 'i18next';
|
|
6
6
|
import { PathLike } from 'node:fs';
|
|
7
|
-
import {
|
|
7
|
+
import { ChokidarOptions } from 'chokidar';
|
|
8
8
|
import { Message, StageChannel, VoiceChannel, Guild, User, Interaction, LocalizationMap, BaseInteraction, APIApplicationCommandOptionChoice } from 'discord.js';
|
|
9
9
|
|
|
10
|
+
/**
|
|
11
|
+
* This is a re-exported type from i18next.
|
|
12
|
+
*
|
|
13
|
+
* We could use NoInfer typescript build-in utility,
|
|
14
|
+
* however this project still supports ts < 5.4.
|
|
15
|
+
*
|
|
16
|
+
* @see https://github.com/millsp/ts-toolbelt/blob/master/sources/Function/NoInfer.ts
|
|
17
|
+
*/
|
|
18
|
+
type $NoInfer<A> = [A][A extends any ? 0 : never];
|
|
10
19
|
/**
|
|
11
20
|
* This is a re-exported type from i18next.
|
|
12
21
|
* It is essentially an object of key-value pairs, where the key is a string and the value is any.
|
|
@@ -42,7 +51,7 @@ interface HMROptions {
|
|
|
42
51
|
/**
|
|
43
52
|
* HMR options
|
|
44
53
|
*/
|
|
45
|
-
options?:
|
|
54
|
+
options?: ChokidarOptions;
|
|
46
55
|
}
|
|
47
56
|
/**
|
|
48
57
|
* Used to dynamically add options based on found languages in {@link InternationalizationHandler#init}.
|
|
@@ -494,4 +503,4 @@ declare module 'discord.js' {
|
|
|
494
503
|
*/
|
|
495
504
|
declare const version: string;
|
|
496
505
|
|
|
497
|
-
export { type $Dictionary, type $SpecialObject, type BuilderWithDescription, type BuilderWithName, type BuilderWithNameAndDescription, type ChannelTarget, type DiscordChannel, type DynamicOptions, type HMROptions, type I18nextFormatter, type I18nextFormatters, type I18nextNamedCachedFormatter, type I18nextNamedFormatter, type InternationalizationClientOptions, type InternationalizationContext, InternationalizationHandler, type InternationalizationOptions, type LocalizedData, type Target, type TextBasedDiscordChannel, applyDescriptionLocalizedBuilder, applyLocalizedBuilder, applyNameLocalizedBuilder, createLocalizedChoice, fetchLanguage, fetchT, getLocalizedData, resolveKey, version };
|
|
506
|
+
export { type $Dictionary, type $NoInfer, type $SpecialObject, type BuilderWithDescription, type BuilderWithName, type BuilderWithNameAndDescription, type ChannelTarget, type DiscordChannel, type DynamicOptions, type HMROptions, type I18nextFormatter, type I18nextFormatters, type I18nextNamedCachedFormatter, type I18nextNamedFormatter, type InternationalizationClientOptions, type InternationalizationContext, InternationalizationHandler, type InternationalizationOptions, type LocalizedData, type Target, type TextBasedDiscordChannel, applyDescriptionLocalizedBuilder, applyLocalizedBuilder, applyNameLocalizedBuilder, createLocalizedChoice, fetchLanguage, fetchT, getLocalizedData, resolveKey, version };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"Augmentations.d.cjs"}
|
|
@@ -175,7 +175,10 @@ var _InternationalizationHandler = class _InternationalizationHandler {
|
|
|
175
175
|
const language = this.languages.get(locale);
|
|
176
176
|
if (!language) throw new ReferenceError("Invalid language provided");
|
|
177
177
|
const defaultValue = typeof defaultValueOrOptions === "string" ? defaultValueOrOptions : this.options.defaultMissingKey ? language(this.options.defaultMissingKey, { replace: { key } }) : "";
|
|
178
|
-
return language(key, {
|
|
178
|
+
return language(key, {
|
|
179
|
+
defaultValue,
|
|
180
|
+
...optionsOrUndefined ?? {}
|
|
181
|
+
});
|
|
179
182
|
}
|
|
180
183
|
/**
|
|
181
184
|
* @param directory The directory that should be walked.
|
|
@@ -229,5 +232,5 @@ __name(_InternationalizationHandler, "InternationalizationHandler");
|
|
|
229
232
|
var InternationalizationHandler = _InternationalizationHandler;
|
|
230
233
|
|
|
231
234
|
exports.InternationalizationHandler = InternationalizationHandler;
|
|
232
|
-
//# sourceMappingURL=
|
|
235
|
+
//# sourceMappingURL=InternationalizationHandler.cjs.map
|
|
233
236
|
//# sourceMappingURL=InternationalizationHandler.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/lib/InternationalizationHandler.ts"],"names":[],"mappings":";;;;;;AAAA,SAAS,cAAc;AACvB,SAAS,WAAW,mBAAmB;AACvC,SAAS,kBAAkC;AAC3C,SAAS,eAAoC;AAC7C,OAAO,aAUA;AAEP,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,KAAK,qBAAqB;AAO5B,IAAM,+BAAN,MAAM,6BAA4B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA2CjC,YAAY,SAAuC;AAtC1D;AAAA;AAAA;AAAA;AAAA,wBAAO,mBAAkB;AAMzB;AAAA;AAAA;AAAA;AAAA,wBAAO,cAAa,oBAAI,IAAY;AAMpC;AAAA;AAAA;AAAA;AAAA,wBAAgB,aAAY,oBAAI,IAAuB;AAMvD;AAAA;AAAA;AAAA;AAAA,wBAAgB;AAOhB;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAgB;AAMhB;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SAAS,KAAK;AAC9B,UAAI,MAAM,YAAY,GAAG;AACxB,eAAO,KAAK,oBAAoB,KAAK,IAAI,MAAM,MAAM,IAAI,GAAG,GAAG,EAAE,GAAG,MAAM,IAAI,GAAG;AAAA,MAClF,WAAW,MAAM,OAAO,KAAK,MAAM,KAAK,SAAS,OAAO,GAAG;AAC1D,cAAM,GAAG,EAAE,GAAG,MAAM,KAAK,MAAM,GAAG,EAAE,CAAC;AAAA,MACtC;AAAA,IACD;AAAA,EACD;AACD;AA5TyC;AAAlC,IAAM,8BAAN","sourcesContent":["import { Result } from '@sapphire/framework';\nimport { container, getRootData } from '@sapphire/pieces';\nimport { isFunction, type Awaitable } from '@sapphire/utilities';\nimport { Backend, type PathResolvable } from '@skyra/i18next-backend';\nimport i18next, {\n\ttype AppendKeyPrefix,\n\ttype DefaultNamespace,\n\ttype InterpolationMap,\n\ttype Namespace,\n\ttype ParseKeys,\n\ttype TFunction,\n\ttype TFunctionReturn,\n\ttype TFunctionReturnOptionalDetails,\n\ttype TOptions\n} from 'i18next';\nimport type { PathLike } from 'node:fs';\nimport { opendir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { URL, fileURLToPath } from 'node:url';\nimport type { $Dictionary, $SpecialObject, InternationalizationContext, InternationalizationOptions } from './types';\n\n/**\n * A generalized class for handling `i18next` JSON files and their discovery.\n * @since 1.0.0\n */\nexport class InternationalizationHandler {\n\t/**\n\t * Describes whether {@link InternationalizationHandler.init} has been run and languages are loaded in {@link InternationalizationHandler.languages}.\n\t * @since 1.0.0\n\t */\n\tpublic languagesLoaded = false;\n\n\t/**\n\t * A `Set` of initially loaded namespaces.\n\t * @since 1.2.0\n\t */\n\tpublic namespaces = new Set<string>();\n\n\t/**\n\t * A `Map` of `i18next` language functions keyed by their language code.\n\t * @since 1.0.0\n\t */\n\tpublic readonly languages = new Map<string, TFunction>();\n\n\t/**\n\t * The options InternationalizationHandler was initialized with in the client.\n\t * @since 1.0.0\n\t */\n\tpublic readonly options: InternationalizationOptions;\n\n\t/**\n\t * The director passed to `@skyra/i18next-backend`.\n\t * Also used in {@link InternationalizationHandler.walkLanguageDirectory}.\n\t * @since 1.2.0\n\t */\n\tpublic readonly languagesDirectory: string;\n\n\t/**\n\t * The backend options for `@skyra/i18next-backend` used by `i18next`.\n\t * @since 1.0.0\n\t */\n\tprotected readonly backendOptions: Backend.Options;\n\n\t/**\n\t * @param options The options that `i18next`, `@skyra/i18next-backend`, and {@link InternationalizationHandler} should use.\n\t * @since 1.0.0\n\t * @constructor\n\t */\n\tpublic constructor(options?: InternationalizationOptions) {\n\t\tthis.options = options ?? { i18next: { ignoreJSONStructure: false } };\n\n\t\tconst baseUserDirectory =\n\t\t\tcontainer.client?.options?.baseUserDirectory instanceof URL\n\t\t\t\t? fileURLToPath(container.client?.options?.baseUserDirectory)\n\t\t\t\t: container.client?.options?.baseUserDirectory;\n\n\t\tthis.languagesDirectory = this.options.defaultLanguageDirectory ?? join(baseUserDirectory ?? getRootData().root, 'languages');\n\n\t\tconst languagePaths = new Set<PathResolvable>([\n\t\t\tjoin(this.languagesDirectory, '{{lng}}', '{{ns}}.json'), //\n\t\t\t...(options?.backend?.paths ?? [])\n\t\t]);\n\n\t\tthis.backendOptions = {\n\t\t\tpaths: [...languagePaths],\n\t\t\t...this.options.backend\n\t\t};\n\n\t\tif (isFunction(this.options.fetchLanguage)) {\n\t\t\tthis.fetchLanguage = this.options.fetchLanguage;\n\t\t}\n\t}\n\n\t/**\n\t * The method to be overridden by the developer.\n\t *\n\t * @note In the event that fetchLanguage is not defined or returns null / undefined, the defaulting from {@link fetchLanguage} will be used.\n\t * @since 2.0.0\n\t * @return A string for the desired language or null for no match.\n\t * @see {@link fetchLanguage}\n\t * @example\n\t * ```typescript\n\t * // Always use the same language (no per-guild configuration):\n\t * container.i18n.fetchLanguage = () => 'en-US';\n\t * ```\n\t * @example\n\t * ```typescript\n\t * // Retrieving the language from an SQL database:\n\t * container.i18n.fetchLanguage = async (context) => {\n\t * const guild = await driver.getOne('SELECT language FROM public.guild WHERE id = $1', [context.guild.id]);\n\t * return guild?.language ?? 'en-US';\n\t * };\n\t * ```\n\t * @example\n\t * ```typescript\n\t * // Retrieving the language from an ORM:\n\t * container.i18n.fetchLanguage = async (context) => {\n\t * const guild = await driver.getRepository(GuildEntity).findOne({ id: context.guild.id });\n\t * return guild?.language ?? 'en-US';\n\t * };\n\t * ```\n\t * @example\n\t * ```typescript\n\t * // Retrieving the language on a per channel basis, e.g. per user or guild channel (ORM example but same principles apply):\n\t * container.i18n.fetchLanguage = async (context) => {\n\t * const channel = await driver.getRepository(ChannelEntity).findOne({ id: context.channel.id });\n\t * return channel?.language ?? 'en-US';\n\t * };\n\t * ```\n\t */\n\tpublic fetchLanguage: (context: InternationalizationContext) => Awaitable<string | null> = () => null;\n\n\t/**\n\t * Initializes the handler by loading in the namespaces, passing the data to i18next, and filling in the {@link InternationalizationHandler#languages}.\n\t * @since 1.0.0\n\t */\n\tpublic async init() {\n\t\tconst { namespaces, languages } = await this.walkRootDirectory(this.languagesDirectory);\n\t\tconst userOptions = isFunction(this.options.i18next) ? this.options.i18next(namespaces, languages) : this.options.i18next;\n\t\tconst ignoreJSONStructure = userOptions?.ignoreJSONStructure ?? false;\n\t\tconst skipOnVariables = userOptions?.interpolation?.skipOnVariables ?? false;\n\n\t\ti18next.use(Backend);\n\t\tawait i18next.init({\n\t\t\tbackend: this.backendOptions,\n\t\t\tfallbackLng: this.options.defaultName ?? 'en-US',\n\t\t\tinitImmediate: false,\n\t\t\tinterpolation: {\n\t\t\t\tescapeValue: false,\n\t\t\t\t...userOptions?.interpolation,\n\t\t\t\tskipOnVariables\n\t\t\t},\n\t\t\tload: 'all',\n\t\t\tdefaultNS: 'default',\n\t\t\tns: namespaces,\n\t\t\tpreload: languages,\n\t\t\t...userOptions,\n\t\t\tignoreJSONStructure\n\t\t});\n\n\t\tthis.namespaces = new Set(namespaces);\n\t\tfor (const item of languages) {\n\t\t\tthis.languages.set(item, i18next.getFixedT(item));\n\t\t}\n\t\tthis.languagesLoaded = true;\n\n\t\tconst formatter = i18next.services.formatter!;\n\t\tconst formatters = this.options.formatters ?? [];\n\t\tfor (const { name, format, cached } of formatters) {\n\t\t\tif (cached) formatter.addCached(name, format);\n\t\t\telse formatter.add(name, format);\n\t\t}\n\t}\n\n\t/**\n\t * Retrieve a raw TFunction from the passed locale.\n\t * @param locale The language to be used.\n\t * @since 1.0.0\n\t */\n\tpublic getT(locale: string) {\n\t\tif (!this.languagesLoaded) throw new Error('Cannot call this method until InternationalizationHandler#init has been called');\n\n\t\tconst t = this.languages.get(locale);\n\t\tif (t) return t;\n\t\tthrow new ReferenceError('Invalid language provided');\n\t}\n\n\t/**\n\t * Localizes a content given one or more keys and i18next options.\n\t * @since 2.0.0\n\t * @param locale The language to be used.\n\t * @param key The key or keys to retrieve the content from.\n\t * @param options The interpolation options.\n\t * @see {@link https://www.i18next.com/overview/api#t}\n\t * @returns The localized content.\n\t */\n\tpublic format<\n\t\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\t\tconst TOpt extends TOptions = TOptions,\n\t\tNs extends Namespace = DefaultNamespace,\n\t\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\t\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n\t>(locale: string, key: Key | Key[], options?: ActualOptions): TFunctionReturnOptionalDetails<Ret, TOpt>;\n\n\t/**\n\t * Localizes a content given one or more keys and i18next options.\n\t * @since 2.0.0\n\t * @param locale The language to be used.\n\t * @param key The key or keys to retrieve the content from.\n\t * @param options The interpolation options as well as a `defaultValue` for the key and any key/value pairs.\n\t * @see {@link https://www.i18next.com/overview/api#t}\n\t * @returns The localized content.\n\t */\n\tpublic format<\n\t\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\t\tconst TOpt extends TOptions = TOptions,\n\t\tNs extends Namespace = DefaultNamespace,\n\t\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\t\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n\t>(locale: string, key: string | string[], options: TOpt & $Dictionary & { defaultValue: string }): TFunctionReturnOptionalDetails<Ret, TOpt>;\n\n\t/**\n\t * Localizes a content given one or more keys and i18next options.\n\t * @since 2.0.0\n\t * @param locale The language to be used.\n\t * @param key The key or keys to retrieve the content from.\n\t * @param defaultValue The default value to use if the key is not found.\n\t * @param options The interpolation options.\n\t * @see {@link https://www.i18next.com/overview/api#t}\n\t * @returns The localized content.\n\t */\n\tpublic format<\n\t\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\t\tconst TOpt extends TOptions = TOptions,\n\t\tNs extends Namespace = DefaultNamespace,\n\t\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\t\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n\t>(\n\t\tlocale: string,\n\t\tkey: string | string[],\n\t\tdefaultValue: string | undefined,\n\t\toptions?: TOpt & $Dictionary\n\t): TFunctionReturnOptionalDetails<Ret, TOpt>;\n\n\t/**\n\t * Localizes a content given one or more keys and i18next options.\n\t * @since 2.0.0\n\t * @param locale The language to be used.\n\t *\n\t * @remark This function also has additional parameters for `key`, `defaultValue`, and `options`, however\n\t * TSDoc does not let us document those while matching proper implementation. See the overloads for this method\n\t * for the documentation on those parameters.\n\t *\n\t * @see {@link https://www.i18next.com/overview/api#t}\n\t * @returns The localized content.\n\t */\n\tpublic format<\n\t\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\t\tconst TOpt extends TOptions = TOptions,\n\t\tNs extends Namespace = DefaultNamespace,\n\t\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\t\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n\t>(\n\t\tlocale: string,\n\t\t...[key, defaultValueOrOptions, optionsOrUndefined]:\n\t\t\t| [key: Key | Key[], options?: ActualOptions]\n\t\t\t| [key: string | string[], options: TOpt & $Dictionary & { defaultValue: string }]\n\t\t\t| [key: string | string[], defaultValue: string | undefined, options?: TOpt & $Dictionary]\n\t): TFunctionReturnOptionalDetails<Ret, TOpt> {\n\t\tif (!this.languagesLoaded) throw new Error('Cannot call this method until InternationalizationHandler#init has been called');\n\n\t\tconst language = this.languages.get(locale);\n\t\tif (!language) throw new ReferenceError('Invalid language provided');\n\n\t\tconst defaultValue =\n\t\t\ttypeof defaultValueOrOptions === 'string'\n\t\t\t\t? defaultValueOrOptions\n\t\t\t\t: this.options.defaultMissingKey\n\t\t\t\t\t? language(this.options.defaultMissingKey, { replace: { key } })\n\t\t\t\t\t: '';\n\n\t\treturn language<Key, TOpt, Ret, ActualOptions>(key, { defaultValue, ...((optionsOrUndefined ?? {}) as TOpt) });\n\t}\n\n\t/**\n\t * @param directory The directory that should be walked.\n\t * @since 3.0.0\n\t */\n\tpublic async walkRootDirectory(directory: PathLike) {\n\t\tconst languages = new Set<string>();\n\t\tconst namespaces = new Set<string>();\n\n\t\tconst dir = await opendir(directory);\n\t\tfor await (const entry of dir) {\n\t\t\t// If the entry is not a directory, skip:\n\t\t\tif (!entry.isDirectory()) continue;\n\n\t\t\t// Load the directory:\n\t\t\tlanguages.add(entry.name);\n\n\t\t\tfor await (const namespace of this.walkLocaleDirectory(join(dir.path, entry.name), '')) {\n\t\t\t\tnamespaces.add(namespace);\n\t\t\t}\n\t\t}\n\n\t\treturn { namespaces: [...namespaces], languages: [...languages] };\n\t}\n\n\tpublic async reloadResources() {\n\t\tconst result = await Result.fromAsync(async () => {\n\t\t\tlet languages = this.options.hmr?.languages;\n\t\t\tlet namespaces = this.options.hmr?.namespaces;\n\t\t\tif (!languages || !namespaces) {\n\t\t\t\tconst languageDirectoryResult = await this.walkRootDirectory(this.languagesDirectory);\n\t\t\t\tlanguages ??= languageDirectoryResult.languages;\n\t\t\t\tnamespaces ??= languageDirectoryResult.namespaces;\n\t\t\t}\n\n\t\t\tawait i18next.reloadResources(languages, namespaces);\n\t\t\tcontainer.logger.info('[i18next-Plugin] Reloaded language resources.');\n\t\t});\n\n\t\tresult.inspectErr((error) => container.logger.error('[i18next-Plugin]: Failed to reload language resources.', error));\n\t}\n\n\t/**\n\t * @description Skips any files that don't end with `.json`.\n\t * @param directory The directory that should be walked.\n\t * @param ns The current namespace.\n\t * @since 3.0.0\n\t */\n\tprivate async *walkLocaleDirectory(directory: string, ns: string): AsyncGenerator<string> {\n\t\tconst dir = await opendir(directory);\n\t\tfor await (const entry of dir) {\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tyield* this.walkLocaleDirectory(join(dir.path, entry.name), `${ns}${entry.name}/`);\n\t\t\t} else if (entry.isFile() && entry.name.endsWith('.json')) {\n\t\t\t\tyield `${ns}${entry.name.slice(0, -5)}`;\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/InternationalizationHandler.ts"],"names":["container","URL","fileURLToPath","join","getRootData","isFunction","i18next","Backend","opendir","Result"],"mappings":";;;;;;;;;;;;;;;;;;;AA0BO,IAAM,4BAAA,GAAN,MAAM,4BAA4B,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA2CjC,YAAY,OAAuC,EAAA;AAtC1D;AAAA;AAAA;AAAA;AAAA,IAAA,aAAA,CAAA,IAAA,EAAO,iBAAkB,EAAA,KAAA,CAAA;AAMzB;AAAA;AAAA;AAAA;AAAA,IAAO,aAAA,CAAA,IAAA,EAAA,YAAA,sBAAiB,GAAY,EAAA,CAAA;AAMpC;AAAA;AAAA;AAAA;AAAA,IAAgB,aAAA,CAAA,IAAA,EAAA,WAAA,sBAAgB,GAAuB,EAAA,CA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AACD;AAEF,CAAA;AAjUyC,MAAA,CAAA,4BAAA,EAAA,6BAAA,CAAA;AAAlC,IAAM,2BAAN,GAAA","file":"InternationalizationHandler.cjs","sourcesContent":["import { Result } from '@sapphire/framework';\nimport { container, getRootData } from '@sapphire/pieces';\nimport { isFunction, type Awaitable } from '@sapphire/utilities';\nimport { Backend, type PathResolvable } from '@skyra/i18next-backend';\nimport i18next, {\n\ttype AppendKeyPrefix,\n\ttype DefaultNamespace,\n\ttype InterpolationMap,\n\ttype Namespace,\n\ttype ParseKeys,\n\ttype TFunction,\n\ttype TFunctionProcessReturnValue,\n\ttype TFunctionReturn,\n\ttype TFunctionReturnOptionalDetails,\n\ttype TOptions\n} from 'i18next';\nimport type { PathLike } from 'node:fs';\nimport { opendir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { URL, fileURLToPath } from 'node:url';\nimport type { $Dictionary, $NoInfer, $SpecialObject, InternationalizationContext, InternationalizationOptions } from './types';\n\n/**\n * A generalized class for handling `i18next` JSON files and their discovery.\n * @since 1.0.0\n */\nexport class InternationalizationHandler {\n\t/**\n\t * Describes whether {@link InternationalizationHandler.init} has been run and languages are loaded in {@link InternationalizationHandler.languages}.\n\t * @since 1.0.0\n\t */\n\tpublic languagesLoaded = false;\n\n\t/**\n\t * A `Set` of initially loaded namespaces.\n\t * @since 1.2.0\n\t */\n\tpublic namespaces = new Set<string>();\n\n\t/**\n\t * A `Map` of `i18next` language functions keyed by their language code.\n\t * @since 1.0.0\n\t */\n\tpublic readonly languages = new Map<string, TFunction>();\n\n\t/**\n\t * The options InternationalizationHandler was initialized with in the client.\n\t * @since 1.0.0\n\t */\n\tpublic readonly options: InternationalizationOptions;\n\n\t/**\n\t * The director passed to `@skyra/i18next-backend`.\n\t * Also used in {@link InternationalizationHandler.walkLanguageDirectory}.\n\t * @since 1.2.0\n\t */\n\tpublic readonly languagesDirectory: string;\n\n\t/**\n\t * The backend options for `@skyra/i18next-backend` used by `i18next`.\n\t * @since 1.0.0\n\t */\n\tprotected readonly backendOptions: Backend.Options;\n\n\t/**\n\t * @param options The options that `i18next`, `@skyra/i18next-backend`, and {@link InternationalizationHandler} should use.\n\t * @since 1.0.0\n\t * @constructor\n\t */\n\tpublic constructor(options?: InternationalizationOptions) {\n\t\tthis.options = options ?? { i18next: { ignoreJSONStructure: false } };\n\n\t\tconst baseUserDirectory =\n\t\t\tcontainer.client?.options?.baseUserDirectory instanceof URL\n\t\t\t\t? fileURLToPath(container.client?.options?.baseUserDirectory)\n\t\t\t\t: container.client?.options?.baseUserDirectory;\n\n\t\tthis.languagesDirectory = this.options.defaultLanguageDirectory ?? join(baseUserDirectory ?? getRootData().root, 'languages');\n\n\t\tconst languagePaths = new Set<PathResolvable>([\n\t\t\tjoin(this.languagesDirectory, '{{lng}}', '{{ns}}.json'), //\n\t\t\t...(options?.backend?.paths ?? [])\n\t\t]);\n\n\t\tthis.backendOptions = {\n\t\t\tpaths: [...languagePaths],\n\t\t\t...this.options.backend\n\t\t};\n\n\t\tif (isFunction(this.options.fetchLanguage)) {\n\t\t\tthis.fetchLanguage = this.options.fetchLanguage;\n\t\t}\n\t}\n\n\t/**\n\t * The method to be overridden by the developer.\n\t *\n\t * @note In the event that fetchLanguage is not defined or returns null / undefined, the defaulting from {@link fetchLanguage} will be used.\n\t * @since 2.0.0\n\t * @return A string for the desired language or null for no match.\n\t * @see {@link fetchLanguage}\n\t * @example\n\t * ```typescript\n\t * // Always use the same language (no per-guild configuration):\n\t * container.i18n.fetchLanguage = () => 'en-US';\n\t * ```\n\t * @example\n\t * ```typescript\n\t * // Retrieving the language from an SQL database:\n\t * container.i18n.fetchLanguage = async (context) => {\n\t * const guild = await driver.getOne('SELECT language FROM public.guild WHERE id = $1', [context.guild.id]);\n\t * return guild?.language ?? 'en-US';\n\t * };\n\t * ```\n\t * @example\n\t * ```typescript\n\t * // Retrieving the language from an ORM:\n\t * container.i18n.fetchLanguage = async (context) => {\n\t * const guild = await driver.getRepository(GuildEntity).findOne({ id: context.guild.id });\n\t * return guild?.language ?? 'en-US';\n\t * };\n\t * ```\n\t * @example\n\t * ```typescript\n\t * // Retrieving the language on a per channel basis, e.g. per user or guild channel (ORM example but same principles apply):\n\t * container.i18n.fetchLanguage = async (context) => {\n\t * const channel = await driver.getRepository(ChannelEntity).findOne({ id: context.channel.id });\n\t * return channel?.language ?? 'en-US';\n\t * };\n\t * ```\n\t */\n\tpublic fetchLanguage: (context: InternationalizationContext) => Awaitable<string | null> = () => null;\n\n\t/**\n\t * Initializes the handler by loading in the namespaces, passing the data to i18next, and filling in the {@link InternationalizationHandler#languages}.\n\t * @since 1.0.0\n\t */\n\tpublic async init() {\n\t\tconst { namespaces, languages } = await this.walkRootDirectory(this.languagesDirectory);\n\t\tconst userOptions = isFunction(this.options.i18next) ? this.options.i18next(namespaces, languages) : this.options.i18next;\n\t\tconst ignoreJSONStructure = userOptions?.ignoreJSONStructure ?? false;\n\t\tconst skipOnVariables = userOptions?.interpolation?.skipOnVariables ?? false;\n\n\t\ti18next.use(Backend);\n\t\tawait i18next.init({\n\t\t\tbackend: this.backendOptions,\n\t\t\tfallbackLng: this.options.defaultName ?? 'en-US',\n\t\t\tinitImmediate: false,\n\t\t\tinterpolation: {\n\t\t\t\tescapeValue: false,\n\t\t\t\t...userOptions?.interpolation,\n\t\t\t\tskipOnVariables\n\t\t\t},\n\t\t\tload: 'all',\n\t\t\tdefaultNS: 'default',\n\t\t\tns: namespaces,\n\t\t\tpreload: languages,\n\t\t\t...userOptions,\n\t\t\tignoreJSONStructure\n\t\t});\n\n\t\tthis.namespaces = new Set(namespaces);\n\t\tfor (const item of languages) {\n\t\t\tthis.languages.set(item, i18next.getFixedT(item));\n\t\t}\n\t\tthis.languagesLoaded = true;\n\n\t\tconst formatter = i18next.services.formatter!;\n\t\tconst formatters = this.options.formatters ?? [];\n\t\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\t\tfor (const { name, format, cached } of formatters) {\n\t\t\tif (cached) formatter.addCached(name, format);\n\t\t\telse formatter.add(name, format);\n\t\t}\n\t}\n\n\t/**\n\t * Retrieve a raw TFunction from the passed locale.\n\t * @param locale The language to be used.\n\t * @since 1.0.0\n\t */\n\tpublic getT(locale: string) {\n\t\tif (!this.languagesLoaded) throw new Error('Cannot call this method until InternationalizationHandler#init has been called');\n\n\t\tconst t = this.languages.get(locale);\n\t\tif (t) return t;\n\t\tthrow new ReferenceError('Invalid language provided');\n\t}\n\n\t/**\n\t * Localizes a content given one or more keys and i18next options.\n\t * @since 2.0.0\n\t * @param locale The language to be used.\n\t * @param key The key or keys to retrieve the content from.\n\t * @param options The interpolation options.\n\t * @see {@link https://www.i18next.com/overview/api#t}\n\t * @returns The localized content.\n\t */\n\tpublic format<\n\t\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\t\tconst TOpt extends TOptions = TOptions,\n\t\tNs extends Namespace = DefaultNamespace,\n\t\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\t\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n\t>(locale: string, key: Key | Key[], options?: ActualOptions): TFunctionReturnOptionalDetails<Ret, TOpt>;\n\n\t/**\n\t * Localizes a content given one or more keys and i18next options.\n\t * @since 2.0.0\n\t * @param locale The language to be used.\n\t * @param key The key or keys to retrieve the content from.\n\t * @param options The interpolation options as well as a `defaultValue` for the key and any key/value pairs.\n\t * @see {@link https://www.i18next.com/overview/api#t}\n\t * @returns The localized content.\n\t */\n\tpublic format<\n\t\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\t\tconst TOpt extends TOptions = TOptions,\n\t\tNs extends Namespace = DefaultNamespace,\n\t\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\t\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n\t>(locale: string, key: string | string[], options: TOpt & $Dictionary & { defaultValue: string }): TFunctionReturnOptionalDetails<Ret, TOpt>;\n\n\t/**\n\t * Localizes a content given one or more keys and i18next options.\n\t * @since 2.0.0\n\t * @param locale The language to be used.\n\t * @param key The key or keys to retrieve the content from.\n\t * @param defaultValue The default value to use if the key is not found.\n\t * @param options The interpolation options.\n\t * @see {@link https://www.i18next.com/overview/api#t}\n\t * @returns The localized content.\n\t */\n\tpublic format<\n\t\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\t\tconst TOpt extends TOptions = TOptions,\n\t\tNs extends Namespace = DefaultNamespace,\n\t\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\t\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n\t>(\n\t\tlocale: string,\n\t\tkey: string | string[],\n\t\tdefaultValue: string | undefined,\n\t\toptions?: TOpt & $Dictionary\n\t): TFunctionReturnOptionalDetails<Ret, TOpt>;\n\n\t/**\n\t * Localizes a content given one or more keys and i18next options.\n\t * @since 2.0.0\n\t * @param locale The language to be used.\n\t *\n\t * @remark This function also has additional parameters for `key`, `defaultValue`, and `options`, however\n\t * TSDoc does not let us document those while matching proper implementation. See the overloads for this method\n\t * for the documentation on those parameters.\n\t *\n\t * @see {@link https://www.i18next.com/overview/api#t}\n\t * @returns The localized content.\n\t */\n\tpublic format<\n\t\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\t\tconst TOpt extends TOptions = TOptions,\n\t\tNs extends Namespace = DefaultNamespace,\n\t\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\t\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>,\n\t\tDefaultValue extends string = never\n\t>(\n\t\tlocale: string,\n\t\t...[key, defaultValueOrOptions, optionsOrUndefined]:\n\t\t\t| [key: Key | Key[], options?: ActualOptions]\n\t\t\t| [key: string | string[], options: TOpt & $Dictionary & { defaultValue: string }]\n\t\t\t| [key: string | string[], defaultValue: DefaultValue | undefined, options?: TOpt & $Dictionary]\n\t): TFunctionReturnOptionalDetails<TFunctionProcessReturnValue<$NoInfer<Ret>, DefaultValue>, TOpt> {\n\t\tif (!this.languagesLoaded) throw new Error('Cannot call this method until InternationalizationHandler#init has been called');\n\n\t\tconst language = this.languages.get(locale);\n\t\tif (!language) throw new ReferenceError('Invalid language provided');\n\n\t\tconst defaultValue =\n\t\t\ttypeof defaultValueOrOptions === 'string'\n\t\t\t\t? defaultValueOrOptions\n\t\t\t\t: this.options.defaultMissingKey\n\t\t\t\t\t? language(this.options.defaultMissingKey, { replace: { key } })\n\t\t\t\t\t: '';\n\n\t\treturn language<Key, TOpt, Ret, ActualOptions, DefaultValue>(key, {\n\t\t\tdefaultValue,\n\t\t\t...((optionsOrUndefined ?? {}) as TOpt)\n\t\t} as TOpt & $Dictionary & { defaultValue: DefaultValue });\n\t}\n\n\t/**\n\t * @param directory The directory that should be walked.\n\t * @since 3.0.0\n\t */\n\tpublic async walkRootDirectory(directory: PathLike) {\n\t\tconst languages = new Set<string>();\n\t\tconst namespaces = new Set<string>();\n\n\t\tconst dir = await opendir(directory);\n\t\tfor await (const entry of dir) {\n\t\t\t// If the entry is not a directory, skip:\n\t\t\tif (!entry.isDirectory()) continue;\n\n\t\t\t// Load the directory:\n\t\t\tlanguages.add(entry.name);\n\n\t\t\tfor await (const namespace of this.walkLocaleDirectory(join(dir.path, entry.name), '')) {\n\t\t\t\tnamespaces.add(namespace);\n\t\t\t}\n\t\t}\n\n\t\treturn { namespaces: [...namespaces], languages: [...languages] };\n\t}\n\n\tpublic async reloadResources() {\n\t\tconst result = await Result.fromAsync(async () => {\n\t\t\tlet languages = this.options.hmr?.languages;\n\t\t\tlet namespaces = this.options.hmr?.namespaces;\n\t\t\tif (!languages || !namespaces) {\n\t\t\t\tconst languageDirectoryResult = await this.walkRootDirectory(this.languagesDirectory);\n\t\t\t\tlanguages ??= languageDirectoryResult.languages;\n\t\t\t\tnamespaces ??= languageDirectoryResult.namespaces;\n\t\t\t}\n\n\t\t\tawait i18next.reloadResources(languages, namespaces);\n\t\t\tcontainer.logger.info('[i18next-Plugin] Reloaded language resources.');\n\t\t});\n\n\t\tresult.inspectErr((error) => container.logger.error('[i18next-Plugin]: Failed to reload language resources.', error));\n\t}\n\n\t/**\n\t * @description Skips any files that don't end with `.json`.\n\t * @param directory The directory that should be walked.\n\t * @param ns The current namespace.\n\t * @since 3.0.0\n\t */\n\tprivate async *walkLocaleDirectory(directory: string, ns: string): AsyncGenerator<string> {\n\t\tconst dir = await opendir(directory);\n\t\tfor await (const entry of dir) {\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tyield* this.walkLocaleDirectory(join(dir.path, entry.name), `${ns}${entry.name}/`);\n\t\t\t} else if (entry.isFile() && entry.name.endsWith('.json')) {\n\t\t\t\tyield `${ns}${entry.name.slice(0, -5)}`;\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
|
|
@@ -22,7 +22,7 @@ function fetchLanguage(target) {
|
|
|
22
22
|
if (target instanceof discord_js.Guild) {
|
|
23
23
|
return resolveLanguage({ user: null, channel: null, guild: target });
|
|
24
24
|
}
|
|
25
|
-
if (target.type === discord_js.ChannelType.DM) {
|
|
25
|
+
if (target.type === discord_js.ChannelType.DM || target.type === discord_js.ChannelType.GroupDM) {
|
|
26
26
|
return resolveLanguage({ user: null, channel: target, guild: null });
|
|
27
27
|
}
|
|
28
28
|
return resolveLanguage({ user: null, channel: target, guild: target.guild });
|
|
@@ -121,5 +121,5 @@ exports.fetchLanguage = fetchLanguage;
|
|
|
121
121
|
exports.fetchT = fetchT;
|
|
122
122
|
exports.getLocalizedData = getLocalizedData;
|
|
123
123
|
exports.resolveKey = resolveKey;
|
|
124
|
-
//# sourceMappingURL=
|
|
124
|
+
//# sourceMappingURL=functions.cjs.map
|
|
125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AAAA,IACnB,eAAe,OAAO,YAAY,MAAM,KAAK,SAAS,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC;AAAA,EACzF;AACD;AAVgB;AAkBT,SAAS,0BAKd,SAAY,KAAmC;AAChD,QAAM,SAAS,iBAAiB,GAAG;AACnC,SAAO,QAAQ,QAAQ,OAAO,KAAK,EAAE,qBAAqB,OAAO,aAAa;AAC/E;AARgB;AAgBT,SAAS,iCAKd,SAAY,KAAmC;AAChD,QAAM,SAAS,iBAAiB,GAAG;AACnC,SAAO,QAAQ,eAAe,OAAO,KAAK,EAAE,4BAA4B,OAAO,aAAa;AAC7F;AARgB;AA8DT,SAAS,sBAKd,YAAe,QAA6G;AAG7H,QAAM,CAAC,YAAY,iBAAiB,IACnC,OAAO,WAAW,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,QAAyB,GAAG,OAAO,CAAC,CAAC,aAA8B,IAAI;AAE3G,4BAA0B,SAAS,UAAU;AAC7C,mCAAiC,SAAS,iBAAiB;AAE3D,SAAO;AACR;AAfgB;AA4CT,SAAS,sBAMf,KACA,SAC+C;AAC/C,QAAM,SAAS,iBAAiB,GAAG;AAEnC,SAAO;AAAA,IACN,GAAG;AAAA,IACH,MAAM,OAAO;AAAA,IACb,oBAAoB,OAAO;AAAA,EAC5B;AACD;AAhBgB","sourcesContent":["import { container } from '@sapphire/pieces';\nimport { lazy } from '@sapphire/utilities';\nimport { BaseInteraction, ChannelType, Guild, Locale, Message, type APIApplicationCommandOptionChoice, type LocaleString } from 'discord.js';\nimport type {\n\tAppendKeyPrefix,\n\tDefaultNamespace,\n\tInterpolationMap,\n\tNamespace,\n\tParseKeys,\n\tTFunctionReturn,\n\tTFunctionReturnOptionalDetails,\n\tTOptions\n} from 'i18next';\nimport type {\n\t$Dictionary,\n\t$SpecialObject,\n\tBuilderWithDescription,\n\tBuilderWithName,\n\tBuilderWithNameAndDescription,\n\tInternationalizationContext,\n\tLocalizedData,\n\tTarget\n} from './types';\n\n/**\n * Retrieves the language name for a specific target, using {@link InternationalizationHandler.fetchLanguage}.\n * If {@link InternationalizationHandler.fetchLanguage} is not defined or this function returns a nullish value,\n * then there will be a series of fallback attempts in the following descending order:\n * 1. Returns {@link Guild.preferredLocale}.\n * 2. Returns {@link InternationalizationOptions.defaultName} if no guild was provided.\n * 3. Returns `'en-US'` if nothing else was found.\n * @since 2.0.0\n * @param target The target to fetch the language from.\n * @see {@link resolveLanguage}\n * @returns The name of the language key.\n */\nexport function fetchLanguage(target: Target): Promise<string> {\n\t// Handle Interactions:\n\tif (target instanceof BaseInteraction) {\n\t\treturn resolveLanguage({\n\t\t\tuser: target.user,\n\t\t\tchannel: target.channel,\n\t\t\tguild: target.guild,\n\t\t\tinteractionGuildLocale: target.guildLocale,\n\t\t\tinteractionLocale: target.locale\n\t\t});\n\t}\n\n\t// Handle Message:\n\tif (target instanceof Message) {\n\t\treturn resolveLanguage({ user: target.author, channel: target.channel, guild: target.guild });\n\t}\n\n\t// Handle Guild:\n\tif (target instanceof Guild) {\n\t\treturn resolveLanguage({ user: null, channel: null, guild: target });\n\t}\n\n\t// Handle DMChannel:\n\tif (target.type === ChannelType.DM) {\n\t\treturn resolveLanguage({ user: null, channel: target, guild: null });\n\t}\n\n\t// Handle any other channel:\n\treturn resolveLanguage({ user: null, channel: target, guild: target.guild });\n}\n\n/**\n * Retrieves the language-assigned function from i18next designated to a target's preferred language code.\n * @since 2.0.0\n * @param target The target to fetch the language from.\n * @returns The language function from i18next.\n */\nexport async function fetchT(target: Target) {\n\treturn container.i18n.getT(await fetchLanguage(target));\n}\n\n/**\n * Resolves a key and its parameters.\n * @since 2.0.0\n * @param target The target to fetch the language key from.\n * @param key The i18next key.\n * @param options The options to be passed to TFunction.\n * @returns The data that `key` held, processed by i18next.\n */\nexport async function resolveKey<\n\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\tconst TOpt extends TOptions = TOptions,\n\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\tNs extends Namespace = DefaultNamespace,\n\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n>(target: Target, key: Key | Key[], options?: ActualOptions): Promise<TFunctionReturnOptionalDetails<Ret, TOpt>>;\n\n/**\n * Resolves a key and its parameters.\n * @since 2.0.0\n * @param target The target to fetch the language key from.\n * @param key The i18next key.\n * @param options The interpolation options as well as a `defaultValue` for the key and any key/value pairs.\n * @returns The data that `key` held, processed by i18next.\n */\nexport async function resolveKey<\n\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\tconst TOpt extends TOptions = TOptions,\n\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\tNs extends Namespace = DefaultNamespace,\n\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n>(target: Target, key: string | string[], options: TOpt & $Dictionary & { defaultValue: string }): Promise<TFunctionReturnOptionalDetails<Ret, TOpt>>;\n\n/**\n * Resolves a key and its parameters.\n * @since 2.0.0\n * @param target The target to fetch the language key from.\n * @param key The i18next key.\n * @param defaultValue The default value to use if the key is not found.\n * @param options The interpolation options.\n * @returns The data that `key` held, processed by i18next.\n */\nexport async function resolveKey<\n\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\tconst TOpt extends TOptions = TOptions,\n\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\tNs extends Namespace = DefaultNamespace,\n\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n>(target: Target, key: string | string[], defaultValue: string, options?: TOpt & $Dictionary): Promise<TFunctionReturnOptionalDetails<Ret, TOpt>>;\n\n/**\n * Resolves a key and its parameters.\n * @since 2.0.0\n * @param target The target to fetch the language key from.\n *\n * @remark This function also has additional parameters for `key`, `defaultValue`, and `options`, however\n * TSDoc does not let us document those while matching proper implementation. See the overloads for this method\n * for the documentation on those parameters.\n *\n * @returns The data that `key` held, processed by i18next.\n */\nexport async function resolveKey<\n\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\tconst TOpt extends TOptions = TOptions,\n\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\tNs extends Namespace = DefaultNamespace,\n\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n>(\n\ttarget: Target,\n\t...[key, defaultValueOrOptions, optionsOrUndefined]:\n\t\t| [key: Key | Key[], options?: ActualOptions]\n\t\t| [key: string | string[], options: TOpt & $Dictionary & { defaultValue: string }]\n\t\t| [key: string | string[], defaultValue: string, options?: TOpt & $Dictionary]\n): Promise<TFunctionReturnOptionalDetails<Ret, TOpt>> {\n\tconst parsedOptions = typeof defaultValueOrOptions === 'string' ? optionsOrUndefined : defaultValueOrOptions;\n\tconst language = typeof parsedOptions?.lng === 'string' ? parsedOptions.lng : await fetchLanguage(target);\n\n\tif (typeof defaultValueOrOptions === 'string') {\n\t\treturn container.i18n.format<Key, TOpt, Ns, Ret, ActualOptions>(language, key, defaultValueOrOptions, optionsOrUndefined);\n\t}\n\n\treturn container.i18n.format<Key, TOpt, Ns, Ret, ActualOptions>(language, key, undefined, defaultValueOrOptions);\n}\n\n/**\n * @internal\n */\nasync function resolveLanguage(context: InternationalizationContext): Promise<string> {\n\tconst lang = await container.i18n.fetchLanguage(context);\n\treturn lang ?? context.guild?.preferredLocale ?? container.i18n.options.defaultName ?? 'en-US';\n}\n\nconst supportedLanguages = new Set(Object.values(Locale)) as ReadonlySet<LocaleString>;\n\nfunction isSupportedDiscordLocale(language: string): language is LocaleString {\n\treturn supportedLanguages.has(language as LocaleString);\n}\n\nconst getLocales = lazy(() => {\n\tconst locales = new Map(container.i18n.languages);\n\n\tfor (const [locale] of locales) {\n\t\tif (!isSupportedDiscordLocale(locale)) {\n\t\t\tprocess.emitWarning('Unsupported Discord locale', {\n\t\t\t\tcode: 'UNSUPPORTED_LOCALE',\n\t\t\t\tdetail: `'${locale}' needs to be one of: ${[...locales.keys()]}`\n\t\t\t});\n\n\t\t\tlocales.delete(locale);\n\t\t}\n\n\t\tcontinue;\n\t}\n\n\treturn locales;\n});\n\nconst getDefaultT = lazy(() => {\n\tconst defaultLocale = container.i18n.options.defaultName ?? 'en-US';\n\n\tif (!isSupportedDiscordLocale(defaultLocale)) {\n\t\tthrow new TypeError(`Unsupported Discord locale found:\\n'${defaultLocale}' is not within the list of ${[...supportedLanguages]}`);\n\t}\n\n\tconst defaultT = getLocales().get(defaultLocale);\n\n\tif (defaultT) {\n\t\treturn defaultT;\n\t}\n\n\tthrow new TypeError(`Could not find ${defaultLocale}`);\n});\n\n/**\n * Gets the value and the localizations from a language key.\n * @param key The key to get the localizations from.\n * @returns The retrieved data.\n * @remarks This should be called **strictly** after loading the locales.\n */\nexport function getLocalizedData<const TOpt extends TOptions = TOptions, Ns extends Namespace = DefaultNamespace, KPrefix = undefined>(\n\tkey: ParseKeys<Ns, TOpt, KPrefix>\n): LocalizedData {\n\tconst locales = getLocales();\n\tconst defaultT = getDefaultT();\n\n\treturn {\n\t\tvalue: defaultT(key),\n\t\tlocalizations: Object.fromEntries(Array.from(locales, ([locale, t]) => [locale, t(key)]))\n\t};\n}\n\n/**\n * Applies the localized names on the builder, calling `setName` and `setNameLocalizations`.\n * @param builder The builder to apply the localizations to.\n * @param key The key to get the localizations from.\n * @returns The updated builder.\n */\nexport function applyNameLocalizedBuilder<\n\tT extends BuilderWithName,\n\tconst TOpt extends TOptions = TOptions,\n\tNs extends Namespace = DefaultNamespace,\n\tKPrefix = undefined\n>(builder: T, key: ParseKeys<Ns, TOpt, KPrefix>) {\n\tconst result = getLocalizedData(key);\n\treturn builder.setName(result.value).setNameLocalizations(result.localizations);\n}\n\n/**\n * Applies the localized descriptions on the builder, calling `setDescription` and `setDescriptionLocalizations`.\n * @param builder The builder to apply the localizations to.\n * @param key The key to get the localizations from.\n * @returns The updated builder.\n */\nexport function applyDescriptionLocalizedBuilder<\n\tT extends BuilderWithDescription,\n\tconst TOpt extends TOptions = TOptions,\n\tNs extends Namespace = DefaultNamespace,\n\tKPrefix = undefined\n>(builder: T, key: ParseKeys<Ns, TOpt, KPrefix>) {\n\tconst result = getLocalizedData(key);\n\treturn builder.setDescription(result.value).setDescriptionLocalizations(result.localizations);\n}\n\n/**\n * Applies the localized names and descriptions on the builder, calling {@link applyNameLocalizedBuilder} and\n * {@link applyDescriptionLocalizedBuilder}.\n *\n * @param builder The builder to apply the localizations to.\n *\n * @param params The root key or the key for the name and description keys.\n * This needs to be either 1 or 2 parameters.\n * See examples below for more information.\n *\n * @returns The updated builder. You can chain subsequent builder methods on this.\n *\n * @remarks If only 2 parameters were passed, then this function will automatically append `Name` and `Description`\n * to the root-key (wherein `root-key` is second parameter in the function, after `builder`)\n * passed through the second parameter.\n *\n * For example given `applyLocalizedBuilder(builder, 'userinfo')` the localized options will use the i18next keys\n * `userinfoName` and `userinfoDescription`.\n *\n * In the following example we provide all parameters and add a User Option\n * `applyLocalizedBuilder` needs either\n * @example\n * ```typescript\n * class UserInfoCommand extends Command {\n * public registerApplicationCommands(registry: ChatInputCommand.Registry) {\n * registry.registerChatInputCommand(\n * (builder) =>\n * applyLocalizedBuilder(builder, 'commands/names:userinfo', 'commands/descriptions:userinfo')\n * .addUserOption(\n * (input) => applyLocalizedBuilder(input, 'commands/options:userinfo-name', 'commands/options:userinfo-description').setRequired(true)\n * )\n * );\n * }\n * }\n * ```\n *\n * In the following example we provide single root keys which means `Name` and `Description` get appended as mentioned above.\n * @example\n * ```typescript\n * class UserInfoCommand extends Command {\n * public registerApplicationCommands(registry: ChatInputCommand.Registry) {\n * registry.registerChatInputCommand(\n * (builder) =>\n * applyLocalizedBuilder(builder, 'commands:userinfo')\n * .addUserOption(\n * (input) => applyLocalizedBuilder(input, 'options:userinfo').setRequired(true)\n * )\n * );\n * }\n * }\n * ```\n */\nexport function applyLocalizedBuilder<\n\tT extends BuilderWithNameAndDescription,\n\tconst TOpt extends TOptions = TOptions,\n\tNs extends Namespace = DefaultNamespace,\n\tKPrefix = undefined\n>(builder: T, ...params: [root: string] | [name: ParseKeys<Ns, TOpt, KPrefix>, description: ParseKeys<Ns, TOpt, KPrefix>]): T {\n\ttype LocalKeysType = ParseKeys<Ns, TOpt, KPrefix>;\n\n\tconst [localeName, localeDescription] =\n\t\tparams.length === 1 ? [`${params[0]}Name` as LocalKeysType, `${params[0]}Description` as LocalKeysType] : params;\n\n\tapplyNameLocalizedBuilder(builder, localeName);\n\tapplyDescriptionLocalizedBuilder(builder, localeDescription);\n\n\treturn builder;\n}\n\n/**\n * Constructs an object that can be passed into `setChoices` for String or Number option with localized names.\n *\n * @param key The i18next key for the name of the select option name.\n * @param options The additional Select Menu options. This should _at least_ include the `value` key.\n * @returns An object with anything provided through {@link createLocalizedChoice.options} with `name` and `name_localizations` added.\n *\n * @example\n * ```typescript\n * export class TypeCommand extends Command {\n * public override registerApplicationCommands(registry: ChatInputCommand.Registry) {\n * registry.registerChatInputCommand((builder) =>\n * applyLocalizedBuilder(builder, 'commands/names:type').addStringOption((option) =>\n * applyLocalizedBuilder(option, 'commands/options:type')\n * .setRequired(true)\n * .setChoices(\n * createLocalizedChoice('selects/pokemon:type-grass', { value: 'grass' }),\n * createLocalizedChoice('selects/pokemon:type-water', { value: 'water' }),\n * createLocalizedChoice('selects/pokemon:type-fire', { value: 'fire' }),\n * createLocalizedChoice('selects/pokemon:type-electric', { value: 'electric' })\n * )\n * )\n * );\n * }\n * }\n * ```\n */\nexport function createLocalizedChoice<\n\tValueType = string | number,\n\tconst TOpt extends TOptions = TOptions,\n\tNs extends Namespace = DefaultNamespace,\n\tKPrefix = undefined\n>(\n\tkey: ParseKeys<Ns, TOpt, KPrefix>,\n\toptions: Omit<APIApplicationCommandOptionChoice<ValueType>, 'name' | 'name_localizations'>\n): APIApplicationCommandOptionChoice<ValueType> {\n\tconst result = getLocalizedData(key);\n\n\treturn {\n\t\t...options,\n\t\tname: result.value,\n\t\tname_localizations: result.localizations\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/functions.ts"],"names":["BaseInteraction","Message","Guild","ChannelType","container","Locale","lazy"],"mappings":";;;;;;;;AAoCO,SAAS,cAAc,MAAiC,EAAA;AAE9D,EAAA,IAAI,kBAAkBA,0BAAiB,EAAA;AACtC,IAAA,OAAO,eAAgB,CAAA;AAAA,MACtB,MAAM,MAAO,CAAA,IAAA;AAAA,MACb,SAAS,MAAO,CAAA,OAAA;AAAA,MAChB,OAAO,MAAO,CAAA,KAAA;AAAA,MACd,wBAAwB,MAAO,CAAA,WAAA;AAAA,MAC/B,mBAAmB,MAAO,CAAA;AAAA,KAC1B,CAAA;AAAA;AAIF,EAAA,IAAI,kBAAkBC,kBAAS,EAAA;AAC9B,IAAO,OAAA,eAAA,CAAgB,EAAE,IAAA,EAAM,MAAO,CAAA,MAAA,EAAQ,OAAS,EAAA,MAAA,CAAO,OAAS,EAAA,KAAA,EAAO,MAAO,CAAA,KAAA,EAAO,CAAA;AAAA;AAI7F,EAAA,IAAI,kBAAkBC,gBAAO,EAAA;AAC5B,IAAO,OAAA,eAAA,CAAgB,EAAE,IAAM,EAAA,IAAA,EAAM,SAAS,IAAM,EAAA,KAAA,EAAO,QAAQ,CAAA;AAAA;AAIpE,EAAA,IAAI,OAAO,IAAS,KAAAC,sBAAA,CAAY,MAAM,MAAO,CAAA,IAAA,KAASA,uBAAY,OAAS,EAAA;AAC1E,IAAO,OAAA,eAAA,CAAgB,EAAE,IAAM,EAAA,IAAA,EAAM,SAAS,MAAQ,EAAA,KAAA,EAAO,MAAM,CAAA;AAAA;AAIpE,EAAO,OAAA,eAAA,CAAgB,EAAE,IAAM,EAAA,IAAA,EAAM,SAAS,M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AA;AAE3D,EAAO,OAAA,OAAA;AACR;AAfgB,MAAA,CAAA,qBAAA,EAAA,uBAAA,CAAA;AA4CT,SAAS,qBAAA,CAMf,KACA,OAC+C,EAAA;AAC/C,EAAM,MAAA,MAAA,GAAS,iBAAiB,GAAG,CAAA;AAEnC,EAAO,OAAA;AAAA,IACN,GAAG,OAAA;AAAA,IACH,MAAM,MAAO,CAAA,KAAA;AAAA,IACb,oBAAoB,MAAO,CAAA;AAAA,GAC5B;AACD;AAhBgB,MAAA,CAAA,qBAAA,EAAA,uBAAA,CAAA","file":"functions.cjs","sourcesContent":["import { container } from '@sapphire/pieces';\nimport { lazy } from '@sapphire/utilities';\nimport { BaseInteraction, ChannelType, Guild, Locale, Message, type APIApplicationCommandOptionChoice, type LocaleString } from 'discord.js';\nimport type {\n\tAppendKeyPrefix,\n\tDefaultNamespace,\n\tInterpolationMap,\n\tNamespace,\n\tParseKeys,\n\tTFunctionReturn,\n\tTFunctionReturnOptionalDetails,\n\tTOptions\n} from 'i18next';\nimport type {\n\t$Dictionary,\n\t$SpecialObject,\n\tBuilderWithDescription,\n\tBuilderWithName,\n\tBuilderWithNameAndDescription,\n\tInternationalizationContext,\n\tLocalizedData,\n\tTarget\n} from './types';\n\n/**\n * Retrieves the language name for a specific target, using {@link InternationalizationHandler.fetchLanguage}.\n * If {@link InternationalizationHandler.fetchLanguage} is not defined or this function returns a nullish value,\n * then there will be a series of fallback attempts in the following descending order:\n * 1. Returns {@link Guild.preferredLocale}.\n * 2. Returns {@link InternationalizationOptions.defaultName} if no guild was provided.\n * 3. Returns `'en-US'` if nothing else was found.\n * @since 2.0.0\n * @param target The target to fetch the language from.\n * @see {@link resolveLanguage}\n * @returns The name of the language key.\n */\nexport function fetchLanguage(target: Target): Promise<string> {\n\t// Handle Interactions:\n\tif (target instanceof BaseInteraction) {\n\t\treturn resolveLanguage({\n\t\t\tuser: target.user,\n\t\t\tchannel: target.channel,\n\t\t\tguild: target.guild,\n\t\t\tinteractionGuildLocale: target.guildLocale,\n\t\t\tinteractionLocale: target.locale\n\t\t});\n\t}\n\n\t// Handle Message:\n\tif (target instanceof Message) {\n\t\treturn resolveLanguage({ user: target.author, channel: target.channel, guild: target.guild });\n\t}\n\n\t// Handle Guild:\n\tif (target instanceof Guild) {\n\t\treturn resolveLanguage({ user: null, channel: null, guild: target });\n\t}\n\n\t// Handle DMChannel and GroupDMChannel:\n\tif (target.type === ChannelType.DM || target.type === ChannelType.GroupDM) {\n\t\treturn resolveLanguage({ user: null, channel: target, guild: null });\n\t}\n\n\t// Handle any other channel:\n\treturn resolveLanguage({ user: null, channel: target, guild: target.guild });\n}\n\n/**\n * Retrieves the language-assigned function from i18next designated to a target's preferred language code.\n * @since 2.0.0\n * @param target The target to fetch the language from.\n * @returns The language function from i18next.\n */\nexport async function fetchT(target: Target) {\n\treturn container.i18n.getT(await fetchLanguage(target));\n}\n\n/**\n * Resolves a key and its parameters.\n * @since 2.0.0\n * @param target The target to fetch the language key from.\n * @param key The i18next key.\n * @param options The options to be passed to TFunction.\n * @returns The data that `key` held, processed by i18next.\n */\nexport async function resolveKey<\n\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\tconst TOpt extends TOptions = TOptions,\n\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\tNs extends Namespace = DefaultNamespace,\n\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n>(target: Target, key: Key | Key[], options?: ActualOptions): Promise<TFunctionReturnOptionalDetails<Ret, TOpt>>;\n\n/**\n * Resolves a key and its parameters.\n * @since 2.0.0\n * @param target The target to fetch the language key from.\n * @param key The i18next key.\n * @param options The interpolation options as well as a `defaultValue` for the key and any key/value pairs.\n * @returns The data that `key` held, processed by i18next.\n */\nexport async function resolveKey<\n\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\tconst TOpt extends TOptions = TOptions,\n\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\tNs extends Namespace = DefaultNamespace,\n\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n>(target: Target, key: string | string[], options: TOpt & $Dictionary & { defaultValue: string }): Promise<TFunctionReturnOptionalDetails<Ret, TOpt>>;\n\n/**\n * Resolves a key and its parameters.\n * @since 2.0.0\n * @param target The target to fetch the language key from.\n * @param key The i18next key.\n * @param defaultValue The default value to use if the key is not found.\n * @param options The interpolation options.\n * @returns The data that `key` held, processed by i18next.\n */\nexport async function resolveKey<\n\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\tconst TOpt extends TOptions = TOptions,\n\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\tNs extends Namespace = DefaultNamespace,\n\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n>(target: Target, key: string | string[], defaultValue: string, options?: TOpt & $Dictionary): Promise<TFunctionReturnOptionalDetails<Ret, TOpt>>;\n\n/**\n * Resolves a key and its parameters.\n * @since 2.0.0\n * @param target The target to fetch the language key from.\n *\n * @remark This function also has additional parameters for `key`, `defaultValue`, and `options`, however\n * TSDoc does not let us document those while matching proper implementation. See the overloads for this method\n * for the documentation on those parameters.\n *\n * @returns The data that `key` held, processed by i18next.\n */\nexport async function resolveKey<\n\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\tconst TOpt extends TOptions = TOptions,\n\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\tNs extends Namespace = DefaultNamespace,\n\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n>(\n\ttarget: Target,\n\t...[key, defaultValueOrOptions, optionsOrUndefined]:\n\t\t| [key: Key | Key[], options?: ActualOptions]\n\t\t| [key: string | string[], options: TOpt & $Dictionary & { defaultValue: string }]\n\t\t| [key: string | string[], defaultValue: string, options?: TOpt & $Dictionary]\n): Promise<TFunctionReturnOptionalDetails<Ret, TOpt>> {\n\tconst parsedOptions = typeof defaultValueOrOptions === 'string' ? optionsOrUndefined : defaultValueOrOptions;\n\tconst language = typeof parsedOptions?.lng === 'string' ? parsedOptions.lng : await fetchLanguage(target);\n\n\tif (typeof defaultValueOrOptions === 'string') {\n\t\treturn container.i18n.format<Key, TOpt, Ns, Ret, ActualOptions>(language, key, defaultValueOrOptions, optionsOrUndefined);\n\t}\n\n\treturn container.i18n.format<Key, TOpt, Ns, Ret, ActualOptions>(language, key, undefined, defaultValueOrOptions);\n}\n\n/**\n * @internal\n */\nasync function resolveLanguage(context: InternationalizationContext): Promise<string> {\n\tconst lang = await container.i18n.fetchLanguage(context);\n\treturn lang ?? context.guild?.preferredLocale ?? container.i18n.options.defaultName ?? 'en-US';\n}\n\nconst supportedLanguages = new Set(Object.values(Locale)) as ReadonlySet<LocaleString>;\n\nfunction isSupportedDiscordLocale(language: string): language is LocaleString {\n\treturn supportedLanguages.has(language as LocaleString);\n}\n\nconst getLocales = lazy(() => {\n\tconst locales = new Map(container.i18n.languages);\n\n\tfor (const [locale] of locales) {\n\t\tif (!isSupportedDiscordLocale(locale)) {\n\t\t\tprocess.emitWarning('Unsupported Discord locale', {\n\t\t\t\tcode: 'UNSUPPORTED_LOCALE',\n\t\t\t\tdetail: `'${locale}' needs to be one of: ${[...locales.keys()]}`\n\t\t\t});\n\n\t\t\tlocales.delete(locale);\n\t\t}\n\n\t\tcontinue;\n\t}\n\n\treturn locales;\n});\n\nconst getDefaultT = lazy(() => {\n\tconst defaultLocale = container.i18n.options.defaultName ?? 'en-US';\n\n\tif (!isSupportedDiscordLocale(defaultLocale)) {\n\t\tthrow new TypeError(`Unsupported Discord locale found:\\n'${defaultLocale}' is not within the list of ${[...supportedLanguages]}`);\n\t}\n\n\tconst defaultT = getLocales().get(defaultLocale);\n\n\tif (defaultT) {\n\t\treturn defaultT;\n\t}\n\n\tthrow new TypeError(`Could not find ${defaultLocale}`);\n});\n\n/**\n * Gets the value and the localizations from a language key.\n * @param key The key to get the localizations from.\n * @returns The retrieved data.\n * @remarks This should be called **strictly** after loading the locales.\n */\nexport function getLocalizedData<const TOpt extends TOptions = TOptions, Ns extends Namespace = DefaultNamespace, KPrefix = undefined>(\n\tkey: ParseKeys<Ns, TOpt, KPrefix>\n): LocalizedData {\n\tconst locales = getLocales();\n\tconst defaultT = getDefaultT();\n\n\treturn {\n\t\tvalue: defaultT(key),\n\t\tlocalizations: Object.fromEntries(Array.from(locales, ([locale, t]) => [locale, t(key)]))\n\t};\n}\n\n/**\n * Applies the localized names on the builder, calling `setName` and `setNameLocalizations`.\n * @param builder The builder to apply the localizations to.\n * @param key The key to get the localizations from.\n * @returns The updated builder.\n */\nexport function applyNameLocalizedBuilder<\n\tT extends BuilderWithName,\n\tconst TOpt extends TOptions = TOptions,\n\tNs extends Namespace = DefaultNamespace,\n\tKPrefix = undefined\n>(builder: T, key: ParseKeys<Ns, TOpt, KPrefix>) {\n\tconst result = getLocalizedData(key);\n\treturn builder.setName(result.value).setNameLocalizations(result.localizations);\n}\n\n/**\n * Applies the localized descriptions on the builder, calling `setDescription` and `setDescriptionLocalizations`.\n * @param builder The builder to apply the localizations to.\n * @param key The key to get the localizations from.\n * @returns The updated builder.\n */\nexport function applyDescriptionLocalizedBuilder<\n\tT extends BuilderWithDescription,\n\tconst TOpt extends TOptions = TOptions,\n\tNs extends Namespace = DefaultNamespace,\n\tKPrefix = undefined\n>(builder: T, key: ParseKeys<Ns, TOpt, KPrefix>) {\n\tconst result = getLocalizedData(key);\n\treturn builder.setDescription(result.value).setDescriptionLocalizations(result.localizations);\n}\n\n/**\n * Applies the localized names and descriptions on the builder, calling {@link applyNameLocalizedBuilder} and\n * {@link applyDescriptionLocalizedBuilder}.\n *\n * @param builder The builder to apply the localizations to.\n *\n * @param params The root key or the key for the name and description keys.\n * This needs to be either 1 or 2 parameters.\n * See examples below for more information.\n *\n * @returns The updated builder. You can chain subsequent builder methods on this.\n *\n * @remarks If only 2 parameters were passed, then this function will automatically append `Name` and `Description`\n * to the root-key (wherein `root-key` is second parameter in the function, after `builder`)\n * passed through the second parameter.\n *\n * For example given `applyLocalizedBuilder(builder, 'userinfo')` the localized options will use the i18next keys\n * `userinfoName` and `userinfoDescription`.\n *\n * In the following example we provide all parameters and add a User Option\n * `applyLocalizedBuilder` needs either\n * @example\n * ```typescript\n * class UserInfoCommand extends Command {\n * public registerApplicationCommands(registry: ChatInputCommand.Registry) {\n * registry.registerChatInputCommand(\n * (builder) =>\n * applyLocalizedBuilder(builder, 'commands/names:userinfo', 'commands/descriptions:userinfo')\n * .addUserOption(\n * (input) => applyLocalizedBuilder(input, 'commands/options:userinfo-name', 'commands/options:userinfo-description').setRequired(true)\n * )\n * );\n * }\n * }\n * ```\n *\n * In the following example we provide single root keys which means `Name` and `Description` get appended as mentioned above.\n * @example\n * ```typescript\n * class UserInfoCommand extends Command {\n * public registerApplicationCommands(registry: ChatInputCommand.Registry) {\n * registry.registerChatInputCommand(\n * (builder) =>\n * applyLocalizedBuilder(builder, 'commands:userinfo')\n * .addUserOption(\n * (input) => applyLocalizedBuilder(input, 'options:userinfo').setRequired(true)\n * )\n * );\n * }\n * }\n * ```\n */\nexport function applyLocalizedBuilder<\n\tT extends BuilderWithNameAndDescription,\n\tconst TOpt extends TOptions = TOptions,\n\tNs extends Namespace = DefaultNamespace,\n\tKPrefix = undefined\n>(builder: T, ...params: [root: string] | [name: ParseKeys<Ns, TOpt, KPrefix>, description: ParseKeys<Ns, TOpt, KPrefix>]): T {\n\ttype LocalKeysType = ParseKeys<Ns, TOpt, KPrefix>;\n\n\tconst [localeName, localeDescription] =\n\t\tparams.length === 1 ? [`${params[0]}Name` as LocalKeysType, `${params[0]}Description` as LocalKeysType] : params;\n\n\tapplyNameLocalizedBuilder(builder, localeName);\n\tapplyDescriptionLocalizedBuilder(builder, localeDescription);\n\n\treturn builder;\n}\n\n/**\n * Constructs an object that can be passed into `setChoices` for String or Number option with localized names.\n *\n * @param key The i18next key for the name of the select option name.\n * @param options The additional Select Menu options. This should _at least_ include the `value` key.\n * @returns An object with anything provided through {@link createLocalizedChoice.options} with `name` and `name_localizations` added.\n *\n * @example\n * ```typescript\n * export class TypeCommand extends Command {\n * public override registerApplicationCommands(registry: ChatInputCommand.Registry) {\n * registry.registerChatInputCommand((builder) =>\n * applyLocalizedBuilder(builder, 'commands/names:type').addStringOption((option) =>\n * applyLocalizedBuilder(option, 'commands/options:type')\n * .setRequired(true)\n * .setChoices(\n * createLocalizedChoice('selects/pokemon:type-grass', { value: 'grass' }),\n * createLocalizedChoice('selects/pokemon:type-water', { value: 'water' }),\n * createLocalizedChoice('selects/pokemon:type-fire', { value: 'fire' }),\n * createLocalizedChoice('selects/pokemon:type-electric', { value: 'electric' })\n * )\n * )\n * );\n * }\n * }\n * ```\n */\nexport function createLocalizedChoice<\n\tValueType = string | number,\n\tconst TOpt extends TOptions = TOptions,\n\tNs extends Namespace = DefaultNamespace,\n\tKPrefix = undefined\n>(\n\tkey: ParseKeys<Ns, TOpt, KPrefix>,\n\toptions: Omit<APIApplicationCommandOptionChoice<ValueType>, 'name' | 'name_localizations'>\n): APIApplicationCommandOptionChoice<ValueType> {\n\tconst result = getLocalizedData(key);\n\n\treturn {\n\t\t...options,\n\t\tname: result.value,\n\t\tname_localizations: result.localizations\n\t};\n}\n"]}
|
package/dist/cjs/lib/types.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"types.cjs"}
|
package/dist/cjs/register.cjs
CHANGED
|
@@ -16,8 +16,7 @@ var _I18nextPlugin = class _I18nextPlugin extends framework.Plugin {
|
|
|
16
16
|
static [framework.postLogin]() {
|
|
17
17
|
if (this.options.i18n?.hmr?.enabled) {
|
|
18
18
|
framework.container.logger.info("[i18next-Plugin]: HMR enabled. Watching for languages changes.");
|
|
19
|
-
|
|
20
|
-
for (const event of ["change", "unlink"]) hmr.on(event, () => framework.container.i18n.reloadResources());
|
|
19
|
+
chokidar.watch(framework.container.i18n.languagesDirectory, this.options.i18n.hmr.options ?? {}).on("change", () => framework.container.i18n.reloadResources()).on("unlink", () => framework.container.i18n.reloadResources());
|
|
21
20
|
}
|
|
22
21
|
}
|
|
23
22
|
};
|
|
@@ -28,5 +27,5 @@ framework.SapphireClient.plugins.registerPreLoginHook(I18nextPlugin[framework.pr
|
|
|
28
27
|
framework.SapphireClient.plugins.registerPostLoginHook(I18nextPlugin[framework.postLogin], "I18next-PostLogin");
|
|
29
28
|
|
|
30
29
|
exports.I18nextPlugin = I18nextPlugin;
|
|
31
|
-
//# sourceMappingURL=
|
|
30
|
+
//# sourceMappingURL=register.cjs.map
|
|
32
31
|
//# sourceMappingURL=register.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/register.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../src/register.ts"],"names":["Plugin","preGenericsInitialization","container","InternationalizationHandler","preLogin","postLogin","watch","SapphireClient"],"mappings":";;;;;;;;AAOO,IAAM,cAAA,GAAN,MAAM,cAAA,SAAsBA,gBAAO,CAAA;AAAA,EACzC,QAAeC,mCAAyB,CAAA,CAAwB,OAA8B,EAAA;AAC7F,IAAAC,mBAAA,CAAU,IAAO,GAAA,IAAIC,qCAA4B,CAAA,OAAA,CAAQ,IAAI,CAAA;AAAA;AAC9D,EAEA,cAAqBC,kBAAQ,CAAuC,GAAA;AACnE,IAAM,MAAAF,mBAAA,CAAU,KAAK,IAAK,EAAA;AAAA;AAC3B,EAEA,QAAeG,mBAAS,CAA8B,GAAA;AACrD,IAAA,IAAI,IAAK,CAAA,OAAA,CAAQ,IAAM,EAAA,GAAA,EAAK,OAAS,EAAA;AACpC,MAAUH,mBAAA,CAAA,MAAA,CAAO,KAAK,gEAAgE,CAAA;AAEtF,MAAMI,cAAA,CAAAJ,mBAAA,CAAU,IAAK,CAAA,kBAAA,EAAoB,IAAK,CAAA,OAAA,CAAQ,KAAK,GAAI,CAAA,OAAA,IAAW,EAAE,CAC1E,CAAA,EAAA,CAAG,UAAU,MAAMA,mBAAA,CAAU,IAAK,CAAA,eAAA,EAAiB,CAAA,CACnD,EAAG,CAAA,QAAA,EAAU,MAAMA,mBAAA,CAAU,IAAK,CAAA,eAAA,EAAiB,CAAA;AAAA;AACtD;AAEF,CAAA;AAlB0C,MAAA,CAAA,cAAA,EAAA,eAAA,CAAA;AAAnC,IAAM,aAAN,GAAA;AAoBPK,wBAAA,CAAe,OAAQ,CAAA,8BAAA,CAA+B,aAAc,CAAAN,mCAAyB,GAAG,mCAAmC,CAAA;AACnIM,wBAAA,CAAe,OAAQ,CAAA,oBAAA,CAAqB,aAAc,CAAAH,kBAAQ,GAAG,kBAAkB,CAAA;AACvFG,wBAAA,CAAe,OAAQ,CAAA,qBAAA,CAAsB,aAAc,CAAAF,mBAAS,GAAG,mBAAmB,CAAA","file":"register.cjs","sourcesContent":["import './index';\n\nimport { Plugin, SapphireClient, container, postLogin, preGenericsInitialization, preLogin } from '@sapphire/framework';\nimport { watch } from 'chokidar';\nimport type { ClientOptions } from 'discord.js';\nimport { InternationalizationHandler } from './index';\n\nexport class I18nextPlugin extends Plugin {\n\tpublic static [preGenericsInitialization](this: SapphireClient, options: ClientOptions): void {\n\t\tcontainer.i18n = new InternationalizationHandler(options.i18n);\n\t}\n\n\tpublic static async [preLogin](this: SapphireClient): Promise<void> {\n\t\tawait container.i18n.init();\n\t}\n\n\tpublic static [postLogin](this: SapphireClient): void {\n\t\tif (this.options.i18n?.hmr?.enabled) {\n\t\t\tcontainer.logger.info('[i18next-Plugin]: HMR enabled. Watching for languages changes.');\n\n\t\t\twatch(container.i18n.languagesDirectory, this.options.i18n.hmr.options ?? {})\n\t\t\t\t.on('change', () => container.i18n.reloadResources())\n\t\t\t\t.on('unlink', () => container.i18n.reloadResources());\n\t\t}\n\t}\n}\n\nSapphireClient.plugins.registerPostInitializationHook(I18nextPlugin[preGenericsInitialization], 'I18next-PreGenericsInitialization');\nSapphireClient.plugins.registerPreLoginHook(I18nextPlugin[preLogin], 'I18next-PreLogin');\nSapphireClient.plugins.registerPostLoginHook(I18nextPlugin[postLogin], 'I18next-PostLogin');\n"]}
|
|
@@ -4,5 +4,5 @@ var __name = (target, value) => __defProp(target, "name", { value, configurable:
|
|
|
4
4
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
5
5
|
|
|
6
6
|
export { __name, __publicField };
|
|
7
|
-
//# sourceMappingURL=
|
|
7
|
+
//# sourceMappingURL=chunk-2JTKI4GS.mjs.map
|
|
8
8
|
//# sourceMappingURL=chunk-2JTKI4GS.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"chunk-2JTKI4GS.mjs"}
|
package/dist/esm/index.d.mts
CHANGED
|
@@ -4,9 +4,18 @@ import * as i18next from 'i18next';
|
|
|
4
4
|
import { InitOptions, TFunction, ParseKeys, TOptions, Namespace, DefaultNamespace, TFunctionReturn, AppendKeyPrefix, InterpolationMap, TFunctionReturnOptionalDetails } from 'i18next';
|
|
5
5
|
export { TFunction, TOptions, default as i18next } from 'i18next';
|
|
6
6
|
import { PathLike } from 'node:fs';
|
|
7
|
-
import {
|
|
7
|
+
import { ChokidarOptions } from 'chokidar';
|
|
8
8
|
import { Message, StageChannel, VoiceChannel, Guild, User, Interaction, LocalizationMap, BaseInteraction, APIApplicationCommandOptionChoice } from 'discord.js';
|
|
9
9
|
|
|
10
|
+
/**
|
|
11
|
+
* This is a re-exported type from i18next.
|
|
12
|
+
*
|
|
13
|
+
* We could use NoInfer typescript build-in utility,
|
|
14
|
+
* however this project still supports ts < 5.4.
|
|
15
|
+
*
|
|
16
|
+
* @see https://github.com/millsp/ts-toolbelt/blob/master/sources/Function/NoInfer.ts
|
|
17
|
+
*/
|
|
18
|
+
type $NoInfer<A> = [A][A extends any ? 0 : never];
|
|
10
19
|
/**
|
|
11
20
|
* This is a re-exported type from i18next.
|
|
12
21
|
* It is essentially an object of key-value pairs, where the key is a string and the value is any.
|
|
@@ -42,7 +51,7 @@ interface HMROptions {
|
|
|
42
51
|
/**
|
|
43
52
|
* HMR options
|
|
44
53
|
*/
|
|
45
|
-
options?:
|
|
54
|
+
options?: ChokidarOptions;
|
|
46
55
|
}
|
|
47
56
|
/**
|
|
48
57
|
* Used to dynamically add options based on found languages in {@link InternationalizationHandler#init}.
|
|
@@ -494,4 +503,4 @@ declare module 'discord.js' {
|
|
|
494
503
|
*/
|
|
495
504
|
declare const version: string;
|
|
496
505
|
|
|
497
|
-
export { type $Dictionary, type $SpecialObject, type BuilderWithDescription, type BuilderWithName, type BuilderWithNameAndDescription, type ChannelTarget, type DiscordChannel, type DynamicOptions, type HMROptions, type I18nextFormatter, type I18nextFormatters, type I18nextNamedCachedFormatter, type I18nextNamedFormatter, type InternationalizationClientOptions, type InternationalizationContext, InternationalizationHandler, type InternationalizationOptions, type LocalizedData, type Target, type TextBasedDiscordChannel, applyDescriptionLocalizedBuilder, applyLocalizedBuilder, applyNameLocalizedBuilder, createLocalizedChoice, fetchLanguage, fetchT, getLocalizedData, resolveKey, version };
|
|
506
|
+
export { type $Dictionary, type $NoInfer, type $SpecialObject, type BuilderWithDescription, type BuilderWithName, type BuilderWithNameAndDescription, type ChannelTarget, type DiscordChannel, type DynamicOptions, type HMROptions, type I18nextFormatter, type I18nextFormatters, type I18nextNamedCachedFormatter, type I18nextNamedFormatter, type InternationalizationClientOptions, type InternationalizationContext, InternationalizationHandler, type InternationalizationOptions, type LocalizedData, type Target, type TextBasedDiscordChannel, applyDescriptionLocalizedBuilder, applyLocalizedBuilder, applyNameLocalizedBuilder, createLocalizedChoice, fetchLanguage, fetchT, getLocalizedData, resolveKey, version };
|
package/dist/esm/index.mjs
CHANGED
|
@@ -4,8 +4,8 @@ export * from './lib/InternationalizationHandler.mjs';
|
|
|
4
4
|
export * from './lib/functions.mjs';
|
|
5
5
|
export * from './lib/types.mjs';
|
|
6
6
|
|
|
7
|
-
var version = "7.1.3
|
|
7
|
+
var version = "7.1.3";
|
|
8
8
|
|
|
9
9
|
export { version };
|
|
10
|
-
//# sourceMappingURL=
|
|
10
|
+
//# sourceMappingURL=index.mjs.map
|
|
11
11
|
//# sourceMappingURL=index.mjs.map
|
package/dist/esm/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts"],"names":[
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;AAyBO,IAAM,OAAkB,GAAA","file":"index.mjs","sourcesContent":["import type { InternationalizationHandler } from './lib/InternationalizationHandler';\nimport type { InternationalizationClientOptions } from './lib/types';\n\nexport { default as i18next, type TFunction, type TOptions } from 'i18next';\nexport * from './lib/InternationalizationHandler';\nexport * from './lib/functions';\nexport * from './lib/types';\n\ndeclare module '@sapphire/pieces' {\n\tinterface Container {\n\t\ti18n: InternationalizationHandler;\n\t}\n}\n\ndeclare module 'discord.js' {\n\texport interface ClientOptions extends InternationalizationClientOptions {}\n}\n\n/**\n * The [@sapphire/plugin-i18next](https://github.com/sapphiredev/plugins/blob/main/packages/i18next) version that you are currently using.\n * An example use of this is showing it of in a bot information command.\n *\n * Note to Sapphire developers: This needs to explicitly be `string` so it is not typed as the string that gets replaced by esbuild\n */\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const version: string = '7.1.3';\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"Augmentations.d.mjs"}
|
|
@@ -166,7 +166,10 @@ var _InternationalizationHandler = class _InternationalizationHandler {
|
|
|
166
166
|
const language = this.languages.get(locale);
|
|
167
167
|
if (!language) throw new ReferenceError("Invalid language provided");
|
|
168
168
|
const defaultValue = typeof defaultValueOrOptions === "string" ? defaultValueOrOptions : this.options.defaultMissingKey ? language(this.options.defaultMissingKey, { replace: { key } }) : "";
|
|
169
|
-
return language(key, {
|
|
169
|
+
return language(key, {
|
|
170
|
+
defaultValue,
|
|
171
|
+
...optionsOrUndefined ?? {}
|
|
172
|
+
});
|
|
170
173
|
}
|
|
171
174
|
/**
|
|
172
175
|
* @param directory The directory that should be walked.
|
|
@@ -220,5 +223,5 @@ __name(_InternationalizationHandler, "InternationalizationHandler");
|
|
|
220
223
|
var InternationalizationHandler = _InternationalizationHandler;
|
|
221
224
|
|
|
222
225
|
export { InternationalizationHandler };
|
|
223
|
-
//# sourceMappingURL=
|
|
226
|
+
//# sourceMappingURL=InternationalizationHandler.mjs.map
|
|
224
227
|
//# sourceMappingURL=InternationalizationHandler.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/lib/InternationalizationHandler.ts"],"names":[],"mappings":";;;;;;AAAA,SAAS,cAAc;AACvB,SAAS,WAAW,mBAAmB;AACvC,SAAS,kBAAkC;AAC3C,SAAS,eAAoC;AAC7C,OAAO,aAUA;AAEP,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,KAAK,qBAAqB;AAO5B,IAAM,+BAAN,MAAM,6BAA4B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA2CjC,YAAY,SAAuC;AAtC1D;AAAA;AAAA;AAAA;AAAA,wBAAO,mBAAkB;AAMzB;AAAA;AAAA;AAAA;AAAA,wBAAO,cAAa,oBAAI,IAAY;AAMpC;AAAA;AAAA;AAAA;AAAA,wBAAgB,aAAY,oBAAI,IAAuB;AAMvD;AAAA;AAAA;AAAA;AAAA,wBAAgB;AAOhB;AAAA;AAAA;AAAA;AAAA;AAAA,w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AACnC,qBAAiB,SAAS,KAAK;AAC9B,UAAI,MAAM,YAAY,GAAG;AACxB,eAAO,KAAK,oBAAoB,KAAK,IAAI,MAAM,MAAM,IAAI,GAAG,GAAG,EAAE,GAAG,MAAM,IAAI,GAAG;AAAA,MAClF,WAAW,MAAM,OAAO,KAAK,MAAM,KAAK,SAAS,OAAO,GAAG;AAC1D,cAAM,GAAG,EAAE,GAAG,MAAM,KAAK,MAAM,GAAG,EAAE,CAAC;AAAA,MACtC;AAAA,IACD;AAAA,EACD;AACD;AA5TyC;AAAlC,IAAM,8BAAN","sourcesContent":["import { Result } from '@sapphire/framework';\nimport { container, getRootData } from '@sapphire/pieces';\nimport { isFunction, type Awaitable } from '@sapphire/utilities';\nimport { Backend, type PathResolvable } from '@skyra/i18next-backend';\nimport i18next, {\n\ttype AppendKeyPrefix,\n\ttype DefaultNamespace,\n\ttype InterpolationMap,\n\ttype Namespace,\n\ttype ParseKeys,\n\ttype TFunction,\n\ttype TFunctionReturn,\n\ttype TFunctionReturnOptionalDetails,\n\ttype TOptions\n} from 'i18next';\nimport type { PathLike } from 'node:fs';\nimport { opendir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { URL, fileURLToPath } from 'node:url';\nimport type { $Dictionary, $SpecialObject, InternationalizationContext, InternationalizationOptions } from './types';\n\n/**\n * A generalized class for handling `i18next` JSON files and their discovery.\n * @since 1.0.0\n */\nexport class InternationalizationHandler {\n\t/**\n\t * Describes whether {@link InternationalizationHandler.init} has been run and languages are loaded in {@link InternationalizationHandler.languages}.\n\t * @since 1.0.0\n\t */\n\tpublic languagesLoaded = false;\n\n\t/**\n\t * A `Set` of initially loaded namespaces.\n\t * @since 1.2.0\n\t */\n\tpublic namespaces = new Set<string>();\n\n\t/**\n\t * A `Map` of `i18next` language functions keyed by their language code.\n\t * @since 1.0.0\n\t */\n\tpublic readonly languages = new Map<string, TFunction>();\n\n\t/**\n\t * The options InternationalizationHandler was initialized with in the client.\n\t * @since 1.0.0\n\t */\n\tpublic readonly options: InternationalizationOptions;\n\n\t/**\n\t * The director passed to `@skyra/i18next-backend`.\n\t * Also used in {@link InternationalizationHandler.walkLanguageDirectory}.\n\t * @since 1.2.0\n\t */\n\tpublic readonly languagesDirectory: string;\n\n\t/**\n\t * The backend options for `@skyra/i18next-backend` used by `i18next`.\n\t * @since 1.0.0\n\t */\n\tprotected readonly backendOptions: Backend.Options;\n\n\t/**\n\t * @param options The options that `i18next`, `@skyra/i18next-backend`, and {@link InternationalizationHandler} should use.\n\t * @since 1.0.0\n\t * @constructor\n\t */\n\tpublic constructor(options?: InternationalizationOptions) {\n\t\tthis.options = options ?? { i18next: { ignoreJSONStructure: false } };\n\n\t\tconst baseUserDirectory =\n\t\t\tcontainer.client?.options?.baseUserDirectory instanceof URL\n\t\t\t\t? fileURLToPath(container.client?.options?.baseUserDirectory)\n\t\t\t\t: container.client?.options?.baseUserDirectory;\n\n\t\tthis.languagesDirectory = this.options.defaultLanguageDirectory ?? join(baseUserDirectory ?? getRootData().root, 'languages');\n\n\t\tconst languagePaths = new Set<PathResolvable>([\n\t\t\tjoin(this.languagesDirectory, '{{lng}}', '{{ns}}.json'), //\n\t\t\t...(options?.backend?.paths ?? [])\n\t\t]);\n\n\t\tthis.backendOptions = {\n\t\t\tpaths: [...languagePaths],\n\t\t\t...this.options.backend\n\t\t};\n\n\t\tif (isFunction(this.options.fetchLanguage)) {\n\t\t\tthis.fetchLanguage = this.options.fetchLanguage;\n\t\t}\n\t}\n\n\t/**\n\t * The method to be overridden by the developer.\n\t *\n\t * @note In the event that fetchLanguage is not defined or returns null / undefined, the defaulting from {@link fetchLanguage} will be used.\n\t * @since 2.0.0\n\t * @return A string for the desired language or null for no match.\n\t * @see {@link fetchLanguage}\n\t * @example\n\t * ```typescript\n\t * // Always use the same language (no per-guild configuration):\n\t * container.i18n.fetchLanguage = () => 'en-US';\n\t * ```\n\t * @example\n\t * ```typescript\n\t * // Retrieving the language from an SQL database:\n\t * container.i18n.fetchLanguage = async (context) => {\n\t * const guild = await driver.getOne('SELECT language FROM public.guild WHERE id = $1', [context.guild.id]);\n\t * return guild?.language ?? 'en-US';\n\t * };\n\t * ```\n\t * @example\n\t * ```typescript\n\t * // Retrieving the language from an ORM:\n\t * container.i18n.fetchLanguage = async (context) => {\n\t * const guild = await driver.getRepository(GuildEntity).findOne({ id: context.guild.id });\n\t * return guild?.language ?? 'en-US';\n\t * };\n\t * ```\n\t * @example\n\t * ```typescript\n\t * // Retrieving the language on a per channel basis, e.g. per user or guild channel (ORM example but same principles apply):\n\t * container.i18n.fetchLanguage = async (context) => {\n\t * const channel = await driver.getRepository(ChannelEntity).findOne({ id: context.channel.id });\n\t * return channel?.language ?? 'en-US';\n\t * };\n\t * ```\n\t */\n\tpublic fetchLanguage: (context: InternationalizationContext) => Awaitable<string | null> = () => null;\n\n\t/**\n\t * Initializes the handler by loading in the namespaces, passing the data to i18next, and filling in the {@link InternationalizationHandler#languages}.\n\t * @since 1.0.0\n\t */\n\tpublic async init() {\n\t\tconst { namespaces, languages } = await this.walkRootDirectory(this.languagesDirectory);\n\t\tconst userOptions = isFunction(this.options.i18next) ? this.options.i18next(namespaces, languages) : this.options.i18next;\n\t\tconst ignoreJSONStructure = userOptions?.ignoreJSONStructure ?? false;\n\t\tconst skipOnVariables = userOptions?.interpolation?.skipOnVariables ?? false;\n\n\t\ti18next.use(Backend);\n\t\tawait i18next.init({\n\t\t\tbackend: this.backendOptions,\n\t\t\tfallbackLng: this.options.defaultName ?? 'en-US',\n\t\t\tinitImmediate: false,\n\t\t\tinterpolation: {\n\t\t\t\tescapeValue: false,\n\t\t\t\t...userOptions?.interpolation,\n\t\t\t\tskipOnVariables\n\t\t\t},\n\t\t\tload: 'all',\n\t\t\tdefaultNS: 'default',\n\t\t\tns: namespaces,\n\t\t\tpreload: languages,\n\t\t\t...userOptions,\n\t\t\tignoreJSONStructure\n\t\t});\n\n\t\tthis.namespaces = new Set(namespaces);\n\t\tfor (const item of languages) {\n\t\t\tthis.languages.set(item, i18next.getFixedT(item));\n\t\t}\n\t\tthis.languagesLoaded = true;\n\n\t\tconst formatter = i18next.services.formatter!;\n\t\tconst formatters = this.options.formatters ?? [];\n\t\tfor (const { name, format, cached } of formatters) {\n\t\t\tif (cached) formatter.addCached(name, format);\n\t\t\telse formatter.add(name, format);\n\t\t}\n\t}\n\n\t/**\n\t * Retrieve a raw TFunction from the passed locale.\n\t * @param locale The language to be used.\n\t * @since 1.0.0\n\t */\n\tpublic getT(locale: string) {\n\t\tif (!this.languagesLoaded) throw new Error('Cannot call this method until InternationalizationHandler#init has been called');\n\n\t\tconst t = this.languages.get(locale);\n\t\tif (t) return t;\n\t\tthrow new ReferenceError('Invalid language provided');\n\t}\n\n\t/**\n\t * Localizes a content given one or more keys and i18next options.\n\t * @since 2.0.0\n\t * @param locale The language to be used.\n\t * @param key The key or keys to retrieve the content from.\n\t * @param options The interpolation options.\n\t * @see {@link https://www.i18next.com/overview/api#t}\n\t * @returns The localized content.\n\t */\n\tpublic format<\n\t\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\t\tconst TOpt extends TOptions = TOptions,\n\t\tNs extends Namespace = DefaultNamespace,\n\t\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\t\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n\t>(locale: string, key: Key | Key[], options?: ActualOptions): TFunctionReturnOptionalDetails<Ret, TOpt>;\n\n\t/**\n\t * Localizes a content given one or more keys and i18next options.\n\t * @since 2.0.0\n\t * @param locale The language to be used.\n\t * @param key The key or keys to retrieve the content from.\n\t * @param options The interpolation options as well as a `defaultValue` for the key and any key/value pairs.\n\t * @see {@link https://www.i18next.com/overview/api#t}\n\t * @returns The localized content.\n\t */\n\tpublic format<\n\t\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\t\tconst TOpt extends TOptions = TOptions,\n\t\tNs extends Namespace = DefaultNamespace,\n\t\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\t\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n\t>(locale: string, key: string | string[], options: TOpt & $Dictionary & { defaultValue: string }): TFunctionReturnOptionalDetails<Ret, TOpt>;\n\n\t/**\n\t * Localizes a content given one or more keys and i18next options.\n\t * @since 2.0.0\n\t * @param locale The language to be used.\n\t * @param key The key or keys to retrieve the content from.\n\t * @param defaultValue The default value to use if the key is not found.\n\t * @param options The interpolation options.\n\t * @see {@link https://www.i18next.com/overview/api#t}\n\t * @returns The localized content.\n\t */\n\tpublic format<\n\t\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\t\tconst TOpt extends TOptions = TOptions,\n\t\tNs extends Namespace = DefaultNamespace,\n\t\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\t\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n\t>(\n\t\tlocale: string,\n\t\tkey: string | string[],\n\t\tdefaultValue: string | undefined,\n\t\toptions?: TOpt & $Dictionary\n\t): TFunctionReturnOptionalDetails<Ret, TOpt>;\n\n\t/**\n\t * Localizes a content given one or more keys and i18next options.\n\t * @since 2.0.0\n\t * @param locale The language to be used.\n\t *\n\t * @remark This function also has additional parameters for `key`, `defaultValue`, and `options`, however\n\t * TSDoc does not let us document those while matching proper implementation. See the overloads for this method\n\t * for the documentation on those parameters.\n\t *\n\t * @see {@link https://www.i18next.com/overview/api#t}\n\t * @returns The localized content.\n\t */\n\tpublic format<\n\t\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\t\tconst TOpt extends TOptions = TOptions,\n\t\tNs extends Namespace = DefaultNamespace,\n\t\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\t\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n\t>(\n\t\tlocale: string,\n\t\t...[key, defaultValueOrOptions, optionsOrUndefined]:\n\t\t\t| [key: Key | Key[], options?: ActualOptions]\n\t\t\t| [key: string | string[], options: TOpt & $Dictionary & { defaultValue: string }]\n\t\t\t| [key: string | string[], defaultValue: string | undefined, options?: TOpt & $Dictionary]\n\t): TFunctionReturnOptionalDetails<Ret, TOpt> {\n\t\tif (!this.languagesLoaded) throw new Error('Cannot call this method until InternationalizationHandler#init has been called');\n\n\t\tconst language = this.languages.get(locale);\n\t\tif (!language) throw new ReferenceError('Invalid language provided');\n\n\t\tconst defaultValue =\n\t\t\ttypeof defaultValueOrOptions === 'string'\n\t\t\t\t? defaultValueOrOptions\n\t\t\t\t: this.options.defaultMissingKey\n\t\t\t\t\t? language(this.options.defaultMissingKey, { replace: { key } })\n\t\t\t\t\t: '';\n\n\t\treturn language<Key, TOpt, Ret, ActualOptions>(key, { defaultValue, ...((optionsOrUndefined ?? {}) as TOpt) });\n\t}\n\n\t/**\n\t * @param directory The directory that should be walked.\n\t * @since 3.0.0\n\t */\n\tpublic async walkRootDirectory(directory: PathLike) {\n\t\tconst languages = new Set<string>();\n\t\tconst namespaces = new Set<string>();\n\n\t\tconst dir = await opendir(directory);\n\t\tfor await (const entry of dir) {\n\t\t\t// If the entry is not a directory, skip:\n\t\t\tif (!entry.isDirectory()) continue;\n\n\t\t\t// Load the directory:\n\t\t\tlanguages.add(entry.name);\n\n\t\t\tfor await (const namespace of this.walkLocaleDirectory(join(dir.path, entry.name), '')) {\n\t\t\t\tnamespaces.add(namespace);\n\t\t\t}\n\t\t}\n\n\t\treturn { namespaces: [...namespaces], languages: [...languages] };\n\t}\n\n\tpublic async reloadResources() {\n\t\tconst result = await Result.fromAsync(async () => {\n\t\t\tlet languages = this.options.hmr?.languages;\n\t\t\tlet namespaces = this.options.hmr?.namespaces;\n\t\t\tif (!languages || !namespaces) {\n\t\t\t\tconst languageDirectoryResult = await this.walkRootDirectory(this.languagesDirectory);\n\t\t\t\tlanguages ??= languageDirectoryResult.languages;\n\t\t\t\tnamespaces ??= languageDirectoryResult.namespaces;\n\t\t\t}\n\n\t\t\tawait i18next.reloadResources(languages, namespaces);\n\t\t\tcontainer.logger.info('[i18next-Plugin] Reloaded language resources.');\n\t\t});\n\n\t\tresult.inspectErr((error) => container.logger.error('[i18next-Plugin]: Failed to reload language resources.', error));\n\t}\n\n\t/**\n\t * @description Skips any files that don't end with `.json`.\n\t * @param directory The directory that should be walked.\n\t * @param ns The current namespace.\n\t * @since 3.0.0\n\t */\n\tprivate async *walkLocaleDirectory(directory: string, ns: string): AsyncGenerator<string> {\n\t\tconst dir = await opendir(directory);\n\t\tfor await (const entry of dir) {\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tyield* this.walkLocaleDirectory(join(dir.path, entry.name), `${ns}${entry.name}/`);\n\t\t\t} else if (entry.isFile() && entry.name.endsWith('.json')) {\n\t\t\t\tyield `${ns}${entry.name.slice(0, -5)}`;\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/InternationalizationHandler.ts"],"names":[],"mappings":";;;;;;;;;;AA0BO,IAAM,4BAAA,GAAN,MAAM,4BAA4B,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA2CjC,YAAY,OAAuC,EAAA;AAtC1D;AAAA;AAAA;AAAA;AAAA,IAAA,aAAA,CAAA,IAAA,EAAO,iBAAkB,EAAA,KAAA,CAAA;AAMzB;AAAA;AAAA;AAAA;AAAA,IAAO,aAAA,CAAA,IAAA,EAAA,YAAA,sBAAiB,GAAY,EAAA,CAAA;AAMpC;AAAA;AAAA;AAAA;AAAA,IAAgB,aAAA,CAAA,IAAA,EAAA,WAAA,sBAAgB,GAAuB,EAAA,CAAA;AAMvD;AAAA;AAAA;AAAA;AAAA,IAAgB,aA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InternationalizationHandler.mjs","sourcesContent":["import { Result } from '@sapphire/framework';\nimport { container, getRootData } from '@sapphire/pieces';\nimport { isFunction, type Awaitable } from '@sapphire/utilities';\nimport { Backend, type PathResolvable } from '@skyra/i18next-backend';\nimport i18next, {\n\ttype AppendKeyPrefix,\n\ttype DefaultNamespace,\n\ttype InterpolationMap,\n\ttype Namespace,\n\ttype ParseKeys,\n\ttype TFunction,\n\ttype TFunctionProcessReturnValue,\n\ttype TFunctionReturn,\n\ttype TFunctionReturnOptionalDetails,\n\ttype TOptions\n} from 'i18next';\nimport type { PathLike } from 'node:fs';\nimport { opendir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { URL, fileURLToPath } from 'node:url';\nimport type { $Dictionary, $NoInfer, $SpecialObject, InternationalizationContext, InternationalizationOptions } from './types';\n\n/**\n * A generalized class for handling `i18next` JSON files and their discovery.\n * @since 1.0.0\n */\nexport class InternationalizationHandler {\n\t/**\n\t * Describes whether {@link InternationalizationHandler.init} has been run and languages are loaded in {@link InternationalizationHandler.languages}.\n\t * @since 1.0.0\n\t */\n\tpublic languagesLoaded = false;\n\n\t/**\n\t * A `Set` of initially loaded namespaces.\n\t * @since 1.2.0\n\t */\n\tpublic namespaces = new Set<string>();\n\n\t/**\n\t * A `Map` of `i18next` language functions keyed by their language code.\n\t * @since 1.0.0\n\t */\n\tpublic readonly languages = new Map<string, TFunction>();\n\n\t/**\n\t * The options InternationalizationHandler was initialized with in the client.\n\t * @since 1.0.0\n\t */\n\tpublic readonly options: InternationalizationOptions;\n\n\t/**\n\t * The director passed to `@skyra/i18next-backend`.\n\t * Also used in {@link InternationalizationHandler.walkLanguageDirectory}.\n\t * @since 1.2.0\n\t */\n\tpublic readonly languagesDirectory: string;\n\n\t/**\n\t * The backend options for `@skyra/i18next-backend` used by `i18next`.\n\t * @since 1.0.0\n\t */\n\tprotected readonly backendOptions: Backend.Options;\n\n\t/**\n\t * @param options The options that `i18next`, `@skyra/i18next-backend`, and {@link InternationalizationHandler} should use.\n\t * @since 1.0.0\n\t * @constructor\n\t */\n\tpublic constructor(options?: InternationalizationOptions) {\n\t\tthis.options = options ?? { i18next: { ignoreJSONStructure: false } };\n\n\t\tconst baseUserDirectory =\n\t\t\tcontainer.client?.options?.baseUserDirectory instanceof URL\n\t\t\t\t? fileURLToPath(container.client?.options?.baseUserDirectory)\n\t\t\t\t: container.client?.options?.baseUserDirectory;\n\n\t\tthis.languagesDirectory = this.options.defaultLanguageDirectory ?? join(baseUserDirectory ?? getRootData().root, 'languages');\n\n\t\tconst languagePaths = new Set<PathResolvable>([\n\t\t\tjoin(this.languagesDirectory, '{{lng}}', '{{ns}}.json'), //\n\t\t\t...(options?.backend?.paths ?? [])\n\t\t]);\n\n\t\tthis.backendOptions = {\n\t\t\tpaths: [...languagePaths],\n\t\t\t...this.options.backend\n\t\t};\n\n\t\tif (isFunction(this.options.fetchLanguage)) {\n\t\t\tthis.fetchLanguage = this.options.fetchLanguage;\n\t\t}\n\t}\n\n\t/**\n\t * The method to be overridden by the developer.\n\t *\n\t * @note In the event that fetchLanguage is not defined or returns null / undefined, the defaulting from {@link fetchLanguage} will be used.\n\t * @since 2.0.0\n\t * @return A string for the desired language or null for no match.\n\t * @see {@link fetchLanguage}\n\t * @example\n\t * ```typescript\n\t * // Always use the same language (no per-guild configuration):\n\t * container.i18n.fetchLanguage = () => 'en-US';\n\t * ```\n\t * @example\n\t * ```typescript\n\t * // Retrieving the language from an SQL database:\n\t * container.i18n.fetchLanguage = async (context) => {\n\t * const guild = await driver.getOne('SELECT language FROM public.guild WHERE id = $1', [context.guild.id]);\n\t * return guild?.language ?? 'en-US';\n\t * };\n\t * ```\n\t * @example\n\t * ```typescript\n\t * // Retrieving the language from an ORM:\n\t * container.i18n.fetchLanguage = async (context) => {\n\t * const guild = await driver.getRepository(GuildEntity).findOne({ id: context.guild.id });\n\t * return guild?.language ?? 'en-US';\n\t * };\n\t * ```\n\t * @example\n\t * ```typescript\n\t * // Retrieving the language on a per channel basis, e.g. per user or guild channel (ORM example but same principles apply):\n\t * container.i18n.fetchLanguage = async (context) => {\n\t * const channel = await driver.getRepository(ChannelEntity).findOne({ id: context.channel.id });\n\t * return channel?.language ?? 'en-US';\n\t * };\n\t * ```\n\t */\n\tpublic fetchLanguage: (context: InternationalizationContext) => Awaitable<string | null> = () => null;\n\n\t/**\n\t * Initializes the handler by loading in the namespaces, passing the data to i18next, and filling in the {@link InternationalizationHandler#languages}.\n\t * @since 1.0.0\n\t */\n\tpublic async init() {\n\t\tconst { namespaces, languages } = await this.walkRootDirectory(this.languagesDirectory);\n\t\tconst userOptions = isFunction(this.options.i18next) ? this.options.i18next(namespaces, languages) : this.options.i18next;\n\t\tconst ignoreJSONStructure = userOptions?.ignoreJSONStructure ?? false;\n\t\tconst skipOnVariables = userOptions?.interpolation?.skipOnVariables ?? false;\n\n\t\ti18next.use(Backend);\n\t\tawait i18next.init({\n\t\t\tbackend: this.backendOptions,\n\t\t\tfallbackLng: this.options.defaultName ?? 'en-US',\n\t\t\tinitImmediate: false,\n\t\t\tinterpolation: {\n\t\t\t\tescapeValue: false,\n\t\t\t\t...userOptions?.interpolation,\n\t\t\t\tskipOnVariables\n\t\t\t},\n\t\t\tload: 'all',\n\t\t\tdefaultNS: 'default',\n\t\t\tns: namespaces,\n\t\t\tpreload: languages,\n\t\t\t...userOptions,\n\t\t\tignoreJSONStructure\n\t\t});\n\n\t\tthis.namespaces = new Set(namespaces);\n\t\tfor (const item of languages) {\n\t\t\tthis.languages.set(item, i18next.getFixedT(item));\n\t\t}\n\t\tthis.languagesLoaded = true;\n\n\t\tconst formatter = i18next.services.formatter!;\n\t\tconst formatters = this.options.formatters ?? [];\n\t\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\t\tfor (const { name, format, cached } of formatters) {\n\t\t\tif (cached) formatter.addCached(name, format);\n\t\t\telse formatter.add(name, format);\n\t\t}\n\t}\n\n\t/**\n\t * Retrieve a raw TFunction from the passed locale.\n\t * @param locale The language to be used.\n\t * @since 1.0.0\n\t */\n\tpublic getT(locale: string) {\n\t\tif (!this.languagesLoaded) throw new Error('Cannot call this method until InternationalizationHandler#init has been called');\n\n\t\tconst t = this.languages.get(locale);\n\t\tif (t) return t;\n\t\tthrow new ReferenceError('Invalid language provided');\n\t}\n\n\t/**\n\t * Localizes a content given one or more keys and i18next options.\n\t * @since 2.0.0\n\t * @param locale The language to be used.\n\t * @param key The key or keys to retrieve the content from.\n\t * @param options The interpolation options.\n\t * @see {@link https://www.i18next.com/overview/api#t}\n\t * @returns The localized content.\n\t */\n\tpublic format<\n\t\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\t\tconst TOpt extends TOptions = TOptions,\n\t\tNs extends Namespace = DefaultNamespace,\n\t\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\t\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n\t>(locale: string, key: Key | Key[], options?: ActualOptions): TFunctionReturnOptionalDetails<Ret, TOpt>;\n\n\t/**\n\t * Localizes a content given one or more keys and i18next options.\n\t * @since 2.0.0\n\t * @param locale The language to be used.\n\t * @param key The key or keys to retrieve the content from.\n\t * @param options The interpolation options as well as a `defaultValue` for the key and any key/value pairs.\n\t * @see {@link https://www.i18next.com/overview/api#t}\n\t * @returns The localized content.\n\t */\n\tpublic format<\n\t\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\t\tconst TOpt extends TOptions = TOptions,\n\t\tNs extends Namespace = DefaultNamespace,\n\t\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\t\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n\t>(locale: string, key: string | string[], options: TOpt & $Dictionary & { defaultValue: string }): TFunctionReturnOptionalDetails<Ret, TOpt>;\n\n\t/**\n\t * Localizes a content given one or more keys and i18next options.\n\t * @since 2.0.0\n\t * @param locale The language to be used.\n\t * @param key The key or keys to retrieve the content from.\n\t * @param defaultValue The default value to use if the key is not found.\n\t * @param options The interpolation options.\n\t * @see {@link https://www.i18next.com/overview/api#t}\n\t * @returns The localized content.\n\t */\n\tpublic format<\n\t\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\t\tconst TOpt extends TOptions = TOptions,\n\t\tNs extends Namespace = DefaultNamespace,\n\t\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\t\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n\t>(\n\t\tlocale: string,\n\t\tkey: string | string[],\n\t\tdefaultValue: string | undefined,\n\t\toptions?: TOpt & $Dictionary\n\t): TFunctionReturnOptionalDetails<Ret, TOpt>;\n\n\t/**\n\t * Localizes a content given one or more keys and i18next options.\n\t * @since 2.0.0\n\t * @param locale The language to be used.\n\t *\n\t * @remark This function also has additional parameters for `key`, `defaultValue`, and `options`, however\n\t * TSDoc does not let us document those while matching proper implementation. See the overloads for this method\n\t * for the documentation on those parameters.\n\t *\n\t * @see {@link https://www.i18next.com/overview/api#t}\n\t * @returns The localized content.\n\t */\n\tpublic format<\n\t\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\t\tconst TOpt extends TOptions = TOptions,\n\t\tNs extends Namespace = DefaultNamespace,\n\t\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\t\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>,\n\t\tDefaultValue extends string = never\n\t>(\n\t\tlocale: string,\n\t\t...[key, defaultValueOrOptions, optionsOrUndefined]:\n\t\t\t| [key: Key | Key[], options?: ActualOptions]\n\t\t\t| [key: string | string[], options: TOpt & $Dictionary & { defaultValue: string }]\n\t\t\t| [key: string | string[], defaultValue: DefaultValue | undefined, options?: TOpt & $Dictionary]\n\t): TFunctionReturnOptionalDetails<TFunctionProcessReturnValue<$NoInfer<Ret>, DefaultValue>, TOpt> {\n\t\tif (!this.languagesLoaded) throw new Error('Cannot call this method until InternationalizationHandler#init has been called');\n\n\t\tconst language = this.languages.get(locale);\n\t\tif (!language) throw new ReferenceError('Invalid language provided');\n\n\t\tconst defaultValue =\n\t\t\ttypeof defaultValueOrOptions === 'string'\n\t\t\t\t? defaultValueOrOptions\n\t\t\t\t: this.options.defaultMissingKey\n\t\t\t\t\t? language(this.options.defaultMissingKey, { replace: { key } })\n\t\t\t\t\t: '';\n\n\t\treturn language<Key, TOpt, Ret, ActualOptions, DefaultValue>(key, {\n\t\t\tdefaultValue,\n\t\t\t...((optionsOrUndefined ?? {}) as TOpt)\n\t\t} as TOpt & $Dictionary & { defaultValue: DefaultValue });\n\t}\n\n\t/**\n\t * @param directory The directory that should be walked.\n\t * @since 3.0.0\n\t */\n\tpublic async walkRootDirectory(directory: PathLike) {\n\t\tconst languages = new Set<string>();\n\t\tconst namespaces = new Set<string>();\n\n\t\tconst dir = await opendir(directory);\n\t\tfor await (const entry of dir) {\n\t\t\t// If the entry is not a directory, skip:\n\t\t\tif (!entry.isDirectory()) continue;\n\n\t\t\t// Load the directory:\n\t\t\tlanguages.add(entry.name);\n\n\t\t\tfor await (const namespace of this.walkLocaleDirectory(join(dir.path, entry.name), '')) {\n\t\t\t\tnamespaces.add(namespace);\n\t\t\t}\n\t\t}\n\n\t\treturn { namespaces: [...namespaces], languages: [...languages] };\n\t}\n\n\tpublic async reloadResources() {\n\t\tconst result = await Result.fromAsync(async () => {\n\t\t\tlet languages = this.options.hmr?.languages;\n\t\t\tlet namespaces = this.options.hmr?.namespaces;\n\t\t\tif (!languages || !namespaces) {\n\t\t\t\tconst languageDirectoryResult = await this.walkRootDirectory(this.languagesDirectory);\n\t\t\t\tlanguages ??= languageDirectoryResult.languages;\n\t\t\t\tnamespaces ??= languageDirectoryResult.namespaces;\n\t\t\t}\n\n\t\t\tawait i18next.reloadResources(languages, namespaces);\n\t\t\tcontainer.logger.info('[i18next-Plugin] Reloaded language resources.');\n\t\t});\n\n\t\tresult.inspectErr((error) => container.logger.error('[i18next-Plugin]: Failed to reload language resources.', error));\n\t}\n\n\t/**\n\t * @description Skips any files that don't end with `.json`.\n\t * @param directory The directory that should be walked.\n\t * @param ns The current namespace.\n\t * @since 3.0.0\n\t */\n\tprivate async *walkLocaleDirectory(directory: string, ns: string): AsyncGenerator<string> {\n\t\tconst dir = await opendir(directory);\n\t\tfor await (const entry of dir) {\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tyield* this.walkLocaleDirectory(join(dir.path, entry.name), `${ns}${entry.name}/`);\n\t\t\t} else if (entry.isFile() && entry.name.endsWith('.json')) {\n\t\t\t\tyield `${ns}${entry.name.slice(0, -5)}`;\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
|
|
@@ -19,7 +19,7 @@ function fetchLanguage(target) {
|
|
|
19
19
|
if (target instanceof Guild) {
|
|
20
20
|
return resolveLanguage({ user: null, channel: null, guild: target });
|
|
21
21
|
}
|
|
22
|
-
if (target.type === ChannelType.DM) {
|
|
22
|
+
if (target.type === ChannelType.DM || target.type === ChannelType.GroupDM) {
|
|
23
23
|
return resolveLanguage({ user: null, channel: target, guild: null });
|
|
24
24
|
}
|
|
25
25
|
return resolveLanguage({ user: null, channel: target, guild: target.guild });
|
|
@@ -111,5 +111,5 @@ function createLocalizedChoice(key, options) {
|
|
|
111
111
|
__name(createLocalizedChoice, "createLocalizedChoice");
|
|
112
112
|
|
|
113
113
|
export { applyDescriptionLocalizedBuilder, applyLocalizedBuilder, applyNameLocalizedBuilder, createLocalizedChoice, fetchLanguage, fetchT, getLocalizedData, resolveKey };
|
|
114
|
-
//# sourceMappingURL=
|
|
114
|
+
//# sourceMappingURL=functions.mjs.map
|
|
115
115
|
//# sourceMappingURL=functions.mjs.map
|
|
@@ -1 +1 @@
|
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AC,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC;AAAA,EACzF;AACD;AAVgB;AAkBT,SAAS,0BAKd,SAAY,KAAmC;AAChD,QAAM,SAAS,iBAAiB,GAAG;AACnC,SAAO,QAAQ,QAAQ,OAAO,KAAK,EAAE,qBAAqB,OAAO,aAAa;AAC/E;AARgB;AAgBT,SAAS,iCAKd,SAAY,KAAmC;AAChD,QAAM,SAAS,iBAAiB,GAAG;AACnC,SAAO,QAAQ,eAAe,OAAO,KAAK,EAAE,4BAA4B,OAAO,aAAa;AAC7F;AARgB;AA8DT,SAAS,sBAKd,YAAe,QAA6G;AAG7H,QAAM,CAAC,YAAY,iBAAiB,IACnC,OAAO,WAAW,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,QAAyB,GAAG,OAAO,CAAC,CAAC,aAA8B,IAAI;AAE3G,4BAA0B,SAAS,UAAU;AAC7C,mCAAiC,SAAS,iBAAiB;AAE3D,SAAO;AACR;AAfgB;AA4CT,SAAS,sBAMf,KACA,SAC+C;AAC/C,QAAM,SAAS,iBAAiB,GAAG;AAEnC,SAAO;AAAA,IACN,GAAG;AAAA,IACH,MAAM,OAAO;AAAA,IACb,oBAAoB,OAAO;AAAA,EAC5B;AACD;AAhBgB","sourcesContent":["import { container } from '@sapphire/pieces';\nimport { lazy } from '@sapphire/utilities';\nimport { BaseInteraction, ChannelType, Guild, Locale, Message, type APIApplicationCommandOptionChoice, type LocaleString } from 'discord.js';\nimport type {\n\tAppendKeyPrefix,\n\tDefaultNamespace,\n\tInterpolationMap,\n\tNamespace,\n\tParseKeys,\n\tTFunctionReturn,\n\tTFunctionReturnOptionalDetails,\n\tTOptions\n} from 'i18next';\nimport type {\n\t$Dictionary,\n\t$SpecialObject,\n\tBuilderWithDescription,\n\tBuilderWithName,\n\tBuilderWithNameAndDescription,\n\tInternationalizationContext,\n\tLocalizedData,\n\tTarget\n} from './types';\n\n/**\n * Retrieves the language name for a specific target, using {@link InternationalizationHandler.fetchLanguage}.\n * If {@link InternationalizationHandler.fetchLanguage} is not defined or this function returns a nullish value,\n * then there will be a series of fallback attempts in the following descending order:\n * 1. Returns {@link Guild.preferredLocale}.\n * 2. Returns {@link InternationalizationOptions.defaultName} if no guild was provided.\n * 3. Returns `'en-US'` if nothing else was found.\n * @since 2.0.0\n * @param target The target to fetch the language from.\n * @see {@link resolveLanguage}\n * @returns The name of the language key.\n */\nexport function fetchLanguage(target: Target): Promise<string> {\n\t// Handle Interactions:\n\tif (target instanceof BaseInteraction) {\n\t\treturn resolveLanguage({\n\t\t\tuser: target.user,\n\t\t\tchannel: target.channel,\n\t\t\tguild: target.guild,\n\t\t\tinteractionGuildLocale: target.guildLocale,\n\t\t\tinteractionLocale: target.locale\n\t\t});\n\t}\n\n\t// Handle Message:\n\tif (target instanceof Message) {\n\t\treturn resolveLanguage({ user: target.author, channel: target.channel, guild: target.guild });\n\t}\n\n\t// Handle Guild:\n\tif (target instanceof Guild) {\n\t\treturn resolveLanguage({ user: null, channel: null, guild: target });\n\t}\n\n\t// Handle DMChannel:\n\tif (target.type === ChannelType.DM) {\n\t\treturn resolveLanguage({ user: null, channel: target, guild: null });\n\t}\n\n\t// Handle any other channel:\n\treturn resolveLanguage({ user: null, channel: target, guild: target.guild });\n}\n\n/**\n * Retrieves the language-assigned function from i18next designated to a target's preferred language code.\n * @since 2.0.0\n * @param target The target to fetch the language from.\n * @returns The language function from i18next.\n */\nexport async function fetchT(target: Target) {\n\treturn container.i18n.getT(await fetchLanguage(target));\n}\n\n/**\n * Resolves a key and its parameters.\n * @since 2.0.0\n * @param target The target to fetch the language key from.\n * @param key The i18next key.\n * @param options The options to be passed to TFunction.\n * @returns The data that `key` held, processed by i18next.\n */\nexport async function resolveKey<\n\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\tconst TOpt extends TOptions = TOptions,\n\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\tNs extends Namespace = DefaultNamespace,\n\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n>(target: Target, key: Key | Key[], options?: ActualOptions): Promise<TFunctionReturnOptionalDetails<Ret, TOpt>>;\n\n/**\n * Resolves a key and its parameters.\n * @since 2.0.0\n * @param target The target to fetch the language key from.\n * @param key The i18next key.\n * @param options The interpolation options as well as a `defaultValue` for the key and any key/value pairs.\n * @returns The data that `key` held, processed by i18next.\n */\nexport async function resolveKey<\n\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\tconst TOpt extends TOptions = TOptions,\n\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\tNs extends Namespace = DefaultNamespace,\n\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n>(target: Target, key: string | string[], options: TOpt & $Dictionary & { defaultValue: string }): Promise<TFunctionReturnOptionalDetails<Ret, TOpt>>;\n\n/**\n * Resolves a key and its parameters.\n * @since 2.0.0\n * @param target The target to fetch the language key from.\n * @param key The i18next key.\n * @param defaultValue The default value to use if the key is not found.\n * @param options The interpolation options.\n * @returns The data that `key` held, processed by i18next.\n */\nexport async function resolveKey<\n\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\tconst TOpt extends TOptions = TOptions,\n\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\tNs extends Namespace = DefaultNamespace,\n\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n>(target: Target, key: string | string[], defaultValue: string, options?: TOpt & $Dictionary): Promise<TFunctionReturnOptionalDetails<Ret, TOpt>>;\n\n/**\n * Resolves a key and its parameters.\n * @since 2.0.0\n * @param target The target to fetch the language key from.\n *\n * @remark This function also has additional parameters for `key`, `defaultValue`, and `options`, however\n * TSDoc does not let us document those while matching proper implementation. See the overloads for this method\n * for the documentation on those parameters.\n *\n * @returns The data that `key` held, processed by i18next.\n */\nexport async function resolveKey<\n\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\tconst TOpt extends TOptions = TOptions,\n\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\tNs extends Namespace = DefaultNamespace,\n\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n>(\n\ttarget: Target,\n\t...[key, defaultValueOrOptions, optionsOrUndefined]:\n\t\t| [key: Key | Key[], options?: ActualOptions]\n\t\t| [key: string | string[], options: TOpt & $Dictionary & { defaultValue: string }]\n\t\t| [key: string | string[], defaultValue: string, options?: TOpt & $Dictionary]\n): Promise<TFunctionReturnOptionalDetails<Ret, TOpt>> {\n\tconst parsedOptions = typeof defaultValueOrOptions === 'string' ? optionsOrUndefined : defaultValueOrOptions;\n\tconst language = typeof parsedOptions?.lng === 'string' ? parsedOptions.lng : await fetchLanguage(target);\n\n\tif (typeof defaultValueOrOptions === 'string') {\n\t\treturn container.i18n.format<Key, TOpt, Ns, Ret, ActualOptions>(language, key, defaultValueOrOptions, optionsOrUndefined);\n\t}\n\n\treturn container.i18n.format<Key, TOpt, Ns, Ret, ActualOptions>(language, key, undefined, defaultValueOrOptions);\n}\n\n/**\n * @internal\n */\nasync function resolveLanguage(context: InternationalizationContext): Promise<string> {\n\tconst lang = await container.i18n.fetchLanguage(context);\n\treturn lang ?? context.guild?.preferredLocale ?? container.i18n.options.defaultName ?? 'en-US';\n}\n\nconst supportedLanguages = new Set(Object.values(Locale)) as ReadonlySet<LocaleString>;\n\nfunction isSupportedDiscordLocale(language: string): language is LocaleString {\n\treturn supportedLanguages.has(language as LocaleString);\n}\n\nconst getLocales = lazy(() => {\n\tconst locales = new Map(container.i18n.languages);\n\n\tfor (const [locale] of locales) {\n\t\tif (!isSupportedDiscordLocale(locale)) {\n\t\t\tprocess.emitWarning('Unsupported Discord locale', {\n\t\t\t\tcode: 'UNSUPPORTED_LOCALE',\n\t\t\t\tdetail: `'${locale}' needs to be one of: ${[...locales.keys()]}`\n\t\t\t});\n\n\t\t\tlocales.delete(locale);\n\t\t}\n\n\t\tcontinue;\n\t}\n\n\treturn locales;\n});\n\nconst getDefaultT = lazy(() => {\n\tconst defaultLocale = container.i18n.options.defaultName ?? 'en-US';\n\n\tif (!isSupportedDiscordLocale(defaultLocale)) {\n\t\tthrow new TypeError(`Unsupported Discord locale found:\\n'${defaultLocale}' is not within the list of ${[...supportedLanguages]}`);\n\t}\n\n\tconst defaultT = getLocales().get(defaultLocale);\n\n\tif (defaultT) {\n\t\treturn defaultT;\n\t}\n\n\tthrow new TypeError(`Could not find ${defaultLocale}`);\n});\n\n/**\n * Gets the value and the localizations from a language key.\n * @param key The key to get the localizations from.\n * @returns The retrieved data.\n * @remarks This should be called **strictly** after loading the locales.\n */\nexport function getLocalizedData<const TOpt extends TOptions = TOptions, Ns extends Namespace = DefaultNamespace, KPrefix = undefined>(\n\tkey: ParseKeys<Ns, TOpt, KPrefix>\n): LocalizedData {\n\tconst locales = getLocales();\n\tconst defaultT = getDefaultT();\n\n\treturn {\n\t\tvalue: defaultT(key),\n\t\tlocalizations: Object.fromEntries(Array.from(locales, ([locale, t]) => [locale, t(key)]))\n\t};\n}\n\n/**\n * Applies the localized names on the builder, calling `setName` and `setNameLocalizations`.\n * @param builder The builder to apply the localizations to.\n * @param key The key to get the localizations from.\n * @returns The updated builder.\n */\nexport function applyNameLocalizedBuilder<\n\tT extends BuilderWithName,\n\tconst TOpt extends TOptions = TOptions,\n\tNs extends Namespace = DefaultNamespace,\n\tKPrefix = undefined\n>(builder: T, key: ParseKeys<Ns, TOpt, KPrefix>) {\n\tconst result = getLocalizedData(key);\n\treturn builder.setName(result.value).setNameLocalizations(result.localizations);\n}\n\n/**\n * Applies the localized descriptions on the builder, calling `setDescription` and `setDescriptionLocalizations`.\n * @param builder The builder to apply the localizations to.\n * @param key The key to get the localizations from.\n * @returns The updated builder.\n */\nexport function applyDescriptionLocalizedBuilder<\n\tT extends BuilderWithDescription,\n\tconst TOpt extends TOptions = TOptions,\n\tNs extends Namespace = DefaultNamespace,\n\tKPrefix = undefined\n>(builder: T, key: ParseKeys<Ns, TOpt, KPrefix>) {\n\tconst result = getLocalizedData(key);\n\treturn builder.setDescription(result.value).setDescriptionLocalizations(result.localizations);\n}\n\n/**\n * Applies the localized names and descriptions on the builder, calling {@link applyNameLocalizedBuilder} and\n * {@link applyDescriptionLocalizedBuilder}.\n *\n * @param builder The builder to apply the localizations to.\n *\n * @param params The root key or the key for the name and description keys.\n * This needs to be either 1 or 2 parameters.\n * See examples below for more information.\n *\n * @returns The updated builder. You can chain subsequent builder methods on this.\n *\n * @remarks If only 2 parameters were passed, then this function will automatically append `Name` and `Description`\n * to the root-key (wherein `root-key` is second parameter in the function, after `builder`)\n * passed through the second parameter.\n *\n * For example given `applyLocalizedBuilder(builder, 'userinfo')` the localized options will use the i18next keys\n * `userinfoName` and `userinfoDescription`.\n *\n * In the following example we provide all parameters and add a User Option\n * `applyLocalizedBuilder` needs either\n * @example\n * ```typescript\n * class UserInfoCommand extends Command {\n * public registerApplicationCommands(registry: ChatInputCommand.Registry) {\n * registry.registerChatInputCommand(\n * (builder) =>\n * applyLocalizedBuilder(builder, 'commands/names:userinfo', 'commands/descriptions:userinfo')\n * .addUserOption(\n * (input) => applyLocalizedBuilder(input, 'commands/options:userinfo-name', 'commands/options:userinfo-description').setRequired(true)\n * )\n * );\n * }\n * }\n * ```\n *\n * In the following example we provide single root keys which means `Name` and `Description` get appended as mentioned above.\n * @example\n * ```typescript\n * class UserInfoCommand extends Command {\n * public registerApplicationCommands(registry: ChatInputCommand.Registry) {\n * registry.registerChatInputCommand(\n * (builder) =>\n * applyLocalizedBuilder(builder, 'commands:userinfo')\n * .addUserOption(\n * (input) => applyLocalizedBuilder(input, 'options:userinfo').setRequired(true)\n * )\n * );\n * }\n * }\n * ```\n */\nexport function applyLocalizedBuilder<\n\tT extends BuilderWithNameAndDescription,\n\tconst TOpt extends TOptions = TOptions,\n\tNs extends Namespace = DefaultNamespace,\n\tKPrefix = undefined\n>(builder: T, ...params: [root: string] | [name: ParseKeys<Ns, TOpt, KPrefix>, description: ParseKeys<Ns, TOpt, KPrefix>]): T {\n\ttype LocalKeysType = ParseKeys<Ns, TOpt, KPrefix>;\n\n\tconst [localeName, localeDescription] =\n\t\tparams.length === 1 ? [`${params[0]}Name` as LocalKeysType, `${params[0]}Description` as LocalKeysType] : params;\n\n\tapplyNameLocalizedBuilder(builder, localeName);\n\tapplyDescriptionLocalizedBuilder(builder, localeDescription);\n\n\treturn builder;\n}\n\n/**\n * Constructs an object that can be passed into `setChoices` for String or Number option with localized names.\n *\n * @param key The i18next key for the name of the select option name.\n * @param options The additional Select Menu options. This should _at least_ include the `value` key.\n * @returns An object with anything provided through {@link createLocalizedChoice.options} with `name` and `name_localizations` added.\n *\n * @example\n * ```typescript\n * export class TypeCommand extends Command {\n * public override registerApplicationCommands(registry: ChatInputCommand.Registry) {\n * registry.registerChatInputCommand((builder) =>\n * applyLocalizedBuilder(builder, 'commands/names:type').addStringOption((option) =>\n * applyLocalizedBuilder(option, 'commands/options:type')\n * .setRequired(true)\n * .setChoices(\n * createLocalizedChoice('selects/pokemon:type-grass', { value: 'grass' }),\n * createLocalizedChoice('selects/pokemon:type-water', { value: 'water' }),\n * createLocalizedChoice('selects/pokemon:type-fire', { value: 'fire' }),\n * createLocalizedChoice('selects/pokemon:type-electric', { value: 'electric' })\n * )\n * )\n * );\n * }\n * }\n * ```\n */\nexport function createLocalizedChoice<\n\tValueType = string | number,\n\tconst TOpt extends TOptions = TOptions,\n\tNs extends Namespace = DefaultNamespace,\n\tKPrefix = undefined\n>(\n\tkey: ParseKeys<Ns, TOpt, KPrefix>,\n\toptions: Omit<APIApplicationCommandOptionChoice<ValueType>, 'name' | 'name_localizations'>\n): APIApplicationCommandOptionChoice<ValueType> {\n\tconst result = getLocalizedData(key);\n\n\treturn {\n\t\t...options,\n\t\tname: result.value,\n\t\tname_localizations: result.localizations\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/functions.ts"],"names":[],"mappings":";;;;;AAoCO,SAAS,cAAc,MAAiC,EAAA;AAE9D,EAAA,IAAI,kBAAkB,eAAiB,EAAA;AACtC,IAAA,OAAO,eAAgB,CAAA;AAAA,MACtB,MAAM,MAAO,CAAA,IAAA;AAAA,MACb,SAAS,MAAO,CAAA,OAAA;AAAA,MAChB,OAAO,MAAO,CAAA,KAAA;AAAA,MACd,wBAAwB,MAAO,CAAA,WAAA;AAAA,MAC/B,mBAAmB,MAAO,CAAA;AAAA,KAC1B,CAAA;AAAA;AAIF,EAAA,IAAI,kBAAkB,OAAS,EAAA;AAC9B,IAAO,OAAA,eAAA,CAAgB,EAAE,IAAA,EAAM,MAAO,CAAA,MAAA,EAAQ,OAAS,EAAA,MAAA,CAAO,OAAS,EAAA,KAAA,EAAO,MAAO,CAAA,KAAA,EAAO,CAAA;AAAA;AAI7F,EAAA,IAAI,kBAAkB,KAAO,EAAA;AAC5B,IAAO,OAAA,eAAA,CAAgB,EAAE,IAAM,EAAA,IAAA,EAAM,SAAS,IAAM,EAAA,KAAA,EAAO,QAAQ,CAAA;AAAA;AAIpE,EAAA,IAAI,OAAO,IAAS,KAAA,WAAA,CAAY,MAAM,MAAO,CAAA,IAAA,KAAS,YAAY,OAAS,EAAA;AAC1E,IAAO,OAAA,eAAA,CAAgB,EAAE,IAAM,EAAA,IAAA,EAAM,SAAS,MAAQ,EAAA,KAAA,EAAO,MAAM,CAAA;AAAA;AAIpE,EAAO,OAAA,eAAA,CAAgB,EAAE,IAAM,EAAA,IAAA,EAAM,SAAS,MAAQ,EAAA,KAAA,EAAO,MAAO,CAAA,KAAA,EAAO,CAAA;AAC5E;AA7BgB,MAAA,CAAA,aAAA,EAAA,eAAA,CA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AAC/C,EAAM,MAAA,MAAA,GAAS,iBAAiB,GAAG,CAAA;AAEnC,EAAO,OAAA;AAAA,IACN,GAAG,OAAA;AAAA,IACH,MAAM,MAAO,CAAA,KAAA;AAAA,IACb,oBAAoB,MAAO,CAAA;AAAA,GAC5B;AACD;AAhBgB,MAAA,CAAA,qBAAA,EAAA,uBAAA,CAAA","file":"functions.mjs","sourcesContent":["import { container } from '@sapphire/pieces';\nimport { lazy } from '@sapphire/utilities';\nimport { BaseInteraction, ChannelType, Guild, Locale, Message, type APIApplicationCommandOptionChoice, type LocaleString } from 'discord.js';\nimport type {\n\tAppendKeyPrefix,\n\tDefaultNamespace,\n\tInterpolationMap,\n\tNamespace,\n\tParseKeys,\n\tTFunctionReturn,\n\tTFunctionReturnOptionalDetails,\n\tTOptions\n} from 'i18next';\nimport type {\n\t$Dictionary,\n\t$SpecialObject,\n\tBuilderWithDescription,\n\tBuilderWithName,\n\tBuilderWithNameAndDescription,\n\tInternationalizationContext,\n\tLocalizedData,\n\tTarget\n} from './types';\n\n/**\n * Retrieves the language name for a specific target, using {@link InternationalizationHandler.fetchLanguage}.\n * If {@link InternationalizationHandler.fetchLanguage} is not defined or this function returns a nullish value,\n * then there will be a series of fallback attempts in the following descending order:\n * 1. Returns {@link Guild.preferredLocale}.\n * 2. Returns {@link InternationalizationOptions.defaultName} if no guild was provided.\n * 3. Returns `'en-US'` if nothing else was found.\n * @since 2.0.0\n * @param target The target to fetch the language from.\n * @see {@link resolveLanguage}\n * @returns The name of the language key.\n */\nexport function fetchLanguage(target: Target): Promise<string> {\n\t// Handle Interactions:\n\tif (target instanceof BaseInteraction) {\n\t\treturn resolveLanguage({\n\t\t\tuser: target.user,\n\t\t\tchannel: target.channel,\n\t\t\tguild: target.guild,\n\t\t\tinteractionGuildLocale: target.guildLocale,\n\t\t\tinteractionLocale: target.locale\n\t\t});\n\t}\n\n\t// Handle Message:\n\tif (target instanceof Message) {\n\t\treturn resolveLanguage({ user: target.author, channel: target.channel, guild: target.guild });\n\t}\n\n\t// Handle Guild:\n\tif (target instanceof Guild) {\n\t\treturn resolveLanguage({ user: null, channel: null, guild: target });\n\t}\n\n\t// Handle DMChannel and GroupDMChannel:\n\tif (target.type === ChannelType.DM || target.type === ChannelType.GroupDM) {\n\t\treturn resolveLanguage({ user: null, channel: target, guild: null });\n\t}\n\n\t// Handle any other channel:\n\treturn resolveLanguage({ user: null, channel: target, guild: target.guild });\n}\n\n/**\n * Retrieves the language-assigned function from i18next designated to a target's preferred language code.\n * @since 2.0.0\n * @param target The target to fetch the language from.\n * @returns The language function from i18next.\n */\nexport async function fetchT(target: Target) {\n\treturn container.i18n.getT(await fetchLanguage(target));\n}\n\n/**\n * Resolves a key and its parameters.\n * @since 2.0.0\n * @param target The target to fetch the language key from.\n * @param key The i18next key.\n * @param options The options to be passed to TFunction.\n * @returns The data that `key` held, processed by i18next.\n */\nexport async function resolveKey<\n\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\tconst TOpt extends TOptions = TOptions,\n\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\tNs extends Namespace = DefaultNamespace,\n\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n>(target: Target, key: Key | Key[], options?: ActualOptions): Promise<TFunctionReturnOptionalDetails<Ret, TOpt>>;\n\n/**\n * Resolves a key and its parameters.\n * @since 2.0.0\n * @param target The target to fetch the language key from.\n * @param key The i18next key.\n * @param options The interpolation options as well as a `defaultValue` for the key and any key/value pairs.\n * @returns The data that `key` held, processed by i18next.\n */\nexport async function resolveKey<\n\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\tconst TOpt extends TOptions = TOptions,\n\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\tNs extends Namespace = DefaultNamespace,\n\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n>(target: Target, key: string | string[], options: TOpt & $Dictionary & { defaultValue: string }): Promise<TFunctionReturnOptionalDetails<Ret, TOpt>>;\n\n/**\n * Resolves a key and its parameters.\n * @since 2.0.0\n * @param target The target to fetch the language key from.\n * @param key The i18next key.\n * @param defaultValue The default value to use if the key is not found.\n * @param options The interpolation options.\n * @returns The data that `key` held, processed by i18next.\n */\nexport async function resolveKey<\n\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\tconst TOpt extends TOptions = TOptions,\n\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\tNs extends Namespace = DefaultNamespace,\n\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n>(target: Target, key: string | string[], defaultValue: string, options?: TOpt & $Dictionary): Promise<TFunctionReturnOptionalDetails<Ret, TOpt>>;\n\n/**\n * Resolves a key and its parameters.\n * @since 2.0.0\n * @param target The target to fetch the language key from.\n *\n * @remark This function also has additional parameters for `key`, `defaultValue`, and `options`, however\n * TSDoc does not let us document those while matching proper implementation. See the overloads for this method\n * for the documentation on those parameters.\n *\n * @returns The data that `key` held, processed by i18next.\n */\nexport async function resolveKey<\n\tconst Key extends ParseKeys<Ns, TOpt, undefined>,\n\tconst TOpt extends TOptions = TOptions,\n\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt> = TOpt['returnObjects'] extends true ? $SpecialObject : string,\n\tNs extends Namespace = DefaultNamespace,\n\tconst ActualOptions extends TOpt & InterpolationMap<Ret> = TOpt & InterpolationMap<Ret>\n>(\n\ttarget: Target,\n\t...[key, defaultValueOrOptions, optionsOrUndefined]:\n\t\t| [key: Key | Key[], options?: ActualOptions]\n\t\t| [key: string | string[], options: TOpt & $Dictionary & { defaultValue: string }]\n\t\t| [key: string | string[], defaultValue: string, options?: TOpt & $Dictionary]\n): Promise<TFunctionReturnOptionalDetails<Ret, TOpt>> {\n\tconst parsedOptions = typeof defaultValueOrOptions === 'string' ? optionsOrUndefined : defaultValueOrOptions;\n\tconst language = typeof parsedOptions?.lng === 'string' ? parsedOptions.lng : await fetchLanguage(target);\n\n\tif (typeof defaultValueOrOptions === 'string') {\n\t\treturn container.i18n.format<Key, TOpt, Ns, Ret, ActualOptions>(language, key, defaultValueOrOptions, optionsOrUndefined);\n\t}\n\n\treturn container.i18n.format<Key, TOpt, Ns, Ret, ActualOptions>(language, key, undefined, defaultValueOrOptions);\n}\n\n/**\n * @internal\n */\nasync function resolveLanguage(context: InternationalizationContext): Promise<string> {\n\tconst lang = await container.i18n.fetchLanguage(context);\n\treturn lang ?? context.guild?.preferredLocale ?? container.i18n.options.defaultName ?? 'en-US';\n}\n\nconst supportedLanguages = new Set(Object.values(Locale)) as ReadonlySet<LocaleString>;\n\nfunction isSupportedDiscordLocale(language: string): language is LocaleString {\n\treturn supportedLanguages.has(language as LocaleString);\n}\n\nconst getLocales = lazy(() => {\n\tconst locales = new Map(container.i18n.languages);\n\n\tfor (const [locale] of locales) {\n\t\tif (!isSupportedDiscordLocale(locale)) {\n\t\t\tprocess.emitWarning('Unsupported Discord locale', {\n\t\t\t\tcode: 'UNSUPPORTED_LOCALE',\n\t\t\t\tdetail: `'${locale}' needs to be one of: ${[...locales.keys()]}`\n\t\t\t});\n\n\t\t\tlocales.delete(locale);\n\t\t}\n\n\t\tcontinue;\n\t}\n\n\treturn locales;\n});\n\nconst getDefaultT = lazy(() => {\n\tconst defaultLocale = container.i18n.options.defaultName ?? 'en-US';\n\n\tif (!isSupportedDiscordLocale(defaultLocale)) {\n\t\tthrow new TypeError(`Unsupported Discord locale found:\\n'${defaultLocale}' is not within the list of ${[...supportedLanguages]}`);\n\t}\n\n\tconst defaultT = getLocales().get(defaultLocale);\n\n\tif (defaultT) {\n\t\treturn defaultT;\n\t}\n\n\tthrow new TypeError(`Could not find ${defaultLocale}`);\n});\n\n/**\n * Gets the value and the localizations from a language key.\n * @param key The key to get the localizations from.\n * @returns The retrieved data.\n * @remarks This should be called **strictly** after loading the locales.\n */\nexport function getLocalizedData<const TOpt extends TOptions = TOptions, Ns extends Namespace = DefaultNamespace, KPrefix = undefined>(\n\tkey: ParseKeys<Ns, TOpt, KPrefix>\n): LocalizedData {\n\tconst locales = getLocales();\n\tconst defaultT = getDefaultT();\n\n\treturn {\n\t\tvalue: defaultT(key),\n\t\tlocalizations: Object.fromEntries(Array.from(locales, ([locale, t]) => [locale, t(key)]))\n\t};\n}\n\n/**\n * Applies the localized names on the builder, calling `setName` and `setNameLocalizations`.\n * @param builder The builder to apply the localizations to.\n * @param key The key to get the localizations from.\n * @returns The updated builder.\n */\nexport function applyNameLocalizedBuilder<\n\tT extends BuilderWithName,\n\tconst TOpt extends TOptions = TOptions,\n\tNs extends Namespace = DefaultNamespace,\n\tKPrefix = undefined\n>(builder: T, key: ParseKeys<Ns, TOpt, KPrefix>) {\n\tconst result = getLocalizedData(key);\n\treturn builder.setName(result.value).setNameLocalizations(result.localizations);\n}\n\n/**\n * Applies the localized descriptions on the builder, calling `setDescription` and `setDescriptionLocalizations`.\n * @param builder The builder to apply the localizations to.\n * @param key The key to get the localizations from.\n * @returns The updated builder.\n */\nexport function applyDescriptionLocalizedBuilder<\n\tT extends BuilderWithDescription,\n\tconst TOpt extends TOptions = TOptions,\n\tNs extends Namespace = DefaultNamespace,\n\tKPrefix = undefined\n>(builder: T, key: ParseKeys<Ns, TOpt, KPrefix>) {\n\tconst result = getLocalizedData(key);\n\treturn builder.setDescription(result.value).setDescriptionLocalizations(result.localizations);\n}\n\n/**\n * Applies the localized names and descriptions on the builder, calling {@link applyNameLocalizedBuilder} and\n * {@link applyDescriptionLocalizedBuilder}.\n *\n * @param builder The builder to apply the localizations to.\n *\n * @param params The root key or the key for the name and description keys.\n * This needs to be either 1 or 2 parameters.\n * See examples below for more information.\n *\n * @returns The updated builder. You can chain subsequent builder methods on this.\n *\n * @remarks If only 2 parameters were passed, then this function will automatically append `Name` and `Description`\n * to the root-key (wherein `root-key` is second parameter in the function, after `builder`)\n * passed through the second parameter.\n *\n * For example given `applyLocalizedBuilder(builder, 'userinfo')` the localized options will use the i18next keys\n * `userinfoName` and `userinfoDescription`.\n *\n * In the following example we provide all parameters and add a User Option\n * `applyLocalizedBuilder` needs either\n * @example\n * ```typescript\n * class UserInfoCommand extends Command {\n * public registerApplicationCommands(registry: ChatInputCommand.Registry) {\n * registry.registerChatInputCommand(\n * (builder) =>\n * applyLocalizedBuilder(builder, 'commands/names:userinfo', 'commands/descriptions:userinfo')\n * .addUserOption(\n * (input) => applyLocalizedBuilder(input, 'commands/options:userinfo-name', 'commands/options:userinfo-description').setRequired(true)\n * )\n * );\n * }\n * }\n * ```\n *\n * In the following example we provide single root keys which means `Name` and `Description` get appended as mentioned above.\n * @example\n * ```typescript\n * class UserInfoCommand extends Command {\n * public registerApplicationCommands(registry: ChatInputCommand.Registry) {\n * registry.registerChatInputCommand(\n * (builder) =>\n * applyLocalizedBuilder(builder, 'commands:userinfo')\n * .addUserOption(\n * (input) => applyLocalizedBuilder(input, 'options:userinfo').setRequired(true)\n * )\n * );\n * }\n * }\n * ```\n */\nexport function applyLocalizedBuilder<\n\tT extends BuilderWithNameAndDescription,\n\tconst TOpt extends TOptions = TOptions,\n\tNs extends Namespace = DefaultNamespace,\n\tKPrefix = undefined\n>(builder: T, ...params: [root: string] | [name: ParseKeys<Ns, TOpt, KPrefix>, description: ParseKeys<Ns, TOpt, KPrefix>]): T {\n\ttype LocalKeysType = ParseKeys<Ns, TOpt, KPrefix>;\n\n\tconst [localeName, localeDescription] =\n\t\tparams.length === 1 ? [`${params[0]}Name` as LocalKeysType, `${params[0]}Description` as LocalKeysType] : params;\n\n\tapplyNameLocalizedBuilder(builder, localeName);\n\tapplyDescriptionLocalizedBuilder(builder, localeDescription);\n\n\treturn builder;\n}\n\n/**\n * Constructs an object that can be passed into `setChoices` for String or Number option with localized names.\n *\n * @param key The i18next key for the name of the select option name.\n * @param options The additional Select Menu options. This should _at least_ include the `value` key.\n * @returns An object with anything provided through {@link createLocalizedChoice.options} with `name` and `name_localizations` added.\n *\n * @example\n * ```typescript\n * export class TypeCommand extends Command {\n * public override registerApplicationCommands(registry: ChatInputCommand.Registry) {\n * registry.registerChatInputCommand((builder) =>\n * applyLocalizedBuilder(builder, 'commands/names:type').addStringOption((option) =>\n * applyLocalizedBuilder(option, 'commands/options:type')\n * .setRequired(true)\n * .setChoices(\n * createLocalizedChoice('selects/pokemon:type-grass', { value: 'grass' }),\n * createLocalizedChoice('selects/pokemon:type-water', { value: 'water' }),\n * createLocalizedChoice('selects/pokemon:type-fire', { value: 'fire' }),\n * createLocalizedChoice('selects/pokemon:type-electric', { value: 'electric' })\n * )\n * )\n * );\n * }\n * }\n * ```\n */\nexport function createLocalizedChoice<\n\tValueType = string | number,\n\tconst TOpt extends TOptions = TOptions,\n\tNs extends Namespace = DefaultNamespace,\n\tKPrefix = undefined\n>(\n\tkey: ParseKeys<Ns, TOpt, KPrefix>,\n\toptions: Omit<APIApplicationCommandOptionChoice<ValueType>, 'name' | 'name_localizations'>\n): APIApplicationCommandOptionChoice<ValueType> {\n\tconst result = getLocalizedData(key);\n\n\treturn {\n\t\t...options,\n\t\tname: result.value,\n\t\tname_localizations: result.localizations\n\t};\n}\n"]}
|
package/dist/esm/lib/types.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"types.mjs"}
|
package/dist/esm/register.mjs
CHANGED
|
@@ -13,8 +13,7 @@ var _I18nextPlugin = class _I18nextPlugin extends Plugin {
|
|
|
13
13
|
static [postLogin]() {
|
|
14
14
|
if (this.options.i18n?.hmr?.enabled) {
|
|
15
15
|
container.logger.info("[i18next-Plugin]: HMR enabled. Watching for languages changes.");
|
|
16
|
-
|
|
17
|
-
for (const event of ["change", "unlink"]) hmr.on(event, () => container.i18n.reloadResources());
|
|
16
|
+
watch(container.i18n.languagesDirectory, this.options.i18n.hmr.options ?? {}).on("change", () => container.i18n.reloadResources()).on("unlink", () => container.i18n.reloadResources());
|
|
18
17
|
}
|
|
19
18
|
}
|
|
20
19
|
};
|
|
@@ -25,5 +24,5 @@ SapphireClient.plugins.registerPreLoginHook(I18nextPlugin[preLogin], "I18next-Pr
|
|
|
25
24
|
SapphireClient.plugins.registerPostLoginHook(I18nextPlugin[postLogin], "I18next-PostLogin");
|
|
26
25
|
|
|
27
26
|
export { I18nextPlugin };
|
|
28
|
-
//# sourceMappingURL=
|
|
27
|
+
//# sourceMappingURL=register.mjs.map
|
|
29
28
|
//# sourceMappingURL=register.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/register.ts"],"names":[],"mappings":";;;;;
|
|
1
|
+
{"version":3,"sources":["../../src/register.ts"],"names":[],"mappings":";;;;;AAOO,IAAM,cAAA,GAAN,MAAM,cAAA,SAAsB,MAAO,CAAA;AAAA,EACzC,QAAe,yBAAyB,CAAA,CAAwB,OAA8B,EAAA;AAC7F,IAAA,SAAA,CAAU,IAAO,GAAA,IAAI,2BAA4B,CAAA,OAAA,CAAQ,IAAI,CAAA;AAAA;AAC9D,EAEA,cAAqB,QAAQ,CAAuC,GAAA;AACnE,IAAM,MAAA,SAAA,CAAU,KAAK,IAAK,EAAA;AAAA;AAC3B,EAEA,QAAe,SAAS,CAA8B,GAAA;AACrD,IAAA,IAAI,IAAK,CAAA,OAAA,CAAQ,IAAM,EAAA,GAAA,EAAK,OAAS,EAAA;AACpC,MAAU,SAAA,CAAA,MAAA,CAAO,KAAK,gEAAgE,CAAA;AAEtF,MAAM,KAAA,CAAA,SAAA,CAAU,IAAK,CAAA,kBAAA,EAAoB,IAAK,CAAA,OAAA,CAAQ,KAAK,GAAI,CAAA,OAAA,IAAW,EAAE,CAC1E,CAAA,EAAA,CAAG,UAAU,MAAM,SAAA,CAAU,IAAK,CAAA,eAAA,EAAiB,CAAA,CACnD,EAAG,CAAA,QAAA,EAAU,MAAM,SAAA,CAAU,IAAK,CAAA,eAAA,EAAiB,CAAA;AAAA;AACtD;AAEF,CAAA;AAlB0C,MAAA,CAAA,cAAA,EAAA,eAAA,CAAA;AAAnC,IAAM,aAAN,GAAA;AAoBP,cAAA,CAAe,OAAQ,CAAA,8BAAA,CAA+B,aAAc,CAAA,yBAAyB,GAAG,mCAAmC,CAAA;AACnI,cAAA,CAAe,OAAQ,CAAA,oBAAA,CAAqB,aAAc,CAAA,QAAQ,GAAG,kBAAkB,CAAA;AACvF,cAAA,CAAe,OAAQ,CAAA,qBAAA,CAAsB,aAAc,CAAA,SAAS,GAAG,mBAAmB,CAAA","file":"register.mjs","sourcesContent":["import './index';\n\nimport { Plugin, SapphireClient, container, postLogin, preGenericsInitialization, preLogin } from '@sapphire/framework';\nimport { watch } from 'chokidar';\nimport type { ClientOptions } from 'discord.js';\nimport { InternationalizationHandler } from './index';\n\nexport class I18nextPlugin extends Plugin {\n\tpublic static [preGenericsInitialization](this: SapphireClient, options: ClientOptions): void {\n\t\tcontainer.i18n = new InternationalizationHandler(options.i18n);\n\t}\n\n\tpublic static async [preLogin](this: SapphireClient): Promise<void> {\n\t\tawait container.i18n.init();\n\t}\n\n\tpublic static [postLogin](this: SapphireClient): void {\n\t\tif (this.options.i18n?.hmr?.enabled) {\n\t\t\tcontainer.logger.info('[i18next-Plugin]: HMR enabled. Watching for languages changes.');\n\n\t\t\twatch(container.i18n.languagesDirectory, this.options.i18n.hmr.options ?? {})\n\t\t\t\t.on('change', () => container.i18n.reloadResources())\n\t\t\t\t.on('unlink', () => container.i18n.reloadResources());\n\t\t}\n\t}\n}\n\nSapphireClient.plugins.registerPostInitializationHook(I18nextPlugin[preGenericsInitialization], 'I18next-PreGenericsInitialization');\nSapphireClient.plugins.registerPreLoginHook(I18nextPlugin[preLogin], 'I18next-PreLogin');\nSapphireClient.plugins.registerPostLoginHook(I18nextPlugin[postLogin], 'I18next-PostLogin');\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sapphire/plugin-i18next",
|
|
3
|
-
"version": "7.1.3
|
|
3
|
+
"version": "7.1.3",
|
|
4
4
|
"description": "Plugin for @sapphire/framework to support i18next.",
|
|
5
5
|
"author": "@sapphire",
|
|
6
6
|
"license": "MIT",
|
|
@@ -50,10 +50,10 @@
|
|
|
50
50
|
"check-update": "cliff-jumper --dry-run"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@sapphire/utilities": "^3.
|
|
53
|
+
"@sapphire/utilities": "^3.18.0",
|
|
54
54
|
"@skyra/i18next-backend": "^2.0.5",
|
|
55
|
-
"chokidar": "^
|
|
56
|
-
"i18next": "^23.
|
|
55
|
+
"chokidar": "^4.0.1",
|
|
56
|
+
"i18next": "^23.16.4"
|
|
57
57
|
},
|
|
58
58
|
"repository": {
|
|
59
59
|
"type": "git",
|
|
@@ -86,13 +86,13 @@
|
|
|
86
86
|
"access": "public"
|
|
87
87
|
},
|
|
88
88
|
"devDependencies": {
|
|
89
|
-
"@favware/cliff-jumper": "^
|
|
89
|
+
"@favware/cliff-jumper": "^5.0.0",
|
|
90
90
|
"@favware/rollup-type-bundler": "^3.3.0",
|
|
91
|
-
"concurrently": "^
|
|
92
|
-
"tsup": "^8.
|
|
93
|
-
"tsx": "^4.
|
|
94
|
-
"typedoc": "^0.
|
|
95
|
-
"typedoc-json-parser": "^10.
|
|
91
|
+
"concurrently": "^9.0.1",
|
|
92
|
+
"tsup": "^8.3.5",
|
|
93
|
+
"tsx": "^4.19.2",
|
|
94
|
+
"typedoc": "^0.26.11",
|
|
95
|
+
"typedoc-json-parser": "^10.2.0",
|
|
96
96
|
"typescript": "~5.4.5"
|
|
97
97
|
}
|
|
98
98
|
}
|