@intlify/core 9.2.0-beta.10

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