@discord/intl 0.5.2 → 0.6.1

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.
@@ -8,70 +8,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- var __values = (this && this.__values) || function(o) {
39
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
40
- if (m) return m.call(o);
41
- if (o && typeof o.length === "number") return {
42
- next: function () {
43
- if (o && i >= o.length) o = void 0;
44
- return { value: o && o[i++], done: !o };
45
- }
46
- };
47
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
48
- };
49
- var __read = (this && this.__read) || function (o, n) {
50
- var m = typeof Symbol === "function" && o[Symbol.iterator];
51
- if (!m) return o;
52
- var i = m.call(o), r, ar = [], e;
53
- try {
54
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
55
- }
56
- catch (error) { e = { error: error }; }
57
- finally {
58
- try {
59
- if (r && !r.done && (m = i["return"])) m.call(i);
60
- }
61
- finally { if (e) throw e.error; }
62
- }
63
- return ar;
64
- };
65
11
  Object.defineProperty(exports, "__esModule", { value: true });
66
12
  exports.MessageLoader = void 0;
67
13
  exports.loadAllMessagesInLocale = loadAllMessagesInLocale;
68
14
  exports.waitForAllDefaultIntlMessagesLoaded = waitForAllDefaultIntlMessagesLoaded;
69
15
  exports.createLoader = createLoader;
70
- var message_1 = require("./message");
71
- var MessageLoader = /** @class */ (function () {
72
- function MessageLoader(messageKeys, localeImportMap, defaultLocale) {
73
- var e_1, _a;
74
- var _this = this;
16
+ const message_1 = require("./message");
17
+ class MessageLoader {
18
+ constructor(messageKeys, localeImportMap, defaultLocale) {
75
19
  this.messageKeys = messageKeys;
76
20
  this.messages = {};
77
21
  this.localeImportMap = localeImportMap;
@@ -86,32 +30,12 @@ var MessageLoader = /** @class */ (function () {
86
30
  // targets change so that values are always replaced.
87
31
  // @ts-expect-error `hot` not defined in types.
88
32
  if (module.hot) {
89
- var _loop_1 = function (locale, file) {
33
+ for (const [locale, file] of Object.entries(localeImportMap)) {
90
34
  // @ts-expect-error `hot` not defined in types.
91
- module.hot.accept(file, function () { return __awaiter(_this, void 0, void 0, function () {
92
- return __generator(this, function (_a) {
93
- switch (_a.label) {
94
- case 0: return [4 /*yield*/, this._loadLocale(locale)];
95
- case 1:
96
- _a.sent();
97
- this._parseCache.clear();
98
- return [2 /*return*/];
99
- }
100
- });
101
- }); });
102
- };
103
- try {
104
- for (var _b = __values(Object.entries(localeImportMap)), _c = _b.next(); !_c.done; _c = _b.next()) {
105
- var _d = __read(_c.value, 2), locale = _d[0], file = _d[1];
106
- _loop_1(locale, file);
107
- }
108
- }
109
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
110
- finally {
111
- try {
112
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
113
- }
114
- finally { if (e_1) throw e_1.error; }
35
+ module.hot.accept(file, () => __awaiter(this, void 0, void 0, function* () {
36
+ yield this._loadLocale(locale);
37
+ this._parseCache.clear();
38
+ }));
115
39
  }
116
40
  }
117
41
  }
@@ -122,25 +46,25 @@ var MessageLoader = /** @class */ (function () {
122
46
  * @param {Record<string, string>} keyMap
123
47
  * @param {Record<string, string>} localeFileMap
124
48
  */
125
- MessageLoader.prototype.withDebugValues = function (keyMap, localeFileMap) {
49
+ withDebugValues(keyMap, localeFileMap) {
126
50
  this._debugKeyMap = keyMap;
127
51
  this._localeFileMap = localeFileMap;
128
- };
129
- MessageLoader.prototype.get = function (key, locale) {
52
+ }
53
+ get(key, locale) {
130
54
  var _a;
131
- var value = (_a = this.getMessageValue(key, locale)) !== null && _a !== void 0 ? _a : this.getMessageValue(key, this.defaultLocale);
55
+ const value = (_a = this.getMessageValue(key, locale)) !== null && _a !== void 0 ? _a : this.getMessageValue(key, this.defaultLocale);
132
56
  if (value != null)
133
57
  return value;
134
58
  // If the message couldn't be found in either the requested nor the default locale, then
135
59
  // nothing can be done.
136
- var errorKey = this._debugKeyMap != null ? "\"".concat(this._debugKeyMap[key], "\" (").concat(key, ")") : undefined;
137
- var requestedLocale = this._localeFileMap != null ? "".concat(locale, " (").concat(this._localeFileMap[locale], ")") : locale;
138
- var defaultLocale = this._localeFileMap != null
139
- ? "".concat(this.defaultLocale, " (").concat(this._localeFileMap[this.defaultLocale], ")")
60
+ const errorKey = this._debugKeyMap != null ? `"${this._debugKeyMap[key]}" (${key})` : undefined;
61
+ const requestedLocale = this._localeFileMap != null ? `${locale} (${this._localeFileMap[locale]})` : locale;
62
+ const defaultLocale = this._localeFileMap != null
63
+ ? `${this.defaultLocale} (${this._localeFileMap[this.defaultLocale]})`
140
64
  : this.defaultLocale;
141
- console.warn("Requested message ".concat(errorKey, " does not have a value in the requested locale ").concat(requestedLocale, " nor the default locale ").concat(defaultLocale));
65
+ console.warn(`Requested message ${errorKey} does not have a value in the requested locale ${requestedLocale} nor the default locale ${defaultLocale}`);
142
66
  return this.fallbackMessage;
143
- };
67
+ }
144
68
  /**
145
69
  * Return the value of the message with the given `key` in the given `locale`. If the message has
146
70
  * no value in that locale, this function returns `undefined`.
@@ -150,9 +74,9 @@ var MessageLoader = /** @class */ (function () {
150
74
  * function will trigger a load for that locale, but will not wait for it to resolve before
151
75
  * returning.
152
76
  */
153
- MessageLoader.prototype.getMessageValue = function (key, locale) {
154
- var cacheKey = key + '@' + locale;
155
- var cachedValue = this._parseCache.get(cacheKey);
77
+ getMessageValue(key, locale) {
78
+ const cacheKey = key + '@' + locale;
79
+ const cachedValue = this._parseCache.get(cacheKey);
156
80
  if (cachedValue != null)
157
81
  return cachedValue;
158
82
  // Check whether the locale exists in memory. If not, start a request to
@@ -167,102 +91,77 @@ var MessageLoader = /** @class */ (function () {
167
91
  }
168
92
  // Then try to return the loaded message.
169
93
  if (key in this.messages[locale]) {
170
- var content = this.messages[locale][key];
171
- var message = new message_1.InternalIntlMessage(content, locale);
94
+ const content = this.messages[locale][key];
95
+ const message = new message_1.InternalIntlMessage(content, locale);
172
96
  this._parseCache.set(cacheKey, message);
173
97
  return message;
174
98
  }
175
99
  // Otherwise just assume it doesn't exist.
176
100
  return undefined;
177
- };
101
+ }
178
102
  /**
179
103
  * Returns a record mapping the keys this object manages to bound functions
180
104
  * for `get` with the that key as the first argument, allowing consumers to
181
105
  * just call the function with a locale to retrieve the translated message
182
106
  * for that key.
183
107
  */
184
- MessageLoader.prototype.getBinds = function () {
185
- var _this = this;
186
- var onChange = this.onChange.bind(this);
187
- return Object.keys(this.messageKeys).reduce(function (acc, key) {
188
- var bound = _this.get.bind(_this, key);
108
+ getBinds() {
109
+ const onChange = this.onChange.bind(this);
110
+ return Object.keys(this.messageKeys).reduce((acc, key) => {
111
+ const bound = this.get.bind(this, key);
189
112
  bound.onChange = onChange;
190
113
  acc[key] = bound;
191
114
  return acc;
192
115
  }, {});
193
- };
194
- MessageLoader.prototype._loadLocale = function (locale) {
195
- return __awaiter(this, void 0, void 0, function () {
196
- var current, _a, _b;
197
- var _c;
198
- return __generator(this, function (_d) {
199
- switch (_d.label) {
200
- case 0:
201
- // Don't re-load a locale that's already in progress.
202
- if (((_c = this._localeLoadingPromises[locale]) === null || _c === void 0 ? void 0 : _c.current) != null) {
203
- return [2 /*return*/];
204
- }
205
- // Safety check in case the locale map doesn't include a require for the
206
- // requested locale. Shouldn't happen, but throwing here is much more
207
- // contextual than whatever error would result otherwise.
208
- if (this.localeImportMap[locale] == null) {
209
- if (this.supportedLocales.includes(locale)) {
210
- // `supportedLocales` is determined by the `localeImportMap`, so if it's present but
211
- // nullish, it's almost definitely a configuration error and deserves to be reported loudly.
212
- throw new Error("Requested to load locale ".concat(locale, ", which should be supported, but no source for translation data was provided."));
213
- }
214
- else {
215
- return [2 /*return*/];
216
- }
217
- }
218
- // If the locale is already set in `messages`, then it doesn't need to be loaded again.
219
- if (this.messages[locale] != null)
220
- return [2 /*return*/];
221
- current = this.localeImportMap[locale]();
222
- this._localeLoadingPromises[locale] = { initialized: false, current: current };
223
- _a = this.messages;
224
- _b = locale;
225
- return [4 /*yield*/, current];
226
- case 1:
227
- _a[_b] = (_d.sent()).default;
228
- this._localeLoadingPromises[locale] = { initialized: true, current: undefined };
229
- this.emitChange();
230
- return [2 /*return*/];
116
+ }
117
+ _loadLocale(locale) {
118
+ return __awaiter(this, void 0, void 0, function* () {
119
+ var _a;
120
+ // Don't re-load a locale that's already in progress.
121
+ if (((_a = this._localeLoadingPromises[locale]) === null || _a === void 0 ? void 0 : _a.current) != null) {
122
+ return;
123
+ }
124
+ // Safety check in case the locale map doesn't include a require for the
125
+ // requested locale. Shouldn't happen, but throwing here is much more
126
+ // contextual than whatever error would result otherwise.
127
+ if (this.localeImportMap[locale] == null) {
128
+ if (this.supportedLocales.includes(locale)) {
129
+ // `supportedLocales` is determined by the `localeImportMap`, so if it's present but
130
+ // nullish, it's almost definitely a configuration error and deserves to be reported loudly.
131
+ throw new Error(`Requested to load locale ${locale}, which should be supported, but no source for translation data was provided.`);
231
132
  }
232
- });
133
+ else {
134
+ return;
135
+ }
136
+ }
137
+ // If the locale is already set in `messages`, then it doesn't need to be loaded again.
138
+ if (this.messages[locale] != null)
139
+ return;
140
+ const current = this.localeImportMap[locale]();
141
+ this._localeLoadingPromises[locale] = { initialized: false, current };
142
+ this.messages[locale] = (yield current).default;
143
+ this._localeLoadingPromises[locale] = { initialized: true, current: undefined };
144
+ this.emitChange();
233
145
  });
234
- };
146
+ }
235
147
  /**
236
148
  * Inform subscribers that the loader state has changed and they should
237
149
  * potentially update to get new values for messages.
238
150
  */
239
- MessageLoader.prototype.emitChange = function () {
240
- var e_2, _a;
241
- try {
242
- for (var _b = __values(this._subscribers.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
243
- var callback = _c.value;
244
- callback();
245
- }
151
+ emitChange() {
152
+ for (const callback of this._subscribers.values()) {
153
+ callback();
246
154
  }
247
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
248
- finally {
249
- try {
250
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
251
- }
252
- finally { if (e_2) throw e_2.error; }
253
- }
254
- };
155
+ }
255
156
  /**
256
157
  * Subscribe to events about when a locale has loaded.
257
158
  */
258
- MessageLoader.prototype.onChange = function (callback) {
259
- var _this = this;
159
+ onChange(callback) {
260
160
  this._subscribers.add(callback);
261
- return function () { return _this._subscribers.delete(callback); };
262
- };
263
- MessageLoader.prototype.isLocaleLoaded = function (locale, requireCurrent) {
264
- if (requireCurrent === void 0) { requireCurrent = false; }
265
- var ref = this._localeLoadingPromises[locale];
161
+ return () => this._subscribers.delete(callback);
162
+ }
163
+ isLocaleLoaded(locale, requireCurrent = false) {
164
+ const ref = this._localeLoadingPromises[locale];
266
165
  // Ensure the locale at least exists and is initialized.
267
166
  if (ref == null || ref.initialized == false)
268
167
  return false;
@@ -272,68 +171,44 @@ var MessageLoader = /** @class */ (function () {
272
171
  return ref.current == null;
273
172
  // Otherwise, initialization is enough.
274
173
  return true;
275
- };
276
- MessageLoader.prototype.waitForLocaleLoaded = function (locale_1) {
277
- return __awaiter(this, arguments, void 0, function (locale, requireCurrent) {
278
- var ref;
279
- if (requireCurrent === void 0) { requireCurrent = false; }
280
- return __generator(this, function (_a) {
281
- switch (_a.label) {
282
- case 0:
283
- ref = this._localeLoadingPromises[locale];
284
- // If the locale hasn't been loaded at all, kick off the load and return
285
- // that Promise directly.
286
- if (ref == null)
287
- return [2 /*return*/, this._loadLocale(locale)];
288
- // If initialization is enough for this request, just resolve immediately.
289
- if (ref.initialized && !requireCurrent)
290
- return [2 /*return*/];
291
- // Otherwise, check the `current` loading state on the object, and if that
292
- // doesn't exist, then the locale data is already finished loading, and the
293
- // containing Promise will just resolve with `undefined`.
294
- return [4 /*yield*/, ref.current];
295
- case 1:
296
- // Otherwise, check the `current` loading state on the object, and if that
297
- // doesn't exist, then the locale data is already finished loading, and the
298
- // containing Promise will just resolve with `undefined`.
299
- _a.sent();
300
- return [2 /*return*/];
301
- }
302
- });
174
+ }
175
+ waitForLocaleLoaded(locale_1) {
176
+ return __awaiter(this, arguments, void 0, function* (locale, requireCurrent = false) {
177
+ const ref = this._localeLoadingPromises[locale];
178
+ // If the locale hasn't been loaded at all, kick off the load and return
179
+ // that Promise directly.
180
+ if (ref == null)
181
+ return this._loadLocale(locale);
182
+ // If initialization is enough for this request, just resolve immediately.
183
+ if (ref.initialized && !requireCurrent)
184
+ return;
185
+ // Otherwise, check the `current` loading state on the object, and if that
186
+ // doesn't exist, then the locale data is already finished loading, and the
187
+ // containing Promise will just resolve with `undefined`.
188
+ yield ref.current;
303
189
  });
304
- };
190
+ }
305
191
  /**
306
192
  * Returns true if this loader's default locale has finished loading. When
307
193
  * true, all messages managed by this loader are guaranteed to have _a_
308
194
  * render-able value, even if one does not exist in the current locale.
309
195
  */
310
- MessageLoader.prototype.waitForDefaultLocale = function () {
311
- return __awaiter(this, arguments, void 0, function (requireCurrent) {
312
- if (requireCurrent === void 0) { requireCurrent = false; }
313
- return __generator(this, function (_a) {
314
- return [2 /*return*/, this.waitForLocaleLoaded(this.defaultLocale, requireCurrent)];
315
- });
196
+ waitForDefaultLocale() {
197
+ return __awaiter(this, arguments, void 0, function* (requireCurrent = false) {
198
+ return this.waitForLocaleLoaded(this.defaultLocale, requireCurrent);
316
199
  });
317
- };
318
- return MessageLoader;
319
- }());
200
+ }
201
+ }
320
202
  exports.MessageLoader = MessageLoader;
321
- var LOADER_REGISTRY = [];
203
+ const LOADER_REGISTRY = [];
322
204
  /**
323
205
  * Kick off a load request for the given locale across all currently-registered
324
206
  * message loaders, returning a Promise that resolves when all loaders have
325
207
  * finished loading that locale.
326
208
  */
327
209
  function loadAllMessagesInLocale(locale) {
328
- return __awaiter(this, void 0, void 0, function () {
329
- return __generator(this, function (_a) {
330
- switch (_a.label) {
331
- case 0: return [4 /*yield*/, Promise.all(LOADER_REGISTRY.map(function (loader) { return loader._loadLocale(locale); }))];
332
- case 1:
333
- _a.sent();
334
- return [2 /*return*/];
335
- }
336
- });
210
+ return __awaiter(this, void 0, void 0, function* () {
211
+ yield Promise.all(LOADER_REGISTRY.map((loader) => loader._loadLocale(locale)));
337
212
  });
338
213
  }
339
214
  /**
@@ -347,15 +222,8 @@ function loadAllMessagesInLocale(locale) {
347
222
  * will always ensure that _all_ loaders that currently exist are initialized.
348
223
  */
349
224
  function waitForAllDefaultIntlMessagesLoaded() {
350
- return __awaiter(this, void 0, void 0, function () {
351
- return __generator(this, function (_a) {
352
- switch (_a.label) {
353
- case 0: return [4 /*yield*/, Promise.all(LOADER_REGISTRY.map(function (loader) { return loader.waitForDefaultLocale(); }))];
354
- case 1:
355
- _a.sent();
356
- return [2 /*return*/];
357
- }
358
- });
225
+ return __awaiter(this, void 0, void 0, function* () {
226
+ yield Promise.all(LOADER_REGISTRY.map((loader) => loader.waitForDefaultLocale()));
359
227
  });
360
228
  }
361
229
  /**
@@ -364,7 +232,7 @@ function waitForAllDefaultIntlMessagesLoaded() {
364
232
  * message defined in `messageKeys`.
365
233
  */
366
234
  function createLoader(messageKeys, localeImportMap, defaultLocale) {
367
- var loader = new MessageLoader(messageKeys, localeImportMap, defaultLocale);
235
+ const loader = new MessageLoader(messageKeys, localeImportMap, defaultLocale);
368
236
  LOADER_REGISTRY.push(loader);
369
237
  return loader;
370
238
  }
package/dist/message.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { FormatJsNode } from './keyless-json';
1
+ import { AstNode, FullFormatJsNode } from '@discord/intl-ast';
2
2
  export declare class InternalIntlMessage {
3
3
  locale: string;
4
- ast: FormatJsNode[];
5
- constructor(messageOrAst: FormatJsNode[], locale: string);
4
+ ast: AstNode[];
5
+ constructor(messageOrAst: AstNode[] | FullFormatJsNode[], locale: string);
6
6
  /**
7
7
  * Return a stringified serialization of this message's AST, with no
8
8
  * formatting or values applied.