@intlify/core-base 9.3.0-beta.17 → 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 (54) hide show
  1. package/dist/core-base.cjs +1527 -1527
  2. package/dist/core-base.esm-browser.js +3000 -2995
  3. package/dist/core-base.esm-browser.prod.js +2 -2
  4. package/dist/core-base.global.js +3000 -2995
  5. package/dist/core-base.global.prod.js +2 -2
  6. package/dist/core-base.mjs +1538 -1538
  7. package/dist/core-base.prod.cjs +1288 -1288
  8. package/dist/e2e/bridge/basic.spec.d.ts +1 -1
  9. package/dist/e2e/bridge/component.spec.d.ts +1 -1
  10. package/dist/e2e/bridge/components/datetime-format.spec.d.ts +1 -1
  11. package/dist/e2e/bridge/components/number-format.spec.d.ts +1 -1
  12. package/dist/e2e/bridge/components/translation.spec.d.ts +1 -1
  13. package/dist/e2e/bridge/plural.spec.d.ts +1 -1
  14. package/dist/e2e/bridge/scope/global.spec.d.ts +1 -1
  15. package/dist/e2e/bridge/scope/inherit-locale.spec.d.ts +1 -1
  16. package/dist/e2e/bridge/scope/local.spec.d.ts +1 -1
  17. package/dist/e2e/components/datetime-format.spec.d.ts +1 -1
  18. package/dist/e2e/components/number-format.spec.d.ts +1 -1
  19. package/dist/e2e/components/translation.spec.d.ts +1 -1
  20. package/dist/e2e/composition.spec.d.ts +1 -1
  21. package/dist/e2e/datetime.spec.d.ts +1 -1
  22. package/dist/e2e/directive/basic.spec.d.ts +1 -1
  23. package/dist/e2e/directive/object.spec.d.ts +1 -1
  24. package/dist/e2e/directive/plural.spec.d.ts +1 -1
  25. package/dist/e2e/directive/preserve.spec.d.ts +1 -1
  26. package/dist/e2e/fallback/basic.spec.d.ts +1 -1
  27. package/dist/e2e/fallback/component.spec.d.ts +1 -1
  28. package/dist/e2e/fallback/default-format.spec.d.ts +1 -1
  29. package/dist/e2e/fallback/format.spec.d.ts +1 -1
  30. package/dist/e2e/fallback/option.spec.d.ts +1 -1
  31. package/dist/e2e/fallback/suppress.spec.d.ts +1 -1
  32. package/dist/e2e/formatting/linked.spec.d.ts +1 -1
  33. package/dist/e2e/formatting/list.spec.d.ts +1 -1
  34. package/dist/e2e/formatting/literal.spec.d.ts +1 -1
  35. package/dist/e2e/formatting/named.spec.d.ts +1 -1
  36. package/dist/e2e/formatting/ruby.spec.d.ts +1 -1
  37. package/dist/e2e/functions/linked.spec.d.ts +1 -1
  38. package/dist/e2e/functions/list.spec.d.ts +1 -1
  39. package/dist/e2e/functions/named.spec.d.ts +1 -1
  40. package/dist/e2e/functions/plural.spec.d.ts +1 -1
  41. package/dist/e2e/helper.d.ts +8 -8
  42. package/dist/e2e/missing/handler.spec.d.ts +1 -1
  43. package/dist/e2e/missing/option.spec.d.ts +1 -1
  44. package/dist/e2e/missing/suppress.spec.d.ts +1 -1
  45. package/dist/e2e/number.spec.d.ts +1 -1
  46. package/dist/e2e/plural/basic.spec.d.ts +1 -1
  47. package/dist/e2e/plural/custom.spec.d.ts +1 -1
  48. package/dist/e2e/scope/global.spec.d.ts +1 -1
  49. package/dist/e2e/scope/inherit-locale.spec.d.ts +1 -1
  50. package/dist/e2e/scope/local.spec.d.ts +1 -1
  51. package/dist/e2e/started.spec.d.ts +1 -1
  52. package/dist/scripts/vitest.globalSetup.d.ts +1 -1
  53. package/dist/scripts/vitest.setup.d.ts +1 -1
  54. package/package.json +6 -6
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * core-base v9.3.0-beta.17
2
+ * core-base v9.3.0-beta.18
3
3
  * (c) 2023 kazuya kawaguchi
4
4
  * Released under the MIT License.
5
5
  */
@@ -9,1313 +9,1313 @@ var messageCompiler = require('@intlify/message-compiler');
9
9
  var shared = require('@intlify/shared');
10
10
  var devtoolsIf = require('@intlify/devtools-if');
11
11
 
12
- const pathStateMachine = [];
13
- pathStateMachine[0 /* States.BEFORE_PATH */] = {
14
- ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
15
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
16
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
17
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
18
- };
19
- pathStateMachine[1 /* States.IN_PATH */] = {
20
- ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
21
- ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
22
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
23
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
24
- };
25
- pathStateMachine[2 /* States.BEFORE_IDENT */] = {
26
- ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
27
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
28
- ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
29
- };
30
- pathStateMachine[3 /* States.IN_IDENT */] = {
31
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
32
- ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
33
- ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
34
- ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
35
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
36
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
37
- };
38
- pathStateMachine[4 /* States.IN_SUB_PATH */] = {
39
- ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
40
- ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
41
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [
42
- 4 /* States.IN_SUB_PATH */,
43
- 2 /* Actions.INC_SUB_PATH_DEPTH */
44
- ],
45
- ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
46
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
47
- ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
48
- };
49
- pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
50
- ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
51
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
52
- ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
53
- };
54
- pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
55
- ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
56
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
57
- ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
58
- };
59
- /**
60
- * Check if an expression is a literal value.
61
- */
62
- const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
63
- function isLiteral(exp) {
64
- return literalValueRE.test(exp);
65
- }
66
- /**
67
- * Strip quotes from a string
68
- */
69
- function stripQuotes(str) {
70
- const a = str.charCodeAt(0);
71
- const b = str.charCodeAt(str.length - 1);
72
- return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
73
- }
74
- /**
75
- * Determine the type of a character in a keypath.
76
- */
77
- function getPathCharType(ch) {
78
- if (ch === undefined || ch === null) {
79
- return "o" /* PathCharTypes.END_OF_FAIL */;
80
- }
81
- const code = ch.charCodeAt(0);
82
- switch (code) {
83
- case 0x5b: // [
84
- case 0x5d: // ]
85
- case 0x2e: // .
86
- case 0x22: // "
87
- case 0x27: // '
88
- return ch;
89
- case 0x5f: // _
90
- case 0x24: // $
91
- case 0x2d: // -
92
- return "i" /* PathCharTypes.IDENT */;
93
- case 0x09: // Tab (HT)
94
- case 0x0a: // Newline (LF)
95
- case 0x0d: // Return (CR)
96
- case 0xa0: // No-break space (NBSP)
97
- case 0xfeff: // Byte Order Mark (BOM)
98
- case 0x2028: // Line Separator (LS)
99
- case 0x2029: // Paragraph Separator (PS)
100
- return "w" /* PathCharTypes.WORKSPACE */;
101
- }
102
- return "i" /* PathCharTypes.IDENT */;
103
- }
104
- /**
105
- * Format a subPath, return its plain form if it is
106
- * a literal string or number. Otherwise prepend the
107
- * dynamic indicator (*).
108
- */
109
- function formatSubPath(path) {
110
- const trimmed = path.trim();
111
- // invalid leading 0
112
- if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
113
- return false;
114
- }
115
- return isLiteral(trimmed)
116
- ? stripQuotes(trimmed)
117
- : "*" /* PathCharTypes.ASTARISK */ + trimmed;
118
- }
119
- /**
120
- * Parse a string path into an array of segments
121
- */
122
- function parse(path) {
123
- const keys = [];
124
- let index = -1;
125
- let mode = 0 /* States.BEFORE_PATH */;
126
- let subPathDepth = 0;
127
- let c;
128
- let key; // eslint-disable-line
129
- let newChar;
130
- let type;
131
- let transition;
132
- let action;
133
- let typeMap;
134
- const actions = [];
135
- actions[0 /* Actions.APPEND */] = () => {
136
- if (key === undefined) {
137
- key = newChar;
138
- }
139
- else {
140
- key += newChar;
141
- }
142
- };
143
- actions[1 /* Actions.PUSH */] = () => {
144
- if (key !== undefined) {
145
- keys.push(key);
146
- key = undefined;
147
- }
148
- };
149
- actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
150
- actions[0 /* Actions.APPEND */]();
151
- subPathDepth++;
152
- };
153
- actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
154
- if (subPathDepth > 0) {
155
- subPathDepth--;
156
- mode = 4 /* States.IN_SUB_PATH */;
157
- actions[0 /* Actions.APPEND */]();
158
- }
159
- else {
160
- subPathDepth = 0;
161
- if (key === undefined) {
162
- return false;
163
- }
164
- key = formatSubPath(key);
165
- if (key === false) {
166
- return false;
167
- }
168
- else {
169
- actions[1 /* Actions.PUSH */]();
170
- }
171
- }
172
- };
173
- function maybeUnescapeQuote() {
174
- const nextChar = path[index + 1];
175
- if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
176
- nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
177
- (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
178
- nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
179
- index++;
180
- newChar = '\\' + nextChar;
181
- actions[0 /* Actions.APPEND */]();
182
- return true;
183
- }
184
- }
185
- while (mode !== null) {
186
- index++;
187
- c = path[index];
188
- if (c === '\\' && maybeUnescapeQuote()) {
189
- continue;
190
- }
191
- type = getPathCharType(c);
192
- typeMap = pathStateMachine[mode];
193
- transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
194
- // check parse error
195
- if (transition === 8 /* States.ERROR */) {
196
- return;
197
- }
198
- mode = transition[0];
199
- if (transition[1] !== undefined) {
200
- action = actions[transition[1]];
201
- if (action) {
202
- newChar = c;
203
- if (action() === false) {
204
- return;
205
- }
206
- }
207
- }
208
- // check parse finish
209
- if (mode === 7 /* States.AFTER_PATH */) {
210
- return keys;
211
- }
212
- }
213
- }
214
- // path token cache
215
- const cache = new Map();
216
- /**
217
- * key-value message resolver
218
- *
219
- * @remarks
220
- * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
221
- *
222
- * @param obj - A target object to be resolved with path
223
- * @param path - A {@link Path | path} to resolve the value of message
224
- *
225
- * @returns A resolved {@link PathValue | path value}
226
- *
227
- * @VueI18nGeneral
228
- */
229
- function resolveWithKeyValue(obj, path) {
230
- return shared.isObject(obj) ? obj[path] : null;
231
- }
232
- /**
233
- * message resolver
234
- *
235
- * @remarks
236
- * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
237
- *
238
- * @param obj - A target object to be resolved with path
239
- * @param path - A {@link Path | path} to resolve the value of message
240
- *
241
- * @returns A resolved {@link PathValue | path value}
242
- *
243
- * @VueI18nGeneral
244
- */
245
- function resolveValue(obj, path) {
246
- // check object
247
- if (!shared.isObject(obj)) {
248
- return null;
249
- }
250
- // parse path
251
- let hit = cache.get(path);
252
- if (!hit) {
253
- hit = parse(path);
254
- if (hit) {
255
- cache.set(path, hit);
256
- }
257
- }
258
- // check hit
259
- if (!hit) {
260
- return null;
261
- }
262
- // resolve path value
263
- const len = hit.length;
264
- let last = obj;
265
- let i = 0;
266
- while (i < len) {
267
- const val = last[hit[i]];
268
- if (val === undefined) {
269
- return null;
270
- }
271
- last = val;
272
- i++;
273
- }
274
- return last;
12
+ const pathStateMachine = [];
13
+ pathStateMachine[0 /* States.BEFORE_PATH */] = {
14
+ ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
15
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
16
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
17
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
18
+ };
19
+ pathStateMachine[1 /* States.IN_PATH */] = {
20
+ ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
21
+ ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
22
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
23
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
24
+ };
25
+ pathStateMachine[2 /* States.BEFORE_IDENT */] = {
26
+ ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
27
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
28
+ ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
29
+ };
30
+ pathStateMachine[3 /* States.IN_IDENT */] = {
31
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
32
+ ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
33
+ ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
34
+ ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
35
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
36
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
37
+ };
38
+ pathStateMachine[4 /* States.IN_SUB_PATH */] = {
39
+ ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
40
+ ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
41
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [
42
+ 4 /* States.IN_SUB_PATH */,
43
+ 2 /* Actions.INC_SUB_PATH_DEPTH */
44
+ ],
45
+ ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
46
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
47
+ ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
48
+ };
49
+ pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
50
+ ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
51
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
52
+ ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
53
+ };
54
+ pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
55
+ ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
56
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
57
+ ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
58
+ };
59
+ /**
60
+ * Check if an expression is a literal value.
61
+ */
62
+ const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
63
+ function isLiteral(exp) {
64
+ return literalValueRE.test(exp);
65
+ }
66
+ /**
67
+ * Strip quotes from a string
68
+ */
69
+ function stripQuotes(str) {
70
+ const a = str.charCodeAt(0);
71
+ const b = str.charCodeAt(str.length - 1);
72
+ return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
73
+ }
74
+ /**
75
+ * Determine the type of a character in a keypath.
76
+ */
77
+ function getPathCharType(ch) {
78
+ if (ch === undefined || ch === null) {
79
+ return "o" /* PathCharTypes.END_OF_FAIL */;
80
+ }
81
+ const code = ch.charCodeAt(0);
82
+ switch (code) {
83
+ case 0x5b: // [
84
+ case 0x5d: // ]
85
+ case 0x2e: // .
86
+ case 0x22: // "
87
+ case 0x27: // '
88
+ return ch;
89
+ case 0x5f: // _
90
+ case 0x24: // $
91
+ case 0x2d: // -
92
+ return "i" /* PathCharTypes.IDENT */;
93
+ case 0x09: // Tab (HT)
94
+ case 0x0a: // Newline (LF)
95
+ case 0x0d: // Return (CR)
96
+ case 0xa0: // No-break space (NBSP)
97
+ case 0xfeff: // Byte Order Mark (BOM)
98
+ case 0x2028: // Line Separator (LS)
99
+ case 0x2029: // Paragraph Separator (PS)
100
+ return "w" /* PathCharTypes.WORKSPACE */;
101
+ }
102
+ return "i" /* PathCharTypes.IDENT */;
103
+ }
104
+ /**
105
+ * Format a subPath, return its plain form if it is
106
+ * a literal string or number. Otherwise prepend the
107
+ * dynamic indicator (*).
108
+ */
109
+ function formatSubPath(path) {
110
+ const trimmed = path.trim();
111
+ // invalid leading 0
112
+ if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
113
+ return false;
114
+ }
115
+ return isLiteral(trimmed)
116
+ ? stripQuotes(trimmed)
117
+ : "*" /* PathCharTypes.ASTARISK */ + trimmed;
118
+ }
119
+ /**
120
+ * Parse a string path into an array of segments
121
+ */
122
+ function parse(path) {
123
+ const keys = [];
124
+ let index = -1;
125
+ let mode = 0 /* States.BEFORE_PATH */;
126
+ let subPathDepth = 0;
127
+ let c;
128
+ let key; // eslint-disable-line
129
+ let newChar;
130
+ let type;
131
+ let transition;
132
+ let action;
133
+ let typeMap;
134
+ const actions = [];
135
+ actions[0 /* Actions.APPEND */] = () => {
136
+ if (key === undefined) {
137
+ key = newChar;
138
+ }
139
+ else {
140
+ key += newChar;
141
+ }
142
+ };
143
+ actions[1 /* Actions.PUSH */] = () => {
144
+ if (key !== undefined) {
145
+ keys.push(key);
146
+ key = undefined;
147
+ }
148
+ };
149
+ actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
150
+ actions[0 /* Actions.APPEND */]();
151
+ subPathDepth++;
152
+ };
153
+ actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
154
+ if (subPathDepth > 0) {
155
+ subPathDepth--;
156
+ mode = 4 /* States.IN_SUB_PATH */;
157
+ actions[0 /* Actions.APPEND */]();
158
+ }
159
+ else {
160
+ subPathDepth = 0;
161
+ if (key === undefined) {
162
+ return false;
163
+ }
164
+ key = formatSubPath(key);
165
+ if (key === false) {
166
+ return false;
167
+ }
168
+ else {
169
+ actions[1 /* Actions.PUSH */]();
170
+ }
171
+ }
172
+ };
173
+ function maybeUnescapeQuote() {
174
+ const nextChar = path[index + 1];
175
+ if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
176
+ nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
177
+ (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
178
+ nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
179
+ index++;
180
+ newChar = '\\' + nextChar;
181
+ actions[0 /* Actions.APPEND */]();
182
+ return true;
183
+ }
184
+ }
185
+ while (mode !== null) {
186
+ index++;
187
+ c = path[index];
188
+ if (c === '\\' && maybeUnescapeQuote()) {
189
+ continue;
190
+ }
191
+ type = getPathCharType(c);
192
+ typeMap = pathStateMachine[mode];
193
+ transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
194
+ // check parse error
195
+ if (transition === 8 /* States.ERROR */) {
196
+ return;
197
+ }
198
+ mode = transition[0];
199
+ if (transition[1] !== undefined) {
200
+ action = actions[transition[1]];
201
+ if (action) {
202
+ newChar = c;
203
+ if (action() === false) {
204
+ return;
205
+ }
206
+ }
207
+ }
208
+ // check parse finish
209
+ if (mode === 7 /* States.AFTER_PATH */) {
210
+ return keys;
211
+ }
212
+ }
213
+ }
214
+ // path token cache
215
+ const cache = new Map();
216
+ /**
217
+ * key-value message resolver
218
+ *
219
+ * @remarks
220
+ * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
221
+ *
222
+ * @param obj - A target object to be resolved with path
223
+ * @param path - A {@link Path | path} to resolve the value of message
224
+ *
225
+ * @returns A resolved {@link PathValue | path value}
226
+ *
227
+ * @VueI18nGeneral
228
+ */
229
+ function resolveWithKeyValue(obj, path) {
230
+ return shared.isObject(obj) ? obj[path] : null;
231
+ }
232
+ /**
233
+ * message resolver
234
+ *
235
+ * @remarks
236
+ * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
237
+ *
238
+ * @param obj - A target object to be resolved with path
239
+ * @param path - A {@link Path | path} to resolve the value of message
240
+ *
241
+ * @returns A resolved {@link PathValue | path value}
242
+ *
243
+ * @VueI18nGeneral
244
+ */
245
+ function resolveValue(obj, path) {
246
+ // check object
247
+ if (!shared.isObject(obj)) {
248
+ return null;
249
+ }
250
+ // parse path
251
+ let hit = cache.get(path);
252
+ if (!hit) {
253
+ hit = parse(path);
254
+ if (hit) {
255
+ cache.set(path, hit);
256
+ }
257
+ }
258
+ // check hit
259
+ if (!hit) {
260
+ return null;
261
+ }
262
+ // resolve path value
263
+ const len = hit.length;
264
+ let last = obj;
265
+ let i = 0;
266
+ while (i < len) {
267
+ const val = last[hit[i]];
268
+ if (val === undefined) {
269
+ return null;
270
+ }
271
+ last = val;
272
+ i++;
273
+ }
274
+ return last;
275
275
  }
276
276
 
277
- const DEFAULT_MODIFIER = (str) => str;
278
- const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
279
- const DEFAULT_MESSAGE_DATA_TYPE = 'text';
280
- const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join('');
281
- const DEFAULT_INTERPOLATE = shared.toDisplayString;
282
- function pluralDefault(choice, choicesLength) {
283
- choice = Math.abs(choice);
284
- if (choicesLength === 2) {
285
- // prettier-ignore
286
- return choice
287
- ? choice > 1
288
- ? 1
289
- : 0
290
- : 1;
291
- }
292
- return choice ? Math.min(choice, 2) : 0;
293
- }
294
- function getPluralIndex(options) {
295
- // prettier-ignore
296
- const index = shared.isNumber(options.pluralIndex)
297
- ? options.pluralIndex
298
- : -1;
299
- // prettier-ignore
300
- return options.named && (shared.isNumber(options.named.count) || shared.isNumber(options.named.n))
301
- ? shared.isNumber(options.named.count)
302
- ? options.named.count
303
- : shared.isNumber(options.named.n)
304
- ? options.named.n
305
- : index
306
- : index;
307
- }
308
- function normalizeNamed(pluralIndex, props) {
309
- if (!props.count) {
310
- props.count = pluralIndex;
311
- }
312
- if (!props.n) {
313
- props.n = pluralIndex;
314
- }
315
- }
316
- function createMessageContext(options = {}) {
317
- const locale = options.locale;
318
- const pluralIndex = getPluralIndex(options);
319
- const pluralRule = shared.isObject(options.pluralRules) &&
320
- shared.isString(locale) &&
321
- shared.isFunction(options.pluralRules[locale])
322
- ? options.pluralRules[locale]
323
- : pluralDefault;
324
- const orgPluralRule = shared.isObject(options.pluralRules) &&
325
- shared.isString(locale) &&
326
- shared.isFunction(options.pluralRules[locale])
327
- ? pluralDefault
328
- : undefined;
329
- const plural = (messages) => {
330
- return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
331
- };
332
- const _list = options.list || [];
333
- const list = (index) => _list[index];
334
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
335
- const _named = options.named || {};
336
- shared.isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
337
- const named = (key) => _named[key];
338
- function message(key) {
339
- // prettier-ignore
340
- const msg = shared.isFunction(options.messages)
341
- ? options.messages(key)
342
- : shared.isObject(options.messages)
343
- ? options.messages[key]
344
- : false;
345
- return !msg
346
- ? options.parent
347
- ? options.parent.message(key) // resolve from parent messages
348
- : DEFAULT_MESSAGE
349
- : msg;
350
- }
351
- const _modifier = (name) => options.modifiers
352
- ? options.modifiers[name]
353
- : DEFAULT_MODIFIER;
354
- const normalize = shared.isPlainObject(options.processor) && shared.isFunction(options.processor.normalize)
355
- ? options.processor.normalize
356
- : DEFAULT_NORMALIZE;
357
- const interpolate = shared.isPlainObject(options.processor) &&
358
- shared.isFunction(options.processor.interpolate)
359
- ? options.processor.interpolate
360
- : DEFAULT_INTERPOLATE;
361
- const type = shared.isPlainObject(options.processor) && shared.isString(options.processor.type)
362
- ? options.processor.type
363
- : DEFAULT_MESSAGE_DATA_TYPE;
364
- const linked = (key, ...args) => {
365
- const [arg1, arg2] = args;
366
- let type = 'text';
367
- let modifier = '';
368
- if (args.length === 1) {
369
- if (shared.isObject(arg1)) {
370
- modifier = arg1.modifier || modifier;
371
- type = arg1.type || type;
372
- }
373
- else if (shared.isString(arg1)) {
374
- modifier = arg1 || modifier;
375
- }
376
- }
377
- else if (args.length === 2) {
378
- if (shared.isString(arg1)) {
379
- modifier = arg1 || modifier;
380
- }
381
- if (shared.isString(arg2)) {
382
- type = arg2 || type;
383
- }
384
- }
385
- let msg = message(key)(ctx);
386
- // The message in vnode resolved with linked are returned as an array by processor.nomalize
387
- if (type === 'vnode' && shared.isArray(msg) && modifier) {
388
- msg = msg[0];
389
- }
390
- return modifier ? _modifier(modifier)(msg, type) : msg;
391
- };
392
- const ctx = {
393
- ["list" /* HelperNameMap.LIST */]: list,
394
- ["named" /* HelperNameMap.NAMED */]: named,
395
- ["plural" /* HelperNameMap.PLURAL */]: plural,
396
- ["linked" /* HelperNameMap.LINKED */]: linked,
397
- ["message" /* HelperNameMap.MESSAGE */]: message,
398
- ["type" /* HelperNameMap.TYPE */]: type,
399
- ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
400
- ["normalize" /* HelperNameMap.NORMALIZE */]: normalize
401
- };
402
- return ctx;
277
+ const DEFAULT_MODIFIER = (str) => str;
278
+ const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
279
+ const DEFAULT_MESSAGE_DATA_TYPE = 'text';
280
+ const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join('');
281
+ const DEFAULT_INTERPOLATE = shared.toDisplayString;
282
+ function pluralDefault(choice, choicesLength) {
283
+ choice = Math.abs(choice);
284
+ if (choicesLength === 2) {
285
+ // prettier-ignore
286
+ return choice
287
+ ? choice > 1
288
+ ? 1
289
+ : 0
290
+ : 1;
291
+ }
292
+ return choice ? Math.min(choice, 2) : 0;
293
+ }
294
+ function getPluralIndex(options) {
295
+ // prettier-ignore
296
+ const index = shared.isNumber(options.pluralIndex)
297
+ ? options.pluralIndex
298
+ : -1;
299
+ // prettier-ignore
300
+ return options.named && (shared.isNumber(options.named.count) || shared.isNumber(options.named.n))
301
+ ? shared.isNumber(options.named.count)
302
+ ? options.named.count
303
+ : shared.isNumber(options.named.n)
304
+ ? options.named.n
305
+ : index
306
+ : index;
307
+ }
308
+ function normalizeNamed(pluralIndex, props) {
309
+ if (!props.count) {
310
+ props.count = pluralIndex;
311
+ }
312
+ if (!props.n) {
313
+ props.n = pluralIndex;
314
+ }
315
+ }
316
+ function createMessageContext(options = {}) {
317
+ const locale = options.locale;
318
+ const pluralIndex = getPluralIndex(options);
319
+ const pluralRule = shared.isObject(options.pluralRules) &&
320
+ shared.isString(locale) &&
321
+ shared.isFunction(options.pluralRules[locale])
322
+ ? options.pluralRules[locale]
323
+ : pluralDefault;
324
+ const orgPluralRule = shared.isObject(options.pluralRules) &&
325
+ shared.isString(locale) &&
326
+ shared.isFunction(options.pluralRules[locale])
327
+ ? pluralDefault
328
+ : undefined;
329
+ const plural = (messages) => {
330
+ return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
331
+ };
332
+ const _list = options.list || [];
333
+ const list = (index) => _list[index];
334
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
335
+ const _named = options.named || {};
336
+ shared.isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
337
+ const named = (key) => _named[key];
338
+ function message(key) {
339
+ // prettier-ignore
340
+ const msg = shared.isFunction(options.messages)
341
+ ? options.messages(key)
342
+ : shared.isObject(options.messages)
343
+ ? options.messages[key]
344
+ : false;
345
+ return !msg
346
+ ? options.parent
347
+ ? options.parent.message(key) // resolve from parent messages
348
+ : DEFAULT_MESSAGE
349
+ : msg;
350
+ }
351
+ const _modifier = (name) => options.modifiers
352
+ ? options.modifiers[name]
353
+ : DEFAULT_MODIFIER;
354
+ const normalize = shared.isPlainObject(options.processor) && shared.isFunction(options.processor.normalize)
355
+ ? options.processor.normalize
356
+ : DEFAULT_NORMALIZE;
357
+ const interpolate = shared.isPlainObject(options.processor) &&
358
+ shared.isFunction(options.processor.interpolate)
359
+ ? options.processor.interpolate
360
+ : DEFAULT_INTERPOLATE;
361
+ const type = shared.isPlainObject(options.processor) && shared.isString(options.processor.type)
362
+ ? options.processor.type
363
+ : DEFAULT_MESSAGE_DATA_TYPE;
364
+ const linked = (key, ...args) => {
365
+ const [arg1, arg2] = args;
366
+ let type = 'text';
367
+ let modifier = '';
368
+ if (args.length === 1) {
369
+ if (shared.isObject(arg1)) {
370
+ modifier = arg1.modifier || modifier;
371
+ type = arg1.type || type;
372
+ }
373
+ else if (shared.isString(arg1)) {
374
+ modifier = arg1 || modifier;
375
+ }
376
+ }
377
+ else if (args.length === 2) {
378
+ if (shared.isString(arg1)) {
379
+ modifier = arg1 || modifier;
380
+ }
381
+ if (shared.isString(arg2)) {
382
+ type = arg2 || type;
383
+ }
384
+ }
385
+ let msg = message(key)(ctx);
386
+ // The message in vnode resolved with linked are returned as an array by processor.nomalize
387
+ if (type === 'vnode' && shared.isArray(msg) && modifier) {
388
+ msg = msg[0];
389
+ }
390
+ return modifier ? _modifier(modifier)(msg, type) : msg;
391
+ };
392
+ const ctx = {
393
+ ["list" /* HelperNameMap.LIST */]: list,
394
+ ["named" /* HelperNameMap.NAMED */]: named,
395
+ ["plural" /* HelperNameMap.PLURAL */]: plural,
396
+ ["linked" /* HelperNameMap.LINKED */]: linked,
397
+ ["message" /* HelperNameMap.MESSAGE */]: message,
398
+ ["type" /* HelperNameMap.TYPE */]: type,
399
+ ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
400
+ ["normalize" /* HelperNameMap.NORMALIZE */]: normalize
401
+ };
402
+ return ctx;
403
403
  }
404
404
 
405
- let devtools = null;
406
- function setDevToolsHook(hook) {
407
- devtools = hook;
408
- }
409
- function getDevToolsHook() {
410
- return devtools;
411
- }
412
- function initI18nDevTools(i18n, version, meta) {
413
- // TODO: queue if devtools is undefined
414
- devtools &&
415
- devtools.emit(devtoolsIf.IntlifyDevToolsHooks.I18nInit, {
416
- timestamp: Date.now(),
417
- i18n,
418
- version,
419
- meta
420
- });
421
- }
422
- const translateDevTools = /* #__PURE__*/ createDevToolsHook(devtoolsIf.IntlifyDevToolsHooks.FunctionTranslate);
423
- function createDevToolsHook(hook) {
424
- return (payloads) => devtools && devtools.emit(hook, payloads);
405
+ let devtools = null;
406
+ function setDevToolsHook(hook) {
407
+ devtools = hook;
408
+ }
409
+ function getDevToolsHook() {
410
+ return devtools;
411
+ }
412
+ function initI18nDevTools(i18n, version, meta) {
413
+ // TODO: queue if devtools is undefined
414
+ devtools &&
415
+ devtools.emit(devtoolsIf.IntlifyDevToolsHooks.I18nInit, {
416
+ timestamp: Date.now(),
417
+ i18n,
418
+ version,
419
+ meta
420
+ });
421
+ }
422
+ const translateDevTools = /* #__PURE__*/ createDevToolsHook(devtoolsIf.IntlifyDevToolsHooks.FunctionTranslate);
423
+ function createDevToolsHook(hook) {
424
+ return (payloads) => devtools && devtools.emit(hook, payloads);
425
425
  }
426
426
 
427
- const CoreWarnCodes = {
428
- NOT_FOUND_KEY: 1,
429
- FALLBACK_TO_TRANSLATE: 2,
430
- CANNOT_FORMAT_NUMBER: 3,
431
- FALLBACK_TO_NUMBER_FORMAT: 4,
432
- CANNOT_FORMAT_DATE: 5,
433
- FALLBACK_TO_DATE_FORMAT: 6,
434
- __EXTEND_POINT__: 7
435
- };
436
- /** @internal */
437
- const warnMessages = {
438
- [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
439
- [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
440
- [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
441
- [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
442
- [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
443
- [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`
444
- };
445
- function getWarnMessage(code, ...args) {
446
- return shared.format(warnMessages[code], ...args);
427
+ const CoreWarnCodes = {
428
+ NOT_FOUND_KEY: 1,
429
+ FALLBACK_TO_TRANSLATE: 2,
430
+ CANNOT_FORMAT_NUMBER: 3,
431
+ FALLBACK_TO_NUMBER_FORMAT: 4,
432
+ CANNOT_FORMAT_DATE: 5,
433
+ FALLBACK_TO_DATE_FORMAT: 6,
434
+ __EXTEND_POINT__: 7
435
+ };
436
+ /** @internal */
437
+ const warnMessages = {
438
+ [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
439
+ [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
440
+ [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
441
+ [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
442
+ [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
443
+ [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`
444
+ };
445
+ function getWarnMessage(code, ...args) {
446
+ return shared.format(warnMessages[code], ...args);
447
447
  }
448
448
 
449
- /**
450
- * Fallback with simple implemenation
451
- *
452
- * @remarks
453
- * A fallback locale function implemented with a simple fallback algorithm.
454
- *
455
- * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
456
- *
457
- * @param ctx - A {@link CoreContext | context}
458
- * @param fallback - A {@link FallbackLocale | fallback locale}
459
- * @param start - A starting {@link Locale | locale}
460
- *
461
- * @returns Fallback locales
462
- *
463
- * @VueI18nGeneral
464
- */
465
- function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
466
- ) {
467
- // prettier-ignore
468
- return [...new Set([
469
- start,
470
- ...(shared.isArray(fallback)
471
- ? fallback
472
- : shared.isObject(fallback)
473
- ? Object.keys(fallback)
474
- : shared.isString(fallback)
475
- ? [fallback]
476
- : [start])
477
- ])];
478
- }
479
- /**
480
- * Fallback with locale chain
481
- *
482
- * @remarks
483
- * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
484
- *
485
- * @param ctx - A {@link CoreContext | context}
486
- * @param fallback - A {@link FallbackLocale | fallback locale}
487
- * @param start - A starting {@link Locale | locale}
488
- *
489
- * @returns Fallback locales
490
- *
491
- * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
492
- *
493
- * @VueI18nGeneral
494
- */
495
- function fallbackWithLocaleChain(ctx, fallback, start) {
496
- const startLocale = shared.isString(start) ? start : DEFAULT_LOCALE;
497
- const context = ctx;
498
- if (!context.__localeChainCache) {
499
- context.__localeChainCache = new Map();
500
- }
501
- let chain = context.__localeChainCache.get(startLocale);
502
- if (!chain) {
503
- chain = [];
504
- // first block defined by start
505
- let block = [start];
506
- // while any intervening block found
507
- while (shared.isArray(block)) {
508
- block = appendBlockToChain(chain, block, fallback);
509
- }
510
- // prettier-ignore
511
- // last block defined by default
512
- const defaults = shared.isArray(fallback) || !shared.isPlainObject(fallback)
513
- ? fallback
514
- : fallback['default']
515
- ? fallback['default']
516
- : null;
517
- // convert defaults to array
518
- block = shared.isString(defaults) ? [defaults] : defaults;
519
- if (shared.isArray(block)) {
520
- appendBlockToChain(chain, block, false);
521
- }
522
- context.__localeChainCache.set(startLocale, chain);
523
- }
524
- return chain;
525
- }
526
- function appendBlockToChain(chain, block, blocks) {
527
- let follow = true;
528
- for (let i = 0; i < block.length && shared.isBoolean(follow); i++) {
529
- const locale = block[i];
530
- if (shared.isString(locale)) {
531
- follow = appendLocaleToChain(chain, block[i], blocks);
532
- }
533
- }
534
- return follow;
535
- }
536
- function appendLocaleToChain(chain, locale, blocks) {
537
- let follow;
538
- const tokens = locale.split('-');
539
- do {
540
- const target = tokens.join('-');
541
- follow = appendItemToChain(chain, target, blocks);
542
- tokens.splice(-1, 1);
543
- } while (tokens.length && follow === true);
544
- return follow;
545
- }
546
- function appendItemToChain(chain, target, blocks) {
547
- let follow = false;
548
- if (!chain.includes(target)) {
549
- follow = true;
550
- if (target) {
551
- follow = target[target.length - 1] !== '!';
552
- const locale = target.replace(/!/g, '');
553
- chain.push(locale);
554
- if ((shared.isArray(blocks) || shared.isPlainObject(blocks)) &&
555
- blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
556
- ) {
557
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
558
- follow = blocks[locale];
559
- }
560
- }
561
- }
562
- return follow;
449
+ /**
450
+ * Fallback with simple implemenation
451
+ *
452
+ * @remarks
453
+ * A fallback locale function implemented with a simple fallback algorithm.
454
+ *
455
+ * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
456
+ *
457
+ * @param ctx - A {@link CoreContext | context}
458
+ * @param fallback - A {@link FallbackLocale | fallback locale}
459
+ * @param start - A starting {@link Locale | locale}
460
+ *
461
+ * @returns Fallback locales
462
+ *
463
+ * @VueI18nGeneral
464
+ */
465
+ function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
466
+ ) {
467
+ // prettier-ignore
468
+ return [...new Set([
469
+ start,
470
+ ...(shared.isArray(fallback)
471
+ ? fallback
472
+ : shared.isObject(fallback)
473
+ ? Object.keys(fallback)
474
+ : shared.isString(fallback)
475
+ ? [fallback]
476
+ : [start])
477
+ ])];
478
+ }
479
+ /**
480
+ * Fallback with locale chain
481
+ *
482
+ * @remarks
483
+ * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
484
+ *
485
+ * @param ctx - A {@link CoreContext | context}
486
+ * @param fallback - A {@link FallbackLocale | fallback locale}
487
+ * @param start - A starting {@link Locale | locale}
488
+ *
489
+ * @returns Fallback locales
490
+ *
491
+ * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
492
+ *
493
+ * @VueI18nGeneral
494
+ */
495
+ function fallbackWithLocaleChain(ctx, fallback, start) {
496
+ const startLocale = shared.isString(start) ? start : DEFAULT_LOCALE;
497
+ const context = ctx;
498
+ if (!context.__localeChainCache) {
499
+ context.__localeChainCache = new Map();
500
+ }
501
+ let chain = context.__localeChainCache.get(startLocale);
502
+ if (!chain) {
503
+ chain = [];
504
+ // first block defined by start
505
+ let block = [start];
506
+ // while any intervening block found
507
+ while (shared.isArray(block)) {
508
+ block = appendBlockToChain(chain, block, fallback);
509
+ }
510
+ // prettier-ignore
511
+ // last block defined by default
512
+ const defaults = shared.isArray(fallback) || !shared.isPlainObject(fallback)
513
+ ? fallback
514
+ : fallback['default']
515
+ ? fallback['default']
516
+ : null;
517
+ // convert defaults to array
518
+ block = shared.isString(defaults) ? [defaults] : defaults;
519
+ if (shared.isArray(block)) {
520
+ appendBlockToChain(chain, block, false);
521
+ }
522
+ context.__localeChainCache.set(startLocale, chain);
523
+ }
524
+ return chain;
525
+ }
526
+ function appendBlockToChain(chain, block, blocks) {
527
+ let follow = true;
528
+ for (let i = 0; i < block.length && shared.isBoolean(follow); i++) {
529
+ const locale = block[i];
530
+ if (shared.isString(locale)) {
531
+ follow = appendLocaleToChain(chain, block[i], blocks);
532
+ }
533
+ }
534
+ return follow;
535
+ }
536
+ function appendLocaleToChain(chain, locale, blocks) {
537
+ let follow;
538
+ const tokens = locale.split('-');
539
+ do {
540
+ const target = tokens.join('-');
541
+ follow = appendItemToChain(chain, target, blocks);
542
+ tokens.splice(-1, 1);
543
+ } while (tokens.length && follow === true);
544
+ return follow;
545
+ }
546
+ function appendItemToChain(chain, target, blocks) {
547
+ let follow = false;
548
+ if (!chain.includes(target)) {
549
+ follow = true;
550
+ if (target) {
551
+ follow = target[target.length - 1] !== '!';
552
+ const locale = target.replace(/!/g, '');
553
+ chain.push(locale);
554
+ if ((shared.isArray(blocks) || shared.isPlainObject(blocks)) &&
555
+ blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
556
+ ) {
557
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
558
+ follow = blocks[locale];
559
+ }
560
+ }
561
+ }
562
+ return follow;
563
563
  }
564
564
 
565
- /* eslint-disable @typescript-eslint/no-explicit-any */
566
- /**
567
- * Intlify core-base version
568
- * @internal
569
- */
570
- const VERSION = '9.3.0-beta.17';
571
- const NOT_REOSLVED = -1;
572
- const DEFAULT_LOCALE = 'en-US';
573
- const MISSING_RESOLVE_VALUE = '';
574
- const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
575
- function getDefaultLinkedModifiers() {
576
- return {
577
- upper: (val, type) => {
578
- // prettier-ignore
579
- return type === 'text' && shared.isString(val)
580
- ? val.toUpperCase()
581
- : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
582
- ? val.children.toUpperCase()
583
- : val;
584
- },
585
- lower: (val, type) => {
586
- // prettier-ignore
587
- return type === 'text' && shared.isString(val)
588
- ? val.toLowerCase()
589
- : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
590
- ? val.children.toLowerCase()
591
- : val;
592
- },
593
- capitalize: (val, type) => {
594
- // prettier-ignore
595
- return (type === 'text' && shared.isString(val)
596
- ? capitalize(val)
597
- : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
598
- ? capitalize(val.children)
599
- : val);
600
- }
601
- };
602
- }
603
- let _compiler;
604
- function registerMessageCompiler(compiler) {
605
- _compiler = compiler;
606
- }
607
- let _resolver;
608
- /**
609
- * Register the message resolver
610
- *
611
- * @param resolver - A {@link MessageResolver} function
612
- *
613
- * @VueI18nGeneral
614
- */
615
- function registerMessageResolver(resolver) {
616
- _resolver = resolver;
617
- }
618
- let _fallbacker;
619
- /**
620
- * Register the locale fallbacker
621
- *
622
- * @param fallbacker - A {@link LocaleFallbacker} function
623
- *
624
- * @VueI18nGeneral
625
- */
626
- function registerLocaleFallbacker(fallbacker) {
627
- _fallbacker = fallbacker;
628
- }
629
- // Additional Meta for Intlify DevTools
630
- let _additionalMeta = null;
631
- const setAdditionalMeta = (meta) => {
632
- _additionalMeta = meta;
633
- };
634
- const getAdditionalMeta = () => _additionalMeta;
635
- let _fallbackContext = null;
636
- const setFallbackContext = (context) => {
637
- _fallbackContext = context;
638
- };
639
- const getFallbackContext = () => _fallbackContext;
640
- // ID for CoreContext
641
- let _cid = 0;
642
- function createCoreContext(options = {}) {
643
- // setup options
644
- const version = shared.isString(options.version) ? options.version : VERSION;
645
- const locale = shared.isString(options.locale) ? options.locale : DEFAULT_LOCALE;
646
- const fallbackLocale = shared.isArray(options.fallbackLocale) ||
647
- shared.isPlainObject(options.fallbackLocale) ||
648
- shared.isString(options.fallbackLocale) ||
649
- options.fallbackLocale === false
650
- ? options.fallbackLocale
651
- : locale;
652
- const messages = shared.isPlainObject(options.messages)
653
- ? options.messages
654
- : { [locale]: {} };
655
- const datetimeFormats = shared.isPlainObject(options.datetimeFormats)
656
- ? options.datetimeFormats
657
- : { [locale]: {} }
658
- ;
659
- const numberFormats = shared.isPlainObject(options.numberFormats)
660
- ? options.numberFormats
661
- : { [locale]: {} }
662
- ;
663
- const modifiers = shared.assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
664
- const pluralRules = options.pluralRules || {};
665
- const missing = shared.isFunction(options.missing) ? options.missing : null;
666
- const missingWarn = shared.isBoolean(options.missingWarn) || shared.isRegExp(options.missingWarn)
667
- ? options.missingWarn
668
- : true;
669
- const fallbackWarn = shared.isBoolean(options.fallbackWarn) || shared.isRegExp(options.fallbackWarn)
670
- ? options.fallbackWarn
671
- : true;
672
- const fallbackFormat = !!options.fallbackFormat;
673
- const unresolving = !!options.unresolving;
674
- const postTranslation = shared.isFunction(options.postTranslation)
675
- ? options.postTranslation
676
- : null;
677
- const processor = shared.isPlainObject(options.processor) ? options.processor : null;
678
- const warnHtmlMessage = shared.isBoolean(options.warnHtmlMessage)
679
- ? options.warnHtmlMessage
680
- : true;
681
- const escapeParameter = !!options.escapeParameter;
682
- const messageCompiler = shared.isFunction(options.messageCompiler)
683
- ? options.messageCompiler
684
- : _compiler;
685
- const messageResolver = shared.isFunction(options.messageResolver)
686
- ? options.messageResolver
687
- : _resolver || resolveWithKeyValue;
688
- const localeFallbacker = shared.isFunction(options.localeFallbacker)
689
- ? options.localeFallbacker
690
- : _fallbacker || fallbackWithSimple;
691
- const fallbackContext = shared.isObject(options.fallbackContext)
692
- ? options.fallbackContext
693
- : undefined;
694
- const onWarn = shared.isFunction(options.onWarn) ? options.onWarn : shared.warn;
695
- // setup internal options
696
- const internalOptions = options;
697
- const __datetimeFormatters = shared.isObject(internalOptions.__datetimeFormatters)
698
- ? internalOptions.__datetimeFormatters
699
- : new Map()
700
- ;
701
- const __numberFormatters = shared.isObject(internalOptions.__numberFormatters)
702
- ? internalOptions.__numberFormatters
703
- : new Map()
704
- ;
705
- const __meta = shared.isObject(internalOptions.__meta) ? internalOptions.__meta : {};
706
- _cid++;
707
- const context = {
708
- version,
709
- cid: _cid,
710
- locale,
711
- fallbackLocale,
712
- messages,
713
- modifiers,
714
- pluralRules,
715
- missing,
716
- missingWarn,
717
- fallbackWarn,
718
- fallbackFormat,
719
- unresolving,
720
- postTranslation,
721
- processor,
722
- warnHtmlMessage,
723
- escapeParameter,
724
- messageCompiler,
725
- messageResolver,
726
- localeFallbacker,
727
- fallbackContext,
728
- onWarn,
729
- __meta
730
- };
731
- {
732
- context.datetimeFormats = datetimeFormats;
733
- context.numberFormats = numberFormats;
734
- context.__datetimeFormatters = __datetimeFormatters;
735
- context.__numberFormatters = __numberFormatters;
736
- }
737
- return context;
738
- }
739
- /** @internal */
740
- function isTranslateFallbackWarn(fallback, key) {
741
- return fallback instanceof RegExp ? fallback.test(key) : fallback;
742
- }
743
- /** @internal */
744
- function isTranslateMissingWarn(missing, key) {
745
- return missing instanceof RegExp ? missing.test(key) : missing;
746
- }
747
- /** @internal */
748
- function handleMissing(context, key, locale, missingWarn, type) {
749
- const { missing, onWarn } = context;
750
- if (missing !== null) {
751
- const ret = missing(context, locale, key, type);
752
- return shared.isString(ret) ? ret : key;
753
- }
754
- else {
755
- return key;
756
- }
757
- }
758
- /** @internal */
759
- function updateFallbackLocale(ctx, locale, fallback) {
760
- const context = ctx;
761
- context.__localeChainCache = new Map();
762
- ctx.localeFallbacker(ctx, fallback, locale);
763
- }
565
+ /* eslint-disable @typescript-eslint/no-explicit-any */
566
+ /**
567
+ * Intlify core-base version
568
+ * @internal
569
+ */
570
+ const VERSION = '9.3.0-beta.18';
571
+ const NOT_REOSLVED = -1;
572
+ const DEFAULT_LOCALE = 'en-US';
573
+ const MISSING_RESOLVE_VALUE = '';
574
+ const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
575
+ function getDefaultLinkedModifiers() {
576
+ return {
577
+ upper: (val, type) => {
578
+ // prettier-ignore
579
+ return type === 'text' && shared.isString(val)
580
+ ? val.toUpperCase()
581
+ : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
582
+ ? val.children.toUpperCase()
583
+ : val;
584
+ },
585
+ lower: (val, type) => {
586
+ // prettier-ignore
587
+ return type === 'text' && shared.isString(val)
588
+ ? val.toLowerCase()
589
+ : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
590
+ ? val.children.toLowerCase()
591
+ : val;
592
+ },
593
+ capitalize: (val, type) => {
594
+ // prettier-ignore
595
+ return (type === 'text' && shared.isString(val)
596
+ ? capitalize(val)
597
+ : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
598
+ ? capitalize(val.children)
599
+ : val);
600
+ }
601
+ };
602
+ }
603
+ let _compiler;
604
+ function registerMessageCompiler(compiler) {
605
+ _compiler = compiler;
606
+ }
607
+ let _resolver;
608
+ /**
609
+ * Register the message resolver
610
+ *
611
+ * @param resolver - A {@link MessageResolver} function
612
+ *
613
+ * @VueI18nGeneral
614
+ */
615
+ function registerMessageResolver(resolver) {
616
+ _resolver = resolver;
617
+ }
618
+ let _fallbacker;
619
+ /**
620
+ * Register the locale fallbacker
621
+ *
622
+ * @param fallbacker - A {@link LocaleFallbacker} function
623
+ *
624
+ * @VueI18nGeneral
625
+ */
626
+ function registerLocaleFallbacker(fallbacker) {
627
+ _fallbacker = fallbacker;
628
+ }
629
+ // Additional Meta for Intlify DevTools
630
+ let _additionalMeta = null;
631
+ const setAdditionalMeta = (meta) => {
632
+ _additionalMeta = meta;
633
+ };
634
+ const getAdditionalMeta = () => _additionalMeta;
635
+ let _fallbackContext = null;
636
+ const setFallbackContext = (context) => {
637
+ _fallbackContext = context;
638
+ };
639
+ const getFallbackContext = () => _fallbackContext;
640
+ // ID for CoreContext
641
+ let _cid = 0;
642
+ function createCoreContext(options = {}) {
643
+ // setup options
644
+ const version = shared.isString(options.version) ? options.version : VERSION;
645
+ const locale = shared.isString(options.locale) ? options.locale : DEFAULT_LOCALE;
646
+ const fallbackLocale = shared.isArray(options.fallbackLocale) ||
647
+ shared.isPlainObject(options.fallbackLocale) ||
648
+ shared.isString(options.fallbackLocale) ||
649
+ options.fallbackLocale === false
650
+ ? options.fallbackLocale
651
+ : locale;
652
+ const messages = shared.isPlainObject(options.messages)
653
+ ? options.messages
654
+ : { [locale]: {} };
655
+ const datetimeFormats = shared.isPlainObject(options.datetimeFormats)
656
+ ? options.datetimeFormats
657
+ : { [locale]: {} }
658
+ ;
659
+ const numberFormats = shared.isPlainObject(options.numberFormats)
660
+ ? options.numberFormats
661
+ : { [locale]: {} }
662
+ ;
663
+ const modifiers = shared.assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
664
+ const pluralRules = options.pluralRules || {};
665
+ const missing = shared.isFunction(options.missing) ? options.missing : null;
666
+ const missingWarn = shared.isBoolean(options.missingWarn) || shared.isRegExp(options.missingWarn)
667
+ ? options.missingWarn
668
+ : true;
669
+ const fallbackWarn = shared.isBoolean(options.fallbackWarn) || shared.isRegExp(options.fallbackWarn)
670
+ ? options.fallbackWarn
671
+ : true;
672
+ const fallbackFormat = !!options.fallbackFormat;
673
+ const unresolving = !!options.unresolving;
674
+ const postTranslation = shared.isFunction(options.postTranslation)
675
+ ? options.postTranslation
676
+ : null;
677
+ const processor = shared.isPlainObject(options.processor) ? options.processor : null;
678
+ const warnHtmlMessage = shared.isBoolean(options.warnHtmlMessage)
679
+ ? options.warnHtmlMessage
680
+ : true;
681
+ const escapeParameter = !!options.escapeParameter;
682
+ const messageCompiler = shared.isFunction(options.messageCompiler)
683
+ ? options.messageCompiler
684
+ : _compiler;
685
+ const messageResolver = shared.isFunction(options.messageResolver)
686
+ ? options.messageResolver
687
+ : _resolver || resolveWithKeyValue;
688
+ const localeFallbacker = shared.isFunction(options.localeFallbacker)
689
+ ? options.localeFallbacker
690
+ : _fallbacker || fallbackWithSimple;
691
+ const fallbackContext = shared.isObject(options.fallbackContext)
692
+ ? options.fallbackContext
693
+ : undefined;
694
+ const onWarn = shared.isFunction(options.onWarn) ? options.onWarn : shared.warn;
695
+ // setup internal options
696
+ const internalOptions = options;
697
+ const __datetimeFormatters = shared.isObject(internalOptions.__datetimeFormatters)
698
+ ? internalOptions.__datetimeFormatters
699
+ : new Map()
700
+ ;
701
+ const __numberFormatters = shared.isObject(internalOptions.__numberFormatters)
702
+ ? internalOptions.__numberFormatters
703
+ : new Map()
704
+ ;
705
+ const __meta = shared.isObject(internalOptions.__meta) ? internalOptions.__meta : {};
706
+ _cid++;
707
+ const context = {
708
+ version,
709
+ cid: _cid,
710
+ locale,
711
+ fallbackLocale,
712
+ messages,
713
+ modifiers,
714
+ pluralRules,
715
+ missing,
716
+ missingWarn,
717
+ fallbackWarn,
718
+ fallbackFormat,
719
+ unresolving,
720
+ postTranslation,
721
+ processor,
722
+ warnHtmlMessage,
723
+ escapeParameter,
724
+ messageCompiler,
725
+ messageResolver,
726
+ localeFallbacker,
727
+ fallbackContext,
728
+ onWarn,
729
+ __meta
730
+ };
731
+ {
732
+ context.datetimeFormats = datetimeFormats;
733
+ context.numberFormats = numberFormats;
734
+ context.__datetimeFormatters = __datetimeFormatters;
735
+ context.__numberFormatters = __numberFormatters;
736
+ }
737
+ return context;
738
+ }
739
+ /** @internal */
740
+ function isTranslateFallbackWarn(fallback, key) {
741
+ return fallback instanceof RegExp ? fallback.test(key) : fallback;
742
+ }
743
+ /** @internal */
744
+ function isTranslateMissingWarn(missing, key) {
745
+ return missing instanceof RegExp ? missing.test(key) : missing;
746
+ }
747
+ /** @internal */
748
+ function handleMissing(context, key, locale, missingWarn, type) {
749
+ const { missing, onWarn } = context;
750
+ if (missing !== null) {
751
+ const ret = missing(context, locale, key, type);
752
+ return shared.isString(ret) ? ret : key;
753
+ }
754
+ else {
755
+ return key;
756
+ }
757
+ }
758
+ /** @internal */
759
+ function updateFallbackLocale(ctx, locale, fallback) {
760
+ const context = ctx;
761
+ context.__localeChainCache = new Map();
762
+ ctx.localeFallbacker(ctx, fallback, locale);
763
+ }
764
764
  /* eslint-enable @typescript-eslint/no-explicit-any */
765
765
 
766
- const defaultOnCacheKey = (source) => source;
767
- let compileCache = Object.create(null);
768
- function clearCompileCache() {
769
- compileCache = Object.create(null);
770
- }
771
- function compileToFunction(source, options = {}) {
772
- {
773
- // check HTML message
774
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
775
- shared.isBoolean(options.warnHtmlMessage)
776
- ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
777
- options.warnHtmlMessage
778
- : true;
779
- // check caches
780
- const onCacheKey = options.onCacheKey || defaultOnCacheKey;
781
- const key = onCacheKey(source);
782
- const cached = compileCache[key];
783
- if (cached) {
784
- return cached;
785
- }
786
- // compile error detecting
787
- let occurred = false;
788
- const onError = options.onError || messageCompiler.defaultOnError;
789
- options.onError = (err) => {
790
- occurred = true;
791
- onError(err);
792
- };
793
- // compile
794
- const { code } = messageCompiler.baseCompile(source, options);
795
- // evaluate function
796
- const msg = new Function(`return ${code}`)();
797
- // if occurred compile error, don't cache
798
- return !occurred ? (compileCache[key] = msg) : msg;
799
- }
766
+ const defaultOnCacheKey = (source) => source;
767
+ let compileCache = Object.create(null);
768
+ function clearCompileCache() {
769
+ compileCache = Object.create(null);
770
+ }
771
+ function compileToFunction(source, options = {}) {
772
+ {
773
+ // check HTML message
774
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
775
+ shared.isBoolean(options.warnHtmlMessage)
776
+ ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
777
+ options.warnHtmlMessage
778
+ : true;
779
+ // check caches
780
+ const onCacheKey = options.onCacheKey || defaultOnCacheKey;
781
+ const key = onCacheKey(source);
782
+ const cached = compileCache[key];
783
+ if (cached) {
784
+ return cached;
785
+ }
786
+ // compile error detecting
787
+ let occurred = false;
788
+ const onError = options.onError || messageCompiler.defaultOnError;
789
+ options.onError = (err) => {
790
+ occurred = true;
791
+ onError(err);
792
+ };
793
+ // compile
794
+ const { code } = messageCompiler.baseCompile(source, options);
795
+ // evaluate function
796
+ const msg = new Function(`return ${code}`)();
797
+ // if occurred compile error, don't cache
798
+ return !occurred ? (compileCache[key] = msg) : msg;
799
+ }
800
800
  }
801
801
 
802
- let code = messageCompiler.CompileErrorCodes.__EXTEND_POINT__;
803
- const inc = () => ++code;
804
- const CoreErrorCodes = {
805
- INVALID_ARGUMENT: code,
806
- INVALID_DATE_ARGUMENT: inc(),
807
- INVALID_ISO_DATE_ARGUMENT: inc(),
808
- __EXTEND_POINT__: inc() // 18
809
- };
810
- function createCoreError(code) {
811
- return messageCompiler.createCompileError(code, null, undefined);
812
- }
813
- /** @internal */
814
- ({
815
- [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
816
- [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
817
- 'Make sure your Date represents a valid date.',
818
- [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string'
802
+ let code = messageCompiler.CompileErrorCodes.__EXTEND_POINT__;
803
+ const inc = () => ++code;
804
+ const CoreErrorCodes = {
805
+ INVALID_ARGUMENT: code,
806
+ INVALID_DATE_ARGUMENT: inc(),
807
+ INVALID_ISO_DATE_ARGUMENT: inc(),
808
+ __EXTEND_POINT__: inc() // 18
809
+ };
810
+ function createCoreError(code) {
811
+ return messageCompiler.createCompileError(code, null, undefined);
812
+ }
813
+ /** @internal */
814
+ ({
815
+ [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
816
+ [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
817
+ 'Make sure your Date represents a valid date.',
818
+ [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string'
819
819
  });
820
820
 
821
- const NOOP_MESSAGE_FUNCTION = () => '';
822
- const isMessageFunction = (val) => shared.isFunction(val);
823
- // implementation of `translate` function
824
- function translate(context, ...args) {
825
- const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
826
- const [key, options] = parseTranslateArgs(...args);
827
- const missingWarn = shared.isBoolean(options.missingWarn)
828
- ? options.missingWarn
829
- : context.missingWarn;
830
- const fallbackWarn = shared.isBoolean(options.fallbackWarn)
831
- ? options.fallbackWarn
832
- : context.fallbackWarn;
833
- const escapeParameter = shared.isBoolean(options.escapeParameter)
834
- ? options.escapeParameter
835
- : context.escapeParameter;
836
- const resolvedMessage = !!options.resolvedMessage;
837
- // prettier-ignore
838
- const defaultMsgOrKey = shared.isString(options.default) || shared.isBoolean(options.default) // default by function option
839
- ? !shared.isBoolean(options.default)
840
- ? options.default
841
- : (!messageCompiler ? () => key : key)
842
- : fallbackFormat // default by `fallbackFormat` option
843
- ? (!messageCompiler ? () => key : key)
844
- : '';
845
- const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
846
- const locale = shared.isString(options.locale) ? options.locale : context.locale;
847
- // escape params
848
- escapeParameter && escapeParams(options);
849
- // resolve message format
850
- // eslint-disable-next-line prefer-const
851
- let [formatScope, targetLocale, message] = !resolvedMessage
852
- ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
853
- : [
854
- key,
855
- locale,
856
- messages[locale] || {}
857
- ];
858
- // NOTE:
859
- // Fix to work around `ssrTransfrom` bug in Vite.
860
- // https://github.com/vitejs/vite/issues/4306
861
- // To get around this, use temporary variables.
862
- // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
863
- let format = formatScope;
864
- // if you use default message, set it as message format!
865
- let cacheBaseKey = key;
866
- if (!resolvedMessage &&
867
- !(shared.isString(format) || isMessageFunction(format))) {
868
- if (enableDefaultMsg) {
869
- format = defaultMsgOrKey;
870
- cacheBaseKey = format;
871
- }
872
- }
873
- // checking message format and target locale
874
- if (!resolvedMessage &&
875
- (!(shared.isString(format) || isMessageFunction(format)) ||
876
- !shared.isString(targetLocale))) {
877
- return unresolving ? NOT_REOSLVED : key;
878
- }
879
- // setup compile error detecting
880
- let occurred = false;
881
- const errorDetector = () => {
882
- occurred = true;
883
- };
884
- // compile message format
885
- const msg = !isMessageFunction(format)
886
- ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
887
- : format;
888
- // if occurred compile error, return the message format
889
- if (occurred) {
890
- return format;
891
- }
892
- // evaluate message with context
893
- const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
894
- const msgContext = createMessageContext(ctxOptions);
895
- const messaged = evaluateMessage(context, msg, msgContext);
896
- // if use post translation option, proceed it with handler
897
- const ret = postTranslation
898
- ? postTranslation(messaged, key)
899
- : messaged;
900
- return ret;
901
- }
902
- function escapeParams(options) {
903
- if (shared.isArray(options.list)) {
904
- options.list = options.list.map(item => shared.isString(item) ? shared.escapeHtml(item) : item);
905
- }
906
- else if (shared.isObject(options.named)) {
907
- Object.keys(options.named).forEach(key => {
908
- if (shared.isString(options.named[key])) {
909
- options.named[key] = shared.escapeHtml(options.named[key]);
910
- }
911
- });
912
- }
913
- }
914
- function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
915
- const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
916
- const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
917
- let message = {};
918
- let targetLocale;
919
- let format = null;
920
- const type = 'translate';
921
- for (let i = 0; i < locales.length; i++) {
922
- targetLocale = locales[i];
923
- message =
924
- messages[targetLocale] || {};
925
- if ((format = resolveValue(message, key)) === null) {
926
- // if null, resolve with object key path
927
- format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
928
- }
929
- if (shared.isString(format) || shared.isFunction(format))
930
- break;
931
- const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
932
- key, targetLocale, missingWarn, type);
933
- if (missingRet !== key) {
934
- format = missingRet;
935
- }
936
- }
937
- return [format, targetLocale, message];
938
- }
939
- function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
940
- const { messageCompiler, warnHtmlMessage } = context;
941
- if (isMessageFunction(format)) {
942
- const msg = format;
943
- msg.locale = msg.locale || targetLocale;
944
- msg.key = msg.key || key;
945
- return msg;
946
- }
947
- if (messageCompiler == null) {
948
- const msg = (() => format);
949
- msg.locale = targetLocale;
950
- msg.key = key;
951
- return msg;
952
- }
953
- const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
954
- msg.locale = targetLocale;
955
- msg.key = key;
956
- msg.source = format;
957
- return msg;
958
- }
959
- function evaluateMessage(context, msg, msgCtx) {
960
- const messaged = msg(msgCtx);
961
- return messaged;
962
- }
963
- /** @internal */
964
- function parseTranslateArgs(...args) {
965
- const [arg1, arg2, arg3] = args;
966
- const options = {};
967
- if (!shared.isString(arg1) && !shared.isNumber(arg1) && !isMessageFunction(arg1)) {
968
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
969
- }
970
- // prettier-ignore
971
- const key = shared.isNumber(arg1)
972
- ? String(arg1)
973
- : isMessageFunction(arg1)
974
- ? arg1
975
- : arg1;
976
- if (shared.isNumber(arg2)) {
977
- options.plural = arg2;
978
- }
979
- else if (shared.isString(arg2)) {
980
- options.default = arg2;
981
- }
982
- else if (shared.isPlainObject(arg2) && !shared.isEmptyObject(arg2)) {
983
- options.named = arg2;
984
- }
985
- else if (shared.isArray(arg2)) {
986
- options.list = arg2;
987
- }
988
- if (shared.isNumber(arg3)) {
989
- options.plural = arg3;
990
- }
991
- else if (shared.isString(arg3)) {
992
- options.default = arg3;
993
- }
994
- else if (shared.isPlainObject(arg3)) {
995
- shared.assign(options, arg3);
996
- }
997
- return [key, options];
998
- }
999
- function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
1000
- return {
1001
- warnHtmlMessage,
1002
- onError: (err) => {
1003
- errorDetector && errorDetector(err);
1004
- {
1005
- throw err;
1006
- }
1007
- },
1008
- onCacheKey: (source) => shared.generateFormatCacheKey(locale, key, source)
1009
- };
1010
- }
1011
- function getMessageContextOptions(context, locale, message, options) {
1012
- const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
1013
- const resolveMessage = (key) => {
1014
- let val = resolveValue(message, key);
1015
- // fallback to root context
1016
- if (val == null && fallbackContext) {
1017
- const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
1018
- val = resolveValue(message, key);
1019
- }
1020
- if (shared.isString(val)) {
1021
- let occurred = false;
1022
- const errorDetector = () => {
1023
- occurred = true;
1024
- };
1025
- const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
1026
- return !occurred
1027
- ? msg
1028
- : NOOP_MESSAGE_FUNCTION;
1029
- }
1030
- else if (isMessageFunction(val)) {
1031
- return val;
1032
- }
1033
- else {
1034
- // TODO: should be implemented warning message
1035
- return NOOP_MESSAGE_FUNCTION;
1036
- }
1037
- };
1038
- const ctxOptions = {
1039
- locale,
1040
- modifiers,
1041
- pluralRules,
1042
- messages: resolveMessage
1043
- };
1044
- if (context.processor) {
1045
- ctxOptions.processor = context.processor;
1046
- }
1047
- if (options.list) {
1048
- ctxOptions.list = options.list;
1049
- }
1050
- if (options.named) {
1051
- ctxOptions.named = options.named;
1052
- }
1053
- if (shared.isNumber(options.plural)) {
1054
- ctxOptions.pluralIndex = options.plural;
1055
- }
1056
- return ctxOptions;
821
+ const NOOP_MESSAGE_FUNCTION = () => '';
822
+ const isMessageFunction = (val) => shared.isFunction(val);
823
+ // implementation of `translate` function
824
+ function translate(context, ...args) {
825
+ const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
826
+ const [key, options] = parseTranslateArgs(...args);
827
+ const missingWarn = shared.isBoolean(options.missingWarn)
828
+ ? options.missingWarn
829
+ : context.missingWarn;
830
+ const fallbackWarn = shared.isBoolean(options.fallbackWarn)
831
+ ? options.fallbackWarn
832
+ : context.fallbackWarn;
833
+ const escapeParameter = shared.isBoolean(options.escapeParameter)
834
+ ? options.escapeParameter
835
+ : context.escapeParameter;
836
+ const resolvedMessage = !!options.resolvedMessage;
837
+ // prettier-ignore
838
+ const defaultMsgOrKey = shared.isString(options.default) || shared.isBoolean(options.default) // default by function option
839
+ ? !shared.isBoolean(options.default)
840
+ ? options.default
841
+ : (!messageCompiler ? () => key : key)
842
+ : fallbackFormat // default by `fallbackFormat` option
843
+ ? (!messageCompiler ? () => key : key)
844
+ : '';
845
+ const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
846
+ const locale = shared.isString(options.locale) ? options.locale : context.locale;
847
+ // escape params
848
+ escapeParameter && escapeParams(options);
849
+ // resolve message format
850
+ // eslint-disable-next-line prefer-const
851
+ let [formatScope, targetLocale, message] = !resolvedMessage
852
+ ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
853
+ : [
854
+ key,
855
+ locale,
856
+ messages[locale] || {}
857
+ ];
858
+ // NOTE:
859
+ // Fix to work around `ssrTransfrom` bug in Vite.
860
+ // https://github.com/vitejs/vite/issues/4306
861
+ // To get around this, use temporary variables.
862
+ // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
863
+ let format = formatScope;
864
+ // if you use default message, set it as message format!
865
+ let cacheBaseKey = key;
866
+ if (!resolvedMessage &&
867
+ !(shared.isString(format) || isMessageFunction(format))) {
868
+ if (enableDefaultMsg) {
869
+ format = defaultMsgOrKey;
870
+ cacheBaseKey = format;
871
+ }
872
+ }
873
+ // checking message format and target locale
874
+ if (!resolvedMessage &&
875
+ (!(shared.isString(format) || isMessageFunction(format)) ||
876
+ !shared.isString(targetLocale))) {
877
+ return unresolving ? NOT_REOSLVED : key;
878
+ }
879
+ // setup compile error detecting
880
+ let occurred = false;
881
+ const errorDetector = () => {
882
+ occurred = true;
883
+ };
884
+ // compile message format
885
+ const msg = !isMessageFunction(format)
886
+ ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
887
+ : format;
888
+ // if occurred compile error, return the message format
889
+ if (occurred) {
890
+ return format;
891
+ }
892
+ // evaluate message with context
893
+ const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
894
+ const msgContext = createMessageContext(ctxOptions);
895
+ const messaged = evaluateMessage(context, msg, msgContext);
896
+ // if use post translation option, proceed it with handler
897
+ const ret = postTranslation
898
+ ? postTranslation(messaged, key)
899
+ : messaged;
900
+ return ret;
901
+ }
902
+ function escapeParams(options) {
903
+ if (shared.isArray(options.list)) {
904
+ options.list = options.list.map(item => shared.isString(item) ? shared.escapeHtml(item) : item);
905
+ }
906
+ else if (shared.isObject(options.named)) {
907
+ Object.keys(options.named).forEach(key => {
908
+ if (shared.isString(options.named[key])) {
909
+ options.named[key] = shared.escapeHtml(options.named[key]);
910
+ }
911
+ });
912
+ }
913
+ }
914
+ function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
915
+ const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
916
+ const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
917
+ let message = {};
918
+ let targetLocale;
919
+ let format = null;
920
+ const type = 'translate';
921
+ for (let i = 0; i < locales.length; i++) {
922
+ targetLocale = locales[i];
923
+ message =
924
+ messages[targetLocale] || {};
925
+ if ((format = resolveValue(message, key)) === null) {
926
+ // if null, resolve with object key path
927
+ format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
928
+ }
929
+ if (shared.isString(format) || shared.isFunction(format))
930
+ break;
931
+ const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
932
+ key, targetLocale, missingWarn, type);
933
+ if (missingRet !== key) {
934
+ format = missingRet;
935
+ }
936
+ }
937
+ return [format, targetLocale, message];
938
+ }
939
+ function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
940
+ const { messageCompiler, warnHtmlMessage } = context;
941
+ if (isMessageFunction(format)) {
942
+ const msg = format;
943
+ msg.locale = msg.locale || targetLocale;
944
+ msg.key = msg.key || key;
945
+ return msg;
946
+ }
947
+ if (messageCompiler == null) {
948
+ const msg = (() => format);
949
+ msg.locale = targetLocale;
950
+ msg.key = key;
951
+ return msg;
952
+ }
953
+ const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
954
+ msg.locale = targetLocale;
955
+ msg.key = key;
956
+ msg.source = format;
957
+ return msg;
958
+ }
959
+ function evaluateMessage(context, msg, msgCtx) {
960
+ const messaged = msg(msgCtx);
961
+ return messaged;
962
+ }
963
+ /** @internal */
964
+ function parseTranslateArgs(...args) {
965
+ const [arg1, arg2, arg3] = args;
966
+ const options = {};
967
+ if (!shared.isString(arg1) && !shared.isNumber(arg1) && !isMessageFunction(arg1)) {
968
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
969
+ }
970
+ // prettier-ignore
971
+ const key = shared.isNumber(arg1)
972
+ ? String(arg1)
973
+ : isMessageFunction(arg1)
974
+ ? arg1
975
+ : arg1;
976
+ if (shared.isNumber(arg2)) {
977
+ options.plural = arg2;
978
+ }
979
+ else if (shared.isString(arg2)) {
980
+ options.default = arg2;
981
+ }
982
+ else if (shared.isPlainObject(arg2) && !shared.isEmptyObject(arg2)) {
983
+ options.named = arg2;
984
+ }
985
+ else if (shared.isArray(arg2)) {
986
+ options.list = arg2;
987
+ }
988
+ if (shared.isNumber(arg3)) {
989
+ options.plural = arg3;
990
+ }
991
+ else if (shared.isString(arg3)) {
992
+ options.default = arg3;
993
+ }
994
+ else if (shared.isPlainObject(arg3)) {
995
+ shared.assign(options, arg3);
996
+ }
997
+ return [key, options];
998
+ }
999
+ function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
1000
+ return {
1001
+ warnHtmlMessage,
1002
+ onError: (err) => {
1003
+ errorDetector && errorDetector(err);
1004
+ {
1005
+ throw err;
1006
+ }
1007
+ },
1008
+ onCacheKey: (source) => shared.generateFormatCacheKey(locale, key, source)
1009
+ };
1010
+ }
1011
+ function getMessageContextOptions(context, locale, message, options) {
1012
+ const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
1013
+ const resolveMessage = (key) => {
1014
+ let val = resolveValue(message, key);
1015
+ // fallback to root context
1016
+ if (val == null && fallbackContext) {
1017
+ const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
1018
+ val = resolveValue(message, key);
1019
+ }
1020
+ if (shared.isString(val)) {
1021
+ let occurred = false;
1022
+ const errorDetector = () => {
1023
+ occurred = true;
1024
+ };
1025
+ const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
1026
+ return !occurred
1027
+ ? msg
1028
+ : NOOP_MESSAGE_FUNCTION;
1029
+ }
1030
+ else if (isMessageFunction(val)) {
1031
+ return val;
1032
+ }
1033
+ else {
1034
+ // TODO: should be implemented warning message
1035
+ return NOOP_MESSAGE_FUNCTION;
1036
+ }
1037
+ };
1038
+ const ctxOptions = {
1039
+ locale,
1040
+ modifiers,
1041
+ pluralRules,
1042
+ messages: resolveMessage
1043
+ };
1044
+ if (context.processor) {
1045
+ ctxOptions.processor = context.processor;
1046
+ }
1047
+ if (options.list) {
1048
+ ctxOptions.list = options.list;
1049
+ }
1050
+ if (options.named) {
1051
+ ctxOptions.named = options.named;
1052
+ }
1053
+ if (shared.isNumber(options.plural)) {
1054
+ ctxOptions.pluralIndex = options.plural;
1055
+ }
1056
+ return ctxOptions;
1057
1057
  }
1058
1058
 
1059
- // implementation of `datetime` function
1060
- function datetime(context, ...args) {
1061
- const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1062
- const { __datetimeFormatters } = context;
1063
- const [key, value, options, overrides] = parseDateTimeArgs(...args);
1064
- const missingWarn = shared.isBoolean(options.missingWarn)
1065
- ? options.missingWarn
1066
- : context.missingWarn;
1067
- shared.isBoolean(options.fallbackWarn)
1068
- ? options.fallbackWarn
1069
- : context.fallbackWarn;
1070
- const part = !!options.part;
1071
- const locale = shared.isString(options.locale) ? options.locale : context.locale;
1072
- const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1073
- fallbackLocale, locale);
1074
- if (!shared.isString(key) || key === '') {
1075
- return new Intl.DateTimeFormat(locale, overrides).format(value);
1076
- }
1077
- // resolve format
1078
- let datetimeFormat = {};
1079
- let targetLocale;
1080
- let format = null;
1081
- const type = 'datetime format';
1082
- for (let i = 0; i < locales.length; i++) {
1083
- targetLocale = locales[i];
1084
- datetimeFormat =
1085
- datetimeFormats[targetLocale] || {};
1086
- format = datetimeFormat[key];
1087
- if (shared.isPlainObject(format))
1088
- break;
1089
- handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1090
- }
1091
- // checking format and target locale
1092
- if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
1093
- return unresolving ? NOT_REOSLVED : key;
1094
- }
1095
- let id = `${targetLocale}__${key}`;
1096
- if (!shared.isEmptyObject(overrides)) {
1097
- id = `${id}__${JSON.stringify(overrides)}`;
1098
- }
1099
- let formatter = __datetimeFormatters.get(id);
1100
- if (!formatter) {
1101
- formatter = new Intl.DateTimeFormat(targetLocale, shared.assign({}, format, overrides));
1102
- __datetimeFormatters.set(id, formatter);
1103
- }
1104
- return !part ? formatter.format(value) : formatter.formatToParts(value);
1105
- }
1106
- /** @internal */
1107
- const DATETIME_FORMAT_OPTIONS_KEYS = [
1108
- 'localeMatcher',
1109
- 'weekday',
1110
- 'era',
1111
- 'year',
1112
- 'month',
1113
- 'day',
1114
- 'hour',
1115
- 'minute',
1116
- 'second',
1117
- 'timeZoneName',
1118
- 'formatMatcher',
1119
- 'hour12',
1120
- 'timeZone',
1121
- 'dateStyle',
1122
- 'timeStyle',
1123
- 'calendar',
1124
- 'dayPeriod',
1125
- 'numberingSystem',
1126
- 'hourCycle',
1127
- 'fractionalSecondDigits'
1128
- ];
1129
- /** @internal */
1130
- function parseDateTimeArgs(...args) {
1131
- const [arg1, arg2, arg3, arg4] = args;
1132
- const options = {};
1133
- let overrides = {};
1134
- let value;
1135
- if (shared.isString(arg1)) {
1136
- // Only allow ISO strings - other date formats are often supported,
1137
- // but may cause different results in different browsers.
1138
- const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
1139
- if (!matches) {
1140
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1141
- }
1142
- // Some browsers can not parse the iso datetime separated by space,
1143
- // this is a compromise solution by replace the 'T'/' ' with 'T'
1144
- const dateTime = matches[3]
1145
- ? matches[3].trim().startsWith('T')
1146
- ? `${matches[1].trim()}${matches[3].trim()}`
1147
- : `${matches[1].trim()}T${matches[3].trim()}`
1148
- : matches[1].trim();
1149
- value = new Date(dateTime);
1150
- try {
1151
- // This will fail if the date is not valid
1152
- value.toISOString();
1153
- }
1154
- catch (e) {
1155
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1156
- }
1157
- }
1158
- else if (shared.isDate(arg1)) {
1159
- if (isNaN(arg1.getTime())) {
1160
- throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
1161
- }
1162
- value = arg1;
1163
- }
1164
- else if (shared.isNumber(arg1)) {
1165
- value = arg1;
1166
- }
1167
- else {
1168
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1169
- }
1170
- if (shared.isString(arg2)) {
1171
- options.key = arg2;
1172
- }
1173
- else if (shared.isPlainObject(arg2)) {
1174
- Object.keys(arg2).forEach(key => {
1175
- if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
1176
- overrides[key] = arg2[key];
1177
- }
1178
- else {
1179
- options[key] = arg2[key];
1180
- }
1181
- });
1182
- }
1183
- if (shared.isString(arg3)) {
1184
- options.locale = arg3;
1185
- }
1186
- else if (shared.isPlainObject(arg3)) {
1187
- overrides = arg3;
1188
- }
1189
- if (shared.isPlainObject(arg4)) {
1190
- overrides = arg4;
1191
- }
1192
- return [options.key || '', value, options, overrides];
1193
- }
1194
- /** @internal */
1195
- function clearDateTimeFormat(ctx, locale, format) {
1196
- const context = ctx;
1197
- for (const key in format) {
1198
- const id = `${locale}__${key}`;
1199
- if (!context.__datetimeFormatters.has(id)) {
1200
- continue;
1201
- }
1202
- context.__datetimeFormatters.delete(id);
1203
- }
1059
+ // implementation of `datetime` function
1060
+ function datetime(context, ...args) {
1061
+ const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1062
+ const { __datetimeFormatters } = context;
1063
+ const [key, value, options, overrides] = parseDateTimeArgs(...args);
1064
+ const missingWarn = shared.isBoolean(options.missingWarn)
1065
+ ? options.missingWarn
1066
+ : context.missingWarn;
1067
+ shared.isBoolean(options.fallbackWarn)
1068
+ ? options.fallbackWarn
1069
+ : context.fallbackWarn;
1070
+ const part = !!options.part;
1071
+ const locale = shared.isString(options.locale) ? options.locale : context.locale;
1072
+ const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1073
+ fallbackLocale, locale);
1074
+ if (!shared.isString(key) || key === '') {
1075
+ return new Intl.DateTimeFormat(locale, overrides).format(value);
1076
+ }
1077
+ // resolve format
1078
+ let datetimeFormat = {};
1079
+ let targetLocale;
1080
+ let format = null;
1081
+ const type = 'datetime format';
1082
+ for (let i = 0; i < locales.length; i++) {
1083
+ targetLocale = locales[i];
1084
+ datetimeFormat =
1085
+ datetimeFormats[targetLocale] || {};
1086
+ format = datetimeFormat[key];
1087
+ if (shared.isPlainObject(format))
1088
+ break;
1089
+ handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1090
+ }
1091
+ // checking format and target locale
1092
+ if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
1093
+ return unresolving ? NOT_REOSLVED : key;
1094
+ }
1095
+ let id = `${targetLocale}__${key}`;
1096
+ if (!shared.isEmptyObject(overrides)) {
1097
+ id = `${id}__${JSON.stringify(overrides)}`;
1098
+ }
1099
+ let formatter = __datetimeFormatters.get(id);
1100
+ if (!formatter) {
1101
+ formatter = new Intl.DateTimeFormat(targetLocale, shared.assign({}, format, overrides));
1102
+ __datetimeFormatters.set(id, formatter);
1103
+ }
1104
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
1105
+ }
1106
+ /** @internal */
1107
+ const DATETIME_FORMAT_OPTIONS_KEYS = [
1108
+ 'localeMatcher',
1109
+ 'weekday',
1110
+ 'era',
1111
+ 'year',
1112
+ 'month',
1113
+ 'day',
1114
+ 'hour',
1115
+ 'minute',
1116
+ 'second',
1117
+ 'timeZoneName',
1118
+ 'formatMatcher',
1119
+ 'hour12',
1120
+ 'timeZone',
1121
+ 'dateStyle',
1122
+ 'timeStyle',
1123
+ 'calendar',
1124
+ 'dayPeriod',
1125
+ 'numberingSystem',
1126
+ 'hourCycle',
1127
+ 'fractionalSecondDigits'
1128
+ ];
1129
+ /** @internal */
1130
+ function parseDateTimeArgs(...args) {
1131
+ const [arg1, arg2, arg3, arg4] = args;
1132
+ const options = {};
1133
+ let overrides = {};
1134
+ let value;
1135
+ if (shared.isString(arg1)) {
1136
+ // Only allow ISO strings - other date formats are often supported,
1137
+ // but may cause different results in different browsers.
1138
+ const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
1139
+ if (!matches) {
1140
+ throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1141
+ }
1142
+ // Some browsers can not parse the iso datetime separated by space,
1143
+ // this is a compromise solution by replace the 'T'/' ' with 'T'
1144
+ const dateTime = matches[3]
1145
+ ? matches[3].trim().startsWith('T')
1146
+ ? `${matches[1].trim()}${matches[3].trim()}`
1147
+ : `${matches[1].trim()}T${matches[3].trim()}`
1148
+ : matches[1].trim();
1149
+ value = new Date(dateTime);
1150
+ try {
1151
+ // This will fail if the date is not valid
1152
+ value.toISOString();
1153
+ }
1154
+ catch (e) {
1155
+ throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1156
+ }
1157
+ }
1158
+ else if (shared.isDate(arg1)) {
1159
+ if (isNaN(arg1.getTime())) {
1160
+ throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
1161
+ }
1162
+ value = arg1;
1163
+ }
1164
+ else if (shared.isNumber(arg1)) {
1165
+ value = arg1;
1166
+ }
1167
+ else {
1168
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1169
+ }
1170
+ if (shared.isString(arg2)) {
1171
+ options.key = arg2;
1172
+ }
1173
+ else if (shared.isPlainObject(arg2)) {
1174
+ Object.keys(arg2).forEach(key => {
1175
+ if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
1176
+ overrides[key] = arg2[key];
1177
+ }
1178
+ else {
1179
+ options[key] = arg2[key];
1180
+ }
1181
+ });
1182
+ }
1183
+ if (shared.isString(arg3)) {
1184
+ options.locale = arg3;
1185
+ }
1186
+ else if (shared.isPlainObject(arg3)) {
1187
+ overrides = arg3;
1188
+ }
1189
+ if (shared.isPlainObject(arg4)) {
1190
+ overrides = arg4;
1191
+ }
1192
+ return [options.key || '', value, options, overrides];
1193
+ }
1194
+ /** @internal */
1195
+ function clearDateTimeFormat(ctx, locale, format) {
1196
+ const context = ctx;
1197
+ for (const key in format) {
1198
+ const id = `${locale}__${key}`;
1199
+ if (!context.__datetimeFormatters.has(id)) {
1200
+ continue;
1201
+ }
1202
+ context.__datetimeFormatters.delete(id);
1203
+ }
1204
1204
  }
1205
1205
 
1206
- // implementation of `number` function
1207
- function number(context, ...args) {
1208
- const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1209
- const { __numberFormatters } = context;
1210
- const [key, value, options, overrides] = parseNumberArgs(...args);
1211
- const missingWarn = shared.isBoolean(options.missingWarn)
1212
- ? options.missingWarn
1213
- : context.missingWarn;
1214
- shared.isBoolean(options.fallbackWarn)
1215
- ? options.fallbackWarn
1216
- : context.fallbackWarn;
1217
- const part = !!options.part;
1218
- const locale = shared.isString(options.locale) ? options.locale : context.locale;
1219
- const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1220
- fallbackLocale, locale);
1221
- if (!shared.isString(key) || key === '') {
1222
- return new Intl.NumberFormat(locale, overrides).format(value);
1223
- }
1224
- // resolve format
1225
- let numberFormat = {};
1226
- let targetLocale;
1227
- let format = null;
1228
- const type = 'number format';
1229
- for (let i = 0; i < locales.length; i++) {
1230
- targetLocale = locales[i];
1231
- numberFormat =
1232
- numberFormats[targetLocale] || {};
1233
- format = numberFormat[key];
1234
- if (shared.isPlainObject(format))
1235
- break;
1236
- handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1237
- }
1238
- // checking format and target locale
1239
- if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
1240
- return unresolving ? NOT_REOSLVED : key;
1241
- }
1242
- let id = `${targetLocale}__${key}`;
1243
- if (!shared.isEmptyObject(overrides)) {
1244
- id = `${id}__${JSON.stringify(overrides)}`;
1245
- }
1246
- let formatter = __numberFormatters.get(id);
1247
- if (!formatter) {
1248
- formatter = new Intl.NumberFormat(targetLocale, shared.assign({}, format, overrides));
1249
- __numberFormatters.set(id, formatter);
1250
- }
1251
- return !part ? formatter.format(value) : formatter.formatToParts(value);
1252
- }
1253
- /** @internal */
1254
- const NUMBER_FORMAT_OPTIONS_KEYS = [
1255
- 'localeMatcher',
1256
- 'style',
1257
- 'currency',
1258
- 'currencyDisplay',
1259
- 'currencySign',
1260
- 'useGrouping',
1261
- 'minimumIntegerDigits',
1262
- 'minimumFractionDigits',
1263
- 'maximumFractionDigits',
1264
- 'minimumSignificantDigits',
1265
- 'maximumSignificantDigits',
1266
- 'compactDisplay',
1267
- 'notation',
1268
- 'signDisplay',
1269
- 'unit',
1270
- 'unitDisplay',
1271
- 'roundingMode',
1272
- 'roundingPriority',
1273
- 'roundingIncrement',
1274
- 'trailingZeroDisplay'
1275
- ];
1276
- /** @internal */
1277
- function parseNumberArgs(...args) {
1278
- const [arg1, arg2, arg3, arg4] = args;
1279
- const options = {};
1280
- let overrides = {};
1281
- if (!shared.isNumber(arg1)) {
1282
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1283
- }
1284
- const value = arg1;
1285
- if (shared.isString(arg2)) {
1286
- options.key = arg2;
1287
- }
1288
- else if (shared.isPlainObject(arg2)) {
1289
- Object.keys(arg2).forEach(key => {
1290
- if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
1291
- overrides[key] = arg2[key];
1292
- }
1293
- else {
1294
- options[key] = arg2[key];
1295
- }
1296
- });
1297
- }
1298
- if (shared.isString(arg3)) {
1299
- options.locale = arg3;
1300
- }
1301
- else if (shared.isPlainObject(arg3)) {
1302
- overrides = arg3;
1303
- }
1304
- if (shared.isPlainObject(arg4)) {
1305
- overrides = arg4;
1306
- }
1307
- return [options.key || '', value, options, overrides];
1308
- }
1309
- /** @internal */
1310
- function clearNumberFormat(ctx, locale, format) {
1311
- const context = ctx;
1312
- for (const key in format) {
1313
- const id = `${locale}__${key}`;
1314
- if (!context.__numberFormatters.has(id)) {
1315
- continue;
1316
- }
1317
- context.__numberFormatters.delete(id);
1318
- }
1206
+ // implementation of `number` function
1207
+ function number(context, ...args) {
1208
+ const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1209
+ const { __numberFormatters } = context;
1210
+ const [key, value, options, overrides] = parseNumberArgs(...args);
1211
+ const missingWarn = shared.isBoolean(options.missingWarn)
1212
+ ? options.missingWarn
1213
+ : context.missingWarn;
1214
+ shared.isBoolean(options.fallbackWarn)
1215
+ ? options.fallbackWarn
1216
+ : context.fallbackWarn;
1217
+ const part = !!options.part;
1218
+ const locale = shared.isString(options.locale) ? options.locale : context.locale;
1219
+ const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1220
+ fallbackLocale, locale);
1221
+ if (!shared.isString(key) || key === '') {
1222
+ return new Intl.NumberFormat(locale, overrides).format(value);
1223
+ }
1224
+ // resolve format
1225
+ let numberFormat = {};
1226
+ let targetLocale;
1227
+ let format = null;
1228
+ const type = 'number format';
1229
+ for (let i = 0; i < locales.length; i++) {
1230
+ targetLocale = locales[i];
1231
+ numberFormat =
1232
+ numberFormats[targetLocale] || {};
1233
+ format = numberFormat[key];
1234
+ if (shared.isPlainObject(format))
1235
+ break;
1236
+ handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1237
+ }
1238
+ // checking format and target locale
1239
+ if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
1240
+ return unresolving ? NOT_REOSLVED : key;
1241
+ }
1242
+ let id = `${targetLocale}__${key}`;
1243
+ if (!shared.isEmptyObject(overrides)) {
1244
+ id = `${id}__${JSON.stringify(overrides)}`;
1245
+ }
1246
+ let formatter = __numberFormatters.get(id);
1247
+ if (!formatter) {
1248
+ formatter = new Intl.NumberFormat(targetLocale, shared.assign({}, format, overrides));
1249
+ __numberFormatters.set(id, formatter);
1250
+ }
1251
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
1252
+ }
1253
+ /** @internal */
1254
+ const NUMBER_FORMAT_OPTIONS_KEYS = [
1255
+ 'localeMatcher',
1256
+ 'style',
1257
+ 'currency',
1258
+ 'currencyDisplay',
1259
+ 'currencySign',
1260
+ 'useGrouping',
1261
+ 'minimumIntegerDigits',
1262
+ 'minimumFractionDigits',
1263
+ 'maximumFractionDigits',
1264
+ 'minimumSignificantDigits',
1265
+ 'maximumSignificantDigits',
1266
+ 'compactDisplay',
1267
+ 'notation',
1268
+ 'signDisplay',
1269
+ 'unit',
1270
+ 'unitDisplay',
1271
+ 'roundingMode',
1272
+ 'roundingPriority',
1273
+ 'roundingIncrement',
1274
+ 'trailingZeroDisplay'
1275
+ ];
1276
+ /** @internal */
1277
+ function parseNumberArgs(...args) {
1278
+ const [arg1, arg2, arg3, arg4] = args;
1279
+ const options = {};
1280
+ let overrides = {};
1281
+ if (!shared.isNumber(arg1)) {
1282
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1283
+ }
1284
+ const value = arg1;
1285
+ if (shared.isString(arg2)) {
1286
+ options.key = arg2;
1287
+ }
1288
+ else if (shared.isPlainObject(arg2)) {
1289
+ Object.keys(arg2).forEach(key => {
1290
+ if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
1291
+ overrides[key] = arg2[key];
1292
+ }
1293
+ else {
1294
+ options[key] = arg2[key];
1295
+ }
1296
+ });
1297
+ }
1298
+ if (shared.isString(arg3)) {
1299
+ options.locale = arg3;
1300
+ }
1301
+ else if (shared.isPlainObject(arg3)) {
1302
+ overrides = arg3;
1303
+ }
1304
+ if (shared.isPlainObject(arg4)) {
1305
+ overrides = arg4;
1306
+ }
1307
+ return [options.key || '', value, options, overrides];
1308
+ }
1309
+ /** @internal */
1310
+ function clearNumberFormat(ctx, locale, format) {
1311
+ const context = ctx;
1312
+ for (const key in format) {
1313
+ const id = `${locale}__${key}`;
1314
+ if (!context.__numberFormatters.has(id)) {
1315
+ continue;
1316
+ }
1317
+ context.__numberFormatters.delete(id);
1318
+ }
1319
1319
  }
1320
1320
 
1321
1321
  exports.CompileErrorCodes = messageCompiler.CompileErrorCodes;