@intlify/core 9.3.0-beta.2 → 9.3.0-beta.21

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,1709 +1,3219 @@
1
1
  /*!
2
- * core v9.3.0-beta.2
3
- * (c) 2022 kazuya kawaguchi
2
+ * core v9.3.0-beta.21
3
+ * (c) 2023 kazuya kawaguchi
4
4
  * Released under the MIT License.
5
5
  */
6
6
  var IntlifyCore = (function (exports) {
7
7
  'use strict';
8
8
 
9
- /**
10
- * Original Utilities
11
- * written by kazuya kawaguchi
12
- */
13
- const inBrowser = typeof window !== 'undefined';
14
- let mark;
15
- let measure;
16
- {
17
- const perf = inBrowser && window.performance;
18
- if (perf &&
19
- perf.mark &&
20
- perf.measure &&
21
- perf.clearMarks &&
22
- perf.clearMeasures) {
23
- mark = (tag) => perf.mark(tag);
24
- measure = (name, startTag, endTag) => {
25
- perf.measure(name, startTag, endTag);
26
- perf.clearMarks(startTag);
27
- perf.clearMarks(endTag);
28
- };
29
- }
30
- }
31
- const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
32
- /* eslint-disable */
33
- function format(message, ...args) {
34
- if (args.length === 1 && isObject(args[0])) {
35
- args = args[0];
36
- }
37
- if (!args || !args.hasOwnProperty) {
38
- args = {};
39
- }
40
- return message.replace(RE_ARGS, (match, identifier) => {
41
- return args.hasOwnProperty(identifier) ? args[identifier] : '';
42
- });
43
- }
44
- const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
45
- const friendlyJSONstringify = (json) => JSON.stringify(json)
46
- .replace(/\u2028/g, '\\u2028')
47
- .replace(/\u2029/g, '\\u2029')
48
- .replace(/\u0027/g, '\\u0027');
49
- const isNumber = (val) => typeof val === 'number' && isFinite(val);
50
- const isDate = (val) => toTypeString(val) === '[object Date]';
51
- const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
52
- const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
53
- function warn(msg, err) {
54
- if (typeof console !== 'undefined') {
55
- console.warn(`[intlify] ` + msg);
56
- /* istanbul ignore if */
57
- if (err) {
58
- console.warn(err.stack);
59
- }
60
- }
61
- }
62
- const assign = Object.assign;
63
- function escapeHtml(rawText) {
64
- return rawText
65
- .replace(/</g, '&lt;')
66
- .replace(/>/g, '&gt;')
67
- .replace(/"/g, '&quot;')
68
- .replace(/'/g, '&apos;');
69
- }
70
- /* eslint-enable */
71
- /**
72
- * Useful Utilities By Evan you
73
- * Modified by kazuya kawaguchi
74
- * MIT License
75
- * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
76
- * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
77
- */
78
- const isArray = Array.isArray;
79
- const isFunction = (val) => typeof val === 'function';
80
- const isString = (val) => typeof val === 'string';
81
- const isBoolean = (val) => typeof val === 'boolean';
82
- const isObject = (val) => // eslint-disable-line
83
- val !== null && typeof val === 'object';
84
- const objectToString = Object.prototype.toString;
85
- const toTypeString = (value) => objectToString.call(value);
86
- const isPlainObject = (val) => toTypeString(val) === '[object Object]';
87
- // for converting list and named values to displayed strings.
88
- const toDisplayString = (val) => {
89
- return val == null
90
- ? ''
91
- : isArray(val) || (isPlainObject(val) && val.toString === objectToString)
92
- ? JSON.stringify(val, null, 2)
93
- : String(val);
94
- };
95
- const RANGE = 2;
96
- function generateCodeFrame(source, start = 0, end = source.length) {
97
- const lines = source.split(/\r?\n/);
98
- let count = 0;
99
- const res = [];
100
- for (let i = 0; i < lines.length; i++) {
101
- count += lines[i].length + 1;
102
- if (count >= start) {
103
- for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
104
- if (j < 0 || j >= lines.length)
105
- continue;
106
- const line = j + 1;
107
- res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
108
- const lineLength = lines[j].length;
109
- if (j === i) {
110
- // push underline
111
- const pad = start - (count - lineLength) + 1;
112
- const length = Math.max(1, end > count ? lineLength - pad : end - start);
113
- res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
114
- }
115
- else if (j > i) {
116
- if (end > count) {
117
- const length = Math.max(Math.min(end - count, lineLength), 1);
118
- res.push(` | ` + '^'.repeat(length));
119
- }
120
- count += lineLength + 1;
121
- }
122
- }
123
- break;
124
- }
125
- }
126
- return res.join('\n');
9
+ /**
10
+ * Original Utilities
11
+ * written by kazuya kawaguchi
12
+ */
13
+ const inBrowser = typeof window !== 'undefined';
14
+ let mark;
15
+ let measure;
16
+ {
17
+ const perf = inBrowser && window.performance;
18
+ if (perf &&
19
+ perf.mark &&
20
+ perf.measure &&
21
+ perf.clearMarks &&
22
+ // @ts-ignore browser compat
23
+ perf.clearMeasures) {
24
+ mark = (tag) => {
25
+ perf.mark(tag);
26
+ };
27
+ measure = (name, startTag, endTag) => {
28
+ perf.measure(name, startTag, endTag);
29
+ perf.clearMarks(startTag);
30
+ perf.clearMarks(endTag);
31
+ };
32
+ }
33
+ }
34
+ const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
35
+ /* eslint-disable */
36
+ function format$1(message, ...args) {
37
+ if (args.length === 1 && isObject(args[0])) {
38
+ args = args[0];
39
+ }
40
+ if (!args || !args.hasOwnProperty) {
41
+ args = {};
42
+ }
43
+ return message.replace(RE_ARGS, (match, identifier) => {
44
+ return args.hasOwnProperty(identifier) ? args[identifier] : '';
45
+ });
46
+ }
47
+ const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
48
+ const friendlyJSONstringify = (json) => JSON.stringify(json)
49
+ .replace(/\u2028/g, '\\u2028')
50
+ .replace(/\u2029/g, '\\u2029')
51
+ .replace(/\u0027/g, '\\u0027');
52
+ const isNumber = (val) => typeof val === 'number' && isFinite(val);
53
+ const isDate = (val) => toTypeString(val) === '[object Date]';
54
+ const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
55
+ const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
56
+ function warn(msg, err) {
57
+ if (typeof console !== 'undefined') {
58
+ console.warn(`[intlify] ` + msg);
59
+ /* istanbul ignore if */
60
+ if (err) {
61
+ console.warn(err.stack);
62
+ }
63
+ }
64
+ }
65
+ const assign = Object.assign;
66
+ function escapeHtml(rawText) {
67
+ return rawText
68
+ .replace(/</g, '&lt;')
69
+ .replace(/>/g, '&gt;')
70
+ .replace(/"/g, '&quot;')
71
+ .replace(/'/g, '&apos;');
72
+ }
73
+ /* eslint-enable */
74
+ /**
75
+ * Useful Utilities By Evan you
76
+ * Modified by kazuya kawaguchi
77
+ * MIT License
78
+ * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
79
+ * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
80
+ */
81
+ const isArray = Array.isArray;
82
+ const isFunction = (val) => typeof val === 'function';
83
+ const isString = (val) => typeof val === 'string';
84
+ const isBoolean = (val) => typeof val === 'boolean';
85
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
86
+ const isObject = (val) => val !== null && typeof val === 'object';
87
+ const objectToString = Object.prototype.toString;
88
+ const toTypeString = (value) => objectToString.call(value);
89
+ const isPlainObject = (val) => {
90
+ if (!isObject(val))
91
+ return false;
92
+ const proto = Object.getPrototypeOf(val);
93
+ return proto === null || proto.constructor === Object;
94
+ };
95
+ // for converting list and named values to displayed strings.
96
+ const toDisplayString = (val) => {
97
+ return val == null
98
+ ? ''
99
+ : isArray(val) || (isPlainObject(val) && val.toString === objectToString)
100
+ ? JSON.stringify(val, null, 2)
101
+ : String(val);
102
+ };
103
+ function join(items, separator = '') {
104
+ return items.reduce((str, item, index) => (index === 0 ? str + item : str + separator + item), '');
105
+ }
106
+ const RANGE = 2;
107
+ function generateCodeFrame(source, start = 0, end = source.length) {
108
+ const lines = source.split(/\r?\n/);
109
+ let count = 0;
110
+ const res = [];
111
+ for (let i = 0; i < lines.length; i++) {
112
+ count += lines[i].length + 1;
113
+ if (count >= start) {
114
+ for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
115
+ if (j < 0 || j >= lines.length)
116
+ continue;
117
+ const line = j + 1;
118
+ res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
119
+ const lineLength = lines[j].length;
120
+ if (j === i) {
121
+ // push underline
122
+ const pad = start - (count - lineLength) + 1;
123
+ const length = Math.max(1, end > count ? lineLength - pad : end - start);
124
+ res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
125
+ }
126
+ else if (j > i) {
127
+ if (end > count) {
128
+ const length = Math.max(Math.min(end - count, lineLength), 1);
129
+ res.push(` | ` + '^'.repeat(length));
130
+ }
131
+ count += lineLength + 1;
132
+ }
133
+ }
134
+ break;
135
+ }
136
+ }
137
+ return res.join('\n');
138
+ }
139
+
140
+ function createPosition(line, column, offset) {
141
+ return { line, column, offset };
142
+ }
143
+ function createLocation(start, end, source) {
144
+ const loc = { start, end };
145
+ if (source != null) {
146
+ loc.source = source;
147
+ }
148
+ return loc;
149
+ }
150
+
151
+ const CompileErrorCodes = {
152
+ // tokenizer error codes
153
+ EXPECTED_TOKEN: 1,
154
+ INVALID_TOKEN_IN_PLACEHOLDER: 2,
155
+ UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
156
+ UNKNOWN_ESCAPE_SEQUENCE: 4,
157
+ INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
158
+ UNBALANCED_CLOSING_BRACE: 6,
159
+ UNTERMINATED_CLOSING_BRACE: 7,
160
+ EMPTY_PLACEHOLDER: 8,
161
+ NOT_ALLOW_NEST_PLACEHOLDER: 9,
162
+ INVALID_LINKED_FORMAT: 10,
163
+ // parser error codes
164
+ MUST_HAVE_MESSAGES_IN_PLURAL: 11,
165
+ UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
166
+ UNEXPECTED_EMPTY_LINKED_KEY: 13,
167
+ UNEXPECTED_LEXICAL_ANALYSIS: 14,
168
+ // Special value for higher-order compilers to pick up the last code
169
+ // to avoid collision of error codes. This should always be kept as the last
170
+ // item.
171
+ __EXTEND_POINT__: 15
172
+ };
173
+ /** @internal */
174
+ const errorMessages$1 = {
175
+ // tokenizer error messages
176
+ [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
177
+ [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
178
+ [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
179
+ [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
180
+ [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
181
+ [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
182
+ [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
183
+ [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
184
+ [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
185
+ [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
186
+ // parser error messages
187
+ [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
188
+ [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
189
+ [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
190
+ [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`
191
+ };
192
+ function createCompileError(code, loc, options = {}) {
193
+ const { domain, messages, args } = options;
194
+ const msg = format$1((messages || errorMessages$1)[code] || '', ...(args || []))
195
+ ;
196
+ const error = new SyntaxError(String(msg));
197
+ error.code = code;
198
+ if (loc) {
199
+ error.location = loc;
200
+ }
201
+ error.domain = domain;
202
+ return error;
203
+ }
204
+ /** @internal */
205
+ function defaultOnError(error) {
206
+ throw error;
207
+ }
208
+
209
+ const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
210
+ const detectHtmlTag = (source) => RE_HTML_TAG.test(source);
211
+
212
+ const CHAR_SP = ' ';
213
+ const CHAR_CR = '\r';
214
+ const CHAR_LF = '\n';
215
+ const CHAR_LS = String.fromCharCode(0x2028);
216
+ const CHAR_PS = String.fromCharCode(0x2029);
217
+ function createScanner(str) {
218
+ const _buf = str;
219
+ let _index = 0;
220
+ let _line = 1;
221
+ let _column = 1;
222
+ let _peekOffset = 0;
223
+ const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
224
+ const isLF = (index) => _buf[index] === CHAR_LF;
225
+ const isPS = (index) => _buf[index] === CHAR_PS;
226
+ const isLS = (index) => _buf[index] === CHAR_LS;
227
+ const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
228
+ const index = () => _index;
229
+ const line = () => _line;
230
+ const column = () => _column;
231
+ const peekOffset = () => _peekOffset;
232
+ const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
233
+ const currentChar = () => charAt(_index);
234
+ const currentPeek = () => charAt(_index + _peekOffset);
235
+ function next() {
236
+ _peekOffset = 0;
237
+ if (isLineEnd(_index)) {
238
+ _line++;
239
+ _column = 0;
240
+ }
241
+ if (isCRLF(_index)) {
242
+ _index++;
243
+ }
244
+ _index++;
245
+ _column++;
246
+ return _buf[_index];
247
+ }
248
+ function peek() {
249
+ if (isCRLF(_index + _peekOffset)) {
250
+ _peekOffset++;
251
+ }
252
+ _peekOffset++;
253
+ return _buf[_index + _peekOffset];
254
+ }
255
+ function reset() {
256
+ _index = 0;
257
+ _line = 1;
258
+ _column = 1;
259
+ _peekOffset = 0;
260
+ }
261
+ function resetPeek(offset = 0) {
262
+ _peekOffset = offset;
263
+ }
264
+ function skipToPeek() {
265
+ const target = _index + _peekOffset;
266
+ // eslint-disable-next-line no-unmodified-loop-condition
267
+ while (target !== _index) {
268
+ next();
269
+ }
270
+ _peekOffset = 0;
271
+ }
272
+ return {
273
+ index,
274
+ line,
275
+ column,
276
+ peekOffset,
277
+ charAt,
278
+ currentChar,
279
+ currentPeek,
280
+ next,
281
+ peek,
282
+ reset,
283
+ resetPeek,
284
+ skipToPeek
285
+ };
286
+ }
287
+
288
+ const EOF = undefined;
289
+ const LITERAL_DELIMITER = "'";
290
+ const ERROR_DOMAIN$1 = 'tokenizer';
291
+ function createTokenizer(source, options = {}) {
292
+ const location = options.location !== false;
293
+ const _scnr = createScanner(source);
294
+ const currentOffset = () => _scnr.index();
295
+ const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
296
+ const _initLoc = currentPosition();
297
+ const _initOffset = currentOffset();
298
+ const _context = {
299
+ currentType: 14 /* TokenTypes.EOF */,
300
+ offset: _initOffset,
301
+ startLoc: _initLoc,
302
+ endLoc: _initLoc,
303
+ lastType: 14 /* TokenTypes.EOF */,
304
+ lastOffset: _initOffset,
305
+ lastStartLoc: _initLoc,
306
+ lastEndLoc: _initLoc,
307
+ braceNest: 0,
308
+ inLinked: false,
309
+ text: ''
310
+ };
311
+ const context = () => _context;
312
+ const { onError } = options;
313
+ function emitError(code, pos, offset, ...args) {
314
+ const ctx = context();
315
+ pos.column += offset;
316
+ pos.offset += offset;
317
+ if (onError) {
318
+ const loc = location ? createLocation(ctx.startLoc, pos) : null;
319
+ const err = createCompileError(code, loc, {
320
+ domain: ERROR_DOMAIN$1,
321
+ args
322
+ });
323
+ onError(err);
324
+ }
325
+ }
326
+ function getToken(context, type, value) {
327
+ context.endLoc = currentPosition();
328
+ context.currentType = type;
329
+ const token = { type };
330
+ if (location) {
331
+ token.loc = createLocation(context.startLoc, context.endLoc);
332
+ }
333
+ if (value != null) {
334
+ token.value = value;
335
+ }
336
+ return token;
337
+ }
338
+ const getEndToken = (context) => getToken(context, 14 /* TokenTypes.EOF */);
339
+ function eat(scnr, ch) {
340
+ if (scnr.currentChar() === ch) {
341
+ scnr.next();
342
+ return ch;
343
+ }
344
+ else {
345
+ emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
346
+ return '';
347
+ }
348
+ }
349
+ function peekSpaces(scnr) {
350
+ let buf = '';
351
+ while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
352
+ buf += scnr.currentPeek();
353
+ scnr.peek();
354
+ }
355
+ return buf;
356
+ }
357
+ function skipSpaces(scnr) {
358
+ const buf = peekSpaces(scnr);
359
+ scnr.skipToPeek();
360
+ return buf;
361
+ }
362
+ function isIdentifierStart(ch) {
363
+ if (ch === EOF) {
364
+ return false;
365
+ }
366
+ const cc = ch.charCodeAt(0);
367
+ return ((cc >= 97 && cc <= 122) || // a-z
368
+ (cc >= 65 && cc <= 90) || // A-Z
369
+ cc === 95 // _
370
+ );
371
+ }
372
+ function isNumberStart(ch) {
373
+ if (ch === EOF) {
374
+ return false;
375
+ }
376
+ const cc = ch.charCodeAt(0);
377
+ return cc >= 48 && cc <= 57; // 0-9
378
+ }
379
+ function isNamedIdentifierStart(scnr, context) {
380
+ const { currentType } = context;
381
+ if (currentType !== 2 /* TokenTypes.BraceLeft */) {
382
+ return false;
383
+ }
384
+ peekSpaces(scnr);
385
+ const ret = isIdentifierStart(scnr.currentPeek());
386
+ scnr.resetPeek();
387
+ return ret;
388
+ }
389
+ function isListIdentifierStart(scnr, context) {
390
+ const { currentType } = context;
391
+ if (currentType !== 2 /* TokenTypes.BraceLeft */) {
392
+ return false;
393
+ }
394
+ peekSpaces(scnr);
395
+ const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
396
+ const ret = isNumberStart(ch);
397
+ scnr.resetPeek();
398
+ return ret;
399
+ }
400
+ function isLiteralStart(scnr, context) {
401
+ const { currentType } = context;
402
+ if (currentType !== 2 /* TokenTypes.BraceLeft */) {
403
+ return false;
404
+ }
405
+ peekSpaces(scnr);
406
+ const ret = scnr.currentPeek() === LITERAL_DELIMITER;
407
+ scnr.resetPeek();
408
+ return ret;
409
+ }
410
+ function isLinkedDotStart(scnr, context) {
411
+ const { currentType } = context;
412
+ if (currentType !== 8 /* TokenTypes.LinkedAlias */) {
413
+ return false;
414
+ }
415
+ peekSpaces(scnr);
416
+ const ret = scnr.currentPeek() === "." /* TokenChars.LinkedDot */;
417
+ scnr.resetPeek();
418
+ return ret;
419
+ }
420
+ function isLinkedModifierStart(scnr, context) {
421
+ const { currentType } = context;
422
+ if (currentType !== 9 /* TokenTypes.LinkedDot */) {
423
+ return false;
424
+ }
425
+ peekSpaces(scnr);
426
+ const ret = isIdentifierStart(scnr.currentPeek());
427
+ scnr.resetPeek();
428
+ return ret;
429
+ }
430
+ function isLinkedDelimiterStart(scnr, context) {
431
+ const { currentType } = context;
432
+ if (!(currentType === 8 /* TokenTypes.LinkedAlias */ ||
433
+ currentType === 12 /* TokenTypes.LinkedModifier */)) {
434
+ return false;
435
+ }
436
+ peekSpaces(scnr);
437
+ const ret = scnr.currentPeek() === ":" /* TokenChars.LinkedDelimiter */;
438
+ scnr.resetPeek();
439
+ return ret;
440
+ }
441
+ function isLinkedReferStart(scnr, context) {
442
+ const { currentType } = context;
443
+ if (currentType !== 10 /* TokenTypes.LinkedDelimiter */) {
444
+ return false;
445
+ }
446
+ const fn = () => {
447
+ const ch = scnr.currentPeek();
448
+ if (ch === "{" /* TokenChars.BraceLeft */) {
449
+ return isIdentifierStart(scnr.peek());
450
+ }
451
+ else if (ch === "@" /* TokenChars.LinkedAlias */ ||
452
+ ch === "%" /* TokenChars.Modulo */ ||
453
+ ch === "|" /* TokenChars.Pipe */ ||
454
+ ch === ":" /* TokenChars.LinkedDelimiter */ ||
455
+ ch === "." /* TokenChars.LinkedDot */ ||
456
+ ch === CHAR_SP ||
457
+ !ch) {
458
+ return false;
459
+ }
460
+ else if (ch === CHAR_LF) {
461
+ scnr.peek();
462
+ return fn();
463
+ }
464
+ else {
465
+ // other characters
466
+ return isIdentifierStart(ch);
467
+ }
468
+ };
469
+ const ret = fn();
470
+ scnr.resetPeek();
471
+ return ret;
472
+ }
473
+ function isPluralStart(scnr) {
474
+ peekSpaces(scnr);
475
+ const ret = scnr.currentPeek() === "|" /* TokenChars.Pipe */;
476
+ scnr.resetPeek();
477
+ return ret;
478
+ }
479
+ function detectModuloStart(scnr) {
480
+ const spaces = peekSpaces(scnr);
481
+ const ret = scnr.currentPeek() === "%" /* TokenChars.Modulo */ &&
482
+ scnr.peek() === "{" /* TokenChars.BraceLeft */;
483
+ scnr.resetPeek();
484
+ return {
485
+ isModulo: ret,
486
+ hasSpace: spaces.length > 0
487
+ };
488
+ }
489
+ function isTextStart(scnr, reset = true) {
490
+ const fn = (hasSpace = false, prev = '', detectModulo = false) => {
491
+ const ch = scnr.currentPeek();
492
+ if (ch === "{" /* TokenChars.BraceLeft */) {
493
+ return prev === "%" /* TokenChars.Modulo */ ? false : hasSpace;
494
+ }
495
+ else if (ch === "@" /* TokenChars.LinkedAlias */ || !ch) {
496
+ return prev === "%" /* TokenChars.Modulo */ ? true : hasSpace;
497
+ }
498
+ else if (ch === "%" /* TokenChars.Modulo */) {
499
+ scnr.peek();
500
+ return fn(hasSpace, "%" /* TokenChars.Modulo */, true);
501
+ }
502
+ else if (ch === "|" /* TokenChars.Pipe */) {
503
+ return prev === "%" /* TokenChars.Modulo */ || detectModulo
504
+ ? true
505
+ : !(prev === CHAR_SP || prev === CHAR_LF);
506
+ }
507
+ else if (ch === CHAR_SP) {
508
+ scnr.peek();
509
+ return fn(true, CHAR_SP, detectModulo);
510
+ }
511
+ else if (ch === CHAR_LF) {
512
+ scnr.peek();
513
+ return fn(true, CHAR_LF, detectModulo);
514
+ }
515
+ else {
516
+ return true;
517
+ }
518
+ };
519
+ const ret = fn();
520
+ reset && scnr.resetPeek();
521
+ return ret;
522
+ }
523
+ function takeChar(scnr, fn) {
524
+ const ch = scnr.currentChar();
525
+ if (ch === EOF) {
526
+ return EOF;
527
+ }
528
+ if (fn(ch)) {
529
+ scnr.next();
530
+ return ch;
531
+ }
532
+ return null;
533
+ }
534
+ function takeIdentifierChar(scnr) {
535
+ const closure = (ch) => {
536
+ const cc = ch.charCodeAt(0);
537
+ return ((cc >= 97 && cc <= 122) || // a-z
538
+ (cc >= 65 && cc <= 90) || // A-Z
539
+ (cc >= 48 && cc <= 57) || // 0-9
540
+ cc === 95 || // _
541
+ cc === 36 // $
542
+ );
543
+ };
544
+ return takeChar(scnr, closure);
545
+ }
546
+ function takeDigit(scnr) {
547
+ const closure = (ch) => {
548
+ const cc = ch.charCodeAt(0);
549
+ return cc >= 48 && cc <= 57; // 0-9
550
+ };
551
+ return takeChar(scnr, closure);
552
+ }
553
+ function takeHexDigit(scnr) {
554
+ const closure = (ch) => {
555
+ const cc = ch.charCodeAt(0);
556
+ return ((cc >= 48 && cc <= 57) || // 0-9
557
+ (cc >= 65 && cc <= 70) || // A-F
558
+ (cc >= 97 && cc <= 102)); // a-f
559
+ };
560
+ return takeChar(scnr, closure);
561
+ }
562
+ function getDigits(scnr) {
563
+ let ch = '';
564
+ let num = '';
565
+ while ((ch = takeDigit(scnr))) {
566
+ num += ch;
567
+ }
568
+ return num;
569
+ }
570
+ function readModulo(scnr) {
571
+ skipSpaces(scnr);
572
+ const ch = scnr.currentChar();
573
+ if (ch !== "%" /* TokenChars.Modulo */) {
574
+ emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
575
+ }
576
+ scnr.next();
577
+ return "%" /* TokenChars.Modulo */;
578
+ }
579
+ function readText(scnr) {
580
+ let buf = '';
581
+ while (true) {
582
+ const ch = scnr.currentChar();
583
+ if (ch === "{" /* TokenChars.BraceLeft */ ||
584
+ ch === "}" /* TokenChars.BraceRight */ ||
585
+ ch === "@" /* TokenChars.LinkedAlias */ ||
586
+ ch === "|" /* TokenChars.Pipe */ ||
587
+ !ch) {
588
+ break;
589
+ }
590
+ else if (ch === "%" /* TokenChars.Modulo */) {
591
+ if (isTextStart(scnr)) {
592
+ buf += ch;
593
+ scnr.next();
594
+ }
595
+ else {
596
+ break;
597
+ }
598
+ }
599
+ else if (ch === CHAR_SP || ch === CHAR_LF) {
600
+ if (isTextStart(scnr)) {
601
+ buf += ch;
602
+ scnr.next();
603
+ }
604
+ else if (isPluralStart(scnr)) {
605
+ break;
606
+ }
607
+ else {
608
+ buf += ch;
609
+ scnr.next();
610
+ }
611
+ }
612
+ else {
613
+ buf += ch;
614
+ scnr.next();
615
+ }
616
+ }
617
+ return buf;
618
+ }
619
+ function readNamedIdentifier(scnr) {
620
+ skipSpaces(scnr);
621
+ let ch = '';
622
+ let name = '';
623
+ while ((ch = takeIdentifierChar(scnr))) {
624
+ name += ch;
625
+ }
626
+ if (scnr.currentChar() === EOF) {
627
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
628
+ }
629
+ return name;
630
+ }
631
+ function readListIdentifier(scnr) {
632
+ skipSpaces(scnr);
633
+ let value = '';
634
+ if (scnr.currentChar() === '-') {
635
+ scnr.next();
636
+ value += `-${getDigits(scnr)}`;
637
+ }
638
+ else {
639
+ value += getDigits(scnr);
640
+ }
641
+ if (scnr.currentChar() === EOF) {
642
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
643
+ }
644
+ return value;
645
+ }
646
+ function readLiteral(scnr) {
647
+ skipSpaces(scnr);
648
+ eat(scnr, `\'`);
649
+ let ch = '';
650
+ let literal = '';
651
+ const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF;
652
+ while ((ch = takeChar(scnr, fn))) {
653
+ if (ch === '\\') {
654
+ literal += readEscapeSequence(scnr);
655
+ }
656
+ else {
657
+ literal += ch;
658
+ }
659
+ }
660
+ const current = scnr.currentChar();
661
+ if (current === CHAR_LF || current === EOF) {
662
+ emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
663
+ // TODO: Is it correct really?
664
+ if (current === CHAR_LF) {
665
+ scnr.next();
666
+ eat(scnr, `\'`);
667
+ }
668
+ return literal;
669
+ }
670
+ eat(scnr, `\'`);
671
+ return literal;
672
+ }
673
+ function readEscapeSequence(scnr) {
674
+ const ch = scnr.currentChar();
675
+ switch (ch) {
676
+ case '\\':
677
+ case `\'`:
678
+ scnr.next();
679
+ return `\\${ch}`;
680
+ case 'u':
681
+ return readUnicodeEscapeSequence(scnr, ch, 4);
682
+ case 'U':
683
+ return readUnicodeEscapeSequence(scnr, ch, 6);
684
+ default:
685
+ emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
686
+ return '';
687
+ }
688
+ }
689
+ function readUnicodeEscapeSequence(scnr, unicode, digits) {
690
+ eat(scnr, unicode);
691
+ let sequence = '';
692
+ for (let i = 0; i < digits; i++) {
693
+ const ch = takeHexDigit(scnr);
694
+ if (!ch) {
695
+ emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
696
+ break;
697
+ }
698
+ sequence += ch;
699
+ }
700
+ return `\\${unicode}${sequence}`;
701
+ }
702
+ function readInvalidIdentifier(scnr) {
703
+ skipSpaces(scnr);
704
+ let ch = '';
705
+ let identifiers = '';
706
+ const closure = (ch) => ch !== "{" /* TokenChars.BraceLeft */ &&
707
+ ch !== "}" /* TokenChars.BraceRight */ &&
708
+ ch !== CHAR_SP &&
709
+ ch !== CHAR_LF;
710
+ while ((ch = takeChar(scnr, closure))) {
711
+ identifiers += ch;
712
+ }
713
+ return identifiers;
714
+ }
715
+ function readLinkedModifier(scnr) {
716
+ let ch = '';
717
+ let name = '';
718
+ while ((ch = takeIdentifierChar(scnr))) {
719
+ name += ch;
720
+ }
721
+ return name;
722
+ }
723
+ function readLinkedRefer(scnr) {
724
+ const fn = (detect = false, buf) => {
725
+ const ch = scnr.currentChar();
726
+ if (ch === "{" /* TokenChars.BraceLeft */ ||
727
+ ch === "%" /* TokenChars.Modulo */ ||
728
+ ch === "@" /* TokenChars.LinkedAlias */ ||
729
+ ch === "|" /* TokenChars.Pipe */ ||
730
+ !ch) {
731
+ return buf;
732
+ }
733
+ else if (ch === CHAR_SP) {
734
+ return buf;
735
+ }
736
+ else if (ch === CHAR_LF) {
737
+ buf += ch;
738
+ scnr.next();
739
+ return fn(detect, buf);
740
+ }
741
+ else {
742
+ buf += ch;
743
+ scnr.next();
744
+ return fn(true, buf);
745
+ }
746
+ };
747
+ return fn(false, '');
748
+ }
749
+ function readPlural(scnr) {
750
+ skipSpaces(scnr);
751
+ const plural = eat(scnr, "|" /* TokenChars.Pipe */);
752
+ skipSpaces(scnr);
753
+ return plural;
754
+ }
755
+ // TODO: We need refactoring of token parsing ...
756
+ function readTokenInPlaceholder(scnr, context) {
757
+ let token = null;
758
+ const ch = scnr.currentChar();
759
+ switch (ch) {
760
+ case "{" /* TokenChars.BraceLeft */:
761
+ if (context.braceNest >= 1) {
762
+ emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
763
+ }
764
+ scnr.next();
765
+ token = getToken(context, 2 /* TokenTypes.BraceLeft */, "{" /* TokenChars.BraceLeft */);
766
+ skipSpaces(scnr);
767
+ context.braceNest++;
768
+ return token;
769
+ case "}" /* TokenChars.BraceRight */:
770
+ if (context.braceNest > 0 &&
771
+ context.currentType === 2 /* TokenTypes.BraceLeft */) {
772
+ emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
773
+ }
774
+ scnr.next();
775
+ token = getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
776
+ context.braceNest--;
777
+ context.braceNest > 0 && skipSpaces(scnr);
778
+ if (context.inLinked && context.braceNest === 0) {
779
+ context.inLinked = false;
780
+ }
781
+ return token;
782
+ case "@" /* TokenChars.LinkedAlias */:
783
+ if (context.braceNest > 0) {
784
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
785
+ }
786
+ token = readTokenInLinked(scnr, context) || getEndToken(context);
787
+ context.braceNest = 0;
788
+ return token;
789
+ default:
790
+ let validNamedIdentifier = true;
791
+ let validListIdentifier = true;
792
+ let validLiteral = true;
793
+ if (isPluralStart(scnr)) {
794
+ if (context.braceNest > 0) {
795
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
796
+ }
797
+ token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
798
+ // reset
799
+ context.braceNest = 0;
800
+ context.inLinked = false;
801
+ return token;
802
+ }
803
+ if (context.braceNest > 0 &&
804
+ (context.currentType === 5 /* TokenTypes.Named */ ||
805
+ context.currentType === 6 /* TokenTypes.List */ ||
806
+ context.currentType === 7 /* TokenTypes.Literal */)) {
807
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
808
+ context.braceNest = 0;
809
+ return readToken(scnr, context);
810
+ }
811
+ if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
812
+ token = getToken(context, 5 /* TokenTypes.Named */, readNamedIdentifier(scnr));
813
+ skipSpaces(scnr);
814
+ return token;
815
+ }
816
+ if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
817
+ token = getToken(context, 6 /* TokenTypes.List */, readListIdentifier(scnr));
818
+ skipSpaces(scnr);
819
+ return token;
820
+ }
821
+ if ((validLiteral = isLiteralStart(scnr, context))) {
822
+ token = getToken(context, 7 /* TokenTypes.Literal */, readLiteral(scnr));
823
+ skipSpaces(scnr);
824
+ return token;
825
+ }
826
+ if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
827
+ // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
828
+ token = getToken(context, 13 /* TokenTypes.InvalidPlace */, readInvalidIdentifier(scnr));
829
+ emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
830
+ skipSpaces(scnr);
831
+ return token;
832
+ }
833
+ break;
834
+ }
835
+ return token;
836
+ }
837
+ // TODO: We need refactoring of token parsing ...
838
+ function readTokenInLinked(scnr, context) {
839
+ const { currentType } = context;
840
+ let token = null;
841
+ const ch = scnr.currentChar();
842
+ if ((currentType === 8 /* TokenTypes.LinkedAlias */ ||
843
+ currentType === 9 /* TokenTypes.LinkedDot */ ||
844
+ currentType === 12 /* TokenTypes.LinkedModifier */ ||
845
+ currentType === 10 /* TokenTypes.LinkedDelimiter */) &&
846
+ (ch === CHAR_LF || ch === CHAR_SP)) {
847
+ emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
848
+ }
849
+ switch (ch) {
850
+ case "@" /* TokenChars.LinkedAlias */:
851
+ scnr.next();
852
+ token = getToken(context, 8 /* TokenTypes.LinkedAlias */, "@" /* TokenChars.LinkedAlias */);
853
+ context.inLinked = true;
854
+ return token;
855
+ case "." /* TokenChars.LinkedDot */:
856
+ skipSpaces(scnr);
857
+ scnr.next();
858
+ return getToken(context, 9 /* TokenTypes.LinkedDot */, "." /* TokenChars.LinkedDot */);
859
+ case ":" /* TokenChars.LinkedDelimiter */:
860
+ skipSpaces(scnr);
861
+ scnr.next();
862
+ return getToken(context, 10 /* TokenTypes.LinkedDelimiter */, ":" /* TokenChars.LinkedDelimiter */);
863
+ default:
864
+ if (isPluralStart(scnr)) {
865
+ token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
866
+ // reset
867
+ context.braceNest = 0;
868
+ context.inLinked = false;
869
+ return token;
870
+ }
871
+ if (isLinkedDotStart(scnr, context) ||
872
+ isLinkedDelimiterStart(scnr, context)) {
873
+ skipSpaces(scnr);
874
+ return readTokenInLinked(scnr, context);
875
+ }
876
+ if (isLinkedModifierStart(scnr, context)) {
877
+ skipSpaces(scnr);
878
+ return getToken(context, 12 /* TokenTypes.LinkedModifier */, readLinkedModifier(scnr));
879
+ }
880
+ if (isLinkedReferStart(scnr, context)) {
881
+ skipSpaces(scnr);
882
+ if (ch === "{" /* TokenChars.BraceLeft */) {
883
+ // scan the placeholder
884
+ return readTokenInPlaceholder(scnr, context) || token;
885
+ }
886
+ else {
887
+ return getToken(context, 11 /* TokenTypes.LinkedKey */, readLinkedRefer(scnr));
888
+ }
889
+ }
890
+ if (currentType === 8 /* TokenTypes.LinkedAlias */) {
891
+ emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
892
+ }
893
+ context.braceNest = 0;
894
+ context.inLinked = false;
895
+ return readToken(scnr, context);
896
+ }
897
+ }
898
+ // TODO: We need refactoring of token parsing ...
899
+ function readToken(scnr, context) {
900
+ let token = { type: 14 /* TokenTypes.EOF */ };
901
+ if (context.braceNest > 0) {
902
+ return readTokenInPlaceholder(scnr, context) || getEndToken(context);
903
+ }
904
+ if (context.inLinked) {
905
+ return readTokenInLinked(scnr, context) || getEndToken(context);
906
+ }
907
+ const ch = scnr.currentChar();
908
+ switch (ch) {
909
+ case "{" /* TokenChars.BraceLeft */:
910
+ return readTokenInPlaceholder(scnr, context) || getEndToken(context);
911
+ case "}" /* TokenChars.BraceRight */:
912
+ emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
913
+ scnr.next();
914
+ return getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
915
+ case "@" /* TokenChars.LinkedAlias */:
916
+ return readTokenInLinked(scnr, context) || getEndToken(context);
917
+ default:
918
+ if (isPluralStart(scnr)) {
919
+ token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
920
+ // reset
921
+ context.braceNest = 0;
922
+ context.inLinked = false;
923
+ return token;
924
+ }
925
+ const { isModulo, hasSpace } = detectModuloStart(scnr);
926
+ if (isModulo) {
927
+ return hasSpace
928
+ ? getToken(context, 0 /* TokenTypes.Text */, readText(scnr))
929
+ : getToken(context, 4 /* TokenTypes.Modulo */, readModulo(scnr));
930
+ }
931
+ if (isTextStart(scnr)) {
932
+ return getToken(context, 0 /* TokenTypes.Text */, readText(scnr));
933
+ }
934
+ break;
935
+ }
936
+ return token;
937
+ }
938
+ function nextToken() {
939
+ const { currentType, offset, startLoc, endLoc } = _context;
940
+ _context.lastType = currentType;
941
+ _context.lastOffset = offset;
942
+ _context.lastStartLoc = startLoc;
943
+ _context.lastEndLoc = endLoc;
944
+ _context.offset = currentOffset();
945
+ _context.startLoc = currentPosition();
946
+ if (_scnr.currentChar() === EOF) {
947
+ return getToken(_context, 14 /* TokenTypes.EOF */);
948
+ }
949
+ return readToken(_scnr, _context);
950
+ }
951
+ return {
952
+ nextToken,
953
+ currentOffset,
954
+ currentPosition,
955
+ context
956
+ };
957
+ }
958
+
959
+ const ERROR_DOMAIN = 'parser';
960
+ // Backslash backslash, backslash quote, uHHHH, UHHHHHH.
961
+ const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
962
+ function fromEscapeSequence(match, codePoint4, codePoint6) {
963
+ switch (match) {
964
+ case `\\\\`:
965
+ return `\\`;
966
+ case `\\\'`:
967
+ return `\'`;
968
+ default: {
969
+ const codePoint = parseInt(codePoint4 || codePoint6, 16);
970
+ if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
971
+ return String.fromCodePoint(codePoint);
972
+ }
973
+ // invalid ...
974
+ // Replace them with U+FFFD REPLACEMENT CHARACTER.
975
+ return '�';
976
+ }
977
+ }
978
+ }
979
+ function createParser(options = {}) {
980
+ const location = options.location !== false;
981
+ const { onError } = options;
982
+ function emitError(tokenzer, code, start, offset, ...args) {
983
+ const end = tokenzer.currentPosition();
984
+ end.offset += offset;
985
+ end.column += offset;
986
+ if (onError) {
987
+ const loc = location ? createLocation(start, end) : null;
988
+ const err = createCompileError(code, loc, {
989
+ domain: ERROR_DOMAIN,
990
+ args
991
+ });
992
+ onError(err);
993
+ }
994
+ }
995
+ function startNode(type, offset, loc) {
996
+ const node = { type };
997
+ if (location) {
998
+ node.start = offset;
999
+ node.end = offset;
1000
+ node.loc = { start: loc, end: loc };
1001
+ }
1002
+ return node;
1003
+ }
1004
+ function endNode(node, offset, pos, type) {
1005
+ if (type) {
1006
+ node.type = type;
1007
+ }
1008
+ if (location) {
1009
+ node.end = offset;
1010
+ if (node.loc) {
1011
+ node.loc.end = pos;
1012
+ }
1013
+ }
1014
+ }
1015
+ function parseText(tokenizer, value) {
1016
+ const context = tokenizer.context();
1017
+ const node = startNode(3 /* NodeTypes.Text */, context.offset, context.startLoc);
1018
+ node.value = value;
1019
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1020
+ return node;
1021
+ }
1022
+ function parseList(tokenizer, index) {
1023
+ const context = tokenizer.context();
1024
+ const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
1025
+ const node = startNode(5 /* NodeTypes.List */, offset, loc);
1026
+ node.index = parseInt(index, 10);
1027
+ tokenizer.nextToken(); // skip brach right
1028
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1029
+ return node;
1030
+ }
1031
+ function parseNamed(tokenizer, key) {
1032
+ const context = tokenizer.context();
1033
+ const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
1034
+ const node = startNode(4 /* NodeTypes.Named */, offset, loc);
1035
+ node.key = key;
1036
+ tokenizer.nextToken(); // skip brach right
1037
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1038
+ return node;
1039
+ }
1040
+ function parseLiteral(tokenizer, value) {
1041
+ const context = tokenizer.context();
1042
+ const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
1043
+ const node = startNode(9 /* NodeTypes.Literal */, offset, loc);
1044
+ node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
1045
+ tokenizer.nextToken(); // skip brach right
1046
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1047
+ return node;
1048
+ }
1049
+ function parseLinkedModifier(tokenizer) {
1050
+ const token = tokenizer.nextToken();
1051
+ const context = tokenizer.context();
1052
+ const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
1053
+ const node = startNode(8 /* NodeTypes.LinkedModifier */, offset, loc);
1054
+ if (token.type !== 12 /* TokenTypes.LinkedModifier */) {
1055
+ // empty modifier
1056
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
1057
+ node.value = '';
1058
+ endNode(node, offset, loc);
1059
+ return {
1060
+ nextConsumeToken: token,
1061
+ node
1062
+ };
1063
+ }
1064
+ // check token
1065
+ if (token.value == null) {
1066
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1067
+ }
1068
+ node.value = token.value || '';
1069
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1070
+ return {
1071
+ node
1072
+ };
1073
+ }
1074
+ function parseLinkedKey(tokenizer, value) {
1075
+ const context = tokenizer.context();
1076
+ const node = startNode(7 /* NodeTypes.LinkedKey */, context.offset, context.startLoc);
1077
+ node.value = value;
1078
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1079
+ return node;
1080
+ }
1081
+ function parseLinked(tokenizer) {
1082
+ const context = tokenizer.context();
1083
+ const linkedNode = startNode(6 /* NodeTypes.Linked */, context.offset, context.startLoc);
1084
+ let token = tokenizer.nextToken();
1085
+ if (token.type === 9 /* TokenTypes.LinkedDot */) {
1086
+ const parsed = parseLinkedModifier(tokenizer);
1087
+ linkedNode.modifier = parsed.node;
1088
+ token = parsed.nextConsumeToken || tokenizer.nextToken();
1089
+ }
1090
+ // asset check token
1091
+ if (token.type !== 10 /* TokenTypes.LinkedDelimiter */) {
1092
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1093
+ }
1094
+ token = tokenizer.nextToken();
1095
+ // skip brace left
1096
+ if (token.type === 2 /* TokenTypes.BraceLeft */) {
1097
+ token = tokenizer.nextToken();
1098
+ }
1099
+ switch (token.type) {
1100
+ case 11 /* TokenTypes.LinkedKey */:
1101
+ if (token.value == null) {
1102
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1103
+ }
1104
+ linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
1105
+ break;
1106
+ case 5 /* TokenTypes.Named */:
1107
+ if (token.value == null) {
1108
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1109
+ }
1110
+ linkedNode.key = parseNamed(tokenizer, token.value || '');
1111
+ break;
1112
+ case 6 /* TokenTypes.List */:
1113
+ if (token.value == null) {
1114
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1115
+ }
1116
+ linkedNode.key = parseList(tokenizer, token.value || '');
1117
+ break;
1118
+ case 7 /* TokenTypes.Literal */:
1119
+ if (token.value == null) {
1120
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1121
+ }
1122
+ linkedNode.key = parseLiteral(tokenizer, token.value || '');
1123
+ break;
1124
+ default:
1125
+ // empty key
1126
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
1127
+ const nextContext = tokenizer.context();
1128
+ const emptyLinkedKeyNode = startNode(7 /* NodeTypes.LinkedKey */, nextContext.offset, nextContext.startLoc);
1129
+ emptyLinkedKeyNode.value = '';
1130
+ endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
1131
+ linkedNode.key = emptyLinkedKeyNode;
1132
+ endNode(linkedNode, nextContext.offset, nextContext.startLoc);
1133
+ return {
1134
+ nextConsumeToken: token,
1135
+ node: linkedNode
1136
+ };
1137
+ }
1138
+ endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
1139
+ return {
1140
+ node: linkedNode
1141
+ };
1142
+ }
1143
+ function parseMessage(tokenizer) {
1144
+ const context = tokenizer.context();
1145
+ const startOffset = context.currentType === 1 /* TokenTypes.Pipe */
1146
+ ? tokenizer.currentOffset()
1147
+ : context.offset;
1148
+ const startLoc = context.currentType === 1 /* TokenTypes.Pipe */
1149
+ ? context.endLoc
1150
+ : context.startLoc;
1151
+ const node = startNode(2 /* NodeTypes.Message */, startOffset, startLoc);
1152
+ node.items = [];
1153
+ let nextToken = null;
1154
+ do {
1155
+ const token = nextToken || tokenizer.nextToken();
1156
+ nextToken = null;
1157
+ switch (token.type) {
1158
+ case 0 /* TokenTypes.Text */:
1159
+ if (token.value == null) {
1160
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1161
+ }
1162
+ node.items.push(parseText(tokenizer, token.value || ''));
1163
+ break;
1164
+ case 6 /* TokenTypes.List */:
1165
+ if (token.value == null) {
1166
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1167
+ }
1168
+ node.items.push(parseList(tokenizer, token.value || ''));
1169
+ break;
1170
+ case 5 /* TokenTypes.Named */:
1171
+ if (token.value == null) {
1172
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1173
+ }
1174
+ node.items.push(parseNamed(tokenizer, token.value || ''));
1175
+ break;
1176
+ case 7 /* TokenTypes.Literal */:
1177
+ if (token.value == null) {
1178
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1179
+ }
1180
+ node.items.push(parseLiteral(tokenizer, token.value || ''));
1181
+ break;
1182
+ case 8 /* TokenTypes.LinkedAlias */:
1183
+ const parsed = parseLinked(tokenizer);
1184
+ node.items.push(parsed.node);
1185
+ nextToken = parsed.nextConsumeToken || null;
1186
+ break;
1187
+ }
1188
+ } while (context.currentType !== 14 /* TokenTypes.EOF */ &&
1189
+ context.currentType !== 1 /* TokenTypes.Pipe */);
1190
+ // adjust message node loc
1191
+ const endOffset = context.currentType === 1 /* TokenTypes.Pipe */
1192
+ ? context.lastOffset
1193
+ : tokenizer.currentOffset();
1194
+ const endLoc = context.currentType === 1 /* TokenTypes.Pipe */
1195
+ ? context.lastEndLoc
1196
+ : tokenizer.currentPosition();
1197
+ endNode(node, endOffset, endLoc);
1198
+ return node;
1199
+ }
1200
+ function parsePlural(tokenizer, offset, loc, msgNode) {
1201
+ const context = tokenizer.context();
1202
+ let hasEmptyMessage = msgNode.items.length === 0;
1203
+ const node = startNode(1 /* NodeTypes.Plural */, offset, loc);
1204
+ node.cases = [];
1205
+ node.cases.push(msgNode);
1206
+ do {
1207
+ const msg = parseMessage(tokenizer);
1208
+ if (!hasEmptyMessage) {
1209
+ hasEmptyMessage = msg.items.length === 0;
1210
+ }
1211
+ node.cases.push(msg);
1212
+ } while (context.currentType !== 14 /* TokenTypes.EOF */);
1213
+ if (hasEmptyMessage) {
1214
+ emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
1215
+ }
1216
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1217
+ return node;
1218
+ }
1219
+ function parseResource(tokenizer) {
1220
+ const context = tokenizer.context();
1221
+ const { offset, startLoc } = context;
1222
+ const msgNode = parseMessage(tokenizer);
1223
+ if (context.currentType === 14 /* TokenTypes.EOF */) {
1224
+ return msgNode;
1225
+ }
1226
+ else {
1227
+ return parsePlural(tokenizer, offset, startLoc, msgNode);
1228
+ }
1229
+ }
1230
+ function parse(source) {
1231
+ const tokenizer = createTokenizer(source, assign({}, options));
1232
+ const context = tokenizer.context();
1233
+ const node = startNode(0 /* NodeTypes.Resource */, context.offset, context.startLoc);
1234
+ if (location && node.loc) {
1235
+ node.loc.source = source;
1236
+ }
1237
+ node.body = parseResource(tokenizer);
1238
+ if (options.onCacheKey) {
1239
+ node.cacheKey = options.onCacheKey(source);
1240
+ }
1241
+ // assert whether achieved to EOF
1242
+ if (context.currentType !== 14 /* TokenTypes.EOF */) {
1243
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');
1244
+ }
1245
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1246
+ return node;
1247
+ }
1248
+ return { parse };
1249
+ }
1250
+ function getTokenCaption(token) {
1251
+ if (token.type === 14 /* TokenTypes.EOF */) {
1252
+ return 'EOF';
1253
+ }
1254
+ const name = (token.value || '').replace(/\r?\n/gu, '\\n');
1255
+ return name.length > 10 ? name.slice(0, 9) + '…' : name;
1256
+ }
1257
+
1258
+ function createTransformer(ast, options = {} // eslint-disable-line
1259
+ ) {
1260
+ const _context = {
1261
+ ast,
1262
+ helpers: new Set()
1263
+ };
1264
+ const context = () => _context;
1265
+ const helper = (name) => {
1266
+ _context.helpers.add(name);
1267
+ return name;
1268
+ };
1269
+ return { context, helper };
1270
+ }
1271
+ function traverseNodes(nodes, transformer) {
1272
+ for (let i = 0; i < nodes.length; i++) {
1273
+ traverseNode(nodes[i], transformer);
1274
+ }
1275
+ }
1276
+ function traverseNode(node, transformer) {
1277
+ // TODO: if we need pre-hook of transform, should be implemented to here
1278
+ switch (node.type) {
1279
+ case 1 /* NodeTypes.Plural */:
1280
+ traverseNodes(node.cases, transformer);
1281
+ transformer.helper("plural" /* HelperNameMap.PLURAL */);
1282
+ break;
1283
+ case 2 /* NodeTypes.Message */:
1284
+ traverseNodes(node.items, transformer);
1285
+ break;
1286
+ case 6 /* NodeTypes.Linked */:
1287
+ const linked = node;
1288
+ traverseNode(linked.key, transformer);
1289
+ transformer.helper("linked" /* HelperNameMap.LINKED */);
1290
+ transformer.helper("type" /* HelperNameMap.TYPE */);
1291
+ break;
1292
+ case 5 /* NodeTypes.List */:
1293
+ transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
1294
+ transformer.helper("list" /* HelperNameMap.LIST */);
1295
+ break;
1296
+ case 4 /* NodeTypes.Named */:
1297
+ transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
1298
+ transformer.helper("named" /* HelperNameMap.NAMED */);
1299
+ break;
1300
+ }
1301
+ // TODO: if we need post-hook of transform, should be implemented to here
1302
+ }
1303
+ // transform AST
1304
+ function transform(ast, options = {} // eslint-disable-line
1305
+ ) {
1306
+ const transformer = createTransformer(ast);
1307
+ transformer.helper("normalize" /* HelperNameMap.NORMALIZE */);
1308
+ // traverse
1309
+ ast.body && traverseNode(ast.body, transformer);
1310
+ // set meta information
1311
+ const context = transformer.context();
1312
+ ast.helpers = Array.from(context.helpers);
1313
+ }
1314
+
1315
+ function optimize(ast) {
1316
+ const body = ast.body;
1317
+ if (body.type === 2 /* NodeTypes.Message */) {
1318
+ optimizeMessageNode(body);
1319
+ }
1320
+ else {
1321
+ body.cases.forEach(c => optimizeMessageNode(c));
1322
+ }
1323
+ return ast;
1324
+ }
1325
+ function optimizeMessageNode(message) {
1326
+ if (message.items.length === 1) {
1327
+ const item = message.items[0];
1328
+ if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
1329
+ message.static = item.value;
1330
+ }
1331
+ }
1332
+ else {
1333
+ const values = [];
1334
+ for (let i = 0; i < message.items.length; i++) {
1335
+ const item = message.items[i];
1336
+ if (!(item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */)) {
1337
+ break;
1338
+ }
1339
+ values.push(item.value);
1340
+ }
1341
+ if (values.length === message.items.length) {
1342
+ message.static = join(values);
1343
+ }
1344
+ }
127
1345
  }
128
1346
 
129
- const CompileErrorCodes = {
130
- // tokenizer error codes
131
- EXPECTED_TOKEN: 1,
132
- INVALID_TOKEN_IN_PLACEHOLDER: 2,
133
- UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
134
- UNKNOWN_ESCAPE_SEQUENCE: 4,
135
- INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
136
- UNBALANCED_CLOSING_BRACE: 6,
137
- UNTERMINATED_CLOSING_BRACE: 7,
138
- EMPTY_PLACEHOLDER: 8,
139
- NOT_ALLOW_NEST_PLACEHOLDER: 9,
140
- INVALID_LINKED_FORMAT: 10,
141
- // parser error codes
142
- MUST_HAVE_MESSAGES_IN_PLURAL: 11,
143
- UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
144
- UNEXPECTED_EMPTY_LINKED_KEY: 13,
145
- UNEXPECTED_LEXICAL_ANALYSIS: 14,
146
- // Special value for higher-order compilers to pick up the last code
147
- // to avoid collision of error codes. This should always be kept as the last
148
- // item.
149
- __EXTEND_POINT__: 15
150
- };
151
- /** @internal */
152
- const errorMessages$1 = {
153
- // tokenizer error messages
154
- [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
155
- [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
156
- [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
157
- [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
158
- [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
159
- [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
160
- [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
161
- [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
162
- [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
163
- [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
164
- // parser error messages
165
- [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
166
- [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
167
- [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
168
- [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`
169
- };
170
- function createCompileError(code, loc, options = {}) {
171
- const { domain, messages, args } = options;
172
- const msg = format((messages || errorMessages$1)[code] || '', ...(args || []))
173
- ;
174
- const error = new SyntaxError(String(msg));
175
- error.code = code;
176
- if (loc) {
177
- error.location = loc;
178
- }
179
- error.domain = domain;
180
- return error;
1347
+ function createCodeGenerator(ast, options) {
1348
+ const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
1349
+ const location = options.location !== false;
1350
+ const _context = {
1351
+ filename,
1352
+ code: '',
1353
+ column: 1,
1354
+ line: 1,
1355
+ offset: 0,
1356
+ map: undefined,
1357
+ breakLineCode,
1358
+ needIndent: _needIndent,
1359
+ indentLevel: 0
1360
+ };
1361
+ if (location && ast.loc) {
1362
+ _context.source = ast.loc.source;
1363
+ }
1364
+ const context = () => _context;
1365
+ function push(code, node) {
1366
+ _context.code += code;
1367
+ }
1368
+ function _newline(n, withBreakLine = true) {
1369
+ const _breakLineCode = withBreakLine ? breakLineCode : '';
1370
+ push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
1371
+ }
1372
+ function indent(withNewLine = true) {
1373
+ const level = ++_context.indentLevel;
1374
+ withNewLine && _newline(level);
1375
+ }
1376
+ function deindent(withNewLine = true) {
1377
+ const level = --_context.indentLevel;
1378
+ withNewLine && _newline(level);
1379
+ }
1380
+ function newline() {
1381
+ _newline(_context.indentLevel);
1382
+ }
1383
+ const helper = (key) => `_${key}`;
1384
+ const needIndent = () => _context.needIndent;
1385
+ return {
1386
+ context,
1387
+ push,
1388
+ indent,
1389
+ deindent,
1390
+ newline,
1391
+ helper,
1392
+ needIndent
1393
+ };
181
1394
  }
1395
+ function generateLinkedNode(generator, node) {
1396
+ const { helper } = generator;
1397
+ generator.push(`${helper("linked" /* HelperNameMap.LINKED */)}(`);
1398
+ generateNode(generator, node.key);
1399
+ if (node.modifier) {
1400
+ generator.push(`, `);
1401
+ generateNode(generator, node.modifier);
1402
+ generator.push(`, _type`);
1403
+ }
1404
+ else {
1405
+ generator.push(`, undefined, _type`);
1406
+ }
1407
+ generator.push(`)`);
1408
+ }
1409
+ function generateMessageNode(generator, node) {
1410
+ const { helper, needIndent } = generator;
1411
+ generator.push(`${helper("normalize" /* HelperNameMap.NORMALIZE */)}([`);
1412
+ generator.indent(needIndent());
1413
+ const length = node.items.length;
1414
+ for (let i = 0; i < length; i++) {
1415
+ generateNode(generator, node.items[i]);
1416
+ if (i === length - 1) {
1417
+ break;
1418
+ }
1419
+ generator.push(', ');
1420
+ }
1421
+ generator.deindent(needIndent());
1422
+ generator.push('])');
1423
+ }
1424
+ function generatePluralNode(generator, node) {
1425
+ const { helper, needIndent } = generator;
1426
+ if (node.cases.length > 1) {
1427
+ generator.push(`${helper("plural" /* HelperNameMap.PLURAL */)}([`);
1428
+ generator.indent(needIndent());
1429
+ const length = node.cases.length;
1430
+ for (let i = 0; i < length; i++) {
1431
+ generateNode(generator, node.cases[i]);
1432
+ if (i === length - 1) {
1433
+ break;
1434
+ }
1435
+ generator.push(', ');
1436
+ }
1437
+ generator.deindent(needIndent());
1438
+ generator.push(`])`);
1439
+ }
1440
+ }
1441
+ function generateResource(generator, node) {
1442
+ if (node.body) {
1443
+ generateNode(generator, node.body);
1444
+ }
1445
+ else {
1446
+ generator.push('null');
1447
+ }
1448
+ }
1449
+ function generateNode(generator, node) {
1450
+ const { helper } = generator;
1451
+ switch (node.type) {
1452
+ case 0 /* NodeTypes.Resource */:
1453
+ generateResource(generator, node);
1454
+ break;
1455
+ case 1 /* NodeTypes.Plural */:
1456
+ generatePluralNode(generator, node);
1457
+ break;
1458
+ case 2 /* NodeTypes.Message */:
1459
+ generateMessageNode(generator, node);
1460
+ break;
1461
+ case 6 /* NodeTypes.Linked */:
1462
+ generateLinkedNode(generator, node);
1463
+ break;
1464
+ case 8 /* NodeTypes.LinkedModifier */:
1465
+ generator.push(JSON.stringify(node.value), node);
1466
+ break;
1467
+ case 7 /* NodeTypes.LinkedKey */:
1468
+ generator.push(JSON.stringify(node.value), node);
1469
+ break;
1470
+ case 5 /* NodeTypes.List */:
1471
+ generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("list" /* HelperNameMap.LIST */)}(${node.index}))`, node);
1472
+ break;
1473
+ case 4 /* NodeTypes.Named */:
1474
+ generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("named" /* HelperNameMap.NAMED */)}(${JSON.stringify(node.key)}))`, node);
1475
+ break;
1476
+ case 9 /* NodeTypes.Literal */:
1477
+ generator.push(JSON.stringify(node.value), node);
1478
+ break;
1479
+ case 3 /* NodeTypes.Text */:
1480
+ generator.push(JSON.stringify(node.value), node);
1481
+ break;
1482
+ default:
1483
+ {
1484
+ throw new Error(`unhandled codegen node type: ${node.type}`);
1485
+ }
1486
+ }
1487
+ }
1488
+ // generate code from AST
1489
+ const generate = (ast, options = {} // eslint-disable-line
1490
+ ) => {
1491
+ const mode = isString(options.mode) ? options.mode : 'normal';
1492
+ const filename = isString(options.filename)
1493
+ ? options.filename
1494
+ : 'message.intl';
1495
+ const sourceMap = !!options.sourceMap;
1496
+ // prettier-ignore
1497
+ const breakLineCode = options.breakLineCode != null
1498
+ ? options.breakLineCode
1499
+ : mode === 'arrow'
1500
+ ? ';'
1501
+ : '\n';
1502
+ const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
1503
+ const helpers = ast.helpers || [];
1504
+ const generator = createCodeGenerator(ast, {
1505
+ mode,
1506
+ filename,
1507
+ sourceMap,
1508
+ breakLineCode,
1509
+ needIndent
1510
+ });
1511
+ generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
1512
+ generator.indent(needIndent);
1513
+ if (helpers.length > 0) {
1514
+ generator.push(`const { ${join(helpers.map(s => `${s}: _${s}`), ', ')} } = ctx`);
1515
+ generator.newline();
1516
+ }
1517
+ generator.push(`return `);
1518
+ generateNode(generator, ast);
1519
+ generator.deindent(needIndent);
1520
+ generator.push(`}`);
1521
+ delete ast.helpers;
1522
+ const { code, map } = generator.context();
1523
+ return {
1524
+ ast,
1525
+ code,
1526
+ map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
1527
+ };
1528
+ };
182
1529
 
183
- const pathStateMachine = [];
184
- pathStateMachine[0 /* BEFORE_PATH */] = {
185
- ["w" /* WORKSPACE */]: [0 /* BEFORE_PATH */],
186
- ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
187
- ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
188
- ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
189
- };
190
- pathStateMachine[1 /* IN_PATH */] = {
191
- ["w" /* WORKSPACE */]: [1 /* IN_PATH */],
192
- ["." /* DOT */]: [2 /* BEFORE_IDENT */],
193
- ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
194
- ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
195
- };
196
- pathStateMachine[2 /* BEFORE_IDENT */] = {
197
- ["w" /* WORKSPACE */]: [2 /* BEFORE_IDENT */],
198
- ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
199
- ["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */]
200
- };
201
- pathStateMachine[3 /* IN_IDENT */] = {
202
- ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
203
- ["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */],
204
- ["w" /* WORKSPACE */]: [1 /* IN_PATH */, 1 /* PUSH */],
205
- ["." /* DOT */]: [2 /* BEFORE_IDENT */, 1 /* PUSH */],
206
- ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */, 1 /* PUSH */],
207
- ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */, 1 /* PUSH */]
208
- };
209
- pathStateMachine[4 /* IN_SUB_PATH */] = {
210
- ["'" /* SINGLE_QUOTE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */],
211
- ["\"" /* DOUBLE_QUOTE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */],
212
- ["[" /* LEFT_BRACKET */]: [
213
- 4 /* IN_SUB_PATH */,
214
- 2 /* INC_SUB_PATH_DEPTH */
215
- ],
216
- ["]" /* RIGHT_BRACKET */]: [1 /* IN_PATH */, 3 /* PUSH_SUB_PATH */],
217
- ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
218
- ["l" /* ELSE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */]
219
- };
220
- pathStateMachine[5 /* IN_SINGLE_QUOTE */] = {
221
- ["'" /* SINGLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
222
- ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
223
- ["l" /* ELSE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */]
224
- };
225
- pathStateMachine[6 /* IN_DOUBLE_QUOTE */] = {
226
- ["\"" /* DOUBLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
227
- ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
228
- ["l" /* ELSE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */]
229
- };
230
- /**
231
- * Check if an expression is a literal value.
232
- */
233
- const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
234
- function isLiteral(exp) {
235
- return literalValueRE.test(exp);
236
- }
237
- /**
238
- * Strip quotes from a string
239
- */
240
- function stripQuotes(str) {
241
- const a = str.charCodeAt(0);
242
- const b = str.charCodeAt(str.length - 1);
243
- return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
244
- }
245
- /**
246
- * Determine the type of a character in a keypath.
247
- */
248
- function getPathCharType(ch) {
249
- if (ch === undefined || ch === null) {
250
- return "o" /* END_OF_FAIL */;
251
- }
252
- const code = ch.charCodeAt(0);
253
- switch (code) {
254
- case 0x5b: // [
255
- case 0x5d: // ]
256
- case 0x2e: // .
257
- case 0x22: // "
258
- case 0x27: // '
259
- return ch;
260
- case 0x5f: // _
261
- case 0x24: // $
262
- case 0x2d: // -
263
- return "i" /* IDENT */;
264
- case 0x09: // Tab (HT)
265
- case 0x0a: // Newline (LF)
266
- case 0x0d: // Return (CR)
267
- case 0xa0: // No-break space (NBSP)
268
- case 0xfeff: // Byte Order Mark (BOM)
269
- case 0x2028: // Line Separator (LS)
270
- case 0x2029: // Paragraph Separator (PS)
271
- return "w" /* WORKSPACE */;
272
- }
273
- return "i" /* IDENT */;
274
- }
275
- /**
276
- * Format a subPath, return its plain form if it is
277
- * a literal string or number. Otherwise prepend the
278
- * dynamic indicator (*).
279
- */
280
- function formatSubPath(path) {
281
- const trimmed = path.trim();
282
- // invalid leading 0
283
- if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
284
- return false;
285
- }
286
- return isLiteral(trimmed)
287
- ? stripQuotes(trimmed)
288
- : "*" /* ASTARISK */ + trimmed;
289
- }
290
- /**
291
- * Parse a string path into an array of segments
292
- */
293
- function parse(path) {
294
- const keys = [];
295
- let index = -1;
296
- let mode = 0 /* BEFORE_PATH */;
297
- let subPathDepth = 0;
298
- let c;
299
- let key; // eslint-disable-line
300
- let newChar;
301
- let type;
302
- let transition;
303
- let action;
304
- let typeMap;
305
- const actions = [];
306
- actions[0 /* APPEND */] = () => {
307
- if (key === undefined) {
308
- key = newChar;
309
- }
310
- else {
311
- key += newChar;
312
- }
313
- };
314
- actions[1 /* PUSH */] = () => {
315
- if (key !== undefined) {
316
- keys.push(key);
317
- key = undefined;
318
- }
319
- };
320
- actions[2 /* INC_SUB_PATH_DEPTH */] = () => {
321
- actions[0 /* APPEND */]();
322
- subPathDepth++;
323
- };
324
- actions[3 /* PUSH_SUB_PATH */] = () => {
325
- if (subPathDepth > 0) {
326
- subPathDepth--;
327
- mode = 4 /* IN_SUB_PATH */;
328
- actions[0 /* APPEND */]();
329
- }
330
- else {
331
- subPathDepth = 0;
332
- if (key === undefined) {
333
- return false;
334
- }
335
- key = formatSubPath(key);
336
- if (key === false) {
337
- return false;
338
- }
339
- else {
340
- actions[1 /* PUSH */]();
341
- }
342
- }
343
- };
344
- function maybeUnescapeQuote() {
345
- const nextChar = path[index + 1];
346
- if ((mode === 5 /* IN_SINGLE_QUOTE */ &&
347
- nextChar === "'" /* SINGLE_QUOTE */) ||
348
- (mode === 6 /* IN_DOUBLE_QUOTE */ &&
349
- nextChar === "\"" /* DOUBLE_QUOTE */)) {
350
- index++;
351
- newChar = '\\' + nextChar;
352
- actions[0 /* APPEND */]();
353
- return true;
354
- }
355
- }
356
- while (mode !== null) {
357
- index++;
358
- c = path[index];
359
- if (c === '\\' && maybeUnescapeQuote()) {
360
- continue;
361
- }
362
- type = getPathCharType(c);
363
- typeMap = pathStateMachine[mode];
364
- transition = typeMap[type] || typeMap["l" /* ELSE */] || 8 /* ERROR */;
365
- // check parse error
366
- if (transition === 8 /* ERROR */) {
367
- return;
368
- }
369
- mode = transition[0];
370
- if (transition[1] !== undefined) {
371
- action = actions[transition[1]];
372
- if (action) {
373
- newChar = c;
374
- if (action() === false) {
375
- return;
376
- }
377
- }
378
- }
379
- // check parse finish
380
- if (mode === 7 /* AFTER_PATH */) {
381
- return keys;
382
- }
383
- }
384
- }
385
- // path token cache
386
- const cache = new Map();
387
- /**
388
- * key-value message resolver
389
- *
390
- * @remarks
391
- * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
392
- *
393
- * @param obj - A target object to be resolved with path
394
- * @param path - A {@link Path | path} to resolve the value of message
395
- *
396
- * @returns A resolved {@link PathValue | path value}
397
- *
398
- * @VueI18nGeneral
399
- */
400
- function resolveWithKeyValue(obj, path) {
401
- return isObject(obj) ? obj[path] : null;
402
- }
403
- /**
404
- * message resolver
405
- *
406
- * @remarks
407
- * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
408
- *
409
- * @param obj - A target object to be resolved with path
410
- * @param path - A {@link Path | path} to resolve the value of message
411
- *
412
- * @returns A resolved {@link PathValue | path value}
413
- *
414
- * @VueI18nGeneral
415
- */
416
- function resolveValue(obj, path) {
417
- // check object
418
- if (!isObject(obj)) {
419
- return null;
420
- }
421
- // parse path
422
- let hit = cache.get(path);
423
- if (!hit) {
424
- hit = parse(path);
425
- if (hit) {
426
- cache.set(path, hit);
427
- }
428
- }
429
- // check hit
430
- if (!hit) {
431
- return null;
432
- }
433
- // resolve path value
434
- const len = hit.length;
435
- let last = obj;
436
- let i = 0;
437
- while (i < len) {
438
- const val = last[hit[i]];
439
- if (val === undefined) {
440
- return null;
441
- }
442
- last = val;
443
- i++;
444
- }
445
- return last;
1530
+ function baseCompile$1(source, options = {}) {
1531
+ const assignedOptions = assign({}, options);
1532
+ const jit = !!assignedOptions.jit;
1533
+ const doOptimize = assignedOptions.optimize == null ? true : assignedOptions.optimize;
1534
+ // parse source codes
1535
+ const parser = createParser(assignedOptions);
1536
+ const ast = parser.parse(source);
1537
+ if (!jit) {
1538
+ // transform ASTs
1539
+ transform(ast, assignedOptions);
1540
+ // optimize ASTs
1541
+ doOptimize && optimize(ast);
1542
+ // generate javascript codes
1543
+ return generate(ast, assignedOptions);
1544
+ }
1545
+ else {
1546
+ // optimize ASTs
1547
+ doOptimize && optimize(ast);
1548
+ // In JIT mode, no ast transform, no code generation.
1549
+ return { ast, code: '' };
1550
+ }
1551
+ }
1552
+
1553
+ const pathStateMachine = [];
1554
+ pathStateMachine[0 /* States.BEFORE_PATH */] = {
1555
+ ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
1556
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
1557
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
1558
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
1559
+ };
1560
+ pathStateMachine[1 /* States.IN_PATH */] = {
1561
+ ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
1562
+ ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
1563
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
1564
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
1565
+ };
1566
+ pathStateMachine[2 /* States.BEFORE_IDENT */] = {
1567
+ ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
1568
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
1569
+ ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
1570
+ };
1571
+ pathStateMachine[3 /* States.IN_IDENT */] = {
1572
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
1573
+ ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
1574
+ ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
1575
+ ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
1576
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
1577
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
1578
+ };
1579
+ pathStateMachine[4 /* States.IN_SUB_PATH */] = {
1580
+ ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
1581
+ ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
1582
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [
1583
+ 4 /* States.IN_SUB_PATH */,
1584
+ 2 /* Actions.INC_SUB_PATH_DEPTH */
1585
+ ],
1586
+ ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
1587
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
1588
+ ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
1589
+ };
1590
+ pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
1591
+ ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
1592
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
1593
+ ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
1594
+ };
1595
+ pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
1596
+ ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
1597
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
1598
+ ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
1599
+ };
1600
+ /**
1601
+ * Check if an expression is a literal value.
1602
+ */
1603
+ const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
1604
+ function isLiteral(exp) {
1605
+ return literalValueRE.test(exp);
1606
+ }
1607
+ /**
1608
+ * Strip quotes from a string
1609
+ */
1610
+ function stripQuotes(str) {
1611
+ const a = str.charCodeAt(0);
1612
+ const b = str.charCodeAt(str.length - 1);
1613
+ return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
1614
+ }
1615
+ /**
1616
+ * Determine the type of a character in a keypath.
1617
+ */
1618
+ function getPathCharType(ch) {
1619
+ if (ch === undefined || ch === null) {
1620
+ return "o" /* PathCharTypes.END_OF_FAIL */;
1621
+ }
1622
+ const code = ch.charCodeAt(0);
1623
+ switch (code) {
1624
+ case 0x5b: // [
1625
+ case 0x5d: // ]
1626
+ case 0x2e: // .
1627
+ case 0x22: // "
1628
+ case 0x27: // '
1629
+ return ch;
1630
+ case 0x5f: // _
1631
+ case 0x24: // $
1632
+ case 0x2d: // -
1633
+ return "i" /* PathCharTypes.IDENT */;
1634
+ case 0x09: // Tab (HT)
1635
+ case 0x0a: // Newline (LF)
1636
+ case 0x0d: // Return (CR)
1637
+ case 0xa0: // No-break space (NBSP)
1638
+ case 0xfeff: // Byte Order Mark (BOM)
1639
+ case 0x2028: // Line Separator (LS)
1640
+ case 0x2029: // Paragraph Separator (PS)
1641
+ return "w" /* PathCharTypes.WORKSPACE */;
1642
+ }
1643
+ return "i" /* PathCharTypes.IDENT */;
1644
+ }
1645
+ /**
1646
+ * Format a subPath, return its plain form if it is
1647
+ * a literal string or number. Otherwise prepend the
1648
+ * dynamic indicator (*).
1649
+ */
1650
+ function formatSubPath(path) {
1651
+ const trimmed = path.trim();
1652
+ // invalid leading 0
1653
+ if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
1654
+ return false;
1655
+ }
1656
+ return isLiteral(trimmed)
1657
+ ? stripQuotes(trimmed)
1658
+ : "*" /* PathCharTypes.ASTARISK */ + trimmed;
1659
+ }
1660
+ /**
1661
+ * Parse a string path into an array of segments
1662
+ */
1663
+ function parse(path) {
1664
+ const keys = [];
1665
+ let index = -1;
1666
+ let mode = 0 /* States.BEFORE_PATH */;
1667
+ let subPathDepth = 0;
1668
+ let c;
1669
+ let key; // eslint-disable-line
1670
+ let newChar;
1671
+ let type;
1672
+ let transition;
1673
+ let action;
1674
+ let typeMap;
1675
+ const actions = [];
1676
+ actions[0 /* Actions.APPEND */] = () => {
1677
+ if (key === undefined) {
1678
+ key = newChar;
1679
+ }
1680
+ else {
1681
+ key += newChar;
1682
+ }
1683
+ };
1684
+ actions[1 /* Actions.PUSH */] = () => {
1685
+ if (key !== undefined) {
1686
+ keys.push(key);
1687
+ key = undefined;
1688
+ }
1689
+ };
1690
+ actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
1691
+ actions[0 /* Actions.APPEND */]();
1692
+ subPathDepth++;
1693
+ };
1694
+ actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
1695
+ if (subPathDepth > 0) {
1696
+ subPathDepth--;
1697
+ mode = 4 /* States.IN_SUB_PATH */;
1698
+ actions[0 /* Actions.APPEND */]();
1699
+ }
1700
+ else {
1701
+ subPathDepth = 0;
1702
+ if (key === undefined) {
1703
+ return false;
1704
+ }
1705
+ key = formatSubPath(key);
1706
+ if (key === false) {
1707
+ return false;
1708
+ }
1709
+ else {
1710
+ actions[1 /* Actions.PUSH */]();
1711
+ }
1712
+ }
1713
+ };
1714
+ function maybeUnescapeQuote() {
1715
+ const nextChar = path[index + 1];
1716
+ if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
1717
+ nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
1718
+ (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
1719
+ nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
1720
+ index++;
1721
+ newChar = '\\' + nextChar;
1722
+ actions[0 /* Actions.APPEND */]();
1723
+ return true;
1724
+ }
1725
+ }
1726
+ while (mode !== null) {
1727
+ index++;
1728
+ c = path[index];
1729
+ if (c === '\\' && maybeUnescapeQuote()) {
1730
+ continue;
1731
+ }
1732
+ type = getPathCharType(c);
1733
+ typeMap = pathStateMachine[mode];
1734
+ transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
1735
+ // check parse error
1736
+ if (transition === 8 /* States.ERROR */) {
1737
+ return;
1738
+ }
1739
+ mode = transition[0];
1740
+ if (transition[1] !== undefined) {
1741
+ action = actions[transition[1]];
1742
+ if (action) {
1743
+ newChar = c;
1744
+ if (action() === false) {
1745
+ return;
1746
+ }
1747
+ }
1748
+ }
1749
+ // check parse finish
1750
+ if (mode === 7 /* States.AFTER_PATH */) {
1751
+ return keys;
1752
+ }
1753
+ }
1754
+ }
1755
+ // path token cache
1756
+ const cache = new Map();
1757
+ /**
1758
+ * key-value message resolver
1759
+ *
1760
+ * @remarks
1761
+ * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
1762
+ *
1763
+ * @param obj - A target object to be resolved with path
1764
+ * @param path - A {@link Path | path} to resolve the value of message
1765
+ *
1766
+ * @returns A resolved {@link PathValue | path value}
1767
+ *
1768
+ * @VueI18nGeneral
1769
+ */
1770
+ function resolveWithKeyValue(obj, path) {
1771
+ return isObject(obj) ? obj[path] : null;
1772
+ }
1773
+ /**
1774
+ * message resolver
1775
+ *
1776
+ * @remarks
1777
+ * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
1778
+ *
1779
+ * @param obj - A target object to be resolved with path
1780
+ * @param path - A {@link Path | path} to resolve the value of message
1781
+ *
1782
+ * @returns A resolved {@link PathValue | path value}
1783
+ *
1784
+ * @VueI18nGeneral
1785
+ */
1786
+ function resolveValue(obj, path) {
1787
+ // check object
1788
+ if (!isObject(obj)) {
1789
+ return null;
1790
+ }
1791
+ // parse path
1792
+ let hit = cache.get(path);
1793
+ if (!hit) {
1794
+ hit = parse(path);
1795
+ if (hit) {
1796
+ cache.set(path, hit);
1797
+ }
1798
+ }
1799
+ // check hit
1800
+ if (!hit) {
1801
+ return null;
1802
+ }
1803
+ // resolve path value
1804
+ const len = hit.length;
1805
+ let last = obj;
1806
+ let i = 0;
1807
+ while (i < len) {
1808
+ const val = last[hit[i]];
1809
+ if (val === undefined) {
1810
+ return null;
1811
+ }
1812
+ last = val;
1813
+ i++;
1814
+ }
1815
+ return last;
446
1816
  }
447
1817
 
448
- const DEFAULT_MODIFIER = (str) => str;
449
- const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
450
- const DEFAULT_MESSAGE_DATA_TYPE = 'text';
451
- const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join('');
452
- const DEFAULT_INTERPOLATE = toDisplayString;
453
- function pluralDefault(choice, choicesLength) {
454
- choice = Math.abs(choice);
455
- if (choicesLength === 2) {
456
- // prettier-ignore
457
- return choice
458
- ? choice > 1
459
- ? 1
460
- : 0
461
- : 1;
462
- }
463
- return choice ? Math.min(choice, 2) : 0;
464
- }
465
- function getPluralIndex(options) {
466
- // prettier-ignore
467
- const index = isNumber(options.pluralIndex)
468
- ? options.pluralIndex
469
- : -1;
470
- // prettier-ignore
471
- return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
472
- ? isNumber(options.named.count)
473
- ? options.named.count
474
- : isNumber(options.named.n)
475
- ? options.named.n
476
- : index
477
- : index;
478
- }
479
- function normalizeNamed(pluralIndex, props) {
480
- if (!props.count) {
481
- props.count = pluralIndex;
482
- }
483
- if (!props.n) {
484
- props.n = pluralIndex;
485
- }
486
- }
487
- function createMessageContext(options = {}) {
488
- const locale = options.locale;
489
- const pluralIndex = getPluralIndex(options);
490
- const pluralRule = isObject(options.pluralRules) &&
491
- isString(locale) &&
492
- isFunction(options.pluralRules[locale])
493
- ? options.pluralRules[locale]
494
- : pluralDefault;
495
- const orgPluralRule = isObject(options.pluralRules) &&
496
- isString(locale) &&
497
- isFunction(options.pluralRules[locale])
498
- ? pluralDefault
499
- : undefined;
500
- const plural = (messages) => {
501
- return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
502
- };
503
- const _list = options.list || [];
504
- const list = (index) => _list[index];
505
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
506
- const _named = options.named || {};
507
- isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
508
- const named = (key) => _named[key];
509
- function message(key) {
510
- // prettier-ignore
511
- const msg = isFunction(options.messages)
512
- ? options.messages(key)
513
- : isObject(options.messages)
514
- ? options.messages[key]
515
- : false;
516
- return !msg
517
- ? options.parent
518
- ? options.parent.message(key) // resolve from parent messages
519
- : DEFAULT_MESSAGE
520
- : msg;
521
- }
522
- const _modifier = (name) => options.modifiers
523
- ? options.modifiers[name]
524
- : DEFAULT_MODIFIER;
525
- const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
526
- ? options.processor.normalize
527
- : DEFAULT_NORMALIZE;
528
- const interpolate = isPlainObject(options.processor) &&
529
- isFunction(options.processor.interpolate)
530
- ? options.processor.interpolate
531
- : DEFAULT_INTERPOLATE;
532
- const type = isPlainObject(options.processor) && isString(options.processor.type)
533
- ? options.processor.type
534
- : DEFAULT_MESSAGE_DATA_TYPE;
535
- const linked = (key, ...args) => {
536
- const [arg1, arg2] = args;
537
- let type = 'text';
538
- let modifier = '';
539
- if (args.length === 1) {
540
- if (isObject(arg1)) {
541
- modifier = arg1.modifier || modifier;
542
- type = arg1.type || type;
543
- }
544
- else if (isString(arg1)) {
545
- modifier = arg1 || modifier;
546
- }
547
- }
548
- else if (args.length === 2) {
549
- if (isString(arg1)) {
550
- modifier = arg1 || modifier;
551
- }
552
- if (isString(arg2)) {
553
- type = arg2 || type;
554
- }
555
- }
556
- let msg = message(key)(ctx);
557
- // The message in vnode resolved with linked are returned as an array by processor.nomalize
558
- if (type === 'vnode' && isArray(msg) && modifier) {
559
- msg = msg[0];
560
- }
561
- return modifier ? _modifier(modifier)(msg, type) : msg;
562
- };
563
- const ctx = {
564
- ["list" /* LIST */]: list,
565
- ["named" /* NAMED */]: named,
566
- ["plural" /* PLURAL */]: plural,
567
- ["linked" /* LINKED */]: linked,
568
- ["message" /* MESSAGE */]: message,
569
- ["type" /* TYPE */]: type,
570
- ["interpolate" /* INTERPOLATE */]: interpolate,
571
- ["normalize" /* NORMALIZE */]: normalize
572
- };
573
- return ctx;
1818
+ const DEFAULT_MODIFIER = (str) => str;
1819
+ const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
1820
+ const DEFAULT_MESSAGE_DATA_TYPE = 'text';
1821
+ const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);
1822
+ const DEFAULT_INTERPOLATE = toDisplayString;
1823
+ function pluralDefault(choice, choicesLength) {
1824
+ choice = Math.abs(choice);
1825
+ if (choicesLength === 2) {
1826
+ // prettier-ignore
1827
+ return choice
1828
+ ? choice > 1
1829
+ ? 1
1830
+ : 0
1831
+ : 1;
1832
+ }
1833
+ return choice ? Math.min(choice, 2) : 0;
1834
+ }
1835
+ function getPluralIndex(options) {
1836
+ // prettier-ignore
1837
+ const index = isNumber(options.pluralIndex)
1838
+ ? options.pluralIndex
1839
+ : -1;
1840
+ // prettier-ignore
1841
+ return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
1842
+ ? isNumber(options.named.count)
1843
+ ? options.named.count
1844
+ : isNumber(options.named.n)
1845
+ ? options.named.n
1846
+ : index
1847
+ : index;
1848
+ }
1849
+ function normalizeNamed(pluralIndex, props) {
1850
+ if (!props.count) {
1851
+ props.count = pluralIndex;
1852
+ }
1853
+ if (!props.n) {
1854
+ props.n = pluralIndex;
1855
+ }
1856
+ }
1857
+ function createMessageContext(options = {}) {
1858
+ const locale = options.locale;
1859
+ const pluralIndex = getPluralIndex(options);
1860
+ const pluralRule = isObject(options.pluralRules) &&
1861
+ isString(locale) &&
1862
+ isFunction(options.pluralRules[locale])
1863
+ ? options.pluralRules[locale]
1864
+ : pluralDefault;
1865
+ const orgPluralRule = isObject(options.pluralRules) &&
1866
+ isString(locale) &&
1867
+ isFunction(options.pluralRules[locale])
1868
+ ? pluralDefault
1869
+ : undefined;
1870
+ const plural = (messages) => {
1871
+ return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
1872
+ };
1873
+ const _list = options.list || [];
1874
+ const list = (index) => _list[index];
1875
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1876
+ const _named = options.named || {};
1877
+ isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
1878
+ const named = (key) => _named[key];
1879
+ function message(key) {
1880
+ // prettier-ignore
1881
+ const msg = isFunction(options.messages)
1882
+ ? options.messages(key)
1883
+ : isObject(options.messages)
1884
+ ? options.messages[key]
1885
+ : false;
1886
+ return !msg
1887
+ ? options.parent
1888
+ ? options.parent.message(key) // resolve from parent messages
1889
+ : DEFAULT_MESSAGE
1890
+ : msg;
1891
+ }
1892
+ const _modifier = (name) => options.modifiers
1893
+ ? options.modifiers[name]
1894
+ : DEFAULT_MODIFIER;
1895
+ const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
1896
+ ? options.processor.normalize
1897
+ : DEFAULT_NORMALIZE;
1898
+ const interpolate = isPlainObject(options.processor) &&
1899
+ isFunction(options.processor.interpolate)
1900
+ ? options.processor.interpolate
1901
+ : DEFAULT_INTERPOLATE;
1902
+ const type = isPlainObject(options.processor) && isString(options.processor.type)
1903
+ ? options.processor.type
1904
+ : DEFAULT_MESSAGE_DATA_TYPE;
1905
+ const linked = (key, ...args) => {
1906
+ const [arg1, arg2] = args;
1907
+ let type = 'text';
1908
+ let modifier = '';
1909
+ if (args.length === 1) {
1910
+ if (isObject(arg1)) {
1911
+ modifier = arg1.modifier || modifier;
1912
+ type = arg1.type || type;
1913
+ }
1914
+ else if (isString(arg1)) {
1915
+ modifier = arg1 || modifier;
1916
+ }
1917
+ }
1918
+ else if (args.length === 2) {
1919
+ if (isString(arg1)) {
1920
+ modifier = arg1 || modifier;
1921
+ }
1922
+ if (isString(arg2)) {
1923
+ type = arg2 || type;
1924
+ }
1925
+ }
1926
+ const ret = message(key)(ctx);
1927
+ const msg =
1928
+ // The message in vnode resolved with linked are returned as an array by processor.nomalize
1929
+ type === 'vnode' && isArray(ret) && modifier
1930
+ ? ret[0]
1931
+ : ret;
1932
+ return modifier ? _modifier(modifier)(msg, type) : msg;
1933
+ };
1934
+ const ctx = {
1935
+ ["list" /* HelperNameMap.LIST */]: list,
1936
+ ["named" /* HelperNameMap.NAMED */]: named,
1937
+ ["plural" /* HelperNameMap.PLURAL */]: plural,
1938
+ ["linked" /* HelperNameMap.LINKED */]: linked,
1939
+ ["message" /* HelperNameMap.MESSAGE */]: message,
1940
+ ["type" /* HelperNameMap.TYPE */]: type,
1941
+ ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
1942
+ ["normalize" /* HelperNameMap.NORMALIZE */]: normalize
1943
+ };
1944
+ return ctx;
574
1945
  }
575
1946
 
576
- const IntlifyDevToolsHooks = {
577
- I18nInit: 'i18n:init',
578
- FunctionTranslate: 'function:translate'
1947
+ const IntlifyDevToolsHooks = {
1948
+ I18nInit: 'i18n:init',
1949
+ FunctionTranslate: 'function:translate'
579
1950
  };
580
1951
 
581
- let devtools = null;
582
- function setDevToolsHook(hook) {
583
- devtools = hook;
584
- }
585
- function getDevToolsHook() {
586
- return devtools;
587
- }
588
- function initI18nDevTools(i18n, version, meta) {
589
- // TODO: queue if devtools is undefined
590
- devtools &&
591
- devtools.emit(IntlifyDevToolsHooks.I18nInit, {
592
- timestamp: Date.now(),
593
- i18n,
594
- version,
595
- meta
596
- });
597
- }
598
- const translateDevTools = /* #__PURE__*/ createDevToolsHook(IntlifyDevToolsHooks.FunctionTranslate);
599
- function createDevToolsHook(hook) {
600
- return (payloads) => devtools && devtools.emit(hook, payloads);
1952
+ let devtools = null;
1953
+ function setDevToolsHook(hook) {
1954
+ devtools = hook;
1955
+ }
1956
+ function getDevToolsHook() {
1957
+ return devtools;
1958
+ }
1959
+ function initI18nDevTools(i18n, version, meta) {
1960
+ // TODO: queue if devtools is undefined
1961
+ devtools &&
1962
+ devtools.emit(IntlifyDevToolsHooks.I18nInit, {
1963
+ timestamp: Date.now(),
1964
+ i18n,
1965
+ version,
1966
+ meta
1967
+ });
1968
+ }
1969
+ const translateDevTools = /* #__PURE__*/ createDevToolsHook(IntlifyDevToolsHooks.FunctionTranslate);
1970
+ function createDevToolsHook(hook) {
1971
+ return (payloads) => devtools && devtools.emit(hook, payloads);
601
1972
  }
602
1973
 
603
- const CoreWarnCodes = {
604
- NOT_FOUND_KEY: 1,
605
- FALLBACK_TO_TRANSLATE: 2,
606
- CANNOT_FORMAT_NUMBER: 3,
607
- FALLBACK_TO_NUMBER_FORMAT: 4,
608
- CANNOT_FORMAT_DATE: 5,
609
- FALLBACK_TO_DATE_FORMAT: 6,
610
- __EXTEND_POINT__: 7
611
- };
612
- /** @internal */
613
- const warnMessages = {
614
- [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
615
- [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
616
- [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
617
- [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
618
- [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
619
- [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`
620
- };
621
- function getWarnMessage(code, ...args) {
622
- return format(warnMessages[code], ...args);
1974
+ const CoreWarnCodes = {
1975
+ NOT_FOUND_KEY: 1,
1976
+ FALLBACK_TO_TRANSLATE: 2,
1977
+ CANNOT_FORMAT_NUMBER: 3,
1978
+ FALLBACK_TO_NUMBER_FORMAT: 4,
1979
+ CANNOT_FORMAT_DATE: 5,
1980
+ FALLBACK_TO_DATE_FORMAT: 6,
1981
+ __EXTEND_POINT__: 7
1982
+ };
1983
+ /** @internal */
1984
+ const warnMessages = {
1985
+ [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
1986
+ [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
1987
+ [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
1988
+ [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
1989
+ [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
1990
+ [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`
1991
+ };
1992
+ function getWarnMessage(code, ...args) {
1993
+ return format$1(warnMessages[code], ...args);
623
1994
  }
624
1995
 
625
- /**
626
- * Fallback with simple implemenation
627
- *
628
- * @remarks
629
- * A fallback locale function implemented with a simple fallback algorithm.
630
- *
631
- * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
632
- *
633
- * @param ctx - A {@link CoreContext | context}
634
- * @param fallback - A {@link FallbackLocale | fallback locale}
635
- * @param start - A starting {@link Locale | locale}
636
- *
637
- * @returns Fallback locales
638
- *
639
- * @VueI18nGeneral
640
- */
641
- function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
642
- ) {
643
- // prettier-ignore
644
- return [...new Set([
645
- start,
646
- ...(isArray(fallback)
647
- ? fallback
648
- : isObject(fallback)
649
- ? Object.keys(fallback)
650
- : isString(fallback)
651
- ? [fallback]
652
- : [start])
653
- ])];
654
- }
655
- /**
656
- * Fallback with locale chain
657
- *
658
- * @remarks
659
- * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
660
- *
661
- * @param ctx - A {@link CoreContext | context}
662
- * @param fallback - A {@link FallbackLocale | fallback locale}
663
- * @param start - A starting {@link Locale | locale}
664
- *
665
- * @returns Fallback locales
666
- *
667
- * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
668
- *
669
- * @VueI18nGeneral
670
- */
671
- function fallbackWithLocaleChain(ctx, fallback, start) {
672
- const startLocale = isString(start) ? start : DEFAULT_LOCALE;
673
- const context = ctx;
674
- if (!context.__localeChainCache) {
675
- context.__localeChainCache = new Map();
676
- }
677
- let chain = context.__localeChainCache.get(startLocale);
678
- if (!chain) {
679
- chain = [];
680
- // first block defined by start
681
- let block = [start];
682
- // while any intervening block found
683
- while (isArray(block)) {
684
- block = appendBlockToChain(chain, block, fallback);
685
- }
686
- // prettier-ignore
687
- // last block defined by default
688
- const defaults = isArray(fallback) || !isPlainObject(fallback)
689
- ? fallback
690
- : fallback['default']
691
- ? fallback['default']
692
- : null;
693
- // convert defaults to array
694
- block = isString(defaults) ? [defaults] : defaults;
695
- if (isArray(block)) {
696
- appendBlockToChain(chain, block, false);
697
- }
698
- context.__localeChainCache.set(startLocale, chain);
699
- }
700
- return chain;
701
- }
702
- function appendBlockToChain(chain, block, blocks) {
703
- let follow = true;
704
- for (let i = 0; i < block.length && isBoolean(follow); i++) {
705
- const locale = block[i];
706
- if (isString(locale)) {
707
- follow = appendLocaleToChain(chain, block[i], blocks);
708
- }
709
- }
710
- return follow;
711
- }
712
- function appendLocaleToChain(chain, locale, blocks) {
713
- let follow;
714
- const tokens = locale.split('-');
715
- do {
716
- const target = tokens.join('-');
717
- follow = appendItemToChain(chain, target, blocks);
718
- tokens.splice(-1, 1);
719
- } while (tokens.length && follow === true);
720
- return follow;
721
- }
722
- function appendItemToChain(chain, target, blocks) {
723
- let follow = false;
724
- if (!chain.includes(target)) {
725
- follow = true;
726
- if (target) {
727
- follow = target[target.length - 1] !== '!';
728
- const locale = target.replace(/!/g, '');
729
- chain.push(locale);
730
- if ((isArray(blocks) || isPlainObject(blocks)) &&
731
- blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
732
- ) {
733
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
734
- follow = blocks[locale];
735
- }
736
- }
737
- }
738
- return follow;
1996
+ /**
1997
+ * Fallback with simple implemenation
1998
+ *
1999
+ * @remarks
2000
+ * A fallback locale function implemented with a simple fallback algorithm.
2001
+ *
2002
+ * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
2003
+ *
2004
+ * @param ctx - A {@link CoreContext | context}
2005
+ * @param fallback - A {@link FallbackLocale | fallback locale}
2006
+ * @param start - A starting {@link Locale | locale}
2007
+ *
2008
+ * @returns Fallback locales
2009
+ *
2010
+ * @VueI18nGeneral
2011
+ */
2012
+ function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
2013
+ ) {
2014
+ // prettier-ignore
2015
+ return [...new Set([
2016
+ start,
2017
+ ...(isArray(fallback)
2018
+ ? fallback
2019
+ : isObject(fallback)
2020
+ ? Object.keys(fallback)
2021
+ : isString(fallback)
2022
+ ? [fallback]
2023
+ : [start])
2024
+ ])];
2025
+ }
2026
+ /**
2027
+ * Fallback with locale chain
2028
+ *
2029
+ * @remarks
2030
+ * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
2031
+ *
2032
+ * @param ctx - A {@link CoreContext | context}
2033
+ * @param fallback - A {@link FallbackLocale | fallback locale}
2034
+ * @param start - A starting {@link Locale | locale}
2035
+ *
2036
+ * @returns Fallback locales
2037
+ *
2038
+ * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
2039
+ *
2040
+ * @VueI18nGeneral
2041
+ */
2042
+ function fallbackWithLocaleChain(ctx, fallback, start) {
2043
+ const startLocale = isString(start) ? start : DEFAULT_LOCALE;
2044
+ const context = ctx;
2045
+ if (!context.__localeChainCache) {
2046
+ context.__localeChainCache = new Map();
2047
+ }
2048
+ let chain = context.__localeChainCache.get(startLocale);
2049
+ if (!chain) {
2050
+ chain = [];
2051
+ // first block defined by start
2052
+ let block = [start];
2053
+ // while any intervening block found
2054
+ while (isArray(block)) {
2055
+ block = appendBlockToChain(chain, block, fallback);
2056
+ }
2057
+ // prettier-ignore
2058
+ // last block defined by default
2059
+ const defaults = isArray(fallback) || !isPlainObject(fallback)
2060
+ ? fallback
2061
+ : fallback['default']
2062
+ ? fallback['default']
2063
+ : null;
2064
+ // convert defaults to array
2065
+ block = isString(defaults) ? [defaults] : defaults;
2066
+ if (isArray(block)) {
2067
+ appendBlockToChain(chain, block, false);
2068
+ }
2069
+ context.__localeChainCache.set(startLocale, chain);
2070
+ }
2071
+ return chain;
2072
+ }
2073
+ function appendBlockToChain(chain, block, blocks) {
2074
+ let follow = true;
2075
+ for (let i = 0; i < block.length && isBoolean(follow); i++) {
2076
+ const locale = block[i];
2077
+ if (isString(locale)) {
2078
+ follow = appendLocaleToChain(chain, block[i], blocks);
2079
+ }
2080
+ }
2081
+ return follow;
2082
+ }
2083
+ function appendLocaleToChain(chain, locale, blocks) {
2084
+ let follow;
2085
+ const tokens = locale.split('-');
2086
+ do {
2087
+ const target = tokens.join('-');
2088
+ follow = appendItemToChain(chain, target, blocks);
2089
+ tokens.splice(-1, 1);
2090
+ } while (tokens.length && follow === true);
2091
+ return follow;
2092
+ }
2093
+ function appendItemToChain(chain, target, blocks) {
2094
+ let follow = false;
2095
+ if (!chain.includes(target)) {
2096
+ follow = true;
2097
+ if (target) {
2098
+ follow = target[target.length - 1] !== '!';
2099
+ const locale = target.replace(/!/g, '');
2100
+ chain.push(locale);
2101
+ if ((isArray(blocks) || isPlainObject(blocks)) &&
2102
+ blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
2103
+ ) {
2104
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2105
+ follow = blocks[locale];
2106
+ }
2107
+ }
2108
+ }
2109
+ return follow;
739
2110
  }
740
2111
 
741
- /* eslint-disable @typescript-eslint/no-explicit-any */
742
- /**
743
- * Intlify core-base version
744
- * @internal
745
- */
746
- const VERSION = '9.3.0-beta.2';
747
- const NOT_REOSLVED = -1;
748
- const DEFAULT_LOCALE = 'en-US';
749
- const MISSING_RESOLVE_VALUE = '';
750
- const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
751
- function getDefaultLinkedModifiers() {
752
- return {
753
- upper: (val, type) => {
754
- // prettier-ignore
755
- return type === 'text' && isString(val)
756
- ? val.toUpperCase()
757
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
758
- ? val.children.toUpperCase()
759
- : val;
760
- },
761
- lower: (val, type) => {
762
- // prettier-ignore
763
- return type === 'text' && isString(val)
764
- ? val.toLowerCase()
765
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
766
- ? val.children.toLowerCase()
767
- : val;
768
- },
769
- capitalize: (val, type) => {
770
- // prettier-ignore
771
- return (type === 'text' && isString(val)
772
- ? capitalize(val)
773
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
774
- ? capitalize(val.children)
775
- : val);
776
- }
777
- };
778
- }
779
- let _compiler;
780
- function registerMessageCompiler(compiler) {
781
- _compiler = compiler;
782
- }
783
- let _resolver;
784
- /**
785
- * Register the message resolver
786
- *
787
- * @param resolver - A {@link MessageResolver} function
788
- *
789
- * @VueI18nGeneral
790
- */
791
- function registerMessageResolver(resolver) {
792
- _resolver = resolver;
793
- }
794
- let _fallbacker;
795
- /**
796
- * Register the locale fallbacker
797
- *
798
- * @param fallbacker - A {@link LocaleFallbacker} function
799
- *
800
- * @VueI18nGeneral
801
- */
802
- function registerLocaleFallbacker(fallbacker) {
803
- _fallbacker = fallbacker;
804
- }
805
- // Additional Meta for Intlify DevTools
806
- let _additionalMeta = null;
807
- const setAdditionalMeta = (meta) => {
808
- _additionalMeta = meta;
809
- };
810
- const getAdditionalMeta = () => _additionalMeta;
811
- let _fallbackContext = null;
812
- const setFallbackContext = (context) => {
813
- _fallbackContext = context;
814
- };
815
- const getFallbackContext = () => _fallbackContext;
816
- // ID for CoreContext
817
- let _cid = 0;
818
- function createCoreContext(options = {}) {
819
- // setup options
820
- const version = isString(options.version) ? options.version : VERSION;
821
- const locale = isString(options.locale) ? options.locale : DEFAULT_LOCALE;
822
- const fallbackLocale = isArray(options.fallbackLocale) ||
823
- isPlainObject(options.fallbackLocale) ||
824
- isString(options.fallbackLocale) ||
825
- options.fallbackLocale === false
826
- ? options.fallbackLocale
827
- : locale;
828
- const messages = isPlainObject(options.messages)
829
- ? options.messages
830
- : { [locale]: {} };
831
- const datetimeFormats = isPlainObject(options.datetimeFormats)
832
- ? options.datetimeFormats
833
- : { [locale]: {} }
834
- ;
835
- const numberFormats = isPlainObject(options.numberFormats)
836
- ? options.numberFormats
837
- : { [locale]: {} }
838
- ;
839
- const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
840
- const pluralRules = options.pluralRules || {};
841
- const missing = isFunction(options.missing) ? options.missing : null;
842
- const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
843
- ? options.missingWarn
844
- : true;
845
- const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
846
- ? options.fallbackWarn
847
- : true;
848
- const fallbackFormat = !!options.fallbackFormat;
849
- const unresolving = !!options.unresolving;
850
- const postTranslation = isFunction(options.postTranslation)
851
- ? options.postTranslation
852
- : null;
853
- const processor = isPlainObject(options.processor) ? options.processor : null;
854
- const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
855
- ? options.warnHtmlMessage
856
- : true;
857
- const escapeParameter = !!options.escapeParameter;
858
- const messageCompiler = isFunction(options.messageCompiler)
859
- ? options.messageCompiler
860
- : _compiler;
861
- const messageResolver = isFunction(options.messageResolver)
862
- ? options.messageResolver
863
- : _resolver || resolveWithKeyValue;
864
- const localeFallbacker = isFunction(options.localeFallbacker)
865
- ? options.localeFallbacker
866
- : _fallbacker || fallbackWithSimple;
867
- const fallbackContext = isObject(options.fallbackContext)
868
- ? options.fallbackContext
869
- : undefined;
870
- const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
871
- // setup internal options
872
- const internalOptions = options;
873
- const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
874
- ? internalOptions.__datetimeFormatters
875
- : new Map()
876
- ;
877
- const __numberFormatters = isObject(internalOptions.__numberFormatters)
878
- ? internalOptions.__numberFormatters
879
- : new Map()
880
- ;
881
- const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
882
- _cid++;
883
- const context = {
884
- version,
885
- cid: _cid,
886
- locale,
887
- fallbackLocale,
888
- messages,
889
- modifiers,
890
- pluralRules,
891
- missing,
892
- missingWarn,
893
- fallbackWarn,
894
- fallbackFormat,
895
- unresolving,
896
- postTranslation,
897
- processor,
898
- warnHtmlMessage,
899
- escapeParameter,
900
- messageCompiler,
901
- messageResolver,
902
- localeFallbacker,
903
- fallbackContext,
904
- onWarn,
905
- __meta
906
- };
907
- {
908
- context.datetimeFormats = datetimeFormats;
909
- context.numberFormats = numberFormats;
910
- context.__datetimeFormatters = __datetimeFormatters;
911
- context.__numberFormatters = __numberFormatters;
912
- }
913
- // for vue-devtools timeline event
914
- {
915
- context.__v_emitter =
916
- internalOptions.__v_emitter != null
917
- ? internalOptions.__v_emitter
918
- : undefined;
919
- }
920
- // NOTE: experimental !!
921
- {
922
- initI18nDevTools(context, version, __meta);
923
- }
924
- return context;
925
- }
926
- /** @internal */
927
- function isTranslateFallbackWarn(fallback, key) {
928
- return fallback instanceof RegExp ? fallback.test(key) : fallback;
929
- }
930
- /** @internal */
931
- function isTranslateMissingWarn(missing, key) {
932
- return missing instanceof RegExp ? missing.test(key) : missing;
933
- }
934
- /** @internal */
935
- function handleMissing(context, key, locale, missingWarn, type) {
936
- const { missing, onWarn } = context;
937
- // for vue-devtools timeline event
938
- {
939
- const emitter = context.__v_emitter;
940
- if (emitter) {
941
- emitter.emit("missing" /* MISSING */, {
942
- locale,
943
- key,
944
- type,
945
- groupId: `${type}:${key}`
946
- });
947
- }
948
- }
949
- if (missing !== null) {
950
- const ret = missing(context, locale, key, type);
951
- return isString(ret) ? ret : key;
952
- }
953
- else {
954
- if (isTranslateMissingWarn(missingWarn, key)) {
955
- onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
956
- }
957
- return key;
958
- }
959
- }
960
- /** @internal */
961
- function updateFallbackLocale(ctx, locale, fallback) {
962
- const context = ctx;
963
- context.__localeChainCache = new Map();
964
- ctx.localeFallbacker(ctx, fallback, locale);
965
- }
2112
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2113
+ /**
2114
+ * Intlify core-base version
2115
+ * @internal
2116
+ */
2117
+ const VERSION = '9.3.0-beta.21';
2118
+ const NOT_REOSLVED = -1;
2119
+ const DEFAULT_LOCALE = 'en-US';
2120
+ const MISSING_RESOLVE_VALUE = '';
2121
+ const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
2122
+ function getDefaultLinkedModifiers() {
2123
+ return {
2124
+ upper: (val, type) => {
2125
+ // prettier-ignore
2126
+ return type === 'text' && isString(val)
2127
+ ? val.toUpperCase()
2128
+ : type === 'vnode' && isObject(val) && '__v_isVNode' in val
2129
+ ? val.children.toUpperCase()
2130
+ : val;
2131
+ },
2132
+ lower: (val, type) => {
2133
+ // prettier-ignore
2134
+ return type === 'text' && isString(val)
2135
+ ? val.toLowerCase()
2136
+ : type === 'vnode' && isObject(val) && '__v_isVNode' in val
2137
+ ? val.children.toLowerCase()
2138
+ : val;
2139
+ },
2140
+ capitalize: (val, type) => {
2141
+ // prettier-ignore
2142
+ return (type === 'text' && isString(val)
2143
+ ? capitalize(val)
2144
+ : type === 'vnode' && isObject(val) && '__v_isVNode' in val
2145
+ ? capitalize(val.children)
2146
+ : val);
2147
+ }
2148
+ };
2149
+ }
2150
+ let _compiler;
2151
+ function registerMessageCompiler(compiler) {
2152
+ _compiler = compiler;
2153
+ }
2154
+ let _resolver;
2155
+ /**
2156
+ * Register the message resolver
2157
+ *
2158
+ * @param resolver - A {@link MessageResolver} function
2159
+ *
2160
+ * @VueI18nGeneral
2161
+ */
2162
+ function registerMessageResolver(resolver) {
2163
+ _resolver = resolver;
2164
+ }
2165
+ let _fallbacker;
2166
+ /**
2167
+ * Register the locale fallbacker
2168
+ *
2169
+ * @param fallbacker - A {@link LocaleFallbacker} function
2170
+ *
2171
+ * @VueI18nGeneral
2172
+ */
2173
+ function registerLocaleFallbacker(fallbacker) {
2174
+ _fallbacker = fallbacker;
2175
+ }
2176
+ // Additional Meta for Intlify DevTools
2177
+ let _additionalMeta = null;
2178
+ const setAdditionalMeta = (meta) => {
2179
+ _additionalMeta = meta;
2180
+ };
2181
+ const getAdditionalMeta = () => _additionalMeta;
2182
+ let _fallbackContext = null;
2183
+ const setFallbackContext = (context) => {
2184
+ _fallbackContext = context;
2185
+ };
2186
+ const getFallbackContext = () => _fallbackContext;
2187
+ // ID for CoreContext
2188
+ let _cid = 0;
2189
+ function createCoreContext(options = {}) {
2190
+ // setup options
2191
+ const version = isString(options.version) ? options.version : VERSION;
2192
+ const locale = isString(options.locale) ? options.locale : DEFAULT_LOCALE;
2193
+ const fallbackLocale = isArray(options.fallbackLocale) ||
2194
+ isPlainObject(options.fallbackLocale) ||
2195
+ isString(options.fallbackLocale) ||
2196
+ options.fallbackLocale === false
2197
+ ? options.fallbackLocale
2198
+ : locale;
2199
+ const messages = isPlainObject(options.messages)
2200
+ ? options.messages
2201
+ : { [locale]: {} };
2202
+ const datetimeFormats = isPlainObject(options.datetimeFormats)
2203
+ ? options.datetimeFormats
2204
+ : { [locale]: {} }
2205
+ ;
2206
+ const numberFormats = isPlainObject(options.numberFormats)
2207
+ ? options.numberFormats
2208
+ : { [locale]: {} }
2209
+ ;
2210
+ const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
2211
+ const pluralRules = options.pluralRules || {};
2212
+ const missing = isFunction(options.missing) ? options.missing : null;
2213
+ const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
2214
+ ? options.missingWarn
2215
+ : true;
2216
+ const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
2217
+ ? options.fallbackWarn
2218
+ : true;
2219
+ const fallbackFormat = !!options.fallbackFormat;
2220
+ const unresolving = !!options.unresolving;
2221
+ const postTranslation = isFunction(options.postTranslation)
2222
+ ? options.postTranslation
2223
+ : null;
2224
+ const processor = isPlainObject(options.processor) ? options.processor : null;
2225
+ const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
2226
+ ? options.warnHtmlMessage
2227
+ : true;
2228
+ const escapeParameter = !!options.escapeParameter;
2229
+ const messageCompiler = isFunction(options.messageCompiler)
2230
+ ? options.messageCompiler
2231
+ : _compiler;
2232
+ const messageResolver = isFunction(options.messageResolver)
2233
+ ? options.messageResolver
2234
+ : _resolver || resolveWithKeyValue;
2235
+ const localeFallbacker = isFunction(options.localeFallbacker)
2236
+ ? options.localeFallbacker
2237
+ : _fallbacker || fallbackWithSimple;
2238
+ const fallbackContext = isObject(options.fallbackContext)
2239
+ ? options.fallbackContext
2240
+ : undefined;
2241
+ const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
2242
+ // setup internal options
2243
+ const internalOptions = options;
2244
+ const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
2245
+ ? internalOptions.__datetimeFormatters
2246
+ : new Map()
2247
+ ;
2248
+ const __numberFormatters = isObject(internalOptions.__numberFormatters)
2249
+ ? internalOptions.__numberFormatters
2250
+ : new Map()
2251
+ ;
2252
+ const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
2253
+ _cid++;
2254
+ const context = {
2255
+ version,
2256
+ cid: _cid,
2257
+ locale,
2258
+ fallbackLocale,
2259
+ messages,
2260
+ modifiers,
2261
+ pluralRules,
2262
+ missing,
2263
+ missingWarn,
2264
+ fallbackWarn,
2265
+ fallbackFormat,
2266
+ unresolving,
2267
+ postTranslation,
2268
+ processor,
2269
+ warnHtmlMessage,
2270
+ escapeParameter,
2271
+ messageCompiler,
2272
+ messageResolver,
2273
+ localeFallbacker,
2274
+ fallbackContext,
2275
+ onWarn,
2276
+ __meta
2277
+ };
2278
+ {
2279
+ context.datetimeFormats = datetimeFormats;
2280
+ context.numberFormats = numberFormats;
2281
+ context.__datetimeFormatters = __datetimeFormatters;
2282
+ context.__numberFormatters = __numberFormatters;
2283
+ }
2284
+ // for vue-devtools timeline event
2285
+ {
2286
+ context.__v_emitter =
2287
+ internalOptions.__v_emitter != null
2288
+ ? internalOptions.__v_emitter
2289
+ : undefined;
2290
+ }
2291
+ // NOTE: experimental !!
2292
+ {
2293
+ initI18nDevTools(context, version, __meta);
2294
+ }
2295
+ return context;
2296
+ }
2297
+ /** @internal */
2298
+ function isTranslateFallbackWarn(fallback, key) {
2299
+ return fallback instanceof RegExp ? fallback.test(key) : fallback;
2300
+ }
2301
+ /** @internal */
2302
+ function isTranslateMissingWarn(missing, key) {
2303
+ return missing instanceof RegExp ? missing.test(key) : missing;
2304
+ }
2305
+ /** @internal */
2306
+ function handleMissing(context, key, locale, missingWarn, type) {
2307
+ const { missing, onWarn } = context;
2308
+ // for vue-devtools timeline event
2309
+ {
2310
+ const emitter = context.__v_emitter;
2311
+ if (emitter) {
2312
+ emitter.emit("missing" /* VueDevToolsTimelineEvents.MISSING */, {
2313
+ locale,
2314
+ key,
2315
+ type,
2316
+ groupId: `${type}:${key}`
2317
+ });
2318
+ }
2319
+ }
2320
+ if (missing !== null) {
2321
+ const ret = missing(context, locale, key, type);
2322
+ return isString(ret) ? ret : key;
2323
+ }
2324
+ else {
2325
+ if (isTranslateMissingWarn(missingWarn, key)) {
2326
+ onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
2327
+ }
2328
+ return key;
2329
+ }
2330
+ }
2331
+ /** @internal */
2332
+ function updateFallbackLocale(ctx, locale, fallback) {
2333
+ const context = ctx;
2334
+ context.__localeChainCache = new Map();
2335
+ ctx.localeFallbacker(ctx, fallback, locale);
2336
+ }
966
2337
  /* eslint-enable @typescript-eslint/no-explicit-any */
967
2338
 
968
- function clearCompileCache() {
969
- }
970
- function compileToFunction(source, options = {}) {
971
- {
972
- warn(`Runtime compilation is not supported in ${'core.runtime.global.js' }.`);
973
- return (() => source);
974
- }
2339
+ function format(ast) {
2340
+ const msg = (ctx) => formatParts(ctx, ast);
2341
+ // TODO: add meta data for vue-devtools debugging, such as `key`, `source` and `locale`
2342
+ // TODO: optimization for static text message
2343
+ return msg;
2344
+ }
2345
+ function formatParts(ctx, ast) {
2346
+ if (ast.body.type === 1 /* NodeTypes.Plural */) {
2347
+ return ctx.plural(ast.body.cases.reduce((messages, c) => [
2348
+ ...messages,
2349
+ formatMessageParts(ctx, c)
2350
+ ], []));
2351
+ }
2352
+ else {
2353
+ return formatMessageParts(ctx, ast.body);
2354
+ }
2355
+ }
2356
+ function formatMessageParts(ctx, node) {
2357
+ if (node.static) {
2358
+ return ctx.type === 'text'
2359
+ ? node.static
2360
+ : ctx.normalize([node.static]);
2361
+ }
2362
+ else {
2363
+ const messages = node.items.reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
2364
+ return ctx.normalize(messages);
2365
+ }
2366
+ }
2367
+ function formatMessagePart(ctx, node) {
2368
+ switch (node.type) {
2369
+ case 3 /* NodeTypes.Text */:
2370
+ return node.value;
2371
+ case 9 /* NodeTypes.Literal */:
2372
+ return node.value;
2373
+ case 4 /* NodeTypes.Named */:
2374
+ return ctx.interpolate(ctx.named(node.key));
2375
+ case 5 /* NodeTypes.List */:
2376
+ return ctx.interpolate(ctx.list(node.index));
2377
+ case 6 /* NodeTypes.Linked */:
2378
+ return ctx.linked(formatMessagePart(ctx, node.key), node.modifier
2379
+ ? formatMessagePart(ctx, node.modifier)
2380
+ : undefined, ctx.type);
2381
+ case 7 /* NodeTypes.LinkedKey */:
2382
+ return node.value;
2383
+ case 8 /* NodeTypes.LinkedModifier */:
2384
+ return node.value;
2385
+ default:
2386
+ throw new Error(`unhandled node type on format message part: ${node.type}`);
2387
+ }
975
2388
  }
976
2389
 
977
- let code = CompileErrorCodes.__EXTEND_POINT__;
978
- const inc = () => ++code;
979
- const CoreErrorCodes = {
980
- INVALID_ARGUMENT: code,
981
- INVALID_DATE_ARGUMENT: inc(),
982
- INVALID_ISO_DATE_ARGUMENT: inc(),
983
- __EXTEND_POINT__: inc() // 18
984
- };
985
- function createCoreError(code) {
986
- return createCompileError(code, null, { messages: errorMessages } );
987
- }
988
- /** @internal */
989
- const errorMessages = {
990
- [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
991
- [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
992
- 'Make sure your Date represents a valid date.',
993
- [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string'
2390
+ let code = CompileErrorCodes.__EXTEND_POINT__;
2391
+ const inc = () => ++code;
2392
+ const CoreErrorCodes = {
2393
+ INVALID_ARGUMENT: code,
2394
+ INVALID_DATE_ARGUMENT: inc(),
2395
+ INVALID_ISO_DATE_ARGUMENT: inc(),
2396
+ NOT_SUPPORT_AST: inc(),
2397
+ __EXTEND_POINT__: inc() // 19
2398
+ };
2399
+ function createCoreError(code) {
2400
+ return createCompileError(code, null, { messages: errorMessages } );
2401
+ }
2402
+ /** @internal */
2403
+ const errorMessages = {
2404
+ [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
2405
+ [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
2406
+ 'Make sure your Date represents a valid date.',
2407
+ [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string',
2408
+ [CoreErrorCodes.NOT_SUPPORT_AST]: 'Not support AST'
994
2409
  };
995
2410
 
996
- const NOOP_MESSAGE_FUNCTION = () => '';
997
- const isMessageFunction = (val) => isFunction(val);
998
- // implementation of `translate` function
999
- function translate(context, ...args) {
1000
- const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
1001
- const [key, options] = parseTranslateArgs(...args);
1002
- const missingWarn = isBoolean(options.missingWarn)
1003
- ? options.missingWarn
1004
- : context.missingWarn;
1005
- const fallbackWarn = isBoolean(options.fallbackWarn)
1006
- ? options.fallbackWarn
1007
- : context.fallbackWarn;
1008
- const escapeParameter = isBoolean(options.escapeParameter)
1009
- ? options.escapeParameter
1010
- : context.escapeParameter;
1011
- const resolvedMessage = !!options.resolvedMessage;
1012
- // prettier-ignore
1013
- const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
1014
- ? !isBoolean(options.default)
1015
- ? options.default
1016
- : (!messageCompiler ? () => key : key)
1017
- : fallbackFormat // default by `fallbackFormat` option
1018
- ? (!messageCompiler ? () => key : key)
1019
- : '';
1020
- const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
1021
- const locale = isString(options.locale) ? options.locale : context.locale;
1022
- // escape params
1023
- escapeParameter && escapeParams(options);
1024
- // resolve message format
1025
- // eslint-disable-next-line prefer-const
1026
- let [formatScope, targetLocale, message] = !resolvedMessage
1027
- ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
1028
- : [
1029
- key,
1030
- locale,
1031
- messages[locale] || {}
1032
- ];
1033
- // NOTE:
1034
- // Fix to work around `ssrTransfrom` bug in Vite.
1035
- // https://github.com/vitejs/vite/issues/4306
1036
- // To get around this, use temporary variables.
1037
- // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
1038
- let format = formatScope;
1039
- // if you use default message, set it as message format!
1040
- let cacheBaseKey = key;
1041
- if (!resolvedMessage &&
1042
- !(isString(format) || isMessageFunction(format))) {
1043
- if (enableDefaultMsg) {
1044
- format = defaultMsgOrKey;
1045
- cacheBaseKey = format;
1046
- }
1047
- }
1048
- // checking message format and target locale
1049
- if (!resolvedMessage &&
1050
- (!(isString(format) || isMessageFunction(format)) ||
1051
- !isString(targetLocale))) {
1052
- return unresolving ? NOT_REOSLVED : key;
1053
- }
1054
- if (isString(format) && context.messageCompiler == null) {
1055
- warn(`The message format compilation is not supported in this build. ` +
1056
- `Because message compiler isn't included. ` +
1057
- `You need to pre-compilation all message format. ` +
1058
- `So translate function return '${key}'.`);
1059
- return key;
1060
- }
1061
- // setup compile error detecting
1062
- let occurred = false;
1063
- const errorDetector = () => {
1064
- occurred = true;
1065
- };
1066
- // compile message format
1067
- const msg = !isMessageFunction(format)
1068
- ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
1069
- : format;
1070
- // if occurred compile error, return the message format
1071
- if (occurred) {
1072
- return format;
1073
- }
1074
- // evaluate message with context
1075
- const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
1076
- const msgContext = createMessageContext(ctxOptions);
1077
- const messaged = evaluateMessage(context, msg, msgContext);
1078
- // if use post translation option, proceed it with handler
1079
- const ret = postTranslation
1080
- ? postTranslation(messaged, key)
1081
- : messaged;
1082
- // NOTE: experimental !!
1083
- {
1084
- // prettier-ignore
1085
- const payloads = {
1086
- timestamp: Date.now(),
1087
- key: isString(key)
1088
- ? key
1089
- : isMessageFunction(format)
1090
- ? format.key
1091
- : '',
1092
- locale: targetLocale || (isMessageFunction(format)
1093
- ? format.locale
1094
- : ''),
1095
- format: isString(format)
1096
- ? format
1097
- : isMessageFunction(format)
1098
- ? format.source
1099
- : '',
1100
- message: ret
1101
- };
1102
- payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
1103
- translateDevTools(payloads);
1104
- }
1105
- return ret;
1106
- }
1107
- function escapeParams(options) {
1108
- if (isArray(options.list)) {
1109
- options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
1110
- }
1111
- else if (isObject(options.named)) {
1112
- Object.keys(options.named).forEach(key => {
1113
- if (isString(options.named[key])) {
1114
- options.named[key] = escapeHtml(options.named[key]);
1115
- }
1116
- });
1117
- }
1118
- }
1119
- function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
1120
- const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
1121
- const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
1122
- let message = {};
1123
- let targetLocale;
1124
- let format = null;
1125
- let from = locale;
1126
- let to = null;
1127
- const type = 'translate';
1128
- for (let i = 0; i < locales.length; i++) {
1129
- targetLocale = to = locales[i];
1130
- if (locale !== targetLocale &&
1131
- isTranslateFallbackWarn(fallbackWarn, key)) {
1132
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
1133
- key,
1134
- target: targetLocale
1135
- }));
1136
- }
1137
- // for vue-devtools timeline event
1138
- if (locale !== targetLocale) {
1139
- const emitter = context.__v_emitter;
1140
- if (emitter) {
1141
- emitter.emit("fallback" /* FALBACK */, {
1142
- type,
1143
- key,
1144
- from,
1145
- to,
1146
- groupId: `${type}:${key}`
1147
- });
1148
- }
1149
- }
1150
- message =
1151
- messages[targetLocale] || {};
1152
- // for vue-devtools timeline event
1153
- let start = null;
1154
- let startTag;
1155
- let endTag;
1156
- if (inBrowser) {
1157
- start = window.performance.now();
1158
- startTag = 'intlify-message-resolve-start';
1159
- endTag = 'intlify-message-resolve-end';
1160
- mark && mark(startTag);
1161
- }
1162
- if ((format = resolveValue(message, key)) === null) {
1163
- // if null, resolve with object key path
1164
- format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
1165
- }
1166
- // for vue-devtools timeline event
1167
- if (inBrowser) {
1168
- const end = window.performance.now();
1169
- const emitter = context.__v_emitter;
1170
- if (emitter && start && format) {
1171
- emitter.emit("message-resolve" /* MESSAGE_RESOLVE */, {
1172
- type: "message-resolve" /* MESSAGE_RESOLVE */,
1173
- key,
1174
- message: format,
1175
- time: end - start,
1176
- groupId: `${type}:${key}`
1177
- });
1178
- }
1179
- if (startTag && endTag && mark && measure) {
1180
- mark(endTag);
1181
- measure('intlify message resolve', startTag, endTag);
1182
- }
1183
- }
1184
- if (isString(format) || isFunction(format))
1185
- break;
1186
- const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1187
- key, targetLocale, missingWarn, type);
1188
- if (missingRet !== key) {
1189
- format = missingRet;
1190
- }
1191
- from = to;
1192
- }
1193
- return [format, targetLocale, message];
1194
- }
1195
- function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
1196
- const { messageCompiler, warnHtmlMessage } = context;
1197
- if (isMessageFunction(format)) {
1198
- const msg = format;
1199
- msg.locale = msg.locale || targetLocale;
1200
- msg.key = msg.key || key;
1201
- return msg;
1202
- }
1203
- if (messageCompiler == null) {
1204
- const msg = (() => format);
1205
- msg.locale = targetLocale;
1206
- msg.key = key;
1207
- return msg;
1208
- }
1209
- // for vue-devtools timeline event
1210
- let start = null;
1211
- let startTag;
1212
- let endTag;
1213
- if (inBrowser) {
1214
- start = window.performance.now();
1215
- startTag = 'intlify-message-compilation-start';
1216
- endTag = 'intlify-message-compilation-end';
1217
- mark && mark(startTag);
1218
- }
1219
- const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
1220
- // for vue-devtools timeline event
1221
- if (inBrowser) {
1222
- const end = window.performance.now();
1223
- const emitter = context.__v_emitter;
1224
- if (emitter && start) {
1225
- emitter.emit("message-compilation" /* MESSAGE_COMPILATION */, {
1226
- type: "message-compilation" /* MESSAGE_COMPILATION */,
1227
- message: format,
1228
- time: end - start,
1229
- groupId: `${'translate'}:${key}`
1230
- });
1231
- }
1232
- if (startTag && endTag && mark && measure) {
1233
- mark(endTag);
1234
- measure('intlify message compilation', startTag, endTag);
1235
- }
1236
- }
1237
- msg.locale = targetLocale;
1238
- msg.key = key;
1239
- msg.source = format;
1240
- return msg;
1241
- }
1242
- function evaluateMessage(context, msg, msgCtx) {
1243
- // for vue-devtools timeline event
1244
- let start = null;
1245
- let startTag;
1246
- let endTag;
1247
- if (inBrowser) {
1248
- start = window.performance.now();
1249
- startTag = 'intlify-message-evaluation-start';
1250
- endTag = 'intlify-message-evaluation-end';
1251
- mark && mark(startTag);
1252
- }
1253
- const messaged = msg(msgCtx);
1254
- // for vue-devtools timeline event
1255
- if (inBrowser) {
1256
- const end = window.performance.now();
1257
- const emitter = context.__v_emitter;
1258
- if (emitter && start) {
1259
- emitter.emit("message-evaluation" /* MESSAGE_EVALUATION */, {
1260
- type: "message-evaluation" /* MESSAGE_EVALUATION */,
1261
- value: messaged,
1262
- time: end - start,
1263
- groupId: `${'translate'}:${msg.key}`
1264
- });
1265
- }
1266
- if (startTag && endTag && mark && measure) {
1267
- mark(endTag);
1268
- measure('intlify message evaluation', startTag, endTag);
1269
- }
1270
- }
1271
- return messaged;
1272
- }
1273
- /** @internal */
1274
- function parseTranslateArgs(...args) {
1275
- const [arg1, arg2, arg3] = args;
1276
- const options = {};
1277
- if (!isString(arg1) && !isNumber(arg1) && !isMessageFunction(arg1)) {
1278
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1279
- }
1280
- // prettier-ignore
1281
- const key = isNumber(arg1)
1282
- ? String(arg1)
1283
- : isMessageFunction(arg1)
1284
- ? arg1
1285
- : arg1;
1286
- if (isNumber(arg2)) {
1287
- options.plural = arg2;
1288
- }
1289
- else if (isString(arg2)) {
1290
- options.default = arg2;
1291
- }
1292
- else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
1293
- options.named = arg2;
1294
- }
1295
- else if (isArray(arg2)) {
1296
- options.list = arg2;
1297
- }
1298
- if (isNumber(arg3)) {
1299
- options.plural = arg3;
1300
- }
1301
- else if (isString(arg3)) {
1302
- options.default = arg3;
1303
- }
1304
- else if (isPlainObject(arg3)) {
1305
- assign(options, arg3);
1306
- }
1307
- return [key, options];
1308
- }
1309
- function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
1310
- return {
1311
- warnHtmlMessage,
1312
- onError: (err) => {
1313
- errorDetector && errorDetector(err);
1314
- {
1315
- const message = `Message compilation error: ${err.message}`;
1316
- const codeFrame = err.location &&
1317
- generateCodeFrame(source, err.location.start.offset, err.location.end.offset);
1318
- const emitter = context.__v_emitter;
1319
- if (emitter) {
1320
- emitter.emit("compile-error" /* COMPILE_ERROR */, {
1321
- message: source,
1322
- error: err.message,
1323
- start: err.location && err.location.start.offset,
1324
- end: err.location && err.location.end.offset,
1325
- groupId: `${'translate'}:${key}`
1326
- });
1327
- }
1328
- console.error(codeFrame ? `${message}\n${codeFrame}` : message);
1329
- }
1330
- },
1331
- onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
1332
- };
1333
- }
1334
- function getMessageContextOptions(context, locale, message, options) {
1335
- const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
1336
- const resolveMessage = (key) => {
1337
- let val = resolveValue(message, key);
1338
- // fallback to root context
1339
- if (val == null && fallbackContext) {
1340
- const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
1341
- val = resolveValue(message, key);
1342
- }
1343
- if (isString(val)) {
1344
- let occurred = false;
1345
- const errorDetector = () => {
1346
- occurred = true;
1347
- };
1348
- const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
1349
- return !occurred
1350
- ? msg
1351
- : NOOP_MESSAGE_FUNCTION;
1352
- }
1353
- else if (isMessageFunction(val)) {
1354
- return val;
1355
- }
1356
- else {
1357
- // TODO: should be implemented warning message
1358
- return NOOP_MESSAGE_FUNCTION;
1359
- }
1360
- };
1361
- const ctxOptions = {
1362
- locale,
1363
- modifiers,
1364
- pluralRules,
1365
- messages: resolveMessage
1366
- };
1367
- if (context.processor) {
1368
- ctxOptions.processor = context.processor;
1369
- }
1370
- if (options.list) {
1371
- ctxOptions.list = options.list;
1372
- }
1373
- if (options.named) {
1374
- ctxOptions.named = options.named;
1375
- }
1376
- if (isNumber(options.plural)) {
1377
- ctxOptions.pluralIndex = options.plural;
1378
- }
1379
- return ctxOptions;
2411
+ const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
2412
+ function checkHtmlMessage(source, warnHtmlMessage) {
2413
+ if (warnHtmlMessage && detectHtmlTag(source)) {
2414
+ warn(format$1(WARN_MESSAGE, { source }));
2415
+ }
2416
+ }
2417
+ const defaultOnCacheKey = (message) => message;
2418
+ let compileCache = Object.create(null);
2419
+ function clearCompileCache() {
2420
+ compileCache = Object.create(null);
2421
+ }
2422
+ function baseCompile(message, options = {}) {
2423
+ // error detecting on compile
2424
+ let detectError = false;
2425
+ const onError = options.onError || defaultOnError;
2426
+ options.onError = (err) => {
2427
+ detectError = true;
2428
+ onError(err);
2429
+ };
2430
+ // compile with mesasge-compiler
2431
+ return { ...baseCompile$1(message, options), detectError };
2432
+ }
2433
+ function compileToFunction(message, options = {}) {
2434
+ if (!isString(message)) {
2435
+ throw createCoreError(CoreErrorCodes.NOT_SUPPORT_AST);
2436
+ }
2437
+ {
2438
+ warn(`Runtime compilation is not supported in ${'core.runtime.global.js' }.`);
2439
+ return (() => message);
2440
+ }
2441
+ }
2442
+ function compile(message, options = {}) {
2443
+ if (isString(message)) {
2444
+ // check HTML message
2445
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2446
+ const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
2447
+ ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
2448
+ options.warnHtmlMessage
2449
+ : true;
2450
+ checkHtmlMessage(message, warnHtmlMessage);
2451
+ // check caches
2452
+ const onCacheKey = options.onCacheKey || defaultOnCacheKey;
2453
+ const cacheKey = onCacheKey(message);
2454
+ const cached = compileCache[cacheKey];
2455
+ if (cached) {
2456
+ return cached;
2457
+ }
2458
+ // compile with JIT mode
2459
+ const { ast, detectError } = baseCompile(message, {
2460
+ ...options,
2461
+ location: true,
2462
+ jit: true
2463
+ });
2464
+ // compose message function from AST
2465
+ const msg = format(ast);
2466
+ // if occurred compile error, don't cache
2467
+ return !detectError
2468
+ ? (compileCache[cacheKey] = msg)
2469
+ : msg;
2470
+ }
2471
+ else {
2472
+ // AST case (passed from bundler)
2473
+ const cacheKey = message.cacheKey;
2474
+ if (cacheKey) {
2475
+ const cached = compileCache[cacheKey];
2476
+ if (cached) {
2477
+ return cached;
2478
+ }
2479
+ // compose message function from message (AST)
2480
+ return (compileCache[cacheKey] =
2481
+ format(message));
2482
+ }
2483
+ else {
2484
+ return format(message);
2485
+ }
2486
+ }
1380
2487
  }
1381
2488
 
1382
- const intlDefined = typeof Intl !== 'undefined';
1383
- const Availabilities = {
1384
- dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
1385
- numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
2489
+ const NOOP_MESSAGE_FUNCTION = () => '';
2490
+ const isMessageFunction = (val) => isFunction(val);
2491
+ const isMessageAST = (val) => isObject(val) && val.type === 0 && 'body' in val;
2492
+ // implementation of `translate` function
2493
+ function translate(context, ...args) {
2494
+ const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
2495
+ const [key, options] = parseTranslateArgs(...args);
2496
+ const missingWarn = isBoolean(options.missingWarn)
2497
+ ? options.missingWarn
2498
+ : context.missingWarn;
2499
+ const fallbackWarn = isBoolean(options.fallbackWarn)
2500
+ ? options.fallbackWarn
2501
+ : context.fallbackWarn;
2502
+ const escapeParameter = isBoolean(options.escapeParameter)
2503
+ ? options.escapeParameter
2504
+ : context.escapeParameter;
2505
+ const resolvedMessage = !!options.resolvedMessage;
2506
+ // prettier-ignore
2507
+ const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
2508
+ ? !isBoolean(options.default)
2509
+ ? options.default
2510
+ : (!messageCompiler ? () => key : key)
2511
+ : fallbackFormat // default by `fallbackFormat` option
2512
+ ? (!messageCompiler ? () => key : key)
2513
+ : '';
2514
+ const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
2515
+ const locale = isString(options.locale) ? options.locale : context.locale;
2516
+ // escape params
2517
+ escapeParameter && escapeParams(options);
2518
+ // resolve message format
2519
+ // eslint-disable-next-line prefer-const
2520
+ let [formatScope, targetLocale, message] = !resolvedMessage
2521
+ ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
2522
+ : [
2523
+ key,
2524
+ locale,
2525
+ messages[locale] || {}
2526
+ ];
2527
+ // NOTE:
2528
+ // Fix to work around `ssrTransfrom` bug in Vite.
2529
+ // https://github.com/vitejs/vite/issues/4306
2530
+ // To get around this, use temporary variables.
2531
+ // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
2532
+ let format = formatScope;
2533
+ // if you use default message, set it as message format!
2534
+ let cacheBaseKey = key;
2535
+ if (!resolvedMessage &&
2536
+ !(isString(format) ||
2537
+ isMessageAST(format) ||
2538
+ isMessageFunction(format))) {
2539
+ if (enableDefaultMsg) {
2540
+ format = defaultMsgOrKey;
2541
+ cacheBaseKey = format;
2542
+ }
2543
+ }
2544
+ // checking message format and target locale
2545
+ if (!resolvedMessage &&
2546
+ (!(isString(format) ||
2547
+ isMessageAST(format) ||
2548
+ isMessageFunction(format)) ||
2549
+ !isString(targetLocale))) {
2550
+ return unresolving ? NOT_REOSLVED : key;
2551
+ }
2552
+ // TODO: refactor
2553
+ if (isString(format) && context.messageCompiler == null) {
2554
+ warn(`The message format compilation is not supported in this build. ` +
2555
+ `Because message compiler isn't included. ` +
2556
+ `You need to pre-compilation all message format. ` +
2557
+ `So translate function return '${key}'.`);
2558
+ return key;
2559
+ }
2560
+ // setup compile error detecting
2561
+ let occurred = false;
2562
+ const errorDetector = () => {
2563
+ occurred = true;
2564
+ };
2565
+ // compile message format
2566
+ const msg = !isMessageFunction(format)
2567
+ ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
2568
+ : format;
2569
+ // if occurred compile error, return the message format
2570
+ if (occurred) {
2571
+ return format;
2572
+ }
2573
+ // evaluate message with context
2574
+ const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
2575
+ const msgContext = createMessageContext(ctxOptions);
2576
+ const messaged = evaluateMessage(context, msg, msgContext);
2577
+ // if use post translation option, proceed it with handler
2578
+ const ret = postTranslation
2579
+ ? postTranslation(messaged, key)
2580
+ : messaged;
2581
+ // NOTE: experimental !!
2582
+ {
2583
+ // prettier-ignore
2584
+ const payloads = {
2585
+ timestamp: Date.now(),
2586
+ key: isString(key)
2587
+ ? key
2588
+ : isMessageFunction(format)
2589
+ ? format.key
2590
+ : '',
2591
+ locale: targetLocale || (isMessageFunction(format)
2592
+ ? format.locale
2593
+ : ''),
2594
+ format: isString(format)
2595
+ ? format
2596
+ : isMessageFunction(format)
2597
+ ? format.source
2598
+ : '',
2599
+ message: ret
2600
+ };
2601
+ payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
2602
+ translateDevTools(payloads);
2603
+ }
2604
+ return ret;
2605
+ }
2606
+ function escapeParams(options) {
2607
+ if (isArray(options.list)) {
2608
+ options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
2609
+ }
2610
+ else if (isObject(options.named)) {
2611
+ Object.keys(options.named).forEach(key => {
2612
+ if (isString(options.named[key])) {
2613
+ options.named[key] = escapeHtml(options.named[key]);
2614
+ }
2615
+ });
2616
+ }
2617
+ }
2618
+ function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
2619
+ const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
2620
+ const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
2621
+ let message = {};
2622
+ let targetLocale;
2623
+ let format = null;
2624
+ let from = locale;
2625
+ let to = null;
2626
+ const type = 'translate';
2627
+ for (let i = 0; i < locales.length; i++) {
2628
+ targetLocale = to = locales[i];
2629
+ if (locale !== targetLocale &&
2630
+ isTranslateFallbackWarn(fallbackWarn, key)) {
2631
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
2632
+ key,
2633
+ target: targetLocale
2634
+ }));
2635
+ }
2636
+ // for vue-devtools timeline event
2637
+ if (locale !== targetLocale) {
2638
+ const emitter = context.__v_emitter;
2639
+ if (emitter) {
2640
+ emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
2641
+ type,
2642
+ key,
2643
+ from,
2644
+ to,
2645
+ groupId: `${type}:${key}`
2646
+ });
2647
+ }
2648
+ }
2649
+ message =
2650
+ messages[targetLocale] || {};
2651
+ // for vue-devtools timeline event
2652
+ let start = null;
2653
+ let startTag;
2654
+ let endTag;
2655
+ if (inBrowser) {
2656
+ start = window.performance.now();
2657
+ startTag = 'intlify-message-resolve-start';
2658
+ endTag = 'intlify-message-resolve-end';
2659
+ mark && mark(startTag);
2660
+ }
2661
+ if ((format = resolveValue(message, key)) === null) {
2662
+ // if null, resolve with object key path
2663
+ format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
2664
+ }
2665
+ // for vue-devtools timeline event
2666
+ if (inBrowser) {
2667
+ const end = window.performance.now();
2668
+ const emitter = context.__v_emitter;
2669
+ if (emitter && start && format) {
2670
+ emitter.emit("message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */, {
2671
+ type: "message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */,
2672
+ key,
2673
+ message: format,
2674
+ time: end - start,
2675
+ groupId: `${type}:${key}`
2676
+ });
2677
+ }
2678
+ if (startTag && endTag && mark && measure) {
2679
+ mark(endTag);
2680
+ measure('intlify message resolve', startTag, endTag);
2681
+ }
2682
+ }
2683
+ if (isString(format) || isMessageAST(format) || isMessageFunction(format)) {
2684
+ break;
2685
+ }
2686
+ const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
2687
+ key, targetLocale, missingWarn, type);
2688
+ if (missingRet !== key) {
2689
+ format = missingRet;
2690
+ }
2691
+ from = to;
2692
+ }
2693
+ return [format, targetLocale, message];
2694
+ }
2695
+ function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
2696
+ const { messageCompiler, warnHtmlMessage } = context;
2697
+ if (isMessageFunction(format)) {
2698
+ const msg = format;
2699
+ msg.locale = msg.locale || targetLocale;
2700
+ msg.key = msg.key || key;
2701
+ return msg;
2702
+ }
2703
+ if (messageCompiler == null) {
2704
+ const msg = (() => format);
2705
+ msg.locale = targetLocale;
2706
+ msg.key = key;
2707
+ return msg;
2708
+ }
2709
+ // for vue-devtools timeline event
2710
+ let start = null;
2711
+ let startTag;
2712
+ let endTag;
2713
+ if (inBrowser) {
2714
+ start = window.performance.now();
2715
+ startTag = 'intlify-message-compilation-start';
2716
+ endTag = 'intlify-message-compilation-end';
2717
+ mark && mark(startTag);
2718
+ }
2719
+ const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
2720
+ // for vue-devtools timeline event
2721
+ if (inBrowser) {
2722
+ const end = window.performance.now();
2723
+ const emitter = context.__v_emitter;
2724
+ if (emitter && start) {
2725
+ emitter.emit("message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */, {
2726
+ type: "message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */,
2727
+ message: format,
2728
+ time: end - start,
2729
+ groupId: `${'translate'}:${key}`
2730
+ });
2731
+ }
2732
+ if (startTag && endTag && mark && measure) {
2733
+ mark(endTag);
2734
+ measure('intlify message compilation', startTag, endTag);
2735
+ }
2736
+ }
2737
+ msg.locale = targetLocale;
2738
+ msg.key = key;
2739
+ msg.source = format;
2740
+ return msg;
2741
+ }
2742
+ function evaluateMessage(context, msg, msgCtx) {
2743
+ // for vue-devtools timeline event
2744
+ let start = null;
2745
+ let startTag;
2746
+ let endTag;
2747
+ if (inBrowser) {
2748
+ start = window.performance.now();
2749
+ startTag = 'intlify-message-evaluation-start';
2750
+ endTag = 'intlify-message-evaluation-end';
2751
+ mark && mark(startTag);
2752
+ }
2753
+ const messaged = msg(msgCtx);
2754
+ // for vue-devtools timeline event
2755
+ if (inBrowser) {
2756
+ const end = window.performance.now();
2757
+ const emitter = context.__v_emitter;
2758
+ if (emitter && start) {
2759
+ emitter.emit("message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */, {
2760
+ type: "message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */,
2761
+ value: messaged,
2762
+ time: end - start,
2763
+ groupId: `${'translate'}:${msg.key}`
2764
+ });
2765
+ }
2766
+ if (startTag && endTag && mark && measure) {
2767
+ mark(endTag);
2768
+ measure('intlify message evaluation', startTag, endTag);
2769
+ }
2770
+ }
2771
+ return messaged;
2772
+ }
2773
+ /** @internal */
2774
+ function parseTranslateArgs(...args) {
2775
+ const [arg1, arg2, arg3] = args;
2776
+ const options = {};
2777
+ if (!isString(arg1) && !isNumber(arg1) && !isMessageFunction(arg1)) {
2778
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
2779
+ }
2780
+ // prettier-ignore
2781
+ const key = isNumber(arg1)
2782
+ ? String(arg1)
2783
+ : isMessageFunction(arg1)
2784
+ ? arg1
2785
+ : arg1;
2786
+ if (isNumber(arg2)) {
2787
+ options.plural = arg2;
2788
+ }
2789
+ else if (isString(arg2)) {
2790
+ options.default = arg2;
2791
+ }
2792
+ else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
2793
+ options.named = arg2;
2794
+ }
2795
+ else if (isArray(arg2)) {
2796
+ options.list = arg2;
2797
+ }
2798
+ if (isNumber(arg3)) {
2799
+ options.plural = arg3;
2800
+ }
2801
+ else if (isString(arg3)) {
2802
+ options.default = arg3;
2803
+ }
2804
+ else if (isPlainObject(arg3)) {
2805
+ assign(options, arg3);
2806
+ }
2807
+ return [key, options];
2808
+ }
2809
+ function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
2810
+ return {
2811
+ warnHtmlMessage,
2812
+ onError: (err) => {
2813
+ errorDetector && errorDetector(err);
2814
+ {
2815
+ const _source = getSourceForCodeFrame(source);
2816
+ const message = `Message compilation error: ${err.message}`;
2817
+ const codeFrame = err.location &&
2818
+ _source &&
2819
+ generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
2820
+ const emitter = context.__v_emitter;
2821
+ if (emitter && _source) {
2822
+ emitter.emit("compile-error" /* VueDevToolsTimelineEvents.COMPILE_ERROR */, {
2823
+ message: _source,
2824
+ error: err.message,
2825
+ start: err.location && err.location.start.offset,
2826
+ end: err.location && err.location.end.offset,
2827
+ groupId: `${'translate'}:${key}`
2828
+ });
2829
+ }
2830
+ console.error(codeFrame ? `${message}\n${codeFrame}` : message);
2831
+ }
2832
+ },
2833
+ onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
2834
+ };
2835
+ }
2836
+ function getSourceForCodeFrame(source) {
2837
+ if (isString(source)) ;
2838
+ else {
2839
+ if (source.loc?.source) {
2840
+ return source.loc.source;
2841
+ }
2842
+ }
2843
+ }
2844
+ function getMessageContextOptions(context, locale, message, options) {
2845
+ const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
2846
+ const resolveMessage = (key) => {
2847
+ let val = resolveValue(message, key);
2848
+ // fallback to root context
2849
+ if (val == null && fallbackContext) {
2850
+ const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
2851
+ val = resolveValue(message, key);
2852
+ }
2853
+ if (isString(val) || isMessageAST(val)) {
2854
+ let occurred = false;
2855
+ const errorDetector = () => {
2856
+ occurred = true;
2857
+ };
2858
+ const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
2859
+ return !occurred
2860
+ ? msg
2861
+ : NOOP_MESSAGE_FUNCTION;
2862
+ }
2863
+ else if (isMessageFunction(val)) {
2864
+ return val;
2865
+ }
2866
+ else {
2867
+ // TODO: should be implemented warning message
2868
+ return NOOP_MESSAGE_FUNCTION;
2869
+ }
2870
+ };
2871
+ const ctxOptions = {
2872
+ locale,
2873
+ modifiers,
2874
+ pluralRules,
2875
+ messages: resolveMessage
2876
+ };
2877
+ if (context.processor) {
2878
+ ctxOptions.processor = context.processor;
2879
+ }
2880
+ if (options.list) {
2881
+ ctxOptions.list = options.list;
2882
+ }
2883
+ if (options.named) {
2884
+ ctxOptions.named = options.named;
2885
+ }
2886
+ if (isNumber(options.plural)) {
2887
+ ctxOptions.pluralIndex = options.plural;
2888
+ }
2889
+ return ctxOptions;
2890
+ }
2891
+
2892
+ const intlDefined = typeof Intl !== 'undefined';
2893
+ const Availabilities = {
2894
+ dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
2895
+ numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
1386
2896
  };
1387
2897
 
1388
- // implementation of `datetime` function
1389
- function datetime(context, ...args) {
1390
- const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1391
- const { __datetimeFormatters } = context;
1392
- if (!Availabilities.dateTimeFormat) {
1393
- onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
1394
- return MISSING_RESOLVE_VALUE;
1395
- }
1396
- const [key, value, options, overrides] = parseDateTimeArgs(...args);
1397
- const missingWarn = isBoolean(options.missingWarn)
1398
- ? options.missingWarn
1399
- : context.missingWarn;
1400
- const fallbackWarn = isBoolean(options.fallbackWarn)
1401
- ? options.fallbackWarn
1402
- : context.fallbackWarn;
1403
- const part = !!options.part;
1404
- const locale = isString(options.locale) ? options.locale : context.locale;
1405
- const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1406
- fallbackLocale, locale);
1407
- if (!isString(key) || key === '') {
1408
- return new Intl.DateTimeFormat(locale, overrides).format(value);
1409
- }
1410
- // resolve format
1411
- let datetimeFormat = {};
1412
- let targetLocale;
1413
- let format = null;
1414
- let from = locale;
1415
- let to = null;
1416
- const type = 'datetime format';
1417
- for (let i = 0; i < locales.length; i++) {
1418
- targetLocale = to = locales[i];
1419
- if (locale !== targetLocale &&
1420
- isTranslateFallbackWarn(fallbackWarn, key)) {
1421
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
1422
- key,
1423
- target: targetLocale
1424
- }));
1425
- }
1426
- // for vue-devtools timeline event
1427
- if (locale !== targetLocale) {
1428
- const emitter = context.__v_emitter;
1429
- if (emitter) {
1430
- emitter.emit("fallback" /* FALBACK */, {
1431
- type,
1432
- key,
1433
- from,
1434
- to,
1435
- groupId: `${type}:${key}`
1436
- });
1437
- }
1438
- }
1439
- datetimeFormat =
1440
- datetimeFormats[targetLocale] || {};
1441
- format = datetimeFormat[key];
1442
- if (isPlainObject(format))
1443
- break;
1444
- handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1445
- from = to;
1446
- }
1447
- // checking format and target locale
1448
- if (!isPlainObject(format) || !isString(targetLocale)) {
1449
- return unresolving ? NOT_REOSLVED : key;
1450
- }
1451
- let id = `${targetLocale}__${key}`;
1452
- if (!isEmptyObject(overrides)) {
1453
- id = `${id}__${JSON.stringify(overrides)}`;
1454
- }
1455
- let formatter = __datetimeFormatters.get(id);
1456
- if (!formatter) {
1457
- formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
1458
- __datetimeFormatters.set(id, formatter);
1459
- }
1460
- return !part ? formatter.format(value) : formatter.formatToParts(value);
1461
- }
1462
- /** @internal */
1463
- const DATETIME_FORMAT_OPTIONS_KEYS = [
1464
- 'localeMatcher',
1465
- 'weekday',
1466
- 'era',
1467
- 'year',
1468
- 'month',
1469
- 'day',
1470
- 'hour',
1471
- 'minute',
1472
- 'second',
1473
- 'timeZoneName',
1474
- 'formatMatcher',
1475
- 'hour12',
1476
- 'timeZone',
1477
- 'dateStyle',
1478
- 'timeStyle',
1479
- 'calendar',
1480
- 'dayPeriod',
1481
- 'numberingSystem',
1482
- 'hourCycle',
1483
- 'fractionalSecondDigits'
1484
- ];
1485
- /** @internal */
1486
- function parseDateTimeArgs(...args) {
1487
- const [arg1, arg2, arg3, arg4] = args;
1488
- const options = {};
1489
- let overrides = {};
1490
- let value;
1491
- if (isString(arg1)) {
1492
- // Only allow ISO strings - other date formats are often supported,
1493
- // but may cause different results in different browsers.
1494
- const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
1495
- if (!matches) {
1496
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1497
- }
1498
- // Some browsers can not parse the iso datetime separated by space,
1499
- // this is a compromise solution by replace the 'T'/' ' with 'T'
1500
- const dateTime = matches[3]
1501
- ? matches[3].trim().startsWith('T')
1502
- ? `${matches[1].trim()}${matches[3].trim()}`
1503
- : `${matches[1].trim()}T${matches[3].trim()}`
1504
- : matches[1].trim();
1505
- value = new Date(dateTime);
1506
- try {
1507
- // This will fail if the date is not valid
1508
- value.toISOString();
1509
- }
1510
- catch (e) {
1511
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1512
- }
1513
- }
1514
- else if (isDate(arg1)) {
1515
- if (isNaN(arg1.getTime())) {
1516
- throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
1517
- }
1518
- value = arg1;
1519
- }
1520
- else if (isNumber(arg1)) {
1521
- value = arg1;
1522
- }
1523
- else {
1524
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1525
- }
1526
- if (isString(arg2)) {
1527
- options.key = arg2;
1528
- }
1529
- else if (isPlainObject(arg2)) {
1530
- Object.keys(arg2).forEach(key => {
1531
- if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
1532
- overrides[key] = arg2[key];
1533
- }
1534
- else {
1535
- options[key] = arg2[key];
1536
- }
1537
- });
1538
- }
1539
- if (isString(arg3)) {
1540
- options.locale = arg3;
1541
- }
1542
- else if (isPlainObject(arg3)) {
1543
- overrides = arg3;
1544
- }
1545
- if (isPlainObject(arg4)) {
1546
- overrides = arg4;
1547
- }
1548
- return [options.key || '', value, options, overrides];
1549
- }
1550
- /** @internal */
1551
- function clearDateTimeFormat(ctx, locale, format) {
1552
- const context = ctx;
1553
- for (const key in format) {
1554
- const id = `${locale}__${key}`;
1555
- if (!context.__datetimeFormatters.has(id)) {
1556
- continue;
1557
- }
1558
- context.__datetimeFormatters.delete(id);
1559
- }
2898
+ // implementation of `datetime` function
2899
+ function datetime(context, ...args) {
2900
+ const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
2901
+ const { __datetimeFormatters } = context;
2902
+ if (!Availabilities.dateTimeFormat) {
2903
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
2904
+ return MISSING_RESOLVE_VALUE;
2905
+ }
2906
+ const [key, value, options, overrides] = parseDateTimeArgs(...args);
2907
+ const missingWarn = isBoolean(options.missingWarn)
2908
+ ? options.missingWarn
2909
+ : context.missingWarn;
2910
+ const fallbackWarn = isBoolean(options.fallbackWarn)
2911
+ ? options.fallbackWarn
2912
+ : context.fallbackWarn;
2913
+ const part = !!options.part;
2914
+ const locale = isString(options.locale) ? options.locale : context.locale;
2915
+ const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
2916
+ fallbackLocale, locale);
2917
+ if (!isString(key) || key === '') {
2918
+ return new Intl.DateTimeFormat(locale, overrides).format(value);
2919
+ }
2920
+ // resolve format
2921
+ let datetimeFormat = {};
2922
+ let targetLocale;
2923
+ let format = null;
2924
+ let from = locale;
2925
+ let to = null;
2926
+ const type = 'datetime format';
2927
+ for (let i = 0; i < locales.length; i++) {
2928
+ targetLocale = to = locales[i];
2929
+ if (locale !== targetLocale &&
2930
+ isTranslateFallbackWarn(fallbackWarn, key)) {
2931
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
2932
+ key,
2933
+ target: targetLocale
2934
+ }));
2935
+ }
2936
+ // for vue-devtools timeline event
2937
+ if (locale !== targetLocale) {
2938
+ const emitter = context.__v_emitter;
2939
+ if (emitter) {
2940
+ emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
2941
+ type,
2942
+ key,
2943
+ from,
2944
+ to,
2945
+ groupId: `${type}:${key}`
2946
+ });
2947
+ }
2948
+ }
2949
+ datetimeFormat =
2950
+ datetimeFormats[targetLocale] || {};
2951
+ format = datetimeFormat[key];
2952
+ if (isPlainObject(format))
2953
+ break;
2954
+ handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
2955
+ from = to;
2956
+ }
2957
+ // checking format and target locale
2958
+ if (!isPlainObject(format) || !isString(targetLocale)) {
2959
+ return unresolving ? NOT_REOSLVED : key;
2960
+ }
2961
+ let id = `${targetLocale}__${key}`;
2962
+ if (!isEmptyObject(overrides)) {
2963
+ id = `${id}__${JSON.stringify(overrides)}`;
2964
+ }
2965
+ let formatter = __datetimeFormatters.get(id);
2966
+ if (!formatter) {
2967
+ formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
2968
+ __datetimeFormatters.set(id, formatter);
2969
+ }
2970
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
2971
+ }
2972
+ /** @internal */
2973
+ const DATETIME_FORMAT_OPTIONS_KEYS = [
2974
+ 'localeMatcher',
2975
+ 'weekday',
2976
+ 'era',
2977
+ 'year',
2978
+ 'month',
2979
+ 'day',
2980
+ 'hour',
2981
+ 'minute',
2982
+ 'second',
2983
+ 'timeZoneName',
2984
+ 'formatMatcher',
2985
+ 'hour12',
2986
+ 'timeZone',
2987
+ 'dateStyle',
2988
+ 'timeStyle',
2989
+ 'calendar',
2990
+ 'dayPeriod',
2991
+ 'numberingSystem',
2992
+ 'hourCycle',
2993
+ 'fractionalSecondDigits'
2994
+ ];
2995
+ /** @internal */
2996
+ function parseDateTimeArgs(...args) {
2997
+ const [arg1, arg2, arg3, arg4] = args;
2998
+ const options = {};
2999
+ let overrides = {};
3000
+ let value;
3001
+ if (isString(arg1)) {
3002
+ // Only allow ISO strings - other date formats are often supported,
3003
+ // but may cause different results in different browsers.
3004
+ const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
3005
+ if (!matches) {
3006
+ throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
3007
+ }
3008
+ // Some browsers can not parse the iso datetime separated by space,
3009
+ // this is a compromise solution by replace the 'T'/' ' with 'T'
3010
+ const dateTime = matches[3]
3011
+ ? matches[3].trim().startsWith('T')
3012
+ ? `${matches[1].trim()}${matches[3].trim()}`
3013
+ : `${matches[1].trim()}T${matches[3].trim()}`
3014
+ : matches[1].trim();
3015
+ value = new Date(dateTime);
3016
+ try {
3017
+ // This will fail if the date is not valid
3018
+ value.toISOString();
3019
+ }
3020
+ catch (e) {
3021
+ throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
3022
+ }
3023
+ }
3024
+ else if (isDate(arg1)) {
3025
+ if (isNaN(arg1.getTime())) {
3026
+ throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
3027
+ }
3028
+ value = arg1;
3029
+ }
3030
+ else if (isNumber(arg1)) {
3031
+ value = arg1;
3032
+ }
3033
+ else {
3034
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
3035
+ }
3036
+ if (isString(arg2)) {
3037
+ options.key = arg2;
3038
+ }
3039
+ else if (isPlainObject(arg2)) {
3040
+ Object.keys(arg2).forEach(key => {
3041
+ if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
3042
+ overrides[key] = arg2[key];
3043
+ }
3044
+ else {
3045
+ options[key] = arg2[key];
3046
+ }
3047
+ });
3048
+ }
3049
+ if (isString(arg3)) {
3050
+ options.locale = arg3;
3051
+ }
3052
+ else if (isPlainObject(arg3)) {
3053
+ overrides = arg3;
3054
+ }
3055
+ if (isPlainObject(arg4)) {
3056
+ overrides = arg4;
3057
+ }
3058
+ return [options.key || '', value, options, overrides];
3059
+ }
3060
+ /** @internal */
3061
+ function clearDateTimeFormat(ctx, locale, format) {
3062
+ const context = ctx;
3063
+ for (const key in format) {
3064
+ const id = `${locale}__${key}`;
3065
+ if (!context.__datetimeFormatters.has(id)) {
3066
+ continue;
3067
+ }
3068
+ context.__datetimeFormatters.delete(id);
3069
+ }
1560
3070
  }
1561
3071
 
1562
- // implementation of `number` function
1563
- function number(context, ...args) {
1564
- const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1565
- const { __numberFormatters } = context;
1566
- if (!Availabilities.numberFormat) {
1567
- onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
1568
- return MISSING_RESOLVE_VALUE;
1569
- }
1570
- const [key, value, options, overrides] = parseNumberArgs(...args);
1571
- const missingWarn = isBoolean(options.missingWarn)
1572
- ? options.missingWarn
1573
- : context.missingWarn;
1574
- const fallbackWarn = isBoolean(options.fallbackWarn)
1575
- ? options.fallbackWarn
1576
- : context.fallbackWarn;
1577
- const part = !!options.part;
1578
- const locale = isString(options.locale) ? options.locale : context.locale;
1579
- const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1580
- fallbackLocale, locale);
1581
- if (!isString(key) || key === '') {
1582
- return new Intl.NumberFormat(locale, overrides).format(value);
1583
- }
1584
- // resolve format
1585
- let numberFormat = {};
1586
- let targetLocale;
1587
- let format = null;
1588
- let from = locale;
1589
- let to = null;
1590
- const type = 'number format';
1591
- for (let i = 0; i < locales.length; i++) {
1592
- targetLocale = to = locales[i];
1593
- if (locale !== targetLocale &&
1594
- isTranslateFallbackWarn(fallbackWarn, key)) {
1595
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
1596
- key,
1597
- target: targetLocale
1598
- }));
1599
- }
1600
- // for vue-devtools timeline event
1601
- if (locale !== targetLocale) {
1602
- const emitter = context.__v_emitter;
1603
- if (emitter) {
1604
- emitter.emit("fallback" /* FALBACK */, {
1605
- type,
1606
- key,
1607
- from,
1608
- to,
1609
- groupId: `${type}:${key}`
1610
- });
1611
- }
1612
- }
1613
- numberFormat =
1614
- numberFormats[targetLocale] || {};
1615
- format = numberFormat[key];
1616
- if (isPlainObject(format))
1617
- break;
1618
- handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1619
- from = to;
1620
- }
1621
- // checking format and target locale
1622
- if (!isPlainObject(format) || !isString(targetLocale)) {
1623
- return unresolving ? NOT_REOSLVED : key;
1624
- }
1625
- let id = `${targetLocale}__${key}`;
1626
- if (!isEmptyObject(overrides)) {
1627
- id = `${id}__${JSON.stringify(overrides)}`;
1628
- }
1629
- let formatter = __numberFormatters.get(id);
1630
- if (!formatter) {
1631
- formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
1632
- __numberFormatters.set(id, formatter);
1633
- }
1634
- return !part ? formatter.format(value) : formatter.formatToParts(value);
1635
- }
1636
- /** @internal */
1637
- const NUMBER_FORMAT_OPTIONS_KEYS = [
1638
- 'localeMatcher',
1639
- 'style',
1640
- 'currency',
1641
- 'currencyDisplay',
1642
- 'currencySign',
1643
- 'useGrouping',
1644
- 'minimumIntegerDigits',
1645
- 'minimumFractionDigits',
1646
- 'maximumFractionDigits',
1647
- 'minimumSignificantDigits',
1648
- 'maximumSignificantDigits',
1649
- 'compactDisplay',
1650
- 'notation',
1651
- 'signDisplay',
1652
- 'unit',
1653
- 'unitDisplay',
1654
- 'roundingMode',
1655
- 'roundingPriority',
1656
- 'roundingIncrement',
1657
- 'trailingZeroDisplay'
1658
- ];
1659
- /** @internal */
1660
- function parseNumberArgs(...args) {
1661
- const [arg1, arg2, arg3, arg4] = args;
1662
- const options = {};
1663
- let overrides = {};
1664
- if (!isNumber(arg1)) {
1665
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1666
- }
1667
- const value = arg1;
1668
- if (isString(arg2)) {
1669
- options.key = arg2;
1670
- }
1671
- else if (isPlainObject(arg2)) {
1672
- Object.keys(arg2).forEach(key => {
1673
- if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
1674
- overrides[key] = arg2[key];
1675
- }
1676
- else {
1677
- options[key] = arg2[key];
1678
- }
1679
- });
1680
- }
1681
- if (isString(arg3)) {
1682
- options.locale = arg3;
1683
- }
1684
- else if (isPlainObject(arg3)) {
1685
- overrides = arg3;
1686
- }
1687
- if (isPlainObject(arg4)) {
1688
- overrides = arg4;
1689
- }
1690
- return [options.key || '', value, options, overrides];
1691
- }
1692
- /** @internal */
1693
- function clearNumberFormat(ctx, locale, format) {
1694
- const context = ctx;
1695
- for (const key in format) {
1696
- const id = `${locale}__${key}`;
1697
- if (!context.__numberFormatters.has(id)) {
1698
- continue;
1699
- }
1700
- context.__numberFormatters.delete(id);
1701
- }
3072
+ // implementation of `number` function
3073
+ function number(context, ...args) {
3074
+ const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
3075
+ const { __numberFormatters } = context;
3076
+ if (!Availabilities.numberFormat) {
3077
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
3078
+ return MISSING_RESOLVE_VALUE;
3079
+ }
3080
+ const [key, value, options, overrides] = parseNumberArgs(...args);
3081
+ const missingWarn = isBoolean(options.missingWarn)
3082
+ ? options.missingWarn
3083
+ : context.missingWarn;
3084
+ const fallbackWarn = isBoolean(options.fallbackWarn)
3085
+ ? options.fallbackWarn
3086
+ : context.fallbackWarn;
3087
+ const part = !!options.part;
3088
+ const locale = isString(options.locale) ? options.locale : context.locale;
3089
+ const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
3090
+ fallbackLocale, locale);
3091
+ if (!isString(key) || key === '') {
3092
+ return new Intl.NumberFormat(locale, overrides).format(value);
3093
+ }
3094
+ // resolve format
3095
+ let numberFormat = {};
3096
+ let targetLocale;
3097
+ let format = null;
3098
+ let from = locale;
3099
+ let to = null;
3100
+ const type = 'number format';
3101
+ for (let i = 0; i < locales.length; i++) {
3102
+ targetLocale = to = locales[i];
3103
+ if (locale !== targetLocale &&
3104
+ isTranslateFallbackWarn(fallbackWarn, key)) {
3105
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
3106
+ key,
3107
+ target: targetLocale
3108
+ }));
3109
+ }
3110
+ // for vue-devtools timeline event
3111
+ if (locale !== targetLocale) {
3112
+ const emitter = context.__v_emitter;
3113
+ if (emitter) {
3114
+ emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
3115
+ type,
3116
+ key,
3117
+ from,
3118
+ to,
3119
+ groupId: `${type}:${key}`
3120
+ });
3121
+ }
3122
+ }
3123
+ numberFormat =
3124
+ numberFormats[targetLocale] || {};
3125
+ format = numberFormat[key];
3126
+ if (isPlainObject(format))
3127
+ break;
3128
+ handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
3129
+ from = to;
3130
+ }
3131
+ // checking format and target locale
3132
+ if (!isPlainObject(format) || !isString(targetLocale)) {
3133
+ return unresolving ? NOT_REOSLVED : key;
3134
+ }
3135
+ let id = `${targetLocale}__${key}`;
3136
+ if (!isEmptyObject(overrides)) {
3137
+ id = `${id}__${JSON.stringify(overrides)}`;
3138
+ }
3139
+ let formatter = __numberFormatters.get(id);
3140
+ if (!formatter) {
3141
+ formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
3142
+ __numberFormatters.set(id, formatter);
3143
+ }
3144
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
3145
+ }
3146
+ /** @internal */
3147
+ const NUMBER_FORMAT_OPTIONS_KEYS = [
3148
+ 'localeMatcher',
3149
+ 'style',
3150
+ 'currency',
3151
+ 'currencyDisplay',
3152
+ 'currencySign',
3153
+ 'useGrouping',
3154
+ 'minimumIntegerDigits',
3155
+ 'minimumFractionDigits',
3156
+ 'maximumFractionDigits',
3157
+ 'minimumSignificantDigits',
3158
+ 'maximumSignificantDigits',
3159
+ 'compactDisplay',
3160
+ 'notation',
3161
+ 'signDisplay',
3162
+ 'unit',
3163
+ 'unitDisplay',
3164
+ 'roundingMode',
3165
+ 'roundingPriority',
3166
+ 'roundingIncrement',
3167
+ 'trailingZeroDisplay'
3168
+ ];
3169
+ /** @internal */
3170
+ function parseNumberArgs(...args) {
3171
+ const [arg1, arg2, arg3, arg4] = args;
3172
+ const options = {};
3173
+ let overrides = {};
3174
+ if (!isNumber(arg1)) {
3175
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
3176
+ }
3177
+ const value = arg1;
3178
+ if (isString(arg2)) {
3179
+ options.key = arg2;
3180
+ }
3181
+ else if (isPlainObject(arg2)) {
3182
+ Object.keys(arg2).forEach(key => {
3183
+ if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
3184
+ overrides[key] = arg2[key];
3185
+ }
3186
+ else {
3187
+ options[key] = arg2[key];
3188
+ }
3189
+ });
3190
+ }
3191
+ if (isString(arg3)) {
3192
+ options.locale = arg3;
3193
+ }
3194
+ else if (isPlainObject(arg3)) {
3195
+ overrides = arg3;
3196
+ }
3197
+ if (isPlainObject(arg4)) {
3198
+ overrides = arg4;
3199
+ }
3200
+ return [options.key || '', value, options, overrides];
3201
+ }
3202
+ /** @internal */
3203
+ function clearNumberFormat(ctx, locale, format) {
3204
+ const context = ctx;
3205
+ for (const key in format) {
3206
+ const id = `${locale}__${key}`;
3207
+ if (!context.__numberFormatters.has(id)) {
3208
+ continue;
3209
+ }
3210
+ context.__numberFormatters.delete(id);
3211
+ }
1702
3212
  }
1703
3213
 
1704
- // register message resolver at @intlify/core
1705
- registerMessageResolver(resolveValue);
1706
- // register fallback locale at @intlify/core
3214
+ // register message resolver at @intlify/core
3215
+ registerMessageResolver(resolveValue);
3216
+ // register fallback locale at @intlify/core
1707
3217
  registerLocaleFallbacker(fallbackWithLocaleChain);
1708
3218
 
1709
3219
  exports.CompileErrorCodes = CompileErrorCodes;
@@ -1719,6 +3229,7 @@ var IntlifyCore = (function (exports) {
1719
3229
  exports.clearCompileCache = clearCompileCache;
1720
3230
  exports.clearDateTimeFormat = clearDateTimeFormat;
1721
3231
  exports.clearNumberFormat = clearNumberFormat;
3232
+ exports.compile = compile;
1722
3233
  exports.compileToFunction = compileToFunction;
1723
3234
  exports.createCompileError = createCompileError;
1724
3235
  exports.createCoreContext = createCoreContext;
@@ -1733,6 +3244,7 @@ var IntlifyCore = (function (exports) {
1733
3244
  exports.getWarnMessage = getWarnMessage;
1734
3245
  exports.handleMissing = handleMissing;
1735
3246
  exports.initI18nDevTools = initI18nDevTools;
3247
+ exports.isMessageAST = isMessageAST;
1736
3248
  exports.isMessageFunction = isMessageFunction;
1737
3249
  exports.isTranslateFallbackWarn = isTranslateFallbackWarn;
1738
3250
  exports.isTranslateMissingWarn = isTranslateMissingWarn;
@@ -1753,8 +3265,6 @@ var IntlifyCore = (function (exports) {
1753
3265
  exports.translateDevTools = translateDevTools;
1754
3266
  exports.updateFallbackLocale = updateFallbackLocale;
1755
3267
 
1756
- Object.defineProperty(exports, '__esModule', { value: true });
1757
-
1758
3268
  return exports;
1759
3269
 
1760
3270
  })({});