@intlify/core-base 9.3.0-beta.16 → 9.3.0-beta.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/dist/core-base.cjs +1527 -1528
  2. package/dist/core-base.d.ts +2 -2
  3. package/dist/core-base.esm-browser.js +3002 -2993
  4. package/dist/core-base.esm-browser.prod.js +2 -2
  5. package/dist/core-base.global.js +3002 -2995
  6. package/dist/core-base.global.prod.js +2 -2
  7. package/dist/core-base.mjs +1539 -1538
  8. package/dist/core-base.prod.cjs +1288 -1284
  9. package/dist/e2e/bridge/basic.spec.d.ts +2 -0
  10. package/dist/e2e/bridge/basic.spec.d.ts.map +1 -0
  11. package/dist/e2e/bridge/component.spec.d.ts +2 -0
  12. package/dist/e2e/bridge/component.spec.d.ts.map +1 -0
  13. package/dist/e2e/bridge/components/datetime-format.spec.d.ts +2 -0
  14. package/dist/e2e/bridge/components/datetime-format.spec.d.ts.map +1 -0
  15. package/dist/e2e/bridge/components/number-format.spec.d.ts +2 -0
  16. package/dist/e2e/bridge/components/number-format.spec.d.ts.map +1 -0
  17. package/dist/e2e/bridge/components/translation.spec.d.ts +2 -0
  18. package/dist/e2e/bridge/components/translation.spec.d.ts.map +1 -0
  19. package/dist/e2e/bridge/plural.spec.d.ts +2 -0
  20. package/dist/e2e/bridge/plural.spec.d.ts.map +1 -0
  21. package/dist/e2e/bridge/scope/global.spec.d.ts +2 -0
  22. package/dist/e2e/bridge/scope/global.spec.d.ts.map +1 -0
  23. package/dist/e2e/bridge/scope/inherit-locale.spec.d.ts +2 -0
  24. package/dist/e2e/bridge/scope/inherit-locale.spec.d.ts.map +1 -0
  25. package/dist/e2e/bridge/scope/local.spec.d.ts +2 -0
  26. package/dist/e2e/bridge/scope/local.spec.d.ts.map +1 -0
  27. package/dist/e2e/components/datetime-format.spec.d.ts +2 -0
  28. package/dist/e2e/components/datetime-format.spec.d.ts.map +1 -0
  29. package/dist/e2e/components/number-format.spec.d.ts +2 -0
  30. package/dist/e2e/components/number-format.spec.d.ts.map +1 -0
  31. package/dist/e2e/components/translation.spec.d.ts +2 -0
  32. package/dist/e2e/components/translation.spec.d.ts.map +1 -0
  33. package/dist/e2e/composition.spec.d.ts +2 -0
  34. package/dist/e2e/composition.spec.d.ts.map +1 -0
  35. package/dist/e2e/datetime.spec.d.ts +2 -0
  36. package/dist/e2e/datetime.spec.d.ts.map +1 -0
  37. package/dist/e2e/directive/basic.spec.d.ts +2 -0
  38. package/dist/e2e/directive/basic.spec.d.ts.map +1 -0
  39. package/dist/e2e/directive/object.spec.d.ts +2 -0
  40. package/dist/e2e/directive/object.spec.d.ts.map +1 -0
  41. package/dist/e2e/directive/plural.spec.d.ts +2 -0
  42. package/dist/e2e/directive/plural.spec.d.ts.map +1 -0
  43. package/dist/e2e/directive/preserve.spec.d.ts +2 -0
  44. package/dist/e2e/directive/preserve.spec.d.ts.map +1 -0
  45. package/dist/e2e/fallback/basic.spec.d.ts +2 -0
  46. package/dist/e2e/fallback/basic.spec.d.ts.map +1 -0
  47. package/dist/e2e/fallback/component.spec.d.ts +2 -0
  48. package/dist/e2e/fallback/component.spec.d.ts.map +1 -0
  49. package/dist/e2e/fallback/default-format.spec.d.ts +2 -0
  50. package/dist/e2e/fallback/default-format.spec.d.ts.map +1 -0
  51. package/dist/e2e/fallback/format.spec.d.ts +2 -0
  52. package/dist/e2e/fallback/format.spec.d.ts.map +1 -0
  53. package/dist/e2e/fallback/option.spec.d.ts +2 -0
  54. package/dist/e2e/fallback/option.spec.d.ts.map +1 -0
  55. package/dist/e2e/fallback/suppress.spec.d.ts +2 -0
  56. package/dist/e2e/fallback/suppress.spec.d.ts.map +1 -0
  57. package/dist/e2e/formatting/linked.spec.d.ts +2 -0
  58. package/dist/e2e/formatting/linked.spec.d.ts.map +1 -0
  59. package/dist/e2e/formatting/list.spec.d.ts +2 -0
  60. package/dist/e2e/formatting/list.spec.d.ts.map +1 -0
  61. package/dist/e2e/formatting/literal.spec.d.ts +2 -0
  62. package/dist/e2e/formatting/literal.spec.d.ts.map +1 -0
  63. package/dist/e2e/formatting/named.spec.d.ts +2 -0
  64. package/dist/e2e/formatting/named.spec.d.ts.map +1 -0
  65. package/dist/e2e/formatting/ruby.spec.d.ts +2 -0
  66. package/dist/e2e/formatting/ruby.spec.d.ts.map +1 -0
  67. package/dist/e2e/functions/linked.spec.d.ts +2 -0
  68. package/dist/e2e/functions/linked.spec.d.ts.map +1 -0
  69. package/dist/e2e/functions/list.spec.d.ts +2 -0
  70. package/dist/e2e/functions/list.spec.d.ts.map +1 -0
  71. package/dist/e2e/functions/named.spec.d.ts +2 -0
  72. package/dist/e2e/functions/named.spec.d.ts.map +1 -0
  73. package/dist/e2e/functions/plural.spec.d.ts +2 -0
  74. package/dist/e2e/functions/plural.spec.d.ts.map +1 -0
  75. package/dist/e2e/helper.d.ts +9 -0
  76. package/dist/e2e/helper.d.ts.map +1 -0
  77. package/dist/e2e/missing/handler.spec.d.ts +2 -0
  78. package/dist/e2e/missing/handler.spec.d.ts.map +1 -0
  79. package/dist/e2e/missing/option.spec.d.ts +2 -0
  80. package/dist/e2e/missing/option.spec.d.ts.map +1 -0
  81. package/dist/e2e/missing/suppress.spec.d.ts +2 -0
  82. package/dist/e2e/missing/suppress.spec.d.ts.map +1 -0
  83. package/dist/e2e/number.spec.d.ts +2 -0
  84. package/dist/e2e/number.spec.d.ts.map +1 -0
  85. package/dist/e2e/plural/basic.spec.d.ts +2 -0
  86. package/dist/e2e/plural/basic.spec.d.ts.map +1 -0
  87. package/dist/e2e/plural/custom.spec.d.ts +2 -0
  88. package/dist/e2e/plural/custom.spec.d.ts.map +1 -0
  89. package/dist/e2e/scope/global.spec.d.ts +2 -0
  90. package/dist/e2e/scope/global.spec.d.ts.map +1 -0
  91. package/dist/e2e/scope/inherit-locale.spec.d.ts +2 -0
  92. package/dist/e2e/scope/inherit-locale.spec.d.ts.map +1 -0
  93. package/dist/e2e/scope/local.spec.d.ts +2 -0
  94. package/dist/e2e/scope/local.spec.d.ts.map +1 -0
  95. package/dist/e2e/started.spec.d.ts +2 -0
  96. package/dist/e2e/started.spec.d.ts.map +1 -0
  97. package/dist/scripts/vitest.globalSetup.d.ts +2 -0
  98. package/dist/scripts/vitest.globalSetup.d.ts.map +1 -0
  99. package/dist/scripts/vitest.setup.d.ts +2 -0
  100. package/dist/scripts/vitest.setup.d.ts.map +1 -0
  101. package/package.json +6 -6
@@ -1,1573 +1,1574 @@
1
1
  /*!
2
- * core-base v9.3.0-beta.16
2
+ * core-base v9.3.0-beta.18
3
3
  * (c) 2023 kazuya kawaguchi
4
4
  * Released under the MIT License.
5
5
  */
6
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';
7
+ import { defaultOnError, baseCompile, detectHtmlTag, CompileErrorCodes, createCompileError } 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 /* States.BEFORE_PATH */] = {
13
- ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
14
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
15
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
16
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
17
- };
18
- pathStateMachine[1 /* States.IN_PATH */] = {
19
- ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
20
- ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
21
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
22
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
23
- };
24
- pathStateMachine[2 /* States.BEFORE_IDENT */] = {
25
- ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
26
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
27
- ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
28
- };
29
- pathStateMachine[3 /* States.IN_IDENT */] = {
30
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
31
- ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
32
- ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
33
- ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
34
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
35
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
36
- };
37
- pathStateMachine[4 /* States.IN_SUB_PATH */] = {
38
- ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
39
- ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
40
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [
41
- 4 /* States.IN_SUB_PATH */,
42
- 2 /* Actions.INC_SUB_PATH_DEPTH */
43
- ],
44
- ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
45
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
46
- ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
47
- };
48
- pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
49
- ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
50
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
51
- ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
52
- };
53
- pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
54
- ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
55
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
56
- ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
57
- };
58
- /**
59
- * Check if an expression is a literal value.
60
- */
61
- const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
62
- function isLiteral(exp) {
63
- return literalValueRE.test(exp);
64
- }
65
- /**
66
- * Strip quotes from a string
67
- */
68
- function stripQuotes(str) {
69
- const a = str.charCodeAt(0);
70
- const b = str.charCodeAt(str.length - 1);
71
- return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
72
- }
73
- /**
74
- * Determine the type of a character in a keypath.
75
- */
76
- function getPathCharType(ch) {
77
- if (ch === undefined || ch === null) {
78
- return "o" /* PathCharTypes.END_OF_FAIL */;
79
- }
80
- const code = ch.charCodeAt(0);
81
- switch (code) {
82
- case 0x5b: // [
83
- case 0x5d: // ]
84
- case 0x2e: // .
85
- case 0x22: // "
86
- case 0x27: // '
87
- return ch;
88
- case 0x5f: // _
89
- case 0x24: // $
90
- case 0x2d: // -
91
- return "i" /* PathCharTypes.IDENT */;
92
- case 0x09: // Tab (HT)
93
- case 0x0a: // Newline (LF)
94
- case 0x0d: // Return (CR)
95
- case 0xa0: // No-break space (NBSP)
96
- case 0xfeff: // Byte Order Mark (BOM)
97
- case 0x2028: // Line Separator (LS)
98
- case 0x2029: // Paragraph Separator (PS)
99
- return "w" /* PathCharTypes.WORKSPACE */;
100
- }
101
- return "i" /* PathCharTypes.IDENT */;
102
- }
103
- /**
104
- * Format a subPath, return its plain form if it is
105
- * a literal string or number. Otherwise prepend the
106
- * dynamic indicator (*).
107
- */
108
- function formatSubPath(path) {
109
- const trimmed = path.trim();
110
- // invalid leading 0
111
- if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
112
- return false;
113
- }
114
- return isLiteral(trimmed)
115
- ? stripQuotes(trimmed)
116
- : "*" /* PathCharTypes.ASTARISK */ + trimmed;
117
- }
118
- /**
119
- * Parse a string path into an array of segments
120
- */
121
- function parse(path) {
122
- const keys = [];
123
- let index = -1;
124
- let mode = 0 /* States.BEFORE_PATH */;
125
- let subPathDepth = 0;
126
- let c;
127
- let key; // eslint-disable-line
128
- let newChar;
129
- let type;
130
- let transition;
131
- let action;
132
- let typeMap;
133
- const actions = [];
134
- actions[0 /* Actions.APPEND */] = () => {
135
- if (key === undefined) {
136
- key = newChar;
137
- }
138
- else {
139
- key += newChar;
140
- }
141
- };
142
- actions[1 /* Actions.PUSH */] = () => {
143
- if (key !== undefined) {
144
- keys.push(key);
145
- key = undefined;
146
- }
147
- };
148
- actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
149
- actions[0 /* Actions.APPEND */]();
150
- subPathDepth++;
151
- };
152
- actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
153
- if (subPathDepth > 0) {
154
- subPathDepth--;
155
- mode = 4 /* States.IN_SUB_PATH */;
156
- actions[0 /* Actions.APPEND */]();
157
- }
158
- else {
159
- subPathDepth = 0;
160
- if (key === undefined) {
161
- return false;
162
- }
163
- key = formatSubPath(key);
164
- if (key === false) {
165
- return false;
166
- }
167
- else {
168
- actions[1 /* Actions.PUSH */]();
169
- }
170
- }
171
- };
172
- function maybeUnescapeQuote() {
173
- const nextChar = path[index + 1];
174
- if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
175
- nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
176
- (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
177
- nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
178
- index++;
179
- newChar = '\\' + nextChar;
180
- actions[0 /* Actions.APPEND */]();
181
- return true;
182
- }
183
- }
184
- while (mode !== null) {
185
- index++;
186
- c = path[index];
187
- if (c === '\\' && maybeUnescapeQuote()) {
188
- continue;
189
- }
190
- type = getPathCharType(c);
191
- typeMap = pathStateMachine[mode];
192
- transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
193
- // check parse error
194
- if (transition === 8 /* States.ERROR */) {
195
- return;
196
- }
197
- mode = transition[0];
198
- if (transition[1] !== undefined) {
199
- action = actions[transition[1]];
200
- if (action) {
201
- newChar = c;
202
- if (action() === false) {
203
- return;
204
- }
205
- }
206
- }
207
- // check parse finish
208
- if (mode === 7 /* States.AFTER_PATH */) {
209
- return keys;
210
- }
211
- }
212
- }
213
- // path token cache
214
- const cache = new Map();
215
- /**
216
- * key-value message resolver
217
- *
218
- * @remarks
219
- * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
220
- *
221
- * @param obj - A target object to be resolved with path
222
- * @param path - A {@link Path | path} to resolve the value of message
223
- *
224
- * @returns A resolved {@link PathValue | path value}
225
- *
226
- * @VueI18nGeneral
227
- */
228
- function resolveWithKeyValue(obj, path) {
229
- return 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
+ const pathStateMachine = [];
12
+ pathStateMachine[0 /* States.BEFORE_PATH */] = {
13
+ ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
14
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
15
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
16
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
17
+ };
18
+ pathStateMachine[1 /* States.IN_PATH */] = {
19
+ ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
20
+ ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
21
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
22
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
23
+ };
24
+ pathStateMachine[2 /* States.BEFORE_IDENT */] = {
25
+ ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
26
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
27
+ ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
28
+ };
29
+ pathStateMachine[3 /* States.IN_IDENT */] = {
30
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
31
+ ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
32
+ ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
33
+ ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
34
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
35
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
36
+ };
37
+ pathStateMachine[4 /* States.IN_SUB_PATH */] = {
38
+ ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
39
+ ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
40
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [
41
+ 4 /* States.IN_SUB_PATH */,
42
+ 2 /* Actions.INC_SUB_PATH_DEPTH */
43
+ ],
44
+ ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
45
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
46
+ ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
47
+ };
48
+ pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
49
+ ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
50
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
51
+ ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
52
+ };
53
+ pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
54
+ ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
55
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
56
+ ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
57
+ };
58
+ /**
59
+ * Check if an expression is a literal value.
60
+ */
61
+ const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
62
+ function isLiteral(exp) {
63
+ return literalValueRE.test(exp);
64
+ }
65
+ /**
66
+ * Strip quotes from a string
67
+ */
68
+ function stripQuotes(str) {
69
+ const a = str.charCodeAt(0);
70
+ const b = str.charCodeAt(str.length - 1);
71
+ return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
72
+ }
73
+ /**
74
+ * Determine the type of a character in a keypath.
75
+ */
76
+ function getPathCharType(ch) {
77
+ if (ch === undefined || ch === null) {
78
+ return "o" /* PathCharTypes.END_OF_FAIL */;
79
+ }
80
+ const code = ch.charCodeAt(0);
81
+ switch (code) {
82
+ case 0x5b: // [
83
+ case 0x5d: // ]
84
+ case 0x2e: // .
85
+ case 0x22: // "
86
+ case 0x27: // '
87
+ return ch;
88
+ case 0x5f: // _
89
+ case 0x24: // $
90
+ case 0x2d: // -
91
+ return "i" /* PathCharTypes.IDENT */;
92
+ case 0x09: // Tab (HT)
93
+ case 0x0a: // Newline (LF)
94
+ case 0x0d: // Return (CR)
95
+ case 0xa0: // No-break space (NBSP)
96
+ case 0xfeff: // Byte Order Mark (BOM)
97
+ case 0x2028: // Line Separator (LS)
98
+ case 0x2029: // Paragraph Separator (PS)
99
+ return "w" /* PathCharTypes.WORKSPACE */;
100
+ }
101
+ return "i" /* PathCharTypes.IDENT */;
102
+ }
103
+ /**
104
+ * Format a subPath, return its plain form if it is
105
+ * a literal string or number. Otherwise prepend the
106
+ * dynamic indicator (*).
107
+ */
108
+ function formatSubPath(path) {
109
+ const trimmed = path.trim();
110
+ // invalid leading 0
111
+ if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
112
+ return false;
113
+ }
114
+ return isLiteral(trimmed)
115
+ ? stripQuotes(trimmed)
116
+ : "*" /* PathCharTypes.ASTARISK */ + trimmed;
117
+ }
118
+ /**
119
+ * Parse a string path into an array of segments
120
+ */
121
+ function parse(path) {
122
+ const keys = [];
123
+ let index = -1;
124
+ let mode = 0 /* States.BEFORE_PATH */;
125
+ let subPathDepth = 0;
126
+ let c;
127
+ let key; // eslint-disable-line
128
+ let newChar;
129
+ let type;
130
+ let transition;
131
+ let action;
132
+ let typeMap;
133
+ const actions = [];
134
+ actions[0 /* Actions.APPEND */] = () => {
135
+ if (key === undefined) {
136
+ key = newChar;
137
+ }
138
+ else {
139
+ key += newChar;
140
+ }
141
+ };
142
+ actions[1 /* Actions.PUSH */] = () => {
143
+ if (key !== undefined) {
144
+ keys.push(key);
145
+ key = undefined;
146
+ }
147
+ };
148
+ actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
149
+ actions[0 /* Actions.APPEND */]();
150
+ subPathDepth++;
151
+ };
152
+ actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
153
+ if (subPathDepth > 0) {
154
+ subPathDepth--;
155
+ mode = 4 /* States.IN_SUB_PATH */;
156
+ actions[0 /* Actions.APPEND */]();
157
+ }
158
+ else {
159
+ subPathDepth = 0;
160
+ if (key === undefined) {
161
+ return false;
162
+ }
163
+ key = formatSubPath(key);
164
+ if (key === false) {
165
+ return false;
166
+ }
167
+ else {
168
+ actions[1 /* Actions.PUSH */]();
169
+ }
170
+ }
171
+ };
172
+ function maybeUnescapeQuote() {
173
+ const nextChar = path[index + 1];
174
+ if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
175
+ nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
176
+ (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
177
+ nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
178
+ index++;
179
+ newChar = '\\' + nextChar;
180
+ actions[0 /* Actions.APPEND */]();
181
+ return true;
182
+ }
183
+ }
184
+ while (mode !== null) {
185
+ index++;
186
+ c = path[index];
187
+ if (c === '\\' && maybeUnescapeQuote()) {
188
+ continue;
189
+ }
190
+ type = getPathCharType(c);
191
+ typeMap = pathStateMachine[mode];
192
+ transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
193
+ // check parse error
194
+ if (transition === 8 /* States.ERROR */) {
195
+ return;
196
+ }
197
+ mode = transition[0];
198
+ if (transition[1] !== undefined) {
199
+ action = actions[transition[1]];
200
+ if (action) {
201
+ newChar = c;
202
+ if (action() === false) {
203
+ return;
204
+ }
205
+ }
206
+ }
207
+ // check parse finish
208
+ if (mode === 7 /* States.AFTER_PATH */) {
209
+ return keys;
210
+ }
211
+ }
212
+ }
213
+ // path token cache
214
+ const cache = new Map();
215
+ /**
216
+ * key-value message resolver
217
+ *
218
+ * @remarks
219
+ * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
220
+ *
221
+ * @param obj - A target object to be resolved with path
222
+ * @param path - A {@link Path | path} to resolve the value of message
223
+ *
224
+ * @returns A resolved {@link PathValue | path value}
225
+ *
226
+ * @VueI18nGeneral
227
+ */
228
+ function resolveWithKeyValue(obj, path) {
229
+ return 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;
274
274
  }
275
275
 
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" /* HelperNameMap.LIST */]: list,
393
- ["named" /* HelperNameMap.NAMED */]: named,
394
- ["plural" /* HelperNameMap.PLURAL */]: plural,
395
- ["linked" /* HelperNameMap.LINKED */]: linked,
396
- ["message" /* HelperNameMap.MESSAGE */]: message,
397
- ["type" /* HelperNameMap.TYPE */]: type,
398
- ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
399
- ["normalize" /* HelperNameMap.NORMALIZE */]: normalize
400
- };
401
- return ctx;
276
+ const DEFAULT_MODIFIER = (str) => str;
277
+ const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
278
+ const DEFAULT_MESSAGE_DATA_TYPE = 'text';
279
+ const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : 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" /* HelperNameMap.LIST */]: list,
393
+ ["named" /* HelperNameMap.NAMED */]: named,
394
+ ["plural" /* HelperNameMap.PLURAL */]: plural,
395
+ ["linked" /* HelperNameMap.LINKED */]: linked,
396
+ ["message" /* HelperNameMap.MESSAGE */]: message,
397
+ ["type" /* HelperNameMap.TYPE */]: type,
398
+ ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
399
+ ["normalize" /* HelperNameMap.NORMALIZE */]: normalize
400
+ };
401
+ return ctx;
402
402
  }
403
403
 
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);
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);
424
424
  }
425
425
 
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);
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);
446
446
  }
447
447
 
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;
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;
562
562
  }
563
563
 
564
- /* eslint-disable @typescript-eslint/no-explicit-any */
565
- /**
566
- * Intlify core-base version
567
- * @internal
568
- */
569
- const VERSION = '9.3.0-beta.16';
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" /* VueDevToolsTimelineEvents.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
- }
564
+ /* eslint-disable @typescript-eslint/no-explicit-any */
565
+ /**
566
+ * Intlify core-base version
567
+ * @internal
568
+ */
569
+ const VERSION = '9.3.0-beta.18';
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" /* VueDevToolsTimelineEvents.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
+ }
789
789
  /* eslint-enable @typescript-eslint/no-explicit-any */
790
790
 
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
- }
791
+ const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
792
+ function checkHtmlMessage(source, warnHtmlMessage) {
793
+ if (warnHtmlMessage && detectHtmlTag(source)) {
794
+ warn(format(WARN_MESSAGE, { source }));
795
+ }
796
+ }
797
+ const defaultOnCacheKey = (source) => source;
798
+ let compileCache = Object.create(null);
799
+ function clearCompileCache() {
800
+ compileCache = Object.create(null);
801
+ }
802
+ function compileToFunction(source, options = {}) {
803
+ {
804
+ // check HTML message
805
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
806
+ const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
807
+ ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
808
+ options.warnHtmlMessage
809
+ : true;
810
+ (process.env.NODE_ENV !== 'production') && checkHtmlMessage(source, warnHtmlMessage);
811
+ // check caches
812
+ const onCacheKey = options.onCacheKey || defaultOnCacheKey;
813
+ const key = onCacheKey(source);
814
+ const cached = compileCache[key];
815
+ if (cached) {
816
+ return cached;
817
+ }
818
+ // compile error detecting
819
+ let occurred = false;
820
+ const onError = options.onError || defaultOnError;
821
+ options.onError = (err) => {
822
+ occurred = true;
823
+ onError(err);
824
+ };
825
+ // compile
826
+ const { code } = baseCompile(source, options);
827
+ // evaluate function
828
+ const msg = new Function(`return ${code}`)();
829
+ // if occurred compile error, don't cache
830
+ return !occurred ? (compileCache[key] = msg) : msg;
831
+ }
831
832
  }
832
833
 
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'
834
+ let code = CompileErrorCodes.__EXTEND_POINT__;
835
+ const inc = () => ++code;
836
+ const CoreErrorCodes = {
837
+ INVALID_ARGUMENT: code,
838
+ INVALID_DATE_ARGUMENT: inc(),
839
+ INVALID_ISO_DATE_ARGUMENT: inc(),
840
+ __EXTEND_POINT__: inc() // 18
841
+ };
842
+ function createCoreError(code) {
843
+ return createCompileError(code, null, (process.env.NODE_ENV !== 'production') ? { messages: errorMessages } : undefined);
844
+ }
845
+ /** @internal */
846
+ const errorMessages = {
847
+ [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
848
+ [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
849
+ 'Make sure your Date represents a valid date.',
850
+ [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string'
850
851
  };
851
852
 
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" /* VueDevToolsTimelineEvents.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" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */, {
1029
- type: "message-resolve" /* VueDevToolsTimelineEvents.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" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */, {
1083
- type: "message-compilation" /* VueDevToolsTimelineEvents.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" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */, {
1117
- type: "message-evaluation" /* VueDevToolsTimelineEvents.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" /* VueDevToolsTimelineEvents.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;
853
+ const NOOP_MESSAGE_FUNCTION = () => '';
854
+ const isMessageFunction = (val) => isFunction(val);
855
+ // implementation of `translate` function
856
+ function translate(context, ...args) {
857
+ const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
858
+ const [key, options] = parseTranslateArgs(...args);
859
+ const missingWarn = isBoolean(options.missingWarn)
860
+ ? options.missingWarn
861
+ : context.missingWarn;
862
+ const fallbackWarn = isBoolean(options.fallbackWarn)
863
+ ? options.fallbackWarn
864
+ : context.fallbackWarn;
865
+ const escapeParameter = isBoolean(options.escapeParameter)
866
+ ? options.escapeParameter
867
+ : context.escapeParameter;
868
+ const resolvedMessage = !!options.resolvedMessage;
869
+ // prettier-ignore
870
+ const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
871
+ ? !isBoolean(options.default)
872
+ ? options.default
873
+ : (!messageCompiler ? () => key : key)
874
+ : fallbackFormat // default by `fallbackFormat` option
875
+ ? (!messageCompiler ? () => key : key)
876
+ : '';
877
+ const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
878
+ const locale = isString(options.locale) ? options.locale : context.locale;
879
+ // escape params
880
+ escapeParameter && escapeParams(options);
881
+ // resolve message format
882
+ // eslint-disable-next-line prefer-const
883
+ let [formatScope, targetLocale, message] = !resolvedMessage
884
+ ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
885
+ : [
886
+ key,
887
+ locale,
888
+ messages[locale] || {}
889
+ ];
890
+ // NOTE:
891
+ // Fix to work around `ssrTransfrom` bug in Vite.
892
+ // https://github.com/vitejs/vite/issues/4306
893
+ // To get around this, use temporary variables.
894
+ // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
895
+ let format = formatScope;
896
+ // if you use default message, set it as message format!
897
+ let cacheBaseKey = key;
898
+ if (!resolvedMessage &&
899
+ !(isString(format) || isMessageFunction(format))) {
900
+ if (enableDefaultMsg) {
901
+ format = defaultMsgOrKey;
902
+ cacheBaseKey = format;
903
+ }
904
+ }
905
+ // checking message format and target locale
906
+ if (!resolvedMessage &&
907
+ (!(isString(format) || isMessageFunction(format)) ||
908
+ !isString(targetLocale))) {
909
+ return unresolving ? NOT_REOSLVED : key;
910
+ }
911
+ if ((process.env.NODE_ENV !== 'production') && isString(format) && context.messageCompiler == null) {
912
+ warn(`The message format compilation is not supported in this build. ` +
913
+ `Because message compiler isn't included. ` +
914
+ `You need to pre-compilation all message format. ` +
915
+ `So translate function return '${key}'.`);
916
+ return key;
917
+ }
918
+ // setup compile error detecting
919
+ let occurred = false;
920
+ const errorDetector = () => {
921
+ occurred = true;
922
+ };
923
+ // compile message format
924
+ const msg = !isMessageFunction(format)
925
+ ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
926
+ : format;
927
+ // if occurred compile error, return the message format
928
+ if (occurred) {
929
+ return format;
930
+ }
931
+ // evaluate message with context
932
+ const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
933
+ const msgContext = createMessageContext(ctxOptions);
934
+ const messaged = evaluateMessage(context, msg, msgContext);
935
+ // if use post translation option, proceed it with handler
936
+ const ret = postTranslation
937
+ ? postTranslation(messaged, key)
938
+ : messaged;
939
+ // NOTE: experimental !!
940
+ if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {
941
+ // prettier-ignore
942
+ const payloads = {
943
+ timestamp: Date.now(),
944
+ key: isString(key)
945
+ ? key
946
+ : isMessageFunction(format)
947
+ ? format.key
948
+ : '',
949
+ locale: targetLocale || (isMessageFunction(format)
950
+ ? format.locale
951
+ : ''),
952
+ format: isString(format)
953
+ ? format
954
+ : isMessageFunction(format)
955
+ ? format.source
956
+ : '',
957
+ message: ret
958
+ };
959
+ payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
960
+ translateDevTools(payloads);
961
+ }
962
+ return ret;
963
+ }
964
+ function escapeParams(options) {
965
+ if (isArray(options.list)) {
966
+ options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
967
+ }
968
+ else if (isObject(options.named)) {
969
+ Object.keys(options.named).forEach(key => {
970
+ if (isString(options.named[key])) {
971
+ options.named[key] = escapeHtml(options.named[key]);
972
+ }
973
+ });
974
+ }
975
+ }
976
+ function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
977
+ const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
978
+ const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
979
+ let message = {};
980
+ let targetLocale;
981
+ let format = null;
982
+ let from = locale;
983
+ let to = null;
984
+ const type = 'translate';
985
+ for (let i = 0; i < locales.length; i++) {
986
+ targetLocale = to = locales[i];
987
+ if ((process.env.NODE_ENV !== 'production') &&
988
+ locale !== targetLocale &&
989
+ isTranslateFallbackWarn(fallbackWarn, key)) {
990
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
991
+ key,
992
+ target: targetLocale
993
+ }));
994
+ }
995
+ // for vue-devtools timeline event
996
+ if ((process.env.NODE_ENV !== 'production') && locale !== targetLocale) {
997
+ const emitter = context.__v_emitter;
998
+ if (emitter) {
999
+ emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
1000
+ type,
1001
+ key,
1002
+ from,
1003
+ to,
1004
+ groupId: `${type}:${key}`
1005
+ });
1006
+ }
1007
+ }
1008
+ message =
1009
+ messages[targetLocale] || {};
1010
+ // for vue-devtools timeline event
1011
+ let start = null;
1012
+ let startTag;
1013
+ let endTag;
1014
+ if ((process.env.NODE_ENV !== 'production') && inBrowser) {
1015
+ start = window.performance.now();
1016
+ startTag = 'intlify-message-resolve-start';
1017
+ endTag = 'intlify-message-resolve-end';
1018
+ mark && mark(startTag);
1019
+ }
1020
+ if ((format = resolveValue(message, key)) === null) {
1021
+ // if null, resolve with object key path
1022
+ format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
1023
+ }
1024
+ // for vue-devtools timeline event
1025
+ if ((process.env.NODE_ENV !== 'production') && inBrowser) {
1026
+ const end = window.performance.now();
1027
+ const emitter = context.__v_emitter;
1028
+ if (emitter && start && format) {
1029
+ emitter.emit("message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */, {
1030
+ type: "message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */,
1031
+ key,
1032
+ message: format,
1033
+ time: end - start,
1034
+ groupId: `${type}:${key}`
1035
+ });
1036
+ }
1037
+ if (startTag && endTag && mark && measure) {
1038
+ mark(endTag);
1039
+ measure('intlify message resolve', startTag, endTag);
1040
+ }
1041
+ }
1042
+ if (isString(format) || isFunction(format))
1043
+ break;
1044
+ const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1045
+ key, targetLocale, missingWarn, type);
1046
+ if (missingRet !== key) {
1047
+ format = missingRet;
1048
+ }
1049
+ from = to;
1050
+ }
1051
+ return [format, targetLocale, message];
1052
+ }
1053
+ function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
1054
+ const { messageCompiler, warnHtmlMessage } = context;
1055
+ if (isMessageFunction(format)) {
1056
+ const msg = format;
1057
+ msg.locale = msg.locale || targetLocale;
1058
+ msg.key = msg.key || key;
1059
+ return msg;
1060
+ }
1061
+ if (messageCompiler == null) {
1062
+ const msg = (() => format);
1063
+ msg.locale = targetLocale;
1064
+ msg.key = key;
1065
+ return msg;
1066
+ }
1067
+ // for vue-devtools timeline event
1068
+ let start = null;
1069
+ let startTag;
1070
+ let endTag;
1071
+ if ((process.env.NODE_ENV !== 'production') && inBrowser) {
1072
+ start = window.performance.now();
1073
+ startTag = 'intlify-message-compilation-start';
1074
+ endTag = 'intlify-message-compilation-end';
1075
+ mark && mark(startTag);
1076
+ }
1077
+ const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
1078
+ // for vue-devtools timeline event
1079
+ if ((process.env.NODE_ENV !== 'production') && inBrowser) {
1080
+ const end = window.performance.now();
1081
+ const emitter = context.__v_emitter;
1082
+ if (emitter && start) {
1083
+ emitter.emit("message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */, {
1084
+ type: "message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */,
1085
+ message: format,
1086
+ time: end - start,
1087
+ groupId: `${'translate'}:${key}`
1088
+ });
1089
+ }
1090
+ if (startTag && endTag && mark && measure) {
1091
+ mark(endTag);
1092
+ measure('intlify message compilation', startTag, endTag);
1093
+ }
1094
+ }
1095
+ msg.locale = targetLocale;
1096
+ msg.key = key;
1097
+ msg.source = format;
1098
+ return msg;
1099
+ }
1100
+ function evaluateMessage(context, msg, msgCtx) {
1101
+ // for vue-devtools timeline event
1102
+ let start = null;
1103
+ let startTag;
1104
+ let endTag;
1105
+ if ((process.env.NODE_ENV !== 'production') && inBrowser) {
1106
+ start = window.performance.now();
1107
+ startTag = 'intlify-message-evaluation-start';
1108
+ endTag = 'intlify-message-evaluation-end';
1109
+ mark && mark(startTag);
1110
+ }
1111
+ const messaged = msg(msgCtx);
1112
+ // for vue-devtools timeline event
1113
+ if ((process.env.NODE_ENV !== 'production') && inBrowser) {
1114
+ const end = window.performance.now();
1115
+ const emitter = context.__v_emitter;
1116
+ if (emitter && start) {
1117
+ emitter.emit("message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */, {
1118
+ type: "message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */,
1119
+ value: messaged,
1120
+ time: end - start,
1121
+ groupId: `${'translate'}:${msg.key}`
1122
+ });
1123
+ }
1124
+ if (startTag && endTag && mark && measure) {
1125
+ mark(endTag);
1126
+ measure('intlify message evaluation', startTag, endTag);
1127
+ }
1128
+ }
1129
+ return messaged;
1130
+ }
1131
+ /** @internal */
1132
+ function parseTranslateArgs(...args) {
1133
+ const [arg1, arg2, arg3] = args;
1134
+ const options = {};
1135
+ if (!isString(arg1) && !isNumber(arg1) && !isMessageFunction(arg1)) {
1136
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1137
+ }
1138
+ // prettier-ignore
1139
+ const key = isNumber(arg1)
1140
+ ? String(arg1)
1141
+ : isMessageFunction(arg1)
1142
+ ? arg1
1143
+ : arg1;
1144
+ if (isNumber(arg2)) {
1145
+ options.plural = arg2;
1146
+ }
1147
+ else if (isString(arg2)) {
1148
+ options.default = arg2;
1149
+ }
1150
+ else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
1151
+ options.named = arg2;
1152
+ }
1153
+ else if (isArray(arg2)) {
1154
+ options.list = arg2;
1155
+ }
1156
+ if (isNumber(arg3)) {
1157
+ options.plural = arg3;
1158
+ }
1159
+ else if (isString(arg3)) {
1160
+ options.default = arg3;
1161
+ }
1162
+ else if (isPlainObject(arg3)) {
1163
+ assign(options, arg3);
1164
+ }
1165
+ return [key, options];
1166
+ }
1167
+ function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
1168
+ return {
1169
+ warnHtmlMessage,
1170
+ onError: (err) => {
1171
+ errorDetector && errorDetector(err);
1172
+ if ((process.env.NODE_ENV !== 'production')) {
1173
+ const message = `Message compilation error: ${err.message}`;
1174
+ const codeFrame = err.location &&
1175
+ generateCodeFrame(source, err.location.start.offset, err.location.end.offset);
1176
+ const emitter = context.__v_emitter;
1177
+ if (emitter) {
1178
+ emitter.emit("compile-error" /* VueDevToolsTimelineEvents.COMPILE_ERROR */, {
1179
+ message: source,
1180
+ error: err.message,
1181
+ start: err.location && err.location.start.offset,
1182
+ end: err.location && err.location.end.offset,
1183
+ groupId: `${'translate'}:${key}`
1184
+ });
1185
+ }
1186
+ console.error(codeFrame ? `${message}\n${codeFrame}` : message);
1187
+ }
1188
+ else {
1189
+ throw err;
1190
+ }
1191
+ },
1192
+ onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
1193
+ };
1194
+ }
1195
+ function getMessageContextOptions(context, locale, message, options) {
1196
+ const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
1197
+ const resolveMessage = (key) => {
1198
+ let val = resolveValue(message, key);
1199
+ // fallback to root context
1200
+ if (val == null && fallbackContext) {
1201
+ const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
1202
+ val = resolveValue(message, key);
1203
+ }
1204
+ if (isString(val)) {
1205
+ let occurred = false;
1206
+ const errorDetector = () => {
1207
+ occurred = true;
1208
+ };
1209
+ const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
1210
+ return !occurred
1211
+ ? msg
1212
+ : NOOP_MESSAGE_FUNCTION;
1213
+ }
1214
+ else if (isMessageFunction(val)) {
1215
+ return val;
1216
+ }
1217
+ else {
1218
+ // TODO: should be implemented warning message
1219
+ return NOOP_MESSAGE_FUNCTION;
1220
+ }
1221
+ };
1222
+ const ctxOptions = {
1223
+ locale,
1224
+ modifiers,
1225
+ pluralRules,
1226
+ messages: resolveMessage
1227
+ };
1228
+ if (context.processor) {
1229
+ ctxOptions.processor = context.processor;
1230
+ }
1231
+ if (options.list) {
1232
+ ctxOptions.list = options.list;
1233
+ }
1234
+ if (options.named) {
1235
+ ctxOptions.named = options.named;
1236
+ }
1237
+ if (isNumber(options.plural)) {
1238
+ ctxOptions.pluralIndex = options.plural;
1239
+ }
1240
+ return ctxOptions;
1240
1241
  }
1241
1242
 
1242
- const intlDefined = typeof Intl !== 'undefined';
1243
- const Availabilities = {
1244
- dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
1245
- numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
1243
+ const intlDefined = typeof Intl !== 'undefined';
1244
+ const Availabilities = {
1245
+ dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
1246
+ numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
1246
1247
  };
1247
1248
 
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" /* VueDevToolsTimelineEvents.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
- }
1249
+ // implementation of `datetime` function
1250
+ function datetime(context, ...args) {
1251
+ const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1252
+ const { __datetimeFormatters } = context;
1253
+ if ((process.env.NODE_ENV !== 'production') && !Availabilities.dateTimeFormat) {
1254
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
1255
+ return MISSING_RESOLVE_VALUE;
1256
+ }
1257
+ const [key, value, options, overrides] = parseDateTimeArgs(...args);
1258
+ const missingWarn = isBoolean(options.missingWarn)
1259
+ ? options.missingWarn
1260
+ : context.missingWarn;
1261
+ const fallbackWarn = isBoolean(options.fallbackWarn)
1262
+ ? options.fallbackWarn
1263
+ : context.fallbackWarn;
1264
+ const part = !!options.part;
1265
+ const locale = isString(options.locale) ? options.locale : context.locale;
1266
+ const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1267
+ fallbackLocale, locale);
1268
+ if (!isString(key) || key === '') {
1269
+ return new Intl.DateTimeFormat(locale, overrides).format(value);
1270
+ }
1271
+ // resolve format
1272
+ let datetimeFormat = {};
1273
+ let targetLocale;
1274
+ let format = null;
1275
+ let from = locale;
1276
+ let to = null;
1277
+ const type = 'datetime format';
1278
+ for (let i = 0; i < locales.length; i++) {
1279
+ targetLocale = to = locales[i];
1280
+ if ((process.env.NODE_ENV !== 'production') &&
1281
+ locale !== targetLocale &&
1282
+ isTranslateFallbackWarn(fallbackWarn, key)) {
1283
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
1284
+ key,
1285
+ target: targetLocale
1286
+ }));
1287
+ }
1288
+ // for vue-devtools timeline event
1289
+ if ((process.env.NODE_ENV !== 'production') && locale !== targetLocale) {
1290
+ const emitter = context.__v_emitter;
1291
+ if (emitter) {
1292
+ emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
1293
+ type,
1294
+ key,
1295
+ from,
1296
+ to,
1297
+ groupId: `${type}:${key}`
1298
+ });
1299
+ }
1300
+ }
1301
+ datetimeFormat =
1302
+ datetimeFormats[targetLocale] || {};
1303
+ format = datetimeFormat[key];
1304
+ if (isPlainObject(format))
1305
+ break;
1306
+ handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1307
+ from = to;
1308
+ }
1309
+ // checking format and target locale
1310
+ if (!isPlainObject(format) || !isString(targetLocale)) {
1311
+ return unresolving ? NOT_REOSLVED : key;
1312
+ }
1313
+ let id = `${targetLocale}__${key}`;
1314
+ if (!isEmptyObject(overrides)) {
1315
+ id = `${id}__${JSON.stringify(overrides)}`;
1316
+ }
1317
+ let formatter = __datetimeFormatters.get(id);
1318
+ if (!formatter) {
1319
+ formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
1320
+ __datetimeFormatters.set(id, formatter);
1321
+ }
1322
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
1323
+ }
1324
+ /** @internal */
1325
+ const DATETIME_FORMAT_OPTIONS_KEYS = [
1326
+ 'localeMatcher',
1327
+ 'weekday',
1328
+ 'era',
1329
+ 'year',
1330
+ 'month',
1331
+ 'day',
1332
+ 'hour',
1333
+ 'minute',
1334
+ 'second',
1335
+ 'timeZoneName',
1336
+ 'formatMatcher',
1337
+ 'hour12',
1338
+ 'timeZone',
1339
+ 'dateStyle',
1340
+ 'timeStyle',
1341
+ 'calendar',
1342
+ 'dayPeriod',
1343
+ 'numberingSystem',
1344
+ 'hourCycle',
1345
+ 'fractionalSecondDigits'
1346
+ ];
1347
+ /** @internal */
1348
+ function parseDateTimeArgs(...args) {
1349
+ const [arg1, arg2, arg3, arg4] = args;
1350
+ const options = {};
1351
+ let overrides = {};
1352
+ let value;
1353
+ if (isString(arg1)) {
1354
+ // Only allow ISO strings - other date formats are often supported,
1355
+ // but may cause different results in different browsers.
1356
+ const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
1357
+ if (!matches) {
1358
+ throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1359
+ }
1360
+ // Some browsers can not parse the iso datetime separated by space,
1361
+ // this is a compromise solution by replace the 'T'/' ' with 'T'
1362
+ const dateTime = matches[3]
1363
+ ? matches[3].trim().startsWith('T')
1364
+ ? `${matches[1].trim()}${matches[3].trim()}`
1365
+ : `${matches[1].trim()}T${matches[3].trim()}`
1366
+ : matches[1].trim();
1367
+ value = new Date(dateTime);
1368
+ try {
1369
+ // This will fail if the date is not valid
1370
+ value.toISOString();
1371
+ }
1372
+ catch (e) {
1373
+ throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1374
+ }
1375
+ }
1376
+ else if (isDate(arg1)) {
1377
+ if (isNaN(arg1.getTime())) {
1378
+ throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
1379
+ }
1380
+ value = arg1;
1381
+ }
1382
+ else if (isNumber(arg1)) {
1383
+ value = arg1;
1384
+ }
1385
+ else {
1386
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1387
+ }
1388
+ if (isString(arg2)) {
1389
+ options.key = arg2;
1390
+ }
1391
+ else if (isPlainObject(arg2)) {
1392
+ Object.keys(arg2).forEach(key => {
1393
+ if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
1394
+ overrides[key] = arg2[key];
1395
+ }
1396
+ else {
1397
+ options[key] = arg2[key];
1398
+ }
1399
+ });
1400
+ }
1401
+ if (isString(arg3)) {
1402
+ options.locale = arg3;
1403
+ }
1404
+ else if (isPlainObject(arg3)) {
1405
+ overrides = arg3;
1406
+ }
1407
+ if (isPlainObject(arg4)) {
1408
+ overrides = arg4;
1409
+ }
1410
+ return [options.key || '', value, options, overrides];
1411
+ }
1412
+ /** @internal */
1413
+ function clearDateTimeFormat(ctx, locale, format) {
1414
+ const context = ctx;
1415
+ for (const key in format) {
1416
+ const id = `${locale}__${key}`;
1417
+ if (!context.__datetimeFormatters.has(id)) {
1418
+ continue;
1419
+ }
1420
+ context.__datetimeFormatters.delete(id);
1421
+ }
1421
1422
  }
1422
1423
 
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" /* VueDevToolsTimelineEvents.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
- }
1424
+ // implementation of `number` function
1425
+ function number(context, ...args) {
1426
+ const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1427
+ const { __numberFormatters } = context;
1428
+ if ((process.env.NODE_ENV !== 'production') && !Availabilities.numberFormat) {
1429
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
1430
+ return MISSING_RESOLVE_VALUE;
1431
+ }
1432
+ const [key, value, options, overrides] = parseNumberArgs(...args);
1433
+ const missingWarn = isBoolean(options.missingWarn)
1434
+ ? options.missingWarn
1435
+ : context.missingWarn;
1436
+ const fallbackWarn = isBoolean(options.fallbackWarn)
1437
+ ? options.fallbackWarn
1438
+ : context.fallbackWarn;
1439
+ const part = !!options.part;
1440
+ const locale = isString(options.locale) ? options.locale : context.locale;
1441
+ const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1442
+ fallbackLocale, locale);
1443
+ if (!isString(key) || key === '') {
1444
+ return new Intl.NumberFormat(locale, overrides).format(value);
1445
+ }
1446
+ // resolve format
1447
+ let numberFormat = {};
1448
+ let targetLocale;
1449
+ let format = null;
1450
+ let from = locale;
1451
+ let to = null;
1452
+ const type = 'number format';
1453
+ for (let i = 0; i < locales.length; i++) {
1454
+ targetLocale = to = locales[i];
1455
+ if ((process.env.NODE_ENV !== 'production') &&
1456
+ locale !== targetLocale &&
1457
+ isTranslateFallbackWarn(fallbackWarn, key)) {
1458
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
1459
+ key,
1460
+ target: targetLocale
1461
+ }));
1462
+ }
1463
+ // for vue-devtools timeline event
1464
+ if ((process.env.NODE_ENV !== 'production') && locale !== targetLocale) {
1465
+ const emitter = context.__v_emitter;
1466
+ if (emitter) {
1467
+ emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
1468
+ type,
1469
+ key,
1470
+ from,
1471
+ to,
1472
+ groupId: `${type}:${key}`
1473
+ });
1474
+ }
1475
+ }
1476
+ numberFormat =
1477
+ numberFormats[targetLocale] || {};
1478
+ format = numberFormat[key];
1479
+ if (isPlainObject(format))
1480
+ break;
1481
+ handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1482
+ from = to;
1483
+ }
1484
+ // checking format and target locale
1485
+ if (!isPlainObject(format) || !isString(targetLocale)) {
1486
+ return unresolving ? NOT_REOSLVED : key;
1487
+ }
1488
+ let id = `${targetLocale}__${key}`;
1489
+ if (!isEmptyObject(overrides)) {
1490
+ id = `${id}__${JSON.stringify(overrides)}`;
1491
+ }
1492
+ let formatter = __numberFormatters.get(id);
1493
+ if (!formatter) {
1494
+ formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
1495
+ __numberFormatters.set(id, formatter);
1496
+ }
1497
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
1498
+ }
1499
+ /** @internal */
1500
+ const NUMBER_FORMAT_OPTIONS_KEYS = [
1501
+ 'localeMatcher',
1502
+ 'style',
1503
+ 'currency',
1504
+ 'currencyDisplay',
1505
+ 'currencySign',
1506
+ 'useGrouping',
1507
+ 'minimumIntegerDigits',
1508
+ 'minimumFractionDigits',
1509
+ 'maximumFractionDigits',
1510
+ 'minimumSignificantDigits',
1511
+ 'maximumSignificantDigits',
1512
+ 'compactDisplay',
1513
+ 'notation',
1514
+ 'signDisplay',
1515
+ 'unit',
1516
+ 'unitDisplay',
1517
+ 'roundingMode',
1518
+ 'roundingPriority',
1519
+ 'roundingIncrement',
1520
+ 'trailingZeroDisplay'
1521
+ ];
1522
+ /** @internal */
1523
+ function parseNumberArgs(...args) {
1524
+ const [arg1, arg2, arg3, arg4] = args;
1525
+ const options = {};
1526
+ let overrides = {};
1527
+ if (!isNumber(arg1)) {
1528
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1529
+ }
1530
+ const value = arg1;
1531
+ if (isString(arg2)) {
1532
+ options.key = arg2;
1533
+ }
1534
+ else if (isPlainObject(arg2)) {
1535
+ Object.keys(arg2).forEach(key => {
1536
+ if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
1537
+ overrides[key] = arg2[key];
1538
+ }
1539
+ else {
1540
+ options[key] = arg2[key];
1541
+ }
1542
+ });
1543
+ }
1544
+ if (isString(arg3)) {
1545
+ options.locale = arg3;
1546
+ }
1547
+ else if (isPlainObject(arg3)) {
1548
+ overrides = arg3;
1549
+ }
1550
+ if (isPlainObject(arg4)) {
1551
+ overrides = arg4;
1552
+ }
1553
+ return [options.key || '', value, options, overrides];
1554
+ }
1555
+ /** @internal */
1556
+ function clearNumberFormat(ctx, locale, format) {
1557
+ const context = ctx;
1558
+ for (const key in format) {
1559
+ const id = `${locale}__${key}`;
1560
+ if (!context.__numberFormatters.has(id)) {
1561
+ continue;
1562
+ }
1563
+ context.__numberFormatters.delete(id);
1564
+ }
1564
1565
  }
1565
1566
 
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
- }
1567
+ // TODO: we could not exports for Node native ES Moudles yet...
1568
+ {
1569
+ if (typeof __INTLIFY_PROD_DEVTOOLS__ !== 'boolean') {
1570
+ getGlobalThis().__INTLIFY_PROD_DEVTOOLS__ = false;
1571
+ }
1571
1572
  }
1572
1573
 
1573
1574
  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 };