@intlify/core-base 9.3.0-beta.1 → 9.3.0-beta.11

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