@intlify/message-compiler 9.3.0-beta.9 → 9.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1586 @@
1
+ /*!
2
+ * message-compiler v9.3.0
3
+ * (c) 2023 kazuya kawaguchi
4
+ * Released under the MIT License.
5
+ */
6
+ import { format, assign, join, isString } from '@intlify/shared';
7
+ import { SourceMapGenerator } from 'source-map-js';
8
+
9
+ const LOCATION_STUB = {
10
+ start: { line: 1, column: 1, offset: 0 },
11
+ end: { line: 1, column: 1, offset: 0 }
12
+ };
13
+ function createPosition(line, column, offset) {
14
+ return { line, column, offset };
15
+ }
16
+ function createLocation(start, end, source) {
17
+ const loc = { start, end };
18
+ if (source != null) {
19
+ loc.source = source;
20
+ }
21
+ return loc;
22
+ }
23
+
24
+ const CompileErrorCodes = {
25
+ // tokenizer error codes
26
+ EXPECTED_TOKEN: 1,
27
+ INVALID_TOKEN_IN_PLACEHOLDER: 2,
28
+ UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
29
+ UNKNOWN_ESCAPE_SEQUENCE: 4,
30
+ INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
31
+ UNBALANCED_CLOSING_BRACE: 6,
32
+ UNTERMINATED_CLOSING_BRACE: 7,
33
+ EMPTY_PLACEHOLDER: 8,
34
+ NOT_ALLOW_NEST_PLACEHOLDER: 9,
35
+ INVALID_LINKED_FORMAT: 10,
36
+ // parser error codes
37
+ MUST_HAVE_MESSAGES_IN_PLURAL: 11,
38
+ UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
39
+ UNEXPECTED_EMPTY_LINKED_KEY: 13,
40
+ UNEXPECTED_LEXICAL_ANALYSIS: 14,
41
+ // generator error codes
42
+ UNHANDLED_CODEGEN_NODE_TYPE: 15,
43
+ // minifier error codes
44
+ UNHANDLED_MINIFIER_NODE_TYPE: 16,
45
+ // Special value for higher-order compilers to pick up the last code
46
+ // to avoid collision of error codes. This should always be kept as the last
47
+ // item.
48
+ __EXTEND_POINT__: 17
49
+ };
50
+ /** @internal */
51
+ const errorMessages = {
52
+ // tokenizer error messages
53
+ [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
54
+ [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
55
+ [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
56
+ [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
57
+ [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
58
+ [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
59
+ [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
60
+ [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
61
+ [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
62
+ [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
63
+ // parser error messages
64
+ [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
65
+ [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
66
+ [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
67
+ [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,
68
+ // generator error messages
69
+ [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,
70
+ // minimizer error messages
71
+ [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`
72
+ };
73
+ function createCompileError(code, loc, options = {}) {
74
+ const { domain, messages, args } = options;
75
+ const msg = (process.env.NODE_ENV !== 'production')
76
+ ? format((messages || errorMessages)[code] || '', ...(args || []))
77
+ : code;
78
+ const error = new SyntaxError(String(msg));
79
+ error.code = code;
80
+ if (loc) {
81
+ error.location = loc;
82
+ }
83
+ error.domain = domain;
84
+ return error;
85
+ }
86
+ /** @internal */
87
+ function defaultOnError(error) {
88
+ throw error;
89
+ }
90
+
91
+ const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
92
+ const detectHtmlTag = (source) => RE_HTML_TAG.test(source);
93
+
94
+ const CHAR_SP = ' ';
95
+ const CHAR_CR = '\r';
96
+ const CHAR_LF = '\n';
97
+ const CHAR_LS = String.fromCharCode(0x2028);
98
+ const CHAR_PS = String.fromCharCode(0x2029);
99
+ function createScanner(str) {
100
+ const _buf = str;
101
+ let _index = 0;
102
+ let _line = 1;
103
+ let _column = 1;
104
+ let _peekOffset = 0;
105
+ const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
106
+ const isLF = (index) => _buf[index] === CHAR_LF;
107
+ const isPS = (index) => _buf[index] === CHAR_PS;
108
+ const isLS = (index) => _buf[index] === CHAR_LS;
109
+ const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
110
+ const index = () => _index;
111
+ const line = () => _line;
112
+ const column = () => _column;
113
+ const peekOffset = () => _peekOffset;
114
+ const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
115
+ const currentChar = () => charAt(_index);
116
+ const currentPeek = () => charAt(_index + _peekOffset);
117
+ function next() {
118
+ _peekOffset = 0;
119
+ if (isLineEnd(_index)) {
120
+ _line++;
121
+ _column = 0;
122
+ }
123
+ if (isCRLF(_index)) {
124
+ _index++;
125
+ }
126
+ _index++;
127
+ _column++;
128
+ return _buf[_index];
129
+ }
130
+ function peek() {
131
+ if (isCRLF(_index + _peekOffset)) {
132
+ _peekOffset++;
133
+ }
134
+ _peekOffset++;
135
+ return _buf[_index + _peekOffset];
136
+ }
137
+ function reset() {
138
+ _index = 0;
139
+ _line = 1;
140
+ _column = 1;
141
+ _peekOffset = 0;
142
+ }
143
+ function resetPeek(offset = 0) {
144
+ _peekOffset = offset;
145
+ }
146
+ function skipToPeek() {
147
+ const target = _index + _peekOffset;
148
+ // eslint-disable-next-line no-unmodified-loop-condition
149
+ while (target !== _index) {
150
+ next();
151
+ }
152
+ _peekOffset = 0;
153
+ }
154
+ return {
155
+ index,
156
+ line,
157
+ column,
158
+ peekOffset,
159
+ charAt,
160
+ currentChar,
161
+ currentPeek,
162
+ next,
163
+ peek,
164
+ reset,
165
+ resetPeek,
166
+ skipToPeek
167
+ };
168
+ }
169
+
170
+ const EOF = undefined;
171
+ const DOT = '.';
172
+ const LITERAL_DELIMITER = "'";
173
+ const ERROR_DOMAIN$3 = 'tokenizer';
174
+ function createTokenizer(source, options = {}) {
175
+ const location = options.location !== false;
176
+ const _scnr = createScanner(source);
177
+ const currentOffset = () => _scnr.index();
178
+ const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
179
+ const _initLoc = currentPosition();
180
+ const _initOffset = currentOffset();
181
+ const _context = {
182
+ currentType: 14 /* TokenTypes.EOF */,
183
+ offset: _initOffset,
184
+ startLoc: _initLoc,
185
+ endLoc: _initLoc,
186
+ lastType: 14 /* TokenTypes.EOF */,
187
+ lastOffset: _initOffset,
188
+ lastStartLoc: _initLoc,
189
+ lastEndLoc: _initLoc,
190
+ braceNest: 0,
191
+ inLinked: false,
192
+ text: ''
193
+ };
194
+ const context = () => _context;
195
+ const { onError } = options;
196
+ function emitError(code, pos, offset, ...args) {
197
+ const ctx = context();
198
+ pos.column += offset;
199
+ pos.offset += offset;
200
+ if (onError) {
201
+ const loc = location ? createLocation(ctx.startLoc, pos) : null;
202
+ const err = createCompileError(code, loc, {
203
+ domain: ERROR_DOMAIN$3,
204
+ args
205
+ });
206
+ onError(err);
207
+ }
208
+ }
209
+ function getToken(context, type, value) {
210
+ context.endLoc = currentPosition();
211
+ context.currentType = type;
212
+ const token = { type };
213
+ if (location) {
214
+ token.loc = createLocation(context.startLoc, context.endLoc);
215
+ }
216
+ if (value != null) {
217
+ token.value = value;
218
+ }
219
+ return token;
220
+ }
221
+ const getEndToken = (context) => getToken(context, 14 /* TokenTypes.EOF */);
222
+ function eat(scnr, ch) {
223
+ if (scnr.currentChar() === ch) {
224
+ scnr.next();
225
+ return ch;
226
+ }
227
+ else {
228
+ emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
229
+ return '';
230
+ }
231
+ }
232
+ function peekSpaces(scnr) {
233
+ let buf = '';
234
+ while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
235
+ buf += scnr.currentPeek();
236
+ scnr.peek();
237
+ }
238
+ return buf;
239
+ }
240
+ function skipSpaces(scnr) {
241
+ const buf = peekSpaces(scnr);
242
+ scnr.skipToPeek();
243
+ return buf;
244
+ }
245
+ function isIdentifierStart(ch) {
246
+ if (ch === EOF) {
247
+ return false;
248
+ }
249
+ const cc = ch.charCodeAt(0);
250
+ return ((cc >= 97 && cc <= 122) || // a-z
251
+ (cc >= 65 && cc <= 90) || // A-Z
252
+ cc === 95 // _
253
+ );
254
+ }
255
+ function isNumberStart(ch) {
256
+ if (ch === EOF) {
257
+ return false;
258
+ }
259
+ const cc = ch.charCodeAt(0);
260
+ return cc >= 48 && cc <= 57; // 0-9
261
+ }
262
+ function isNamedIdentifierStart(scnr, context) {
263
+ const { currentType } = context;
264
+ if (currentType !== 2 /* TokenTypes.BraceLeft */) {
265
+ return false;
266
+ }
267
+ peekSpaces(scnr);
268
+ const ret = isIdentifierStart(scnr.currentPeek());
269
+ scnr.resetPeek();
270
+ return ret;
271
+ }
272
+ function isListIdentifierStart(scnr, context) {
273
+ const { currentType } = context;
274
+ if (currentType !== 2 /* TokenTypes.BraceLeft */) {
275
+ return false;
276
+ }
277
+ peekSpaces(scnr);
278
+ const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
279
+ const ret = isNumberStart(ch);
280
+ scnr.resetPeek();
281
+ return ret;
282
+ }
283
+ function isLiteralStart(scnr, context) {
284
+ const { currentType } = context;
285
+ if (currentType !== 2 /* TokenTypes.BraceLeft */) {
286
+ return false;
287
+ }
288
+ peekSpaces(scnr);
289
+ const ret = scnr.currentPeek() === LITERAL_DELIMITER;
290
+ scnr.resetPeek();
291
+ return ret;
292
+ }
293
+ function isLinkedDotStart(scnr, context) {
294
+ const { currentType } = context;
295
+ if (currentType !== 8 /* TokenTypes.LinkedAlias */) {
296
+ return false;
297
+ }
298
+ peekSpaces(scnr);
299
+ const ret = scnr.currentPeek() === "." /* TokenChars.LinkedDot */;
300
+ scnr.resetPeek();
301
+ return ret;
302
+ }
303
+ function isLinkedModifierStart(scnr, context) {
304
+ const { currentType } = context;
305
+ if (currentType !== 9 /* TokenTypes.LinkedDot */) {
306
+ return false;
307
+ }
308
+ peekSpaces(scnr);
309
+ const ret = isIdentifierStart(scnr.currentPeek());
310
+ scnr.resetPeek();
311
+ return ret;
312
+ }
313
+ function isLinkedDelimiterStart(scnr, context) {
314
+ const { currentType } = context;
315
+ if (!(currentType === 8 /* TokenTypes.LinkedAlias */ ||
316
+ currentType === 12 /* TokenTypes.LinkedModifier */)) {
317
+ return false;
318
+ }
319
+ peekSpaces(scnr);
320
+ const ret = scnr.currentPeek() === ":" /* TokenChars.LinkedDelimiter */;
321
+ scnr.resetPeek();
322
+ return ret;
323
+ }
324
+ function isLinkedReferStart(scnr, context) {
325
+ const { currentType } = context;
326
+ if (currentType !== 10 /* TokenTypes.LinkedDelimiter */) {
327
+ return false;
328
+ }
329
+ const fn = () => {
330
+ const ch = scnr.currentPeek();
331
+ if (ch === "{" /* TokenChars.BraceLeft */) {
332
+ return isIdentifierStart(scnr.peek());
333
+ }
334
+ else if (ch === "@" /* TokenChars.LinkedAlias */ ||
335
+ ch === "%" /* TokenChars.Modulo */ ||
336
+ ch === "|" /* TokenChars.Pipe */ ||
337
+ ch === ":" /* TokenChars.LinkedDelimiter */ ||
338
+ ch === "." /* TokenChars.LinkedDot */ ||
339
+ ch === CHAR_SP ||
340
+ !ch) {
341
+ return false;
342
+ }
343
+ else if (ch === CHAR_LF) {
344
+ scnr.peek();
345
+ return fn();
346
+ }
347
+ else {
348
+ // other characters
349
+ return isIdentifierStart(ch);
350
+ }
351
+ };
352
+ const ret = fn();
353
+ scnr.resetPeek();
354
+ return ret;
355
+ }
356
+ function isPluralStart(scnr) {
357
+ peekSpaces(scnr);
358
+ const ret = scnr.currentPeek() === "|" /* TokenChars.Pipe */;
359
+ scnr.resetPeek();
360
+ return ret;
361
+ }
362
+ function detectModuloStart(scnr) {
363
+ const spaces = peekSpaces(scnr);
364
+ const ret = scnr.currentPeek() === "%" /* TokenChars.Modulo */ &&
365
+ scnr.peek() === "{" /* TokenChars.BraceLeft */;
366
+ scnr.resetPeek();
367
+ return {
368
+ isModulo: ret,
369
+ hasSpace: spaces.length > 0
370
+ };
371
+ }
372
+ function isTextStart(scnr, reset = true) {
373
+ const fn = (hasSpace = false, prev = '', detectModulo = false) => {
374
+ const ch = scnr.currentPeek();
375
+ if (ch === "{" /* TokenChars.BraceLeft */) {
376
+ return prev === "%" /* TokenChars.Modulo */ ? false : hasSpace;
377
+ }
378
+ else if (ch === "@" /* TokenChars.LinkedAlias */ || !ch) {
379
+ return prev === "%" /* TokenChars.Modulo */ ? true : hasSpace;
380
+ }
381
+ else if (ch === "%" /* TokenChars.Modulo */) {
382
+ scnr.peek();
383
+ return fn(hasSpace, "%" /* TokenChars.Modulo */, true);
384
+ }
385
+ else if (ch === "|" /* TokenChars.Pipe */) {
386
+ return prev === "%" /* TokenChars.Modulo */ || detectModulo
387
+ ? true
388
+ : !(prev === CHAR_SP || prev === CHAR_LF);
389
+ }
390
+ else if (ch === CHAR_SP) {
391
+ scnr.peek();
392
+ return fn(true, CHAR_SP, detectModulo);
393
+ }
394
+ else if (ch === CHAR_LF) {
395
+ scnr.peek();
396
+ return fn(true, CHAR_LF, detectModulo);
397
+ }
398
+ else {
399
+ return true;
400
+ }
401
+ };
402
+ const ret = fn();
403
+ reset && scnr.resetPeek();
404
+ return ret;
405
+ }
406
+ function takeChar(scnr, fn) {
407
+ const ch = scnr.currentChar();
408
+ if (ch === EOF) {
409
+ return EOF;
410
+ }
411
+ if (fn(ch)) {
412
+ scnr.next();
413
+ return ch;
414
+ }
415
+ return null;
416
+ }
417
+ function takeIdentifierChar(scnr) {
418
+ const closure = (ch) => {
419
+ const cc = ch.charCodeAt(0);
420
+ return ((cc >= 97 && cc <= 122) || // a-z
421
+ (cc >= 65 && cc <= 90) || // A-Z
422
+ (cc >= 48 && cc <= 57) || // 0-9
423
+ cc === 95 || // _
424
+ cc === 36 // $
425
+ );
426
+ };
427
+ return takeChar(scnr, closure);
428
+ }
429
+ function takeDigit(scnr) {
430
+ const closure = (ch) => {
431
+ const cc = ch.charCodeAt(0);
432
+ return cc >= 48 && cc <= 57; // 0-9
433
+ };
434
+ return takeChar(scnr, closure);
435
+ }
436
+ function takeHexDigit(scnr) {
437
+ const closure = (ch) => {
438
+ const cc = ch.charCodeAt(0);
439
+ return ((cc >= 48 && cc <= 57) || // 0-9
440
+ (cc >= 65 && cc <= 70) || // A-F
441
+ (cc >= 97 && cc <= 102)); // a-f
442
+ };
443
+ return takeChar(scnr, closure);
444
+ }
445
+ function getDigits(scnr) {
446
+ let ch = '';
447
+ let num = '';
448
+ while ((ch = takeDigit(scnr))) {
449
+ num += ch;
450
+ }
451
+ return num;
452
+ }
453
+ function readModulo(scnr) {
454
+ skipSpaces(scnr);
455
+ const ch = scnr.currentChar();
456
+ if (ch !== "%" /* TokenChars.Modulo */) {
457
+ emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
458
+ }
459
+ scnr.next();
460
+ return "%" /* TokenChars.Modulo */;
461
+ }
462
+ function readText(scnr) {
463
+ let buf = '';
464
+ while (true) {
465
+ const ch = scnr.currentChar();
466
+ if (ch === "{" /* TokenChars.BraceLeft */ ||
467
+ ch === "}" /* TokenChars.BraceRight */ ||
468
+ ch === "@" /* TokenChars.LinkedAlias */ ||
469
+ ch === "|" /* TokenChars.Pipe */ ||
470
+ !ch) {
471
+ break;
472
+ }
473
+ else if (ch === "%" /* TokenChars.Modulo */) {
474
+ if (isTextStart(scnr)) {
475
+ buf += ch;
476
+ scnr.next();
477
+ }
478
+ else {
479
+ break;
480
+ }
481
+ }
482
+ else if (ch === CHAR_SP || ch === CHAR_LF) {
483
+ if (isTextStart(scnr)) {
484
+ buf += ch;
485
+ scnr.next();
486
+ }
487
+ else if (isPluralStart(scnr)) {
488
+ break;
489
+ }
490
+ else {
491
+ buf += ch;
492
+ scnr.next();
493
+ }
494
+ }
495
+ else {
496
+ buf += ch;
497
+ scnr.next();
498
+ }
499
+ }
500
+ return buf;
501
+ }
502
+ function readNamedIdentifier(scnr) {
503
+ skipSpaces(scnr);
504
+ let ch = '';
505
+ let name = '';
506
+ while ((ch = takeIdentifierChar(scnr))) {
507
+ name += ch;
508
+ }
509
+ if (scnr.currentChar() === EOF) {
510
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
511
+ }
512
+ return name;
513
+ }
514
+ function readListIdentifier(scnr) {
515
+ skipSpaces(scnr);
516
+ let value = '';
517
+ if (scnr.currentChar() === '-') {
518
+ scnr.next();
519
+ value += `-${getDigits(scnr)}`;
520
+ }
521
+ else {
522
+ value += getDigits(scnr);
523
+ }
524
+ if (scnr.currentChar() === EOF) {
525
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
526
+ }
527
+ return value;
528
+ }
529
+ function readLiteral(scnr) {
530
+ skipSpaces(scnr);
531
+ eat(scnr, `\'`);
532
+ let ch = '';
533
+ let literal = '';
534
+ const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF;
535
+ while ((ch = takeChar(scnr, fn))) {
536
+ if (ch === '\\') {
537
+ literal += readEscapeSequence(scnr);
538
+ }
539
+ else {
540
+ literal += ch;
541
+ }
542
+ }
543
+ const current = scnr.currentChar();
544
+ if (current === CHAR_LF || current === EOF) {
545
+ emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
546
+ // TODO: Is it correct really?
547
+ if (current === CHAR_LF) {
548
+ scnr.next();
549
+ eat(scnr, `\'`);
550
+ }
551
+ return literal;
552
+ }
553
+ eat(scnr, `\'`);
554
+ return literal;
555
+ }
556
+ function readEscapeSequence(scnr) {
557
+ const ch = scnr.currentChar();
558
+ switch (ch) {
559
+ case '\\':
560
+ case `\'`:
561
+ scnr.next();
562
+ return `\\${ch}`;
563
+ case 'u':
564
+ return readUnicodeEscapeSequence(scnr, ch, 4);
565
+ case 'U':
566
+ return readUnicodeEscapeSequence(scnr, ch, 6);
567
+ default:
568
+ emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
569
+ return '';
570
+ }
571
+ }
572
+ function readUnicodeEscapeSequence(scnr, unicode, digits) {
573
+ eat(scnr, unicode);
574
+ let sequence = '';
575
+ for (let i = 0; i < digits; i++) {
576
+ const ch = takeHexDigit(scnr);
577
+ if (!ch) {
578
+ emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
579
+ break;
580
+ }
581
+ sequence += ch;
582
+ }
583
+ return `\\${unicode}${sequence}`;
584
+ }
585
+ function readInvalidIdentifier(scnr) {
586
+ skipSpaces(scnr);
587
+ let ch = '';
588
+ let identifiers = '';
589
+ const closure = (ch) => ch !== "{" /* TokenChars.BraceLeft */ &&
590
+ ch !== "}" /* TokenChars.BraceRight */ &&
591
+ ch !== CHAR_SP &&
592
+ ch !== CHAR_LF;
593
+ while ((ch = takeChar(scnr, closure))) {
594
+ identifiers += ch;
595
+ }
596
+ return identifiers;
597
+ }
598
+ function readLinkedModifier(scnr) {
599
+ let ch = '';
600
+ let name = '';
601
+ while ((ch = takeIdentifierChar(scnr))) {
602
+ name += ch;
603
+ }
604
+ return name;
605
+ }
606
+ function readLinkedRefer(scnr) {
607
+ const fn = (detect = false, buf) => {
608
+ const ch = scnr.currentChar();
609
+ if (ch === "{" /* TokenChars.BraceLeft */ ||
610
+ ch === "%" /* TokenChars.Modulo */ ||
611
+ ch === "@" /* TokenChars.LinkedAlias */ ||
612
+ ch === "|" /* TokenChars.Pipe */ ||
613
+ !ch) {
614
+ return buf;
615
+ }
616
+ else if (ch === CHAR_SP) {
617
+ return buf;
618
+ }
619
+ else if (ch === CHAR_LF || ch === DOT) {
620
+ buf += ch;
621
+ scnr.next();
622
+ return fn(detect, buf);
623
+ }
624
+ else if (!isIdentifierStart(ch)) {
625
+ return buf;
626
+ }
627
+ else {
628
+ buf += ch;
629
+ scnr.next();
630
+ return fn(true, buf);
631
+ }
632
+ };
633
+ return fn(false, '');
634
+ }
635
+ function readPlural(scnr) {
636
+ skipSpaces(scnr);
637
+ const plural = eat(scnr, "|" /* TokenChars.Pipe */);
638
+ skipSpaces(scnr);
639
+ return plural;
640
+ }
641
+ // TODO: We need refactoring of token parsing ...
642
+ function readTokenInPlaceholder(scnr, context) {
643
+ let token = null;
644
+ const ch = scnr.currentChar();
645
+ switch (ch) {
646
+ case "{" /* TokenChars.BraceLeft */:
647
+ if (context.braceNest >= 1) {
648
+ emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
649
+ }
650
+ scnr.next();
651
+ token = getToken(context, 2 /* TokenTypes.BraceLeft */, "{" /* TokenChars.BraceLeft */);
652
+ skipSpaces(scnr);
653
+ context.braceNest++;
654
+ return token;
655
+ case "}" /* TokenChars.BraceRight */:
656
+ if (context.braceNest > 0 &&
657
+ context.currentType === 2 /* TokenTypes.BraceLeft */) {
658
+ emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
659
+ }
660
+ scnr.next();
661
+ token = getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
662
+ context.braceNest--;
663
+ context.braceNest > 0 && skipSpaces(scnr);
664
+ if (context.inLinked && context.braceNest === 0) {
665
+ context.inLinked = false;
666
+ }
667
+ return token;
668
+ case "@" /* TokenChars.LinkedAlias */:
669
+ if (context.braceNest > 0) {
670
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
671
+ }
672
+ token = readTokenInLinked(scnr, context) || getEndToken(context);
673
+ context.braceNest = 0;
674
+ return token;
675
+ default:
676
+ let validNamedIdentifier = true;
677
+ let validListIdentifier = true;
678
+ let validLiteral = true;
679
+ if (isPluralStart(scnr)) {
680
+ if (context.braceNest > 0) {
681
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
682
+ }
683
+ token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
684
+ // reset
685
+ context.braceNest = 0;
686
+ context.inLinked = false;
687
+ return token;
688
+ }
689
+ if (context.braceNest > 0 &&
690
+ (context.currentType === 5 /* TokenTypes.Named */ ||
691
+ context.currentType === 6 /* TokenTypes.List */ ||
692
+ context.currentType === 7 /* TokenTypes.Literal */)) {
693
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
694
+ context.braceNest = 0;
695
+ return readToken(scnr, context);
696
+ }
697
+ if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
698
+ token = getToken(context, 5 /* TokenTypes.Named */, readNamedIdentifier(scnr));
699
+ skipSpaces(scnr);
700
+ return token;
701
+ }
702
+ if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
703
+ token = getToken(context, 6 /* TokenTypes.List */, readListIdentifier(scnr));
704
+ skipSpaces(scnr);
705
+ return token;
706
+ }
707
+ if ((validLiteral = isLiteralStart(scnr, context))) {
708
+ token = getToken(context, 7 /* TokenTypes.Literal */, readLiteral(scnr));
709
+ skipSpaces(scnr);
710
+ return token;
711
+ }
712
+ if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
713
+ // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
714
+ token = getToken(context, 13 /* TokenTypes.InvalidPlace */, readInvalidIdentifier(scnr));
715
+ emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
716
+ skipSpaces(scnr);
717
+ return token;
718
+ }
719
+ break;
720
+ }
721
+ return token;
722
+ }
723
+ // TODO: We need refactoring of token parsing ...
724
+ function readTokenInLinked(scnr, context) {
725
+ const { currentType } = context;
726
+ let token = null;
727
+ const ch = scnr.currentChar();
728
+ if ((currentType === 8 /* TokenTypes.LinkedAlias */ ||
729
+ currentType === 9 /* TokenTypes.LinkedDot */ ||
730
+ currentType === 12 /* TokenTypes.LinkedModifier */ ||
731
+ currentType === 10 /* TokenTypes.LinkedDelimiter */) &&
732
+ (ch === CHAR_LF || ch === CHAR_SP)) {
733
+ emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
734
+ }
735
+ switch (ch) {
736
+ case "@" /* TokenChars.LinkedAlias */:
737
+ scnr.next();
738
+ token = getToken(context, 8 /* TokenTypes.LinkedAlias */, "@" /* TokenChars.LinkedAlias */);
739
+ context.inLinked = true;
740
+ return token;
741
+ case "." /* TokenChars.LinkedDot */:
742
+ skipSpaces(scnr);
743
+ scnr.next();
744
+ return getToken(context, 9 /* TokenTypes.LinkedDot */, "." /* TokenChars.LinkedDot */);
745
+ case ":" /* TokenChars.LinkedDelimiter */:
746
+ skipSpaces(scnr);
747
+ scnr.next();
748
+ return getToken(context, 10 /* TokenTypes.LinkedDelimiter */, ":" /* TokenChars.LinkedDelimiter */);
749
+ default:
750
+ if (isPluralStart(scnr)) {
751
+ token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
752
+ // reset
753
+ context.braceNest = 0;
754
+ context.inLinked = false;
755
+ return token;
756
+ }
757
+ if (isLinkedDotStart(scnr, context) ||
758
+ isLinkedDelimiterStart(scnr, context)) {
759
+ skipSpaces(scnr);
760
+ return readTokenInLinked(scnr, context);
761
+ }
762
+ if (isLinkedModifierStart(scnr, context)) {
763
+ skipSpaces(scnr);
764
+ return getToken(context, 12 /* TokenTypes.LinkedModifier */, readLinkedModifier(scnr));
765
+ }
766
+ if (isLinkedReferStart(scnr, context)) {
767
+ skipSpaces(scnr);
768
+ if (ch === "{" /* TokenChars.BraceLeft */) {
769
+ // scan the placeholder
770
+ return readTokenInPlaceholder(scnr, context) || token;
771
+ }
772
+ else {
773
+ return getToken(context, 11 /* TokenTypes.LinkedKey */, readLinkedRefer(scnr));
774
+ }
775
+ }
776
+ if (currentType === 8 /* TokenTypes.LinkedAlias */) {
777
+ emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
778
+ }
779
+ context.braceNest = 0;
780
+ context.inLinked = false;
781
+ return readToken(scnr, context);
782
+ }
783
+ }
784
+ // TODO: We need refactoring of token parsing ...
785
+ function readToken(scnr, context) {
786
+ let token = { type: 14 /* TokenTypes.EOF */ };
787
+ if (context.braceNest > 0) {
788
+ return readTokenInPlaceholder(scnr, context) || getEndToken(context);
789
+ }
790
+ if (context.inLinked) {
791
+ return readTokenInLinked(scnr, context) || getEndToken(context);
792
+ }
793
+ const ch = scnr.currentChar();
794
+ switch (ch) {
795
+ case "{" /* TokenChars.BraceLeft */:
796
+ return readTokenInPlaceholder(scnr, context) || getEndToken(context);
797
+ case "}" /* TokenChars.BraceRight */:
798
+ emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
799
+ scnr.next();
800
+ return getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
801
+ case "@" /* TokenChars.LinkedAlias */:
802
+ return readTokenInLinked(scnr, context) || getEndToken(context);
803
+ default:
804
+ if (isPluralStart(scnr)) {
805
+ token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
806
+ // reset
807
+ context.braceNest = 0;
808
+ context.inLinked = false;
809
+ return token;
810
+ }
811
+ const { isModulo, hasSpace } = detectModuloStart(scnr);
812
+ if (isModulo) {
813
+ return hasSpace
814
+ ? getToken(context, 0 /* TokenTypes.Text */, readText(scnr))
815
+ : getToken(context, 4 /* TokenTypes.Modulo */, readModulo(scnr));
816
+ }
817
+ if (isTextStart(scnr)) {
818
+ return getToken(context, 0 /* TokenTypes.Text */, readText(scnr));
819
+ }
820
+ break;
821
+ }
822
+ return token;
823
+ }
824
+ function nextToken() {
825
+ const { currentType, offset, startLoc, endLoc } = _context;
826
+ _context.lastType = currentType;
827
+ _context.lastOffset = offset;
828
+ _context.lastStartLoc = startLoc;
829
+ _context.lastEndLoc = endLoc;
830
+ _context.offset = currentOffset();
831
+ _context.startLoc = currentPosition();
832
+ if (_scnr.currentChar() === EOF) {
833
+ return getToken(_context, 14 /* TokenTypes.EOF */);
834
+ }
835
+ return readToken(_scnr, _context);
836
+ }
837
+ return {
838
+ nextToken,
839
+ currentOffset,
840
+ currentPosition,
841
+ context
842
+ };
843
+ }
844
+
845
+ const ERROR_DOMAIN$2 = 'parser';
846
+ // Backslash backslash, backslash quote, uHHHH, UHHHHHH.
847
+ const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
848
+ function fromEscapeSequence(match, codePoint4, codePoint6) {
849
+ switch (match) {
850
+ case `\\\\`:
851
+ return `\\`;
852
+ case `\\\'`:
853
+ return `\'`;
854
+ default: {
855
+ const codePoint = parseInt(codePoint4 || codePoint6, 16);
856
+ if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
857
+ return String.fromCodePoint(codePoint);
858
+ }
859
+ // invalid ...
860
+ // Replace them with U+FFFD REPLACEMENT CHARACTER.
861
+ return '�';
862
+ }
863
+ }
864
+ }
865
+ function createParser(options = {}) {
866
+ const location = options.location !== false;
867
+ const { onError } = options;
868
+ function emitError(tokenzer, code, start, offset, ...args) {
869
+ const end = tokenzer.currentPosition();
870
+ end.offset += offset;
871
+ end.column += offset;
872
+ if (onError) {
873
+ const loc = location ? createLocation(start, end) : null;
874
+ const err = createCompileError(code, loc, {
875
+ domain: ERROR_DOMAIN$2,
876
+ args
877
+ });
878
+ onError(err);
879
+ }
880
+ }
881
+ function startNode(type, offset, loc) {
882
+ const node = { type };
883
+ if (location) {
884
+ node.start = offset;
885
+ node.end = offset;
886
+ node.loc = { start: loc, end: loc };
887
+ }
888
+ return node;
889
+ }
890
+ function endNode(node, offset, pos, type) {
891
+ if (type) {
892
+ node.type = type;
893
+ }
894
+ if (location) {
895
+ node.end = offset;
896
+ if (node.loc) {
897
+ node.loc.end = pos;
898
+ }
899
+ }
900
+ }
901
+ function parseText(tokenizer, value) {
902
+ const context = tokenizer.context();
903
+ const node = startNode(3 /* NodeTypes.Text */, context.offset, context.startLoc);
904
+ node.value = value;
905
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
906
+ return node;
907
+ }
908
+ function parseList(tokenizer, index) {
909
+ const context = tokenizer.context();
910
+ const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
911
+ const node = startNode(5 /* NodeTypes.List */, offset, loc);
912
+ node.index = parseInt(index, 10);
913
+ tokenizer.nextToken(); // skip brach right
914
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
915
+ return node;
916
+ }
917
+ function parseNamed(tokenizer, key) {
918
+ const context = tokenizer.context();
919
+ const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
920
+ const node = startNode(4 /* NodeTypes.Named */, offset, loc);
921
+ node.key = key;
922
+ tokenizer.nextToken(); // skip brach right
923
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
924
+ return node;
925
+ }
926
+ function parseLiteral(tokenizer, value) {
927
+ const context = tokenizer.context();
928
+ const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
929
+ const node = startNode(9 /* NodeTypes.Literal */, offset, loc);
930
+ node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
931
+ tokenizer.nextToken(); // skip brach right
932
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
933
+ return node;
934
+ }
935
+ function parseLinkedModifier(tokenizer) {
936
+ const token = tokenizer.nextToken();
937
+ const context = tokenizer.context();
938
+ const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
939
+ const node = startNode(8 /* NodeTypes.LinkedModifier */, offset, loc);
940
+ if (token.type !== 12 /* TokenTypes.LinkedModifier */) {
941
+ // empty modifier
942
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
943
+ node.value = '';
944
+ endNode(node, offset, loc);
945
+ return {
946
+ nextConsumeToken: token,
947
+ node
948
+ };
949
+ }
950
+ // check token
951
+ if (token.value == null) {
952
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
953
+ }
954
+ node.value = token.value || '';
955
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
956
+ return {
957
+ node
958
+ };
959
+ }
960
+ function parseLinkedKey(tokenizer, value) {
961
+ const context = tokenizer.context();
962
+ const node = startNode(7 /* NodeTypes.LinkedKey */, context.offset, context.startLoc);
963
+ node.value = value;
964
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
965
+ return node;
966
+ }
967
+ function parseLinked(tokenizer) {
968
+ const context = tokenizer.context();
969
+ const linkedNode = startNode(6 /* NodeTypes.Linked */, context.offset, context.startLoc);
970
+ let token = tokenizer.nextToken();
971
+ if (token.type === 9 /* TokenTypes.LinkedDot */) {
972
+ const parsed = parseLinkedModifier(tokenizer);
973
+ linkedNode.modifier = parsed.node;
974
+ token = parsed.nextConsumeToken || tokenizer.nextToken();
975
+ }
976
+ // asset check token
977
+ if (token.type !== 10 /* TokenTypes.LinkedDelimiter */) {
978
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
979
+ }
980
+ token = tokenizer.nextToken();
981
+ // skip brace left
982
+ if (token.type === 2 /* TokenTypes.BraceLeft */) {
983
+ token = tokenizer.nextToken();
984
+ }
985
+ switch (token.type) {
986
+ case 11 /* TokenTypes.LinkedKey */:
987
+ if (token.value == null) {
988
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
989
+ }
990
+ linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
991
+ break;
992
+ case 5 /* TokenTypes.Named */:
993
+ if (token.value == null) {
994
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
995
+ }
996
+ linkedNode.key = parseNamed(tokenizer, token.value || '');
997
+ break;
998
+ case 6 /* TokenTypes.List */:
999
+ if (token.value == null) {
1000
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1001
+ }
1002
+ linkedNode.key = parseList(tokenizer, token.value || '');
1003
+ break;
1004
+ case 7 /* TokenTypes.Literal */:
1005
+ if (token.value == null) {
1006
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1007
+ }
1008
+ linkedNode.key = parseLiteral(tokenizer, token.value || '');
1009
+ break;
1010
+ default:
1011
+ // empty key
1012
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
1013
+ const nextContext = tokenizer.context();
1014
+ const emptyLinkedKeyNode = startNode(7 /* NodeTypes.LinkedKey */, nextContext.offset, nextContext.startLoc);
1015
+ emptyLinkedKeyNode.value = '';
1016
+ endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
1017
+ linkedNode.key = emptyLinkedKeyNode;
1018
+ endNode(linkedNode, nextContext.offset, nextContext.startLoc);
1019
+ return {
1020
+ nextConsumeToken: token,
1021
+ node: linkedNode
1022
+ };
1023
+ }
1024
+ endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
1025
+ return {
1026
+ node: linkedNode
1027
+ };
1028
+ }
1029
+ function parseMessage(tokenizer) {
1030
+ const context = tokenizer.context();
1031
+ const startOffset = context.currentType === 1 /* TokenTypes.Pipe */
1032
+ ? tokenizer.currentOffset()
1033
+ : context.offset;
1034
+ const startLoc = context.currentType === 1 /* TokenTypes.Pipe */
1035
+ ? context.endLoc
1036
+ : context.startLoc;
1037
+ const node = startNode(2 /* NodeTypes.Message */, startOffset, startLoc);
1038
+ node.items = [];
1039
+ let nextToken = null;
1040
+ do {
1041
+ const token = nextToken || tokenizer.nextToken();
1042
+ nextToken = null;
1043
+ switch (token.type) {
1044
+ case 0 /* TokenTypes.Text */:
1045
+ if (token.value == null) {
1046
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1047
+ }
1048
+ node.items.push(parseText(tokenizer, token.value || ''));
1049
+ break;
1050
+ case 6 /* TokenTypes.List */:
1051
+ if (token.value == null) {
1052
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1053
+ }
1054
+ node.items.push(parseList(tokenizer, token.value || ''));
1055
+ break;
1056
+ case 5 /* TokenTypes.Named */:
1057
+ if (token.value == null) {
1058
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1059
+ }
1060
+ node.items.push(parseNamed(tokenizer, token.value || ''));
1061
+ break;
1062
+ case 7 /* TokenTypes.Literal */:
1063
+ if (token.value == null) {
1064
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1065
+ }
1066
+ node.items.push(parseLiteral(tokenizer, token.value || ''));
1067
+ break;
1068
+ case 8 /* TokenTypes.LinkedAlias */:
1069
+ const parsed = parseLinked(tokenizer);
1070
+ node.items.push(parsed.node);
1071
+ nextToken = parsed.nextConsumeToken || null;
1072
+ break;
1073
+ }
1074
+ } while (context.currentType !== 14 /* TokenTypes.EOF */ &&
1075
+ context.currentType !== 1 /* TokenTypes.Pipe */);
1076
+ // adjust message node loc
1077
+ const endOffset = context.currentType === 1 /* TokenTypes.Pipe */
1078
+ ? context.lastOffset
1079
+ : tokenizer.currentOffset();
1080
+ const endLoc = context.currentType === 1 /* TokenTypes.Pipe */
1081
+ ? context.lastEndLoc
1082
+ : tokenizer.currentPosition();
1083
+ endNode(node, endOffset, endLoc);
1084
+ return node;
1085
+ }
1086
+ function parsePlural(tokenizer, offset, loc, msgNode) {
1087
+ const context = tokenizer.context();
1088
+ let hasEmptyMessage = msgNode.items.length === 0;
1089
+ const node = startNode(1 /* NodeTypes.Plural */, offset, loc);
1090
+ node.cases = [];
1091
+ node.cases.push(msgNode);
1092
+ do {
1093
+ const msg = parseMessage(tokenizer);
1094
+ if (!hasEmptyMessage) {
1095
+ hasEmptyMessage = msg.items.length === 0;
1096
+ }
1097
+ node.cases.push(msg);
1098
+ } while (context.currentType !== 14 /* TokenTypes.EOF */);
1099
+ if (hasEmptyMessage) {
1100
+ emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
1101
+ }
1102
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1103
+ return node;
1104
+ }
1105
+ function parseResource(tokenizer) {
1106
+ const context = tokenizer.context();
1107
+ const { offset, startLoc } = context;
1108
+ const msgNode = parseMessage(tokenizer);
1109
+ if (context.currentType === 14 /* TokenTypes.EOF */) {
1110
+ return msgNode;
1111
+ }
1112
+ else {
1113
+ return parsePlural(tokenizer, offset, startLoc, msgNode);
1114
+ }
1115
+ }
1116
+ function parse(source) {
1117
+ const tokenizer = createTokenizer(source, assign({}, options));
1118
+ const context = tokenizer.context();
1119
+ const node = startNode(0 /* NodeTypes.Resource */, context.offset, context.startLoc);
1120
+ if (location && node.loc) {
1121
+ node.loc.source = source;
1122
+ }
1123
+ node.body = parseResource(tokenizer);
1124
+ if (options.onCacheKey) {
1125
+ node.cacheKey = options.onCacheKey(source);
1126
+ }
1127
+ // assert whether achieved to EOF
1128
+ if (context.currentType !== 14 /* TokenTypes.EOF */) {
1129
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');
1130
+ }
1131
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1132
+ return node;
1133
+ }
1134
+ return { parse };
1135
+ }
1136
+ function getTokenCaption(token) {
1137
+ if (token.type === 14 /* TokenTypes.EOF */) {
1138
+ return 'EOF';
1139
+ }
1140
+ const name = (token.value || '').replace(/\r?\n/gu, '\\n');
1141
+ return name.length > 10 ? name.slice(0, 9) + '…' : name;
1142
+ }
1143
+
1144
+ function createTransformer(ast, options = {} // eslint-disable-line
1145
+ ) {
1146
+ const _context = {
1147
+ ast,
1148
+ helpers: new Set()
1149
+ };
1150
+ const context = () => _context;
1151
+ const helper = (name) => {
1152
+ _context.helpers.add(name);
1153
+ return name;
1154
+ };
1155
+ return { context, helper };
1156
+ }
1157
+ function traverseNodes(nodes, transformer) {
1158
+ for (let i = 0; i < nodes.length; i++) {
1159
+ traverseNode(nodes[i], transformer);
1160
+ }
1161
+ }
1162
+ function traverseNode(node, transformer) {
1163
+ // TODO: if we need pre-hook of transform, should be implemented to here
1164
+ switch (node.type) {
1165
+ case 1 /* NodeTypes.Plural */:
1166
+ traverseNodes(node.cases, transformer);
1167
+ transformer.helper("plural" /* HelperNameMap.PLURAL */);
1168
+ break;
1169
+ case 2 /* NodeTypes.Message */:
1170
+ traverseNodes(node.items, transformer);
1171
+ break;
1172
+ case 6 /* NodeTypes.Linked */:
1173
+ const linked = node;
1174
+ traverseNode(linked.key, transformer);
1175
+ transformer.helper("linked" /* HelperNameMap.LINKED */);
1176
+ transformer.helper("type" /* HelperNameMap.TYPE */);
1177
+ break;
1178
+ case 5 /* NodeTypes.List */:
1179
+ transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
1180
+ transformer.helper("list" /* HelperNameMap.LIST */);
1181
+ break;
1182
+ case 4 /* NodeTypes.Named */:
1183
+ transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
1184
+ transformer.helper("named" /* HelperNameMap.NAMED */);
1185
+ break;
1186
+ }
1187
+ // TODO: if we need post-hook of transform, should be implemented to here
1188
+ }
1189
+ // transform AST
1190
+ function transform(ast, options = {} // eslint-disable-line
1191
+ ) {
1192
+ const transformer = createTransformer(ast);
1193
+ transformer.helper("normalize" /* HelperNameMap.NORMALIZE */);
1194
+ // traverse
1195
+ ast.body && traverseNode(ast.body, transformer);
1196
+ // set meta information
1197
+ const context = transformer.context();
1198
+ ast.helpers = Array.from(context.helpers);
1199
+ }
1200
+
1201
+ function optimize(ast) {
1202
+ const body = ast.body;
1203
+ if (body.type === 2 /* NodeTypes.Message */) {
1204
+ optimizeMessageNode(body);
1205
+ }
1206
+ else {
1207
+ body.cases.forEach(c => optimizeMessageNode(c));
1208
+ }
1209
+ return ast;
1210
+ }
1211
+ function optimizeMessageNode(message) {
1212
+ if (message.items.length === 1) {
1213
+ const item = message.items[0];
1214
+ if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
1215
+ message.static = item.value;
1216
+ delete item.value; // optimization for size
1217
+ }
1218
+ }
1219
+ else {
1220
+ const values = [];
1221
+ for (let i = 0; i < message.items.length; i++) {
1222
+ const item = message.items[i];
1223
+ if (!(item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */)) {
1224
+ break;
1225
+ }
1226
+ if (item.value == null) {
1227
+ break;
1228
+ }
1229
+ values.push(item.value);
1230
+ }
1231
+ if (values.length === message.items.length) {
1232
+ message.static = join(values);
1233
+ for (let i = 0; i < message.items.length; i++) {
1234
+ const item = message.items[i];
1235
+ if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
1236
+ delete item.value; // optimization for size
1237
+ }
1238
+ }
1239
+ }
1240
+ }
1241
+ }
1242
+
1243
+ const ERROR_DOMAIN$1 = 'minifier';
1244
+ /* eslint-disable @typescript-eslint/no-explicit-any */
1245
+ function minify(node) {
1246
+ node.t = node.type;
1247
+ switch (node.type) {
1248
+ case 0 /* NodeTypes.Resource */:
1249
+ const resource = node;
1250
+ minify(resource.body);
1251
+ resource.b = resource.body;
1252
+ delete resource.body;
1253
+ break;
1254
+ case 1 /* NodeTypes.Plural */:
1255
+ const plural = node;
1256
+ const cases = plural.cases;
1257
+ for (let i = 0; i < cases.length; i++) {
1258
+ minify(cases[i]);
1259
+ }
1260
+ plural.c = cases;
1261
+ delete plural.cases;
1262
+ break;
1263
+ case 2 /* NodeTypes.Message */:
1264
+ const message = node;
1265
+ const items = message.items;
1266
+ for (let i = 0; i < items.length; i++) {
1267
+ minify(items[i]);
1268
+ }
1269
+ message.i = items;
1270
+ delete message.items;
1271
+ if (message.static) {
1272
+ message.s = message.static;
1273
+ delete message.static;
1274
+ }
1275
+ break;
1276
+ case 3 /* NodeTypes.Text */:
1277
+ case 9 /* NodeTypes.Literal */:
1278
+ case 8 /* NodeTypes.LinkedModifier */:
1279
+ case 7 /* NodeTypes.LinkedKey */:
1280
+ const valueNode = node;
1281
+ if (valueNode.value) {
1282
+ valueNode.v = valueNode.value;
1283
+ delete valueNode.value;
1284
+ }
1285
+ break;
1286
+ case 6 /* NodeTypes.Linked */:
1287
+ const linked = node;
1288
+ minify(linked.key);
1289
+ linked.k = linked.key;
1290
+ delete linked.key;
1291
+ if (linked.modifier) {
1292
+ minify(linked.modifier);
1293
+ linked.m = linked.modifier;
1294
+ delete linked.modifier;
1295
+ }
1296
+ break;
1297
+ case 5 /* NodeTypes.List */:
1298
+ const list = node;
1299
+ list.i = list.index;
1300
+ delete list.index;
1301
+ break;
1302
+ case 4 /* NodeTypes.Named */:
1303
+ const named = node;
1304
+ named.k = named.key;
1305
+ delete named.key;
1306
+ break;
1307
+ default:
1308
+ if ((process.env.NODE_ENV !== 'production')) {
1309
+ throw createCompileError(CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE, null, {
1310
+ domain: ERROR_DOMAIN$1,
1311
+ args: [node.type]
1312
+ });
1313
+ }
1314
+ }
1315
+ delete node.type;
1316
+ }
1317
+ /* eslint-enable @typescript-eslint/no-explicit-any */
1318
+
1319
+ const ERROR_DOMAIN = 'parser';
1320
+ function createCodeGenerator(ast, options) {
1321
+ const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
1322
+ const location = options.location !== false;
1323
+ const _context = {
1324
+ filename,
1325
+ code: '',
1326
+ column: 1,
1327
+ line: 1,
1328
+ offset: 0,
1329
+ map: undefined,
1330
+ breakLineCode,
1331
+ needIndent: _needIndent,
1332
+ indentLevel: 0
1333
+ };
1334
+ if (location && ast.loc) {
1335
+ _context.source = ast.loc.source;
1336
+ }
1337
+ const context = () => _context;
1338
+ function push(code, node) {
1339
+ _context.code += code;
1340
+ if (_context.map) {
1341
+ if (node && node.loc && node.loc !== LOCATION_STUB) {
1342
+ addMapping(node.loc.start, getMappingName(node));
1343
+ }
1344
+ advancePositionWithSource(_context, code);
1345
+ }
1346
+ }
1347
+ function _newline(n, withBreakLine = true) {
1348
+ const _breakLineCode = withBreakLine ? breakLineCode : '';
1349
+ push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
1350
+ }
1351
+ function indent(withNewLine = true) {
1352
+ const level = ++_context.indentLevel;
1353
+ withNewLine && _newline(level);
1354
+ }
1355
+ function deindent(withNewLine = true) {
1356
+ const level = --_context.indentLevel;
1357
+ withNewLine && _newline(level);
1358
+ }
1359
+ function newline() {
1360
+ _newline(_context.indentLevel);
1361
+ }
1362
+ const helper = (key) => `_${key}`;
1363
+ const needIndent = () => _context.needIndent;
1364
+ function addMapping(loc, name) {
1365
+ _context.map.addMapping({
1366
+ name,
1367
+ source: _context.filename,
1368
+ original: {
1369
+ line: loc.line,
1370
+ column: loc.column - 1
1371
+ },
1372
+ generated: {
1373
+ line: _context.line,
1374
+ column: _context.column - 1
1375
+ }
1376
+ });
1377
+ }
1378
+ if (location && sourceMap) {
1379
+ _context.map = new SourceMapGenerator();
1380
+ _context.map.setSourceContent(filename, _context.source);
1381
+ }
1382
+ return {
1383
+ context,
1384
+ push,
1385
+ indent,
1386
+ deindent,
1387
+ newline,
1388
+ helper,
1389
+ needIndent
1390
+ };
1391
+ }
1392
+ function generateLinkedNode(generator, node) {
1393
+ const { helper } = generator;
1394
+ generator.push(`${helper("linked" /* HelperNameMap.LINKED */)}(`);
1395
+ generateNode(generator, node.key);
1396
+ if (node.modifier) {
1397
+ generator.push(`, `);
1398
+ generateNode(generator, node.modifier);
1399
+ generator.push(`, _type`);
1400
+ }
1401
+ else {
1402
+ generator.push(`, undefined, _type`);
1403
+ }
1404
+ generator.push(`)`);
1405
+ }
1406
+ function generateMessageNode(generator, node) {
1407
+ const { helper, needIndent } = generator;
1408
+ generator.push(`${helper("normalize" /* HelperNameMap.NORMALIZE */)}([`);
1409
+ generator.indent(needIndent());
1410
+ const length = node.items.length;
1411
+ for (let i = 0; i < length; i++) {
1412
+ generateNode(generator, node.items[i]);
1413
+ if (i === length - 1) {
1414
+ break;
1415
+ }
1416
+ generator.push(', ');
1417
+ }
1418
+ generator.deindent(needIndent());
1419
+ generator.push('])');
1420
+ }
1421
+ function generatePluralNode(generator, node) {
1422
+ const { helper, needIndent } = generator;
1423
+ if (node.cases.length > 1) {
1424
+ generator.push(`${helper("plural" /* HelperNameMap.PLURAL */)}([`);
1425
+ generator.indent(needIndent());
1426
+ const length = node.cases.length;
1427
+ for (let i = 0; i < length; i++) {
1428
+ generateNode(generator, node.cases[i]);
1429
+ if (i === length - 1) {
1430
+ break;
1431
+ }
1432
+ generator.push(', ');
1433
+ }
1434
+ generator.deindent(needIndent());
1435
+ generator.push(`])`);
1436
+ }
1437
+ }
1438
+ function generateResource(generator, node) {
1439
+ if (node.body) {
1440
+ generateNode(generator, node.body);
1441
+ }
1442
+ else {
1443
+ generator.push('null');
1444
+ }
1445
+ }
1446
+ function generateNode(generator, node) {
1447
+ const { helper } = generator;
1448
+ switch (node.type) {
1449
+ case 0 /* NodeTypes.Resource */:
1450
+ generateResource(generator, node);
1451
+ break;
1452
+ case 1 /* NodeTypes.Plural */:
1453
+ generatePluralNode(generator, node);
1454
+ break;
1455
+ case 2 /* NodeTypes.Message */:
1456
+ generateMessageNode(generator, node);
1457
+ break;
1458
+ case 6 /* NodeTypes.Linked */:
1459
+ generateLinkedNode(generator, node);
1460
+ break;
1461
+ case 8 /* NodeTypes.LinkedModifier */:
1462
+ generator.push(JSON.stringify(node.value), node);
1463
+ break;
1464
+ case 7 /* NodeTypes.LinkedKey */:
1465
+ generator.push(JSON.stringify(node.value), node);
1466
+ break;
1467
+ case 5 /* NodeTypes.List */:
1468
+ generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("list" /* HelperNameMap.LIST */)}(${node.index}))`, node);
1469
+ break;
1470
+ case 4 /* NodeTypes.Named */:
1471
+ generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("named" /* HelperNameMap.NAMED */)}(${JSON.stringify(node.key)}))`, node);
1472
+ break;
1473
+ case 9 /* NodeTypes.Literal */:
1474
+ generator.push(JSON.stringify(node.value), node);
1475
+ break;
1476
+ case 3 /* NodeTypes.Text */:
1477
+ generator.push(JSON.stringify(node.value), node);
1478
+ break;
1479
+ default:
1480
+ if ((process.env.NODE_ENV !== 'production')) {
1481
+ throw createCompileError(CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE, null, {
1482
+ domain: ERROR_DOMAIN,
1483
+ args: [node.type]
1484
+ });
1485
+ }
1486
+ }
1487
+ }
1488
+ // generate code from AST
1489
+ const generate = (ast, options = {} // eslint-disable-line
1490
+ ) => {
1491
+ const mode = isString(options.mode) ? options.mode : 'normal';
1492
+ const filename = isString(options.filename)
1493
+ ? options.filename
1494
+ : 'message.intl';
1495
+ const sourceMap = !!options.sourceMap;
1496
+ // prettier-ignore
1497
+ const breakLineCode = options.breakLineCode != null
1498
+ ? options.breakLineCode
1499
+ : mode === 'arrow'
1500
+ ? ';'
1501
+ : '\n';
1502
+ const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
1503
+ const helpers = ast.helpers || [];
1504
+ const generator = createCodeGenerator(ast, {
1505
+ mode,
1506
+ filename,
1507
+ sourceMap,
1508
+ breakLineCode,
1509
+ needIndent
1510
+ });
1511
+ generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
1512
+ generator.indent(needIndent);
1513
+ if (helpers.length > 0) {
1514
+ generator.push(`const { ${join(helpers.map(s => `${s}: _${s}`), ', ')} } = ctx`);
1515
+ generator.newline();
1516
+ }
1517
+ generator.push(`return `);
1518
+ generateNode(generator, ast);
1519
+ generator.deindent(needIndent);
1520
+ generator.push(`}`);
1521
+ delete ast.helpers;
1522
+ const { code, map } = generator.context();
1523
+ return {
1524
+ ast,
1525
+ code,
1526
+ map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
1527
+ };
1528
+ };
1529
+ function getMappingName(node) {
1530
+ switch (node.type) {
1531
+ case 3 /* NodeTypes.Text */:
1532
+ case 9 /* NodeTypes.Literal */:
1533
+ case 8 /* NodeTypes.LinkedModifier */:
1534
+ case 7 /* NodeTypes.LinkedKey */:
1535
+ return node.value;
1536
+ case 5 /* NodeTypes.List */:
1537
+ return node.index.toString();
1538
+ case 4 /* NodeTypes.Named */:
1539
+ return node.key;
1540
+ default:
1541
+ return undefined;
1542
+ }
1543
+ }
1544
+ function advancePositionWithSource(pos, source, numberOfCharacters = source.length) {
1545
+ let linesCount = 0;
1546
+ let lastNewLinePos = -1;
1547
+ for (let i = 0; i < numberOfCharacters; i++) {
1548
+ if (source.charCodeAt(i) === 10 /* newline char code */) {
1549
+ linesCount++;
1550
+ lastNewLinePos = i;
1551
+ }
1552
+ }
1553
+ pos.offset += numberOfCharacters;
1554
+ pos.line += linesCount;
1555
+ pos.column =
1556
+ lastNewLinePos === -1
1557
+ ? pos.column + numberOfCharacters
1558
+ : numberOfCharacters - lastNewLinePos;
1559
+ return pos;
1560
+ }
1561
+
1562
+ function baseCompile(source, options = {}) {
1563
+ const assignedOptions = assign({}, options);
1564
+ const jit = !!assignedOptions.jit;
1565
+ const enalbeMinify = !!assignedOptions.minify;
1566
+ const enambeOptimize = assignedOptions.optimize == null ? true : assignedOptions.optimize;
1567
+ // parse source codes
1568
+ const parser = createParser(assignedOptions);
1569
+ const ast = parser.parse(source);
1570
+ if (!jit) {
1571
+ // transform ASTs
1572
+ transform(ast, assignedOptions);
1573
+ // generate javascript codes
1574
+ return generate(ast, assignedOptions);
1575
+ }
1576
+ else {
1577
+ // optimize ASTs
1578
+ enambeOptimize && optimize(ast);
1579
+ // minimize ASTs
1580
+ enalbeMinify && minify(ast);
1581
+ // In JIT mode, no ast transform, no code generation.
1582
+ return { ast, code: '' };
1583
+ }
1584
+ }
1585
+
1586
+ export { CompileErrorCodes, ERROR_DOMAIN$2 as ERROR_DOMAIN, LOCATION_STUB, baseCompile, createCompileError, createLocation, createParser, createPosition, defaultOnError, detectHtmlTag, errorMessages };