@sapphire/plugin-i18next 6.1.1-next.eccc557.0 → 7.0.0-next.1f2cccc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/cjs/index.cjs +39 -0
  2. package/dist/cjs/index.cjs.map +1 -0
  3. package/dist/cjs/index.d.ts +428 -0
  4. package/dist/cjs/lib/Augmentations.d.cjs +4 -0
  5. package/dist/cjs/lib/Augmentations.d.cjs.map +1 -0
  6. package/dist/cjs/lib/InternationalizationHandler.cjs +236 -0
  7. package/dist/cjs/lib/InternationalizationHandler.cjs.map +1 -0
  8. package/dist/cjs/lib/functions.cjs +125 -0
  9. package/dist/cjs/lib/functions.cjs.map +1 -0
  10. package/dist/cjs/lib/types.cjs +4 -0
  11. package/dist/cjs/lib/types.cjs.map +1 -0
  12. package/dist/cjs/register.cjs +33 -0
  13. package/dist/cjs/register.cjs.map +1 -0
  14. package/dist/cjs/register.d.ts +10 -0
  15. package/dist/esm/chunk-6QB3UK4Q.mjs +11 -0
  16. package/dist/esm/chunk-6QB3UK4Q.mjs.map +1 -0
  17. package/dist/esm/index.d.mts +428 -0
  18. package/dist/esm/index.mjs +11 -0
  19. package/dist/esm/index.mjs.map +1 -0
  20. package/dist/esm/lib/Augmentations.d.mjs +3 -0
  21. package/dist/esm/lib/Augmentations.d.mjs.map +1 -0
  22. package/dist/esm/lib/InternationalizationHandler.mjs +224 -0
  23. package/dist/esm/lib/InternationalizationHandler.mjs.map +1 -0
  24. package/dist/esm/lib/functions.mjs +115 -0
  25. package/dist/esm/lib/functions.mjs.map +1 -0
  26. package/dist/esm/lib/types.mjs +3 -0
  27. package/dist/esm/lib/types.mjs.map +1 -0
  28. package/dist/esm/register.d.mts +10 -0
  29. package/dist/esm/register.mjs +30 -0
  30. package/dist/esm/register.mjs.map +1 -0
  31. package/package.json +37 -22
  32. package/dist/index.d.ts +0 -16
  33. package/dist/index.d.ts.map +0 -1
  34. package/dist/index.js +0 -26
  35. package/dist/index.js.map +0 -1
  36. package/dist/index.mjs +0 -13
  37. package/dist/lib/InternationalizationHandler.d.ts +0 -127
  38. package/dist/lib/InternationalizationHandler.d.ts.map +0 -1
  39. package/dist/lib/InternationalizationHandler.js +0 -271
  40. package/dist/lib/InternationalizationHandler.js.map +0 -1
  41. package/dist/lib/functions.d.ts +0 -137
  42. package/dist/lib/functions.d.ts.map +0 -1
  43. package/dist/lib/functions.js +0 -241
  44. package/dist/lib/functions.js.map +0 -1
  45. package/dist/lib/types.d.ts +0 -151
  46. package/dist/lib/types.d.ts.map +0 -1
  47. package/dist/lib/types.js +0 -3
  48. package/dist/lib/types.js.map +0 -1
  49. package/dist/register.d.ts +0 -9
  50. package/dist/register.d.ts.map +0 -1
  51. package/dist/register.js +0 -28
  52. package/dist/register.js.map +0 -1
  53. package/dist/register.mjs +0 -4
@@ -0,0 +1,236 @@
1
+ 'use strict';
2
+
3
+ var framework = require('@sapphire/framework');
4
+ var pieces = require('@sapphire/pieces');
5
+ var utilities = require('@sapphire/utilities');
6
+ var i18nextBackend = require('@skyra/i18next-backend');
7
+ var i18next = require('i18next');
8
+ var promises = require('fs/promises');
9
+ var path = require('path');
10
+ var url = require('url');
11
+
12
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
+
14
+ var i18next__default = /*#__PURE__*/_interopDefault(i18next);
15
+
16
+ var __defProp = Object.defineProperty;
17
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
18
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
19
+ var __publicField = (obj, key, value) => {
20
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
21
+ return value;
22
+ };
23
+ var _InternationalizationHandler = class _InternationalizationHandler {
24
+ /**
25
+ * @param options The options that `i18next`, `@skyra/i18next-backend`, and {@link InternationalizationHandler} should use.
26
+ * @since 1.0.0
27
+ * @constructor
28
+ */
29
+ constructor(options) {
30
+ /**
31
+ * Describes whether {@link InternationalizationHandler.init} has been run and languages are loaded in {@link InternationalizationHandler.languages}.
32
+ * @since 1.0.0
33
+ */
34
+ __publicField(this, "languagesLoaded", false);
35
+ /**
36
+ * A `Set` of initially loaded namespaces.
37
+ * @since 1.2.0
38
+ */
39
+ __publicField(this, "namespaces", /* @__PURE__ */ new Set());
40
+ /**
41
+ * A `Map` of `i18next` language functions keyed by their language code.
42
+ * @since 1.0.0
43
+ */
44
+ __publicField(this, "languages", /* @__PURE__ */ new Map());
45
+ /**
46
+ * The options InternationalizationHandler was initialized with in the client.
47
+ * @since 1.0.0
48
+ */
49
+ __publicField(this, "options");
50
+ /**
51
+ * The director passed to `@skyra/i18next-backend`.
52
+ * Also used in {@link InternationalizationHandler.walkLanguageDirectory}.
53
+ * @since 1.2.0
54
+ */
55
+ __publicField(this, "languagesDirectory");
56
+ /**
57
+ * The backend options for `@skyra/i18next-backend` used by `i18next`.
58
+ * @since 1.0.0
59
+ */
60
+ __publicField(this, "backendOptions");
61
+ /**
62
+ * The method to be overridden by the developer.
63
+ *
64
+ * @note In the event that fetchLanguage is not defined or returns null / undefined, the defaulting from {@link fetchLanguage} will be used.
65
+ * @since 2.0.0
66
+ * @return A string for the desired language or null for no match.
67
+ * @see {@link fetchLanguage}
68
+ * @example
69
+ * ```typescript
70
+ * // Always use the same language (no per-guild configuration):
71
+ * container.i18n.fetchLanguage = () => 'en-US';
72
+ * ```
73
+ * @example
74
+ * ```typescript
75
+ * // Retrieving the language from an SQL database:
76
+ * container.i18n.fetchLanguage = async (context) => {
77
+ * const guild = await driver.getOne('SELECT language FROM public.guild WHERE id = $1', [context.guild.id]);
78
+ * return guild?.language ?? 'en-US';
79
+ * };
80
+ * ```
81
+ * @example
82
+ * ```typescript
83
+ * // Retrieving the language from an ORM:
84
+ * container.i18n.fetchLanguage = async (context) => {
85
+ * const guild = await driver.getRepository(GuildEntity).findOne({ id: context.guild.id });
86
+ * return guild?.language ?? 'en-US';
87
+ * };
88
+ * ```
89
+ * @example
90
+ * ```typescript
91
+ * // Retrieving the language on a per channel basis, e.g. per user or guild channel (ORM example but same principles apply):
92
+ * container.i18n.fetchLanguage = async (context) => {
93
+ * const channel = await driver.getRepository(ChannelEntity).findOne({ id: context.channel.id });
94
+ * return channel?.language ?? 'en-US';
95
+ * };
96
+ * ```
97
+ */
98
+ __publicField(this, "fetchLanguage", /* @__PURE__ */ __name(() => null, "fetchLanguage"));
99
+ this.options = options ?? { i18next: { ignoreJSONStructure: false } };
100
+ const baseUserDirectory = pieces.container.client?.options?.baseUserDirectory instanceof url.URL ? url.fileURLToPath(pieces.container.client?.options?.baseUserDirectory) : pieces.container.client?.options?.baseUserDirectory;
101
+ this.languagesDirectory = this.options.defaultLanguageDirectory ?? path.join(baseUserDirectory ?? pieces.getRootData().root, "languages");
102
+ const languagePaths = /* @__PURE__ */ new Set([
103
+ path.join(this.languagesDirectory, "{{lng}}", "{{ns}}.json"),
104
+ //
105
+ ...options?.backend?.paths ?? []
106
+ ]);
107
+ this.backendOptions = {
108
+ paths: [...languagePaths],
109
+ ...this.options.backend
110
+ };
111
+ if (utilities.isFunction(this.options.fetchLanguage)) {
112
+ this.fetchLanguage = this.options.fetchLanguage;
113
+ }
114
+ }
115
+ /**
116
+ * Initializes the handler by loading in the namespaces, passing the data to i18next, and filling in the {@link InternationalizationHandler#languages}.
117
+ * @since 1.0.0
118
+ */
119
+ async init() {
120
+ const { namespaces, languages } = await this.walkRootDirectory(this.languagesDirectory);
121
+ const userOptions = utilities.isFunction(this.options.i18next) ? this.options.i18next(namespaces, languages) : this.options.i18next;
122
+ const ignoreJSONStructure = userOptions?.ignoreJSONStructure ?? false;
123
+ const skipOnVariables = userOptions?.interpolation?.skipOnVariables ?? false;
124
+ i18next__default.default.use(i18nextBackend.Backend);
125
+ await i18next__default.default.init({
126
+ backend: this.backendOptions,
127
+ fallbackLng: this.options.defaultName ?? "en-US",
128
+ initImmediate: false,
129
+ interpolation: {
130
+ escapeValue: false,
131
+ ...userOptions?.interpolation,
132
+ skipOnVariables
133
+ },
134
+ load: "all",
135
+ defaultNS: "default",
136
+ ns: namespaces,
137
+ preload: languages,
138
+ ...userOptions,
139
+ ignoreJSONStructure
140
+ });
141
+ this.namespaces = new Set(namespaces);
142
+ for (const item of languages) {
143
+ this.languages.set(item, i18next__default.default.getFixedT(item));
144
+ }
145
+ this.languagesLoaded = true;
146
+ const formatters = this.options.formatters ?? [];
147
+ for (const { name, format } of formatters) {
148
+ i18next__default.default.services.formatter.add(name, format);
149
+ }
150
+ }
151
+ /**
152
+ * Retrieve a raw TFunction from the passed locale.
153
+ * @param locale The language to be used.
154
+ * @since 1.0.0
155
+ */
156
+ getT(locale) {
157
+ if (!this.languagesLoaded)
158
+ throw new Error("Cannot call this method until InternationalizationHandler#init has been called");
159
+ const t = this.languages.get(locale);
160
+ if (t)
161
+ return t;
162
+ throw new ReferenceError("Invalid language provided");
163
+ }
164
+ /**
165
+ * Localizes a content given one or more keys and i18next options.
166
+ * @since 2.0.0
167
+ * @param locale The language to be used.
168
+ * @param key The key or keys to retrieve the content from.
169
+ * @param options The interpolation options.
170
+ * @see {@link https://www.i18next.com/overview/api#t}
171
+ * @returns The localized content.
172
+ */
173
+ format(locale, ...[key, defaultValueOrOptions, optionsOrUndefined]) {
174
+ if (!this.languagesLoaded)
175
+ throw new Error("Cannot call this method until InternationalizationHandler#init has been called");
176
+ const language = this.languages.get(locale);
177
+ if (!language)
178
+ throw new ReferenceError("Invalid language provided");
179
+ const defaultValue = typeof defaultValueOrOptions === "string" ? defaultValueOrOptions : this.options.defaultMissingKey ? language(this.options.defaultMissingKey, { replace: { key } }) : "";
180
+ return language(key, defaultValue, optionsOrUndefined);
181
+ }
182
+ /**
183
+ * @param directory The directory that should be walked.
184
+ * @since 3.0.0
185
+ */
186
+ async walkRootDirectory(directory) {
187
+ const languages = /* @__PURE__ */ new Set();
188
+ const namespaces = /* @__PURE__ */ new Set();
189
+ const dir = await promises.opendir(directory);
190
+ for await (const entry of dir) {
191
+ if (!entry.isDirectory())
192
+ continue;
193
+ languages.add(entry.name);
194
+ for await (const namespace of this.walkLocaleDirectory(path.join(dir.path, entry.name), "")) {
195
+ namespaces.add(namespace);
196
+ }
197
+ }
198
+ return { namespaces: [...namespaces], languages: [...languages] };
199
+ }
200
+ async reloadResources() {
201
+ const result = await framework.Result.fromAsync(async () => {
202
+ let languages = this.options.hmr?.languages;
203
+ let namespaces = this.options.hmr?.namespaces;
204
+ if (!languages || !namespaces) {
205
+ const languageDirectoryResult = await this.walkRootDirectory(this.languagesDirectory);
206
+ languages ??= languageDirectoryResult.languages;
207
+ namespaces ??= languageDirectoryResult.namespaces;
208
+ }
209
+ await i18next__default.default.reloadResources(languages, namespaces);
210
+ pieces.container.logger.info("[i18next-Plugin] Reloaded language resources.");
211
+ });
212
+ result.inspectErr((error) => pieces.container.logger.error("[i18next-Plugin]: Failed to reload language resources.", error));
213
+ }
214
+ /**
215
+ * @description Skips any files that don't end with `.json`.
216
+ * @param directory The directory that should be walked.
217
+ * @param ns The current namespace.
218
+ * @since 3.0.0
219
+ */
220
+ async *walkLocaleDirectory(directory, ns) {
221
+ const dir = await promises.opendir(directory);
222
+ for await (const entry of dir) {
223
+ if (entry.isDirectory()) {
224
+ yield* this.walkLocaleDirectory(path.join(dir.path, entry.name), `${ns}${entry.name}/`);
225
+ } else if (entry.isFile() && entry.name.endsWith(".json")) {
226
+ yield `${ns}${entry.name.slice(0, -5)}`;
227
+ }
228
+ }
229
+ }
230
+ };
231
+ __name(_InternationalizationHandler, "InternationalizationHandler");
232
+ var InternationalizationHandler = _InternationalizationHandler;
233
+
234
+ exports.InternationalizationHandler = InternationalizationHandler;
235
+ //# sourceMappingURL=out.js.map
236
+ //# sourceMappingURL=InternationalizationHandler.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/lib/InternationalizationHandler.ts"],"names":[],"mappings":";;;;;;;;;AAAA,SAAS,cAAc;AACvB,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AK,kBAAkB;AACpF,sBAAc,wBAAwB;AACtC,uBAAe,wBAAwB;AAAA,MACxC;AAEA,YAAM,QAAQ,gBAAgB,WAAW,UAAU;AACnD,gBAAU,OAAO,KAAK,+CAA+C;AAAA,IACtE,CAAC;AAED,WAAO,WAAW,CAAC,UAAU,UAAU,OAAO,MAAM,0DAA0D,KAAK,CAAC;AAAA,EACrH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAe,oBAAoB,WAAmB,IAAoC;AACzF,UAAM,MAAM,MAAM,QAAQ,SAAS;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;AA9PyC;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 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, 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 formatters = this.options.formatters ?? [];\n\t\tfor (const { name, format } of formatters) {\n\t\t\ti18next.services.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,\n\t\tNs extends Namespace,\n\t\tRet extends TFunctionReturn<Ns, AppendKeyPrefix<Key, undefined>, TOpt>,\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 ? language(this.options.defaultMissingKey, { replace: { key } })\n\t\t\t\t : '';\n\n\t\treturn language<Key, TOpt, Ret, ActualOptions>(key, defaultValue, optionsOrUndefined);\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"]}
@@ -0,0 +1,125 @@
1
+ 'use strict';
2
+
3
+ var pieces = require('@sapphire/pieces');
4
+ var utilities = require('@sapphire/utilities');
5
+ var discord_js = require('discord.js');
6
+
7
+ var __defProp = Object.defineProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ function fetchLanguage(target) {
10
+ if (target instanceof discord_js.BaseInteraction) {
11
+ return resolveLanguage({
12
+ user: target.user,
13
+ channel: target.channel,
14
+ guild: target.guild,
15
+ interactionGuildLocale: target.guildLocale,
16
+ interactionLocale: target.locale
17
+ });
18
+ }
19
+ if (target instanceof discord_js.Message) {
20
+ return resolveLanguage({ user: target.author, channel: target.channel, guild: target.guild });
21
+ }
22
+ if (target instanceof discord_js.Guild) {
23
+ return resolveLanguage({ user: null, channel: null, guild: target });
24
+ }
25
+ if (target.type === discord_js.ChannelType.DM) {
26
+ return resolveLanguage({ user: null, channel: target, guild: null });
27
+ }
28
+ return resolveLanguage({ user: null, channel: target, guild: target.guild });
29
+ }
30
+ __name(fetchLanguage, "fetchLanguage");
31
+ async function fetchT(target) {
32
+ return pieces.container.i18n.getT(await fetchLanguage(target));
33
+ }
34
+ __name(fetchT, "fetchT");
35
+ async function resolveKey(target, ...[key, defaultValueOrOptions, optionsOrUndefined]) {
36
+ const parsedOptions = typeof defaultValueOrOptions === "string" ? optionsOrUndefined : defaultValueOrOptions;
37
+ const language = typeof parsedOptions?.lng === "string" ? parsedOptions.lng : await fetchLanguage(target);
38
+ if (typeof defaultValueOrOptions === "string") {
39
+ return pieces.container.i18n.format(language, key, defaultValueOrOptions, optionsOrUndefined);
40
+ }
41
+ return pieces.container.i18n.format(language, key, void 0, defaultValueOrOptions);
42
+ }
43
+ __name(resolveKey, "resolveKey");
44
+ async function resolveLanguage(context) {
45
+ const lang = await pieces.container.i18n.fetchLanguage(context);
46
+ return lang ?? context.guild?.preferredLocale ?? pieces.container.i18n.options.defaultName ?? "en-US";
47
+ }
48
+ __name(resolveLanguage, "resolveLanguage");
49
+ var supportedLanguages = new Set(Object.values(discord_js.Locale));
50
+ function isSupportedDiscordLocale(language) {
51
+ return supportedLanguages.has(language);
52
+ }
53
+ __name(isSupportedDiscordLocale, "isSupportedDiscordLocale");
54
+ var getLocales = utilities.lazy(() => {
55
+ const locales = new Map(pieces.container.i18n.languages);
56
+ for (const [locale] of locales) {
57
+ if (!isSupportedDiscordLocale(locale)) {
58
+ process.emitWarning("Unsupported Discord locale", {
59
+ code: "UNSUPPORTED_LOCALE",
60
+ detail: `'${locale}' needs to be one of: ${[...locales.keys()]}`
61
+ });
62
+ locales.delete(locale);
63
+ }
64
+ continue;
65
+ }
66
+ return locales;
67
+ });
68
+ var getDefaultT = utilities.lazy(() => {
69
+ const defaultLocale = pieces.container.i18n.options.defaultName ?? "en-US";
70
+ if (!isSupportedDiscordLocale(defaultLocale)) {
71
+ throw new TypeError(`Unsupported Discord locale found:
72
+ '${defaultLocale}' is not within the list of ${[...supportedLanguages]}`);
73
+ }
74
+ const defaultT = getLocales().get(defaultLocale);
75
+ if (defaultT) {
76
+ return defaultT;
77
+ }
78
+ throw new TypeError(`Could not find ${defaultLocale}`);
79
+ });
80
+ function getLocalizedData(key) {
81
+ const locales = getLocales();
82
+ const defaultT = getDefaultT();
83
+ return {
84
+ value: defaultT(key),
85
+ localizations: Object.fromEntries(Array.from(locales, ([locale, t]) => [locale, t(key)]))
86
+ };
87
+ }
88
+ __name(getLocalizedData, "getLocalizedData");
89
+ function applyNameLocalizedBuilder(builder, key) {
90
+ const result = getLocalizedData(key);
91
+ return builder.setName(result.value).setNameLocalizations(result.localizations);
92
+ }
93
+ __name(applyNameLocalizedBuilder, "applyNameLocalizedBuilder");
94
+ function applyDescriptionLocalizedBuilder(builder, key) {
95
+ const result = getLocalizedData(key);
96
+ return builder.setDescription(result.value).setDescriptionLocalizations(result.localizations);
97
+ }
98
+ __name(applyDescriptionLocalizedBuilder, "applyDescriptionLocalizedBuilder");
99
+ function applyLocalizedBuilder(builder, ...params) {
100
+ const [localeName, localeDescription] = params.length === 1 ? [`${params[0]}Name`, `${params[0]}Description`] : params;
101
+ applyNameLocalizedBuilder(builder, localeName);
102
+ applyDescriptionLocalizedBuilder(builder, localeDescription);
103
+ return builder;
104
+ }
105
+ __name(applyLocalizedBuilder, "applyLocalizedBuilder");
106
+ function createLocalizedChoice(key, options) {
107
+ const result = getLocalizedData(key);
108
+ return {
109
+ ...options,
110
+ name: result.value,
111
+ name_localizations: result.localizations
112
+ };
113
+ }
114
+ __name(createLocalizedChoice, "createLocalizedChoice");
115
+
116
+ exports.applyDescriptionLocalizedBuilder = applyDescriptionLocalizedBuilder;
117
+ exports.applyLocalizedBuilder = applyLocalizedBuilder;
118
+ exports.applyNameLocalizedBuilder = applyNameLocalizedBuilder;
119
+ exports.createLocalizedChoice = createLocalizedChoice;
120
+ exports.fetchLanguage = fetchLanguage;
121
+ exports.fetchT = fetchT;
122
+ exports.getLocalizedData = getLocalizedData;
123
+ exports.resolveKey = resolveKey;
124
+ //# sourceMappingURL=out.js.map
125
+ //# sourceMappingURL=functions.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/lib/functions.ts"],"names":[],"mappings":";;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,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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>(\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"]}
@@ -0,0 +1,4 @@
1
+ 'use strict';
2
+
3
+ //# sourceMappingURL=out.js.map
4
+ //# sourceMappingURL=types.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":""}
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+
3
+ var framework = require('@sapphire/framework');
4
+ var chokidar = require('chokidar');
5
+ var index_cjs = require('./index.cjs');
6
+
7
+ var __defProp = Object.defineProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var _I18nextPlugin = class _I18nextPlugin extends framework.Plugin {
10
+ static [framework.preGenericsInitialization](options) {
11
+ framework.container.i18n = new index_cjs.InternationalizationHandler(options.i18n);
12
+ }
13
+ static async [framework.preLogin]() {
14
+ await framework.container.i18n.init();
15
+ }
16
+ static [framework.postLogin]() {
17
+ if (this.options.i18n?.hmr?.enabled) {
18
+ framework.container.logger.info("[i18next-Plugin]: HMR enabled. Watching for languages changes.");
19
+ const hmr = chokidar.watch(framework.container.i18n.languagesDirectory, this.options.i18n.hmr.options);
20
+ for (const event of ["change", "unlink"])
21
+ hmr.on(event, () => framework.container.i18n.reloadResources());
22
+ }
23
+ }
24
+ };
25
+ __name(_I18nextPlugin, "I18nextPlugin");
26
+ var I18nextPlugin = _I18nextPlugin;
27
+ framework.SapphireClient.plugins.registerPostInitializationHook(I18nextPlugin[framework.preGenericsInitialization], "I18next-PreGenericsInitialization");
28
+ framework.SapphireClient.plugins.registerPreLoginHook(I18nextPlugin[framework.preLogin], "I18next-PreLogin");
29
+ framework.SapphireClient.plugins.registerPostLoginHook(I18nextPlugin[framework.postLogin], "I18next-PostLogin");
30
+
31
+ exports.I18nextPlugin = I18nextPlugin;
32
+ //# sourceMappingURL=out.js.map
33
+ //# sourceMappingURL=register.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/register.ts"],"names":[],"mappings":";;;;AAAA,SAAS,QAAQ,gBAAgB,WAAW,WAAW,2BAA2B,gBAAgB;AAClG,SAAS,aAAa;AAEtB,SAAS,mCAAmC;AAErC,IAAM,iBAAN,MAAM,uBAAsB,OAAO;AAAA,EACzC,QAAe,yBAAyB,EAAwB,SAA8B;AAC7F,cAAU,OAAO,IAAI,4BAA4B,QAAQ,IAAI;AAAA,EAC9D;AAAA,EAEA,cAAqB,QAAQ,IAAuC;AACnE,UAAM,UAAU,KAAK,KAAK;AAAA,EAC3B;AAAA,EAEA,QAAe,SAAS,IAA8B;AACrD,QAAI,KAAK,QAAQ,MAAM,KAAK,SAAS;AACpC,gBAAU,OAAO,KAAK,gEAAgE;AACtF,YAAM,MAAM,MAAM,UAAU,KAAK,oBAAoB,KAAK,QAAQ,KAAK,IAAI,OAAO;AAElF,iBAAW,SAAS,CAAC,UAAU,QAAQ;AAAG,YAAI,GAAG,OAAO,MAAM,UAAU,KAAK,gBAAgB,CAAC;AAAA,IAC/F;AAAA,EACD;AACD;AAjB0C;AAAnC,IAAM,gBAAN;AAmBP,eAAe,QAAQ,+BAA+B,cAAc,yBAAyB,GAAG,mCAAmC;AACnI,eAAe,QAAQ,qBAAqB,cAAc,QAAQ,GAAG,kBAAkB;AACvF,eAAe,QAAQ,sBAAsB,cAAc,SAAS,GAAG,mBAAmB","sourcesContent":["import { 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\t\t\tconst hmr = watch(container.i18n.languagesDirectory, this.options.i18n.hmr.options);\n\n\t\t\tfor (const event of ['change', 'unlink']) hmr.on(event, () => 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"]}
@@ -0,0 +1,10 @@
1
+ import { Plugin, preGenericsInitialization, SapphireClient, preLogin, postLogin } from '@sapphire/framework';
2
+ import { ClientOptions } from 'discord.js';
3
+
4
+ declare class I18nextPlugin extends Plugin {
5
+ static [preGenericsInitialization](this: SapphireClient, options: ClientOptions): void;
6
+ static [preLogin](this: SapphireClient): Promise<void>;
7
+ static [postLogin](this: SapphireClient): void;
8
+ }
9
+
10
+ export { I18nextPlugin };
@@ -0,0 +1,11 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
4
+ var __publicField = (obj, key, value) => {
5
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
6
+ return value;
7
+ };
8
+
9
+ export { __name, __publicField };
10
+ //# sourceMappingURL=out.js.map
11
+ //# sourceMappingURL=chunk-6QB3UK4Q.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","sourcesContent":[]}