@intlify/core-base 9.3.0-beta.9 → 9.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1563 +1,1709 @@
1
1
  /*!
2
- * core-base v9.3.0-beta.9
3
- * (c) 2022 kazuya kawaguchi
2
+ * core-base v9.4.0
3
+ * (c) 2023 kazuya kawaguchi
4
4
  * Released under the MIT License.
5
5
  */
6
6
  'use strict';
7
7
 
8
- Object.defineProperty(exports, '__esModule', { value: true });
9
-
10
8
  var messageCompiler = require('@intlify/message-compiler');
11
9
  var shared = require('@intlify/shared');
12
- var devtoolsIf = require('@intlify/devtools-if');
13
10
 
14
- const pathStateMachine = [];
15
- pathStateMachine[0 /* BEFORE_PATH */] = {
16
- ["w" /* WORKSPACE */]: [0 /* BEFORE_PATH */],
17
- ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
18
- ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
19
- ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
20
- };
21
- pathStateMachine[1 /* IN_PATH */] = {
22
- ["w" /* WORKSPACE */]: [1 /* IN_PATH */],
23
- ["." /* DOT */]: [2 /* BEFORE_IDENT */],
24
- ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
25
- ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
26
- };
27
- pathStateMachine[2 /* BEFORE_IDENT */] = {
28
- ["w" /* WORKSPACE */]: [2 /* BEFORE_IDENT */],
29
- ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
30
- ["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */]
31
- };
32
- pathStateMachine[3 /* IN_IDENT */] = {
33
- ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
34
- ["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */],
35
- ["w" /* WORKSPACE */]: [1 /* IN_PATH */, 1 /* PUSH */],
36
- ["." /* DOT */]: [2 /* BEFORE_IDENT */, 1 /* PUSH */],
37
- ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */, 1 /* PUSH */],
38
- ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */, 1 /* PUSH */]
39
- };
40
- pathStateMachine[4 /* IN_SUB_PATH */] = {
41
- ["'" /* SINGLE_QUOTE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */],
42
- ["\"" /* DOUBLE_QUOTE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */],
43
- ["[" /* LEFT_BRACKET */]: [
44
- 4 /* IN_SUB_PATH */,
45
- 2 /* INC_SUB_PATH_DEPTH */
46
- ],
47
- ["]" /* RIGHT_BRACKET */]: [1 /* IN_PATH */, 3 /* PUSH_SUB_PATH */],
48
- ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
49
- ["l" /* ELSE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */]
50
- };
51
- pathStateMachine[5 /* IN_SINGLE_QUOTE */] = {
52
- ["'" /* SINGLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
53
- ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
54
- ["l" /* ELSE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */]
55
- };
56
- pathStateMachine[6 /* IN_DOUBLE_QUOTE */] = {
57
- ["\"" /* DOUBLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
58
- ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
59
- ["l" /* ELSE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */]
60
- };
61
- /**
62
- * Check if an expression is a literal value.
63
- */
64
- const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
65
- function isLiteral(exp) {
66
- return literalValueRE.test(exp);
67
- }
68
- /**
69
- * Strip quotes from a string
70
- */
71
- function stripQuotes(str) {
72
- const a = str.charCodeAt(0);
73
- const b = str.charCodeAt(str.length - 1);
74
- return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
75
- }
76
- /**
77
- * Determine the type of a character in a keypath.
78
- */
79
- function getPathCharType(ch) {
80
- if (ch === undefined || ch === null) {
81
- return "o" /* END_OF_FAIL */;
82
- }
83
- const code = ch.charCodeAt(0);
84
- switch (code) {
85
- case 0x5b: // [
86
- case 0x5d: // ]
87
- case 0x2e: // .
88
- case 0x22: // "
89
- case 0x27: // '
90
- return ch;
91
- case 0x5f: // _
92
- case 0x24: // $
93
- case 0x2d: // -
94
- return "i" /* IDENT */;
95
- case 0x09: // Tab (HT)
96
- case 0x0a: // Newline (LF)
97
- case 0x0d: // Return (CR)
98
- case 0xa0: // No-break space (NBSP)
99
- case 0xfeff: // Byte Order Mark (BOM)
100
- case 0x2028: // Line Separator (LS)
101
- case 0x2029: // Paragraph Separator (PS)
102
- return "w" /* WORKSPACE */;
103
- }
104
- return "i" /* IDENT */;
105
- }
106
- /**
107
- * Format a subPath, return its plain form if it is
108
- * a literal string or number. Otherwise prepend the
109
- * dynamic indicator (*).
110
- */
111
- function formatSubPath(path) {
112
- const trimmed = path.trim();
113
- // invalid leading 0
114
- if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
115
- return false;
116
- }
117
- return isLiteral(trimmed)
118
- ? stripQuotes(trimmed)
119
- : "*" /* ASTARISK */ + trimmed;
120
- }
121
- /**
122
- * Parse a string path into an array of segments
123
- */
124
- function parse(path) {
125
- const keys = [];
126
- let index = -1;
127
- let mode = 0 /* BEFORE_PATH */;
128
- let subPathDepth = 0;
129
- let c;
130
- let key; // eslint-disable-line
131
- let newChar;
132
- let type;
133
- let transition;
134
- let action;
135
- let typeMap;
136
- const actions = [];
137
- actions[0 /* APPEND */] = () => {
138
- if (key === undefined) {
139
- key = newChar;
140
- }
141
- else {
142
- key += newChar;
143
- }
144
- };
145
- actions[1 /* PUSH */] = () => {
146
- if (key !== undefined) {
147
- keys.push(key);
148
- key = undefined;
149
- }
150
- };
151
- actions[2 /* INC_SUB_PATH_DEPTH */] = () => {
152
- actions[0 /* APPEND */]();
153
- subPathDepth++;
154
- };
155
- actions[3 /* PUSH_SUB_PATH */] = () => {
156
- if (subPathDepth > 0) {
157
- subPathDepth--;
158
- mode = 4 /* IN_SUB_PATH */;
159
- actions[0 /* APPEND */]();
160
- }
161
- else {
162
- subPathDepth = 0;
163
- if (key === undefined) {
164
- return false;
165
- }
166
- key = formatSubPath(key);
167
- if (key === false) {
168
- return false;
169
- }
170
- else {
171
- actions[1 /* PUSH */]();
172
- }
173
- }
174
- };
175
- function maybeUnescapeQuote() {
176
- const nextChar = path[index + 1];
177
- if ((mode === 5 /* IN_SINGLE_QUOTE */ &&
178
- nextChar === "'" /* SINGLE_QUOTE */) ||
179
- (mode === 6 /* IN_DOUBLE_QUOTE */ &&
180
- nextChar === "\"" /* DOUBLE_QUOTE */)) {
181
- index++;
182
- newChar = '\\' + nextChar;
183
- actions[0 /* APPEND */]();
184
- return true;
185
- }
186
- }
187
- while (mode !== null) {
188
- index++;
189
- c = path[index];
190
- if (c === '\\' && maybeUnescapeQuote()) {
191
- continue;
192
- }
193
- type = getPathCharType(c);
194
- typeMap = pathStateMachine[mode];
195
- transition = typeMap[type] || typeMap["l" /* ELSE */] || 8 /* ERROR */;
196
- // check parse error
197
- if (transition === 8 /* ERROR */) {
198
- return;
199
- }
200
- mode = transition[0];
201
- if (transition[1] !== undefined) {
202
- action = actions[transition[1]];
203
- if (action) {
204
- newChar = c;
205
- if (action() === false) {
206
- return;
207
- }
208
- }
209
- }
210
- // check parse finish
211
- if (mode === 7 /* AFTER_PATH */) {
212
- return keys;
213
- }
214
- }
215
- }
216
- // path token cache
217
- const cache = new Map();
218
- /**
219
- * key-value message resolver
220
- *
221
- * @remarks
222
- * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
223
- *
224
- * @param obj - A target object to be resolved with path
225
- * @param path - A {@link Path | path} to resolve the value of message
226
- *
227
- * @returns A resolved {@link PathValue | path value}
228
- *
229
- * @VueI18nGeneral
230
- */
231
- function resolveWithKeyValue(obj, path) {
232
- return shared.isObject(obj) ? obj[path] : null;
233
- }
234
- /**
235
- * message resolver
236
- *
237
- * @remarks
238
- * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
239
- *
240
- * @param obj - A target object to be resolved with path
241
- * @param path - A {@link Path | path} to resolve the value of message
242
- *
243
- * @returns A resolved {@link PathValue | path value}
244
- *
245
- * @VueI18nGeneral
246
- */
247
- function resolveValue(obj, path) {
248
- // check object
249
- if (!shared.isObject(obj)) {
250
- return null;
251
- }
252
- // parse path
253
- let hit = cache.get(path);
254
- if (!hit) {
255
- hit = parse(path);
256
- if (hit) {
257
- cache.set(path, hit);
258
- }
259
- }
260
- // check hit
261
- if (!hit) {
262
- return null;
263
- }
264
- // resolve path value
265
- const len = hit.length;
266
- let last = obj;
267
- let i = 0;
268
- while (i < len) {
269
- const val = last[hit[i]];
270
- if (val === undefined) {
271
- return null;
272
- }
273
- last = val;
274
- i++;
275
- }
276
- return last;
11
+ const pathStateMachine = [];
12
+ pathStateMachine[0 /* States.BEFORE_PATH */] = {
13
+ ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
14
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
15
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
16
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
17
+ };
18
+ pathStateMachine[1 /* States.IN_PATH */] = {
19
+ ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
20
+ ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
21
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
22
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
23
+ };
24
+ pathStateMachine[2 /* States.BEFORE_IDENT */] = {
25
+ ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
26
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
27
+ ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
28
+ };
29
+ pathStateMachine[3 /* States.IN_IDENT */] = {
30
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
31
+ ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
32
+ ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
33
+ ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
34
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
35
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
36
+ };
37
+ pathStateMachine[4 /* States.IN_SUB_PATH */] = {
38
+ ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
39
+ ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
40
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [
41
+ 4 /* States.IN_SUB_PATH */,
42
+ 2 /* Actions.INC_SUB_PATH_DEPTH */
43
+ ],
44
+ ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
45
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
46
+ ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
47
+ };
48
+ pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
49
+ ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
50
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
51
+ ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
52
+ };
53
+ pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
54
+ ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
55
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
56
+ ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
57
+ };
58
+ /**
59
+ * Check if an expression is a literal value.
60
+ */
61
+ const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
62
+ function isLiteral(exp) {
63
+ return literalValueRE.test(exp);
64
+ }
65
+ /**
66
+ * Strip quotes from a string
67
+ */
68
+ function stripQuotes(str) {
69
+ const a = str.charCodeAt(0);
70
+ const b = str.charCodeAt(str.length - 1);
71
+ return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
72
+ }
73
+ /**
74
+ * Determine the type of a character in a keypath.
75
+ */
76
+ function getPathCharType(ch) {
77
+ if (ch === undefined || ch === null) {
78
+ return "o" /* PathCharTypes.END_OF_FAIL */;
79
+ }
80
+ const code = ch.charCodeAt(0);
81
+ switch (code) {
82
+ case 0x5b: // [
83
+ case 0x5d: // ]
84
+ case 0x2e: // .
85
+ case 0x22: // "
86
+ case 0x27: // '
87
+ return ch;
88
+ case 0x5f: // _
89
+ case 0x24: // $
90
+ case 0x2d: // -
91
+ return "i" /* PathCharTypes.IDENT */;
92
+ case 0x09: // Tab (HT)
93
+ case 0x0a: // Newline (LF)
94
+ case 0x0d: // Return (CR)
95
+ case 0xa0: // No-break space (NBSP)
96
+ case 0xfeff: // Byte Order Mark (BOM)
97
+ case 0x2028: // Line Separator (LS)
98
+ case 0x2029: // Paragraph Separator (PS)
99
+ return "w" /* PathCharTypes.WORKSPACE */;
100
+ }
101
+ return "i" /* PathCharTypes.IDENT */;
102
+ }
103
+ /**
104
+ * Format a subPath, return its plain form if it is
105
+ * a literal string or number. Otherwise prepend the
106
+ * dynamic indicator (*).
107
+ */
108
+ function formatSubPath(path) {
109
+ const trimmed = path.trim();
110
+ // invalid leading 0
111
+ if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
112
+ return false;
113
+ }
114
+ return isLiteral(trimmed)
115
+ ? stripQuotes(trimmed)
116
+ : "*" /* PathCharTypes.ASTARISK */ + trimmed;
117
+ }
118
+ /**
119
+ * Parse a string path into an array of segments
120
+ */
121
+ function parse(path) {
122
+ const keys = [];
123
+ let index = -1;
124
+ let mode = 0 /* States.BEFORE_PATH */;
125
+ let subPathDepth = 0;
126
+ let c;
127
+ let key; // eslint-disable-line
128
+ let newChar;
129
+ let type;
130
+ let transition;
131
+ let action;
132
+ let typeMap;
133
+ const actions = [];
134
+ actions[0 /* Actions.APPEND */] = () => {
135
+ if (key === undefined) {
136
+ key = newChar;
137
+ }
138
+ else {
139
+ key += newChar;
140
+ }
141
+ };
142
+ actions[1 /* Actions.PUSH */] = () => {
143
+ if (key !== undefined) {
144
+ keys.push(key);
145
+ key = undefined;
146
+ }
147
+ };
148
+ actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
149
+ actions[0 /* Actions.APPEND */]();
150
+ subPathDepth++;
151
+ };
152
+ actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
153
+ if (subPathDepth > 0) {
154
+ subPathDepth--;
155
+ mode = 4 /* States.IN_SUB_PATH */;
156
+ actions[0 /* Actions.APPEND */]();
157
+ }
158
+ else {
159
+ subPathDepth = 0;
160
+ if (key === undefined) {
161
+ return false;
162
+ }
163
+ key = formatSubPath(key);
164
+ if (key === false) {
165
+ return false;
166
+ }
167
+ else {
168
+ actions[1 /* Actions.PUSH */]();
169
+ }
170
+ }
171
+ };
172
+ function maybeUnescapeQuote() {
173
+ const nextChar = path[index + 1];
174
+ if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
175
+ nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
176
+ (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
177
+ nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
178
+ index++;
179
+ newChar = '\\' + nextChar;
180
+ actions[0 /* Actions.APPEND */]();
181
+ return true;
182
+ }
183
+ }
184
+ while (mode !== null) {
185
+ index++;
186
+ c = path[index];
187
+ if (c === '\\' && maybeUnescapeQuote()) {
188
+ continue;
189
+ }
190
+ type = getPathCharType(c);
191
+ typeMap = pathStateMachine[mode];
192
+ transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
193
+ // check parse error
194
+ if (transition === 8 /* States.ERROR */) {
195
+ return;
196
+ }
197
+ mode = transition[0];
198
+ if (transition[1] !== undefined) {
199
+ action = actions[transition[1]];
200
+ if (action) {
201
+ newChar = c;
202
+ if (action() === false) {
203
+ return;
204
+ }
205
+ }
206
+ }
207
+ // check parse finish
208
+ if (mode === 7 /* States.AFTER_PATH */) {
209
+ return keys;
210
+ }
211
+ }
212
+ }
213
+ // path token cache
214
+ const cache = new Map();
215
+ /**
216
+ * key-value message resolver
217
+ *
218
+ * @remarks
219
+ * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
220
+ *
221
+ * @param obj - A target object to be resolved with path
222
+ * @param path - A {@link Path | path} to resolve the value of message
223
+ *
224
+ * @returns A resolved {@link PathValue | path value}
225
+ *
226
+ * @VueI18nGeneral
227
+ */
228
+ function resolveWithKeyValue(obj, path) {
229
+ return shared.isObject(obj) ? obj[path] : null;
230
+ }
231
+ /**
232
+ * message resolver
233
+ *
234
+ * @remarks
235
+ * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
236
+ *
237
+ * @param obj - A target object to be resolved with path
238
+ * @param path - A {@link Path | path} to resolve the value of message
239
+ *
240
+ * @returns A resolved {@link PathValue | path value}
241
+ *
242
+ * @VueI18nGeneral
243
+ */
244
+ function resolveValue(obj, path) {
245
+ // check object
246
+ if (!shared.isObject(obj)) {
247
+ return null;
248
+ }
249
+ // parse path
250
+ let hit = cache.get(path);
251
+ if (!hit) {
252
+ hit = parse(path);
253
+ if (hit) {
254
+ cache.set(path, hit);
255
+ }
256
+ }
257
+ // check hit
258
+ if (!hit) {
259
+ return null;
260
+ }
261
+ // resolve path value
262
+ const len = hit.length;
263
+ let last = obj;
264
+ let i = 0;
265
+ while (i < len) {
266
+ const val = last[hit[i]];
267
+ if (val === undefined) {
268
+ return null;
269
+ }
270
+ last = val;
271
+ i++;
272
+ }
273
+ return last;
277
274
  }
278
275
 
279
- const DEFAULT_MODIFIER = (str) => str;
280
- const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
281
- const DEFAULT_MESSAGE_DATA_TYPE = 'text';
282
- const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join('');
283
- const DEFAULT_INTERPOLATE = shared.toDisplayString;
284
- function pluralDefault(choice, choicesLength) {
285
- choice = Math.abs(choice);
286
- if (choicesLength === 2) {
287
- // prettier-ignore
288
- return choice
289
- ? choice > 1
290
- ? 1
291
- : 0
292
- : 1;
293
- }
294
- return choice ? Math.min(choice, 2) : 0;
295
- }
296
- function getPluralIndex(options) {
297
- // prettier-ignore
298
- const index = shared.isNumber(options.pluralIndex)
299
- ? options.pluralIndex
300
- : -1;
301
- // prettier-ignore
302
- return options.named && (shared.isNumber(options.named.count) || shared.isNumber(options.named.n))
303
- ? shared.isNumber(options.named.count)
304
- ? options.named.count
305
- : shared.isNumber(options.named.n)
306
- ? options.named.n
307
- : index
308
- : index;
309
- }
310
- function normalizeNamed(pluralIndex, props) {
311
- if (!props.count) {
312
- props.count = pluralIndex;
313
- }
314
- if (!props.n) {
315
- props.n = pluralIndex;
316
- }
317
- }
318
- function createMessageContext(options = {}) {
319
- const locale = options.locale;
320
- const pluralIndex = getPluralIndex(options);
321
- const pluralRule = shared.isObject(options.pluralRules) &&
322
- shared.isString(locale) &&
323
- shared.isFunction(options.pluralRules[locale])
324
- ? options.pluralRules[locale]
325
- : pluralDefault;
326
- const orgPluralRule = shared.isObject(options.pluralRules) &&
327
- shared.isString(locale) &&
328
- shared.isFunction(options.pluralRules[locale])
329
- ? pluralDefault
330
- : undefined;
331
- const plural = (messages) => {
332
- return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
333
- };
334
- const _list = options.list || [];
335
- const list = (index) => _list[index];
336
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
337
- const _named = options.named || {};
338
- shared.isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
339
- const named = (key) => _named[key];
340
- function message(key) {
341
- // prettier-ignore
342
- const msg = shared.isFunction(options.messages)
343
- ? options.messages(key)
344
- : shared.isObject(options.messages)
345
- ? options.messages[key]
346
- : false;
347
- return !msg
348
- ? options.parent
349
- ? options.parent.message(key) // resolve from parent messages
350
- : DEFAULT_MESSAGE
351
- : msg;
352
- }
353
- const _modifier = (name) => options.modifiers
354
- ? options.modifiers[name]
355
- : DEFAULT_MODIFIER;
356
- const normalize = shared.isPlainObject(options.processor) && shared.isFunction(options.processor.normalize)
357
- ? options.processor.normalize
358
- : DEFAULT_NORMALIZE;
359
- const interpolate = shared.isPlainObject(options.processor) &&
360
- shared.isFunction(options.processor.interpolate)
361
- ? options.processor.interpolate
362
- : DEFAULT_INTERPOLATE;
363
- const type = shared.isPlainObject(options.processor) && shared.isString(options.processor.type)
364
- ? options.processor.type
365
- : DEFAULT_MESSAGE_DATA_TYPE;
366
- const linked = (key, ...args) => {
367
- const [arg1, arg2] = args;
368
- let type = 'text';
369
- let modifier = '';
370
- if (args.length === 1) {
371
- if (shared.isObject(arg1)) {
372
- modifier = arg1.modifier || modifier;
373
- type = arg1.type || type;
374
- }
375
- else if (shared.isString(arg1)) {
376
- modifier = arg1 || modifier;
377
- }
378
- }
379
- else if (args.length === 2) {
380
- if (shared.isString(arg1)) {
381
- modifier = arg1 || modifier;
382
- }
383
- if (shared.isString(arg2)) {
384
- type = arg2 || type;
385
- }
386
- }
387
- let msg = message(key)(ctx);
388
- // The message in vnode resolved with linked are returned as an array by processor.nomalize
389
- if (type === 'vnode' && shared.isArray(msg) && modifier) {
390
- msg = msg[0];
391
- }
392
- return modifier ? _modifier(modifier)(msg, type) : msg;
393
- };
394
- const ctx = {
395
- ["list" /* LIST */]: list,
396
- ["named" /* NAMED */]: named,
397
- ["plural" /* PLURAL */]: plural,
398
- ["linked" /* LINKED */]: linked,
399
- ["message" /* MESSAGE */]: message,
400
- ["type" /* TYPE */]: type,
401
- ["interpolate" /* INTERPOLATE */]: interpolate,
402
- ["normalize" /* NORMALIZE */]: normalize
403
- };
404
- return ctx;
276
+ const DEFAULT_MODIFIER = (str) => str;
277
+ const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
278
+ const DEFAULT_MESSAGE_DATA_TYPE = 'text';
279
+ const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : shared.join(values);
280
+ const DEFAULT_INTERPOLATE = shared.toDisplayString;
281
+ function pluralDefault(choice, choicesLength) {
282
+ choice = Math.abs(choice);
283
+ if (choicesLength === 2) {
284
+ // prettier-ignore
285
+ return choice
286
+ ? choice > 1
287
+ ? 1
288
+ : 0
289
+ : 1;
290
+ }
291
+ return choice ? Math.min(choice, 2) : 0;
292
+ }
293
+ function getPluralIndex(options) {
294
+ // prettier-ignore
295
+ const index = shared.isNumber(options.pluralIndex)
296
+ ? options.pluralIndex
297
+ : -1;
298
+ // prettier-ignore
299
+ return options.named && (shared.isNumber(options.named.count) || shared.isNumber(options.named.n))
300
+ ? shared.isNumber(options.named.count)
301
+ ? options.named.count
302
+ : shared.isNumber(options.named.n)
303
+ ? options.named.n
304
+ : index
305
+ : index;
306
+ }
307
+ function normalizeNamed(pluralIndex, props) {
308
+ if (!props.count) {
309
+ props.count = pluralIndex;
310
+ }
311
+ if (!props.n) {
312
+ props.n = pluralIndex;
313
+ }
314
+ }
315
+ function createMessageContext(options = {}) {
316
+ const locale = options.locale;
317
+ const pluralIndex = getPluralIndex(options);
318
+ const pluralRule = shared.isObject(options.pluralRules) &&
319
+ shared.isString(locale) &&
320
+ shared.isFunction(options.pluralRules[locale])
321
+ ? options.pluralRules[locale]
322
+ : pluralDefault;
323
+ const orgPluralRule = shared.isObject(options.pluralRules) &&
324
+ shared.isString(locale) &&
325
+ shared.isFunction(options.pluralRules[locale])
326
+ ? pluralDefault
327
+ : undefined;
328
+ const plural = (messages) => {
329
+ return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
330
+ };
331
+ const _list = options.list || [];
332
+ const list = (index) => _list[index];
333
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
334
+ const _named = options.named || {};
335
+ shared.isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
336
+ const named = (key) => _named[key];
337
+ function message(key) {
338
+ // prettier-ignore
339
+ const msg = shared.isFunction(options.messages)
340
+ ? options.messages(key)
341
+ : shared.isObject(options.messages)
342
+ ? options.messages[key]
343
+ : false;
344
+ return !msg
345
+ ? options.parent
346
+ ? options.parent.message(key) // resolve from parent messages
347
+ : DEFAULT_MESSAGE
348
+ : msg;
349
+ }
350
+ const _modifier = (name) => options.modifiers
351
+ ? options.modifiers[name]
352
+ : DEFAULT_MODIFIER;
353
+ const normalize = shared.isPlainObject(options.processor) && shared.isFunction(options.processor.normalize)
354
+ ? options.processor.normalize
355
+ : DEFAULT_NORMALIZE;
356
+ const interpolate = shared.isPlainObject(options.processor) &&
357
+ shared.isFunction(options.processor.interpolate)
358
+ ? options.processor.interpolate
359
+ : DEFAULT_INTERPOLATE;
360
+ const type = shared.isPlainObject(options.processor) && shared.isString(options.processor.type)
361
+ ? options.processor.type
362
+ : DEFAULT_MESSAGE_DATA_TYPE;
363
+ const linked = (key, ...args) => {
364
+ const [arg1, arg2] = args;
365
+ let type = 'text';
366
+ let modifier = '';
367
+ if (args.length === 1) {
368
+ if (shared.isObject(arg1)) {
369
+ modifier = arg1.modifier || modifier;
370
+ type = arg1.type || type;
371
+ }
372
+ else if (shared.isString(arg1)) {
373
+ modifier = arg1 || modifier;
374
+ }
375
+ }
376
+ else if (args.length === 2) {
377
+ if (shared.isString(arg1)) {
378
+ modifier = arg1 || modifier;
379
+ }
380
+ if (shared.isString(arg2)) {
381
+ type = arg2 || type;
382
+ }
383
+ }
384
+ const ret = message(key)(ctx);
385
+ const msg =
386
+ // The message in vnode resolved with linked are returned as an array by processor.nomalize
387
+ type === 'vnode' && shared.isArray(ret) && modifier
388
+ ? ret[0]
389
+ : ret;
390
+ return modifier ? _modifier(modifier)(msg, type) : msg;
391
+ };
392
+ const ctx = {
393
+ ["list" /* HelperNameMap.LIST */]: list,
394
+ ["named" /* HelperNameMap.NAMED */]: named,
395
+ ["plural" /* HelperNameMap.PLURAL */]: plural,
396
+ ["linked" /* HelperNameMap.LINKED */]: linked,
397
+ ["message" /* HelperNameMap.MESSAGE */]: message,
398
+ ["type" /* HelperNameMap.TYPE */]: type,
399
+ ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
400
+ ["normalize" /* HelperNameMap.NORMALIZE */]: normalize,
401
+ ["values" /* HelperNameMap.VALUES */]: shared.assign({}, _list, _named)
402
+ };
403
+ return ctx;
405
404
  }
406
405
 
407
- let devtools = null;
408
- function setDevToolsHook(hook) {
409
- devtools = hook;
410
- }
411
- function getDevToolsHook() {
412
- return devtools;
413
- }
414
- function initI18nDevTools(i18n, version, meta) {
415
- // TODO: queue if devtools is undefined
416
- devtools &&
417
- devtools.emit(devtoolsIf.IntlifyDevToolsHooks.I18nInit, {
418
- timestamp: Date.now(),
419
- i18n,
420
- version,
421
- meta
422
- });
423
- }
424
- const translateDevTools = /* #__PURE__*/ createDevToolsHook(devtoolsIf.IntlifyDevToolsHooks.FunctionTranslate);
425
- function createDevToolsHook(hook) {
426
- return (payloads) => devtools && devtools.emit(hook, payloads);
406
+ let devtools = null;
407
+ function setDevToolsHook(hook) {
408
+ devtools = hook;
409
+ }
410
+ function getDevToolsHook() {
411
+ return devtools;
412
+ }
413
+ function initI18nDevTools(i18n, version, meta) {
414
+ // TODO: queue if devtools is undefined
415
+ devtools &&
416
+ devtools.emit("i18n:init" /* IntlifyDevToolsHooks.I18nInit */, {
417
+ timestamp: Date.now(),
418
+ i18n,
419
+ version,
420
+ meta
421
+ });
422
+ }
423
+ const translateDevTools = /* #__PURE__*/ createDevToolsHook("function:translate" /* IntlifyDevToolsHooks.FunctionTranslate */);
424
+ function createDevToolsHook(hook) {
425
+ return (payloads) => devtools && devtools.emit(hook, payloads);
427
426
  }
428
427
 
429
- const CoreWarnCodes = {
430
- NOT_FOUND_KEY: 1,
431
- FALLBACK_TO_TRANSLATE: 2,
432
- CANNOT_FORMAT_NUMBER: 3,
433
- FALLBACK_TO_NUMBER_FORMAT: 4,
434
- CANNOT_FORMAT_DATE: 5,
435
- FALLBACK_TO_DATE_FORMAT: 6,
436
- __EXTEND_POINT__: 7
437
- };
438
- /** @internal */
439
- const warnMessages = {
440
- [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
441
- [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
442
- [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
443
- [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
444
- [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
445
- [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`
446
- };
447
- function getWarnMessage(code, ...args) {
448
- return shared.format(warnMessages[code], ...args);
428
+ const CoreWarnCodes = {
429
+ NOT_FOUND_KEY: 1,
430
+ FALLBACK_TO_TRANSLATE: 2,
431
+ CANNOT_FORMAT_NUMBER: 3,
432
+ FALLBACK_TO_NUMBER_FORMAT: 4,
433
+ CANNOT_FORMAT_DATE: 5,
434
+ FALLBACK_TO_DATE_FORMAT: 6,
435
+ EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: 7,
436
+ __EXTEND_POINT__: 8
437
+ };
438
+ /** @internal */
439
+ const warnMessages = {
440
+ [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
441
+ [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
442
+ [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
443
+ [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
444
+ [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
445
+ [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
446
+ [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.`
447
+ };
448
+ function getWarnMessage(code, ...args) {
449
+ return shared.format(warnMessages[code], ...args);
449
450
  }
450
451
 
451
- /**
452
- * Fallback with simple implemenation
453
- *
454
- * @remarks
455
- * A fallback locale function implemented with a simple fallback algorithm.
456
- *
457
- * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
458
- *
459
- * @param ctx - A {@link CoreContext | context}
460
- * @param fallback - A {@link FallbackLocale | fallback locale}
461
- * @param start - A starting {@link Locale | locale}
462
- *
463
- * @returns Fallback locales
464
- *
465
- * @VueI18nGeneral
466
- */
467
- function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
468
- ) {
469
- // prettier-ignore
470
- return [...new Set([
471
- start,
472
- ...(shared.isArray(fallback)
473
- ? fallback
474
- : shared.isObject(fallback)
475
- ? Object.keys(fallback)
476
- : shared.isString(fallback)
477
- ? [fallback]
478
- : [start])
479
- ])];
480
- }
481
- /**
482
- * Fallback with locale chain
483
- *
484
- * @remarks
485
- * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
486
- *
487
- * @param ctx - A {@link CoreContext | context}
488
- * @param fallback - A {@link FallbackLocale | fallback locale}
489
- * @param start - A starting {@link Locale | locale}
490
- *
491
- * @returns Fallback locales
492
- *
493
- * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
494
- *
495
- * @VueI18nGeneral
496
- */
497
- function fallbackWithLocaleChain(ctx, fallback, start) {
498
- const startLocale = shared.isString(start) ? start : DEFAULT_LOCALE;
499
- const context = ctx;
500
- if (!context.__localeChainCache) {
501
- context.__localeChainCache = new Map();
502
- }
503
- let chain = context.__localeChainCache.get(startLocale);
504
- if (!chain) {
505
- chain = [];
506
- // first block defined by start
507
- let block = [start];
508
- // while any intervening block found
509
- while (shared.isArray(block)) {
510
- block = appendBlockToChain(chain, block, fallback);
511
- }
512
- // prettier-ignore
513
- // last block defined by default
514
- const defaults = shared.isArray(fallback) || !shared.isPlainObject(fallback)
515
- ? fallback
516
- : fallback['default']
517
- ? fallback['default']
518
- : null;
519
- // convert defaults to array
520
- block = shared.isString(defaults) ? [defaults] : defaults;
521
- if (shared.isArray(block)) {
522
- appendBlockToChain(chain, block, false);
523
- }
524
- context.__localeChainCache.set(startLocale, chain);
525
- }
526
- return chain;
527
- }
528
- function appendBlockToChain(chain, block, blocks) {
529
- let follow = true;
530
- for (let i = 0; i < block.length && shared.isBoolean(follow); i++) {
531
- const locale = block[i];
532
- if (shared.isString(locale)) {
533
- follow = appendLocaleToChain(chain, block[i], blocks);
534
- }
535
- }
536
- return follow;
537
- }
538
- function appendLocaleToChain(chain, locale, blocks) {
539
- let follow;
540
- const tokens = locale.split('-');
541
- do {
542
- const target = tokens.join('-');
543
- follow = appendItemToChain(chain, target, blocks);
544
- tokens.splice(-1, 1);
545
- } while (tokens.length && follow === true);
546
- return follow;
547
- }
548
- function appendItemToChain(chain, target, blocks) {
549
- let follow = false;
550
- if (!chain.includes(target)) {
551
- follow = true;
552
- if (target) {
553
- follow = target[target.length - 1] !== '!';
554
- const locale = target.replace(/!/g, '');
555
- chain.push(locale);
556
- if ((shared.isArray(blocks) || shared.isPlainObject(blocks)) &&
557
- blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
558
- ) {
559
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
560
- follow = blocks[locale];
561
- }
562
- }
563
- }
564
- return follow;
452
+ /**
453
+ * Fallback with simple implemenation
454
+ *
455
+ * @remarks
456
+ * A fallback locale function implemented with a simple fallback algorithm.
457
+ *
458
+ * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
459
+ *
460
+ * @param ctx - A {@link CoreContext | context}
461
+ * @param fallback - A {@link FallbackLocale | fallback locale}
462
+ * @param start - A starting {@link Locale | locale}
463
+ *
464
+ * @returns Fallback locales
465
+ *
466
+ * @VueI18nGeneral
467
+ */
468
+ function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
469
+ ) {
470
+ // prettier-ignore
471
+ return [...new Set([
472
+ start,
473
+ ...(shared.isArray(fallback)
474
+ ? fallback
475
+ : shared.isObject(fallback)
476
+ ? Object.keys(fallback)
477
+ : shared.isString(fallback)
478
+ ? [fallback]
479
+ : [start])
480
+ ])];
481
+ }
482
+ /**
483
+ * Fallback with locale chain
484
+ *
485
+ * @remarks
486
+ * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
487
+ *
488
+ * @param ctx - A {@link CoreContext | context}
489
+ * @param fallback - A {@link FallbackLocale | fallback locale}
490
+ * @param start - A starting {@link Locale | locale}
491
+ *
492
+ * @returns Fallback locales
493
+ *
494
+ * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
495
+ *
496
+ * @VueI18nGeneral
497
+ */
498
+ function fallbackWithLocaleChain(ctx, fallback, start) {
499
+ const startLocale = shared.isString(start) ? start : DEFAULT_LOCALE;
500
+ const context = ctx;
501
+ if (!context.__localeChainCache) {
502
+ context.__localeChainCache = new Map();
503
+ }
504
+ let chain = context.__localeChainCache.get(startLocale);
505
+ if (!chain) {
506
+ chain = [];
507
+ // first block defined by start
508
+ let block = [start];
509
+ // while any intervening block found
510
+ while (shared.isArray(block)) {
511
+ block = appendBlockToChain(chain, block, fallback);
512
+ }
513
+ // prettier-ignore
514
+ // last block defined by default
515
+ const defaults = shared.isArray(fallback) || !shared.isPlainObject(fallback)
516
+ ? fallback
517
+ : fallback['default']
518
+ ? fallback['default']
519
+ : null;
520
+ // convert defaults to array
521
+ block = shared.isString(defaults) ? [defaults] : defaults;
522
+ if (shared.isArray(block)) {
523
+ appendBlockToChain(chain, block, false);
524
+ }
525
+ context.__localeChainCache.set(startLocale, chain);
526
+ }
527
+ return chain;
528
+ }
529
+ function appendBlockToChain(chain, block, blocks) {
530
+ let follow = true;
531
+ for (let i = 0; i < block.length && shared.isBoolean(follow); i++) {
532
+ const locale = block[i];
533
+ if (shared.isString(locale)) {
534
+ follow = appendLocaleToChain(chain, block[i], blocks);
535
+ }
536
+ }
537
+ return follow;
538
+ }
539
+ function appendLocaleToChain(chain, locale, blocks) {
540
+ let follow;
541
+ const tokens = locale.split('-');
542
+ do {
543
+ const target = tokens.join('-');
544
+ follow = appendItemToChain(chain, target, blocks);
545
+ tokens.splice(-1, 1);
546
+ } while (tokens.length && follow === true);
547
+ return follow;
548
+ }
549
+ function appendItemToChain(chain, target, blocks) {
550
+ let follow = false;
551
+ if (!chain.includes(target)) {
552
+ follow = true;
553
+ if (target) {
554
+ follow = target[target.length - 1] !== '!';
555
+ const locale = target.replace(/!/g, '');
556
+ chain.push(locale);
557
+ if ((shared.isArray(blocks) || shared.isPlainObject(blocks)) &&
558
+ blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
559
+ ) {
560
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
561
+ follow = blocks[locale];
562
+ }
563
+ }
564
+ }
565
+ return follow;
565
566
  }
566
567
 
567
- /* eslint-disable @typescript-eslint/no-explicit-any */
568
- /**
569
- * Intlify core-base version
570
- * @internal
571
- */
572
- const VERSION = '9.3.0-beta.9';
573
- const NOT_REOSLVED = -1;
574
- const DEFAULT_LOCALE = 'en-US';
575
- const MISSING_RESOLVE_VALUE = '';
576
- const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
577
- function getDefaultLinkedModifiers() {
578
- return {
579
- upper: (val, type) => {
580
- // prettier-ignore
581
- return type === 'text' && shared.isString(val)
582
- ? val.toUpperCase()
583
- : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
584
- ? val.children.toUpperCase()
585
- : val;
586
- },
587
- lower: (val, type) => {
588
- // prettier-ignore
589
- return type === 'text' && shared.isString(val)
590
- ? val.toLowerCase()
591
- : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
592
- ? val.children.toLowerCase()
593
- : val;
594
- },
595
- capitalize: (val, type) => {
596
- // prettier-ignore
597
- return (type === 'text' && shared.isString(val)
598
- ? capitalize(val)
599
- : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
600
- ? capitalize(val.children)
601
- : val);
602
- }
603
- };
604
- }
605
- let _compiler;
606
- function registerMessageCompiler(compiler) {
607
- _compiler = compiler;
608
- }
609
- let _resolver;
610
- /**
611
- * Register the message resolver
612
- *
613
- * @param resolver - A {@link MessageResolver} function
614
- *
615
- * @VueI18nGeneral
616
- */
617
- function registerMessageResolver(resolver) {
618
- _resolver = resolver;
619
- }
620
- let _fallbacker;
621
- /**
622
- * Register the locale fallbacker
623
- *
624
- * @param fallbacker - A {@link LocaleFallbacker} function
625
- *
626
- * @VueI18nGeneral
627
- */
628
- function registerLocaleFallbacker(fallbacker) {
629
- _fallbacker = fallbacker;
630
- }
631
- // Additional Meta for Intlify DevTools
632
- let _additionalMeta = null;
633
- const setAdditionalMeta = (meta) => {
634
- _additionalMeta = meta;
635
- };
636
- const getAdditionalMeta = () => _additionalMeta;
637
- let _fallbackContext = null;
638
- const setFallbackContext = (context) => {
639
- _fallbackContext = context;
640
- };
641
- const getFallbackContext = () => _fallbackContext;
642
- // ID for CoreContext
643
- let _cid = 0;
644
- function createCoreContext(options = {}) {
645
- // setup options
646
- const version = shared.isString(options.version) ? options.version : VERSION;
647
- const locale = shared.isString(options.locale) ? options.locale : DEFAULT_LOCALE;
648
- const fallbackLocale = shared.isArray(options.fallbackLocale) ||
649
- shared.isPlainObject(options.fallbackLocale) ||
650
- shared.isString(options.fallbackLocale) ||
651
- options.fallbackLocale === false
652
- ? options.fallbackLocale
653
- : locale;
654
- const messages = shared.isPlainObject(options.messages)
655
- ? options.messages
656
- : { [locale]: {} };
657
- const datetimeFormats = shared.isPlainObject(options.datetimeFormats)
658
- ? options.datetimeFormats
659
- : { [locale]: {} }
660
- ;
661
- const numberFormats = shared.isPlainObject(options.numberFormats)
662
- ? options.numberFormats
663
- : { [locale]: {} }
664
- ;
665
- const modifiers = shared.assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
666
- const pluralRules = options.pluralRules || {};
667
- const missing = shared.isFunction(options.missing) ? options.missing : null;
668
- const missingWarn = shared.isBoolean(options.missingWarn) || shared.isRegExp(options.missingWarn)
669
- ? options.missingWarn
670
- : true;
671
- const fallbackWarn = shared.isBoolean(options.fallbackWarn) || shared.isRegExp(options.fallbackWarn)
672
- ? options.fallbackWarn
673
- : true;
674
- const fallbackFormat = !!options.fallbackFormat;
675
- const unresolving = !!options.unresolving;
676
- const postTranslation = shared.isFunction(options.postTranslation)
677
- ? options.postTranslation
678
- : null;
679
- const processor = shared.isPlainObject(options.processor) ? options.processor : null;
680
- const warnHtmlMessage = shared.isBoolean(options.warnHtmlMessage)
681
- ? options.warnHtmlMessage
682
- : true;
683
- const escapeParameter = !!options.escapeParameter;
684
- const messageCompiler = shared.isFunction(options.messageCompiler)
685
- ? options.messageCompiler
686
- : _compiler;
687
- const messageResolver = shared.isFunction(options.messageResolver)
688
- ? options.messageResolver
689
- : _resolver || resolveWithKeyValue;
690
- const localeFallbacker = shared.isFunction(options.localeFallbacker)
691
- ? options.localeFallbacker
692
- : _fallbacker || fallbackWithSimple;
693
- const fallbackContext = shared.isObject(options.fallbackContext)
694
- ? options.fallbackContext
695
- : undefined;
696
- const onWarn = shared.isFunction(options.onWarn) ? options.onWarn : shared.warn;
697
- // setup internal options
698
- const internalOptions = options;
699
- const __datetimeFormatters = shared.isObject(internalOptions.__datetimeFormatters)
700
- ? internalOptions.__datetimeFormatters
701
- : new Map()
702
- ;
703
- const __numberFormatters = shared.isObject(internalOptions.__numberFormatters)
704
- ? internalOptions.__numberFormatters
705
- : new Map()
706
- ;
707
- const __meta = shared.isObject(internalOptions.__meta) ? internalOptions.__meta : {};
708
- _cid++;
709
- const context = {
710
- version,
711
- cid: _cid,
712
- locale,
713
- fallbackLocale,
714
- messages,
715
- modifiers,
716
- pluralRules,
717
- missing,
718
- missingWarn,
719
- fallbackWarn,
720
- fallbackFormat,
721
- unresolving,
722
- postTranslation,
723
- processor,
724
- warnHtmlMessage,
725
- escapeParameter,
726
- messageCompiler,
727
- messageResolver,
728
- localeFallbacker,
729
- fallbackContext,
730
- onWarn,
731
- __meta
732
- };
733
- {
734
- context.datetimeFormats = datetimeFormats;
735
- context.numberFormats = numberFormats;
736
- context.__datetimeFormatters = __datetimeFormatters;
737
- context.__numberFormatters = __numberFormatters;
738
- }
739
- // for vue-devtools timeline event
740
- {
741
- context.__v_emitter =
742
- internalOptions.__v_emitter != null
743
- ? internalOptions.__v_emitter
744
- : undefined;
745
- }
746
- // NOTE: experimental !!
747
- {
748
- initI18nDevTools(context, version, __meta);
749
- }
750
- return context;
751
- }
752
- /** @internal */
753
- function isTranslateFallbackWarn(fallback, key) {
754
- return fallback instanceof RegExp ? fallback.test(key) : fallback;
755
- }
756
- /** @internal */
757
- function isTranslateMissingWarn(missing, key) {
758
- return missing instanceof RegExp ? missing.test(key) : missing;
759
- }
760
- /** @internal */
761
- function handleMissing(context, key, locale, missingWarn, type) {
762
- const { missing, onWarn } = context;
763
- // for vue-devtools timeline event
764
- {
765
- const emitter = context.__v_emitter;
766
- if (emitter) {
767
- emitter.emit("missing" /* MISSING */, {
768
- locale,
769
- key,
770
- type,
771
- groupId: `${type}:${key}`
772
- });
773
- }
774
- }
775
- if (missing !== null) {
776
- const ret = missing(context, locale, key, type);
777
- return shared.isString(ret) ? ret : key;
778
- }
779
- else {
780
- if (isTranslateMissingWarn(missingWarn, key)) {
781
- onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
782
- }
783
- return key;
784
- }
785
- }
786
- /** @internal */
787
- function updateFallbackLocale(ctx, locale, fallback) {
788
- const context = ctx;
789
- context.__localeChainCache = new Map();
790
- ctx.localeFallbacker(ctx, fallback, locale);
791
- }
568
+ /* eslint-disable @typescript-eslint/no-explicit-any */
569
+ /**
570
+ * Intlify core-base version
571
+ * @internal
572
+ */
573
+ const VERSION = '9.4.0';
574
+ const NOT_REOSLVED = -1;
575
+ const DEFAULT_LOCALE = 'en-US';
576
+ const MISSING_RESOLVE_VALUE = '';
577
+ const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
578
+ function getDefaultLinkedModifiers() {
579
+ return {
580
+ upper: (val, type) => {
581
+ // prettier-ignore
582
+ return type === 'text' && shared.isString(val)
583
+ ? val.toUpperCase()
584
+ : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
585
+ ? val.children.toUpperCase()
586
+ : val;
587
+ },
588
+ lower: (val, type) => {
589
+ // prettier-ignore
590
+ return type === 'text' && shared.isString(val)
591
+ ? val.toLowerCase()
592
+ : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
593
+ ? val.children.toLowerCase()
594
+ : val;
595
+ },
596
+ capitalize: (val, type) => {
597
+ // prettier-ignore
598
+ return (type === 'text' && shared.isString(val)
599
+ ? capitalize(val)
600
+ : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
601
+ ? capitalize(val.children)
602
+ : val);
603
+ }
604
+ };
605
+ }
606
+ let _compiler;
607
+ function registerMessageCompiler(compiler) {
608
+ _compiler = compiler;
609
+ }
610
+ let _resolver;
611
+ /**
612
+ * Register the message resolver
613
+ *
614
+ * @param resolver - A {@link MessageResolver} function
615
+ *
616
+ * @VueI18nGeneral
617
+ */
618
+ function registerMessageResolver(resolver) {
619
+ _resolver = resolver;
620
+ }
621
+ let _fallbacker;
622
+ /**
623
+ * Register the locale fallbacker
624
+ *
625
+ * @param fallbacker - A {@link LocaleFallbacker} function
626
+ *
627
+ * @VueI18nGeneral
628
+ */
629
+ function registerLocaleFallbacker(fallbacker) {
630
+ _fallbacker = fallbacker;
631
+ }
632
+ // Additional Meta for Intlify DevTools
633
+ let _additionalMeta = null;
634
+ const setAdditionalMeta = /* #__PURE__*/ (meta) => {
635
+ _additionalMeta = meta;
636
+ };
637
+ const getAdditionalMeta = /* #__PURE__*/ () => _additionalMeta;
638
+ let _fallbackContext = null;
639
+ const setFallbackContext = (context) => {
640
+ _fallbackContext = context;
641
+ };
642
+ const getFallbackContext = () => _fallbackContext;
643
+ // ID for CoreContext
644
+ let _cid = 0;
645
+ function createCoreContext(options = {}) {
646
+ // setup options
647
+ const onWarn = shared.isFunction(options.onWarn) ? options.onWarn : shared.warn;
648
+ const version = shared.isString(options.version) ? options.version : VERSION;
649
+ const locale = shared.isString(options.locale) ? options.locale : DEFAULT_LOCALE;
650
+ const fallbackLocale = shared.isArray(options.fallbackLocale) ||
651
+ shared.isPlainObject(options.fallbackLocale) ||
652
+ shared.isString(options.fallbackLocale) ||
653
+ options.fallbackLocale === false
654
+ ? options.fallbackLocale
655
+ : locale;
656
+ const messages = shared.isPlainObject(options.messages)
657
+ ? options.messages
658
+ : { [locale]: {} };
659
+ const datetimeFormats = shared.isPlainObject(options.datetimeFormats)
660
+ ? options.datetimeFormats
661
+ : { [locale]: {} }
662
+ ;
663
+ const numberFormats = shared.isPlainObject(options.numberFormats)
664
+ ? options.numberFormats
665
+ : { [locale]: {} }
666
+ ;
667
+ const modifiers = shared.assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
668
+ const pluralRules = options.pluralRules || {};
669
+ const missing = shared.isFunction(options.missing) ? options.missing : null;
670
+ const missingWarn = shared.isBoolean(options.missingWarn) || shared.isRegExp(options.missingWarn)
671
+ ? options.missingWarn
672
+ : true;
673
+ const fallbackWarn = shared.isBoolean(options.fallbackWarn) || shared.isRegExp(options.fallbackWarn)
674
+ ? options.fallbackWarn
675
+ : true;
676
+ const fallbackFormat = !!options.fallbackFormat;
677
+ const unresolving = !!options.unresolving;
678
+ const postTranslation = shared.isFunction(options.postTranslation)
679
+ ? options.postTranslation
680
+ : null;
681
+ const processor = shared.isPlainObject(options.processor) ? options.processor : null;
682
+ const warnHtmlMessage = shared.isBoolean(options.warnHtmlMessage)
683
+ ? options.warnHtmlMessage
684
+ : true;
685
+ const escapeParameter = !!options.escapeParameter;
686
+ const messageCompiler = shared.isFunction(options.messageCompiler)
687
+ ? options.messageCompiler
688
+ : _compiler;
689
+ if (shared.isFunction(options.messageCompiler)) {
690
+ shared.warnOnce(getWarnMessage(CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER));
691
+ }
692
+ const messageResolver = shared.isFunction(options.messageResolver)
693
+ ? options.messageResolver
694
+ : _resolver || resolveWithKeyValue;
695
+ const localeFallbacker = shared.isFunction(options.localeFallbacker)
696
+ ? options.localeFallbacker
697
+ : _fallbacker || fallbackWithSimple;
698
+ const fallbackContext = shared.isObject(options.fallbackContext)
699
+ ? options.fallbackContext
700
+ : undefined;
701
+ // setup internal options
702
+ const internalOptions = options;
703
+ const __datetimeFormatters = shared.isObject(internalOptions.__datetimeFormatters)
704
+ ? internalOptions.__datetimeFormatters
705
+ : new Map()
706
+ ;
707
+ const __numberFormatters = shared.isObject(internalOptions.__numberFormatters)
708
+ ? internalOptions.__numberFormatters
709
+ : new Map()
710
+ ;
711
+ const __meta = shared.isObject(internalOptions.__meta) ? internalOptions.__meta : {};
712
+ _cid++;
713
+ const context = {
714
+ version,
715
+ cid: _cid,
716
+ locale,
717
+ fallbackLocale,
718
+ messages,
719
+ modifiers,
720
+ pluralRules,
721
+ missing,
722
+ missingWarn,
723
+ fallbackWarn,
724
+ fallbackFormat,
725
+ unresolving,
726
+ postTranslation,
727
+ processor,
728
+ warnHtmlMessage,
729
+ escapeParameter,
730
+ messageCompiler,
731
+ messageResolver,
732
+ localeFallbacker,
733
+ fallbackContext,
734
+ onWarn,
735
+ __meta
736
+ };
737
+ {
738
+ context.datetimeFormats = datetimeFormats;
739
+ context.numberFormats = numberFormats;
740
+ context.__datetimeFormatters = __datetimeFormatters;
741
+ context.__numberFormatters = __numberFormatters;
742
+ }
743
+ // for vue-devtools timeline event
744
+ {
745
+ context.__v_emitter =
746
+ internalOptions.__v_emitter != null
747
+ ? internalOptions.__v_emitter
748
+ : undefined;
749
+ }
750
+ // NOTE: experimental !!
751
+ {
752
+ initI18nDevTools(context, version, __meta);
753
+ }
754
+ return context;
755
+ }
756
+ /** @internal */
757
+ function isTranslateFallbackWarn(fallback, key) {
758
+ return fallback instanceof RegExp ? fallback.test(key) : fallback;
759
+ }
760
+ /** @internal */
761
+ function isTranslateMissingWarn(missing, key) {
762
+ return missing instanceof RegExp ? missing.test(key) : missing;
763
+ }
764
+ /** @internal */
765
+ function handleMissing(context, key, locale, missingWarn, type) {
766
+ const { missing, onWarn } = context;
767
+ // for vue-devtools timeline event
768
+ {
769
+ const emitter = context.__v_emitter;
770
+ if (emitter) {
771
+ emitter.emit("missing" /* VueDevToolsTimelineEvents.MISSING */, {
772
+ locale,
773
+ key,
774
+ type,
775
+ groupId: `${type}:${key}`
776
+ });
777
+ }
778
+ }
779
+ if (missing !== null) {
780
+ const ret = missing(context, locale, key, type);
781
+ return shared.isString(ret) ? ret : key;
782
+ }
783
+ else {
784
+ if (isTranslateMissingWarn(missingWarn, key)) {
785
+ onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
786
+ }
787
+ return key;
788
+ }
789
+ }
790
+ /** @internal */
791
+ function updateFallbackLocale(ctx, locale, fallback) {
792
+ const context = ctx;
793
+ context.__localeChainCache = new Map();
794
+ ctx.localeFallbacker(ctx, fallback, locale);
795
+ }
792
796
  /* eslint-enable @typescript-eslint/no-explicit-any */
793
797
 
794
- const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
795
- const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
796
- function checkHtmlMessage(source, options) {
797
- const warnHtmlMessage = shared.isBoolean(options.warnHtmlMessage)
798
- ? options.warnHtmlMessage
799
- : true;
800
- if (warnHtmlMessage && RE_HTML_TAG.test(source)) {
801
- shared.warn(shared.format(WARN_MESSAGE, { source }));
802
- }
803
- }
804
- const defaultOnCacheKey = (source) => source;
805
- let compileCache = Object.create(null);
806
- function clearCompileCache() {
807
- compileCache = Object.create(null);
808
- }
809
- function compileToFunction(source, options = {}) {
810
- {
811
- // check HTML message
812
- checkHtmlMessage(source, options);
813
- // check caches
814
- const onCacheKey = options.onCacheKey || defaultOnCacheKey;
815
- const key = onCacheKey(source);
816
- const cached = compileCache[key];
817
- if (cached) {
818
- return cached;
819
- }
820
- // compile error detecting
821
- let occurred = false;
822
- const onError = options.onError || messageCompiler.defaultOnError;
823
- options.onError = (err) => {
824
- occurred = true;
825
- onError(err);
826
- };
827
- // compile
828
- const { code } = messageCompiler.baseCompile(source, options);
829
- // evaluate function
830
- const msg = new Function(`return ${code}`)();
831
- // if occurred compile error, don't cache
832
- return !occurred ? (compileCache[key] = msg) : msg;
833
- }
798
+ function format(ast) {
799
+ const msg = (ctx) => formatParts(ctx, ast);
800
+ return msg;
801
+ }
802
+ function formatParts(ctx, ast) {
803
+ const body = ast.b || ast.body;
804
+ if ((body.t || body.type) === 1 /* NodeTypes.Plural */) {
805
+ const plural = body;
806
+ const cases = plural.c || plural.cases;
807
+ return ctx.plural(cases.reduce((messages, c) => [
808
+ ...messages,
809
+ formatMessageParts(ctx, c)
810
+ ], []));
811
+ }
812
+ else {
813
+ return formatMessageParts(ctx, body);
814
+ }
815
+ }
816
+ function formatMessageParts(ctx, node) {
817
+ const _static = node.s || node.static;
818
+ if (_static) {
819
+ return ctx.type === 'text'
820
+ ? _static
821
+ : ctx.normalize([_static]);
822
+ }
823
+ else {
824
+ const messages = (node.i || node.items).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
825
+ return ctx.normalize(messages);
826
+ }
827
+ }
828
+ function formatMessagePart(ctx, node) {
829
+ const type = node.t || node.type;
830
+ switch (type) {
831
+ case 3 /* NodeTypes.Text */:
832
+ const text = node;
833
+ return (text.v || text.value);
834
+ case 9 /* NodeTypes.Literal */:
835
+ const literal = node;
836
+ return (literal.v || literal.value);
837
+ case 4 /* NodeTypes.Named */:
838
+ const named = node;
839
+ return ctx.interpolate(ctx.named(named.k || named.key));
840
+ case 5 /* NodeTypes.List */:
841
+ const list = node;
842
+ return ctx.interpolate(ctx.list(list.i || list.index));
843
+ case 6 /* NodeTypes.Linked */:
844
+ const linked = node;
845
+ const modifier = linked.m || linked.modifier;
846
+ return ctx.linked(formatMessagePart(ctx, linked.k || linked.key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);
847
+ case 7 /* NodeTypes.LinkedKey */:
848
+ const linkedKey = node;
849
+ return (linkedKey.v || linkedKey.value);
850
+ case 8 /* NodeTypes.LinkedModifier */:
851
+ const linkedModifier = node;
852
+ return (linkedModifier.v || linkedModifier.value);
853
+ default:
854
+ throw new Error(`unhandled node type on format message part: ${type}`);
855
+ }
834
856
  }
835
857
 
836
- let code = messageCompiler.CompileErrorCodes.__EXTEND_POINT__;
837
- const inc = () => ++code;
838
- const CoreErrorCodes = {
839
- INVALID_ARGUMENT: code,
840
- INVALID_DATE_ARGUMENT: inc(),
841
- INVALID_ISO_DATE_ARGUMENT: inc(),
842
- __EXTEND_POINT__: inc() // 18
843
- };
844
- function createCoreError(code) {
845
- return messageCompiler.createCompileError(code, null, { messages: errorMessages } );
846
- }
847
- /** @internal */
848
- const errorMessages = {
849
- [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
850
- [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
851
- 'Make sure your Date represents a valid date.',
852
- [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string'
858
+ const code = messageCompiler.CompileErrorCodes.__EXTEND_POINT__;
859
+ const inc = shared.incrementer(code);
860
+ const CoreErrorCodes = {
861
+ INVALID_ARGUMENT: code,
862
+ INVALID_DATE_ARGUMENT: inc(),
863
+ INVALID_ISO_DATE_ARGUMENT: inc(),
864
+ NOT_SUPPORT_NON_STRING_MESSAGE: inc(),
865
+ __EXTEND_POINT__: inc() // 22
866
+ };
867
+ function createCoreError(code) {
868
+ return messageCompiler.createCompileError(code, null, { messages: errorMessages } );
869
+ }
870
+ /** @internal */
871
+ const errorMessages = {
872
+ [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
873
+ [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
874
+ 'Make sure your Date represents a valid date.',
875
+ [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string',
876
+ [CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE]: 'Not support non-string message'
877
+ };
878
+
879
+ const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
880
+ function checkHtmlMessage(source, warnHtmlMessage) {
881
+ if (warnHtmlMessage && messageCompiler.detectHtmlTag(source)) {
882
+ shared.warn(shared.format(WARN_MESSAGE, { source }));
883
+ }
884
+ }
885
+ const defaultOnCacheKey = (message) => message;
886
+ let compileCache = Object.create(null);
887
+ function clearCompileCache() {
888
+ compileCache = Object.create(null);
889
+ }
890
+ const isMessageAST = (val) => shared.isObject(val) &&
891
+ (val.t === 0 || val.type === 0) &&
892
+ ('b' in val || 'body' in val);
893
+ function baseCompile(message, options = {}) {
894
+ // error detecting on compile
895
+ let detectError = false;
896
+ const onError = options.onError || messageCompiler.defaultOnError;
897
+ options.onError = (err) => {
898
+ detectError = true;
899
+ onError(err);
900
+ };
901
+ // compile with mesasge-compiler
902
+ return { ...messageCompiler.baseCompile(message, options), detectError };
903
+ }
904
+ const compileToFunction = /* #__PURE__*/ (message, context) => {
905
+ if (!shared.isString(message)) {
906
+ throw createCoreError(CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE);
907
+ }
908
+ {
909
+ // check HTML message
910
+ const warnHtmlMessage = shared.isBoolean(context.warnHtmlMessage)
911
+ ? context.warnHtmlMessage
912
+ : true;
913
+ checkHtmlMessage(message, warnHtmlMessage);
914
+ // check caches
915
+ const onCacheKey = context.onCacheKey || defaultOnCacheKey;
916
+ const cacheKey = onCacheKey(message);
917
+ const cached = compileCache[cacheKey];
918
+ if (cached) {
919
+ return cached;
920
+ }
921
+ // compile
922
+ const { code, detectError } = baseCompile(message, context);
923
+ // evaluate function
924
+ const msg = new Function(`return ${code}`)();
925
+ // if occurred compile error, don't cache
926
+ return !detectError
927
+ ? (compileCache[cacheKey] = msg)
928
+ : msg;
929
+ }
853
930
  };
931
+ function compile(message, context) {
932
+ if (shared.isString(message)) {
933
+ // check HTML message
934
+ const warnHtmlMessage = shared.isBoolean(context.warnHtmlMessage)
935
+ ? context.warnHtmlMessage
936
+ : true;
937
+ checkHtmlMessage(message, warnHtmlMessage);
938
+ // check caches
939
+ const onCacheKey = context.onCacheKey || defaultOnCacheKey;
940
+ const cacheKey = onCacheKey(message);
941
+ const cached = compileCache[cacheKey];
942
+ if (cached) {
943
+ return cached;
944
+ }
945
+ // compile with JIT mode
946
+ const { ast, detectError } = baseCompile(message, {
947
+ ...context,
948
+ location: true,
949
+ jit: true
950
+ });
951
+ // compose message function from AST
952
+ const msg = format(ast);
953
+ // if occurred compile error, don't cache
954
+ return !detectError
955
+ ? (compileCache[cacheKey] = msg)
956
+ : msg;
957
+ }
958
+ else {
959
+ if (!isMessageAST(message)) {
960
+ shared.warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);
961
+ return (() => message);
962
+ }
963
+ // AST case (passed from bundler)
964
+ const cacheKey = message.cacheKey;
965
+ if (cacheKey) {
966
+ const cached = compileCache[cacheKey];
967
+ if (cached) {
968
+ return cached;
969
+ }
970
+ // compose message function from message (AST)
971
+ return (compileCache[cacheKey] =
972
+ format(message));
973
+ }
974
+ else {
975
+ return format(message);
976
+ }
977
+ }
978
+ }
854
979
 
855
- const NOOP_MESSAGE_FUNCTION = () => '';
856
- const isMessageFunction = (val) => shared.isFunction(val);
857
- // implementation of `translate` function
858
- function translate(context, ...args) {
859
- const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
860
- const [key, options] = parseTranslateArgs(...args);
861
- const missingWarn = shared.isBoolean(options.missingWarn)
862
- ? options.missingWarn
863
- : context.missingWarn;
864
- const fallbackWarn = shared.isBoolean(options.fallbackWarn)
865
- ? options.fallbackWarn
866
- : context.fallbackWarn;
867
- const escapeParameter = shared.isBoolean(options.escapeParameter)
868
- ? options.escapeParameter
869
- : context.escapeParameter;
870
- const resolvedMessage = !!options.resolvedMessage;
871
- // prettier-ignore
872
- const defaultMsgOrKey = shared.isString(options.default) || shared.isBoolean(options.default) // default by function option
873
- ? !shared.isBoolean(options.default)
874
- ? options.default
875
- : (!messageCompiler ? () => key : key)
876
- : fallbackFormat // default by `fallbackFormat` option
877
- ? (!messageCompiler ? () => key : key)
878
- : '';
879
- const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
880
- const locale = shared.isString(options.locale) ? options.locale : context.locale;
881
- // escape params
882
- escapeParameter && escapeParams(options);
883
- // resolve message format
884
- // eslint-disable-next-line prefer-const
885
- let [formatScope, targetLocale, message] = !resolvedMessage
886
- ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
887
- : [
888
- key,
889
- locale,
890
- messages[locale] || {}
891
- ];
892
- // NOTE:
893
- // Fix to work around `ssrTransfrom` bug in Vite.
894
- // https://github.com/vitejs/vite/issues/4306
895
- // To get around this, use temporary variables.
896
- // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
897
- let format = formatScope;
898
- // if you use default message, set it as message format!
899
- let cacheBaseKey = key;
900
- if (!resolvedMessage &&
901
- !(shared.isString(format) || isMessageFunction(format))) {
902
- if (enableDefaultMsg) {
903
- format = defaultMsgOrKey;
904
- cacheBaseKey = format;
905
- }
906
- }
907
- // checking message format and target locale
908
- if (!resolvedMessage &&
909
- (!(shared.isString(format) || isMessageFunction(format)) ||
910
- !shared.isString(targetLocale))) {
911
- return unresolving ? NOT_REOSLVED : key;
912
- }
913
- if (shared.isString(format) && context.messageCompiler == null) {
914
- shared.warn(`The message format compilation is not supported in this build. ` +
915
- `Because message compiler isn't included. ` +
916
- `You need to pre-compilation all message format. ` +
917
- `So translate function return '${key}'.`);
918
- return key;
919
- }
920
- // setup compile error detecting
921
- let occurred = false;
922
- const errorDetector = () => {
923
- occurred = true;
924
- };
925
- // compile message format
926
- const msg = !isMessageFunction(format)
927
- ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
928
- : format;
929
- // if occurred compile error, return the message format
930
- if (occurred) {
931
- return format;
932
- }
933
- // evaluate message with context
934
- const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
935
- const msgContext = createMessageContext(ctxOptions);
936
- const messaged = evaluateMessage(context, msg, msgContext);
937
- // if use post translation option, proceed it with handler
938
- const ret = postTranslation
939
- ? postTranslation(messaged, key)
940
- : messaged;
941
- // NOTE: experimental !!
942
- {
943
- // prettier-ignore
944
- const payloads = {
945
- timestamp: Date.now(),
946
- key: shared.isString(key)
947
- ? key
948
- : isMessageFunction(format)
949
- ? format.key
950
- : '',
951
- locale: targetLocale || (isMessageFunction(format)
952
- ? format.locale
953
- : ''),
954
- format: shared.isString(format)
955
- ? format
956
- : isMessageFunction(format)
957
- ? format.source
958
- : '',
959
- message: ret
960
- };
961
- payloads.meta = shared.assign({}, context.__meta, getAdditionalMeta() || {});
962
- translateDevTools(payloads);
963
- }
964
- return ret;
965
- }
966
- function escapeParams(options) {
967
- if (shared.isArray(options.list)) {
968
- options.list = options.list.map(item => shared.isString(item) ? shared.escapeHtml(item) : item);
969
- }
970
- else if (shared.isObject(options.named)) {
971
- Object.keys(options.named).forEach(key => {
972
- if (shared.isString(options.named[key])) {
973
- options.named[key] = shared.escapeHtml(options.named[key]);
974
- }
975
- });
976
- }
977
- }
978
- function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
979
- const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
980
- const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
981
- let message = {};
982
- let targetLocale;
983
- let format = null;
984
- let from = locale;
985
- let to = null;
986
- const type = 'translate';
987
- for (let i = 0; i < locales.length; i++) {
988
- targetLocale = to = locales[i];
989
- if (locale !== targetLocale &&
990
- isTranslateFallbackWarn(fallbackWarn, key)) {
991
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
992
- key,
993
- target: targetLocale
994
- }));
995
- }
996
- // for vue-devtools timeline event
997
- if (locale !== targetLocale) {
998
- const emitter = context.__v_emitter;
999
- if (emitter) {
1000
- emitter.emit("fallback" /* FALBACK */, {
1001
- type,
1002
- key,
1003
- from,
1004
- to,
1005
- groupId: `${type}:${key}`
1006
- });
1007
- }
1008
- }
1009
- message =
1010
- messages[targetLocale] || {};
1011
- // for vue-devtools timeline event
1012
- let start = null;
1013
- let startTag;
1014
- let endTag;
1015
- if (shared.inBrowser) {
1016
- start = window.performance.now();
1017
- startTag = 'intlify-message-resolve-start';
1018
- endTag = 'intlify-message-resolve-end';
1019
- shared.mark && shared.mark(startTag);
1020
- }
1021
- if ((format = resolveValue(message, key)) === null) {
1022
- // if null, resolve with object key path
1023
- format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
1024
- }
1025
- // for vue-devtools timeline event
1026
- if (shared.inBrowser) {
1027
- const end = window.performance.now();
1028
- const emitter = context.__v_emitter;
1029
- if (emitter && start && format) {
1030
- emitter.emit("message-resolve" /* MESSAGE_RESOLVE */, {
1031
- type: "message-resolve" /* MESSAGE_RESOLVE */,
1032
- key,
1033
- message: format,
1034
- time: end - start,
1035
- groupId: `${type}:${key}`
1036
- });
1037
- }
1038
- if (startTag && endTag && shared.mark && shared.measure) {
1039
- shared.mark(endTag);
1040
- shared.measure('intlify message resolve', startTag, endTag);
1041
- }
1042
- }
1043
- if (shared.isString(format) || shared.isFunction(format))
1044
- break;
1045
- const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1046
- key, targetLocale, missingWarn, type);
1047
- if (missingRet !== key) {
1048
- format = missingRet;
1049
- }
1050
- from = to;
1051
- }
1052
- return [format, targetLocale, message];
1053
- }
1054
- function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
1055
- const { messageCompiler, warnHtmlMessage } = context;
1056
- if (isMessageFunction(format)) {
1057
- const msg = format;
1058
- msg.locale = msg.locale || targetLocale;
1059
- msg.key = msg.key || key;
1060
- return msg;
1061
- }
1062
- if (messageCompiler == null) {
1063
- const msg = (() => format);
1064
- msg.locale = targetLocale;
1065
- msg.key = key;
1066
- return msg;
1067
- }
1068
- // for vue-devtools timeline event
1069
- let start = null;
1070
- let startTag;
1071
- let endTag;
1072
- if (shared.inBrowser) {
1073
- start = window.performance.now();
1074
- startTag = 'intlify-message-compilation-start';
1075
- endTag = 'intlify-message-compilation-end';
1076
- shared.mark && shared.mark(startTag);
1077
- }
1078
- const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
1079
- // for vue-devtools timeline event
1080
- if (shared.inBrowser) {
1081
- const end = window.performance.now();
1082
- const emitter = context.__v_emitter;
1083
- if (emitter && start) {
1084
- emitter.emit("message-compilation" /* MESSAGE_COMPILATION */, {
1085
- type: "message-compilation" /* MESSAGE_COMPILATION */,
1086
- message: format,
1087
- time: end - start,
1088
- groupId: `${'translate'}:${key}`
1089
- });
1090
- }
1091
- if (startTag && endTag && shared.mark && shared.measure) {
1092
- shared.mark(endTag);
1093
- shared.measure('intlify message compilation', startTag, endTag);
1094
- }
1095
- }
1096
- msg.locale = targetLocale;
1097
- msg.key = key;
1098
- msg.source = format;
1099
- return msg;
1100
- }
1101
- function evaluateMessage(context, msg, msgCtx) {
1102
- // for vue-devtools timeline event
1103
- let start = null;
1104
- let startTag;
1105
- let endTag;
1106
- if (shared.inBrowser) {
1107
- start = window.performance.now();
1108
- startTag = 'intlify-message-evaluation-start';
1109
- endTag = 'intlify-message-evaluation-end';
1110
- shared.mark && shared.mark(startTag);
1111
- }
1112
- const messaged = msg(msgCtx);
1113
- // for vue-devtools timeline event
1114
- if (shared.inBrowser) {
1115
- const end = window.performance.now();
1116
- const emitter = context.__v_emitter;
1117
- if (emitter && start) {
1118
- emitter.emit("message-evaluation" /* MESSAGE_EVALUATION */, {
1119
- type: "message-evaluation" /* MESSAGE_EVALUATION */,
1120
- value: messaged,
1121
- time: end - start,
1122
- groupId: `${'translate'}:${msg.key}`
1123
- });
1124
- }
1125
- if (startTag && endTag && shared.mark && shared.measure) {
1126
- shared.mark(endTag);
1127
- shared.measure('intlify message evaluation', startTag, endTag);
1128
- }
1129
- }
1130
- return messaged;
1131
- }
1132
- /** @internal */
1133
- function parseTranslateArgs(...args) {
1134
- const [arg1, arg2, arg3] = args;
1135
- const options = {};
1136
- if (!shared.isString(arg1) && !shared.isNumber(arg1) && !isMessageFunction(arg1)) {
1137
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1138
- }
1139
- // prettier-ignore
1140
- const key = shared.isNumber(arg1)
1141
- ? String(arg1)
1142
- : isMessageFunction(arg1)
1143
- ? arg1
1144
- : arg1;
1145
- if (shared.isNumber(arg2)) {
1146
- options.plural = arg2;
1147
- }
1148
- else if (shared.isString(arg2)) {
1149
- options.default = arg2;
1150
- }
1151
- else if (shared.isPlainObject(arg2) && !shared.isEmptyObject(arg2)) {
1152
- options.named = arg2;
1153
- }
1154
- else if (shared.isArray(arg2)) {
1155
- options.list = arg2;
1156
- }
1157
- if (shared.isNumber(arg3)) {
1158
- options.plural = arg3;
1159
- }
1160
- else if (shared.isString(arg3)) {
1161
- options.default = arg3;
1162
- }
1163
- else if (shared.isPlainObject(arg3)) {
1164
- shared.assign(options, arg3);
1165
- }
1166
- return [key, options];
1167
- }
1168
- function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
1169
- return {
1170
- warnHtmlMessage,
1171
- onError: (err) => {
1172
- errorDetector && errorDetector(err);
1173
- {
1174
- const message = `Message compilation error: ${err.message}`;
1175
- const codeFrame = err.location &&
1176
- shared.generateCodeFrame(source, err.location.start.offset, err.location.end.offset);
1177
- const emitter = context.__v_emitter;
1178
- if (emitter) {
1179
- emitter.emit("compile-error" /* COMPILE_ERROR */, {
1180
- message: source,
1181
- error: err.message,
1182
- start: err.location && err.location.start.offset,
1183
- end: err.location && err.location.end.offset,
1184
- groupId: `${'translate'}:${key}`
1185
- });
1186
- }
1187
- console.error(codeFrame ? `${message}\n${codeFrame}` : message);
1188
- }
1189
- },
1190
- onCacheKey: (source) => shared.generateFormatCacheKey(locale, key, source)
1191
- };
1192
- }
1193
- function getMessageContextOptions(context, locale, message, options) {
1194
- const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
1195
- const resolveMessage = (key) => {
1196
- let val = resolveValue(message, key);
1197
- // fallback to root context
1198
- if (val == null && fallbackContext) {
1199
- const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
1200
- val = resolveValue(message, key);
1201
- }
1202
- if (shared.isString(val)) {
1203
- let occurred = false;
1204
- const errorDetector = () => {
1205
- occurred = true;
1206
- };
1207
- const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
1208
- return !occurred
1209
- ? msg
1210
- : NOOP_MESSAGE_FUNCTION;
1211
- }
1212
- else if (isMessageFunction(val)) {
1213
- return val;
1214
- }
1215
- else {
1216
- // TODO: should be implemented warning message
1217
- return NOOP_MESSAGE_FUNCTION;
1218
- }
1219
- };
1220
- const ctxOptions = {
1221
- locale,
1222
- modifiers,
1223
- pluralRules,
1224
- messages: resolveMessage
1225
- };
1226
- if (context.processor) {
1227
- ctxOptions.processor = context.processor;
1228
- }
1229
- if (options.list) {
1230
- ctxOptions.list = options.list;
1231
- }
1232
- if (options.named) {
1233
- ctxOptions.named = options.named;
1234
- }
1235
- if (shared.isNumber(options.plural)) {
1236
- ctxOptions.pluralIndex = options.plural;
1237
- }
1238
- return ctxOptions;
980
+ const NOOP_MESSAGE_FUNCTION = () => '';
981
+ const isMessageFunction = (val) => shared.isFunction(val);
982
+ // implementation of `translate` function
983
+ function translate(context, ...args) {
984
+ const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
985
+ const [key, options] = parseTranslateArgs(...args);
986
+ const missingWarn = shared.isBoolean(options.missingWarn)
987
+ ? options.missingWarn
988
+ : context.missingWarn;
989
+ const fallbackWarn = shared.isBoolean(options.fallbackWarn)
990
+ ? options.fallbackWarn
991
+ : context.fallbackWarn;
992
+ const escapeParameter = shared.isBoolean(options.escapeParameter)
993
+ ? options.escapeParameter
994
+ : context.escapeParameter;
995
+ const resolvedMessage = !!options.resolvedMessage;
996
+ // prettier-ignore
997
+ const defaultMsgOrKey = shared.isString(options.default) || shared.isBoolean(options.default) // default by function option
998
+ ? !shared.isBoolean(options.default)
999
+ ? options.default
1000
+ : (!messageCompiler ? () => key : key)
1001
+ : fallbackFormat // default by `fallbackFormat` option
1002
+ ? (!messageCompiler ? () => key : key)
1003
+ : '';
1004
+ const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
1005
+ const locale = shared.isString(options.locale) ? options.locale : context.locale;
1006
+ // escape params
1007
+ escapeParameter && escapeParams(options);
1008
+ // resolve message format
1009
+ // eslint-disable-next-line prefer-const
1010
+ let [formatScope, targetLocale, message] = !resolvedMessage
1011
+ ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
1012
+ : [
1013
+ key,
1014
+ locale,
1015
+ messages[locale] || {}
1016
+ ];
1017
+ // NOTE:
1018
+ // Fix to work around `ssrTransfrom` bug in Vite.
1019
+ // https://github.com/vitejs/vite/issues/4306
1020
+ // To get around this, use temporary variables.
1021
+ // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
1022
+ let format = formatScope;
1023
+ // if you use default message, set it as message format!
1024
+ let cacheBaseKey = key;
1025
+ if (!resolvedMessage &&
1026
+ !(shared.isString(format) ||
1027
+ isMessageAST(format) ||
1028
+ isMessageFunction(format))) {
1029
+ if (enableDefaultMsg) {
1030
+ format = defaultMsgOrKey;
1031
+ cacheBaseKey = format;
1032
+ }
1033
+ }
1034
+ // checking message format and target locale
1035
+ if (!resolvedMessage &&
1036
+ (!(shared.isString(format) ||
1037
+ isMessageAST(format) ||
1038
+ isMessageFunction(format)) ||
1039
+ !shared.isString(targetLocale))) {
1040
+ return unresolving ? NOT_REOSLVED : key;
1041
+ }
1042
+ // TODO: refactor
1043
+ if (shared.isString(format) && context.messageCompiler == null) {
1044
+ shared.warn(`The message format compilation is not supported in this build. ` +
1045
+ `Because message compiler isn't included. ` +
1046
+ `You need to pre-compilation all message format. ` +
1047
+ `So translate function return '${key}'.`);
1048
+ return key;
1049
+ }
1050
+ // setup compile error detecting
1051
+ let occurred = false;
1052
+ const onError = () => {
1053
+ occurred = true;
1054
+ };
1055
+ // compile message format
1056
+ const msg = !isMessageFunction(format)
1057
+ ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
1058
+ : format;
1059
+ // if occurred compile error, return the message format
1060
+ if (occurred) {
1061
+ return format;
1062
+ }
1063
+ // evaluate message with context
1064
+ const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
1065
+ const msgContext = createMessageContext(ctxOptions);
1066
+ const messaged = evaluateMessage(context, msg, msgContext);
1067
+ // if use post translation option, proceed it with handler
1068
+ const ret = postTranslation
1069
+ ? postTranslation(messaged, key)
1070
+ : messaged;
1071
+ // NOTE: experimental !!
1072
+ {
1073
+ // prettier-ignore
1074
+ const payloads = {
1075
+ timestamp: Date.now(),
1076
+ key: shared.isString(key)
1077
+ ? key
1078
+ : isMessageFunction(format)
1079
+ ? format.key
1080
+ : '',
1081
+ locale: targetLocale || (isMessageFunction(format)
1082
+ ? format.locale
1083
+ : ''),
1084
+ format: shared.isString(format)
1085
+ ? format
1086
+ : isMessageFunction(format)
1087
+ ? format.source
1088
+ : '',
1089
+ message: ret
1090
+ };
1091
+ payloads.meta = shared.assign({}, context.__meta, getAdditionalMeta() || {});
1092
+ translateDevTools(payloads);
1093
+ }
1094
+ return ret;
1095
+ }
1096
+ function escapeParams(options) {
1097
+ if (shared.isArray(options.list)) {
1098
+ options.list = options.list.map(item => shared.isString(item) ? shared.escapeHtml(item) : item);
1099
+ }
1100
+ else if (shared.isObject(options.named)) {
1101
+ Object.keys(options.named).forEach(key => {
1102
+ if (shared.isString(options.named[key])) {
1103
+ options.named[key] = shared.escapeHtml(options.named[key]);
1104
+ }
1105
+ });
1106
+ }
1107
+ }
1108
+ function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
1109
+ const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
1110
+ const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
1111
+ let message = {};
1112
+ let targetLocale;
1113
+ let format = null;
1114
+ let from = locale;
1115
+ let to = null;
1116
+ const type = 'translate';
1117
+ for (let i = 0; i < locales.length; i++) {
1118
+ targetLocale = to = locales[i];
1119
+ if (locale !== targetLocale &&
1120
+ isTranslateFallbackWarn(fallbackWarn, key)) {
1121
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
1122
+ key,
1123
+ target: targetLocale
1124
+ }));
1125
+ }
1126
+ // for vue-devtools timeline event
1127
+ if (locale !== targetLocale) {
1128
+ const emitter = context.__v_emitter;
1129
+ if (emitter) {
1130
+ emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
1131
+ type,
1132
+ key,
1133
+ from,
1134
+ to,
1135
+ groupId: `${type}:${key}`
1136
+ });
1137
+ }
1138
+ }
1139
+ message =
1140
+ messages[targetLocale] || {};
1141
+ // for vue-devtools timeline event
1142
+ let start = null;
1143
+ let startTag;
1144
+ let endTag;
1145
+ if (shared.inBrowser) {
1146
+ start = window.performance.now();
1147
+ startTag = 'intlify-message-resolve-start';
1148
+ endTag = 'intlify-message-resolve-end';
1149
+ shared.mark && shared.mark(startTag);
1150
+ }
1151
+ if ((format = resolveValue(message, key)) === null) {
1152
+ // if null, resolve with object key path
1153
+ format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
1154
+ }
1155
+ // for vue-devtools timeline event
1156
+ if (shared.inBrowser) {
1157
+ const end = window.performance.now();
1158
+ const emitter = context.__v_emitter;
1159
+ if (emitter && start && format) {
1160
+ emitter.emit("message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */, {
1161
+ type: "message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */,
1162
+ key,
1163
+ message: format,
1164
+ time: end - start,
1165
+ groupId: `${type}:${key}`
1166
+ });
1167
+ }
1168
+ if (startTag && endTag && shared.mark && shared.measure) {
1169
+ shared.mark(endTag);
1170
+ shared.measure('intlify message resolve', startTag, endTag);
1171
+ }
1172
+ }
1173
+ if (shared.isString(format) || isMessageAST(format) || isMessageFunction(format)) {
1174
+ break;
1175
+ }
1176
+ const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1177
+ key, targetLocale, missingWarn, type);
1178
+ if (missingRet !== key) {
1179
+ format = missingRet;
1180
+ }
1181
+ from = to;
1182
+ }
1183
+ return [format, targetLocale, message];
1184
+ }
1185
+ function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
1186
+ const { messageCompiler, warnHtmlMessage } = context;
1187
+ if (isMessageFunction(format)) {
1188
+ const msg = format;
1189
+ msg.locale = msg.locale || targetLocale;
1190
+ msg.key = msg.key || key;
1191
+ return msg;
1192
+ }
1193
+ if (messageCompiler == null) {
1194
+ const msg = (() => format);
1195
+ msg.locale = targetLocale;
1196
+ msg.key = key;
1197
+ return msg;
1198
+ }
1199
+ // for vue-devtools timeline event
1200
+ let start = null;
1201
+ let startTag;
1202
+ let endTag;
1203
+ if (shared.inBrowser) {
1204
+ start = window.performance.now();
1205
+ startTag = 'intlify-message-compilation-start';
1206
+ endTag = 'intlify-message-compilation-end';
1207
+ shared.mark && shared.mark(startTag);
1208
+ }
1209
+ const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
1210
+ // for vue-devtools timeline event
1211
+ if (shared.inBrowser) {
1212
+ const end = window.performance.now();
1213
+ const emitter = context.__v_emitter;
1214
+ if (emitter && start) {
1215
+ emitter.emit("message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */, {
1216
+ type: "message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */,
1217
+ message: format,
1218
+ time: end - start,
1219
+ groupId: `${'translate'}:${key}`
1220
+ });
1221
+ }
1222
+ if (startTag && endTag && shared.mark && shared.measure) {
1223
+ shared.mark(endTag);
1224
+ shared.measure('intlify message compilation', startTag, endTag);
1225
+ }
1226
+ }
1227
+ msg.locale = targetLocale;
1228
+ msg.key = key;
1229
+ msg.source = format;
1230
+ return msg;
1231
+ }
1232
+ function evaluateMessage(context, msg, msgCtx) {
1233
+ // for vue-devtools timeline event
1234
+ let start = null;
1235
+ let startTag;
1236
+ let endTag;
1237
+ if (shared.inBrowser) {
1238
+ start = window.performance.now();
1239
+ startTag = 'intlify-message-evaluation-start';
1240
+ endTag = 'intlify-message-evaluation-end';
1241
+ shared.mark && shared.mark(startTag);
1242
+ }
1243
+ const messaged = msg(msgCtx);
1244
+ // for vue-devtools timeline event
1245
+ if (shared.inBrowser) {
1246
+ const end = window.performance.now();
1247
+ const emitter = context.__v_emitter;
1248
+ if (emitter && start) {
1249
+ emitter.emit("message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */, {
1250
+ type: "message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */,
1251
+ value: messaged,
1252
+ time: end - start,
1253
+ groupId: `${'translate'}:${msg.key}`
1254
+ });
1255
+ }
1256
+ if (startTag && endTag && shared.mark && shared.measure) {
1257
+ shared.mark(endTag);
1258
+ shared.measure('intlify message evaluation', startTag, endTag);
1259
+ }
1260
+ }
1261
+ return messaged;
1262
+ }
1263
+ /** @internal */
1264
+ function parseTranslateArgs(...args) {
1265
+ const [arg1, arg2, arg3] = args;
1266
+ const options = {};
1267
+ if (!shared.isString(arg1) &&
1268
+ !shared.isNumber(arg1) &&
1269
+ !isMessageFunction(arg1) &&
1270
+ !isMessageAST(arg1)) {
1271
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1272
+ }
1273
+ // prettier-ignore
1274
+ const key = shared.isNumber(arg1)
1275
+ ? String(arg1)
1276
+ : isMessageFunction(arg1)
1277
+ ? arg1
1278
+ : arg1;
1279
+ if (shared.isNumber(arg2)) {
1280
+ options.plural = arg2;
1281
+ }
1282
+ else if (shared.isString(arg2)) {
1283
+ options.default = arg2;
1284
+ }
1285
+ else if (shared.isPlainObject(arg2) && !shared.isEmptyObject(arg2)) {
1286
+ options.named = arg2;
1287
+ }
1288
+ else if (shared.isArray(arg2)) {
1289
+ options.list = arg2;
1290
+ }
1291
+ if (shared.isNumber(arg3)) {
1292
+ options.plural = arg3;
1293
+ }
1294
+ else if (shared.isString(arg3)) {
1295
+ options.default = arg3;
1296
+ }
1297
+ else if (shared.isPlainObject(arg3)) {
1298
+ shared.assign(options, arg3);
1299
+ }
1300
+ return [key, options];
1301
+ }
1302
+ function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
1303
+ return {
1304
+ locale,
1305
+ key,
1306
+ warnHtmlMessage,
1307
+ onError: (err) => {
1308
+ onError && onError(err);
1309
+ {
1310
+ const _source = getSourceForCodeFrame(source);
1311
+ const message = `Message compilation error: ${err.message}`;
1312
+ const codeFrame = err.location &&
1313
+ _source &&
1314
+ shared.generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
1315
+ const emitter = context.__v_emitter;
1316
+ if (emitter && _source) {
1317
+ emitter.emit("compile-error" /* VueDevToolsTimelineEvents.COMPILE_ERROR */, {
1318
+ message: _source,
1319
+ error: err.message,
1320
+ start: err.location && err.location.start.offset,
1321
+ end: err.location && err.location.end.offset,
1322
+ groupId: `${'translate'}:${key}`
1323
+ });
1324
+ }
1325
+ console.error(codeFrame ? `${message}\n${codeFrame}` : message);
1326
+ }
1327
+ },
1328
+ onCacheKey: (source) => shared.generateFormatCacheKey(locale, key, source)
1329
+ };
1330
+ }
1331
+ function getSourceForCodeFrame(source) {
1332
+ if (shared.isString(source)) ;
1333
+ else {
1334
+ if (source.loc?.source) {
1335
+ return source.loc.source;
1336
+ }
1337
+ }
1338
+ }
1339
+ function getMessageContextOptions(context, locale, message, options) {
1340
+ const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
1341
+ const resolveMessage = (key) => {
1342
+ let val = resolveValue(message, key);
1343
+ // fallback to root context
1344
+ if (val == null && fallbackContext) {
1345
+ const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
1346
+ val = resolveValue(message, key);
1347
+ }
1348
+ if (shared.isString(val) || isMessageAST(val)) {
1349
+ let occurred = false;
1350
+ const onError = () => {
1351
+ occurred = true;
1352
+ };
1353
+ const msg = compileMessageFormat(context, key, locale, val, key, onError);
1354
+ return !occurred
1355
+ ? msg
1356
+ : NOOP_MESSAGE_FUNCTION;
1357
+ }
1358
+ else if (isMessageFunction(val)) {
1359
+ return val;
1360
+ }
1361
+ else {
1362
+ // TODO: should be implemented warning message
1363
+ return NOOP_MESSAGE_FUNCTION;
1364
+ }
1365
+ };
1366
+ const ctxOptions = {
1367
+ locale,
1368
+ modifiers,
1369
+ pluralRules,
1370
+ messages: resolveMessage
1371
+ };
1372
+ if (context.processor) {
1373
+ ctxOptions.processor = context.processor;
1374
+ }
1375
+ if (options.list) {
1376
+ ctxOptions.list = options.list;
1377
+ }
1378
+ if (options.named) {
1379
+ ctxOptions.named = options.named;
1380
+ }
1381
+ if (shared.isNumber(options.plural)) {
1382
+ ctxOptions.pluralIndex = options.plural;
1383
+ }
1384
+ return ctxOptions;
1239
1385
  }
1240
1386
 
1241
- const intlDefined = typeof Intl !== 'undefined';
1242
- const Availabilities = {
1243
- dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
1244
- numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
1387
+ const intlDefined = typeof Intl !== 'undefined';
1388
+ const Availabilities = {
1389
+ dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
1390
+ numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
1245
1391
  };
1246
1392
 
1247
- // implementation of `datetime` function
1248
- function datetime(context, ...args) {
1249
- const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1250
- const { __datetimeFormatters } = context;
1251
- if (!Availabilities.dateTimeFormat) {
1252
- onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
1253
- return MISSING_RESOLVE_VALUE;
1254
- }
1255
- const [key, value, options, overrides] = parseDateTimeArgs(...args);
1256
- const missingWarn = shared.isBoolean(options.missingWarn)
1257
- ? options.missingWarn
1258
- : context.missingWarn;
1259
- const fallbackWarn = shared.isBoolean(options.fallbackWarn)
1260
- ? options.fallbackWarn
1261
- : context.fallbackWarn;
1262
- const part = !!options.part;
1263
- const locale = shared.isString(options.locale) ? options.locale : context.locale;
1264
- const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1265
- fallbackLocale, locale);
1266
- if (!shared.isString(key) || key === '') {
1267
- return new Intl.DateTimeFormat(locale, overrides).format(value);
1268
- }
1269
- // resolve format
1270
- let datetimeFormat = {};
1271
- let targetLocale;
1272
- let format = null;
1273
- let from = locale;
1274
- let to = null;
1275
- const type = 'datetime format';
1276
- for (let i = 0; i < locales.length; i++) {
1277
- targetLocale = to = locales[i];
1278
- if (locale !== targetLocale &&
1279
- isTranslateFallbackWarn(fallbackWarn, key)) {
1280
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
1281
- key,
1282
- target: targetLocale
1283
- }));
1284
- }
1285
- // for vue-devtools timeline event
1286
- if (locale !== targetLocale) {
1287
- const emitter = context.__v_emitter;
1288
- if (emitter) {
1289
- emitter.emit("fallback" /* FALBACK */, {
1290
- type,
1291
- key,
1292
- from,
1293
- to,
1294
- groupId: `${type}:${key}`
1295
- });
1296
- }
1297
- }
1298
- datetimeFormat =
1299
- datetimeFormats[targetLocale] || {};
1300
- format = datetimeFormat[key];
1301
- if (shared.isPlainObject(format))
1302
- break;
1303
- handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1304
- from = to;
1305
- }
1306
- // checking format and target locale
1307
- if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
1308
- return unresolving ? NOT_REOSLVED : key;
1309
- }
1310
- let id = `${targetLocale}__${key}`;
1311
- if (!shared.isEmptyObject(overrides)) {
1312
- id = `${id}__${JSON.stringify(overrides)}`;
1313
- }
1314
- let formatter = __datetimeFormatters.get(id);
1315
- if (!formatter) {
1316
- formatter = new Intl.DateTimeFormat(targetLocale, shared.assign({}, format, overrides));
1317
- __datetimeFormatters.set(id, formatter);
1318
- }
1319
- return !part ? formatter.format(value) : formatter.formatToParts(value);
1320
- }
1321
- /** @internal */
1322
- const DATETIME_FORMAT_OPTIONS_KEYS = [
1323
- 'localeMatcher',
1324
- 'weekday',
1325
- 'era',
1326
- 'year',
1327
- 'month',
1328
- 'day',
1329
- 'hour',
1330
- 'minute',
1331
- 'second',
1332
- 'timeZoneName',
1333
- 'formatMatcher',
1334
- 'hour12',
1335
- 'timeZone',
1336
- 'dateStyle',
1337
- 'timeStyle',
1338
- 'calendar',
1339
- 'dayPeriod',
1340
- 'numberingSystem',
1341
- 'hourCycle',
1342
- 'fractionalSecondDigits'
1343
- ];
1344
- /** @internal */
1345
- function parseDateTimeArgs(...args) {
1346
- const [arg1, arg2, arg3, arg4] = args;
1347
- const options = {};
1348
- let overrides = {};
1349
- let value;
1350
- if (shared.isString(arg1)) {
1351
- // Only allow ISO strings - other date formats are often supported,
1352
- // but may cause different results in different browsers.
1353
- const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
1354
- if (!matches) {
1355
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1356
- }
1357
- // Some browsers can not parse the iso datetime separated by space,
1358
- // this is a compromise solution by replace the 'T'/' ' with 'T'
1359
- const dateTime = matches[3]
1360
- ? matches[3].trim().startsWith('T')
1361
- ? `${matches[1].trim()}${matches[3].trim()}`
1362
- : `${matches[1].trim()}T${matches[3].trim()}`
1363
- : matches[1].trim();
1364
- value = new Date(dateTime);
1365
- try {
1366
- // This will fail if the date is not valid
1367
- value.toISOString();
1368
- }
1369
- catch (e) {
1370
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1371
- }
1372
- }
1373
- else if (shared.isDate(arg1)) {
1374
- if (isNaN(arg1.getTime())) {
1375
- throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
1376
- }
1377
- value = arg1;
1378
- }
1379
- else if (shared.isNumber(arg1)) {
1380
- value = arg1;
1381
- }
1382
- else {
1383
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1384
- }
1385
- if (shared.isString(arg2)) {
1386
- options.key = arg2;
1387
- }
1388
- else if (shared.isPlainObject(arg2)) {
1389
- Object.keys(arg2).forEach(key => {
1390
- if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
1391
- overrides[key] = arg2[key];
1392
- }
1393
- else {
1394
- options[key] = arg2[key];
1395
- }
1396
- });
1397
- }
1398
- if (shared.isString(arg3)) {
1399
- options.locale = arg3;
1400
- }
1401
- else if (shared.isPlainObject(arg3)) {
1402
- overrides = arg3;
1403
- }
1404
- if (shared.isPlainObject(arg4)) {
1405
- overrides = arg4;
1406
- }
1407
- return [options.key || '', value, options, overrides];
1408
- }
1409
- /** @internal */
1410
- function clearDateTimeFormat(ctx, locale, format) {
1411
- const context = ctx;
1412
- for (const key in format) {
1413
- const id = `${locale}__${key}`;
1414
- if (!context.__datetimeFormatters.has(id)) {
1415
- continue;
1416
- }
1417
- context.__datetimeFormatters.delete(id);
1418
- }
1393
+ // implementation of `datetime` function
1394
+ function datetime(context, ...args) {
1395
+ const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1396
+ const { __datetimeFormatters } = context;
1397
+ if (!Availabilities.dateTimeFormat) {
1398
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
1399
+ return MISSING_RESOLVE_VALUE;
1400
+ }
1401
+ const [key, value, options, overrides] = parseDateTimeArgs(...args);
1402
+ const missingWarn = shared.isBoolean(options.missingWarn)
1403
+ ? options.missingWarn
1404
+ : context.missingWarn;
1405
+ const fallbackWarn = shared.isBoolean(options.fallbackWarn)
1406
+ ? options.fallbackWarn
1407
+ : context.fallbackWarn;
1408
+ const part = !!options.part;
1409
+ const locale = shared.isString(options.locale) ? options.locale : context.locale;
1410
+ const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1411
+ fallbackLocale, locale);
1412
+ if (!shared.isString(key) || key === '') {
1413
+ return new Intl.DateTimeFormat(locale, overrides).format(value);
1414
+ }
1415
+ // resolve format
1416
+ let datetimeFormat = {};
1417
+ let targetLocale;
1418
+ let format = null;
1419
+ let from = locale;
1420
+ let to = null;
1421
+ const type = 'datetime format';
1422
+ for (let i = 0; i < locales.length; i++) {
1423
+ targetLocale = to = locales[i];
1424
+ if (locale !== targetLocale &&
1425
+ isTranslateFallbackWarn(fallbackWarn, key)) {
1426
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
1427
+ key,
1428
+ target: targetLocale
1429
+ }));
1430
+ }
1431
+ // for vue-devtools timeline event
1432
+ if (locale !== targetLocale) {
1433
+ const emitter = context.__v_emitter;
1434
+ if (emitter) {
1435
+ emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
1436
+ type,
1437
+ key,
1438
+ from,
1439
+ to,
1440
+ groupId: `${type}:${key}`
1441
+ });
1442
+ }
1443
+ }
1444
+ datetimeFormat =
1445
+ datetimeFormats[targetLocale] || {};
1446
+ format = datetimeFormat[key];
1447
+ if (shared.isPlainObject(format))
1448
+ break;
1449
+ handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1450
+ from = to;
1451
+ }
1452
+ // checking format and target locale
1453
+ if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
1454
+ return unresolving ? NOT_REOSLVED : key;
1455
+ }
1456
+ let id = `${targetLocale}__${key}`;
1457
+ if (!shared.isEmptyObject(overrides)) {
1458
+ id = `${id}__${JSON.stringify(overrides)}`;
1459
+ }
1460
+ let formatter = __datetimeFormatters.get(id);
1461
+ if (!formatter) {
1462
+ formatter = new Intl.DateTimeFormat(targetLocale, shared.assign({}, format, overrides));
1463
+ __datetimeFormatters.set(id, formatter);
1464
+ }
1465
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
1466
+ }
1467
+ /** @internal */
1468
+ const DATETIME_FORMAT_OPTIONS_KEYS = [
1469
+ 'localeMatcher',
1470
+ 'weekday',
1471
+ 'era',
1472
+ 'year',
1473
+ 'month',
1474
+ 'day',
1475
+ 'hour',
1476
+ 'minute',
1477
+ 'second',
1478
+ 'timeZoneName',
1479
+ 'formatMatcher',
1480
+ 'hour12',
1481
+ 'timeZone',
1482
+ 'dateStyle',
1483
+ 'timeStyle',
1484
+ 'calendar',
1485
+ 'dayPeriod',
1486
+ 'numberingSystem',
1487
+ 'hourCycle',
1488
+ 'fractionalSecondDigits'
1489
+ ];
1490
+ /** @internal */
1491
+ function parseDateTimeArgs(...args) {
1492
+ const [arg1, arg2, arg3, arg4] = args;
1493
+ const options = {};
1494
+ let overrides = {};
1495
+ let value;
1496
+ if (shared.isString(arg1)) {
1497
+ // Only allow ISO strings - other date formats are often supported,
1498
+ // but may cause different results in different browsers.
1499
+ const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
1500
+ if (!matches) {
1501
+ throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1502
+ }
1503
+ // Some browsers can not parse the iso datetime separated by space,
1504
+ // this is a compromise solution by replace the 'T'/' ' with 'T'
1505
+ const dateTime = matches[3]
1506
+ ? matches[3].trim().startsWith('T')
1507
+ ? `${matches[1].trim()}${matches[3].trim()}`
1508
+ : `${matches[1].trim()}T${matches[3].trim()}`
1509
+ : matches[1].trim();
1510
+ value = new Date(dateTime);
1511
+ try {
1512
+ // This will fail if the date is not valid
1513
+ value.toISOString();
1514
+ }
1515
+ catch (e) {
1516
+ throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1517
+ }
1518
+ }
1519
+ else if (shared.isDate(arg1)) {
1520
+ if (isNaN(arg1.getTime())) {
1521
+ throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
1522
+ }
1523
+ value = arg1;
1524
+ }
1525
+ else if (shared.isNumber(arg1)) {
1526
+ value = arg1;
1527
+ }
1528
+ else {
1529
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1530
+ }
1531
+ if (shared.isString(arg2)) {
1532
+ options.key = arg2;
1533
+ }
1534
+ else if (shared.isPlainObject(arg2)) {
1535
+ Object.keys(arg2).forEach(key => {
1536
+ if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
1537
+ overrides[key] = arg2[key];
1538
+ }
1539
+ else {
1540
+ options[key] = arg2[key];
1541
+ }
1542
+ });
1543
+ }
1544
+ if (shared.isString(arg3)) {
1545
+ options.locale = arg3;
1546
+ }
1547
+ else if (shared.isPlainObject(arg3)) {
1548
+ overrides = arg3;
1549
+ }
1550
+ if (shared.isPlainObject(arg4)) {
1551
+ overrides = arg4;
1552
+ }
1553
+ return [options.key || '', value, options, overrides];
1554
+ }
1555
+ /** @internal */
1556
+ function clearDateTimeFormat(ctx, locale, format) {
1557
+ const context = ctx;
1558
+ for (const key in format) {
1559
+ const id = `${locale}__${key}`;
1560
+ if (!context.__datetimeFormatters.has(id)) {
1561
+ continue;
1562
+ }
1563
+ context.__datetimeFormatters.delete(id);
1564
+ }
1419
1565
  }
1420
1566
 
1421
- // implementation of `number` function
1422
- function number(context, ...args) {
1423
- const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1424
- const { __numberFormatters } = context;
1425
- if (!Availabilities.numberFormat) {
1426
- onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
1427
- return MISSING_RESOLVE_VALUE;
1428
- }
1429
- const [key, value, options, overrides] = parseNumberArgs(...args);
1430
- const missingWarn = shared.isBoolean(options.missingWarn)
1431
- ? options.missingWarn
1432
- : context.missingWarn;
1433
- const fallbackWarn = shared.isBoolean(options.fallbackWarn)
1434
- ? options.fallbackWarn
1435
- : context.fallbackWarn;
1436
- const part = !!options.part;
1437
- const locale = shared.isString(options.locale) ? options.locale : context.locale;
1438
- const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1439
- fallbackLocale, locale);
1440
- if (!shared.isString(key) || key === '') {
1441
- return new Intl.NumberFormat(locale, overrides).format(value);
1442
- }
1443
- // resolve format
1444
- let numberFormat = {};
1445
- let targetLocale;
1446
- let format = null;
1447
- let from = locale;
1448
- let to = null;
1449
- const type = 'number format';
1450
- for (let i = 0; i < locales.length; i++) {
1451
- targetLocale = to = locales[i];
1452
- if (locale !== targetLocale &&
1453
- isTranslateFallbackWarn(fallbackWarn, key)) {
1454
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
1455
- key,
1456
- target: targetLocale
1457
- }));
1458
- }
1459
- // for vue-devtools timeline event
1460
- if (locale !== targetLocale) {
1461
- const emitter = context.__v_emitter;
1462
- if (emitter) {
1463
- emitter.emit("fallback" /* FALBACK */, {
1464
- type,
1465
- key,
1466
- from,
1467
- to,
1468
- groupId: `${type}:${key}`
1469
- });
1470
- }
1471
- }
1472
- numberFormat =
1473
- numberFormats[targetLocale] || {};
1474
- format = numberFormat[key];
1475
- if (shared.isPlainObject(format))
1476
- break;
1477
- handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1478
- from = to;
1479
- }
1480
- // checking format and target locale
1481
- if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
1482
- return unresolving ? NOT_REOSLVED : key;
1483
- }
1484
- let id = `${targetLocale}__${key}`;
1485
- if (!shared.isEmptyObject(overrides)) {
1486
- id = `${id}__${JSON.stringify(overrides)}`;
1487
- }
1488
- let formatter = __numberFormatters.get(id);
1489
- if (!formatter) {
1490
- formatter = new Intl.NumberFormat(targetLocale, shared.assign({}, format, overrides));
1491
- __numberFormatters.set(id, formatter);
1492
- }
1493
- return !part ? formatter.format(value) : formatter.formatToParts(value);
1494
- }
1495
- /** @internal */
1496
- const NUMBER_FORMAT_OPTIONS_KEYS = [
1497
- 'localeMatcher',
1498
- 'style',
1499
- 'currency',
1500
- 'currencyDisplay',
1501
- 'currencySign',
1502
- 'useGrouping',
1503
- 'minimumIntegerDigits',
1504
- 'minimumFractionDigits',
1505
- 'maximumFractionDigits',
1506
- 'minimumSignificantDigits',
1507
- 'maximumSignificantDigits',
1508
- 'compactDisplay',
1509
- 'notation',
1510
- 'signDisplay',
1511
- 'unit',
1512
- 'unitDisplay',
1513
- 'roundingMode',
1514
- 'roundingPriority',
1515
- 'roundingIncrement',
1516
- 'trailingZeroDisplay'
1517
- ];
1518
- /** @internal */
1519
- function parseNumberArgs(...args) {
1520
- const [arg1, arg2, arg3, arg4] = args;
1521
- const options = {};
1522
- let overrides = {};
1523
- if (!shared.isNumber(arg1)) {
1524
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1525
- }
1526
- const value = arg1;
1527
- if (shared.isString(arg2)) {
1528
- options.key = arg2;
1529
- }
1530
- else if (shared.isPlainObject(arg2)) {
1531
- Object.keys(arg2).forEach(key => {
1532
- if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
1533
- overrides[key] = arg2[key];
1534
- }
1535
- else {
1536
- options[key] = arg2[key];
1537
- }
1538
- });
1539
- }
1540
- if (shared.isString(arg3)) {
1541
- options.locale = arg3;
1542
- }
1543
- else if (shared.isPlainObject(arg3)) {
1544
- overrides = arg3;
1545
- }
1546
- if (shared.isPlainObject(arg4)) {
1547
- overrides = arg4;
1548
- }
1549
- return [options.key || '', value, options, overrides];
1550
- }
1551
- /** @internal */
1552
- function clearNumberFormat(ctx, locale, format) {
1553
- const context = ctx;
1554
- for (const key in format) {
1555
- const id = `${locale}__${key}`;
1556
- if (!context.__numberFormatters.has(id)) {
1557
- continue;
1558
- }
1559
- context.__numberFormatters.delete(id);
1560
- }
1567
+ // implementation of `number` function
1568
+ function number(context, ...args) {
1569
+ const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1570
+ const { __numberFormatters } = context;
1571
+ if (!Availabilities.numberFormat) {
1572
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
1573
+ return MISSING_RESOLVE_VALUE;
1574
+ }
1575
+ const [key, value, options, overrides] = parseNumberArgs(...args);
1576
+ const missingWarn = shared.isBoolean(options.missingWarn)
1577
+ ? options.missingWarn
1578
+ : context.missingWarn;
1579
+ const fallbackWarn = shared.isBoolean(options.fallbackWarn)
1580
+ ? options.fallbackWarn
1581
+ : context.fallbackWarn;
1582
+ const part = !!options.part;
1583
+ const locale = shared.isString(options.locale) ? options.locale : context.locale;
1584
+ const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1585
+ fallbackLocale, locale);
1586
+ if (!shared.isString(key) || key === '') {
1587
+ return new Intl.NumberFormat(locale, overrides).format(value);
1588
+ }
1589
+ // resolve format
1590
+ let numberFormat = {};
1591
+ let targetLocale;
1592
+ let format = null;
1593
+ let from = locale;
1594
+ let to = null;
1595
+ const type = 'number format';
1596
+ for (let i = 0; i < locales.length; i++) {
1597
+ targetLocale = to = locales[i];
1598
+ if (locale !== targetLocale &&
1599
+ isTranslateFallbackWarn(fallbackWarn, key)) {
1600
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
1601
+ key,
1602
+ target: targetLocale
1603
+ }));
1604
+ }
1605
+ // for vue-devtools timeline event
1606
+ if (locale !== targetLocale) {
1607
+ const emitter = context.__v_emitter;
1608
+ if (emitter) {
1609
+ emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
1610
+ type,
1611
+ key,
1612
+ from,
1613
+ to,
1614
+ groupId: `${type}:${key}`
1615
+ });
1616
+ }
1617
+ }
1618
+ numberFormat =
1619
+ numberFormats[targetLocale] || {};
1620
+ format = numberFormat[key];
1621
+ if (shared.isPlainObject(format))
1622
+ break;
1623
+ handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1624
+ from = to;
1625
+ }
1626
+ // checking format and target locale
1627
+ if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
1628
+ return unresolving ? NOT_REOSLVED : key;
1629
+ }
1630
+ let id = `${targetLocale}__${key}`;
1631
+ if (!shared.isEmptyObject(overrides)) {
1632
+ id = `${id}__${JSON.stringify(overrides)}`;
1633
+ }
1634
+ let formatter = __numberFormatters.get(id);
1635
+ if (!formatter) {
1636
+ formatter = new Intl.NumberFormat(targetLocale, shared.assign({}, format, overrides));
1637
+ __numberFormatters.set(id, formatter);
1638
+ }
1639
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
1640
+ }
1641
+ /** @internal */
1642
+ const NUMBER_FORMAT_OPTIONS_KEYS = [
1643
+ 'localeMatcher',
1644
+ 'style',
1645
+ 'currency',
1646
+ 'currencyDisplay',
1647
+ 'currencySign',
1648
+ 'useGrouping',
1649
+ 'minimumIntegerDigits',
1650
+ 'minimumFractionDigits',
1651
+ 'maximumFractionDigits',
1652
+ 'minimumSignificantDigits',
1653
+ 'maximumSignificantDigits',
1654
+ 'compactDisplay',
1655
+ 'notation',
1656
+ 'signDisplay',
1657
+ 'unit',
1658
+ 'unitDisplay',
1659
+ 'roundingMode',
1660
+ 'roundingPriority',
1661
+ 'roundingIncrement',
1662
+ 'trailingZeroDisplay'
1663
+ ];
1664
+ /** @internal */
1665
+ function parseNumberArgs(...args) {
1666
+ const [arg1, arg2, arg3, arg4] = args;
1667
+ const options = {};
1668
+ let overrides = {};
1669
+ if (!shared.isNumber(arg1)) {
1670
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1671
+ }
1672
+ const value = arg1;
1673
+ if (shared.isString(arg2)) {
1674
+ options.key = arg2;
1675
+ }
1676
+ else if (shared.isPlainObject(arg2)) {
1677
+ Object.keys(arg2).forEach(key => {
1678
+ if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
1679
+ overrides[key] = arg2[key];
1680
+ }
1681
+ else {
1682
+ options[key] = arg2[key];
1683
+ }
1684
+ });
1685
+ }
1686
+ if (shared.isString(arg3)) {
1687
+ options.locale = arg3;
1688
+ }
1689
+ else if (shared.isPlainObject(arg3)) {
1690
+ overrides = arg3;
1691
+ }
1692
+ if (shared.isPlainObject(arg4)) {
1693
+ overrides = arg4;
1694
+ }
1695
+ return [options.key || '', value, options, overrides];
1696
+ }
1697
+ /** @internal */
1698
+ function clearNumberFormat(ctx, locale, format) {
1699
+ const context = ctx;
1700
+ for (const key in format) {
1701
+ const id = `${locale}__${key}`;
1702
+ if (!context.__numberFormatters.has(id)) {
1703
+ continue;
1704
+ }
1705
+ context.__numberFormatters.delete(id);
1706
+ }
1561
1707
  }
1562
1708
 
1563
1709
  exports.CompileErrorCodes = messageCompiler.CompileErrorCodes;
@@ -1574,6 +1720,7 @@ exports.VERSION = VERSION;
1574
1720
  exports.clearCompileCache = clearCompileCache;
1575
1721
  exports.clearDateTimeFormat = clearDateTimeFormat;
1576
1722
  exports.clearNumberFormat = clearNumberFormat;
1723
+ exports.compile = compile;
1577
1724
  exports.compileToFunction = compileToFunction;
1578
1725
  exports.createCoreContext = createCoreContext;
1579
1726
  exports.createCoreError = createCoreError;
@@ -1587,6 +1734,7 @@ exports.getFallbackContext = getFallbackContext;
1587
1734
  exports.getWarnMessage = getWarnMessage;
1588
1735
  exports.handleMissing = handleMissing;
1589
1736
  exports.initI18nDevTools = initI18nDevTools;
1737
+ exports.isMessageAST = isMessageAST;
1590
1738
  exports.isMessageFunction = isMessageFunction;
1591
1739
  exports.isTranslateFallbackWarn = isTranslateFallbackWarn;
1592
1740
  exports.isTranslateMissingWarn = isTranslateMissingWarn;