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

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