@intlify/message-compiler 12.0.0-alpha.2 → 12.0.0-alpha.4

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