@intlify/core 10.0.0-alpha.4 → 10.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * core v10.0.0-alpha.4
2
+ * core v10.0.0-beta.1
3
3
  * (c) 2024 kazuya kawaguchi
4
4
  * Released under the MIT License.
5
5
  */
@@ -128,10 +128,6 @@ function generateCodeFrame(source, start = 0, end = source.length) {
128
128
  }
129
129
  return res.join('\n');
130
130
  }
131
- function incrementer(code) {
132
- let current = code;
133
- return () => ++current;
134
- }
135
131
 
136
132
  function warn(msg, err) {
137
133
  if (typeof console !== 'undefined') {
@@ -150,17 +146,6 @@ function warnOnce(msg) {
150
146
  }
151
147
  }
152
148
 
153
- function createPosition(line, column, offset) {
154
- return { line, column, offset };
155
- }
156
- function createLocation(start, end, source) {
157
- const loc = { start, end };
158
- if (source != null) {
159
- loc.source = source;
160
- }
161
- return loc;
162
- }
163
-
164
149
  const CompileErrorCodes = {
165
150
  // tokenizer error codes
166
151
  EXPECTED_TOKEN: 1,
@@ -181,12 +166,12 @@ const CompileErrorCodes = {
181
166
  // generator error codes
182
167
  UNHANDLED_CODEGEN_NODE_TYPE: 15,
183
168
  // minifier error codes
184
- UNHANDLED_MINIFIER_NODE_TYPE: 16,
185
- // Special value for higher-order compilers to pick up the last code
186
- // to avoid collision of error codes. This should always be kept as the last
187
- // item.
188
- __EXTEND_POINT__: 17
169
+ UNHANDLED_MINIFIER_NODE_TYPE: 16
189
170
  };
171
+ // Special value for higher-order compilers to pick up the last code
172
+ // to avoid collision of error codes.
173
+ // This should always be kept as the last item.
174
+ const COMPILE_ERROR_CODES_EXTEND_POINT = 17;
190
175
  /** @internal */
191
176
  const errorMessages$1 = {
192
177
  // tokenizer error messages
@@ -222,1441 +207,6 @@ function createCompileError(code, loc, options = {}) {
222
207
  error.domain = domain;
223
208
  return error;
224
209
  }
225
- /** @internal */
226
- function defaultOnError(error) {
227
- throw error;
228
- }
229
-
230
- // eslint-disable-next-line no-useless-escape
231
- const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
232
- const detectHtmlTag = (source) => RE_HTML_TAG.test(source);
233
-
234
- const CHAR_SP = ' ';
235
- const CHAR_CR = '\r';
236
- const CHAR_LF = '\n';
237
- const CHAR_LS = String.fromCharCode(0x2028);
238
- const CHAR_PS = String.fromCharCode(0x2029);
239
- function createScanner(str) {
240
- const _buf = str;
241
- let _index = 0;
242
- let _line = 1;
243
- let _column = 1;
244
- let _peekOffset = 0;
245
- const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
246
- const isLF = (index) => _buf[index] === CHAR_LF;
247
- const isPS = (index) => _buf[index] === CHAR_PS;
248
- const isLS = (index) => _buf[index] === CHAR_LS;
249
- const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
250
- const index = () => _index;
251
- const line = () => _line;
252
- const column = () => _column;
253
- const peekOffset = () => _peekOffset;
254
- const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
255
- const currentChar = () => charAt(_index);
256
- const currentPeek = () => charAt(_index + _peekOffset);
257
- function next() {
258
- _peekOffset = 0;
259
- if (isLineEnd(_index)) {
260
- _line++;
261
- _column = 0;
262
- }
263
- if (isCRLF(_index)) {
264
- _index++;
265
- }
266
- _index++;
267
- _column++;
268
- return _buf[_index];
269
- }
270
- function peek() {
271
- if (isCRLF(_index + _peekOffset)) {
272
- _peekOffset++;
273
- }
274
- _peekOffset++;
275
- return _buf[_index + _peekOffset];
276
- }
277
- function reset() {
278
- _index = 0;
279
- _line = 1;
280
- _column = 1;
281
- _peekOffset = 0;
282
- }
283
- function resetPeek(offset = 0) {
284
- _peekOffset = offset;
285
- }
286
- function skipToPeek() {
287
- const target = _index + _peekOffset;
288
- while (target !== _index) {
289
- next();
290
- }
291
- _peekOffset = 0;
292
- }
293
- return {
294
- index,
295
- line,
296
- column,
297
- peekOffset,
298
- charAt,
299
- currentChar,
300
- currentPeek,
301
- next,
302
- peek,
303
- reset,
304
- resetPeek,
305
- skipToPeek
306
- };
307
- }
308
-
309
- const EOF = undefined;
310
- const DOT = '.';
311
- const LITERAL_DELIMITER = "'";
312
- const ERROR_DOMAIN$3 = 'tokenizer';
313
- function createTokenizer(source, options = {}) {
314
- const location = options.location !== false;
315
- const _scnr = createScanner(source);
316
- const currentOffset = () => _scnr.index();
317
- const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
318
- const _initLoc = currentPosition();
319
- const _initOffset = currentOffset();
320
- const _context = {
321
- currentType: 13 /* TokenTypes.EOF */,
322
- offset: _initOffset,
323
- startLoc: _initLoc,
324
- endLoc: _initLoc,
325
- lastType: 13 /* TokenTypes.EOF */,
326
- lastOffset: _initOffset,
327
- lastStartLoc: _initLoc,
328
- lastEndLoc: _initLoc,
329
- braceNest: 0,
330
- inLinked: false,
331
- text: ''
332
- };
333
- const context = () => _context;
334
- const { onError } = options;
335
- function emitError(code, pos, offset, ...args) {
336
- const ctx = context();
337
- pos.column += offset;
338
- pos.offset += offset;
339
- if (onError) {
340
- const loc = location ? createLocation(ctx.startLoc, pos) : null;
341
- const err = createCompileError(code, loc, {
342
- domain: ERROR_DOMAIN$3,
343
- args
344
- });
345
- onError(err);
346
- }
347
- }
348
- function getToken(context, type, value) {
349
- context.endLoc = currentPosition();
350
- context.currentType = type;
351
- const token = { type };
352
- if (location) {
353
- token.loc = createLocation(context.startLoc, context.endLoc);
354
- }
355
- if (value != null) {
356
- token.value = value;
357
- }
358
- return token;
359
- }
360
- const getEndToken = (context) => getToken(context, 13 /* TokenTypes.EOF */);
361
- function eat(scnr, ch) {
362
- if (scnr.currentChar() === ch) {
363
- scnr.next();
364
- return ch;
365
- }
366
- else {
367
- emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
368
- return '';
369
- }
370
- }
371
- function peekSpaces(scnr) {
372
- let buf = '';
373
- while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
374
- buf += scnr.currentPeek();
375
- scnr.peek();
376
- }
377
- return buf;
378
- }
379
- function skipSpaces(scnr) {
380
- const buf = peekSpaces(scnr);
381
- scnr.skipToPeek();
382
- return buf;
383
- }
384
- function isIdentifierStart(ch) {
385
- if (ch === EOF) {
386
- return false;
387
- }
388
- const cc = ch.charCodeAt(0);
389
- return ((cc >= 97 && cc <= 122) || // a-z
390
- (cc >= 65 && cc <= 90) || // A-Z
391
- cc === 95 // _
392
- );
393
- }
394
- function isNumberStart(ch) {
395
- if (ch === EOF) {
396
- return false;
397
- }
398
- const cc = ch.charCodeAt(0);
399
- return cc >= 48 && cc <= 57; // 0-9
400
- }
401
- function isNamedIdentifierStart(scnr, context) {
402
- const { currentType } = context;
403
- if (currentType !== 2 /* TokenTypes.BraceLeft */) {
404
- return false;
405
- }
406
- peekSpaces(scnr);
407
- const ret = isIdentifierStart(scnr.currentPeek());
408
- scnr.resetPeek();
409
- return ret;
410
- }
411
- function isListIdentifierStart(scnr, context) {
412
- const { currentType } = context;
413
- if (currentType !== 2 /* TokenTypes.BraceLeft */) {
414
- return false;
415
- }
416
- peekSpaces(scnr);
417
- const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
418
- const ret = isNumberStart(ch);
419
- scnr.resetPeek();
420
- return ret;
421
- }
422
- function isLiteralStart(scnr, context) {
423
- const { currentType } = context;
424
- if (currentType !== 2 /* TokenTypes.BraceLeft */) {
425
- return false;
426
- }
427
- peekSpaces(scnr);
428
- const ret = scnr.currentPeek() === LITERAL_DELIMITER;
429
- scnr.resetPeek();
430
- return ret;
431
- }
432
- function isLinkedDotStart(scnr, context) {
433
- const { currentType } = context;
434
- if (currentType !== 7 /* TokenTypes.LinkedAlias */) {
435
- return false;
436
- }
437
- peekSpaces(scnr);
438
- const ret = scnr.currentPeek() === "." /* TokenChars.LinkedDot */;
439
- scnr.resetPeek();
440
- return ret;
441
- }
442
- function isLinkedModifierStart(scnr, context) {
443
- const { currentType } = context;
444
- if (currentType !== 8 /* TokenTypes.LinkedDot */) {
445
- return false;
446
- }
447
- peekSpaces(scnr);
448
- const ret = isIdentifierStart(scnr.currentPeek());
449
- scnr.resetPeek();
450
- return ret;
451
- }
452
- function isLinkedDelimiterStart(scnr, context) {
453
- const { currentType } = context;
454
- if (!(currentType === 7 /* TokenTypes.LinkedAlias */ ||
455
- currentType === 11 /* TokenTypes.LinkedModifier */)) {
456
- return false;
457
- }
458
- peekSpaces(scnr);
459
- const ret = scnr.currentPeek() === ":" /* TokenChars.LinkedDelimiter */;
460
- scnr.resetPeek();
461
- return ret;
462
- }
463
- function isLinkedReferStart(scnr, context) {
464
- const { currentType } = context;
465
- if (currentType !== 9 /* TokenTypes.LinkedDelimiter */) {
466
- return false;
467
- }
468
- const fn = () => {
469
- const ch = scnr.currentPeek();
470
- if (ch === "{" /* TokenChars.BraceLeft */) {
471
- return isIdentifierStart(scnr.peek());
472
- }
473
- else if (ch === "@" /* TokenChars.LinkedAlias */ ||
474
- ch === "|" /* TokenChars.Pipe */ ||
475
- ch === ":" /* TokenChars.LinkedDelimiter */ ||
476
- ch === "." /* TokenChars.LinkedDot */ ||
477
- ch === CHAR_SP ||
478
- !ch) {
479
- return false;
480
- }
481
- else if (ch === CHAR_LF) {
482
- scnr.peek();
483
- return fn();
484
- }
485
- else {
486
- // other characters
487
- return isTextStart(scnr, false);
488
- }
489
- };
490
- const ret = fn();
491
- scnr.resetPeek();
492
- return ret;
493
- }
494
- function isPluralStart(scnr) {
495
- peekSpaces(scnr);
496
- const ret = scnr.currentPeek() === "|" /* TokenChars.Pipe */;
497
- scnr.resetPeek();
498
- return ret;
499
- }
500
- function isTextStart(scnr, reset = true) {
501
- const fn = (hasSpace = false, prev = '') => {
502
- const ch = scnr.currentPeek();
503
- if (ch === "{" /* TokenChars.BraceLeft */) {
504
- return hasSpace;
505
- }
506
- else if (ch === "@" /* TokenChars.LinkedAlias */ || !ch) {
507
- return hasSpace;
508
- }
509
- else if (ch === "|" /* TokenChars.Pipe */) {
510
- return !(prev === CHAR_SP || prev === CHAR_LF);
511
- }
512
- else if (ch === CHAR_SP) {
513
- scnr.peek();
514
- return fn(true, CHAR_SP);
515
- }
516
- else if (ch === CHAR_LF) {
517
- scnr.peek();
518
- return fn(true, CHAR_LF);
519
- }
520
- else {
521
- return true;
522
- }
523
- };
524
- const ret = fn();
525
- reset && scnr.resetPeek();
526
- return ret;
527
- }
528
- function takeChar(scnr, fn) {
529
- const ch = scnr.currentChar();
530
- if (ch === EOF) {
531
- return EOF;
532
- }
533
- if (fn(ch)) {
534
- scnr.next();
535
- return ch;
536
- }
537
- return null;
538
- }
539
- function isIdentifier(ch) {
540
- const cc = ch.charCodeAt(0);
541
- return ((cc >= 97 && cc <= 122) || // a-z
542
- (cc >= 65 && cc <= 90) || // A-Z
543
- (cc >= 48 && cc <= 57) || // 0-9
544
- cc === 95 || // _
545
- cc === 36 // $
546
- );
547
- }
548
- function takeIdentifierChar(scnr) {
549
- return takeChar(scnr, isIdentifier);
550
- }
551
- function isNamedIdentifier(ch) {
552
- const cc = ch.charCodeAt(0);
553
- return ((cc >= 97 && cc <= 122) || // a-z
554
- (cc >= 65 && cc <= 90) || // A-Z
555
- (cc >= 48 && cc <= 57) || // 0-9
556
- cc === 95 || // _
557
- cc === 36 || // $
558
- cc === 45 // -
559
- );
560
- }
561
- function takeNamedIdentifierChar(scnr) {
562
- return takeChar(scnr, isNamedIdentifier);
563
- }
564
- function isDigit(ch) {
565
- const cc = ch.charCodeAt(0);
566
- return cc >= 48 && cc <= 57; // 0-9
567
- }
568
- function takeDigit(scnr) {
569
- return takeChar(scnr, isDigit);
570
- }
571
- function isHexDigit(ch) {
572
- const cc = ch.charCodeAt(0);
573
- return ((cc >= 48 && cc <= 57) || // 0-9
574
- (cc >= 65 && cc <= 70) || // A-F
575
- (cc >= 97 && cc <= 102)); // a-f
576
- }
577
- function takeHexDigit(scnr) {
578
- return takeChar(scnr, isHexDigit);
579
- }
580
- function getDigits(scnr) {
581
- let ch = '';
582
- let num = '';
583
- while ((ch = takeDigit(scnr))) {
584
- num += ch;
585
- }
586
- return num;
587
- }
588
- function readText(scnr) {
589
- let buf = '';
590
- while (true) {
591
- const ch = scnr.currentChar();
592
- if (ch === "{" /* TokenChars.BraceLeft */ ||
593
- ch === "}" /* TokenChars.BraceRight */ ||
594
- ch === "@" /* TokenChars.LinkedAlias */ ||
595
- ch === "|" /* TokenChars.Pipe */ ||
596
- !ch) {
597
- break;
598
- }
599
- else if (ch === CHAR_SP || ch === CHAR_LF) {
600
- if (isTextStart(scnr)) {
601
- buf += ch;
602
- scnr.next();
603
- }
604
- else if (isPluralStart(scnr)) {
605
- break;
606
- }
607
- else {
608
- buf += ch;
609
- scnr.next();
610
- }
611
- }
612
- else {
613
- buf += ch;
614
- scnr.next();
615
- }
616
- }
617
- return buf;
618
- }
619
- function readNamedIdentifier(scnr) {
620
- skipSpaces(scnr);
621
- let ch = '';
622
- let name = '';
623
- while ((ch = takeNamedIdentifierChar(scnr))) {
624
- name += ch;
625
- }
626
- if (scnr.currentChar() === EOF) {
627
- emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
628
- }
629
- return name;
630
- }
631
- function readListIdentifier(scnr) {
632
- skipSpaces(scnr);
633
- let value = '';
634
- if (scnr.currentChar() === '-') {
635
- scnr.next();
636
- value += `-${getDigits(scnr)}`;
637
- }
638
- else {
639
- value += getDigits(scnr);
640
- }
641
- if (scnr.currentChar() === EOF) {
642
- emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
643
- }
644
- return value;
645
- }
646
- function isLiteral(ch) {
647
- return ch !== LITERAL_DELIMITER && ch !== CHAR_LF;
648
- }
649
- function readLiteral(scnr) {
650
- skipSpaces(scnr);
651
- // eslint-disable-next-line no-useless-escape
652
- eat(scnr, `\'`);
653
- let ch = '';
654
- let literal = '';
655
- while ((ch = takeChar(scnr, isLiteral))) {
656
- if (ch === '\\') {
657
- literal += readEscapeSequence(scnr);
658
- }
659
- else {
660
- literal += ch;
661
- }
662
- }
663
- const current = scnr.currentChar();
664
- if (current === CHAR_LF || current === EOF) {
665
- emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
666
- // TODO: Is it correct really?
667
- if (current === CHAR_LF) {
668
- scnr.next();
669
- // eslint-disable-next-line no-useless-escape
670
- eat(scnr, `\'`);
671
- }
672
- return literal;
673
- }
674
- // eslint-disable-next-line no-useless-escape
675
- eat(scnr, `\'`);
676
- return literal;
677
- }
678
- function readEscapeSequence(scnr) {
679
- const ch = scnr.currentChar();
680
- switch (ch) {
681
- case '\\':
682
- case `\'`: // eslint-disable-line no-useless-escape
683
- scnr.next();
684
- return `\\${ch}`;
685
- case 'u':
686
- return readUnicodeEscapeSequence(scnr, ch, 4);
687
- case 'U':
688
- return readUnicodeEscapeSequence(scnr, ch, 6);
689
- default:
690
- emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
691
- return '';
692
- }
693
- }
694
- function readUnicodeEscapeSequence(scnr, unicode, digits) {
695
- eat(scnr, unicode);
696
- let sequence = '';
697
- for (let i = 0; i < digits; i++) {
698
- const ch = takeHexDigit(scnr);
699
- if (!ch) {
700
- emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
701
- break;
702
- }
703
- sequence += ch;
704
- }
705
- return `\\${unicode}${sequence}`;
706
- }
707
- function isInvalidIdentifier(ch) {
708
- return (ch !== "{" /* TokenChars.BraceLeft */ &&
709
- ch !== "}" /* TokenChars.BraceRight */ &&
710
- ch !== CHAR_SP &&
711
- ch !== CHAR_LF);
712
- }
713
- function readInvalidIdentifier(scnr) {
714
- skipSpaces(scnr);
715
- let ch = '';
716
- let identifiers = '';
717
- while ((ch = takeChar(scnr, isInvalidIdentifier))) {
718
- identifiers += ch;
719
- }
720
- return identifiers;
721
- }
722
- function readLinkedModifier(scnr) {
723
- let ch = '';
724
- let name = '';
725
- while ((ch = takeIdentifierChar(scnr))) {
726
- name += ch;
727
- }
728
- return name;
729
- }
730
- function readLinkedRefer(scnr) {
731
- const fn = (buf) => {
732
- const ch = scnr.currentChar();
733
- if (ch === "{" /* TokenChars.BraceLeft */ ||
734
- ch === "@" /* TokenChars.LinkedAlias */ ||
735
- ch === "|" /* TokenChars.Pipe */ ||
736
- ch === "(" /* TokenChars.ParenLeft */ ||
737
- ch === ")" /* TokenChars.ParenRight */ ||
738
- !ch) {
739
- return buf;
740
- }
741
- else if (ch === CHAR_SP) {
742
- return buf;
743
- }
744
- else if (ch === CHAR_LF || ch === DOT) {
745
- buf += ch;
746
- scnr.next();
747
- return fn(buf);
748
- }
749
- else {
750
- buf += ch;
751
- scnr.next();
752
- return fn(buf);
753
- }
754
- };
755
- return fn('');
756
- }
757
- function readPlural(scnr) {
758
- skipSpaces(scnr);
759
- const plural = eat(scnr, "|" /* TokenChars.Pipe */);
760
- skipSpaces(scnr);
761
- return plural;
762
- }
763
- // TODO: We need refactoring of token parsing ...
764
- function readTokenInPlaceholder(scnr, context) {
765
- let token = null;
766
- const ch = scnr.currentChar();
767
- switch (ch) {
768
- case "{" /* TokenChars.BraceLeft */:
769
- if (context.braceNest >= 1) {
770
- emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
771
- }
772
- scnr.next();
773
- token = getToken(context, 2 /* TokenTypes.BraceLeft */, "{" /* TokenChars.BraceLeft */);
774
- skipSpaces(scnr);
775
- context.braceNest++;
776
- return token;
777
- case "}" /* TokenChars.BraceRight */:
778
- if (context.braceNest > 0 &&
779
- context.currentType === 2 /* TokenTypes.BraceLeft */) {
780
- emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
781
- }
782
- scnr.next();
783
- token = getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
784
- context.braceNest--;
785
- context.braceNest > 0 && skipSpaces(scnr);
786
- if (context.inLinked && context.braceNest === 0) {
787
- context.inLinked = false;
788
- }
789
- return token;
790
- case "@" /* TokenChars.LinkedAlias */:
791
- if (context.braceNest > 0) {
792
- emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
793
- }
794
- token = readTokenInLinked(scnr, context) || getEndToken(context);
795
- context.braceNest = 0;
796
- return token;
797
- default: {
798
- let validNamedIdentifier = true;
799
- let validListIdentifier = true;
800
- let validLiteral = true;
801
- if (isPluralStart(scnr)) {
802
- if (context.braceNest > 0) {
803
- emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
804
- }
805
- token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
806
- // reset
807
- context.braceNest = 0;
808
- context.inLinked = false;
809
- return token;
810
- }
811
- if (context.braceNest > 0 &&
812
- (context.currentType === 4 /* TokenTypes.Named */ ||
813
- context.currentType === 5 /* TokenTypes.List */ ||
814
- context.currentType === 6 /* TokenTypes.Literal */)) {
815
- emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
816
- context.braceNest = 0;
817
- return readToken(scnr, context);
818
- }
819
- if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
820
- token = getToken(context, 4 /* TokenTypes.Named */, readNamedIdentifier(scnr));
821
- skipSpaces(scnr);
822
- return token;
823
- }
824
- if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
825
- token = getToken(context, 5 /* TokenTypes.List */, readListIdentifier(scnr));
826
- skipSpaces(scnr);
827
- return token;
828
- }
829
- if ((validLiteral = isLiteralStart(scnr, context))) {
830
- token = getToken(context, 6 /* TokenTypes.Literal */, readLiteral(scnr));
831
- skipSpaces(scnr);
832
- return token;
833
- }
834
- if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
835
- // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
836
- token = getToken(context, 12 /* TokenTypes.InvalidPlace */, readInvalidIdentifier(scnr));
837
- emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
838
- skipSpaces(scnr);
839
- return token;
840
- }
841
- break;
842
- }
843
- }
844
- return token;
845
- }
846
- // TODO: We need refactoring of token parsing ...
847
- function readTokenInLinked(scnr, context) {
848
- const { currentType } = context;
849
- let token = null;
850
- const ch = scnr.currentChar();
851
- if ((currentType === 7 /* TokenTypes.LinkedAlias */ ||
852
- currentType === 8 /* TokenTypes.LinkedDot */ ||
853
- currentType === 11 /* TokenTypes.LinkedModifier */ ||
854
- currentType === 9 /* TokenTypes.LinkedDelimiter */) &&
855
- (ch === CHAR_LF || ch === CHAR_SP)) {
856
- emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
857
- }
858
- switch (ch) {
859
- case "@" /* TokenChars.LinkedAlias */:
860
- scnr.next();
861
- token = getToken(context, 7 /* TokenTypes.LinkedAlias */, "@" /* TokenChars.LinkedAlias */);
862
- context.inLinked = true;
863
- return token;
864
- case "." /* TokenChars.LinkedDot */:
865
- skipSpaces(scnr);
866
- scnr.next();
867
- return getToken(context, 8 /* TokenTypes.LinkedDot */, "." /* TokenChars.LinkedDot */);
868
- case ":" /* TokenChars.LinkedDelimiter */:
869
- skipSpaces(scnr);
870
- scnr.next();
871
- return getToken(context, 9 /* TokenTypes.LinkedDelimiter */, ":" /* TokenChars.LinkedDelimiter */);
872
- default:
873
- if (isPluralStart(scnr)) {
874
- token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
875
- // reset
876
- context.braceNest = 0;
877
- context.inLinked = false;
878
- return token;
879
- }
880
- if (isLinkedDotStart(scnr, context) ||
881
- isLinkedDelimiterStart(scnr, context)) {
882
- skipSpaces(scnr);
883
- return readTokenInLinked(scnr, context);
884
- }
885
- if (isLinkedModifierStart(scnr, context)) {
886
- skipSpaces(scnr);
887
- return getToken(context, 11 /* TokenTypes.LinkedModifier */, readLinkedModifier(scnr));
888
- }
889
- if (isLinkedReferStart(scnr, context)) {
890
- skipSpaces(scnr);
891
- if (ch === "{" /* TokenChars.BraceLeft */) {
892
- // scan the placeholder
893
- return readTokenInPlaceholder(scnr, context) || token;
894
- }
895
- else {
896
- return getToken(context, 10 /* TokenTypes.LinkedKey */, readLinkedRefer(scnr));
897
- }
898
- }
899
- if (currentType === 7 /* TokenTypes.LinkedAlias */) {
900
- emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
901
- }
902
- context.braceNest = 0;
903
- context.inLinked = false;
904
- return readToken(scnr, context);
905
- }
906
- }
907
- // TODO: We need refactoring of token parsing ...
908
- function readToken(scnr, context) {
909
- let token = { type: 13 /* TokenTypes.EOF */ };
910
- if (context.braceNest > 0) {
911
- return readTokenInPlaceholder(scnr, context) || getEndToken(context);
912
- }
913
- if (context.inLinked) {
914
- return readTokenInLinked(scnr, context) || getEndToken(context);
915
- }
916
- const ch = scnr.currentChar();
917
- switch (ch) {
918
- case "{" /* TokenChars.BraceLeft */:
919
- return readTokenInPlaceholder(scnr, context) || getEndToken(context);
920
- case "}" /* TokenChars.BraceRight */:
921
- emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
922
- scnr.next();
923
- return getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
924
- case "@" /* TokenChars.LinkedAlias */:
925
- return readTokenInLinked(scnr, context) || getEndToken(context);
926
- default: {
927
- if (isPluralStart(scnr)) {
928
- token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
929
- // reset
930
- context.braceNest = 0;
931
- context.inLinked = false;
932
- return token;
933
- }
934
- if (isTextStart(scnr)) {
935
- return getToken(context, 0 /* TokenTypes.Text */, readText(scnr));
936
- }
937
- break;
938
- }
939
- }
940
- return token;
941
- }
942
- function nextToken() {
943
- const { currentType, offset, startLoc, endLoc } = _context;
944
- _context.lastType = currentType;
945
- _context.lastOffset = offset;
946
- _context.lastStartLoc = startLoc;
947
- _context.lastEndLoc = endLoc;
948
- _context.offset = currentOffset();
949
- _context.startLoc = currentPosition();
950
- if (_scnr.currentChar() === EOF) {
951
- return getToken(_context, 13 /* TokenTypes.EOF */);
952
- }
953
- return readToken(_scnr, _context);
954
- }
955
- return {
956
- nextToken,
957
- currentOffset,
958
- currentPosition,
959
- context
960
- };
961
- }
962
-
963
- const ERROR_DOMAIN$2 = 'parser';
964
- // Backslash backslash, backslash quote, uHHHH, UHHHHHH.
965
- const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
966
- function fromEscapeSequence(match, codePoint4, codePoint6) {
967
- switch (match) {
968
- case `\\\\`:
969
- return `\\`;
970
- // eslint-disable-next-line no-useless-escape
971
- case `\\\'`:
972
- // eslint-disable-next-line no-useless-escape
973
- return `\'`;
974
- default: {
975
- const codePoint = parseInt(codePoint4 || codePoint6, 16);
976
- if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
977
- return String.fromCodePoint(codePoint);
978
- }
979
- // invalid ...
980
- // Replace them with U+FFFD REPLACEMENT CHARACTER.
981
- return '�';
982
- }
983
- }
984
- }
985
- function createParser(options = {}) {
986
- const location = options.location !== false;
987
- const { onError } = options;
988
- function emitError(tokenzer, code, start, offset, ...args) {
989
- const end = tokenzer.currentPosition();
990
- end.offset += offset;
991
- end.column += offset;
992
- if (onError) {
993
- const loc = location ? createLocation(start, end) : null;
994
- const err = createCompileError(code, loc, {
995
- domain: ERROR_DOMAIN$2,
996
- args
997
- });
998
- onError(err);
999
- }
1000
- }
1001
- function startNode(type, offset, loc) {
1002
- const node = { type };
1003
- if (location) {
1004
- node.start = offset;
1005
- node.end = offset;
1006
- node.loc = { start: loc, end: loc };
1007
- }
1008
- return node;
1009
- }
1010
- function endNode(node, offset, pos, type) {
1011
- if (type) {
1012
- node.type = type;
1013
- }
1014
- if (location) {
1015
- node.end = offset;
1016
- if (node.loc) {
1017
- node.loc.end = pos;
1018
- }
1019
- }
1020
- }
1021
- function parseText(tokenizer, value) {
1022
- const context = tokenizer.context();
1023
- const node = startNode(3 /* NodeTypes.Text */, context.offset, context.startLoc);
1024
- node.value = value;
1025
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1026
- return node;
1027
- }
1028
- function parseList(tokenizer, index) {
1029
- const context = tokenizer.context();
1030
- const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
1031
- const node = startNode(5 /* NodeTypes.List */, offset, loc);
1032
- node.index = parseInt(index, 10);
1033
- tokenizer.nextToken(); // skip brach right
1034
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1035
- return node;
1036
- }
1037
- function parseNamed(tokenizer, key) {
1038
- const context = tokenizer.context();
1039
- const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
1040
- const node = startNode(4 /* NodeTypes.Named */, offset, loc);
1041
- node.key = key;
1042
- tokenizer.nextToken(); // skip brach right
1043
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1044
- return node;
1045
- }
1046
- function parseLiteral(tokenizer, value) {
1047
- const context = tokenizer.context();
1048
- const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
1049
- const node = startNode(9 /* NodeTypes.Literal */, offset, loc);
1050
- node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
1051
- tokenizer.nextToken(); // skip brach right
1052
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1053
- return node;
1054
- }
1055
- function parseLinkedModifier(tokenizer) {
1056
- const token = tokenizer.nextToken();
1057
- const context = tokenizer.context();
1058
- const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
1059
- const node = startNode(8 /* NodeTypes.LinkedModifier */, offset, loc);
1060
- if (token.type !== 11 /* TokenTypes.LinkedModifier */) {
1061
- // empty modifier
1062
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
1063
- node.value = '';
1064
- endNode(node, offset, loc);
1065
- return {
1066
- nextConsumeToken: token,
1067
- node
1068
- };
1069
- }
1070
- // check token
1071
- if (token.value == null) {
1072
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1073
- }
1074
- node.value = token.value || '';
1075
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1076
- return {
1077
- node
1078
- };
1079
- }
1080
- function parseLinkedKey(tokenizer, value) {
1081
- const context = tokenizer.context();
1082
- const node = startNode(7 /* NodeTypes.LinkedKey */, context.offset, context.startLoc);
1083
- node.value = value;
1084
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1085
- return node;
1086
- }
1087
- function parseLinked(tokenizer) {
1088
- const context = tokenizer.context();
1089
- const linkedNode = startNode(6 /* NodeTypes.Linked */, context.offset, context.startLoc);
1090
- let token = tokenizer.nextToken();
1091
- if (token.type === 8 /* TokenTypes.LinkedDot */) {
1092
- const parsed = parseLinkedModifier(tokenizer);
1093
- linkedNode.modifier = parsed.node;
1094
- token = parsed.nextConsumeToken || tokenizer.nextToken();
1095
- }
1096
- // asset check token
1097
- if (token.type !== 9 /* TokenTypes.LinkedDelimiter */) {
1098
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1099
- }
1100
- token = tokenizer.nextToken();
1101
- // skip brace left
1102
- if (token.type === 2 /* TokenTypes.BraceLeft */) {
1103
- token = tokenizer.nextToken();
1104
- }
1105
- switch (token.type) {
1106
- case 10 /* TokenTypes.LinkedKey */:
1107
- if (token.value == null) {
1108
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1109
- }
1110
- linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
1111
- break;
1112
- case 4 /* TokenTypes.Named */:
1113
- if (token.value == null) {
1114
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1115
- }
1116
- linkedNode.key = parseNamed(tokenizer, token.value || '');
1117
- break;
1118
- case 5 /* TokenTypes.List */:
1119
- if (token.value == null) {
1120
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1121
- }
1122
- linkedNode.key = parseList(tokenizer, token.value || '');
1123
- break;
1124
- case 6 /* TokenTypes.Literal */:
1125
- if (token.value == null) {
1126
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1127
- }
1128
- linkedNode.key = parseLiteral(tokenizer, token.value || '');
1129
- break;
1130
- default: {
1131
- // empty key
1132
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
1133
- const nextContext = tokenizer.context();
1134
- const emptyLinkedKeyNode = startNode(7 /* NodeTypes.LinkedKey */, nextContext.offset, nextContext.startLoc);
1135
- emptyLinkedKeyNode.value = '';
1136
- endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
1137
- linkedNode.key = emptyLinkedKeyNode;
1138
- endNode(linkedNode, nextContext.offset, nextContext.startLoc);
1139
- return {
1140
- nextConsumeToken: token,
1141
- node: linkedNode
1142
- };
1143
- }
1144
- }
1145
- endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
1146
- return {
1147
- node: linkedNode
1148
- };
1149
- }
1150
- function parseMessage(tokenizer) {
1151
- const context = tokenizer.context();
1152
- const startOffset = context.currentType === 1 /* TokenTypes.Pipe */
1153
- ? tokenizer.currentOffset()
1154
- : context.offset;
1155
- const startLoc = context.currentType === 1 /* TokenTypes.Pipe */
1156
- ? context.endLoc
1157
- : context.startLoc;
1158
- const node = startNode(2 /* NodeTypes.Message */, startOffset, startLoc);
1159
- node.items = [];
1160
- let nextToken = null;
1161
- do {
1162
- const token = nextToken || tokenizer.nextToken();
1163
- nextToken = null;
1164
- switch (token.type) {
1165
- case 0 /* TokenTypes.Text */:
1166
- if (token.value == null) {
1167
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1168
- }
1169
- node.items.push(parseText(tokenizer, token.value || ''));
1170
- break;
1171
- case 5 /* TokenTypes.List */:
1172
- if (token.value == null) {
1173
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1174
- }
1175
- node.items.push(parseList(tokenizer, token.value || ''));
1176
- break;
1177
- case 4 /* TokenTypes.Named */:
1178
- if (token.value == null) {
1179
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1180
- }
1181
- node.items.push(parseNamed(tokenizer, token.value || ''));
1182
- break;
1183
- case 6 /* TokenTypes.Literal */:
1184
- if (token.value == null) {
1185
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1186
- }
1187
- node.items.push(parseLiteral(tokenizer, token.value || ''));
1188
- break;
1189
- case 7 /* TokenTypes.LinkedAlias */: {
1190
- const parsed = parseLinked(tokenizer);
1191
- node.items.push(parsed.node);
1192
- nextToken = parsed.nextConsumeToken || null;
1193
- break;
1194
- }
1195
- }
1196
- } while (context.currentType !== 13 /* TokenTypes.EOF */ &&
1197
- context.currentType !== 1 /* TokenTypes.Pipe */);
1198
- // adjust message node loc
1199
- const endOffset = context.currentType === 1 /* TokenTypes.Pipe */
1200
- ? context.lastOffset
1201
- : tokenizer.currentOffset();
1202
- const endLoc = context.currentType === 1 /* TokenTypes.Pipe */
1203
- ? context.lastEndLoc
1204
- : tokenizer.currentPosition();
1205
- endNode(node, endOffset, endLoc);
1206
- return node;
1207
- }
1208
- function parsePlural(tokenizer, offset, loc, msgNode) {
1209
- const context = tokenizer.context();
1210
- let hasEmptyMessage = msgNode.items.length === 0;
1211
- const node = startNode(1 /* NodeTypes.Plural */, offset, loc);
1212
- node.cases = [];
1213
- node.cases.push(msgNode);
1214
- do {
1215
- const msg = parseMessage(tokenizer);
1216
- if (!hasEmptyMessage) {
1217
- hasEmptyMessage = msg.items.length === 0;
1218
- }
1219
- node.cases.push(msg);
1220
- } while (context.currentType !== 13 /* TokenTypes.EOF */);
1221
- if (hasEmptyMessage) {
1222
- emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
1223
- }
1224
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1225
- return node;
1226
- }
1227
- function parseResource(tokenizer) {
1228
- const context = tokenizer.context();
1229
- const { offset, startLoc } = context;
1230
- const msgNode = parseMessage(tokenizer);
1231
- if (context.currentType === 13 /* TokenTypes.EOF */) {
1232
- return msgNode;
1233
- }
1234
- else {
1235
- return parsePlural(tokenizer, offset, startLoc, msgNode);
1236
- }
1237
- }
1238
- function parse(source) {
1239
- const tokenizer = createTokenizer(source, assign({}, options));
1240
- const context = tokenizer.context();
1241
- const node = startNode(0 /* NodeTypes.Resource */, context.offset, context.startLoc);
1242
- if (location && node.loc) {
1243
- node.loc.source = source;
1244
- }
1245
- node.body = parseResource(tokenizer);
1246
- if (options.onCacheKey) {
1247
- node.cacheKey = options.onCacheKey(source);
1248
- }
1249
- // assert whether achieved to EOF
1250
- if (context.currentType !== 13 /* TokenTypes.EOF */) {
1251
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');
1252
- }
1253
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1254
- return node;
1255
- }
1256
- return { parse };
1257
- }
1258
- function getTokenCaption(token) {
1259
- if (token.type === 13 /* TokenTypes.EOF */) {
1260
- return 'EOF';
1261
- }
1262
- const name = (token.value || '').replace(/\r?\n/gu, '\\n');
1263
- return name.length > 10 ? name.slice(0, 9) + '…' : name;
1264
- }
1265
-
1266
- function createTransformer(ast, options = {} // eslint-disable-line
1267
- ) {
1268
- const _context = {
1269
- ast,
1270
- helpers: new Set()
1271
- };
1272
- const context = () => _context;
1273
- const helper = (name) => {
1274
- _context.helpers.add(name);
1275
- return name;
1276
- };
1277
- return { context, helper };
1278
- }
1279
- function traverseNodes(nodes, transformer) {
1280
- for (let i = 0; i < nodes.length; i++) {
1281
- traverseNode(nodes[i], transformer);
1282
- }
1283
- }
1284
- function traverseNode(node, transformer) {
1285
- // TODO: if we need pre-hook of transform, should be implemented to here
1286
- switch (node.type) {
1287
- case 1 /* NodeTypes.Plural */:
1288
- traverseNodes(node.cases, transformer);
1289
- transformer.helper("plural" /* HelperNameMap.PLURAL */);
1290
- break;
1291
- case 2 /* NodeTypes.Message */:
1292
- traverseNodes(node.items, transformer);
1293
- break;
1294
- case 6 /* NodeTypes.Linked */: {
1295
- const linked = node;
1296
- traverseNode(linked.key, transformer);
1297
- transformer.helper("linked" /* HelperNameMap.LINKED */);
1298
- transformer.helper("type" /* HelperNameMap.TYPE */);
1299
- break;
1300
- }
1301
- case 5 /* NodeTypes.List */:
1302
- transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
1303
- transformer.helper("list" /* HelperNameMap.LIST */);
1304
- break;
1305
- case 4 /* NodeTypes.Named */:
1306
- transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
1307
- transformer.helper("named" /* HelperNameMap.NAMED */);
1308
- break;
1309
- }
1310
- // TODO: if we need post-hook of transform, should be implemented to here
1311
- }
1312
- // transform AST
1313
- function transform(ast, options = {} // eslint-disable-line
1314
- ) {
1315
- const transformer = createTransformer(ast);
1316
- transformer.helper("normalize" /* HelperNameMap.NORMALIZE */);
1317
- // traverse
1318
- ast.body && traverseNode(ast.body, transformer);
1319
- // set meta information
1320
- const context = transformer.context();
1321
- ast.helpers = Array.from(context.helpers);
1322
- }
1323
-
1324
- function optimize(ast) {
1325
- const body = ast.body;
1326
- if (body.type === 2 /* NodeTypes.Message */) {
1327
- optimizeMessageNode(body);
1328
- }
1329
- else {
1330
- body.cases.forEach(c => optimizeMessageNode(c));
1331
- }
1332
- return ast;
1333
- }
1334
- function optimizeMessageNode(message) {
1335
- if (message.items.length === 1) {
1336
- const item = message.items[0];
1337
- if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
1338
- message.static = item.value;
1339
- delete item.value; // optimization for size
1340
- }
1341
- }
1342
- else {
1343
- const values = [];
1344
- for (let i = 0; i < message.items.length; i++) {
1345
- const item = message.items[i];
1346
- if (!(item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */)) {
1347
- break;
1348
- }
1349
- if (item.value == null) {
1350
- break;
1351
- }
1352
- values.push(item.value);
1353
- }
1354
- if (values.length === message.items.length) {
1355
- message.static = join(values);
1356
- for (let i = 0; i < message.items.length; i++) {
1357
- const item = message.items[i];
1358
- if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
1359
- delete item.value; // optimization for size
1360
- }
1361
- }
1362
- }
1363
- }
1364
- }
1365
-
1366
- const ERROR_DOMAIN$1 = 'minifier';
1367
- /* eslint-disable @typescript-eslint/no-explicit-any */
1368
- function minify(node) {
1369
- node.t = node.type;
1370
- switch (node.type) {
1371
- case 0 /* NodeTypes.Resource */: {
1372
- const resource = node;
1373
- minify(resource.body);
1374
- resource.b = resource.body;
1375
- delete resource.body;
1376
- break;
1377
- }
1378
- case 1 /* NodeTypes.Plural */: {
1379
- const plural = node;
1380
- const cases = plural.cases;
1381
- for (let i = 0; i < cases.length; i++) {
1382
- minify(cases[i]);
1383
- }
1384
- plural.c = cases;
1385
- delete plural.cases;
1386
- break;
1387
- }
1388
- case 2 /* NodeTypes.Message */: {
1389
- const message = node;
1390
- const items = message.items;
1391
- for (let i = 0; i < items.length; i++) {
1392
- minify(items[i]);
1393
- }
1394
- message.i = items;
1395
- delete message.items;
1396
- if (message.static) {
1397
- message.s = message.static;
1398
- delete message.static;
1399
- }
1400
- break;
1401
- }
1402
- case 3 /* NodeTypes.Text */:
1403
- case 9 /* NodeTypes.Literal */:
1404
- case 8 /* NodeTypes.LinkedModifier */:
1405
- case 7 /* NodeTypes.LinkedKey */: {
1406
- const valueNode = node;
1407
- if (valueNode.value) {
1408
- valueNode.v = valueNode.value;
1409
- delete valueNode.value;
1410
- }
1411
- break;
1412
- }
1413
- case 6 /* NodeTypes.Linked */: {
1414
- const linked = node;
1415
- minify(linked.key);
1416
- linked.k = linked.key;
1417
- delete linked.key;
1418
- if (linked.modifier) {
1419
- minify(linked.modifier);
1420
- linked.m = linked.modifier;
1421
- delete linked.modifier;
1422
- }
1423
- break;
1424
- }
1425
- case 5 /* NodeTypes.List */: {
1426
- const list = node;
1427
- list.i = list.index;
1428
- delete list.index;
1429
- break;
1430
- }
1431
- case 4 /* NodeTypes.Named */: {
1432
- const named = node;
1433
- named.k = named.key;
1434
- delete named.key;
1435
- break;
1436
- }
1437
- default:
1438
- {
1439
- throw createCompileError(CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE, null, {
1440
- domain: ERROR_DOMAIN$1,
1441
- args: [node.type]
1442
- });
1443
- }
1444
- }
1445
- delete node.type;
1446
- }
1447
- /* eslint-enable @typescript-eslint/no-explicit-any */
1448
-
1449
- // eslint-disable-next-line @typescript-eslint/triple-slash-reference
1450
- /// <reference types="source-map-js" />
1451
- const ERROR_DOMAIN = 'parser';
1452
- function createCodeGenerator(ast, options) {
1453
- const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
1454
- const location = options.location !== false;
1455
- const _context = {
1456
- filename,
1457
- code: '',
1458
- column: 1,
1459
- line: 1,
1460
- offset: 0,
1461
- map: undefined,
1462
- breakLineCode,
1463
- needIndent: _needIndent,
1464
- indentLevel: 0
1465
- };
1466
- if (location && ast.loc) {
1467
- _context.source = ast.loc.source;
1468
- }
1469
- const context = () => _context;
1470
- function push(code, node) {
1471
- _context.code += code;
1472
- }
1473
- function _newline(n, withBreakLine = true) {
1474
- const _breakLineCode = withBreakLine ? breakLineCode : '';
1475
- push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
1476
- }
1477
- function indent(withNewLine = true) {
1478
- const level = ++_context.indentLevel;
1479
- withNewLine && _newline(level);
1480
- }
1481
- function deindent(withNewLine = true) {
1482
- const level = --_context.indentLevel;
1483
- withNewLine && _newline(level);
1484
- }
1485
- function newline() {
1486
- _newline(_context.indentLevel);
1487
- }
1488
- const helper = (key) => `_${key}`;
1489
- const needIndent = () => _context.needIndent;
1490
- return {
1491
- context,
1492
- push,
1493
- indent,
1494
- deindent,
1495
- newline,
1496
- helper,
1497
- needIndent
1498
- };
1499
- }
1500
- function generateLinkedNode(generator, node) {
1501
- const { helper } = generator;
1502
- generator.push(`${helper("linked" /* HelperNameMap.LINKED */)}(`);
1503
- generateNode(generator, node.key);
1504
- if (node.modifier) {
1505
- generator.push(`, `);
1506
- generateNode(generator, node.modifier);
1507
- generator.push(`, _type`);
1508
- }
1509
- else {
1510
- generator.push(`, undefined, _type`);
1511
- }
1512
- generator.push(`)`);
1513
- }
1514
- function generateMessageNode(generator, node) {
1515
- const { helper, needIndent } = generator;
1516
- generator.push(`${helper("normalize" /* HelperNameMap.NORMALIZE */)}([`);
1517
- generator.indent(needIndent());
1518
- const length = node.items.length;
1519
- for (let i = 0; i < length; i++) {
1520
- generateNode(generator, node.items[i]);
1521
- if (i === length - 1) {
1522
- break;
1523
- }
1524
- generator.push(', ');
1525
- }
1526
- generator.deindent(needIndent());
1527
- generator.push('])');
1528
- }
1529
- function generatePluralNode(generator, node) {
1530
- const { helper, needIndent } = generator;
1531
- if (node.cases.length > 1) {
1532
- generator.push(`${helper("plural" /* HelperNameMap.PLURAL */)}([`);
1533
- generator.indent(needIndent());
1534
- const length = node.cases.length;
1535
- for (let i = 0; i < length; i++) {
1536
- generateNode(generator, node.cases[i]);
1537
- if (i === length - 1) {
1538
- break;
1539
- }
1540
- generator.push(', ');
1541
- }
1542
- generator.deindent(needIndent());
1543
- generator.push(`])`);
1544
- }
1545
- }
1546
- function generateResource(generator, node) {
1547
- if (node.body) {
1548
- generateNode(generator, node.body);
1549
- }
1550
- else {
1551
- generator.push('null');
1552
- }
1553
- }
1554
- function generateNode(generator, node) {
1555
- const { helper } = generator;
1556
- switch (node.type) {
1557
- case 0 /* NodeTypes.Resource */:
1558
- generateResource(generator, node);
1559
- break;
1560
- case 1 /* NodeTypes.Plural */:
1561
- generatePluralNode(generator, node);
1562
- break;
1563
- case 2 /* NodeTypes.Message */:
1564
- generateMessageNode(generator, node);
1565
- break;
1566
- case 6 /* NodeTypes.Linked */:
1567
- generateLinkedNode(generator, node);
1568
- break;
1569
- case 8 /* NodeTypes.LinkedModifier */:
1570
- generator.push(JSON.stringify(node.value), node);
1571
- break;
1572
- case 7 /* NodeTypes.LinkedKey */:
1573
- generator.push(JSON.stringify(node.value), node);
1574
- break;
1575
- case 5 /* NodeTypes.List */:
1576
- generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("list" /* HelperNameMap.LIST */)}(${node.index}))`, node);
1577
- break;
1578
- case 4 /* NodeTypes.Named */:
1579
- generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("named" /* HelperNameMap.NAMED */)}(${JSON.stringify(node.key)}))`, node);
1580
- break;
1581
- case 9 /* NodeTypes.Literal */:
1582
- generator.push(JSON.stringify(node.value), node);
1583
- break;
1584
- case 3 /* NodeTypes.Text */:
1585
- generator.push(JSON.stringify(node.value), node);
1586
- break;
1587
- default:
1588
- {
1589
- throw createCompileError(CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE, null, {
1590
- domain: ERROR_DOMAIN,
1591
- args: [node.type]
1592
- });
1593
- }
1594
- }
1595
- }
1596
- // generate code from AST
1597
- const generate = (ast, options = {}) => {
1598
- const mode = isString(options.mode) ? options.mode : 'normal';
1599
- const filename = isString(options.filename)
1600
- ? options.filename
1601
- : 'message.intl';
1602
- const sourceMap = !!options.sourceMap;
1603
- // prettier-ignore
1604
- const breakLineCode = options.breakLineCode != null
1605
- ? options.breakLineCode
1606
- : mode === 'arrow'
1607
- ? ';'
1608
- : '\n';
1609
- const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
1610
- const helpers = ast.helpers || [];
1611
- const generator = createCodeGenerator(ast, {
1612
- mode,
1613
- filename,
1614
- sourceMap,
1615
- breakLineCode,
1616
- needIndent
1617
- });
1618
- generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
1619
- generator.indent(needIndent);
1620
- if (helpers.length > 0) {
1621
- generator.push(`const { ${join(helpers.map(s => `${s}: _${s}`), ', ')} } = ctx`);
1622
- generator.newline();
1623
- }
1624
- generator.push(`return `);
1625
- generateNode(generator, ast);
1626
- generator.deindent(needIndent);
1627
- generator.push(`}`);
1628
- delete ast.helpers;
1629
- const { code, map } = generator.context();
1630
- return {
1631
- ast,
1632
- code,
1633
- map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
1634
- };
1635
- };
1636
-
1637
- function baseCompile$1(source, options = {}) {
1638
- const assignedOptions = assign({}, options);
1639
- const jit = !!assignedOptions.jit;
1640
- const enalbeMinify = !!assignedOptions.minify;
1641
- const enambeOptimize = assignedOptions.optimize == null ? true : assignedOptions.optimize;
1642
- // parse source codes
1643
- const parser = createParser(assignedOptions);
1644
- const ast = parser.parse(source);
1645
- if (!jit) {
1646
- // transform ASTs
1647
- transform(ast, assignedOptions);
1648
- // generate javascript codes
1649
- return generate(ast, assignedOptions);
1650
- }
1651
- else {
1652
- // optimize ASTs
1653
- enambeOptimize && optimize(ast);
1654
- // minimize ASTs
1655
- enalbeMinify && minify(ast);
1656
- // In JIT mode, no ast transform, no code generation.
1657
- return { ast, code: '' };
1658
- }
1659
- }
1660
210
 
1661
211
  const pathStateMachine = [];
1662
212
  pathStateMachine[0 /* States.BEFORE_PATH */] = {
@@ -2079,18 +629,16 @@ function createDevToolsHook(hook) {
2079
629
  return (payloads) => devtools && devtools.emit(hook, payloads);
2080
630
  }
2081
631
 
2082
- const code$1 = 1;
2083
- const inc$1 = incrementer(code$1);
2084
632
  const CoreWarnCodes = {
2085
- NOT_FOUND_KEY: code$1, // 1
2086
- FALLBACK_TO_TRANSLATE: inc$1(), // 2
2087
- CANNOT_FORMAT_NUMBER: inc$1(), // 3
2088
- FALLBACK_TO_NUMBER_FORMAT: inc$1(), // 4
2089
- CANNOT_FORMAT_DATE: inc$1(), // 5
2090
- FALLBACK_TO_DATE_FORMAT: inc$1(), // 6
2091
- EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: inc$1(), // 7
2092
- __EXTEND_POINT__: inc$1() // 8
633
+ NOT_FOUND_KEY: 1,
634
+ FALLBACK_TO_TRANSLATE: 2,
635
+ CANNOT_FORMAT_NUMBER: 3,
636
+ FALLBACK_TO_NUMBER_FORMAT: 4,
637
+ CANNOT_FORMAT_DATE: 5,
638
+ FALLBACK_TO_DATE_FORMAT: 6,
639
+ EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: 7
2093
640
  };
641
+ const CORE_WARN_CODES_EXTEND_POINT = 8;
2094
642
  /** @internal */
2095
643
  const warnMessages = {
2096
644
  [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
@@ -2105,18 +653,16 @@ function getWarnMessage(code, ...args) {
2105
653
  return format$1(warnMessages[code], ...args);
2106
654
  }
2107
655
 
2108
- const code = CompileErrorCodes.__EXTEND_POINT__;
2109
- const inc = incrementer(code);
2110
656
  const CoreErrorCodes = {
2111
- INVALID_ARGUMENT: code, // 17
2112
- INVALID_DATE_ARGUMENT: inc(), // 18
2113
- INVALID_ISO_DATE_ARGUMENT: inc(), // 19
2114
- NOT_SUPPORT_NON_STRING_MESSAGE: inc(), // 20
2115
- NOT_SUPPORT_LOCALE_PROMISE_VALUE: inc(), // 21
2116
- NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: inc(), // 22
2117
- NOT_SUPPORT_LOCALE_TYPE: inc(), // 23
2118
- __EXTEND_POINT__: inc() // 24
657
+ INVALID_ARGUMENT: COMPILE_ERROR_CODES_EXTEND_POINT, // 17
658
+ INVALID_DATE_ARGUMENT: 18,
659
+ INVALID_ISO_DATE_ARGUMENT: 19,
660
+ NOT_SUPPORT_NON_STRING_MESSAGE: 20,
661
+ NOT_SUPPORT_LOCALE_PROMISE_VALUE: 21,
662
+ NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: 22,
663
+ NOT_SUPPORT_LOCALE_TYPE: 23
2119
664
  };
665
+ const CORE_ERROR_CODES_EXTEND_POINT = 24;
2120
666
  function createCoreError(code) {
2121
667
  return createCompileError(code, null, { messages: errorMessages } );
2122
668
  }
@@ -2285,7 +831,7 @@ function appendItemToChain(chain, target, blocks) {
2285
831
  * Intlify core-base version
2286
832
  * @internal
2287
833
  */
2288
- const VERSION = '10.0.0-alpha.4';
834
+ const VERSION = '10.0.0-beta.1';
2289
835
  const NOT_REOSLVED = -1;
2290
836
  const DEFAULT_LOCALE = 'en-US';
2291
837
  const MISSING_RESOLVE_VALUE = '';
@@ -2601,13 +1147,6 @@ function formatMessagePart(ctx, node) {
2601
1147
  }
2602
1148
  }
2603
1149
 
2604
- const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
2605
- function checkHtmlMessage(source, warnHtmlMessage) {
2606
- if (warnHtmlMessage && detectHtmlTag(source)) {
2607
- warn(format$1(WARN_MESSAGE, { source }));
2608
- }
2609
- }
2610
- const defaultOnCacheKey = (message) => message;
2611
1150
  let compileCache = Object.create(null);
2612
1151
  function clearCompileCache() {
2613
1152
  compileCache = Object.create(null);
@@ -2615,55 +1154,9 @@ function clearCompileCache() {
2615
1154
  const isMessageAST = (val) => isObject(val) &&
2616
1155
  (val.t === 0 || val.type === 0) &&
2617
1156
  ('b' in val || 'body' in val);
2618
- function baseCompile(message, options = {}) {
2619
- // error detecting on compile
2620
- let detectError = false;
2621
- const onError = options.onError || defaultOnError;
2622
- options.onError = (err) => {
2623
- detectError = true;
2624
- onError(err);
2625
- };
2626
- // compile with mesasge-compiler
2627
- return { ...baseCompile$1(message, options), detectError };
2628
- }
2629
1157
  /* #__NO_SIDE_EFFECTS__ */
2630
- const compileToFunction = (message, context) => {
2631
- if (!isString(message)) {
2632
- throw createCoreError(CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE);
2633
- }
2634
- {
2635
- warn(`Runtime compilation is not supported in ${'core.runtime.esm-browser.js' }.`);
2636
- return (() => message);
2637
- }
2638
- };
2639
1158
  function compile(message, context) {
2640
- if (isString(message)) {
2641
- // check HTML message
2642
- const warnHtmlMessage = isBoolean(context.warnHtmlMessage)
2643
- ? context.warnHtmlMessage
2644
- : true;
2645
- checkHtmlMessage(message, warnHtmlMessage);
2646
- // check caches
2647
- const onCacheKey = context.onCacheKey || defaultOnCacheKey;
2648
- const cacheKey = onCacheKey(message);
2649
- const cached = compileCache[cacheKey];
2650
- if (cached) {
2651
- return cached;
2652
- }
2653
- // compile with JIT mode
2654
- const { ast, detectError } = baseCompile(message, {
2655
- ...context,
2656
- location: true,
2657
- jit: true
2658
- });
2659
- // compose message function from AST
2660
- const msg = format(ast);
2661
- // if occurred compile error, don't cache
2662
- return !detectError
2663
- ? (compileCache[cacheKey] = msg)
2664
- : msg;
2665
- }
2666
- else {
1159
+ {
2667
1160
  if (!isMessageAST(message)) {
2668
1161
  warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);
2669
1162
  return (() => message);
@@ -2708,8 +1201,10 @@ function translate(context, ...args) {
2708
1201
  : (!messageCompiler ? () => key : key)
2709
1202
  : fallbackFormat // default by `fallbackFormat` option
2710
1203
  ? (!messageCompiler ? () => key : key)
2711
- : '';
2712
- const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
1204
+ : null;
1205
+ const enableDefaultMsg = fallbackFormat ||
1206
+ (defaultMsgOrKey != null &&
1207
+ (isString(defaultMsgOrKey) || isFunction(defaultMsgOrKey)));
2713
1208
  const locale = getLocale(context, options);
2714
1209
  // escape params
2715
1210
  escapeParameter && escapeParams(options);
@@ -3419,9 +1914,11 @@ function clearNumberFormat(ctx, locale, format) {
3419
1914
  }
3420
1915
  }
3421
1916
 
1917
+ // register message compiler for jit compilation
1918
+ registerMessageCompiler(compile);
3422
1919
  // register message resolver at @intlify/core
3423
1920
  registerMessageResolver(resolveValue);
3424
1921
  // register fallback locale at @intlify/core
3425
1922
  registerLocaleFallbacker(fallbackWithLocaleChain);
3426
1923
 
3427
- export { CompileErrorCodes, CoreErrorCodes, CoreWarnCodes, DATETIME_FORMAT_OPTIONS_KEYS, DEFAULT_LOCALE, DEFAULT_MESSAGE_DATA_TYPE, MISSING_RESOLVE_VALUE, NOT_REOSLVED, NUMBER_FORMAT_OPTIONS_KEYS, VERSION, clearCompileCache, clearDateTimeFormat, clearNumberFormat, compile, compileToFunction, createCompileError, createCoreContext, createCoreError, createMessageContext, datetime, fallbackWithLocaleChain, fallbackWithSimple, getAdditionalMeta, getDevToolsHook, getFallbackContext, getLocale, getWarnMessage, handleMissing, initI18nDevTools, isAlmostSameLocale, isImplicitFallback, isMessageAST, isMessageFunction, isTranslateFallbackWarn, isTranslateMissingWarn, number, parse, parseDateTimeArgs, parseNumberArgs, parseTranslateArgs, registerLocaleFallbacker, registerMessageCompiler, registerMessageResolver, resolveLocale, resolveValue, resolveWithKeyValue, setAdditionalMeta, setDevToolsHook, setFallbackContext, translate, translateDevTools, updateFallbackLocale };
1924
+ export { CORE_ERROR_CODES_EXTEND_POINT, CORE_WARN_CODES_EXTEND_POINT, CompileErrorCodes, CoreErrorCodes, CoreWarnCodes, DATETIME_FORMAT_OPTIONS_KEYS, DEFAULT_LOCALE, DEFAULT_MESSAGE_DATA_TYPE, MISSING_RESOLVE_VALUE, NOT_REOSLVED, NUMBER_FORMAT_OPTIONS_KEYS, VERSION, clearCompileCache, clearDateTimeFormat, clearNumberFormat, compile, createCompileError, createCoreContext, createCoreError, createMessageContext, datetime, fallbackWithLocaleChain, fallbackWithSimple, getAdditionalMeta, getDevToolsHook, getFallbackContext, getLocale, getWarnMessage, handleMissing, initI18nDevTools, isAlmostSameLocale, isImplicitFallback, isMessageAST, isMessageFunction, isTranslateFallbackWarn, isTranslateMissingWarn, number, parse, parseDateTimeArgs, parseNumberArgs, parseTranslateArgs, registerLocaleFallbacker, registerMessageCompiler, registerMessageResolver, resolveLocale, resolveValue, resolveWithKeyValue, setAdditionalMeta, setDevToolsHook, setFallbackContext, translate, translateDevTools, updateFallbackLocale };