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