@intlify/core 12.0.0-alpha.1 → 12.0.0-alpha.10

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.
@@ -1,2048 +1,1733 @@
1
- /*!
2
- * core v12.0.0-alpha.1
3
- * (c) 2016-present kazuya kawaguchi and contributors
4
- * Released under the MIT License.
5
- */
6
1
  /**
7
- * Original Utilities
8
- * written by kazuya kawaguchi
9
- */
10
- const inBrowser = typeof window !== 'undefined';
2
+ * @intlify/core v12.0.0-alpha.10
3
+ * (c) 2016-present kazuya kawaguchi and contributors
4
+ * @license MIT
5
+ **/
6
+ // packages/shared/src/utils.ts
7
+ /**
8
+ * Original Utilities
9
+ * written by kazuya kawaguchi
10
+ */
11
+ const inBrowser = typeof window !== "undefined";
11
12
  let mark;
12
13
  let measure;
13
14
  {
14
- const perf = inBrowser && window.performance;
15
- if (perf &&
16
- perf.mark &&
17
- perf.measure &&
18
- perf.clearMarks &&
19
- // @ts-ignore browser compat
20
- perf.clearMeasures) {
21
- mark = (tag) => {
22
- perf.mark(tag);
23
- };
24
- measure = (name, startTag, endTag) => {
25
- perf.measure(name, startTag, endTag);
26
- perf.clearMarks(startTag);
27
- perf.clearMarks(endTag);
28
- };
29
- }
30
- }
31
- const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
32
- /* eslint-disable */
15
+ const perf = inBrowser && window.performance;
16
+ if (perf && perf.mark && perf.measure && perf.clearMarks && perf.clearMeasures) {
17
+ mark = (tag) => {
18
+ perf.mark(tag);
19
+ };
20
+ measure = (name, startTag, endTag) => {
21
+ perf.measure(name, startTag, endTag);
22
+ perf.clearMarks(startTag);
23
+ perf.clearMarks(endTag);
24
+ perf.clearMeasures(name);
25
+ };
26
+ }
27
+ }
28
+ const RE_ARGS = /\{([0-9a-z]+)\}/gi;
33
29
  function format$1(message, ...args) {
34
- if (args.length === 1 && isObject(args[0])) {
35
- args = args[0];
36
- }
37
- if (!args || !args.hasOwnProperty) {
38
- args = {};
39
- }
40
- return message.replace(RE_ARGS, (match, identifier) => {
41
- return args.hasOwnProperty(identifier) ? args[identifier] : '';
42
- });
43
- }
44
- const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
45
- const friendlyJSONstringify = (json) => JSON.stringify(json)
46
- .replace(/\u2028/g, '\\u2028')
47
- .replace(/\u2029/g, '\\u2029')
48
- .replace(/\u0027/g, '\\u0027');
49
- const isNumber = (val) => typeof val === 'number' && isFinite(val);
50
- const isDate = (val) => toTypeString(val) === '[object Date]';
51
- const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
52
- const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
30
+ if (args.length === 1 && isObject(args[0])) args = args[0];
31
+ if (!args || !args.hasOwnProperty) args = {};
32
+ return message.replace(RE_ARGS, (_match, identifier) => {
33
+ return args.hasOwnProperty(identifier) ? args[identifier] : "";
34
+ });
35
+ }
36
+ const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({
37
+ l: locale,
38
+ k: key,
39
+ s: source
40
+ });
41
+ const friendlyJSONstringify = (json) => JSON.stringify(json).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029").replace(/\u0027/g, "\\u0027");
42
+ const isNumber = (val) => typeof val === "number" && isFinite(val);
43
+ function toDevtoolsGroupId(type, key) {
44
+ return isString(key) || isNumber(key) ? `${type}:${key}` : type;
45
+ }
46
+ const isDate = (val) => toTypeString(val) === "[object Date]";
47
+ const isRegExp = (val) => toTypeString(val) === "[object RegExp]";
48
+ const isKeylessObject = (val) => Object.keys(val).length === 0;
53
49
  const assign = Object.assign;
54
50
  const _create = Object.create;
55
51
  const create = (obj = null) => _create(obj);
56
- function escapeHtml(rawText) {
57
- return rawText
58
- .replace(/</g, '&lt;')
59
- .replace(/>/g, '&gt;')
60
- .replace(/"/g, '&quot;')
61
- .replace(/'/g, '&apos;');
62
- }
63
52
  const hasOwnProperty = Object.prototype.hasOwnProperty;
64
53
  function hasOwn(obj, key) {
65
- return hasOwnProperty.call(obj, key);
54
+ return hasOwnProperty.call(obj, key);
55
+ }
56
+ /**
57
+ * Get `obj[key]` only when `key` is an own property of `obj`, so that a key such as `constructor`
58
+ * does not read a property inherited from `Object.prototype`.
59
+ * The property is read before the check, so that a reactive `obj` tracks `key` even when it is missing.
60
+ */
61
+ function getOwn(obj, key) {
62
+ const value = obj[key];
63
+ return hasOwn(obj, key) ? value : void 0;
64
+ }
65
+ /**
66
+ * Whether `key` is a property name of `Object.prototype`, such as `__proto__`, `constructor` or `toString`.
67
+ * On a plain object, such a key reads a built-in, and assigning to `__proto__` replaces the prototype.
68
+ */
69
+ function isObjectPrototypeKey(key) {
70
+ return hasOwn(Object.prototype, key);
66
71
  }
67
- /* eslint-enable */
68
72
  /**
69
- * Useful Utilities By Evan you
70
- * Modified by kazuya kawaguchi
71
- * MIT License
72
- * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
73
- * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
74
- */
73
+ * Useful Utilities By Evan you
74
+ * Modified by kazuya kawaguchi
75
+ * MIT License
76
+ * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
77
+ * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
78
+ */
75
79
  const isArray = Array.isArray;
76
- const isFunction = (val) => typeof val === 'function';
77
- const isString = (val) => typeof val === 'string';
78
- const isBoolean = (val) => typeof val === 'boolean';
79
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
80
- const isObject = (val) => val !== null && typeof val === 'object';
81
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
80
+ const isFunction = (val) => typeof val === "function";
81
+ const isString = (val) => typeof val === "string";
82
+ const isBoolean = (val) => typeof val === "boolean";
83
+ const isObject = (val) => val !== null && typeof val === "object";
82
84
  const isPromise = (val) => {
83
- return isObject(val) && isFunction(val.then) && isFunction(val.catch);
85
+ return isObject(val) && isFunction(val.then) && isFunction(val.catch);
84
86
  };
85
87
  const objectToString = Object.prototype.toString;
86
88
  const toTypeString = (value) => objectToString.call(value);
87
- const isPlainObject = (val) => toTypeString(val) === '[object Object]';
88
- // for converting list and named values to displayed strings.
89
+ const isPlainObject = (val) => toTypeString(val) === "[object Object]";
89
90
  const toDisplayString = (val) => {
90
- return val == null
91
- ? ''
92
- : isArray(val) || (isPlainObject(val) && val.toString === objectToString)
93
- ? JSON.stringify(val, null, 2)
94
- : String(val);
91
+ return val == null ? "" : isArray(val) || isPlainObject(val) && val.toString === objectToString ? JSON.stringify(val, null, 2) : String(val);
95
92
  };
96
- function join(items, separator = '') {
97
- return items.reduce((str, item, index) => (index === 0 ? str + item : str + separator + item), '');
93
+ function join(items, separator = "") {
94
+ return items.reduce((str, item, index) => index === 0 ? str + item : str + separator + item, "");
98
95
  }
99
96
  const RANGE = 2;
100
97
  function generateCodeFrame(source, start = 0, end = source.length) {
101
- const lines = source.split(/\r?\n/);
102
- let count = 0;
103
- const res = [];
104
- for (let i = 0; i < lines.length; i++) {
105
- count += lines[i].length + 1;
106
- if (count >= start) {
107
- for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
108
- if (j < 0 || j >= lines.length)
109
- continue;
110
- const line = j + 1;
111
- res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
112
- const lineLength = lines[j].length;
113
- if (j === i) {
114
- // push underline
115
- const pad = start - (count - lineLength) + 1;
116
- const length = Math.max(1, end > count ? lineLength - pad : end - start);
117
- res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
118
- }
119
- else if (j > i) {
120
- if (end > count) {
121
- const length = Math.max(Math.min(end - count, lineLength), 1);
122
- res.push(` | ` + '^'.repeat(length));
123
- }
124
- count += lineLength + 1;
125
- }
126
- }
127
- break;
128
- }
129
- }
130
- return res.join('\n');
131
- }
132
-
98
+ const lines = source.split(/\r?\n/);
99
+ let count = 0;
100
+ const res = [];
101
+ for (let i = 0; i < lines.length; i++) {
102
+ count += lines[i].length + 1;
103
+ if (count >= start) {
104
+ for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
105
+ if (j < 0 || j >= lines.length) continue;
106
+ const line = j + 1;
107
+ res.push(`${line}${" ".repeat(3 - String(line).length)}| ${lines[j]}`);
108
+ const lineLength = lines[j].length;
109
+ if (j === i) {
110
+ const pad = start - (count - lineLength) + 1;
111
+ const length = Math.max(1, end > count ? lineLength - pad : end - start);
112
+ res.push(` | ` + " ".repeat(pad) + "^".repeat(length));
113
+ } else if (j > i) {
114
+ if (end > count) {
115
+ const length = Math.max(Math.min(end - count, lineLength), 1);
116
+ res.push(` | ` + "^".repeat(length));
117
+ }
118
+ count += lineLength + 1;
119
+ }
120
+ }
121
+ break;
122
+ }
123
+ }
124
+ return res.join("\n");
125
+ }
126
+ // packages/shared/src/warn.ts
133
127
  function warn(msg, err) {
134
- if (typeof console !== 'undefined') {
135
- console.warn(`[intlify] ` + msg);
136
- /* istanbul ignore if */
137
- if (err) {
138
- console.warn(err.stack);
139
- }
140
- }
128
+ if (typeof console !== "undefined") {
129
+ console.warn(`[intlify] ` + msg);
130
+ /* istanbul ignore if */
131
+ if (err) console.warn(err.stack);
132
+ }
141
133
  }
142
134
  const hasWarned = {};
143
135
  function warnOnce(msg) {
144
- if (!hasWarned[msg]) {
145
- hasWarned[msg] = true;
146
- warn(msg);
147
- }
136
+ if (!hasWarned[msg]) {
137
+ hasWarned[msg] = true;
138
+ warn(msg);
139
+ }
140
+ }
141
+ // packages/shared/src/sanitize.ts
142
+ function escapeHtml(rawText) {
143
+ return rawText.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;").replace(/\//g, "&#x2F;").replace(/=/g, "&#x3D;");
144
+ }
145
+ function escapeAttributeValue(value) {
146
+ return value.replace(/&(?![a-z0-9#]{2,6};)/gi, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&apos;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
147
+ }
148
+ const javascriptSchemePattern = /^javascript:/i;
149
+ const urlAttributePattern = /^(?:href|xlink:href|src|action|formaction)$/i;
150
+ const numericCharacterReferencePattern = /&#(?:x([0-9a-f]+)|(\d+));?/gi;
151
+ const namedWhitespaceCharacterReferencePattern = /&(?:Tab|NewLine);/g;
152
+ const colonCharacterReferencePattern = /&colon;?/gi;
153
+ const controlOrWhitespacePattern = /[\u0000-\u0020\u007f-\u009f]/g;
154
+ const eventHandlerPattern = /^on\w/i;
155
+ const srcdocPattern = /^srcdoc$/i;
156
+ const dangerousElementPattern = /^(?:base|animate|set|script|plaintext)$/i;
157
+ const textContentElementPattern = /^(?:iframe|noembed|noframes|noscript|style|textarea|title|xmp)$/i;
158
+ const tagStartPattern = /<(\/?)([a-z][^\t\n\f\r />]*)/iy;
159
+ const tagStepPattern = /([\t\n\f\r /]*)(?:(>)|([^\t\n\f\r />][^\t\n\f\r />=]*)(?:[\t\n\f\r ]*=[\t\n\f\r ]*(?:(["'])([\s\S]*?)(\4|$)|([^\t\n\f\r >]*)))?)/y;
160
+ const commentPattern = /<!--(?:>|->|[\s\S]*?--!?>)/y;
161
+ function decodeNumericCharacterReference(match, hex, decimal) {
162
+ const digits = hex || decimal;
163
+ if (!digits) return match;
164
+ const codePoint = Number.parseInt(digits, hex ? 16 : 10);
165
+ return codePoint <= 127 ? String.fromCharCode(codePoint) : match;
166
+ }
167
+ function hasJavascriptScheme(value) {
168
+ const normalized = value.replace(numericCharacterReferencePattern, decodeNumericCharacterReference).replace(namedWhitespaceCharacterReferencePattern, "").replace(colonCharacterReferencePattern, ":").replace(controlOrWhitespacePattern, "");
169
+ return javascriptSchemePattern.test(normalized);
170
+ }
171
+ function sanitizeStyleValue(value) {
172
+ const urlPattern = /url\s*\(/gi;
173
+ let sanitized = "";
174
+ let cursor = 0;
175
+ let match;
176
+ while ((match = urlPattern.exec(value)) !== null) {
177
+ const urlStart = match.index;
178
+ const openParenIndex = urlPattern.lastIndex - 1;
179
+ let index = openParenIndex + 1;
180
+ let depth = 1;
181
+ let quote = null;
182
+ for (; index < value.length; index++) {
183
+ const char = value[index];
184
+ if (quote) {
185
+ if (char === quote) quote = null;
186
+ continue;
187
+ }
188
+ if (char === "\"" || char === "'") quote = char;
189
+ else if (char === "(") depth++;
190
+ else if (char === ")") {
191
+ depth--;
192
+ if (depth === 0) break;
193
+ }
194
+ }
195
+ if (depth !== 0) break;
196
+ const rawUrlValue = value.slice(openParenIndex + 1, index).trim();
197
+ const unquotedUrlValue = rawUrlValue.startsWith("\"") && rawUrlValue.endsWith("\"") || rawUrlValue.startsWith("'") && rawUrlValue.endsWith("'") ? rawUrlValue.slice(1, -1).trim() : rawUrlValue;
198
+ sanitized += value.slice(cursor, urlStart);
199
+ sanitized += hasJavascriptScheme(unquotedUrlValue) ? "url(about:blank)" : value.slice(urlStart, index + 1);
200
+ cursor = index + 1;
201
+ }
202
+ return sanitized + value.slice(cursor);
203
+ }
204
+ function sanitizeAttributeValue(attrName, value) {
205
+ if (urlAttributePattern.test(attrName) && hasJavascriptScheme(value)) return "about:blank";
206
+ return escapeAttributeValue(attrName.toLowerCase() === "style" ? sanitizeStyleValue(value) : value);
207
+ }
208
+ function escapeLessThan(text) {
209
+ return text.replace(/</g, "&lt;");
210
+ }
211
+ function serializeAttribute(attrName, value, quote, neutralized) {
212
+ let name = attrName;
213
+ if (eventHandlerPattern.test(attrName)) {
214
+ neutralized.eventHandler = true;
215
+ name = `&#111;n${attrName.slice(2)}`;
216
+ } else if (srcdocPattern.test(attrName)) {
217
+ neutralized.srcdoc = true;
218
+ name = `&#115;${attrName.slice(1)}`;
219
+ }
220
+ if (value === void 0) return name;
221
+ const valueQuote = quote || "";
222
+ return `${name}=${valueQuote}${sanitizeAttributeValue(attrName, value)}${valueQuote}`;
223
+ }
224
+ /**
225
+ * Read a tag with the rules of the HTML tokenizer.
226
+ * A start tag is written again with its attributes sanitized, and an end tag is kept as it is
227
+ *
228
+ * @param html - The HTML
229
+ * @param start - The index of `<`
230
+ * @param neutralized - What has been neutralized
231
+ * @returns The tag, the tag name, and the index after the tag (-1 when the tag is not closed),
232
+ * or `undefined` when `<` does not start a tag
233
+ */
234
+ function readTag(html, start, neutralized) {
235
+ tagStartPattern.lastIndex = start;
236
+ const tagStart = tagStartPattern.exec(html);
237
+ if (!tagStart) return;
238
+ const [, slash, tagName] = tagStart;
239
+ let tag = tagStart[0];
240
+ let step;
241
+ tagStepPattern.lastIndex = tagStartPattern.lastIndex;
242
+ while (step = tagStepPattern.exec(html)) {
243
+ const [raw, separator, close, attrName, quote, quotedValue, closingQuote, unquotedValue] = step;
244
+ if (close) {
245
+ const end = tagStepPattern.lastIndex;
246
+ return [
247
+ slash ? html.slice(start, end) : tag + raw,
248
+ tagName,
249
+ end
250
+ ];
251
+ }
252
+ if (quote && !closingQuote) break;
253
+ if (!slash) tag += separator + serializeAttribute(attrName, quote ? quotedValue : unquotedValue, quote, neutralized);
254
+ }
255
+ return [
256
+ tag,
257
+ tagName,
258
+ -1
259
+ ];
260
+ }
261
+ /**
262
+ * Find the end tag of an element whose content is text, as the HTML tokenizer does:
263
+ * the first `</` followed by the tag name, and by whitespace, `/` or `>`
264
+ *
265
+ * @returns The index of the end tag, or -1 when it is not found or not closed in the string
266
+ */
267
+ function findTextContentEnd(html, from, tagName) {
268
+ for (let index = html.indexOf("</", from); index !== -1; index = html.indexOf("</", index + 2)) {
269
+ const endTag = readTag(html, index, {});
270
+ if (endTag && endTag[1].toLowerCase() === tagName.toLowerCase()) return endTag[2] === -1 ? -1 : index;
271
+ }
272
+ return -1;
148
273
  }
149
-
274
+ /**
275
+ * Sanitize the translated HTML
276
+ *
277
+ * @remarks
278
+ * Tags are read with the rules of the HTML tokenizer, so that the sanitizer and browsers agree on
279
+ * where each tag and each attribute starts and ends, and every attribute of every start tag is checked.
280
+ * What is still open at the end of the string (a tag, a comment, or an element whose content is text,
281
+ * like `<textarea>`) becomes text: on the server (SSR), the rest of the page follows the translation,
282
+ * and it would be read as a part of what is open
283
+ *
284
+ * @param html - The translated HTML
285
+ * @returns The sanitized HTML
286
+ */
287
+ function sanitizeTranslatedHtml(html) {
288
+ const neutralized = {};
289
+ let result = "";
290
+ let index = 0;
291
+ let lessThan;
292
+ while ((lessThan = html.indexOf("<", index)) !== -1) {
293
+ result += html.slice(index, lessThan);
294
+ index = lessThan + 1;
295
+ const read = readTag(html, lessThan, neutralized);
296
+ if (read) {
297
+ const [tag, tagName, end] = read;
298
+ if (end === -1) {
299
+ neutralized.unclosed = true;
300
+ result += escapeLessThan(html.slice(lessThan));
301
+ index = html.length;
302
+ break;
303
+ }
304
+ index = end;
305
+ if (tag[1] === "/") result += tag;
306
+ else if (dangerousElementPattern.test(tagName)) {
307
+ neutralized.element = true;
308
+ result += escapeLessThan(tag);
309
+ } else if (textContentElementPattern.test(tagName)) {
310
+ const contentEnd = findTextContentEnd(html, end, tagName);
311
+ if (contentEnd === -1) {
312
+ neutralized.unclosed = true;
313
+ result += escapeLessThan(tag);
314
+ } else {
315
+ result += tag + escapeLessThan(html.slice(end, contentEnd));
316
+ index = contentEnd;
317
+ }
318
+ } else result += tag;
319
+ continue;
320
+ }
321
+ commentPattern.lastIndex = lessThan;
322
+ if (commentPattern.test(html)) {
323
+ result += html.slice(lessThan, commentPattern.lastIndex);
324
+ index = commentPattern.lastIndex;
325
+ continue;
326
+ }
327
+ if (html.startsWith("<!--", lessThan)) neutralized.unclosed = true;
328
+ result += "&lt;";
329
+ }
330
+ result += html.slice(index);
331
+ if (neutralized.eventHandler) warn("Potentially dangerous event handlers detected in translation. Consider removing onclick, onerror, etc. from your translation messages.");
332
+ if (neutralized.srcdoc) warn("Potentially dangerous srcdoc attribute detected in translation. Consider removing srcdoc from your translation messages.");
333
+ if (neutralized.element) warn("Potentially dangerous element (<base>, <animate>, <set>, <script> or <plaintext>) detected in translation. Consider removing it from your translation messages.");
334
+ if (neutralized.unclosed) warn("Unclosed tag, comment or element (such as <textarea>) detected in translation. Consider closing it in your translation messages.");
335
+ return result;
336
+ }
337
+ // packages/shared/src/messages.ts
150
338
  const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val);
151
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
152
339
  function deepCopy(src, des) {
153
- // src and des should both be objects, and none of them can be a array
154
- if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {
155
- throw new Error('Invalid value');
156
- }
157
- const stack = [{ src, des }];
158
- while (stack.length) {
159
- const { src, des } = stack.pop();
160
- // using `Object.keys` which skips prototype properties
161
- Object.keys(src).forEach(key => {
162
- if (key === '__proto__') {
163
- return;
164
- }
165
- // if src[key] is an object/array, set des[key]
166
- // to empty object/array to prevent setting by reference
167
- if (isObject(src[key]) && !isObject(des[key])) {
168
- des[key] = Array.isArray(src[key]) ? [] : create();
169
- }
170
- if (isNotObjectOrIsArray(des[key]) || isNotObjectOrIsArray(src[key])) {
171
- // replace with src[key] when:
172
- // src[key] or des[key] is not an object, or
173
- // src[key] or des[key] is an array
174
- des[key] = src[key];
175
- }
176
- else {
177
- // src[key] and des[key] are both objects, merge them
178
- stack.push({ src: src[key], des: des[key] });
179
- }
180
- });
181
- }
182
- }
183
-
340
+ if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des) || des === Object.prototype) throw new Error("Invalid value");
341
+ const stack = [src, des];
342
+ while (stack.length) {
343
+ const des = stack.pop();
344
+ const src = stack.pop();
345
+ const keys = Object.keys(src);
346
+ for (let i = 0; i < keys.length; i++) {
347
+ const key = keys[i];
348
+ if (key === "__proto__") continue;
349
+ const value = src[key];
350
+ if (!isObject(value)) {
351
+ des[key] = value;
352
+ continue;
353
+ }
354
+ if (isArray(value)) {
355
+ const copied = [];
356
+ copied.length = value.length;
357
+ des[key] = copied;
358
+ stack.push(value, copied);
359
+ continue;
360
+ }
361
+ let desValue = des[key];
362
+ if (!isObject(desValue) || isArray(desValue)) desValue = des[key] = create();
363
+ stack.push(value, desValue);
364
+ }
365
+ }
366
+ }
367
+ // packages/message-compiler/src/errors.ts
184
368
  const CompileErrorCodes = {
185
- // tokenizer error codes
186
- EXPECTED_TOKEN: 1,
187
- INVALID_TOKEN_IN_PLACEHOLDER: 2,
188
- UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
189
- UNKNOWN_ESCAPE_SEQUENCE: 4,
190
- INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
191
- UNBALANCED_CLOSING_BRACE: 6,
192
- UNTERMINATED_CLOSING_BRACE: 7,
193
- EMPTY_PLACEHOLDER: 8,
194
- NOT_ALLOW_NEST_PLACEHOLDER: 9,
195
- INVALID_LINKED_FORMAT: 10,
196
- // parser error codes
197
- MUST_HAVE_MESSAGES_IN_PLURAL: 11,
198
- UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
199
- UNEXPECTED_EMPTY_LINKED_KEY: 13,
200
- UNEXPECTED_LEXICAL_ANALYSIS: 14,
201
- // generator error codes
202
- UNHANDLED_CODEGEN_NODE_TYPE: 15,
203
- // minifier error codes
204
- UNHANDLED_MINIFIER_NODE_TYPE: 16
369
+ EXPECTED_TOKEN: 1,
370
+ INVALID_TOKEN_IN_PLACEHOLDER: 2,
371
+ UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
372
+ UNKNOWN_ESCAPE_SEQUENCE: 4,
373
+ INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
374
+ UNBALANCED_CLOSING_BRACE: 6,
375
+ UNTERMINATED_CLOSING_BRACE: 7,
376
+ EMPTY_PLACEHOLDER: 8,
377
+ NOT_ALLOW_NEST_PLACEHOLDER: 9,
378
+ INVALID_LINKED_FORMAT: 10,
379
+ MUST_HAVE_MESSAGES_IN_PLURAL: 11,
380
+ UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
381
+ UNEXPECTED_EMPTY_LINKED_KEY: 13,
382
+ UNEXPECTED_LEXICAL_ANALYSIS: 14,
383
+ UNHANDLED_CODEGEN_NODE_TYPE: 15,
384
+ UNHANDLED_MINIFIER_NODE_TYPE: 16
205
385
  };
206
- // Special value for higher-order compilers to pick up the last code
207
- // to avoid collision of error codes.
208
- // This should always be kept as the last item.
209
- const COMPILE_ERROR_CODES_EXTEND_POINT = 17;
210
386
  /** @internal */
211
387
  const errorMessages$1 = {
212
- // tokenizer error messages
213
- [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
214
- [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
215
- [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
216
- [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
217
- [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
218
- [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
219
- [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
220
- [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
221
- [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
222
- [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
223
- // parser error messages
224
- [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
225
- [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
226
- [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
227
- [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,
228
- // generator error messages
229
- [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,
230
- // minimizer error messages
231
- [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`
388
+ [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
389
+ [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
390
+ [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
391
+ [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
392
+ [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
393
+ [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
394
+ [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
395
+ [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
396
+ [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
397
+ [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
398
+ [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
399
+ [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
400
+ [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
401
+ [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,
402
+ [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,
403
+ [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`
232
404
  };
233
405
  function createCompileError(code, loc, options = {}) {
234
- const { domain, messages, args } = options;
235
- const msg = format$1((messages || errorMessages$1)[code] || '', ...(args || []))
236
- ;
237
- const error = new SyntaxError(String(msg));
238
- error.code = code;
239
- if (loc) {
240
- error.location = loc;
241
- }
242
- error.domain = domain;
243
- return error;
244
- }
245
-
246
- function format(ast) {
247
- const msg = (ctx) => formatParts(ctx, ast);
248
- return msg;
406
+ const { domain, messages, args } = options;
407
+ const msg = format$1((messages || errorMessages$1)[code] || "", ...args || []);
408
+ const error = new SyntaxError(String(msg));
409
+ error.code = code;
410
+ if (loc) error.location = loc;
411
+ error.domain = domain;
412
+ return error;
413
+ }
414
+ // packages/core-base/src/ast.ts
415
+ function isMessageAST(val) {
416
+ return isObject(val) && resolveType(val) === 0 && (hasOwn(val, "b") || hasOwn(val, "body"));
249
417
  }
250
- function formatParts(ctx, ast) {
251
- const body = resolveBody(ast);
252
- if (body == null) {
253
- throw createUnhandleNodeError(0 /* NodeTypes.Resource */);
254
- }
255
- const type = resolveType(body);
256
- if (type === 1 /* NodeTypes.Plural */) {
257
- const plural = body;
258
- const cases = resolveCases(plural);
259
- return ctx.plural(cases.reduce((messages, c) => [
260
- ...messages,
261
- formatMessageParts(ctx, c)
262
- ], []));
263
- }
264
- else {
265
- return formatMessageParts(ctx, body);
266
- }
267
- }
268
- const PROPS_BODY = ['b', 'body'];
418
+ const PROPS_BODY = ["b", "body"];
269
419
  function resolveBody(node) {
270
- return resolveProps(node, PROPS_BODY);
420
+ return resolveProps(node, PROPS_BODY);
271
421
  }
272
- const PROPS_CASES = ['c', 'cases'];
422
+ const PROPS_CASES = ["c", "cases"];
273
423
  function resolveCases(node) {
274
- return resolveProps(node, PROPS_CASES, []);
424
+ return resolveProps(node, PROPS_CASES, []);
275
425
  }
276
- function formatMessageParts(ctx, node) {
277
- const static_ = resolveStatic(node);
278
- if (static_ != null) {
279
- return ctx.type === 'text'
280
- ? static_
281
- : ctx.normalize([static_]);
282
- }
283
- else {
284
- const messages = resolveItems(node).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
285
- return ctx.normalize(messages);
286
- }
287
- }
288
- const PROPS_STATIC = ['s', 'static'];
426
+ const PROPS_STATIC = ["s", "static"];
289
427
  function resolveStatic(node) {
290
- return resolveProps(node, PROPS_STATIC);
428
+ return resolveProps(node, PROPS_STATIC);
291
429
  }
292
- const PROPS_ITEMS = ['i', 'items'];
430
+ const PROPS_ITEMS = ["i", "items"];
293
431
  function resolveItems(node) {
294
- return resolveProps(node, PROPS_ITEMS, []);
432
+ return resolveProps(node, PROPS_ITEMS, []);
295
433
  }
296
- function formatMessagePart(ctx, node) {
297
- const type = resolveType(node);
298
- switch (type) {
299
- case 3 /* NodeTypes.Text */: {
300
- return resolveValue$1(node, type);
301
- }
302
- case 9 /* NodeTypes.Literal */: {
303
- return resolveValue$1(node, type);
304
- }
305
- case 4 /* NodeTypes.Named */: {
306
- const named = node;
307
- if (hasOwn(named, 'k') && named.k) {
308
- return ctx.interpolate(ctx.named(named.k));
309
- }
310
- if (hasOwn(named, 'key') && named.key) {
311
- return ctx.interpolate(ctx.named(named.key));
312
- }
313
- throw createUnhandleNodeError(type);
314
- }
315
- case 5 /* NodeTypes.List */: {
316
- const list = node;
317
- if (hasOwn(list, 'i') && isNumber(list.i)) {
318
- return ctx.interpolate(ctx.list(list.i));
319
- }
320
- if (hasOwn(list, 'index') && isNumber(list.index)) {
321
- return ctx.interpolate(ctx.list(list.index));
322
- }
323
- throw createUnhandleNodeError(type);
324
- }
325
- case 6 /* NodeTypes.Linked */: {
326
- const linked = node;
327
- const modifier = resolveLinkedModifier(linked);
328
- const key = resolveLinkedKey(linked);
329
- return ctx.linked(formatMessagePart(ctx, key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);
330
- }
331
- case 7 /* NodeTypes.LinkedKey */: {
332
- return resolveValue$1(node, type);
333
- }
334
- case 8 /* NodeTypes.LinkedModifier */: {
335
- return resolveValue$1(node, type);
336
- }
337
- default:
338
- throw new Error(`unhandled node on format message part: ${type}`);
339
- }
340
- }
341
- const PROPS_TYPE = ['t', 'type'];
434
+ const PROPS_TYPE = ["t", "type"];
342
435
  function resolveType(node) {
343
- return resolveProps(node, PROPS_TYPE);
436
+ return resolveProps(node, PROPS_TYPE);
344
437
  }
345
- const PROPS_VALUE = ['v', 'value'];
438
+ const PROPS_VALUE = ["v", "value"];
346
439
  function resolveValue$1(node, type) {
347
- const resolved = resolveProps(node, PROPS_VALUE);
348
- if (resolved != null) {
349
- return resolved;
350
- }
351
- else {
352
- throw createUnhandleNodeError(type);
353
- }
354
- }
355
- const PROPS_MODIFIER = ['m', 'modifier'];
440
+ const resolved = resolveProps(node, PROPS_VALUE);
441
+ if (resolved != null) return resolved;
442
+ else throw createUnhandleNodeError(type);
443
+ }
444
+ const PROPS_MODIFIER = ["m", "modifier"];
356
445
  function resolveLinkedModifier(node) {
357
- return resolveProps(node, PROPS_MODIFIER);
446
+ return resolveProps(node, PROPS_MODIFIER);
358
447
  }
359
- const PROPS_KEY = ['k', 'key'];
448
+ const PROPS_KEY = ["k", "key"];
360
449
  function resolveLinkedKey(node) {
361
- const resolved = resolveProps(node, PROPS_KEY);
362
- if (resolved) {
363
- return resolved;
364
- }
365
- else {
366
- throw createUnhandleNodeError(6 /* NodeTypes.Linked */);
367
- }
450
+ const resolved = resolveProps(node, PROPS_KEY);
451
+ if (resolved) return resolved;
452
+ else throw createUnhandleNodeError(6);
368
453
  }
369
454
  function resolveProps(node, props, defaultValue) {
370
- for (let i = 0; i < props.length; i++) {
371
- const prop = props[i];
372
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
373
- if (hasOwn(node, prop) && node[prop] != null) {
374
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
375
- return node[prop];
376
- }
377
- }
378
- return defaultValue;
379
- }
455
+ for (let i = 0; i < props.length; i++) {
456
+ const prop = props[i];
457
+ if (hasOwn(node, prop) && node[prop] != null) return node[prop];
458
+ }
459
+ return defaultValue;
460
+ }
461
+ const AST_NODE_PROPS_KEYS = [
462
+ ...PROPS_BODY,
463
+ ...PROPS_CASES,
464
+ ...PROPS_STATIC,
465
+ ...PROPS_ITEMS,
466
+ ...PROPS_KEY,
467
+ ...PROPS_MODIFIER,
468
+ ...PROPS_VALUE,
469
+ ...PROPS_TYPE
470
+ ];
380
471
  function createUnhandleNodeError(type) {
381
- return new Error(`unhandled node type: ${type}`);
472
+ return /* @__PURE__ */ new Error(`unhandled node type: ${type}`);
473
+ }
474
+ // packages/core-base/src/format.ts
475
+ function format(ast) {
476
+ return (ctx) => formatParts(ctx, ast);
477
+ }
478
+ function formatParts(ctx, ast) {
479
+ const body = resolveBody(ast);
480
+ if (body == null) throw createUnhandleNodeError(0);
481
+ if (resolveType(body) === 1) {
482
+ const cases = resolveCases(body);
483
+ return ctx.plural(cases.reduce((messages, c) => [...isArray(messages) ? messages : [messages], formatMessageParts(ctx, c)], []));
484
+ } else return formatMessageParts(ctx, body);
382
485
  }
383
-
486
+ function formatMessageParts(ctx, node) {
487
+ const static_ = resolveStatic(node);
488
+ if (static_ != null) return ctx.type === "text" ? static_ : ctx.normalize([static_]);
489
+ else {
490
+ const messages = resolveItems(node).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
491
+ return ctx.normalize(messages);
492
+ }
493
+ }
494
+ function formatMessagePart(ctx, node) {
495
+ const type = resolveType(node);
496
+ switch (type) {
497
+ case 3: return resolveValue$1(node, type);
498
+ case 9: return resolveValue$1(node, type);
499
+ case 4: {
500
+ const named = node;
501
+ if (hasOwn(named, "k") && named.k) return ctx.interpolate(ctx.named(named.k));
502
+ if (hasOwn(named, "key") && named.key) return ctx.interpolate(ctx.named(named.key));
503
+ throw createUnhandleNodeError(type);
504
+ }
505
+ case 5: {
506
+ const list = node;
507
+ if (hasOwn(list, "i") && isNumber(list.i)) return ctx.interpolate(ctx.list(list.i));
508
+ if (hasOwn(list, "index") && isNumber(list.index)) return ctx.interpolate(ctx.list(list.index));
509
+ throw createUnhandleNodeError(type);
510
+ }
511
+ case 6: {
512
+ const linked = node;
513
+ const modifier = resolveLinkedModifier(linked);
514
+ const key = resolveLinkedKey(linked);
515
+ return ctx.linked(formatMessagePart(ctx, key), modifier ? formatMessagePart(ctx, modifier) : void 0, ctx.type);
516
+ }
517
+ case 7: return resolveValue$1(node, type);
518
+ case 8: return resolveValue$1(node, type);
519
+ default: throw new Error(`unhandled node on format message part: ${type}`);
520
+ }
521
+ }
522
+ // packages/core-base/src/compilation.ts
384
523
  let compileCache = create();
385
524
  function clearCompileCache() {
386
- compileCache = create();
387
- }
388
- function isMessageAST(val) {
389
- return (isObject(val) &&
390
- resolveType(val) === 0 &&
391
- (hasOwn(val, 'b') || hasOwn(val, 'body')));
525
+ compileCache = create();
392
526
  }
393
527
  /* #__NO_SIDE_EFFECTS__ */
394
528
  function compile(message, context) {
395
- {
396
- if (!isMessageAST(message)) {
397
- warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);
398
- return (() => message);
399
- }
400
- // AST case (passed from bundler)
401
- const cacheKey = message.cacheKey;
402
- if (cacheKey) {
403
- const cached = compileCache[cacheKey];
404
- if (cached) {
405
- return cached;
406
- }
407
- // compose message function from message (AST)
408
- return (compileCache[cacheKey] =
409
- format(message));
410
- }
411
- else {
412
- return format(message);
413
- }
414
- }
415
- }
416
-
417
- let devtools = null;
418
- function setDevToolsHook(hook) {
419
- devtools = hook;
420
- }
421
- function getDevToolsHook() {
422
- return devtools;
423
- }
424
- function initI18nDevTools(i18n, version, meta) {
425
- // TODO: queue if devtools is undefined
426
- devtools &&
427
- devtools.emit('i18n:init', {
428
- timestamp: Date.now(),
429
- i18n,
430
- version,
431
- meta
432
- });
433
- }
434
- const translateDevTools =
435
- /* #__PURE__*/ createDevToolsHook('function:translate');
436
- function createDevToolsHook(hook) {
437
- return (payloads) => devtools && devtools.emit(hook, payloads);
438
- }
439
-
529
+ {
530
+ if (!isMessageAST(message)) {
531
+ warn(`Cannot compile the message of '${context.key}' key, because the message compiler is not included in this build. Pre-compile the message. So translate function returns the message as is.`);
532
+ return (() => message);
533
+ }
534
+ const cacheKey = message.cacheKey;
535
+ if (cacheKey) {
536
+ const cached = compileCache[cacheKey];
537
+ if (cached) return cached;
538
+ return compileCache[cacheKey] = format(message);
539
+ } else return format(message);
540
+ }
541
+ }
542
+ // packages/core-base/src/errors.ts
440
543
  const CoreErrorCodes = {
441
- INVALID_ARGUMENT: COMPILE_ERROR_CODES_EXTEND_POINT, // 17
442
- INVALID_DATE_ARGUMENT: 18,
443
- INVALID_ISO_DATE_ARGUMENT: 19,
444
- NOT_SUPPORT_NON_STRING_MESSAGE: 20,
445
- NOT_SUPPORT_LOCALE_PROMISE_VALUE: 21,
446
- NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: 22,
447
- NOT_SUPPORT_LOCALE_TYPE: 23
544
+ INVALID_ARGUMENT: 17,
545
+ INVALID_DATE_ARGUMENT: 18,
546
+ INVALID_ISO_DATE_ARGUMENT: 19,
547
+ NOT_SUPPORT_LOCALE_PROMISE_VALUE: 20,
548
+ NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: 21,
549
+ NOT_SUPPORT_LOCALE_TYPE: 22
448
550
  };
449
- const CORE_ERROR_CODES_EXTEND_POINT = 24;
551
+ const CORE_ERROR_CODES_EXTEND_POINT = 23;
450
552
  function createCoreError(code) {
451
- return createCompileError(code, null, { messages: errorMessages } );
553
+ return createCompileError(code, null, { messages: errorMessages });
452
554
  }
453
555
  /** @internal */
454
556
  const errorMessages = {
455
- [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
456
- [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
457
- 'Make sure your Date represents a valid date.',
458
- [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string',
459
- [CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE]: 'Not support non-string message',
460
- [CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE]: 'cannot support promise value',
461
- [CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]: 'cannot support async function',
462
- [CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE]: 'cannot support locale type'
557
+ [CoreErrorCodes.INVALID_ARGUMENT]: "Invalid arguments",
558
+ [CoreErrorCodes.INVALID_DATE_ARGUMENT]: "The date provided is an invalid Date object.Make sure your Date represents a valid date.",
559
+ [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: "The argument provided is not a valid ISO date string",
560
+ [CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE]: "cannot support promise value",
561
+ [CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]: "cannot support async function",
562
+ [CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE]: "cannot support locale type"
463
563
  };
464
-
564
+ // packages/core-base/src/fallbacker.ts
465
565
  /** @internal */
466
566
  function getLocale(context, options) {
467
- return options.locale != null
468
- ? resolveLocale(options.locale)
469
- : resolveLocale(context.locale);
567
+ return options.locale != null ? resolveLocale(options.locale) : resolveLocale(context.locale);
470
568
  }
471
569
  let _resolveLocale;
472
570
  /** @internal */
473
571
  function resolveLocale(locale) {
474
- if (isString(locale)) {
475
- return locale;
476
- }
477
- else {
478
- if (isFunction(locale)) {
479
- if (locale.resolvedOnce && _resolveLocale != null) {
480
- return _resolveLocale;
481
- }
482
- else if (locale.constructor.name === 'Function') {
483
- const resolve = locale();
484
- if (isPromise(resolve)) {
485
- throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);
486
- }
487
- return (_resolveLocale = resolve);
488
- }
489
- else {
490
- throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);
491
- }
492
- }
493
- else {
494
- throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);
495
- }
496
- }
572
+ if (isString(locale)) return locale;
573
+ else if (isFunction(locale)) {
574
+ if (locale.resolvedOnce && _resolveLocale != null) return _resolveLocale;
575
+ else if (locale.constructor.name === "Function") {
576
+ const resolve = locale();
577
+ if (isPromise(resolve)) throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);
578
+ return _resolveLocale = resolve;
579
+ } else throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);
580
+ } else throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);
497
581
  }
498
582
  /**
499
- * Fallback with simple implemenation
500
- *
501
- * @remarks
502
- * A fallback locale function implemented with a simple fallback algorithm.
503
- *
504
- * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
505
- *
506
- * @param ctx - A {@link CoreContext | context}
507
- * @param fallback - A {@link FallbackLocale | fallback locale}
508
- * @param start - A starting {@link Locale | locale}
509
- *
510
- * @returns Fallback locales
511
- *
512
- * @VueI18nGeneral
513
- */
514
- function fallbackWithSimple(ctx, fallback, start) {
515
- // prettier-ignore
516
- return [...new Set([
517
- start,
518
- ...(isArray(fallback)
519
- ? fallback
520
- : isObject(fallback)
521
- ? Object.keys(fallback)
522
- : isString(fallback)
523
- ? [fallback]
524
- : [start])
525
- ])];
583
+ * Fallback with simple implemenation
584
+ *
585
+ * @remarks
586
+ * A fallback locale function implemented with a simple fallback algorithm.
587
+ *
588
+ * Basically, the chain consists of `start` plus the specified fallback: for a string or array `fallbackLocale`, the value as specified in the props is used; for a map `fallbackLocale`, the map's **keys** are used and the `default` key is skipped since it is not a locale name.
589
+ *
590
+ * @param ctx - A {@link CoreContext | context}
591
+ * @param fallback - A {@link FallbackLocale | fallback locale}
592
+ * @param start - A starting {@link Locale | locale}
593
+ *
594
+ * @returns Fallback locales
595
+ *
596
+ * @VueI18nGeneral
597
+ */
598
+ function fallbackWithSimple(_ctx, fallback, start) {
599
+ return [.../* @__PURE__ */ new Set([start, ...isArray(fallback) ? fallback : isObject(fallback) ? Object.keys(fallback).filter((locale) => locale !== "default") : isString(fallback) ? [fallback] : [start]])];
526
600
  }
527
601
  /**
528
- * Fallback with locale chain
529
- *
530
- * @remarks
531
- * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
532
- *
533
- * @param ctx - A {@link CoreContext | context}
534
- * @param fallback - A {@link FallbackLocale | fallback locale}
535
- * @param start - A starting {@link Locale | locale}
536
- *
537
- * @returns Fallback locales
538
- *
539
- * @VueI18nSee [Fallbacking](../../guide/essentials/fallback)
540
- *
541
- * @VueI18nGeneral
542
- */
602
+ * Fallback with locale chain
603
+ *
604
+ * @remarks
605
+ * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
606
+ *
607
+ * Chains are cached per fallback identity. If you mutate an object or array fallback in place,
608
+ * pass a new object or array instead so that the chain is recomputed.
609
+ *
610
+ * @param ctx - A {@link CoreContext | context}
611
+ * @param fallback - A {@link FallbackLocale | fallback locale}
612
+ * @param start - A starting {@link Locale | locale}
613
+ *
614
+ * @returns Fallback locales
615
+ *
616
+ * @VueI18nSee [Fallbacking](../../guide/essentials/fallback)
617
+ *
618
+ * @VueI18nGeneral
619
+ */
543
620
  function fallbackWithLocaleChain(ctx, fallback, start) {
544
- const startLocale = isString(start) ? start : DEFAULT_LOCALE;
545
- const context = ctx;
546
- if (!context.__localeChainCache) {
547
- context.__localeChainCache = new Map();
548
- }
549
- let chain = context.__localeChainCache.get(startLocale);
550
- if (!chain) {
551
- chain = [];
552
- // first block defined by start
553
- let block = [start];
554
- // while any intervening block found
555
- while (isArray(block)) {
556
- block = appendBlockToChain(chain, block, fallback);
557
- }
558
- // prettier-ignore
559
- // last block defined by default
560
- const defaults = isArray(fallback) || !isPlainObject(fallback)
561
- ? fallback
562
- : fallback['default']
563
- ? fallback['default']
564
- : null;
565
- // convert defaults to array
566
- block = isString(defaults) ? [defaults] : defaults;
567
- if (isArray(block)) {
568
- appendBlockToChain(chain, block, false);
569
- }
570
- context.__localeChainCache.set(startLocale, chain);
571
- }
572
- return chain;
621
+ const startLocale = isString(start) ? start : DEFAULT_LOCALE;
622
+ const context = ctx;
623
+ let chains;
624
+ if (isObject(fallback)) {
625
+ if (!context.__localeChainObjectCache) context.__localeChainObjectCache = /* @__PURE__ */ new WeakMap();
626
+ chains = context.__localeChainObjectCache.get(fallback);
627
+ if (!chains) {
628
+ chains = /* @__PURE__ */ new Map();
629
+ context.__localeChainObjectCache.set(fallback, chains);
630
+ }
631
+ } else {
632
+ if (!context.__localeChainCache) context.__localeChainCache = /* @__PURE__ */ new Map();
633
+ chains = context.__localeChainCache.get(fallback);
634
+ if (!chains) {
635
+ chains = /* @__PURE__ */ new Map();
636
+ context.__localeChainCache.set(fallback, chains);
637
+ }
638
+ }
639
+ const cached = chains.get(startLocale);
640
+ if (cached) return cached;
641
+ const chain = [];
642
+ let block = [start];
643
+ while (isArray(block)) block = appendBlockToChain(chain, block, fallback);
644
+ const defaults = isArray(fallback) || !isPlainObject(fallback) ? fallback : fallback["default"] ? fallback["default"] : null;
645
+ block = isString(defaults) ? [defaults] : defaults;
646
+ if (isArray(block)) appendBlockToChain(chain, block, false);
647
+ chains.set(startLocale, chain);
648
+ return chain;
573
649
  }
574
650
  function appendBlockToChain(chain, block, blocks) {
575
- let follow = true;
576
- for (let i = 0; i < block.length && isBoolean(follow); i++) {
577
- const locale = block[i];
578
- if (isString(locale)) {
579
- follow = appendLocaleToChain(chain, block[i], blocks);
580
- }
581
- }
582
- return follow;
651
+ let follow = true;
652
+ for (let i = 0; i < block.length && isBoolean(follow); i++) {
653
+ const locale = block[i];
654
+ if (isString(locale)) follow = appendLocaleToChain(chain, block[i], blocks);
655
+ }
656
+ return follow;
583
657
  }
584
658
  function appendLocaleToChain(chain, locale, blocks) {
585
- let follow;
586
- const tokens = locale.split('-');
587
- do {
588
- const target = tokens.join('-');
589
- follow = appendItemToChain(chain, target, blocks);
590
- tokens.splice(-1, 1);
591
- } while (tokens.length && follow === true);
592
- return follow;
659
+ let follow;
660
+ const tokens = locale.split("-");
661
+ do {
662
+ follow = appendItemToChain(chain, tokens.join("-"), blocks);
663
+ tokens.splice(-1, 1);
664
+ } while (tokens.length && follow === true);
665
+ return follow;
593
666
  }
594
667
  function appendItemToChain(chain, target, blocks) {
595
- let follow = false;
596
- if (!chain.includes(target)) {
597
- follow = true;
598
- if (target) {
599
- follow = target[target.length - 1] !== '!';
600
- const locale = target.replace(/!/g, '');
601
- chain.push(locale);
602
- if ((isArray(blocks) || isPlainObject(blocks)) &&
603
- blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
604
- ) {
605
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
606
- follow = blocks[locale];
607
- }
608
- }
609
- }
610
- return follow;
611
- }
612
-
668
+ let follow = false;
669
+ if (!chain.includes(target)) {
670
+ follow = true;
671
+ if (target) {
672
+ follow = target[target.length - 1] !== "!";
673
+ const locale = target.replace(/!/g, "");
674
+ chain.push(locale);
675
+ if ((isArray(blocks) || isPlainObject(blocks)) && blocks[locale]) follow = blocks[locale];
676
+ }
677
+ }
678
+ return follow;
679
+ }
680
+ // packages/core-base/src/resolver.ts
613
681
  const pathStateMachine = [];
614
- pathStateMachine[0 /* States.BEFORE_PATH */] = {
615
- ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
616
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
617
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
618
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
682
+ pathStateMachine[0] = {
683
+ ["w"]: [0],
684
+ ["i"]: [3, 0],
685
+ ["["]: [4],
686
+ ["o"]: [7]
619
687
  };
620
- pathStateMachine[1 /* States.IN_PATH */] = {
621
- ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
622
- ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
623
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
624
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
688
+ pathStateMachine[1] = {
689
+ ["w"]: [1],
690
+ ["."]: [2],
691
+ ["["]: [4],
692
+ ["o"]: [7]
625
693
  };
626
- pathStateMachine[2 /* States.BEFORE_IDENT */] = {
627
- ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
628
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
629
- ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
694
+ pathStateMachine[2] = {
695
+ ["w"]: [2],
696
+ ["i"]: [3, 0],
697
+ ["0"]: [3, 0]
630
698
  };
631
- pathStateMachine[3 /* States.IN_IDENT */] = {
632
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
633
- ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
634
- ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
635
- ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
636
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
637
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
699
+ pathStateMachine[3] = {
700
+ ["i"]: [3, 0],
701
+ ["0"]: [3, 0],
702
+ ["w"]: [1, 1],
703
+ ["."]: [2, 1],
704
+ ["["]: [4, 1],
705
+ ["o"]: [7, 1]
638
706
  };
639
- pathStateMachine[4 /* States.IN_SUB_PATH */] = {
640
- ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
641
- ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
642
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [
643
- 4 /* States.IN_SUB_PATH */,
644
- 2 /* Actions.INC_SUB_PATH_DEPTH */
645
- ],
646
- ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
647
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
648
- ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
707
+ pathStateMachine[4] = {
708
+ ["'"]: [5, 0],
709
+ ["\""]: [6, 0],
710
+ ["["]: [4, 2],
711
+ ["]"]: [1, 3],
712
+ ["o"]: 8,
713
+ ["l"]: [4, 0]
649
714
  };
650
- pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
651
- ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
652
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
653
- ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
715
+ pathStateMachine[5] = {
716
+ ["'"]: [4, 0],
717
+ ["o"]: 8,
718
+ ["l"]: [5, 0]
654
719
  };
655
- pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
656
- ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
657
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
658
- ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
720
+ pathStateMachine[6] = {
721
+ ["\""]: [4, 0],
722
+ ["o"]: 8,
723
+ ["l"]: [6, 0]
659
724
  };
660
725
  /**
661
- * Check if an expression is a literal value.
662
- */
726
+ * Check if an expression is a literal value.
727
+ */
663
728
  const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
664
729
  function isLiteral(exp) {
665
- return literalValueRE.test(exp);
730
+ return literalValueRE.test(exp);
666
731
  }
667
732
  /**
668
- * Strip quotes from a string
669
- */
733
+ * Strip quotes from a string
734
+ */
670
735
  function stripQuotes(str) {
671
- const a = str.charCodeAt(0);
672
- const b = str.charCodeAt(str.length - 1);
673
- return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
736
+ const a = str.charCodeAt(0);
737
+ return a === str.charCodeAt(str.length - 1) && (a === 34 || a === 39) ? str.slice(1, -1) : str;
674
738
  }
675
739
  /**
676
- * Determine the type of a character in a keypath.
677
- */
740
+ * Determine the type of a character in a keypath.
741
+ */
678
742
  function getPathCharType(ch) {
679
- if (ch === undefined || ch === null) {
680
- return "o" /* PathCharTypes.END_OF_FAIL */;
681
- }
682
- const code = ch.charCodeAt(0);
683
- switch (code) {
684
- case 0x5b: // [
685
- case 0x5d: // ]
686
- case 0x2e: // .
687
- case 0x22: // "
688
- case 0x27: // '
689
- return ch;
690
- case 0x5f: // _
691
- case 0x24: // $
692
- case 0x2d: // -
693
- return "i" /* PathCharTypes.IDENT */;
694
- case 0x09: // Tab (HT)
695
- case 0x0a: // Newline (LF)
696
- case 0x0d: // Return (CR)
697
- case 0xa0: // No-break space (NBSP)
698
- case 0xfeff: // Byte Order Mark (BOM)
699
- case 0x2028: // Line Separator (LS)
700
- case 0x2029: // Paragraph Separator (PS)
701
- return "w" /* PathCharTypes.WORKSPACE */;
702
- }
703
- return "i" /* PathCharTypes.IDENT */;
743
+ if (ch === void 0 || ch === null) return "o";
744
+ switch (ch.charCodeAt(0)) {
745
+ case 91:
746
+ case 93:
747
+ case 46:
748
+ case 34:
749
+ case 39: return ch;
750
+ case 95:
751
+ case 36:
752
+ case 45: return "i";
753
+ case 9:
754
+ case 10:
755
+ case 13:
756
+ case 160:
757
+ case 65279:
758
+ case 8232:
759
+ case 8233: return "w";
760
+ }
761
+ return "i";
704
762
  }
705
763
  /**
706
- * Format a subPath, return its plain form if it is
707
- * a literal string or number. Otherwise prepend the
708
- * dynamic indicator (*).
709
- */
764
+ * Format a subPath, return its plain form if it is
765
+ * a literal string or number. Otherwise prepend the
766
+ * dynamic indicator (*).
767
+ */
710
768
  function formatSubPath(path) {
711
- const trimmed = path.trim();
712
- // invalid leading 0
713
- if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
714
- return false;
715
- }
716
- return isLiteral(trimmed)
717
- ? stripQuotes(trimmed)
718
- : "*" /* PathCharTypes.ASTARISK */ + trimmed;
769
+ const trimmed = path.trim();
770
+ if (path.charAt(0) === "0" && isNaN(parseInt(path))) return false;
771
+ return isLiteral(trimmed) ? stripQuotes(trimmed) : "*" + trimmed;
719
772
  }
720
773
  /**
721
- * Parse a string path into an array of segments
722
- */
774
+ * Parse a string path into an array of segments
775
+ */
723
776
  function parse(path) {
724
- const keys = [];
725
- let index = -1;
726
- let mode = 0 /* States.BEFORE_PATH */;
727
- let subPathDepth = 0;
728
- let c;
729
- let key; // eslint-disable-line
730
- let newChar;
731
- let type;
732
- let transition;
733
- let action;
734
- let typeMap;
735
- const actions = [];
736
- actions[0 /* Actions.APPEND */] = () => {
737
- if (key === undefined) {
738
- key = newChar;
739
- }
740
- else {
741
- key += newChar;
742
- }
743
- };
744
- actions[1 /* Actions.PUSH */] = () => {
745
- if (key !== undefined) {
746
- keys.push(key);
747
- key = undefined;
748
- }
749
- };
750
- actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
751
- actions[0 /* Actions.APPEND */]();
752
- subPathDepth++;
753
- };
754
- actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
755
- if (subPathDepth > 0) {
756
- subPathDepth--;
757
- mode = 4 /* States.IN_SUB_PATH */;
758
- actions[0 /* Actions.APPEND */]();
759
- }
760
- else {
761
- subPathDepth = 0;
762
- if (key === undefined) {
763
- return false;
764
- }
765
- key = formatSubPath(key);
766
- if (key === false) {
767
- return false;
768
- }
769
- else {
770
- actions[1 /* Actions.PUSH */]();
771
- }
772
- }
773
- };
774
- function maybeUnescapeQuote() {
775
- const nextChar = path[index + 1];
776
- if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
777
- nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
778
- (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
779
- nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
780
- index++;
781
- newChar = '\\' + nextChar;
782
- actions[0 /* Actions.APPEND */]();
783
- return true;
784
- }
785
- }
786
- while (mode !== null) {
787
- index++;
788
- c = path[index];
789
- if (c === '\\' && maybeUnescapeQuote()) {
790
- continue;
791
- }
792
- type = getPathCharType(c);
793
- typeMap = pathStateMachine[mode];
794
- transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
795
- // check parse error
796
- if (transition === 8 /* States.ERROR */) {
797
- return;
798
- }
799
- mode = transition[0];
800
- if (transition[1] !== undefined) {
801
- action = actions[transition[1]];
802
- if (action) {
803
- newChar = c;
804
- if (action() === false) {
805
- return;
806
- }
807
- }
808
- }
809
- // check parse finish
810
- if (mode === 7 /* States.AFTER_PATH */) {
811
- return keys;
812
- }
813
- }
814
- }
815
- // path token cache
816
- const cache = new Map();
777
+ const keys = [];
778
+ let index = -1;
779
+ let mode = 0;
780
+ let subPathDepth = 0;
781
+ let c;
782
+ let key;
783
+ let newChar;
784
+ let type;
785
+ let transition;
786
+ let action;
787
+ let typeMap;
788
+ const actions = [];
789
+ actions[0] = () => {
790
+ if (key === void 0) key = newChar;
791
+ else key += newChar;
792
+ };
793
+ actions[1] = () => {
794
+ if (key !== void 0) {
795
+ keys.push(key);
796
+ key = void 0;
797
+ }
798
+ };
799
+ actions[2] = () => {
800
+ actions[0]();
801
+ subPathDepth++;
802
+ };
803
+ actions[3] = () => {
804
+ if (subPathDepth > 0) {
805
+ subPathDepth--;
806
+ mode = 4;
807
+ actions[0]();
808
+ } else {
809
+ subPathDepth = 0;
810
+ if (key === void 0) return false;
811
+ key = formatSubPath(key);
812
+ if (key === false) return false;
813
+ else actions[1]();
814
+ }
815
+ };
816
+ function maybeUnescapeQuote() {
817
+ const nextChar = path[index + 1];
818
+ if (mode === 5 && nextChar === "'" || mode === 6 && nextChar === "\"") {
819
+ index++;
820
+ newChar = "\\" + nextChar;
821
+ actions[0]();
822
+ return true;
823
+ }
824
+ }
825
+ while (mode !== null) {
826
+ index++;
827
+ c = path[index];
828
+ if (c === "\\" && maybeUnescapeQuote()) continue;
829
+ type = getPathCharType(c);
830
+ typeMap = pathStateMachine[mode];
831
+ transition = typeMap[type] || typeMap["l"] || 8;
832
+ if (transition === 8) return;
833
+ mode = transition[0];
834
+ if (transition[1] !== void 0) {
835
+ action = actions[transition[1]];
836
+ if (action) {
837
+ newChar = c;
838
+ if (action() === false) return;
839
+ }
840
+ }
841
+ if (mode === 7) return keys;
842
+ }
843
+ }
844
+ const cache = /* @__PURE__ */ new Map();
817
845
  /**
818
- * key-value message resolver
819
- *
820
- * @remarks
821
- * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
822
- *
823
- * @param obj - A target object to be resolved with path
824
- * @param path - A {@link Path | path} to resolve the value of message
825
- *
826
- * @returns A resolved {@link PathValue | path value}
827
- *
828
- * @VueI18nGeneral
829
- */
846
+ * key-value message resolver
847
+ *
848
+ * @remarks
849
+ * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
850
+ *
851
+ * @param obj - A target object to be resolved with path
852
+ * @param path - A {@link Path | path} to resolve the value of message
853
+ *
854
+ * @returns A resolved {@link PathValue | path value}
855
+ *
856
+ * @VueI18nGeneral
857
+ */
830
858
  function resolveWithKeyValue(obj, path) {
831
- return isObject(obj) ? obj[path] : null;
859
+ return isObject(obj) ? getOwn(obj, path) : null;
832
860
  }
833
861
  /**
834
- * message resolver
835
- *
836
- * @remarks
837
- * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
838
- *
839
- * @param obj - A target object to be resolved with path
840
- * @param path - A {@link Path | path} to resolve the value of message
841
- *
842
- * @returns A resolved {@link PathValue | path value}
843
- *
844
- * @VueI18nGeneral
845
- */
862
+ * message resolver
863
+ *
864
+ * @remarks
865
+ * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
866
+ *
867
+ * @param obj - A target object to be resolved with path
868
+ * @param path - A {@link Path | path} to resolve the value of message
869
+ *
870
+ * @returns A resolved {@link PathValue | path value}
871
+ *
872
+ * @VueI18nGeneral
873
+ */
846
874
  function resolveValue(obj, path) {
847
- // check object
848
- if (!isObject(obj)) {
849
- return null;
850
- }
851
- // parse path
852
- let hit = cache.get(path);
853
- if (!hit) {
854
- hit = parse(path);
855
- if (hit) {
856
- cache.set(path, hit);
857
- }
858
- }
859
- // check hit
860
- if (!hit) {
861
- return null;
862
- }
863
- // resolve path value
864
- const len = hit.length;
865
- let last = obj;
866
- let i = 0;
867
- while (i < len) {
868
- const val = last[hit[i]];
869
- if (val === undefined) {
870
- return null;
871
- }
872
- if (isFunction(last)) {
873
- return null;
874
- }
875
- last = val;
876
- i++;
877
- }
878
- return last;
879
- }
880
-
875
+ if (!isObject(obj)) return null;
876
+ let hit = cache.get(path);
877
+ if (!hit) {
878
+ hit = parse(path);
879
+ if (hit) cache.set(path, hit);
880
+ }
881
+ if (!hit) return null;
882
+ const len = hit.length;
883
+ let last = obj;
884
+ let i = 0;
885
+ while (i < len) {
886
+ const key = hit[i];
887
+ /**
888
+ * NOTE:
889
+ * if `key` is intlify message format AST node key and `last` is intlify message format AST, skip it.
890
+ * because the AST node is not a key-value structure.
891
+ */
892
+ if (AST_NODE_PROPS_KEYS.includes(key) && isMessageAST(last)) return null;
893
+ if (!isObject(last)) return null;
894
+ if (!hasOwn(last, key)) return null;
895
+ const val = last[key];
896
+ if (val === void 0) return null;
897
+ if (isFunction(last)) return null;
898
+ last = val;
899
+ i++;
900
+ }
901
+ return last;
902
+ }
903
+ // packages/core-base/src/warnings.ts
881
904
  const CoreWarnCodes = {
882
- NOT_FOUND_KEY: 1,
883
- FALLBACK_TO_TRANSLATE: 2,
884
- CANNOT_FORMAT_NUMBER: 3,
885
- FALLBACK_TO_NUMBER_FORMAT: 4,
886
- CANNOT_FORMAT_DATE: 5,
887
- FALLBACK_TO_DATE_FORMAT: 6,
888
- EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: 7
905
+ NOT_FOUND_KEY: 1,
906
+ FALLBACK_TO_TRANSLATE: 2,
907
+ CANNOT_FORMAT_NUMBER: 3,
908
+ FALLBACK_TO_NUMBER_FORMAT: 4,
909
+ CANNOT_FORMAT_DATE: 5,
910
+ FALLBACK_TO_DATE_FORMAT: 6,
911
+ EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: 7,
912
+ INVALID_NUMBER_ARGUMENT: 8,
913
+ INVALID_DATE_ARGUMENT: 9,
914
+ IGNORE_UNSAFE_LOCALE: 10,
915
+ FALLBACK_TO_DEFAULT_PLURAL_RULE: 11,
916
+ FALLBACK_FROM_INVALID_LOCALE: 12
889
917
  };
890
- const CORE_WARN_CODES_EXTEND_POINT = 8;
918
+ const CORE_WARN_CODES_EXTEND_POINT = 13;
891
919
  /** @internal */
892
920
  const warnMessages = {
893
- [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
894
- [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
895
- [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
896
- [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
897
- [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
898
- [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
899
- [CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER]: `This project is using Custom Message Compiler, which is an experimental feature. It may receive breaking changes or be removed in the future.`
921
+ [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale {resource}.`,
922
+ [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
923
+ [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
924
+ [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
925
+ [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
926
+ [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
927
+ [CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER]: `This project is using Custom Message Compiler, which is an experimental feature. It may receive breaking changes or be removed in the future.`,
928
+ [CoreWarnCodes.INVALID_NUMBER_ARGUMENT]: `Invalid argument for number formatting: expected a number but received '{value}'.`,
929
+ [CoreWarnCodes.INVALID_DATE_ARGUMENT]: `Invalid argument for datetime formatting: expected a Date, number, or ISO string but received '{value}'.`,
930
+ [CoreWarnCodes.IGNORE_UNSAFE_LOCALE]: `Ignore '{locale}' locale: it is a property name of Object.prototype`,
931
+ [CoreWarnCodes.FALLBACK_TO_DEFAULT_PLURAL_RULE]: `Fall back to the default plural rule for '{locale}' locale: Intl.PluralRules does not support it`,
932
+ [CoreWarnCodes.FALLBACK_FROM_INVALID_LOCALE]: `Fall back to '{target}' locale for {type} formatting with '{locale}' locale: it is not a BCP 47 language tag`
900
933
  };
901
934
  function getWarnMessage(code, ...args) {
902
- return format$1(warnMessages[code], ...args);
935
+ return format$1(warnMessages[code], ...args);
903
936
  }
904
-
905
- /* eslint-disable @typescript-eslint/no-explicit-any */
937
+ // packages/core-base/src/context.ts
906
938
  /**
907
- * Intlify core-base version
908
- * @internal
909
- */
910
- const VERSION = '12.0.0-alpha.1';
911
- const NOT_REOSLVED = -1;
912
- const DEFAULT_LOCALE = 'en-US';
913
- const MISSING_RESOLVE_VALUE = '';
939
+ * Intlify core-base version
940
+ * @internal
941
+ */
942
+ const VERSION = "12.0.0-alpha.10";
943
+ const NOT_RESOLVED = -1;
944
+ const DEFAULT_LOCALE = "en-US";
945
+ const MISSING_RESOLVE_VALUE = "";
914
946
  const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
915
947
  function getDefaultLinkedModifiers() {
916
- return {
917
- upper: (val, type) => {
918
- // prettier-ignore
919
- return type === 'text' && isString(val)
920
- ? val.toUpperCase()
921
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
922
- ? val.children.toUpperCase()
923
- : val;
924
- },
925
- lower: (val, type) => {
926
- // prettier-ignore
927
- return type === 'text' && isString(val)
928
- ? val.toLowerCase()
929
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
930
- ? val.children.toLowerCase()
931
- : val;
932
- },
933
- capitalize: (val, type) => {
934
- // prettier-ignore
935
- return (type === 'text' && isString(val)
936
- ? capitalize(val)
937
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
938
- ? capitalize(val.children)
939
- : val);
940
- }
941
- };
948
+ return {
949
+ upper: (val, type) => {
950
+ return type === "text" && isString(val) ? val.toUpperCase() : type === "vnode" && isObject(val) && "__v_isVNode" in val ? val.children.toUpperCase() : val;
951
+ },
952
+ lower: (val, type) => {
953
+ return type === "text" && isString(val) ? val.toLowerCase() : type === "vnode" && isObject(val) && "__v_isVNode" in val ? val.children.toLowerCase() : val;
954
+ },
955
+ capitalize: (val, type) => {
956
+ return type === "text" && isString(val) ? capitalize(val) : type === "vnode" && isObject(val) && "__v_isVNode" in val ? capitalize(val.children) : val;
957
+ }
958
+ };
942
959
  }
943
960
  let _compiler;
961
+ /**
962
+ * Register the message compiler
963
+ *
964
+ * @param compiler - A {@link MessageCompiler} function
965
+ *
966
+ * @deprecated Use `messageCompiler` option of `createI18n` or `createCoreContext` instead. This function will be removed in v13.
967
+ *
968
+ * @VueI18nGeneral
969
+ */
944
970
  function registerMessageCompiler(compiler) {
945
- _compiler = compiler;
971
+ warnOnce(`registerMessageCompiler is deprecated. Use 'messageCompiler' option of 'createI18n' or 'createCoreContext' instead.`);
972
+ _compiler = compiler;
946
973
  }
947
974
  let _resolver;
948
975
  /**
949
- * Register the message resolver
950
- *
951
- * @param resolver - A {@link MessageResolver} function
952
- *
953
- * @VueI18nGeneral
954
- */
976
+ * Register the message resolver
977
+ *
978
+ * @param resolver - A {@link MessageResolver} function
979
+ *
980
+ * @deprecated Use `messageResolver` option of `createI18n` or `createCoreContext` instead. This function will be removed in v13.
981
+ *
982
+ * @VueI18nGeneral
983
+ */
955
984
  function registerMessageResolver(resolver) {
956
- _resolver = resolver;
985
+ warnOnce(`registerMessageResolver is deprecated. Use 'messageResolver' option of 'createI18n' or 'createCoreContext' instead.`);
986
+ _resolver = resolver;
957
987
  }
958
988
  let _fallbacker;
959
989
  /**
960
- * Register the locale fallbacker
961
- *
962
- * @param fallbacker - A {@link LocaleFallbacker} function
963
- *
964
- * @VueI18nGeneral
965
- */
990
+ * Register the locale fallbacker
991
+ *
992
+ * @param fallbacker - A {@link LocaleFallbacker} function
993
+ *
994
+ * @deprecated Use `localeFallbacker` option of `createI18n` or `createCoreContext` instead. This function will be removed in v13.
995
+ *
996
+ * @VueI18nGeneral
997
+ */
966
998
  function registerLocaleFallbacker(fallbacker) {
967
- _fallbacker = fallbacker;
999
+ warnOnce(`registerLocaleFallbacker is deprecated. Use 'localeFallbacker' option of 'createI18n' or 'createCoreContext' instead.`);
1000
+ _fallbacker = fallbacker;
968
1001
  }
969
- // Additional Meta for Intlify DevTools
970
- let _additionalMeta = null;
971
- /* #__NO_SIDE_EFFECTS__ */
972
- const setAdditionalMeta = (meta) => {
973
- _additionalMeta = meta;
974
- };
975
- /* #__NO_SIDE_EFFECTS__ */
976
- const getAdditionalMeta = () => _additionalMeta;
977
- let _fallbackContext = null;
978
- const setFallbackContext = (context) => {
979
- _fallbackContext = context;
980
- };
981
- const getFallbackContext = () => _fallbackContext;
982
- // ID for CoreContext
983
1002
  let _cid = 0;
984
1003
  function createCoreContext(options = {}) {
985
- // setup options
986
- const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
987
- const version = isString(options.version) ? options.version : VERSION;
988
- const locale = isString(options.locale) || isFunction(options.locale)
989
- ? options.locale
990
- : DEFAULT_LOCALE;
991
- const _locale = isFunction(locale) ? DEFAULT_LOCALE : locale;
992
- const fallbackLocale = isArray(options.fallbackLocale) ||
993
- isPlainObject(options.fallbackLocale) ||
994
- isString(options.fallbackLocale) ||
995
- options.fallbackLocale === false
996
- ? options.fallbackLocale
997
- : _locale;
998
- const messages = isPlainObject(options.messages)
999
- ? options.messages
1000
- : createResources(_locale);
1001
- const datetimeFormats = isPlainObject(options.datetimeFormats)
1002
- ? options.datetimeFormats
1003
- : createResources(_locale)
1004
- ;
1005
- const numberFormats = isPlainObject(options.numberFormats)
1006
- ? options.numberFormats
1007
- : createResources(_locale)
1008
- ;
1009
- const modifiers = assign(create(), options.modifiers, getDefaultLinkedModifiers());
1010
- const pluralRules = options.pluralRules || create();
1011
- const missing = isFunction(options.missing) ? options.missing : null;
1012
- const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
1013
- ? options.missingWarn
1014
- : true;
1015
- const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
1016
- ? options.fallbackWarn
1017
- : true;
1018
- const fallbackFormat = !!options.fallbackFormat;
1019
- const unresolving = !!options.unresolving;
1020
- const postTranslation = isFunction(options.postTranslation)
1021
- ? options.postTranslation
1022
- : null;
1023
- const processor = isPlainObject(options.processor) ? options.processor : null;
1024
- const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
1025
- ? options.warnHtmlMessage
1026
- : true;
1027
- const escapeParameter = !!options.escapeParameter;
1028
- const messageCompiler = isFunction(options.messageCompiler)
1029
- ? options.messageCompiler
1030
- : _compiler;
1031
- if (isFunction(options.messageCompiler)) {
1032
- warnOnce(getWarnMessage(CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER));
1033
- }
1034
- const messageResolver = isFunction(options.messageResolver)
1035
- ? options.messageResolver
1036
- : _resolver || resolveWithKeyValue;
1037
- const localeFallbacker = isFunction(options.localeFallbacker)
1038
- ? options.localeFallbacker
1039
- : _fallbacker || fallbackWithSimple;
1040
- const fallbackContext = isObject(options.fallbackContext)
1041
- ? options.fallbackContext
1042
- : undefined;
1043
- // setup internal options
1044
- const internalOptions = options;
1045
- const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
1046
- ? internalOptions.__datetimeFormatters
1047
- : new Map()
1048
- ;
1049
- const __numberFormatters = isObject(internalOptions.__numberFormatters)
1050
- ? internalOptions.__numberFormatters
1051
- : new Map()
1052
- ;
1053
- const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
1054
- _cid++;
1055
- const context = {
1056
- version,
1057
- cid: _cid,
1058
- locale,
1059
- fallbackLocale,
1060
- messages,
1061
- modifiers,
1062
- pluralRules,
1063
- missing,
1064
- missingWarn,
1065
- fallbackWarn,
1066
- fallbackFormat,
1067
- unresolving,
1068
- postTranslation,
1069
- processor,
1070
- warnHtmlMessage,
1071
- escapeParameter,
1072
- messageCompiler,
1073
- messageResolver,
1074
- localeFallbacker,
1075
- fallbackContext,
1076
- onWarn,
1077
- __meta
1078
- };
1079
- {
1080
- context.datetimeFormats = datetimeFormats;
1081
- context.numberFormats = numberFormats;
1082
- context.__datetimeFormatters = __datetimeFormatters;
1083
- context.__numberFormatters = __numberFormatters;
1084
- }
1085
- // for vue-devtools timeline event
1086
- {
1087
- context.__v_emitter =
1088
- internalOptions.__v_emitter != null
1089
- ? internalOptions.__v_emitter
1090
- : undefined;
1091
- }
1092
- // NOTE: experimental !!
1093
- {
1094
- initI18nDevTools(context, version, __meta);
1095
- }
1096
- return context;
1004
+ const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
1005
+ const version = isString(options.version) ? options.version : VERSION;
1006
+ const locale = isString(options.locale) || isFunction(options.locale) ? options.locale : DEFAULT_LOCALE;
1007
+ const _locale = isFunction(locale) ? DEFAULT_LOCALE : locale;
1008
+ const fallbackLocale = isFallbackLocale(options.fallbackLocale) ? options.fallbackLocale : _locale;
1009
+ const messages = isPlainObject(options.messages) ? options.messages : createResources(_locale);
1010
+ const datetimeFormats = isPlainObject(options.datetimeFormats) ? options.datetimeFormats : createResources(_locale);
1011
+ const numberFormats = isPlainObject(options.numberFormats) ? options.numberFormats : createResources(_locale);
1012
+ const modifiers = assign(create(), options.modifiers, getDefaultLinkedModifiers());
1013
+ const pluralRules = options.pluralRules || create();
1014
+ const missing = isFunction(options.missing) ? options.missing : null;
1015
+ const missingWarn = isWarnOption(options.missingWarn) ? options.missingWarn : true;
1016
+ const fallbackWarn = isWarnOption(options.fallbackWarn) ? options.fallbackWarn : true;
1017
+ const fallbackFormat = !!options.fallbackFormat;
1018
+ const unresolving = !!options.unresolving;
1019
+ const postTranslation = isFunction(options.postTranslation) ? options.postTranslation : null;
1020
+ const processor = isPlainObject(options.processor) ? options.processor : null;
1021
+ const warnHtmlMessage = isBoolean(options.warnHtmlMessage) ? options.warnHtmlMessage : true;
1022
+ const escapeParameter = !!options.escapeParameter;
1023
+ const messageCompiler = isFunction(options.messageCompiler) ? options.messageCompiler : _compiler || null;
1024
+ const messageResolver = isFunction(options.messageResolver) ? options.messageResolver : _resolver || resolveWithKeyValue;
1025
+ const localeFallbacker = isFunction(options.localeFallbacker) ? options.localeFallbacker : _fallbacker || fallbackWithSimple;
1026
+ const fallbackContext = isObject(options.fallbackContext) ? options.fallbackContext : void 0;
1027
+ _cid++;
1028
+ const context = {
1029
+ version,
1030
+ cid: _cid,
1031
+ locale,
1032
+ fallbackLocale,
1033
+ messages,
1034
+ modifiers,
1035
+ pluralRules,
1036
+ missing,
1037
+ missingWarn,
1038
+ fallbackWarn,
1039
+ fallbackFormat,
1040
+ unresolving,
1041
+ postTranslation,
1042
+ processor,
1043
+ warnHtmlMessage,
1044
+ escapeParameter,
1045
+ messageCompiler,
1046
+ messageResolver,
1047
+ localeFallbacker,
1048
+ fallbackContext,
1049
+ onWarn
1050
+ };
1051
+ context.datetimeFormats = datetimeFormats;
1052
+ context.numberFormats = numberFormats;
1053
+ context.__datetimeFormatters = /* @__PURE__ */ new Map();
1054
+ context.__numberFormatters = /* @__PURE__ */ new Map();
1055
+ return context;
1097
1056
  }
1098
1057
  const createResources = (locale) => ({ [locale]: create() });
1099
- // TODO: API documentation, if `@intlify/core` will be documented as a separate package
1058
+ /**
1059
+ * @version 12.0.0
1060
+ */
1100
1061
  function getLocaleMessage(ctx, locale) {
1101
- const src = ctx.messages[locale];
1102
- if (src == null) {
1103
- return undefined;
1104
- }
1105
- const dest = create();
1106
- deepCopy(src, dest);
1107
- return dest;
1108
- }
1109
- // TODO: API documentation, if `@intlify/core` will be documented as a separate package
1062
+ const src = getOwn(ctx.messages, locale);
1063
+ if (src == null) return;
1064
+ const dest = create();
1065
+ deepCopy(src, dest);
1066
+ return dest;
1067
+ }
1068
+ /**
1069
+ * @version 12.0.0
1070
+ */
1110
1071
  function setLocaleMessage(ctx, locale, messages) {
1111
- ctx.messages[locale] = messages;
1072
+ if (isObjectPrototypeKey(locale)) {
1073
+ ctx.onWarn(getWarnMessage(CoreWarnCodes.IGNORE_UNSAFE_LOCALE, { locale }));
1074
+ return;
1075
+ }
1076
+ ctx.messages[locale] = messages;
1077
+ }
1078
+ /** @internal */
1079
+ function isFallbackLocale(val) {
1080
+ return isString(val) || isArray(val) || isPlainObject(val) || val === false;
1081
+ }
1082
+ /** @internal */
1083
+ function isWarnOption(val) {
1084
+ return isBoolean(val) || isRegExp(val);
1112
1085
  }
1113
1086
  /** @internal */
1114
1087
  function isTranslateFallbackWarn(fallback, key) {
1115
- return fallback instanceof RegExp ? fallback.test(key) : fallback;
1088
+ return isRegExp(fallback) ? fallback.test(key) : fallback;
1116
1089
  }
1117
1090
  /** @internal */
1118
1091
  function isTranslateMissingWarn(missing, key) {
1119
- return missing instanceof RegExp ? missing.test(key) : missing;
1092
+ return isRegExp(missing) ? missing.test(key) : missing;
1120
1093
  }
1121
1094
  /** @internal */
1122
1095
  function handleMissing(context, key, locale, missingWarn, type) {
1123
- const { missing, onWarn } = context;
1124
- // for vue-devtools timeline event
1125
- {
1126
- const emitter = context.__v_emitter;
1127
- if (emitter) {
1128
- emitter.emit('missing', {
1129
- locale,
1130
- key,
1131
- type,
1132
- groupId: `${type}:${key}`
1133
- });
1134
- }
1135
- }
1136
- if (missing !== null) {
1137
- const ret = missing(context, locale, key, type);
1138
- return isString(ret) ? ret : key;
1139
- }
1140
- else {
1141
- if (isTranslateMissingWarn(missingWarn, key)) {
1142
- onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
1143
- }
1144
- return key;
1145
- }
1096
+ const { missing, onWarn } = context;
1097
+ {
1098
+ const emitter = context.__v_emitter;
1099
+ if (emitter) emitter.emit("missing", {
1100
+ locale,
1101
+ key,
1102
+ type,
1103
+ groupId: toDevtoolsGroupId(type, key)
1104
+ });
1105
+ }
1106
+ if (missing !== null) {
1107
+ const ret = missing(context, locale, key, type);
1108
+ return isString(ret) ? ret : key;
1109
+ } else {
1110
+ if (isTranslateMissingWarn(missingWarn, key)) onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, {
1111
+ key,
1112
+ locale,
1113
+ resource: type === "datetime format" ? "datetime formats" : type === "number format" ? "number formats" : "messages"
1114
+ }));
1115
+ return key;
1116
+ }
1117
+ }
1118
+ function invalidateLocaleChainCache(ctx, fallback) {
1119
+ const context = ctx;
1120
+ if (isObject(fallback)) context.__localeChainObjectCache?.delete(fallback);
1121
+ else context.__localeChainCache?.delete(fallback);
1146
1122
  }
1147
1123
  /** @internal */
1148
1124
  function updateFallbackLocale(ctx, locale, fallback) {
1149
- const context = ctx;
1150
- context.__localeChainCache = new Map();
1151
- ctx.localeFallbacker(ctx, fallback, locale);
1125
+ invalidateLocaleChainCache(ctx, fallback);
1126
+ if (ctx.fallbackContext) invalidateLocaleChainCache(ctx.fallbackContext, fallback);
1127
+ {
1128
+ const { __datetimeFormatters, __numberFormatters } = ctx;
1129
+ __datetimeFormatters.clear();
1130
+ __numberFormatters.clear();
1131
+ }
1132
+ ctx.localeFallbacker(ctx, fallback, locale);
1152
1133
  }
1153
1134
  /** @internal */
1154
1135
  function isAlmostSameLocale(locale, compareLocale) {
1155
- if (locale === compareLocale)
1156
- return false;
1157
- return locale.split('-')[0] === compareLocale.split('-')[0];
1136
+ if (locale === compareLocale) return false;
1137
+ return locale.split("-")[0] === compareLocale.split("-")[0];
1158
1138
  }
1159
1139
  /** @internal */
1160
1140
  function isImplicitFallback(targetLocale, locales) {
1161
- const index = locales.indexOf(targetLocale);
1162
- if (index === -1) {
1163
- return false;
1164
- }
1165
- for (let i = index + 1; i < locales.length; i++) {
1166
- if (isAlmostSameLocale(targetLocale, locales[i])) {
1167
- return true;
1168
- }
1169
- }
1170
- return false;
1171
- }
1172
- /* eslint-enable @typescript-eslint/no-explicit-any */
1173
-
1174
- const intlDefined = typeof Intl !== 'undefined';
1141
+ const index = locales.indexOf(targetLocale);
1142
+ if (index === -1) return false;
1143
+ for (let i = index + 1; i < locales.length; i++) if (isAlmostSameLocale(targetLocale, locales[i])) return true;
1144
+ return false;
1145
+ }
1146
+ // packages/core-base/src/formatter.ts
1147
+ function resolveFormatLocale(context, key, locale, formats, missingWarn, fallbackWarn, type) {
1148
+ const { fallbackLocale, localeFallbacker, onWarn } = context;
1149
+ const locales = localeFallbacker(context, fallbackLocale, locale);
1150
+ let from = locale;
1151
+ for (let i = 0; i < locales.length; i++) {
1152
+ const targetLocale = locales[i];
1153
+ if (locale !== targetLocale && isTranslateFallbackWarn(fallbackWarn, key)) onWarn(getWarnMessage(type === "datetime format" ? CoreWarnCodes.FALLBACK_TO_DATE_FORMAT : CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
1154
+ key,
1155
+ target: targetLocale
1156
+ }));
1157
+ if (locale !== targetLocale) {
1158
+ const emitter = context.__v_emitter;
1159
+ if (emitter) emitter.emit("fallback", {
1160
+ type,
1161
+ key,
1162
+ from,
1163
+ to: targetLocale,
1164
+ groupId: toDevtoolsGroupId(type, key)
1165
+ });
1166
+ }
1167
+ const format = getOwn(getOwn(formats, targetLocale) || {}, key);
1168
+ if (isPlainObject(format) && isString(targetLocale)) return targetLocale;
1169
+ handleMissing(context, key, targetLocale, missingWarn, type);
1170
+ from = targetLocale;
1171
+ }
1172
+ return null;
1173
+ }
1174
+ function isLanguageTag(locale) {
1175
+ try {
1176
+ Intl.getCanonicalLocales(locale);
1177
+ return true;
1178
+ } catch {
1179
+ return false;
1180
+ }
1181
+ }
1182
+ /**
1183
+ * Create an `Intl.DateTimeFormat` or `Intl.NumberFormat` formatter
1184
+ *
1185
+ * @remarks
1186
+ * `Intl` throws a RangeError for a locale that is not a BCP 47 language tag (e.g. `pt_BR`),
1187
+ * so fall back to the first language tag in the locale chain, or the default locale
1188
+ */
1189
+ function createFormatter(context, IntlFormatter, locale, options, type) {
1190
+ try {
1191
+ return new IntlFormatter(locale, options);
1192
+ } catch (error) {
1193
+ if (isLanguageTag(locale)) throw error;
1194
+ const { fallbackLocale, localeFallbacker, onWarn } = context;
1195
+ const target = localeFallbacker(context, fallbackLocale, locale).find(isLanguageTag) || "en-US";
1196
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_FROM_INVALID_LOCALE, {
1197
+ locale,
1198
+ target,
1199
+ type: type === "datetime format" ? "datetime" : "number"
1200
+ }));
1201
+ return new IntlFormatter(target, options);
1202
+ }
1203
+ }
1204
+ /**
1205
+ * Format a value with the format of a key, or only with the overrides when no key is given
1206
+ *
1207
+ * @remarks
1208
+ * The common part of `datetime()` and `number()`, after they check and parse the arguments
1209
+ */
1210
+ function formatValue(context, [key, value, options, overrides], IntlFormatter, formatters, formats, type) {
1211
+ const missingWarn = isBoolean(options.missingWarn) ? options.missingWarn : context.missingWarn;
1212
+ const fallbackWarn = isBoolean(options.fallbackWarn) ? options.fallbackWarn : context.fallbackWarn;
1213
+ const part = !!options.part;
1214
+ const locale = getLocale(context, options);
1215
+ if (!isString(key) || key === "") {
1216
+ const formatter = createFormatter(context, IntlFormatter, locale.replace(/!/g, ""), overrides, type);
1217
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
1218
+ }
1219
+ const targetLocale = resolveFormatLocale(context, key, locale, formats, missingWarn, fallbackWarn, type);
1220
+ if (!isString(targetLocale)) return context.unresolving ? -1 : key;
1221
+ const format = formats[targetLocale][key];
1222
+ const id = getFormatterCacheKey(targetLocale, key, overrides);
1223
+ let formatter = formatters.get(id);
1224
+ if (!formatter) {
1225
+ formatter = createFormatter(context, IntlFormatter, targetLocale, assign({}, format, overrides), type);
1226
+ formatters.set(id, formatter);
1227
+ }
1228
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
1229
+ }
1230
+ function getFormatterCacheKey(locale, key, overrides) {
1231
+ let id = `${locale}__${key}`;
1232
+ if (isPlainObject(overrides) && !isKeylessObject(overrides)) id = `${id}__${JSON.stringify(overrides)}`;
1233
+ return id;
1234
+ }
1235
+ function clearFormatCache(formatters, locale, format) {
1236
+ for (const key in format) {
1237
+ const prefix = `${locale}__${key}`;
1238
+ for (const id of formatters.keys()) if (id === prefix || id.startsWith(`${prefix}__`)) formatters.delete(id);
1239
+ }
1240
+ }
1241
+ function parseFormatArgs(args, options, initialOverrides, optionsKeys) {
1242
+ const [, arg2, arg3, arg4] = args;
1243
+ let overrides = initialOverrides;
1244
+ if (isString(arg2)) options.key = arg2;
1245
+ else if (isPlainObject(arg2)) Object.keys(arg2).forEach((key) => {
1246
+ if (optionsKeys.includes(key)) overrides[key] = arg2[key];
1247
+ else options[key] = arg2[key];
1248
+ });
1249
+ if (isString(arg3)) options.locale = arg3;
1250
+ else if (isPlainObject(arg3)) overrides = arg3;
1251
+ if (isPlainObject(arg4)) overrides = arg4;
1252
+ return overrides;
1253
+ }
1254
+ // packages/core-base/src/intl.ts
1255
+ const intlDefined = typeof Intl !== "undefined";
1175
1256
  const Availabilities = {
1176
- dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
1177
- numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
1257
+ dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== "undefined",
1258
+ numberFormat: intlDefined && typeof Intl.NumberFormat !== "undefined"
1178
1259
  };
1179
-
1180
- // implementation of `datetime` function
1260
+ // packages/core-base/src/datetime.ts
1181
1261
  function datetime(context, ...args) {
1182
- const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1183
- const { __datetimeFormatters } = context;
1184
- if (!Availabilities.dateTimeFormat) {
1185
- onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
1186
- return MISSING_RESOLVE_VALUE;
1187
- }
1188
- const [key, value, options, overrides] = parseDateTimeArgs(...args);
1189
- const missingWarn = isBoolean(options.missingWarn)
1190
- ? options.missingWarn
1191
- : context.missingWarn;
1192
- const fallbackWarn = isBoolean(options.fallbackWarn)
1193
- ? options.fallbackWarn
1194
- : context.fallbackWarn;
1195
- const part = !!options.part;
1196
- const locale = getLocale(context, options);
1197
- const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1198
- fallbackLocale, locale);
1199
- if (!isString(key) || key === '') {
1200
- return new Intl.DateTimeFormat(locale, overrides).format(value);
1201
- }
1202
- // resolve format
1203
- let datetimeFormat = {};
1204
- let targetLocale;
1205
- let format = null;
1206
- let from = locale;
1207
- let to = null;
1208
- const type = 'datetime format';
1209
- for (let i = 0; i < locales.length; i++) {
1210
- targetLocale = to = locales[i];
1211
- if (locale !== targetLocale &&
1212
- isTranslateFallbackWarn(fallbackWarn, key)) {
1213
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
1214
- key,
1215
- target: targetLocale
1216
- }));
1217
- }
1218
- // for vue-devtools timeline event
1219
- if (locale !== targetLocale) {
1220
- const emitter = context.__v_emitter;
1221
- if (emitter) {
1222
- emitter.emit('fallback', {
1223
- type,
1224
- key,
1225
- from,
1226
- to,
1227
- groupId: `${type}:${key}`
1228
- });
1229
- }
1230
- }
1231
- datetimeFormat =
1232
- datetimeFormats[targetLocale] || {};
1233
- format = datetimeFormat[key];
1234
- if (isPlainObject(format))
1235
- break;
1236
- handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1237
- from = to;
1238
- }
1239
- // checking format and target locale
1240
- if (!isPlainObject(format) || !isString(targetLocale)) {
1241
- return unresolving ? NOT_REOSLVED : key;
1242
- }
1243
- let id = `${targetLocale}__${key}`;
1244
- if (!isEmptyObject(overrides)) {
1245
- id = `${id}__${JSON.stringify(overrides)}`;
1246
- }
1247
- let formatter = __datetimeFormatters.get(id);
1248
- if (!formatter) {
1249
- formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
1250
- __datetimeFormatters.set(id, formatter);
1251
- }
1252
- return !part ? formatter.format(value) : formatter.formatToParts(value);
1262
+ const { datetimeFormats, onWarn } = context;
1263
+ const { __datetimeFormatters } = context;
1264
+ if (!Availabilities.dateTimeFormat) {
1265
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
1266
+ return "";
1267
+ }
1268
+ if (!isString(args[0]) && !isDate(args[0]) && !isNumber(args[0])) {
1269
+ onWarn(getWarnMessage(CoreWarnCodes.INVALID_DATE_ARGUMENT, { value: String(args[0]) }));
1270
+ return "";
1271
+ }
1272
+ return formatValue(context, parseDateTimeArgs(...args), Intl.DateTimeFormat, __datetimeFormatters, datetimeFormats, "datetime format");
1253
1273
  }
1254
1274
  /** @internal */
1255
1275
  const DATETIME_FORMAT_OPTIONS_KEYS = [
1256
- 'localeMatcher',
1257
- 'weekday',
1258
- 'era',
1259
- 'year',
1260
- 'month',
1261
- 'day',
1262
- 'hour',
1263
- 'minute',
1264
- 'second',
1265
- 'timeZoneName',
1266
- 'formatMatcher',
1267
- 'hour12',
1268
- 'timeZone',
1269
- 'dateStyle',
1270
- 'timeStyle',
1271
- 'calendar',
1272
- 'dayPeriod',
1273
- 'numberingSystem',
1274
- 'hourCycle',
1275
- 'fractionalSecondDigits'
1276
+ "localeMatcher",
1277
+ "weekday",
1278
+ "era",
1279
+ "year",
1280
+ "month",
1281
+ "day",
1282
+ "hour",
1283
+ "minute",
1284
+ "second",
1285
+ "timeZoneName",
1286
+ "formatMatcher",
1287
+ "hour12",
1288
+ "timeZone",
1289
+ "dateStyle",
1290
+ "timeStyle",
1291
+ "calendar",
1292
+ "dayPeriod",
1293
+ "numberingSystem",
1294
+ "hourCycle",
1295
+ "fractionalSecondDigits"
1276
1296
  ];
1277
1297
  /** @internal */
1278
1298
  function parseDateTimeArgs(...args) {
1279
- const [arg1, arg2, arg3, arg4] = args;
1280
- const options = create();
1281
- let overrides = create();
1282
- let value;
1283
- if (isString(arg1)) {
1284
- // Only allow ISO strings - other date formats are often supported,
1285
- // but may cause different results in different browsers.
1286
- const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
1287
- if (!matches) {
1288
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1289
- }
1290
- // Some browsers can not parse the iso datetime separated by space,
1291
- // this is a compromise solution by replace the 'T'/' ' with 'T'
1292
- const dateTime = matches[3]
1293
- ? matches[3].trim().startsWith('T')
1294
- ? `${matches[1].trim()}${matches[3].trim()}`
1295
- : `${matches[1].trim()}T${matches[3].trim()}`
1296
- : matches[1].trim();
1297
- value = new Date(dateTime);
1298
- try {
1299
- // This will fail if the date is not valid
1300
- value.toISOString();
1301
- }
1302
- catch {
1303
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1304
- }
1305
- }
1306
- else if (isDate(arg1)) {
1307
- if (isNaN(arg1.getTime())) {
1308
- throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
1309
- }
1310
- value = arg1;
1311
- }
1312
- else if (isNumber(arg1)) {
1313
- value = arg1;
1314
- }
1315
- else {
1316
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1317
- }
1318
- if (isString(arg2)) {
1319
- options.key = arg2;
1320
- }
1321
- else if (isPlainObject(arg2)) {
1322
- Object.keys(arg2).forEach(key => {
1323
- if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
1324
- overrides[key] = arg2[key];
1325
- }
1326
- else {
1327
- options[key] = arg2[key];
1328
- }
1329
- });
1330
- }
1331
- if (isString(arg3)) {
1332
- options.locale = arg3;
1333
- }
1334
- else if (isPlainObject(arg3)) {
1335
- overrides = arg3;
1336
- }
1337
- if (isPlainObject(arg4)) {
1338
- overrides = arg4;
1339
- }
1340
- return [options.key || '', value, options, overrides];
1299
+ const [arg1] = args;
1300
+ const options = create();
1301
+ const initialOverrides = create();
1302
+ let value;
1303
+ if (isString(arg1)) {
1304
+ const matches = arg1.match(/^(\d{4}-\d{2}-\d{2})(?:(T|\s)(.+))?$/);
1305
+ if (!matches) throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1306
+ const dateTime = matches[3] ? matches[3].trim().startsWith("T") ? `${matches[1].trim()}${matches[3].trim()}` : `${matches[1].trim()}T${matches[3].trim()}` : matches[1].trim();
1307
+ value = new Date(dateTime);
1308
+ try {
1309
+ value.toISOString();
1310
+ } catch {
1311
+ throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1312
+ }
1313
+ } else if (isDate(arg1)) {
1314
+ if (isNaN(arg1.getTime())) throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
1315
+ value = arg1;
1316
+ } else if (isNumber(arg1)) value = arg1;
1317
+ else throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1318
+ const overrides = parseFormatArgs(args, options, initialOverrides, DATETIME_FORMAT_OPTIONS_KEYS);
1319
+ return [
1320
+ options.key || "",
1321
+ value,
1322
+ options,
1323
+ overrides
1324
+ ];
1341
1325
  }
1342
1326
  /** @internal */
1343
1327
  function clearDateTimeFormat(ctx, locale, format) {
1344
- const context = ctx;
1345
- for (const key in format) {
1346
- const id = `${locale}__${key}`;
1347
- if (!context.__datetimeFormatters.has(id)) {
1348
- continue;
1349
- }
1350
- context.__datetimeFormatters.delete(id);
1351
- }
1352
- }
1353
-
1354
- // implementation of `number` function
1328
+ clearFormatCache(ctx.__datetimeFormatters, locale, format);
1329
+ }
1330
+ // packages/core-base/src/number.ts
1355
1331
  function number(context, ...args) {
1356
- const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1357
- const { __numberFormatters } = context;
1358
- if (!Availabilities.numberFormat) {
1359
- onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
1360
- return MISSING_RESOLVE_VALUE;
1361
- }
1362
- const [key, value, options, overrides] = parseNumberArgs(...args);
1363
- const missingWarn = isBoolean(options.missingWarn)
1364
- ? options.missingWarn
1365
- : context.missingWarn;
1366
- const fallbackWarn = isBoolean(options.fallbackWarn)
1367
- ? options.fallbackWarn
1368
- : context.fallbackWarn;
1369
- const part = !!options.part;
1370
- const locale = getLocale(context, options);
1371
- const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1372
- fallbackLocale, locale);
1373
- if (!isString(key) || key === '') {
1374
- return new Intl.NumberFormat(locale, overrides).format(value);
1375
- }
1376
- // resolve format
1377
- let numberFormat = {};
1378
- let targetLocale;
1379
- let format = null;
1380
- let from = locale;
1381
- let to = null;
1382
- const type = 'number format';
1383
- for (let i = 0; i < locales.length; i++) {
1384
- targetLocale = to = locales[i];
1385
- if (locale !== targetLocale &&
1386
- isTranslateFallbackWarn(fallbackWarn, key)) {
1387
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
1388
- key,
1389
- target: targetLocale
1390
- }));
1391
- }
1392
- // for vue-devtools timeline event
1393
- if (locale !== targetLocale) {
1394
- const emitter = context.__v_emitter;
1395
- if (emitter) {
1396
- emitter.emit('fallback', {
1397
- type,
1398
- key,
1399
- from,
1400
- to,
1401
- groupId: `${type}:${key}`
1402
- });
1403
- }
1404
- }
1405
- numberFormat =
1406
- numberFormats[targetLocale] || {};
1407
- format = numberFormat[key];
1408
- if (isPlainObject(format))
1409
- break;
1410
- handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1411
- from = to;
1412
- }
1413
- // checking format and target locale
1414
- if (!isPlainObject(format) || !isString(targetLocale)) {
1415
- return unresolving ? NOT_REOSLVED : key;
1416
- }
1417
- let id = `${targetLocale}__${key}`;
1418
- if (!isEmptyObject(overrides)) {
1419
- id = `${id}__${JSON.stringify(overrides)}`;
1420
- }
1421
- let formatter = __numberFormatters.get(id);
1422
- if (!formatter) {
1423
- formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
1424
- __numberFormatters.set(id, formatter);
1425
- }
1426
- return !part ? formatter.format(value) : formatter.formatToParts(value);
1332
+ const { numberFormats, onWarn } = context;
1333
+ const { __numberFormatters } = context;
1334
+ if (!Availabilities.numberFormat) {
1335
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
1336
+ return "";
1337
+ }
1338
+ if (!isNumber(args[0])) {
1339
+ onWarn(getWarnMessage(CoreWarnCodes.INVALID_NUMBER_ARGUMENT, { value: String(args[0]) }));
1340
+ return "";
1341
+ }
1342
+ return formatValue(context, parseNumberArgs(...args), Intl.NumberFormat, __numberFormatters, numberFormats, "number format");
1427
1343
  }
1428
1344
  /** @internal */
1429
1345
  const NUMBER_FORMAT_OPTIONS_KEYS = [
1430
- 'localeMatcher',
1431
- 'style',
1432
- 'currency',
1433
- 'currencyDisplay',
1434
- 'currencySign',
1435
- 'useGrouping',
1436
- 'minimumIntegerDigits',
1437
- 'minimumFractionDigits',
1438
- 'maximumFractionDigits',
1439
- 'minimumSignificantDigits',
1440
- 'maximumSignificantDigits',
1441
- 'compactDisplay',
1442
- 'notation',
1443
- 'signDisplay',
1444
- 'unit',
1445
- 'unitDisplay',
1446
- 'roundingMode',
1447
- 'roundingPriority',
1448
- 'roundingIncrement',
1449
- 'trailingZeroDisplay'
1346
+ "localeMatcher",
1347
+ "style",
1348
+ "currency",
1349
+ "currencyDisplay",
1350
+ "currencySign",
1351
+ "useGrouping",
1352
+ "minimumIntegerDigits",
1353
+ "minimumFractionDigits",
1354
+ "maximumFractionDigits",
1355
+ "minimumSignificantDigits",
1356
+ "maximumSignificantDigits",
1357
+ "compactDisplay",
1358
+ "notation",
1359
+ "signDisplay",
1360
+ "unit",
1361
+ "unitDisplay",
1362
+ "roundingMode",
1363
+ "roundingPriority",
1364
+ "roundingIncrement",
1365
+ "trailingZeroDisplay"
1450
1366
  ];
1451
1367
  /** @internal */
1452
1368
  function parseNumberArgs(...args) {
1453
- const [arg1, arg2, arg3, arg4] = args;
1454
- const options = create();
1455
- let overrides = create();
1456
- if (!isNumber(arg1)) {
1457
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1458
- }
1459
- const value = arg1;
1460
- if (isString(arg2)) {
1461
- options.key = arg2;
1462
- }
1463
- else if (isPlainObject(arg2)) {
1464
- Object.keys(arg2).forEach(key => {
1465
- if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
1466
- overrides[key] = arg2[key];
1467
- }
1468
- else {
1469
- options[key] = arg2[key];
1470
- }
1471
- });
1472
- }
1473
- if (isString(arg3)) {
1474
- options.locale = arg3;
1475
- }
1476
- else if (isPlainObject(arg3)) {
1477
- overrides = arg3;
1478
- }
1479
- if (isPlainObject(arg4)) {
1480
- overrides = arg4;
1481
- }
1482
- return [options.key || '', value, options, overrides];
1369
+ const [arg1] = args;
1370
+ const options = create();
1371
+ const initialOverrides = create();
1372
+ if (!isNumber(arg1)) throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1373
+ const value = arg1;
1374
+ const overrides = parseFormatArgs(args, options, initialOverrides, NUMBER_FORMAT_OPTIONS_KEYS);
1375
+ return [
1376
+ options.key || "",
1377
+ value,
1378
+ options,
1379
+ overrides
1380
+ ];
1483
1381
  }
1484
1382
  /** @internal */
1485
1383
  function clearNumberFormat(ctx, locale, format) {
1486
- const context = ctx;
1487
- for (const key in format) {
1488
- const id = `${locale}__${key}`;
1489
- if (!context.__numberFormatters.has(id)) {
1490
- continue;
1491
- }
1492
- context.__numberFormatters.delete(id);
1493
- }
1494
- }
1495
-
1384
+ clearFormatCache(ctx.__numberFormatters, locale, format);
1385
+ }
1386
+ // packages/core-base/src/runtime.ts
1496
1387
  const DEFAULT_MODIFIER = (str) => str;
1497
- const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
1498
- const DEFAULT_MESSAGE_DATA_TYPE = 'text';
1499
- const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);
1388
+ const DEFAULT_MESSAGE = (_ctx) => "";
1389
+ const DEFAULT_MESSAGE_DATA_TYPE = "text";
1390
+ const DEFAULT_NORMALIZE = (values) => values.length === 0 ? "" : join(values);
1500
1391
  const DEFAULT_INTERPOLATE = toDisplayString;
1501
1392
  function pluralDefault(choice, choicesLength) {
1502
- choice = Math.abs(choice);
1503
- if (choicesLength === 2) {
1504
- // prettier-ignore
1505
- return choice
1506
- ? choice > 1
1507
- ? 1
1508
- : 0
1509
- : 1;
1510
- }
1511
- return choice ? Math.min(choice, 2) : 0;
1393
+ choice = Math.abs(choice);
1394
+ if (choicesLength === 2) return choice === 1 ? 0 : 1;
1395
+ return Math.min(choice, 2);
1396
+ }
1397
+ const PLURAL_CATEGORY_ORDER = [
1398
+ "zero",
1399
+ "one",
1400
+ "two",
1401
+ "few",
1402
+ "many",
1403
+ "other"
1404
+ ];
1405
+ const intlPluralRulesCache = /* @__PURE__ */ new Map();
1406
+ const INTL_PLURAL_RULES_CACHE_SIZE = 1e3;
1407
+ function createIntlPluralRules(locale) {
1408
+ try {
1409
+ if (Intl.PluralRules.supportedLocalesOf(locale).length === 0) return null;
1410
+ const rules = new Intl.PluralRules(locale);
1411
+ return {
1412
+ rules,
1413
+ categories: rules.resolvedOptions().pluralCategories.slice().sort((a, b) => PLURAL_CATEGORY_ORDER.indexOf(a) - PLURAL_CATEGORY_ORDER.indexOf(b))
1414
+ };
1415
+ } catch {
1416
+ return null;
1417
+ }
1418
+ }
1419
+ function getIntlPluralRules(locale) {
1420
+ let cached = intlPluralRulesCache.get(locale);
1421
+ if (cached === void 0) {
1422
+ cached = createIntlPluralRules(locale);
1423
+ if (cached === null) warn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DEFAULT_PLURAL_RULE, { locale }));
1424
+ if (intlPluralRulesCache.size >= INTL_PLURAL_RULES_CACHE_SIZE) intlPluralRulesCache.delete(intlPluralRulesCache.keys().next().value);
1425
+ intlPluralRulesCache.set(locale, cached);
1426
+ }
1427
+ return cached;
1512
1428
  }
1513
1429
  function getPluralIndex(options) {
1514
- // prettier-ignore
1515
- const index = isNumber(options.pluralIndex)
1516
- ? options.pluralIndex
1517
- : -1;
1518
- // prettier-ignore
1519
- return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
1520
- ? isNumber(options.named.count)
1521
- ? options.named.count
1522
- : isNumber(options.named.n)
1523
- ? options.named.n
1524
- : index
1525
- : index;
1526
- }
1527
- function normalizeNamed(pluralIndex, props) {
1528
- if (!props.count) {
1529
- props.count = pluralIndex;
1530
- }
1531
- if (!props.n) {
1532
- props.n = pluralIndex;
1533
- }
1430
+ if (isNumber(options.pluralIndex)) return options.pluralIndex;
1431
+ return isNumber(options.named?.count) ? options.named.count : isNumber(options.named?.n) ? options.named.n : -1;
1534
1432
  }
1535
1433
  function createMessageContext(options = {}) {
1536
- const locale = options.locale;
1537
- const pluralIndex = getPluralIndex(options);
1538
- const pluralRule = isObject(options.pluralRules) &&
1539
- isString(locale) &&
1540
- isFunction(options.pluralRules[locale])
1541
- ? options.pluralRules[locale]
1542
- : pluralDefault;
1543
- const orgPluralRule = isObject(options.pluralRules) &&
1544
- isString(locale) &&
1545
- isFunction(options.pluralRules[locale])
1546
- ? pluralDefault
1547
- : undefined;
1548
- const plural = (messages) => {
1549
- return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
1550
- };
1551
- const _list = options.list || [];
1552
- const list = (index) => _list[index];
1553
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1554
- const _named = options.named || create();
1555
- isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
1556
- const named = (key) => _named[key];
1557
- function message(key, useLinked) {
1558
- // prettier-ignore
1559
- const msg = isFunction(options.messages)
1560
- ? options.messages(key, !!useLinked)
1561
- : isObject(options.messages)
1562
- ? options.messages[key]
1563
- : false;
1564
- return !msg
1565
- ? options.parent
1566
- ? options.parent.message(key) // resolve from parent messages
1567
- : DEFAULT_MESSAGE
1568
- : msg;
1569
- }
1570
- const _modifier = (name) => options.modifiers
1571
- ? options.modifiers[name]
1572
- : DEFAULT_MODIFIER;
1573
- const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
1574
- ? options.processor.normalize
1575
- : DEFAULT_NORMALIZE;
1576
- const interpolate = isPlainObject(options.processor) &&
1577
- isFunction(options.processor.interpolate)
1578
- ? options.processor.interpolate
1579
- : DEFAULT_INTERPOLATE;
1580
- const type = isPlainObject(options.processor) && isString(options.processor.type)
1581
- ? options.processor.type
1582
- : DEFAULT_MESSAGE_DATA_TYPE;
1583
- const linked = (key, ...args) => {
1584
- const [arg1, arg2] = args;
1585
- let type = 'text';
1586
- let modifier = '';
1587
- if (args.length === 1) {
1588
- if (isObject(arg1)) {
1589
- modifier = arg1.modifier || modifier;
1590
- type = arg1.type || type;
1591
- }
1592
- else if (isString(arg1)) {
1593
- modifier = arg1 || modifier;
1594
- }
1595
- }
1596
- else if (args.length === 2) {
1597
- if (isString(arg1)) {
1598
- modifier = arg1 || modifier;
1599
- }
1600
- if (isString(arg2)) {
1601
- type = arg2 || type;
1602
- }
1603
- }
1604
- const ret = message(key, true)(ctx);
1605
- const msg =
1606
- // The message in vnode resolved with linked are returned as an array by processor.nomalize
1607
- type === 'vnode' && isArray(ret) && modifier
1608
- ? ret[0]
1609
- : ret;
1610
- return modifier ? _modifier(modifier)(msg, type) : msg;
1611
- };
1612
- const ctx = {
1613
- ["list" /* HelperNameMap.LIST */]: list,
1614
- ["named" /* HelperNameMap.NAMED */]: named,
1615
- ["plural" /* HelperNameMap.PLURAL */]: plural,
1616
- ["linked" /* HelperNameMap.LINKED */]: linked,
1617
- ["message" /* HelperNameMap.MESSAGE */]: message,
1618
- ["type" /* HelperNameMap.TYPE */]: type,
1619
- ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
1620
- ["normalize" /* HelperNameMap.NORMALIZE */]: normalize,
1621
- ["values" /* HelperNameMap.VALUES */]: assign(create(), _list, _named)
1622
- };
1623
- return ctx;
1624
- }
1625
-
1626
- const NOOP_MESSAGE_FUNCTION = () => '';
1434
+ const locale = options.locale;
1435
+ const pluralIndex = getPluralIndex(options);
1436
+ let resolvedPluralRule;
1437
+ if (isString(locale) && options.pluralRules && isFunction(getOwn(options.pluralRules, locale))) resolvedPluralRule = options.pluralRules[locale];
1438
+ else if (isString(locale) && typeof Intl !== "undefined" && typeof Intl.PluralRules !== "undefined") resolvedPluralRule = (choice, choicesLength) => {
1439
+ const intlPluralRules = getIntlPluralRules(locale);
1440
+ if (intlPluralRules === null || choicesLength > intlPluralRules.categories.length) return pluralDefault(choice, choicesLength);
1441
+ const { rules, categories } = intlPluralRules;
1442
+ const category = rules.select(Math.abs(choice));
1443
+ const index = categories.indexOf(category);
1444
+ return Math.min(index === -1 ? choicesLength - 1 : index, choicesLength - 1);
1445
+ };
1446
+ else resolvedPluralRule = pluralDefault;
1447
+ const orgPluralRule = resolvedPluralRule === pluralDefault ? void 0 : pluralDefault;
1448
+ const plural = (messages) => messages[resolvedPluralRule(pluralIndex, messages.length, orgPluralRule)];
1449
+ const _list = options.list || [];
1450
+ const list = (index) => _list[index];
1451
+ const _named = options.named || create();
1452
+ const hasPluralIndex = isNumber(options.pluralIndex);
1453
+ const named = (key) => {
1454
+ const value = isObjectPrototypeKey(key) ? getOwn(_named, key) : _named[key];
1455
+ return hasPluralIndex && value == null && (key === "count" || key === "n") ? options.pluralIndex : value;
1456
+ };
1457
+ function message(key, useLinked) {
1458
+ const msg = isFunction(options.messages) ? options.messages(key, !!useLinked) : isObject(options.messages) ? options.messages[key] : false;
1459
+ return !msg ? options.parent ? options.parent.message(key) : DEFAULT_MESSAGE : msg;
1460
+ }
1461
+ const _modifier = (name) => options.modifiers ? getOwn(options.modifiers, name) : DEFAULT_MODIFIER;
1462
+ const normalize = isFunction(options.processor?.normalize) ? options.processor.normalize : DEFAULT_NORMALIZE;
1463
+ const interpolate = isFunction(options.processor?.interpolate) ? options.processor.interpolate : DEFAULT_INTERPOLATE;
1464
+ const type = isString(options.processor?.type) ? options.processor.type : DEFAULT_MESSAGE_DATA_TYPE;
1465
+ const linked = (key, ...args) => {
1466
+ const [arg1, arg2] = args;
1467
+ let type = "text";
1468
+ let modifier = "";
1469
+ if (args.length === 1) {
1470
+ if (isObject(arg1)) {
1471
+ modifier = arg1.modifier || modifier;
1472
+ type = arg1.type || type;
1473
+ } else if (isString(arg1)) modifier = arg1 || modifier;
1474
+ } else if (args.length === 2) {
1475
+ if (isString(arg1)) modifier = arg1 || modifier;
1476
+ if (isString(arg2)) type = arg2 || type;
1477
+ }
1478
+ const ret = message(key, true)(ctx);
1479
+ const resolved = ret === "" || ret === void 0 ? key : ret;
1480
+ const msg = type === "vnode" && isArray(resolved) && modifier ? resolved[0] : resolved;
1481
+ if (!modifier) return msg;
1482
+ const modify = _modifier(modifier);
1483
+ if (isFunction(modify)) return modify(msg, type);
1484
+ warnOnce(`Not found '${modifier}' modifier for the linked message of '${key}' key. Use a built-in modifier, or set a custom modifier with 'modifiers' option. So the linked message is used as is.`);
1485
+ return msg;
1486
+ };
1487
+ const ctx = {
1488
+ ["list"]: list,
1489
+ ["named"]: named,
1490
+ ["plural"]: plural,
1491
+ ["linked"]: linked,
1492
+ ["message"]: message,
1493
+ ["type"]: type,
1494
+ ["interpolate"]: interpolate,
1495
+ ["normalize"]: normalize,
1496
+ ["values"]: assign(create(), _list, _named, hasPluralIndex ? {
1497
+ count: named("count"),
1498
+ n: named("n")
1499
+ } : {})
1500
+ };
1501
+ return ctx;
1502
+ }
1503
+ // packages/core-base/src/translate.ts
1504
+ const NOOP_MESSAGE_FUNCTION = () => "";
1627
1505
  const isMessageFunction = (val) => isFunction(val);
1628
- // implementation of `translate` function
1506
+ /** @internal */
1507
+ const isMessageFormat = (val) => isString(val) || isMessageAST(val) || isMessageFunction(val);
1629
1508
  function translate(context, ...args) {
1630
- const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
1631
- const [key, options] = parseTranslateArgs(...args);
1632
- const missingWarn = isBoolean(options.missingWarn)
1633
- ? options.missingWarn
1634
- : context.missingWarn;
1635
- const fallbackWarn = isBoolean(options.fallbackWarn)
1636
- ? options.fallbackWarn
1637
- : context.fallbackWarn;
1638
- const escapeParameter = isBoolean(options.escapeParameter)
1639
- ? options.escapeParameter
1640
- : context.escapeParameter;
1641
- const resolvedMessage = !!options.resolvedMessage;
1642
- // prettier-ignore
1643
- const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
1644
- ? !isBoolean(options.default)
1645
- ? options.default
1646
- : (!messageCompiler ? () => key : key)
1647
- : fallbackFormat // default by `fallbackFormat` option
1648
- ? (!messageCompiler ? () => key : key)
1649
- : null;
1650
- const enableDefaultMsg = fallbackFormat ||
1651
- (defaultMsgOrKey != null &&
1652
- (isString(defaultMsgOrKey) || isFunction(defaultMsgOrKey)));
1653
- const locale = getLocale(context, options);
1654
- // escape params
1655
- escapeParameter && escapeParams(options);
1656
- // resolve message format
1657
- // eslint-disable-next-line prefer-const
1658
- let [formatScope, targetLocale, message] = !resolvedMessage
1659
- ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
1660
- : [
1661
- key,
1662
- locale,
1663
- messages[locale] || create()
1664
- ];
1665
- // NOTE:
1666
- // Fix to work around `ssrTransfrom` bug in Vite.
1667
- // https://github.com/vitejs/vite/issues/4306
1668
- // To get around this, use temporary variables.
1669
- // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
1670
- let format = formatScope;
1671
- // if you use default message, set it as message format!
1672
- let cacheBaseKey = key;
1673
- if (!resolvedMessage &&
1674
- !(isString(format) ||
1675
- isMessageAST(format) ||
1676
- isMessageFunction(format))) {
1677
- if (enableDefaultMsg) {
1678
- format = defaultMsgOrKey;
1679
- cacheBaseKey = format;
1680
- }
1681
- }
1682
- // checking message format and target locale
1683
- if (!resolvedMessage &&
1684
- (!(isString(format) ||
1685
- isMessageAST(format) ||
1686
- isMessageFunction(format)) ||
1687
- !isString(targetLocale))) {
1688
- return unresolving ? NOT_REOSLVED : key;
1689
- }
1690
- // TODO: refactor
1691
- if (isString(format) && context.messageCompiler == null) {
1692
- warn(`The message format compilation is not supported in this build. ` +
1693
- `Because message compiler isn't included. ` +
1694
- `You need to pre-compilation all message format. ` +
1695
- `So translate function return '${key}'.`);
1696
- return key;
1697
- }
1698
- // setup compile error detecting
1699
- let occurred = false;
1700
- const onError = () => {
1701
- occurred = true;
1702
- };
1703
- // compile message format
1704
- const msg = !isMessageFunction(format)
1705
- ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
1706
- : format;
1707
- // if occurred compile error, return the message format
1708
- if (occurred) {
1709
- return format;
1710
- }
1711
- // evaluate message with context
1712
- const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
1713
- const msgContext = createMessageContext(ctxOptions);
1714
- const messaged = evaluateMessage(context, msg, msgContext);
1715
- // if use post translation option, proceed it with handler
1716
- const ret = postTranslation
1717
- ? postTranslation(messaged, key)
1718
- : messaged;
1719
- // NOTE: experimental !!
1720
- {
1721
- // prettier-ignore
1722
- const payloads = {
1723
- timestamp: Date.now(),
1724
- key: isString(key)
1725
- ? key
1726
- : isMessageFunction(format)
1727
- ? format.key
1728
- : '',
1729
- locale: targetLocale || (isMessageFunction(format)
1730
- ? format.locale
1731
- : ''),
1732
- format: isString(format)
1733
- ? format
1734
- : isMessageFunction(format)
1735
- ? format.source
1736
- : '',
1737
- message: ret
1738
- };
1739
- payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
1740
- translateDevTools(payloads);
1741
- }
1742
- return ret;
1509
+ const [key, options] = parseTranslateArgs(...args);
1510
+ const locale = getLocale(context, options);
1511
+ const escapeParameter = isBoolean(options.escapeParameter) ? options.escapeParameter : context.escapeParameter;
1512
+ escapeParameter && escapeParams(options);
1513
+ const resolvedMessage = !!options.resolvedMessage;
1514
+ let [format, targetLocale, message] = !resolvedMessage ? resolveMessageFormat(context, key, locale, context.fallbackLocale, isBoolean(options.fallbackWarn) ? options.fallbackWarn : context.fallbackWarn, isBoolean(options.missingWarn) ? options.missingWarn : context.missingWarn) : [
1515
+ key,
1516
+ locale,
1517
+ getOwn(context.messages, locale) || create()
1518
+ ];
1519
+ let cacheBaseKey = key;
1520
+ if (!resolvedMessage && !isMessageFormat(format)) {
1521
+ const defaultMsgOrKey = isString(options.default) ? options.default : isBoolean(options.default) || context.fallbackFormat ? !context.messageCompiler ? () => key : key : null;
1522
+ if (context.fallbackFormat || defaultMsgOrKey != null && (isString(defaultMsgOrKey) || isFunction(defaultMsgOrKey))) {
1523
+ format = defaultMsgOrKey;
1524
+ cacheBaseKey = format;
1525
+ }
1526
+ }
1527
+ if (!resolvedMessage && (!isMessageFormat(format) || !isString(targetLocale))) return context.unresolving ? -1 : key;
1528
+ if (isString(format) && context.messageCompiler == null) warn(`Cannot compile the message of '${stringifyKey(key)}' key, because no message compiler is set. Use 'messageCompiler' option of 'createCoreContext', or pre-compile the message. So translate function returns the message as is.`);
1529
+ let occurred = false;
1530
+ const onError = () => {
1531
+ occurred = true;
1532
+ };
1533
+ const msg = !isMessageFunction(format) ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) : format;
1534
+ if (occurred) return format;
1535
+ const msgContext = createMessageContext(getMessageContextOptions(context, targetLocale, message, options));
1536
+ const timeline = startTimelineMeasure(context, "evaluation");
1537
+ const messaged = msg(msgContext);
1538
+ if (timeline) timeline.emitter.emit("message-evaluation", {
1539
+ type: "message-evaluation",
1540
+ value: messaged,
1541
+ time: endTimelineMeasure(timeline),
1542
+ groupId: toDevtoolsGroupId("translate", msg.key)
1543
+ });
1544
+ let ret = context.postTranslation ? context.postTranslation(messaged, key) : messaged;
1545
+ if (escapeParameter && isString(ret)) ret = sanitizeTranslatedHtml(ret);
1546
+ return ret;
1743
1547
  }
1744
1548
  function escapeParams(options) {
1745
- if (isArray(options.list)) {
1746
- options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
1747
- }
1748
- else if (isObject(options.named)) {
1749
- Object.keys(options.named).forEach(key => {
1750
- if (isString(options.named[key])) {
1751
- options.named[key] = escapeHtml(options.named[key]);
1752
- }
1753
- });
1754
- }
1549
+ if (isArray(options.list)) options.list = options.list.map((item) => isString(item) ? escapeHtml(item) : item);
1550
+ if (isObject(options.named)) {
1551
+ const source = options.named;
1552
+ const named = create();
1553
+ for (const key of Object.keys(source)) {
1554
+ const value = source[key];
1555
+ named[key] = isString(value) ? escapeHtml(value) : value;
1556
+ }
1557
+ options.named = named;
1558
+ }
1755
1559
  }
1756
1560
  function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
1757
- const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
1758
- const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
1759
- let message = create();
1760
- let targetLocale;
1761
- let format = null;
1762
- let from = locale;
1763
- let to = null;
1764
- const type = 'translate';
1765
- for (let i = 0; i < locales.length; i++) {
1766
- targetLocale = to = locales[i];
1767
- if (locale !== targetLocale &&
1768
- !isAlmostSameLocale(locale, targetLocale) &&
1769
- isTranslateFallbackWarn(fallbackWarn, key)) {
1770
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
1771
- key,
1772
- target: targetLocale
1773
- }));
1774
- }
1775
- // for vue-devtools timeline event
1776
- if (locale !== targetLocale) {
1777
- const emitter = context.__v_emitter;
1778
- if (emitter) {
1779
- emitter.emit('fallback', {
1780
- type,
1781
- key,
1782
- from,
1783
- to,
1784
- groupId: `${type}:${key}`
1785
- });
1786
- }
1787
- }
1788
- message =
1789
- messages[targetLocale] || create();
1790
- // for vue-devtools timeline event
1791
- let start = null;
1792
- let startTag;
1793
- let endTag;
1794
- if (inBrowser) {
1795
- start = window.performance.now();
1796
- startTag = 'intlify-message-resolve-start';
1797
- endTag = 'intlify-message-resolve-end';
1798
- mark && mark(startTag);
1799
- }
1800
- if ((format = resolveValue(message, key)) === null) {
1801
- // if null, resolve with object key path
1802
- format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
1803
- }
1804
- // for vue-devtools timeline event
1805
- if (inBrowser) {
1806
- const end = window.performance.now();
1807
- const emitter = context.__v_emitter;
1808
- if (emitter && start && format) {
1809
- emitter.emit('message-resolve', {
1810
- type: 'message-resolve',
1811
- key,
1812
- message: format,
1813
- time: end - start,
1814
- groupId: `${type}:${key}`
1815
- });
1816
- }
1817
- if (startTag && endTag && mark && measure) {
1818
- mark(endTag);
1819
- measure('intlify message resolve', startTag, endTag);
1820
- }
1821
- }
1822
- if (isString(format) || isMessageAST(format) || isMessageFunction(format)) {
1823
- break;
1824
- }
1825
- if (!isImplicitFallback(targetLocale, locales)) {
1826
- const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1827
- key, targetLocale, missingWarn, type);
1828
- if (missingRet !== key) {
1829
- format = missingRet;
1830
- }
1831
- }
1832
- from = to;
1833
- }
1834
- return [format, targetLocale, message];
1561
+ const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
1562
+ const locales = localeFallbacker(context, fallbackLocale, locale);
1563
+ let message = create();
1564
+ let targetLocale;
1565
+ let format = null;
1566
+ let from = locale;
1567
+ const type = "translate";
1568
+ for (let i = 0; i < locales.length; i++) {
1569
+ targetLocale = locales[i];
1570
+ if (locale !== targetLocale && !isAlmostSameLocale(locale, targetLocale) && isTranslateFallbackWarn(fallbackWarn, key)) onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
1571
+ key,
1572
+ target: targetLocale
1573
+ }));
1574
+ if (locale !== targetLocale) {
1575
+ const emitter = context.__v_emitter;
1576
+ if (emitter) emitter.emit("fallback", {
1577
+ type,
1578
+ key,
1579
+ from,
1580
+ to: targetLocale,
1581
+ groupId: toDevtoolsGroupId(type, key)
1582
+ });
1583
+ }
1584
+ message = getOwn(messages, targetLocale) || create();
1585
+ const timeline = startTimelineMeasure(context, "resolve");
1586
+ if ((format = resolveValue(message, key)) === null) format = getOwn(message, key);
1587
+ if (timeline) {
1588
+ const time = endTimelineMeasure(timeline);
1589
+ if (format) timeline.emitter.emit("message-resolve", {
1590
+ type: "message-resolve",
1591
+ key,
1592
+ message: format,
1593
+ time,
1594
+ groupId: toDevtoolsGroupId(type, key)
1595
+ });
1596
+ }
1597
+ if (isMessageFormat(format)) break;
1598
+ if (!isImplicitFallback(targetLocale, locales)) {
1599
+ const missingRet = handleMissing(context, key, targetLocale, missingWarn, type);
1600
+ if (missingRet !== key) format = missingRet;
1601
+ }
1602
+ from = targetLocale;
1603
+ }
1604
+ return [
1605
+ format,
1606
+ targetLocale,
1607
+ message
1608
+ ];
1609
+ }
1610
+ function stringifyKey(key) {
1611
+ return isString(key) ? key : isObject(key) ? JSON.stringify(key) : isFunction(key) ? key.name || "function" : "";
1835
1612
  }
1836
1613
  function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
1837
- const { messageCompiler, warnHtmlMessage } = context;
1838
- if (isMessageFunction(format)) {
1839
- const msg = format;
1840
- msg.locale = msg.locale || targetLocale;
1841
- msg.key = msg.key || key;
1842
- return msg;
1843
- }
1844
- if (messageCompiler == null) {
1845
- const msg = (() => format);
1846
- msg.locale = targetLocale;
1847
- msg.key = key;
1848
- return msg;
1849
- }
1850
- // for vue-devtools timeline event
1851
- let start = null;
1852
- let startTag;
1853
- let endTag;
1854
- if (inBrowser) {
1855
- start = window.performance.now();
1856
- startTag = 'intlify-message-compilation-start';
1857
- endTag = 'intlify-message-compilation-end';
1858
- mark && mark(startTag);
1859
- }
1860
- const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
1861
- // for vue-devtools timeline event
1862
- if (inBrowser) {
1863
- const end = window.performance.now();
1864
- const emitter = context.__v_emitter;
1865
- if (emitter && start) {
1866
- emitter.emit('message-compilation', {
1867
- type: 'message-compilation',
1868
- message: format,
1869
- time: end - start,
1870
- groupId: `${'translate'}:${key}`
1871
- });
1872
- }
1873
- if (startTag && endTag && mark && measure) {
1874
- mark(endTag);
1875
- measure('intlify message compilation', startTag, endTag);
1876
- }
1877
- }
1878
- msg.locale = targetLocale;
1879
- msg.key = key;
1880
- msg.source = format;
1881
- return msg;
1882
- }
1883
- function evaluateMessage(context, msg, msgCtx) {
1884
- // for vue-devtools timeline event
1885
- let start = null;
1886
- let startTag;
1887
- let endTag;
1888
- if (inBrowser) {
1889
- start = window.performance.now();
1890
- startTag = 'intlify-message-evaluation-start';
1891
- endTag = 'intlify-message-evaluation-end';
1892
- mark && mark(startTag);
1893
- }
1894
- const messaged = msg(msgCtx);
1895
- // for vue-devtools timeline event
1896
- if (inBrowser) {
1897
- const end = window.performance.now();
1898
- const emitter = context.__v_emitter;
1899
- if (emitter && start) {
1900
- emitter.emit('message-evaluation', {
1901
- type: 'message-evaluation',
1902
- value: messaged,
1903
- time: end - start,
1904
- groupId: `${'translate'}:${msg.key}`
1905
- });
1906
- }
1907
- if (startTag && endTag && mark && measure) {
1908
- mark(endTag);
1909
- measure('intlify message evaluation', startTag, endTag);
1910
- }
1911
- }
1912
- return messaged;
1614
+ if (isMessageFunction(format)) {
1615
+ const msg = format;
1616
+ msg.locale = msg.locale || targetLocale;
1617
+ msg.key = msg.key || key;
1618
+ return msg;
1619
+ }
1620
+ if (context.messageCompiler == null) {
1621
+ const msg = (() => format);
1622
+ msg.locale = targetLocale;
1623
+ msg.key = key;
1624
+ return msg;
1625
+ }
1626
+ const timeline = startTimelineMeasure(context, "compilation");
1627
+ const msg = context.messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, context.warnHtmlMessage, onError));
1628
+ if (timeline) timeline.emitter.emit("message-compilation", {
1629
+ type: "message-compilation",
1630
+ message: format,
1631
+ time: endTimelineMeasure(timeline),
1632
+ groupId: toDevtoolsGroupId("translate", key)
1633
+ });
1634
+ msg.locale = targetLocale;
1635
+ msg.key = key;
1636
+ msg.source = format;
1637
+ return msg;
1638
+ }
1639
+ function startTimelineMeasure(context, name) {
1640
+ const emitter = context.__v_emitter;
1641
+ if (!inBrowser || !emitter) return null;
1642
+ const start = window.performance.now();
1643
+ mark?.(`intlify-message-${name}-start`);
1644
+ return {
1645
+ emitter,
1646
+ name,
1647
+ start
1648
+ };
1649
+ }
1650
+ function endTimelineMeasure({ name, start }) {
1651
+ const time = window.performance.now() - start;
1652
+ if (mark && measure) {
1653
+ const startTag = `intlify-message-${name}-start`;
1654
+ const endTag = `intlify-message-${name}-end`;
1655
+ mark(endTag);
1656
+ measure(`intlify message ${name}`, startTag, endTag);
1657
+ }
1658
+ return time;
1913
1659
  }
1914
1660
  /** @internal */
1915
1661
  function parseTranslateArgs(...args) {
1916
- const [arg1, arg2, arg3] = args;
1917
- const options = create();
1918
- if (!isString(arg1) &&
1919
- !isNumber(arg1) &&
1920
- !isMessageFunction(arg1) &&
1921
- !isMessageAST(arg1)) {
1922
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1923
- }
1924
- // prettier-ignore
1925
- const key = isNumber(arg1)
1926
- ? String(arg1)
1927
- : isMessageFunction(arg1)
1928
- ? arg1
1929
- : arg1;
1930
- if (isNumber(arg2)) {
1931
- options.plural = arg2;
1932
- }
1933
- else if (isString(arg2)) {
1934
- options.default = arg2;
1935
- }
1936
- else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
1937
- options.named = arg2;
1938
- }
1939
- else if (isArray(arg2)) {
1940
- options.list = arg2;
1941
- }
1942
- if (isNumber(arg3)) {
1943
- options.plural = arg3;
1944
- }
1945
- else if (isString(arg3)) {
1946
- options.default = arg3;
1947
- }
1948
- else if (isPlainObject(arg3)) {
1949
- assign(options, arg3);
1950
- }
1951
- return [key, options];
1662
+ const [arg1, arg2, arg3] = args;
1663
+ if (!isString(arg1) && !isNumber(arg1) && !isMessageFunction(arg1) && !isMessageAST(arg1)) throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1664
+ const key = isNumber(arg1) ? String(arg1) : isMessageFunction(arg1) ? arg1 : arg1;
1665
+ const options = create();
1666
+ if (isNumber(arg2)) options.plural = arg2;
1667
+ else if (isString(arg2)) options.default = arg2;
1668
+ else if (isPlainObject(arg2) && !isKeylessObject(arg2)) options.named = arg2;
1669
+ else if (isArray(arg2)) options.list = arg2;
1670
+ if (isNumber(arg3)) options.plural = arg3;
1671
+ else if (isString(arg3)) options.default = arg3;
1672
+ else if (isPlainObject(arg3)) assign(options, arg3);
1673
+ return [key, options];
1952
1674
  }
1953
1675
  function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
1954
- return {
1955
- locale,
1956
- key,
1957
- warnHtmlMessage,
1958
- onError: (err) => {
1959
- onError && onError(err);
1960
- {
1961
- const _source = getSourceForCodeFrame(source);
1962
- const message = `Message compilation error: ${err.message}`;
1963
- const codeFrame = err.location &&
1964
- _source &&
1965
- generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
1966
- const emitter = context.__v_emitter;
1967
- if (emitter && _source) {
1968
- emitter.emit('compile-error', {
1969
- message: _source,
1970
- error: err.message,
1971
- start: err.location && err.location.start.offset,
1972
- end: err.location && err.location.end.offset,
1973
- groupId: `${'translate'}:${key}`
1974
- });
1975
- }
1976
- console.error(codeFrame ? `${message}\n${codeFrame}` : message);
1977
- }
1978
- },
1979
- onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
1980
- };
1676
+ return {
1677
+ locale,
1678
+ key,
1679
+ warnHtmlMessage,
1680
+ onError: (err) => {
1681
+ onError?.(err);
1682
+ {
1683
+ const _source = getSourceForCodeFrame(source);
1684
+ const codeFrame = err.location && _source && generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
1685
+ const emitter = context.__v_emitter;
1686
+ if (emitter && _source) emitter.emit("compile-error", {
1687
+ message: _source,
1688
+ error: err.message,
1689
+ start: err.location && err.location.start.offset,
1690
+ end: err.location && err.location.end.offset,
1691
+ groupId: toDevtoolsGroupId("translate", key)
1692
+ });
1693
+ const message = `Message compilation error: ${err.message}`;
1694
+ throw new SyntaxError(codeFrame ? `${message}\n${codeFrame}` : message);
1695
+ }
1696
+ },
1697
+ onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
1698
+ };
1981
1699
  }
1982
1700
  function getSourceForCodeFrame(source) {
1983
- if (isString(source)) {
1984
- return source;
1985
- }
1986
- else {
1987
- if (source.loc && source.loc.source) {
1988
- return source.loc.source;
1989
- }
1990
- }
1701
+ if (isString(source)) return source;
1702
+ else if (source.loc?.source) return source.loc.source;
1991
1703
  }
1992
1704
  function getMessageContextOptions(context, locale, message, options) {
1993
- const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
1994
- const resolveMessage = (key, useLinked) => {
1995
- let val = resolveValue(message, key);
1996
- // fallback
1997
- if (val == null && (fallbackContext || useLinked)) {
1998
- const [, , message] = resolveMessageFormat(fallbackContext || context, // NOTE: if has fallbackContext, fallback to root, else if use linked, fallback to local context
1999
- key, locale, fallbackLocale, fallbackWarn, missingWarn);
2000
- val = resolveValue(message, key);
2001
- }
2002
- if (isString(val) || isMessageAST(val)) {
2003
- let occurred = false;
2004
- const onError = () => {
2005
- occurred = true;
2006
- };
2007
- const msg = compileMessageFormat(context, key, locale, val, key, onError);
2008
- return !occurred
2009
- ? msg
2010
- : NOOP_MESSAGE_FUNCTION;
2011
- }
2012
- else if (isMessageFunction(val)) {
2013
- return val;
2014
- }
2015
- else {
2016
- // TODO: should be implemented warning message
2017
- return NOOP_MESSAGE_FUNCTION;
2018
- }
2019
- };
2020
- const ctxOptions = {
2021
- locale,
2022
- modifiers,
2023
- pluralRules,
2024
- messages: resolveMessage
2025
- };
2026
- if (context.processor) {
2027
- ctxOptions.processor = context.processor;
2028
- }
2029
- if (options.list) {
2030
- ctxOptions.list = options.list;
2031
- }
2032
- if (options.named) {
2033
- ctxOptions.named = options.named;
2034
- }
2035
- if (isNumber(options.plural)) {
2036
- ctxOptions.pluralIndex = options.plural;
2037
- }
2038
- return ctxOptions;
2039
- }
2040
-
2041
- // register message compiler for jit compilation
2042
- registerMessageCompiler(compile);
2043
- // register message resolver at @intlify/core
2044
- registerMessageResolver(resolveValue);
2045
- // register fallback locale at @intlify/core
2046
- registerLocaleFallbacker(fallbackWithLocaleChain);
2047
-
2048
- export { CORE_ERROR_CODES_EXTEND_POINT, CORE_WARN_CODES_EXTEND_POINT, CoreWarnCodes, DATETIME_FORMAT_OPTIONS_KEYS, DEFAULT_LOCALE, DEFAULT_MESSAGE_DATA_TYPE, MISSING_RESOLVE_VALUE, NOT_REOSLVED, NUMBER_FORMAT_OPTIONS_KEYS, VERSION, clearCompileCache, clearDateTimeFormat, clearNumberFormat, compile, createCompileError, createCoreContext, createCoreError, createMessageContext, datetime, fallbackWithLocaleChain, fallbackWithSimple, getAdditionalMeta, getDevToolsHook, getFallbackContext, getLocale, getLocaleMessage, getWarnMessage, handleMissing, initI18nDevTools, isAlmostSameLocale, isImplicitFallback, isMessageAST, isMessageFunction, isTranslateFallbackWarn, isTranslateMissingWarn, number, parse, parseDateTimeArgs, parseNumberArgs, parseTranslateArgs, registerLocaleFallbacker, registerMessageCompiler, registerMessageResolver, resolveLocale, resolveValue, resolveWithKeyValue, setAdditionalMeta, setDevToolsHook, setFallbackContext, setLocaleMessage, translate, translateDevTools, updateFallbackLocale };
1705
+ const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
1706
+ const resolveMessage = (key, useLinked) => {
1707
+ let val = resolveValue(message, key);
1708
+ if (val == null && (fallbackContext || useLinked)) {
1709
+ const [format, , message] = resolveMessageFormat(fallbackContext || context, key, locale, fallbackLocale, fallbackWarn, missingWarn);
1710
+ val = format ?? resolveValue(message, key);
1711
+ }
1712
+ if (isString(val) || isMessageAST(val)) {
1713
+ let occurred = false;
1714
+ const onError = () => {
1715
+ occurred = true;
1716
+ };
1717
+ const msg = compileMessageFormat(context, key, locale, val, key, onError);
1718
+ return !occurred ? msg : NOOP_MESSAGE_FUNCTION;
1719
+ } else if (isMessageFunction(val)) return val;
1720
+ else return NOOP_MESSAGE_FUNCTION;
1721
+ };
1722
+ return {
1723
+ locale,
1724
+ modifiers,
1725
+ pluralRules,
1726
+ messages: resolveMessage,
1727
+ processor: context.processor ?? void 0,
1728
+ list: options.list ?? void 0,
1729
+ named: options.named ?? void 0,
1730
+ pluralIndex: isNumber(options.plural) ? options.plural : void 0
1731
+ };
1732
+ }
1733
+ export { AST_NODE_PROPS_KEYS, CORE_ERROR_CODES_EXTEND_POINT, CORE_WARN_CODES_EXTEND_POINT, CoreWarnCodes, DATETIME_FORMAT_OPTIONS_KEYS, DEFAULT_LOCALE, DEFAULT_MESSAGE_DATA_TYPE, MISSING_RESOLVE_VALUE, NOT_RESOLVED, NUMBER_FORMAT_OPTIONS_KEYS, VERSION, clearCompileCache, clearDateTimeFormat, clearNumberFormat, compile, createCompileError, createCoreContext, createCoreError, createMessageContext, datetime, fallbackWithLocaleChain, fallbackWithSimple, getLocale, getLocaleMessage, getWarnMessage, handleMissing, isAlmostSameLocale, isFallbackLocale, isImplicitFallback, isMessageAST, isMessageFormat, isMessageFunction, isTranslateFallbackWarn, isTranslateMissingWarn, isWarnOption, number, parse, parseDateTimeArgs, parseNumberArgs, parseTranslateArgs, registerLocaleFallbacker, registerMessageCompiler, registerMessageResolver, resolveLocale, resolveValue, resolveWithKeyValue, setLocaleMessage, translate, updateFallbackLocale };