1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | import { ref, getCurrentInstance, computed, watch, onBeforeMount, onUnmounted } from '@vue/composition-api';
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | const inBrowser = typeof window !== 'undefined';
|
13 | let mark;
|
14 | {
|
15 | const perf = inBrowser && window.performance;
|
16 | if (perf &&
|
17 | perf.mark &&
|
18 | perf.measure &&
|
19 | perf.clearMarks &&
|
20 | perf.clearMeasures) {
|
21 | mark = (tag) => perf.mark(tag);
|
22 | }
|
23 | }
|
24 | const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
|
25 |
|
26 | function format(message, ...args) {
|
27 | if (args.length === 1 && isObject(args[0])) {
|
28 | args = args[0];
|
29 | }
|
30 | if (!args || !args.hasOwnProperty) {
|
31 | args = {};
|
32 | }
|
33 | return message.replace(RE_ARGS, (match, identifier) => {
|
34 | return args.hasOwnProperty(identifier) ? args[identifier] : '';
|
35 | });
|
36 | }
|
37 | const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
|
38 | const makeSymbol = (name) => hasSymbol ? Symbol(name) : name;
|
39 | const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
|
40 | const friendlyJSONstringify = (json) => JSON.stringify(json)
|
41 | .replace(/\u2028/g, '\\u2028')
|
42 | .replace(/\u2029/g, '\\u2029')
|
43 | .replace(/\u0027/g, '\\u0027');
|
44 | const isNumber = (val) => typeof val === 'number' && isFinite(val);
|
45 | const isDate = (val) => toTypeString(val) === '[object Date]';
|
46 | const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
|
47 | const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
|
48 | function warn(msg, err) {
|
49 | if (typeof console !== 'undefined') {
|
50 | console.warn(`[intlify] ` + msg);
|
51 |
|
52 | if (err) {
|
53 | console.warn(err.stack);
|
54 | }
|
55 | }
|
56 | }
|
57 | const assign = Object.assign;
|
58 | let _globalThis;
|
59 | const getGlobalThis = () => {
|
60 |
|
61 | return (_globalThis ||
|
62 | (_globalThis =
|
63 | typeof globalThis !== 'undefined'
|
64 | ? globalThis
|
65 | : typeof self !== 'undefined'
|
66 | ? self
|
67 | : typeof window !== 'undefined'
|
68 | ? window
|
69 | : typeof global !== 'undefined'
|
70 | ? global
|
71 | : {}));
|
72 | };
|
73 | function escapeHtml(rawText) {
|
74 | return rawText
|
75 | .replace(/</g, '<')
|
76 | .replace(/>/g, '>')
|
77 | .replace(/"/g, '"')
|
78 | .replace(/'/g, ''');
|
79 | }
|
80 | const hasOwnProperty = Object.prototype.hasOwnProperty;
|
81 | function hasOwn(obj, key) {
|
82 | return hasOwnProperty.call(obj, key);
|
83 | }
|
84 |
|
85 |
|
86 |
|
87 |
|
88 |
|
89 |
|
90 |
|
91 |
|
92 | const isArray = Array.isArray;
|
93 | const isFunction = (val) => typeof val === 'function';
|
94 | const isString = (val) => typeof val === 'string';
|
95 | const isBoolean = (val) => typeof val === 'boolean';
|
96 | const isObject = (val) =>
|
97 | val !== null && typeof val === 'object';
|
98 | const objectToString = Object.prototype.toString;
|
99 | const toTypeString = (value) => objectToString.call(value);
|
100 | const isPlainObject = (val) => toTypeString(val) === '[object Object]';
|
101 |
|
102 | const toDisplayString = (val) => {
|
103 | return val == null
|
104 | ? ''
|
105 | : isArray(val) || (isPlainObject(val) && val.toString === objectToString)
|
106 | ? JSON.stringify(val, null, 2)
|
107 | : String(val);
|
108 | };
|
109 |
|
110 | const CompileErrorCodes = {
|
111 |
|
112 | EXPECTED_TOKEN: 1,
|
113 | INVALID_TOKEN_IN_PLACEHOLDER: 2,
|
114 | UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
|
115 | UNKNOWN_ESCAPE_SEQUENCE: 4,
|
116 | INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
|
117 | UNBALANCED_CLOSING_BRACE: 6,
|
118 | UNTERMINATED_CLOSING_BRACE: 7,
|
119 | EMPTY_PLACEHOLDER: 8,
|
120 | NOT_ALLOW_NEST_PLACEHOLDER: 9,
|
121 | INVALID_LINKED_FORMAT: 10,
|
122 |
|
123 | MUST_HAVE_MESSAGES_IN_PLURAL: 11,
|
124 | UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
|
125 | UNEXPECTED_EMPTY_LINKED_KEY: 13,
|
126 | UNEXPECTED_LEXICAL_ANALYSIS: 14,
|
127 |
|
128 |
|
129 |
|
130 | __EXTEND_POINT__: 15
|
131 | };
|
132 |
|
133 | const errorMessages$2 = {
|
134 |
|
135 | [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
|
136 | [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
|
137 | [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
|
138 | [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
|
139 | [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
|
140 | [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
|
141 | [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
|
142 | [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
|
143 | [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
|
144 | [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
|
145 |
|
146 | [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
|
147 | [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
|
148 | [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
|
149 | [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`
|
150 | };
|
151 | function createCompileError(code, loc, options = {}) {
|
152 | const { domain, messages, args } = options;
|
153 | const msg = format((messages || errorMessages$2)[code] || '', ...(args || []))
|
154 | ;
|
155 | const error = new SyntaxError(String(msg));
|
156 | error.code = code;
|
157 | if (loc) {
|
158 | error.location = loc;
|
159 | }
|
160 | error.domain = domain;
|
161 | return error;
|
162 | }
|
163 |
|
164 | function defaultOnError(error) {
|
165 | throw error;
|
166 | }
|
167 |
|
168 | function createPosition(line, column, offset) {
|
169 | return { line, column, offset };
|
170 | }
|
171 | function createLocation(start, end, source) {
|
172 | const loc = { start, end };
|
173 | if (source != null) {
|
174 | loc.source = source;
|
175 | }
|
176 | return loc;
|
177 | }
|
178 |
|
179 | const CHAR_SP = ' ';
|
180 | const CHAR_CR = '\r';
|
181 | const CHAR_LF = '\n';
|
182 | const CHAR_LS = String.fromCharCode(0x2028);
|
183 | const CHAR_PS = String.fromCharCode(0x2029);
|
184 | function createScanner(str) {
|
185 | const _buf = str;
|
186 | let _index = 0;
|
187 | let _line = 1;
|
188 | let _column = 1;
|
189 | let _peekOffset = 0;
|
190 | const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
|
191 | const isLF = (index) => _buf[index] === CHAR_LF;
|
192 | const isPS = (index) => _buf[index] === CHAR_PS;
|
193 | const isLS = (index) => _buf[index] === CHAR_LS;
|
194 | const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
|
195 | const index = () => _index;
|
196 | const line = () => _line;
|
197 | const column = () => _column;
|
198 | const peekOffset = () => _peekOffset;
|
199 | const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
|
200 | const currentChar = () => charAt(_index);
|
201 | const currentPeek = () => charAt(_index + _peekOffset);
|
202 | function next() {
|
203 | _peekOffset = 0;
|
204 | if (isLineEnd(_index)) {
|
205 | _line++;
|
206 | _column = 0;
|
207 | }
|
208 | if (isCRLF(_index)) {
|
209 | _index++;
|
210 | }
|
211 | _index++;
|
212 | _column++;
|
213 | return _buf[_index];
|
214 | }
|
215 | function peek() {
|
216 | if (isCRLF(_index + _peekOffset)) {
|
217 | _peekOffset++;
|
218 | }
|
219 | _peekOffset++;
|
220 | return _buf[_index + _peekOffset];
|
221 | }
|
222 | function reset() {
|
223 | _index = 0;
|
224 | _line = 1;
|
225 | _column = 1;
|
226 | _peekOffset = 0;
|
227 | }
|
228 | function resetPeek(offset = 0) {
|
229 | _peekOffset = offset;
|
230 | }
|
231 | function skipToPeek() {
|
232 | const target = _index + _peekOffset;
|
233 |
|
234 | while (target !== _index) {
|
235 | next();
|
236 | }
|
237 | _peekOffset = 0;
|
238 | }
|
239 | return {
|
240 | index,
|
241 | line,
|
242 | column,
|
243 | peekOffset,
|
244 | charAt,
|
245 | currentChar,
|
246 | currentPeek,
|
247 | next,
|
248 | peek,
|
249 | reset,
|
250 | resetPeek,
|
251 | skipToPeek
|
252 | };
|
253 | }
|
254 |
|
255 | const EOF = undefined;
|
256 | const LITERAL_DELIMITER = "'";
|
257 | const ERROR_DOMAIN$1 = 'tokenizer';
|
258 | function createTokenizer(source, options = {}) {
|
259 | const location = options.location !== false;
|
260 | const _scnr = createScanner(source);
|
261 | const currentOffset = () => _scnr.index();
|
262 | const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
|
263 | const _initLoc = currentPosition();
|
264 | const _initOffset = currentOffset();
|
265 | const _context = {
|
266 | currentType: 14 ,
|
267 | offset: _initOffset,
|
268 | startLoc: _initLoc,
|
269 | endLoc: _initLoc,
|
270 | lastType: 14 ,
|
271 | lastOffset: _initOffset,
|
272 | lastStartLoc: _initLoc,
|
273 | lastEndLoc: _initLoc,
|
274 | braceNest: 0,
|
275 | inLinked: false,
|
276 | text: ''
|
277 | };
|
278 | const context = () => _context;
|
279 | const { onError } = options;
|
280 | function emitError(code, pos, offset, ...args) {
|
281 | const ctx = context();
|
282 | pos.column += offset;
|
283 | pos.offset += offset;
|
284 | if (onError) {
|
285 | const loc = createLocation(ctx.startLoc, pos);
|
286 | const err = createCompileError(code, loc, {
|
287 | domain: ERROR_DOMAIN$1,
|
288 | args
|
289 | });
|
290 | onError(err);
|
291 | }
|
292 | }
|
293 | function getToken(context, type, value) {
|
294 | context.endLoc = currentPosition();
|
295 | context.currentType = type;
|
296 | const token = { type };
|
297 | if (location) {
|
298 | token.loc = createLocation(context.startLoc, context.endLoc);
|
299 | }
|
300 | if (value != null) {
|
301 | token.value = value;
|
302 | }
|
303 | return token;
|
304 | }
|
305 | const getEndToken = (context) => getToken(context, 14 );
|
306 | function eat(scnr, ch) {
|
307 | if (scnr.currentChar() === ch) {
|
308 | scnr.next();
|
309 | return ch;
|
310 | }
|
311 | else {
|
312 | emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
|
313 | return '';
|
314 | }
|
315 | }
|
316 | function peekSpaces(scnr) {
|
317 | let buf = '';
|
318 | while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
|
319 | buf += scnr.currentPeek();
|
320 | scnr.peek();
|
321 | }
|
322 | return buf;
|
323 | }
|
324 | function skipSpaces(scnr) {
|
325 | const buf = peekSpaces(scnr);
|
326 | scnr.skipToPeek();
|
327 | return buf;
|
328 | }
|
329 | function isIdentifierStart(ch) {
|
330 | if (ch === EOF) {
|
331 | return false;
|
332 | }
|
333 | const cc = ch.charCodeAt(0);
|
334 | return ((cc >= 97 && cc <= 122) ||
|
335 | (cc >= 65 && cc <= 90) ||
|
336 | cc === 95
|
337 | );
|
338 | }
|
339 | function isNumberStart(ch) {
|
340 | if (ch === EOF) {
|
341 | return false;
|
342 | }
|
343 | const cc = ch.charCodeAt(0);
|
344 | return cc >= 48 && cc <= 57;
|
345 | }
|
346 | function isNamedIdentifierStart(scnr, context) {
|
347 | const { currentType } = context;
|
348 | if (currentType !== 2 ) {
|
349 | return false;
|
350 | }
|
351 | peekSpaces(scnr);
|
352 | const ret = isIdentifierStart(scnr.currentPeek());
|
353 | scnr.resetPeek();
|
354 | return ret;
|
355 | }
|
356 | function isListIdentifierStart(scnr, context) {
|
357 | const { currentType } = context;
|
358 | if (currentType !== 2 ) {
|
359 | return false;
|
360 | }
|
361 | peekSpaces(scnr);
|
362 | const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
|
363 | const ret = isNumberStart(ch);
|
364 | scnr.resetPeek();
|
365 | return ret;
|
366 | }
|
367 | function isLiteralStart(scnr, context) {
|
368 | const { currentType } = context;
|
369 | if (currentType !== 2 ) {
|
370 | return false;
|
371 | }
|
372 | peekSpaces(scnr);
|
373 | const ret = scnr.currentPeek() === LITERAL_DELIMITER;
|
374 | scnr.resetPeek();
|
375 | return ret;
|
376 | }
|
377 | function isLinkedDotStart(scnr, context) {
|
378 | const { currentType } = context;
|
379 | if (currentType !== 8 ) {
|
380 | return false;
|
381 | }
|
382 | peekSpaces(scnr);
|
383 | const ret = scnr.currentPeek() === "." ;
|
384 | scnr.resetPeek();
|
385 | return ret;
|
386 | }
|
387 | function isLinkedModifierStart(scnr, context) {
|
388 | const { currentType } = context;
|
389 | if (currentType !== 9 ) {
|
390 | return false;
|
391 | }
|
392 | peekSpaces(scnr);
|
393 | const ret = isIdentifierStart(scnr.currentPeek());
|
394 | scnr.resetPeek();
|
395 | return ret;
|
396 | }
|
397 | function isLinkedDelimiterStart(scnr, context) {
|
398 | const { currentType } = context;
|
399 | if (!(currentType === 8 ||
|
400 | currentType === 12 )) {
|
401 | return false;
|
402 | }
|
403 | peekSpaces(scnr);
|
404 | const ret = scnr.currentPeek() === ":" ;
|
405 | scnr.resetPeek();
|
406 | return ret;
|
407 | }
|
408 | function isLinkedReferStart(scnr, context) {
|
409 | const { currentType } = context;
|
410 | if (currentType !== 10 ) {
|
411 | return false;
|
412 | }
|
413 | const fn = () => {
|
414 | const ch = scnr.currentPeek();
|
415 | if (ch === "{" ) {
|
416 | return isIdentifierStart(scnr.peek());
|
417 | }
|
418 | else if (ch === "@" ||
|
419 | ch === "%" ||
|
420 | ch === "|" ||
|
421 | ch === ":" ||
|
422 | ch === "." ||
|
423 | ch === CHAR_SP ||
|
424 | !ch) {
|
425 | return false;
|
426 | }
|
427 | else if (ch === CHAR_LF) {
|
428 | scnr.peek();
|
429 | return fn();
|
430 | }
|
431 | else {
|
432 |
|
433 | return isIdentifierStart(ch);
|
434 | }
|
435 | };
|
436 | const ret = fn();
|
437 | scnr.resetPeek();
|
438 | return ret;
|
439 | }
|
440 | function isPluralStart(scnr) {
|
441 | peekSpaces(scnr);
|
442 | const ret = scnr.currentPeek() === "|" ;
|
443 | scnr.resetPeek();
|
444 | return ret;
|
445 | }
|
446 | function isTextStart(scnr, reset = true) {
|
447 | const fn = (hasSpace = false, prev = '', detectModulo = false) => {
|
448 | const ch = scnr.currentPeek();
|
449 | if (ch === "{" ) {
|
450 | return prev === "%" ? false : hasSpace;
|
451 | }
|
452 | else if (ch === "@" || !ch) {
|
453 | return prev === "%" ? true : hasSpace;
|
454 | }
|
455 | else if (ch === "%" ) {
|
456 | scnr.peek();
|
457 | return fn(hasSpace, "%" , true);
|
458 | }
|
459 | else if (ch === "|" ) {
|
460 | return prev === "%" || detectModulo
|
461 | ? true
|
462 | : !(prev === CHAR_SP || prev === CHAR_LF);
|
463 | }
|
464 | else if (ch === CHAR_SP) {
|
465 | scnr.peek();
|
466 | return fn(true, CHAR_SP, detectModulo);
|
467 | }
|
468 | else if (ch === CHAR_LF) {
|
469 | scnr.peek();
|
470 | return fn(true, CHAR_LF, detectModulo);
|
471 | }
|
472 | else {
|
473 | return true;
|
474 | }
|
475 | };
|
476 | const ret = fn();
|
477 | reset && scnr.resetPeek();
|
478 | return ret;
|
479 | }
|
480 | function takeChar(scnr, fn) {
|
481 | const ch = scnr.currentChar();
|
482 | if (ch === EOF) {
|
483 | return EOF;
|
484 | }
|
485 | if (fn(ch)) {
|
486 | scnr.next();
|
487 | return ch;
|
488 | }
|
489 | return null;
|
490 | }
|
491 | function takeIdentifierChar(scnr) {
|
492 | const closure = (ch) => {
|
493 | const cc = ch.charCodeAt(0);
|
494 | return ((cc >= 97 && cc <= 122) ||
|
495 | (cc >= 65 && cc <= 90) ||
|
496 | (cc >= 48 && cc <= 57) ||
|
497 | cc === 95 ||
|
498 | cc === 36
|
499 | );
|
500 | };
|
501 | return takeChar(scnr, closure);
|
502 | }
|
503 | function takeDigit(scnr) {
|
504 | const closure = (ch) => {
|
505 | const cc = ch.charCodeAt(0);
|
506 | return cc >= 48 && cc <= 57;
|
507 | };
|
508 | return takeChar(scnr, closure);
|
509 | }
|
510 | function takeHexDigit(scnr) {
|
511 | const closure = (ch) => {
|
512 | const cc = ch.charCodeAt(0);
|
513 | return ((cc >= 48 && cc <= 57) ||
|
514 | (cc >= 65 && cc <= 70) ||
|
515 | (cc >= 97 && cc <= 102));
|
516 | };
|
517 | return takeChar(scnr, closure);
|
518 | }
|
519 | function getDigits(scnr) {
|
520 | let ch = '';
|
521 | let num = '';
|
522 | while ((ch = takeDigit(scnr))) {
|
523 | num += ch;
|
524 | }
|
525 | return num;
|
526 | }
|
527 | function readText(scnr) {
|
528 | const fn = (buf) => {
|
529 | const ch = scnr.currentChar();
|
530 | if (ch === "{" ||
|
531 | ch === "}" ||
|
532 | ch === "@" ||
|
533 | !ch) {
|
534 | return buf;
|
535 | }
|
536 | else if (ch === "%" ) {
|
537 | if (isTextStart(scnr)) {
|
538 | buf += ch;
|
539 | scnr.next();
|
540 | return fn(buf);
|
541 | }
|
542 | else {
|
543 | return buf;
|
544 | }
|
545 | }
|
546 | else if (ch === "|" ) {
|
547 | return buf;
|
548 | }
|
549 | else if (ch === CHAR_SP || ch === CHAR_LF) {
|
550 | if (isTextStart(scnr)) {
|
551 | buf += ch;
|
552 | scnr.next();
|
553 | return fn(buf);
|
554 | }
|
555 | else if (isPluralStart(scnr)) {
|
556 | return buf;
|
557 | }
|
558 | else {
|
559 | buf += ch;
|
560 | scnr.next();
|
561 | return fn(buf);
|
562 | }
|
563 | }
|
564 | else {
|
565 | buf += ch;
|
566 | scnr.next();
|
567 | return fn(buf);
|
568 | }
|
569 | };
|
570 | return fn('');
|
571 | }
|
572 | function readNamedIdentifier(scnr) {
|
573 | skipSpaces(scnr);
|
574 | let ch = '';
|
575 | let name = '';
|
576 | while ((ch = takeIdentifierChar(scnr))) {
|
577 | name += ch;
|
578 | }
|
579 | if (scnr.currentChar() === EOF) {
|
580 | emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
|
581 | }
|
582 | return name;
|
583 | }
|
584 | function readListIdentifier(scnr) {
|
585 | skipSpaces(scnr);
|
586 | let value = '';
|
587 | if (scnr.currentChar() === '-') {
|
588 | scnr.next();
|
589 | value += `-${getDigits(scnr)}`;
|
590 | }
|
591 | else {
|
592 | value += getDigits(scnr);
|
593 | }
|
594 | if (scnr.currentChar() === EOF) {
|
595 | emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
|
596 | }
|
597 | return value;
|
598 | }
|
599 | function readLiteral(scnr) {
|
600 | skipSpaces(scnr);
|
601 | eat(scnr, `\'`);
|
602 | let ch = '';
|
603 | let literal = '';
|
604 | const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF;
|
605 | while ((ch = takeChar(scnr, fn))) {
|
606 | if (ch === '\\') {
|
607 | literal += readEscapeSequence(scnr);
|
608 | }
|
609 | else {
|
610 | literal += ch;
|
611 | }
|
612 | }
|
613 | const current = scnr.currentChar();
|
614 | if (current === CHAR_LF || current === EOF) {
|
615 | emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
|
616 |
|
617 | if (current === CHAR_LF) {
|
618 | scnr.next();
|
619 | eat(scnr, `\'`);
|
620 | }
|
621 | return literal;
|
622 | }
|
623 | eat(scnr, `\'`);
|
624 | return literal;
|
625 | }
|
626 | function readEscapeSequence(scnr) {
|
627 | const ch = scnr.currentChar();
|
628 | switch (ch) {
|
629 | case '\\':
|
630 | case `\'`:
|
631 | scnr.next();
|
632 | return `\\${ch}`;
|
633 | case 'u':
|
634 | return readUnicodeEscapeSequence(scnr, ch, 4);
|
635 | case 'U':
|
636 | return readUnicodeEscapeSequence(scnr, ch, 6);
|
637 | default:
|
638 | emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
|
639 | return '';
|
640 | }
|
641 | }
|
642 | function readUnicodeEscapeSequence(scnr, unicode, digits) {
|
643 | eat(scnr, unicode);
|
644 | let sequence = '';
|
645 | for (let i = 0; i < digits; i++) {
|
646 | const ch = takeHexDigit(scnr);
|
647 | if (!ch) {
|
648 | emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
|
649 | break;
|
650 | }
|
651 | sequence += ch;
|
652 | }
|
653 | return `\\${unicode}${sequence}`;
|
654 | }
|
655 | function readInvalidIdentifier(scnr) {
|
656 | skipSpaces(scnr);
|
657 | let ch = '';
|
658 | let identifiers = '';
|
659 | const closure = (ch) => ch !== "{" &&
|
660 | ch !== "}" &&
|
661 | ch !== CHAR_SP &&
|
662 | ch !== CHAR_LF;
|
663 | while ((ch = takeChar(scnr, closure))) {
|
664 | identifiers += ch;
|
665 | }
|
666 | return identifiers;
|
667 | }
|
668 | function readLinkedModifier(scnr) {
|
669 | let ch = '';
|
670 | let name = '';
|
671 | while ((ch = takeIdentifierChar(scnr))) {
|
672 | name += ch;
|
673 | }
|
674 | return name;
|
675 | }
|
676 | function readLinkedRefer(scnr) {
|
677 | const fn = (detect = false, buf) => {
|
678 | const ch = scnr.currentChar();
|
679 | if (ch === "{" ||
|
680 | ch === "%" ||
|
681 | ch === "@" ||
|
682 | ch === "|" ||
|
683 | !ch) {
|
684 | return buf;
|
685 | }
|
686 | else if (ch === CHAR_SP) {
|
687 | return buf;
|
688 | }
|
689 | else if (ch === CHAR_LF) {
|
690 | buf += ch;
|
691 | scnr.next();
|
692 | return fn(detect, buf);
|
693 | }
|
694 | else {
|
695 | buf += ch;
|
696 | scnr.next();
|
697 | return fn(true, buf);
|
698 | }
|
699 | };
|
700 | return fn(false, '');
|
701 | }
|
702 | function readPlural(scnr) {
|
703 | skipSpaces(scnr);
|
704 | const plural = eat(scnr, "|" );
|
705 | skipSpaces(scnr);
|
706 | return plural;
|
707 | }
|
708 |
|
709 | function readTokenInPlaceholder(scnr, context) {
|
710 | let token = null;
|
711 | const ch = scnr.currentChar();
|
712 | switch (ch) {
|
713 | case "{" :
|
714 | if (context.braceNest >= 1) {
|
715 | emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
|
716 | }
|
717 | scnr.next();
|
718 | token = getToken(context, 2 , "{" );
|
719 | skipSpaces(scnr);
|
720 | context.braceNest++;
|
721 | return token;
|
722 | case "}" :
|
723 | if (context.braceNest > 0 &&
|
724 | context.currentType === 2 ) {
|
725 | emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
|
726 | }
|
727 | scnr.next();
|
728 | token = getToken(context, 3 , "}" );
|
729 | context.braceNest--;
|
730 | context.braceNest > 0 && skipSpaces(scnr);
|
731 | if (context.inLinked && context.braceNest === 0) {
|
732 | context.inLinked = false;
|
733 | }
|
734 | return token;
|
735 | case "@" :
|
736 | if (context.braceNest > 0) {
|
737 | emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
|
738 | }
|
739 | token = readTokenInLinked(scnr, context) || getEndToken(context);
|
740 | context.braceNest = 0;
|
741 | return token;
|
742 | default:
|
743 | let validNamedIdentifier = true;
|
744 | let validListIdentifier = true;
|
745 | let validLiteral = true;
|
746 | if (isPluralStart(scnr)) {
|
747 | if (context.braceNest > 0) {
|
748 | emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
|
749 | }
|
750 | token = getToken(context, 1 , readPlural(scnr));
|
751 |
|
752 | context.braceNest = 0;
|
753 | context.inLinked = false;
|
754 | return token;
|
755 | }
|
756 | if (context.braceNest > 0 &&
|
757 | (context.currentType === 5 ||
|
758 | context.currentType === 6 ||
|
759 | context.currentType === 7 )) {
|
760 | emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
|
761 | context.braceNest = 0;
|
762 | return readToken(scnr, context);
|
763 | }
|
764 | if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
|
765 | token = getToken(context, 5 , readNamedIdentifier(scnr));
|
766 | skipSpaces(scnr);
|
767 | return token;
|
768 | }
|
769 | if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
|
770 | token = getToken(context, 6 , readListIdentifier(scnr));
|
771 | skipSpaces(scnr);
|
772 | return token;
|
773 | }
|
774 | if ((validLiteral = isLiteralStart(scnr, context))) {
|
775 | token = getToken(context, 7 , readLiteral(scnr));
|
776 | skipSpaces(scnr);
|
777 | return token;
|
778 | }
|
779 | if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
|
780 |
|
781 | token = getToken(context, 13 , readInvalidIdentifier(scnr));
|
782 | emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
|
783 | skipSpaces(scnr);
|
784 | return token;
|
785 | }
|
786 | break;
|
787 | }
|
788 | return token;
|
789 | }
|
790 |
|
791 | function readTokenInLinked(scnr, context) {
|
792 | const { currentType } = context;
|
793 | let token = null;
|
794 | const ch = scnr.currentChar();
|
795 | if ((currentType === 8 ||
|
796 | currentType === 9 ||
|
797 | currentType === 12 ||
|
798 | currentType === 10 ) &&
|
799 | (ch === CHAR_LF || ch === CHAR_SP)) {
|
800 | emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
|
801 | }
|
802 | switch (ch) {
|
803 | case "@" :
|
804 | scnr.next();
|
805 | token = getToken(context, 8 , "@" );
|
806 | context.inLinked = true;
|
807 | return token;
|
808 | case "." :
|
809 | skipSpaces(scnr);
|
810 | scnr.next();
|
811 | return getToken(context, 9 , "." );
|
812 | case ":" :
|
813 | skipSpaces(scnr);
|
814 | scnr.next();
|
815 | return getToken(context, 10 , ":" );
|
816 | default:
|
817 | if (isPluralStart(scnr)) {
|
818 | token = getToken(context, 1 , readPlural(scnr));
|
819 |
|
820 | context.braceNest = 0;
|
821 | context.inLinked = false;
|
822 | return token;
|
823 | }
|
824 | if (isLinkedDotStart(scnr, context) ||
|
825 | isLinkedDelimiterStart(scnr, context)) {
|
826 | skipSpaces(scnr);
|
827 | return readTokenInLinked(scnr, context);
|
828 | }
|
829 | if (isLinkedModifierStart(scnr, context)) {
|
830 | skipSpaces(scnr);
|
831 | return getToken(context, 12 , readLinkedModifier(scnr));
|
832 | }
|
833 | if (isLinkedReferStart(scnr, context)) {
|
834 | skipSpaces(scnr);
|
835 | if (ch === "{" ) {
|
836 |
|
837 | return readTokenInPlaceholder(scnr, context) || token;
|
838 | }
|
839 | else {
|
840 | return getToken(context, 11 , readLinkedRefer(scnr));
|
841 | }
|
842 | }
|
843 | if (currentType === 8 ) {
|
844 | emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
|
845 | }
|
846 | context.braceNest = 0;
|
847 | context.inLinked = false;
|
848 | return readToken(scnr, context);
|
849 | }
|
850 | }
|
851 |
|
852 | function readToken(scnr, context) {
|
853 | let token = { type: 14 };
|
854 | if (context.braceNest > 0) {
|
855 | return readTokenInPlaceholder(scnr, context) || getEndToken(context);
|
856 | }
|
857 | if (context.inLinked) {
|
858 | return readTokenInLinked(scnr, context) || getEndToken(context);
|
859 | }
|
860 | const ch = scnr.currentChar();
|
861 | switch (ch) {
|
862 | case "{" :
|
863 | return readTokenInPlaceholder(scnr, context) || getEndToken(context);
|
864 | case "}" :
|
865 | emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
|
866 | scnr.next();
|
867 | return getToken(context, 3 , "}" );
|
868 | case "@" :
|
869 | return readTokenInLinked(scnr, context) || getEndToken(context);
|
870 | default:
|
871 | if (isPluralStart(scnr)) {
|
872 | token = getToken(context, 1 , readPlural(scnr));
|
873 |
|
874 | context.braceNest = 0;
|
875 | context.inLinked = false;
|
876 | return token;
|
877 | }
|
878 | if (isTextStart(scnr)) {
|
879 | return getToken(context, 0 , readText(scnr));
|
880 | }
|
881 | if (ch === "%" ) {
|
882 | scnr.next();
|
883 | return getToken(context, 4 , "%" );
|
884 | }
|
885 | break;
|
886 | }
|
887 | return token;
|
888 | }
|
889 | function nextToken() {
|
890 | const { currentType, offset, startLoc, endLoc } = _context;
|
891 | _context.lastType = currentType;
|
892 | _context.lastOffset = offset;
|
893 | _context.lastStartLoc = startLoc;
|
894 | _context.lastEndLoc = endLoc;
|
895 | _context.offset = currentOffset();
|
896 | _context.startLoc = currentPosition();
|
897 | if (_scnr.currentChar() === EOF) {
|
898 | return getToken(_context, 14 );
|
899 | }
|
900 | return readToken(_scnr, _context);
|
901 | }
|
902 | return {
|
903 | nextToken,
|
904 | currentOffset,
|
905 | currentPosition,
|
906 | context
|
907 | };
|
908 | }
|
909 |
|
910 | const ERROR_DOMAIN = 'parser';
|
911 |
|
912 | const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
|
913 | function fromEscapeSequence(match, codePoint4, codePoint6) {
|
914 | switch (match) {
|
915 | case `\\\\`:
|
916 | return `\\`;
|
917 | case `\\\'`:
|
918 | return `\'`;
|
919 | default: {
|
920 | const codePoint = parseInt(codePoint4 || codePoint6, 16);
|
921 | if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
|
922 | return String.fromCodePoint(codePoint);
|
923 | }
|
924 |
|
925 |
|
926 | return '�';
|
927 | }
|
928 | }
|
929 | }
|
930 | function createParser(options = {}) {
|
931 | const location = options.location !== false;
|
932 | const { onError } = options;
|
933 | function emitError(tokenzer, code, start, offset, ...args) {
|
934 | const end = tokenzer.currentPosition();
|
935 | end.offset += offset;
|
936 | end.column += offset;
|
937 | if (onError) {
|
938 | const loc = createLocation(start, end);
|
939 | const err = createCompileError(code, loc, {
|
940 | domain: ERROR_DOMAIN,
|
941 | args
|
942 | });
|
943 | onError(err);
|
944 | }
|
945 | }
|
946 | function startNode(type, offset, loc) {
|
947 | const node = {
|
948 | type,
|
949 | start: offset,
|
950 | end: offset
|
951 | };
|
952 | if (location) {
|
953 | node.loc = { start: loc, end: loc };
|
954 | }
|
955 | return node;
|
956 | }
|
957 | function endNode(node, offset, pos, type) {
|
958 | node.end = offset;
|
959 | if (type) {
|
960 | node.type = type;
|
961 | }
|
962 | if (location && node.loc) {
|
963 | node.loc.end = pos;
|
964 | }
|
965 | }
|
966 | function parseText(tokenizer, value) {
|
967 | const context = tokenizer.context();
|
968 | const node = startNode(3 , context.offset, context.startLoc);
|
969 | node.value = value;
|
970 | endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
|
971 | return node;
|
972 | }
|
973 | function parseList(tokenizer, index) {
|
974 | const context = tokenizer.context();
|
975 | const { lastOffset: offset, lastStartLoc: loc } = context;
|
976 | const node = startNode(5 , offset, loc);
|
977 | node.index = parseInt(index, 10);
|
978 | tokenizer.nextToken();
|
979 | endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
|
980 | return node;
|
981 | }
|
982 | function parseNamed(tokenizer, key) {
|
983 | const context = tokenizer.context();
|
984 | const { lastOffset: offset, lastStartLoc: loc } = context;
|
985 | const node = startNode(4 , offset, loc);
|
986 | node.key = key;
|
987 | tokenizer.nextToken();
|
988 | endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
|
989 | return node;
|
990 | }
|
991 | function parseLiteral(tokenizer, value) {
|
992 | const context = tokenizer.context();
|
993 | const { lastOffset: offset, lastStartLoc: loc } = context;
|
994 | const node = startNode(9 , offset, loc);
|
995 | node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
|
996 | tokenizer.nextToken();
|
997 | endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
|
998 | return node;
|
999 | }
|
1000 | function parseLinkedModifier(tokenizer) {
|
1001 | const token = tokenizer.nextToken();
|
1002 | const context = tokenizer.context();
|
1003 | const { lastOffset: offset, lastStartLoc: loc } = context;
|
1004 | const node = startNode(8 , offset, loc);
|
1005 | if (token.type !== 12 ) {
|
1006 |
|
1007 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
|
1008 | node.value = '';
|
1009 | endNode(node, offset, loc);
|
1010 | return {
|
1011 | nextConsumeToken: token,
|
1012 | node
|
1013 | };
|
1014 | }
|
1015 |
|
1016 | if (token.value == null) {
|
1017 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1018 | }
|
1019 | node.value = token.value || '';
|
1020 | endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
|
1021 | return {
|
1022 | node
|
1023 | };
|
1024 | }
|
1025 | function parseLinkedKey(tokenizer, value) {
|
1026 | const context = tokenizer.context();
|
1027 | const node = startNode(7 , context.offset, context.startLoc);
|
1028 | node.value = value;
|
1029 | endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
|
1030 | return node;
|
1031 | }
|
1032 | function parseLinked(tokenizer) {
|
1033 | const context = tokenizer.context();
|
1034 | const linkedNode = startNode(6 , context.offset, context.startLoc);
|
1035 | let token = tokenizer.nextToken();
|
1036 | if (token.type === 9 ) {
|
1037 | const parsed = parseLinkedModifier(tokenizer);
|
1038 | linkedNode.modifier = parsed.node;
|
1039 | token = parsed.nextConsumeToken || tokenizer.nextToken();
|
1040 | }
|
1041 |
|
1042 | if (token.type !== 10 ) {
|
1043 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1044 | }
|
1045 | token = tokenizer.nextToken();
|
1046 |
|
1047 | if (token.type === 2 ) {
|
1048 | token = tokenizer.nextToken();
|
1049 | }
|
1050 | switch (token.type) {
|
1051 | case 11 :
|
1052 | if (token.value == null) {
|
1053 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1054 | }
|
1055 | linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
|
1056 | break;
|
1057 | case 5 :
|
1058 | if (token.value == null) {
|
1059 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1060 | }
|
1061 | linkedNode.key = parseNamed(tokenizer, token.value || '');
|
1062 | break;
|
1063 | case 6 :
|
1064 | if (token.value == null) {
|
1065 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1066 | }
|
1067 | linkedNode.key = parseList(tokenizer, token.value || '');
|
1068 | break;
|
1069 | case 7 :
|
1070 | if (token.value == null) {
|
1071 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1072 | }
|
1073 | linkedNode.key = parseLiteral(tokenizer, token.value || '');
|
1074 | break;
|
1075 | default:
|
1076 |
|
1077 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
|
1078 | const nextContext = tokenizer.context();
|
1079 | const emptyLinkedKeyNode = startNode(7 , nextContext.offset, nextContext.startLoc);
|
1080 | emptyLinkedKeyNode.value = '';
|
1081 | endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
|
1082 | linkedNode.key = emptyLinkedKeyNode;
|
1083 | endNode(linkedNode, nextContext.offset, nextContext.startLoc);
|
1084 | return {
|
1085 | nextConsumeToken: token,
|
1086 | node: linkedNode
|
1087 | };
|
1088 | }
|
1089 | endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
|
1090 | return {
|
1091 | node: linkedNode
|
1092 | };
|
1093 | }
|
1094 | function parseMessage(tokenizer) {
|
1095 | const context = tokenizer.context();
|
1096 | const startOffset = context.currentType === 1
|
1097 | ? tokenizer.currentOffset()
|
1098 | : context.offset;
|
1099 | const startLoc = context.currentType === 1
|
1100 | ? context.endLoc
|
1101 | : context.startLoc;
|
1102 | const node = startNode(2 , startOffset, startLoc);
|
1103 | node.items = [];
|
1104 | let nextToken = null;
|
1105 | do {
|
1106 | const token = nextToken || tokenizer.nextToken();
|
1107 | nextToken = null;
|
1108 | switch (token.type) {
|
1109 | case 0 :
|
1110 | if (token.value == null) {
|
1111 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1112 | }
|
1113 | node.items.push(parseText(tokenizer, token.value || ''));
|
1114 | break;
|
1115 | case 6 :
|
1116 | if (token.value == null) {
|
1117 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1118 | }
|
1119 | node.items.push(parseList(tokenizer, token.value || ''));
|
1120 | break;
|
1121 | case 5 :
|
1122 | if (token.value == null) {
|
1123 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1124 | }
|
1125 | node.items.push(parseNamed(tokenizer, token.value || ''));
|
1126 | break;
|
1127 | case 7 :
|
1128 | if (token.value == null) {
|
1129 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1130 | }
|
1131 | node.items.push(parseLiteral(tokenizer, token.value || ''));
|
1132 | break;
|
1133 | case 8 :
|
1134 | const parsed = parseLinked(tokenizer);
|
1135 | node.items.push(parsed.node);
|
1136 | nextToken = parsed.nextConsumeToken || null;
|
1137 | break;
|
1138 | }
|
1139 | } while (context.currentType !== 14 &&
|
1140 | context.currentType !== 1 );
|
1141 |
|
1142 | const endOffset = context.currentType === 1
|
1143 | ? context.lastOffset
|
1144 | : tokenizer.currentOffset();
|
1145 | const endLoc = context.currentType === 1
|
1146 | ? context.lastEndLoc
|
1147 | : tokenizer.currentPosition();
|
1148 | endNode(node, endOffset, endLoc);
|
1149 | return node;
|
1150 | }
|
1151 | function parsePlural(tokenizer, offset, loc, msgNode) {
|
1152 | const context = tokenizer.context();
|
1153 | let hasEmptyMessage = msgNode.items.length === 0;
|
1154 | const node = startNode(1 , offset, loc);
|
1155 | node.cases = [];
|
1156 | node.cases.push(msgNode);
|
1157 | do {
|
1158 | const msg = parseMessage(tokenizer);
|
1159 | if (!hasEmptyMessage) {
|
1160 | hasEmptyMessage = msg.items.length === 0;
|
1161 | }
|
1162 | node.cases.push(msg);
|
1163 | } while (context.currentType !== 14 );
|
1164 | if (hasEmptyMessage) {
|
1165 | emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
|
1166 | }
|
1167 | endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
|
1168 | return node;
|
1169 | }
|
1170 | function parseResource(tokenizer) {
|
1171 | const context = tokenizer.context();
|
1172 | const { offset, startLoc } = context;
|
1173 | const msgNode = parseMessage(tokenizer);
|
1174 | if (context.currentType === 14 ) {
|
1175 | return msgNode;
|
1176 | }
|
1177 | else {
|
1178 | return parsePlural(tokenizer, offset, startLoc, msgNode);
|
1179 | }
|
1180 | }
|
1181 | function parse(source) {
|
1182 | const tokenizer = createTokenizer(source, assign({}, options));
|
1183 | const context = tokenizer.context();
|
1184 | const node = startNode(0 , context.offset, context.startLoc);
|
1185 | if (location && node.loc) {
|
1186 | node.loc.source = source;
|
1187 | }
|
1188 | node.body = parseResource(tokenizer);
|
1189 |
|
1190 | if (context.currentType !== 14 ) {
|
1191 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');
|
1192 | }
|
1193 | endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
|
1194 | return node;
|
1195 | }
|
1196 | return { parse };
|
1197 | }
|
1198 | function getTokenCaption(token) {
|
1199 | if (token.type === 14 ) {
|
1200 | return 'EOF';
|
1201 | }
|
1202 | const name = (token.value || '').replace(/\r?\n/gu, '\\n');
|
1203 | return name.length > 10 ? name.slice(0, 9) + '…' : name;
|
1204 | }
|
1205 |
|
1206 | function createTransformer(ast, options = {} // eslint-disable-line
|
1207 | ) {
|
1208 | const _context = {
|
1209 | ast,
|
1210 | helpers: new Set()
|
1211 | };
|
1212 | const context = () => _context;
|
1213 | const helper = (name) => {
|
1214 | _context.helpers.add(name);
|
1215 | return name;
|
1216 | };
|
1217 | return { context, helper };
|
1218 | }
|
1219 | function traverseNodes(nodes, transformer) {
|
1220 | for (let i = 0; i < nodes.length; i++) {
|
1221 | traverseNode(nodes[i], transformer);
|
1222 | }
|
1223 | }
|
1224 | function traverseNode(node, transformer) {
|
1225 |
|
1226 | switch (node.type) {
|
1227 | case 1 :
|
1228 | traverseNodes(node.cases, transformer);
|
1229 | transformer.helper("plural" );
|
1230 | break;
|
1231 | case 2 :
|
1232 | traverseNodes(node.items, transformer);
|
1233 | break;
|
1234 | case 6 :
|
1235 | const linked = node;
|
1236 | traverseNode(linked.key, transformer);
|
1237 | transformer.helper("linked" );
|
1238 | break;
|
1239 | case 5 :
|
1240 | transformer.helper("interpolate" );
|
1241 | transformer.helper("list" );
|
1242 | break;
|
1243 | case 4 :
|
1244 | transformer.helper("interpolate" );
|
1245 | transformer.helper("named" );
|
1246 | break;
|
1247 | }
|
1248 |
|
1249 | }
|
1250 |
|
1251 | function transform(ast, options = {} // eslint-disable-line
|
1252 | ) {
|
1253 | const transformer = createTransformer(ast);
|
1254 | transformer.helper("normalize" );
|
1255 |
|
1256 | ast.body && traverseNode(ast.body, transformer);
|
1257 |
|
1258 | const context = transformer.context();
|
1259 | ast.helpers = Array.from(context.helpers);
|
1260 | }
|
1261 |
|
1262 | function createCodeGenerator(ast, options) {
|
1263 | const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
|
1264 | const _context = {
|
1265 | source: ast.loc.source,
|
1266 | filename,
|
1267 | code: '',
|
1268 | column: 1,
|
1269 | line: 1,
|
1270 | offset: 0,
|
1271 | map: undefined,
|
1272 | breakLineCode,
|
1273 | needIndent: _needIndent,
|
1274 | indentLevel: 0
|
1275 | };
|
1276 | const context = () => _context;
|
1277 | function push(code, node) {
|
1278 | _context.code += code;
|
1279 | }
|
1280 | function _newline(n, withBreakLine = true) {
|
1281 | const _breakLineCode = withBreakLine ? breakLineCode : '';
|
1282 | push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
|
1283 | }
|
1284 | function indent(withNewLine = true) {
|
1285 | const level = ++_context.indentLevel;
|
1286 | withNewLine && _newline(level);
|
1287 | }
|
1288 | function deindent(withNewLine = true) {
|
1289 | const level = --_context.indentLevel;
|
1290 | withNewLine && _newline(level);
|
1291 | }
|
1292 | function newline() {
|
1293 | _newline(_context.indentLevel);
|
1294 | }
|
1295 | const helper = (key) => `_${key}`;
|
1296 | const needIndent = () => _context.needIndent;
|
1297 | return {
|
1298 | context,
|
1299 | push,
|
1300 | indent,
|
1301 | deindent,
|
1302 | newline,
|
1303 | helper,
|
1304 | needIndent
|
1305 | };
|
1306 | }
|
1307 | function generateLinkedNode(generator, node) {
|
1308 | const { helper } = generator;
|
1309 | generator.push(`${helper("linked" /* LINKED */)}(`);
|
1310 | generateNode(generator, node.key);
|
1311 | if (node.modifier) {
|
1312 | generator.push(`, `);
|
1313 | generateNode(generator, node.modifier);
|
1314 | }
|
1315 | generator.push(`)`);
|
1316 | }
|
1317 | function generateMessageNode(generator, node) {
|
1318 | const { helper, needIndent } = generator;
|
1319 | generator.push(`${helper("normalize" /* NORMALIZE */)}([`);
|
1320 | generator.indent(needIndent());
|
1321 | const length = node.items.length;
|
1322 | for (let i = 0; i < length; i++) {
|
1323 | generateNode(generator, node.items[i]);
|
1324 | if (i === length - 1) {
|
1325 | break;
|
1326 | }
|
1327 | generator.push(', ');
|
1328 | }
|
1329 | generator.deindent(needIndent());
|
1330 | generator.push('])');
|
1331 | }
|
1332 | function generatePluralNode(generator, node) {
|
1333 | const { helper, needIndent } = generator;
|
1334 | if (node.cases.length > 1) {
|
1335 | generator.push(`${helper("plural" /* PLURAL */)}([`);
|
1336 | generator.indent(needIndent());
|
1337 | const length = node.cases.length;
|
1338 | for (let i = 0; i < length; i++) {
|
1339 | generateNode(generator, node.cases[i]);
|
1340 | if (i === length - 1) {
|
1341 | break;
|
1342 | }
|
1343 | generator.push(', ');
|
1344 | }
|
1345 | generator.deindent(needIndent());
|
1346 | generator.push(`])`);
|
1347 | }
|
1348 | }
|
1349 | function generateResource(generator, node) {
|
1350 | if (node.body) {
|
1351 | generateNode(generator, node.body);
|
1352 | }
|
1353 | else {
|
1354 | generator.push('null');
|
1355 | }
|
1356 | }
|
1357 | function generateNode(generator, node) {
|
1358 | const { helper } = generator;
|
1359 | switch (node.type) {
|
1360 | case 0 :
|
1361 | generateResource(generator, node);
|
1362 | break;
|
1363 | case 1 :
|
1364 | generatePluralNode(generator, node);
|
1365 | break;
|
1366 | case 2 :
|
1367 | generateMessageNode(generator, node);
|
1368 | break;
|
1369 | case 6 :
|
1370 | generateLinkedNode(generator, node);
|
1371 | break;
|
1372 | case 8 :
|
1373 | generator.push(JSON.stringify(node.value), node);
|
1374 | break;
|
1375 | case 7 :
|
1376 | generator.push(JSON.stringify(node.value), node);
|
1377 | break;
|
1378 | case 5 :
|
1379 | generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node);
|
1380 | break;
|
1381 | case 4 :
|
1382 | generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node);
|
1383 | break;
|
1384 | case 9 :
|
1385 | generator.push(JSON.stringify(node.value), node);
|
1386 | break;
|
1387 | case 3 :
|
1388 | generator.push(JSON.stringify(node.value), node);
|
1389 | break;
|
1390 | default:
|
1391 | {
|
1392 | throw new Error(`unhandled codegen node type: ${node.type}`);
|
1393 | }
|
1394 | }
|
1395 | }
|
1396 |
|
1397 | const generate = (ast, options = {}
|
1398 | ) => {
|
1399 | const mode = isString(options.mode) ? options.mode : 'normal';
|
1400 | const filename = isString(options.filename)
|
1401 | ? options.filename
|
1402 | : 'message.intl';
|
1403 | const sourceMap = !!options.sourceMap;
|
1404 |
|
1405 | const breakLineCode = options.breakLineCode != null
|
1406 | ? options.breakLineCode
|
1407 | : mode === 'arrow'
|
1408 | ? ';'
|
1409 | : '\n';
|
1410 | const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
|
1411 | const helpers = ast.helpers || [];
|
1412 | const generator = createCodeGenerator(ast, {
|
1413 | mode,
|
1414 | filename,
|
1415 | sourceMap,
|
1416 | breakLineCode,
|
1417 | needIndent
|
1418 | });
|
1419 | generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
|
1420 | generator.indent(needIndent);
|
1421 | if (helpers.length > 0) {
|
1422 | generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`);
|
1423 | generator.newline();
|
1424 | }
|
1425 | generator.push(`return `);
|
1426 | generateNode(generator, ast);
|
1427 | generator.deindent(needIndent);
|
1428 | generator.push(`}`);
|
1429 | const { code, map } = generator.context();
|
1430 | return {
|
1431 | ast,
|
1432 | code,
|
1433 | map: map ? map.toJSON() : undefined
|
1434 | };
|
1435 | };
|
1436 |
|
1437 | function baseCompile(source, options = {}) {
|
1438 | const assignedOptions = assign({}, options);
|
1439 |
|
1440 | const parser = createParser(assignedOptions);
|
1441 | const ast = parser.parse(source);
|
1442 |
|
1443 | transform(ast, assignedOptions);
|
1444 |
|
1445 | return generate(ast, assignedOptions);
|
1446 | }
|
1447 |
|
1448 | const pathStateMachine = [];
|
1449 | pathStateMachine[0 ] = {
|
1450 | ["w" ]: [0 ],
|
1451 | ["i" ]: [3 , 0 ],
|
1452 | ["[" ]: [4 ],
|
1453 | ["o" ]: [7 ]
|
1454 | };
|
1455 | pathStateMachine[1 ] = {
|
1456 | ["w" ]: [1 ],
|
1457 | ["." ]: [2 ],
|
1458 | ["[" ]: [4 ],
|
1459 | ["o" ]: [7 ]
|
1460 | };
|
1461 | pathStateMachine[2 ] = {
|
1462 | ["w" ]: [2 ],
|
1463 | ["i" ]: [3 , 0 ],
|
1464 | ["0" ]: [3 , 0 ]
|
1465 | };
|
1466 | pathStateMachine[3 ] = {
|
1467 | ["i" ]: [3 , 0 ],
|
1468 | ["0" ]: [3 , 0 ],
|
1469 | ["w" ]: [1 , 1 ],
|
1470 | ["." ]: [2 , 1 ],
|
1471 | ["[" ]: [4 , 1 ],
|
1472 | ["o" ]: [7 , 1 ]
|
1473 | };
|
1474 | pathStateMachine[4 ] = {
|
1475 | ["'" ]: [5 , 0 ],
|
1476 | ["\"" ]: [6 , 0 ],
|
1477 | ["[" ]: [
|
1478 | 4 ,
|
1479 | 2
|
1480 | ],
|
1481 | ["]" ]: [1 , 3 ],
|
1482 | ["o" ]: 8 ,
|
1483 | ["l" ]: [4 , 0 ]
|
1484 | };
|
1485 | pathStateMachine[5 ] = {
|
1486 | ["'" ]: [4 , 0 ],
|
1487 | ["o" ]: 8 ,
|
1488 | ["l" ]: [5 , 0 ]
|
1489 | };
|
1490 | pathStateMachine[6 ] = {
|
1491 | ["\"" ]: [4 , 0 ],
|
1492 | ["o" ]: 8 ,
|
1493 | ["l" ]: [6 , 0 ]
|
1494 | };
|
1495 |
|
1496 |
|
1497 |
|
1498 | const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
|
1499 | function isLiteral(exp) {
|
1500 | return literalValueRE.test(exp);
|
1501 | }
|
1502 |
|
1503 |
|
1504 |
|
1505 | function stripQuotes(str) {
|
1506 | const a = str.charCodeAt(0);
|
1507 | const b = str.charCodeAt(str.length - 1);
|
1508 | return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
|
1509 | }
|
1510 |
|
1511 |
|
1512 |
|
1513 | function getPathCharType(ch) {
|
1514 | if (ch === undefined || ch === null) {
|
1515 | return "o" ;
|
1516 | }
|
1517 | const code = ch.charCodeAt(0);
|
1518 | switch (code) {
|
1519 | case 0x5b:
|
1520 | case 0x5d:
|
1521 | case 0x2e:
|
1522 | case 0x22:
|
1523 | case 0x27:
|
1524 | return ch;
|
1525 | case 0x5f:
|
1526 | case 0x24:
|
1527 | case 0x2d:
|
1528 | return "i" ;
|
1529 | case 0x09:
|
1530 | case 0x0a:
|
1531 | case 0x0d:
|
1532 | case 0xa0:
|
1533 | case 0xfeff:
|
1534 | case 0x2028:
|
1535 | case 0x2029:
|
1536 | return "w" ;
|
1537 | }
|
1538 | return "i" ;
|
1539 | }
|
1540 |
|
1541 |
|
1542 |
|
1543 |
|
1544 |
|
1545 | function formatSubPath(path) {
|
1546 | const trimmed = path.trim();
|
1547 |
|
1548 | if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
|
1549 | return false;
|
1550 | }
|
1551 | return isLiteral(trimmed)
|
1552 | ? stripQuotes(trimmed)
|
1553 | : "*" + trimmed;
|
1554 | }
|
1555 |
|
1556 |
|
1557 |
|
1558 | function parse(path) {
|
1559 | const keys = [];
|
1560 | let index = -1;
|
1561 | let mode = 0 ;
|
1562 | let subPathDepth = 0;
|
1563 | let c;
|
1564 | let key;
|
1565 | let newChar;
|
1566 | let type;
|
1567 | let transition;
|
1568 | let action;
|
1569 | let typeMap;
|
1570 | const actions = [];
|
1571 | actions[0 ] = () => {
|
1572 | if (key === undefined) {
|
1573 | key = newChar;
|
1574 | }
|
1575 | else {
|
1576 | key += newChar;
|
1577 | }
|
1578 | };
|
1579 | actions[1 ] = () => {
|
1580 | if (key !== undefined) {
|
1581 | keys.push(key);
|
1582 | key = undefined;
|
1583 | }
|
1584 | };
|
1585 | actions[2 ] = () => {
|
1586 | actions[0 ]();
|
1587 | subPathDepth++;
|
1588 | };
|
1589 | actions[3 ] = () => {
|
1590 | if (subPathDepth > 0) {
|
1591 | subPathDepth--;
|
1592 | mode = 4 ;
|
1593 | actions[0 ]();
|
1594 | }
|
1595 | else {
|
1596 | subPathDepth = 0;
|
1597 | if (key === undefined) {
|
1598 | return false;
|
1599 | }
|
1600 | key = formatSubPath(key);
|
1601 | if (key === false) {
|
1602 | return false;
|
1603 | }
|
1604 | else {
|
1605 | actions[1 ]();
|
1606 | }
|
1607 | }
|
1608 | };
|
1609 | function maybeUnescapeQuote() {
|
1610 | const nextChar = path[index + 1];
|
1611 | if ((mode === 5 &&
|
1612 | nextChar === "'" ) ||
|
1613 | (mode === 6 &&
|
1614 | nextChar === "\"" )) {
|
1615 | index++;
|
1616 | newChar = '\\' + nextChar;
|
1617 | actions[0 ]();
|
1618 | return true;
|
1619 | }
|
1620 | }
|
1621 | while (mode !== null) {
|
1622 | index++;
|
1623 | c = path[index];
|
1624 | if (c === '\\' && maybeUnescapeQuote()) {
|
1625 | continue;
|
1626 | }
|
1627 | type = getPathCharType(c);
|
1628 | typeMap = pathStateMachine[mode];
|
1629 | transition = typeMap[type] || typeMap["l" ] || 8 ;
|
1630 |
|
1631 | if (transition === 8 ) {
|
1632 | return;
|
1633 | }
|
1634 | mode = transition[0];
|
1635 | if (transition[1] !== undefined) {
|
1636 | action = actions[transition[1]];
|
1637 | if (action) {
|
1638 | newChar = c;
|
1639 | if (action() === false) {
|
1640 | return;
|
1641 | }
|
1642 | }
|
1643 | }
|
1644 |
|
1645 | if (mode === 7 ) {
|
1646 | return keys;
|
1647 | }
|
1648 | }
|
1649 | }
|
1650 |
|
1651 | const cache = new Map();
|
1652 |
|
1653 |
|
1654 |
|
1655 |
|
1656 |
|
1657 |
|
1658 |
|
1659 |
|
1660 |
|
1661 |
|
1662 |
|
1663 |
|
1664 |
|
1665 | function resolveWithKeyValue(obj, path) {
|
1666 | return isObject(obj) ? obj[path] : null;
|
1667 | }
|
1668 |
|
1669 |
|
1670 |
|
1671 |
|
1672 |
|
1673 |
|
1674 |
|
1675 |
|
1676 |
|
1677 |
|
1678 |
|
1679 |
|
1680 |
|
1681 | function resolveValue(obj, path) {
|
1682 |
|
1683 | if (!isObject(obj)) {
|
1684 | return null;
|
1685 | }
|
1686 |
|
1687 | let hit = cache.get(path);
|
1688 | if (!hit) {
|
1689 | hit = parse(path);
|
1690 | if (hit) {
|
1691 | cache.set(path, hit);
|
1692 | }
|
1693 | }
|
1694 |
|
1695 | if (!hit) {
|
1696 | return null;
|
1697 | }
|
1698 |
|
1699 | const len = hit.length;
|
1700 | let last = obj;
|
1701 | let i = 0;
|
1702 | while (i < len) {
|
1703 | const val = last[hit[i]];
|
1704 | if (val === undefined) {
|
1705 | return null;
|
1706 | }
|
1707 | last = val;
|
1708 | i++;
|
1709 | }
|
1710 | return last;
|
1711 | }
|
1712 |
|
1713 | const DEFAULT_MODIFIER = (str) => str;
|
1714 | const DEFAULT_MESSAGE = (ctx) => '';
|
1715 | const DEFAULT_MESSAGE_DATA_TYPE = 'text';
|
1716 | const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join('');
|
1717 | const DEFAULT_INTERPOLATE = toDisplayString;
|
1718 | function pluralDefault(choice, choicesLength) {
|
1719 | choice = Math.abs(choice);
|
1720 | if (choicesLength === 2) {
|
1721 |
|
1722 | return choice
|
1723 | ? choice > 1
|
1724 | ? 1
|
1725 | : 0
|
1726 | : 1;
|
1727 | }
|
1728 | return choice ? Math.min(choice, 2) : 0;
|
1729 | }
|
1730 | function getPluralIndex(options) {
|
1731 |
|
1732 | const index = isNumber(options.pluralIndex)
|
1733 | ? options.pluralIndex
|
1734 | : -1;
|
1735 |
|
1736 | return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
|
1737 | ? isNumber(options.named.count)
|
1738 | ? options.named.count
|
1739 | : isNumber(options.named.n)
|
1740 | ? options.named.n
|
1741 | : index
|
1742 | : index;
|
1743 | }
|
1744 | function normalizeNamed(pluralIndex, props) {
|
1745 | if (!props.count) {
|
1746 | props.count = pluralIndex;
|
1747 | }
|
1748 | if (!props.n) {
|
1749 | props.n = pluralIndex;
|
1750 | }
|
1751 | }
|
1752 | function createMessageContext(options = {}) {
|
1753 | const locale = options.locale;
|
1754 | const pluralIndex = getPluralIndex(options);
|
1755 | const pluralRule = isObject(options.pluralRules) &&
|
1756 | isString(locale) &&
|
1757 | isFunction(options.pluralRules[locale])
|
1758 | ? options.pluralRules[locale]
|
1759 | : pluralDefault;
|
1760 | const orgPluralRule = isObject(options.pluralRules) &&
|
1761 | isString(locale) &&
|
1762 | isFunction(options.pluralRules[locale])
|
1763 | ? pluralDefault
|
1764 | : undefined;
|
1765 | const plural = (messages) => messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
|
1766 | const _list = options.list || [];
|
1767 | const list = (index) => _list[index];
|
1768 |
|
1769 | const _named = options.named || {};
|
1770 | isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
|
1771 | const named = (key) => _named[key];
|
1772 |
|
1773 | function message(key) {
|
1774 |
|
1775 | const msg = isFunction(options.messages)
|
1776 | ? options.messages(key)
|
1777 | : isObject(options.messages)
|
1778 | ? options.messages[key]
|
1779 | : false;
|
1780 | return !msg
|
1781 | ? options.parent
|
1782 | ? options.parent.message(key)
|
1783 | : DEFAULT_MESSAGE
|
1784 | : msg;
|
1785 | }
|
1786 | const _modifier = (name) => options.modifiers
|
1787 | ? options.modifiers[name]
|
1788 | : DEFAULT_MODIFIER;
|
1789 | const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
|
1790 | ? options.processor.normalize
|
1791 | : DEFAULT_NORMALIZE;
|
1792 | const interpolate = isPlainObject(options.processor) &&
|
1793 | isFunction(options.processor.interpolate)
|
1794 | ? options.processor.interpolate
|
1795 | : DEFAULT_INTERPOLATE;
|
1796 | const type = isPlainObject(options.processor) && isString(options.processor.type)
|
1797 | ? options.processor.type
|
1798 | : DEFAULT_MESSAGE_DATA_TYPE;
|
1799 | const ctx = {
|
1800 | ["list" ]: list,
|
1801 | ["named" ]: named,
|
1802 | ["plural" ]: plural,
|
1803 | ["linked" ]: (key, modifier) => {
|
1804 |
|
1805 | const msg = message(key)(ctx);
|
1806 | return isString(modifier) ? _modifier(modifier)(msg) : msg;
|
1807 | },
|
1808 | ["message" ]: message,
|
1809 | ["type" ]: type,
|
1810 | ["interpolate" ]: interpolate,
|
1811 | ["normalize" ]: normalize
|
1812 | };
|
1813 | return ctx;
|
1814 | }
|
1815 |
|
1816 | const IntlifyDevToolsHooks = {
|
1817 | I18nInit: 'i18n:init',
|
1818 | FunctionTranslate: 'function:translate'
|
1819 | };
|
1820 |
|
1821 | let devtools = null;
|
1822 | function setDevToolsHook(hook) {
|
1823 | devtools = hook;
|
1824 | }
|
1825 | function initI18nDevTools(i18n, version, meta) {
|
1826 |
|
1827 | devtools &&
|
1828 | devtools.emit(IntlifyDevToolsHooks.I18nInit, {
|
1829 | timestamp: Date.now(),
|
1830 | i18n,
|
1831 | version,
|
1832 | meta
|
1833 | });
|
1834 | }
|
1835 | const translateDevTools = createDevToolsHook(IntlifyDevToolsHooks.FunctionTranslate);
|
1836 | function createDevToolsHook(hook) {
|
1837 | return (payloads) => devtools && devtools.emit(hook, payloads);
|
1838 | }
|
1839 |
|
1840 | const CoreWarnCodes = {
|
1841 | NOT_FOUND_KEY: 1,
|
1842 | FALLBACK_TO_TRANSLATE: 2,
|
1843 | CANNOT_FORMAT_NUMBER: 3,
|
1844 | FALLBACK_TO_NUMBER_FORMAT: 4,
|
1845 | CANNOT_FORMAT_DATE: 5,
|
1846 | FALLBACK_TO_DATE_FORMAT: 6,
|
1847 | __EXTEND_POINT__: 7
|
1848 | };
|
1849 |
|
1850 | const warnMessages$1 = {
|
1851 | [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
|
1852 | [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
|
1853 | [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
|
1854 | [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
|
1855 | [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
|
1856 | [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`
|
1857 | };
|
1858 | function getWarnMessage$1(code, ...args) {
|
1859 | return format(warnMessages$1[code], ...args);
|
1860 | }
|
1861 |
|
1862 |
|
1863 |
|
1864 |
|
1865 |
|
1866 |
|
1867 |
|
1868 |
|
1869 |
|
1870 |
|
1871 |
|
1872 |
|
1873 |
|
1874 |
|
1875 |
|
1876 |
|
1877 |
|
1878 | function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
|
1879 | ) {
|
1880 |
|
1881 | return [...new Set([
|
1882 | start,
|
1883 | ...(isArray(fallback)
|
1884 | ? fallback
|
1885 | : isObject(fallback)
|
1886 | ? Object.keys(fallback)
|
1887 | : isString(fallback)
|
1888 | ? [fallback]
|
1889 | : [start])
|
1890 | ])];
|
1891 | }
|
1892 |
|
1893 |
|
1894 |
|
1895 |
|
1896 |
|
1897 |
|
1898 |
|
1899 |
|
1900 |
|
1901 |
|
1902 |
|
1903 |
|
1904 |
|
1905 |
|
1906 |
|
1907 |
|
1908 | function fallbackWithLocaleChain(ctx, fallback, start) {
|
1909 | const startLocale = isString(start) ? start : DEFAULT_LOCALE;
|
1910 | const context = ctx;
|
1911 | if (!context.__localeChainCache) {
|
1912 | context.__localeChainCache = new Map();
|
1913 | }
|
1914 | let chain = context.__localeChainCache.get(startLocale);
|
1915 | if (!chain) {
|
1916 | chain = [];
|
1917 |
|
1918 | let block = [start];
|
1919 |
|
1920 | while (isArray(block)) {
|
1921 | block = appendBlockToChain(chain, block, fallback);
|
1922 | }
|
1923 |
|
1924 |
|
1925 | const defaults = isArray(fallback) || !isPlainObject(fallback)
|
1926 | ? fallback
|
1927 | : fallback['default']
|
1928 | ? fallback['default']
|
1929 | : null;
|
1930 |
|
1931 | block = isString(defaults) ? [defaults] : defaults;
|
1932 | if (isArray(block)) {
|
1933 | appendBlockToChain(chain, block, false);
|
1934 | }
|
1935 | context.__localeChainCache.set(startLocale, chain);
|
1936 | }
|
1937 | return chain;
|
1938 | }
|
1939 | function appendBlockToChain(chain, block, blocks) {
|
1940 | let follow = true;
|
1941 | for (let i = 0; i < block.length && isBoolean(follow); i++) {
|
1942 | const locale = block[i];
|
1943 | if (isString(locale)) {
|
1944 | follow = appendLocaleToChain(chain, block[i], blocks);
|
1945 | }
|
1946 | }
|
1947 | return follow;
|
1948 | }
|
1949 | function appendLocaleToChain(chain, locale, blocks) {
|
1950 | let follow;
|
1951 | const tokens = locale.split('-');
|
1952 | do {
|
1953 | const target = tokens.join('-');
|
1954 | follow = appendItemToChain(chain, target, blocks);
|
1955 | tokens.splice(-1, 1);
|
1956 | } while (tokens.length && follow === true);
|
1957 | return follow;
|
1958 | }
|
1959 | function appendItemToChain(chain, target, blocks) {
|
1960 | let follow = false;
|
1961 | if (!chain.includes(target)) {
|
1962 | follow = true;
|
1963 | if (target) {
|
1964 | follow = target[target.length - 1] !== '!';
|
1965 | const locale = target.replace(/!/g, '');
|
1966 | chain.push(locale);
|
1967 | if ((isArray(blocks) || isPlainObject(blocks)) &&
|
1968 | blocks[locale]
|
1969 | ) {
|
1970 |
|
1971 | follow = blocks[locale];
|
1972 | }
|
1973 | }
|
1974 | }
|
1975 | return follow;
|
1976 | }
|
1977 |
|
1978 |
|
1979 |
|
1980 |
|
1981 |
|
1982 |
|
1983 | const VERSION$1 = '9.2.0-beta.6';
|
1984 | const NOT_REOSLVED = -1;
|
1985 | const DEFAULT_LOCALE = 'en-US';
|
1986 | const MISSING_RESOLVE_VALUE = '';
|
1987 | function getDefaultLinkedModifiers() {
|
1988 | return {
|
1989 | upper: (val) => (isString(val) ? val.toUpperCase() : val),
|
1990 | lower: (val) => (isString(val) ? val.toLowerCase() : val),
|
1991 |
|
1992 | capitalize: (val) => (isString(val)
|
1993 | ? `${val.charAt(0).toLocaleUpperCase()}${val.substr(1)}`
|
1994 | : val)
|
1995 | };
|
1996 | }
|
1997 | let _compiler;
|
1998 | function registerMessageCompiler(compiler) {
|
1999 | _compiler = compiler;
|
2000 | }
|
2001 | let _resolver;
|
2002 |
|
2003 |
|
2004 |
|
2005 |
|
2006 |
|
2007 |
|
2008 |
|
2009 | function registerMessageResolver(resolver) {
|
2010 | _resolver = resolver;
|
2011 | }
|
2012 | let _fallbacker;
|
2013 |
|
2014 |
|
2015 |
|
2016 |
|
2017 |
|
2018 |
|
2019 |
|
2020 | function registerLocaleFallbacker(fallbacker) {
|
2021 | _fallbacker = fallbacker;
|
2022 | }
|
2023 |
|
2024 | let _additionalMeta = null;
|
2025 | const setAdditionalMeta = (meta) => {
|
2026 | _additionalMeta = meta;
|
2027 | };
|
2028 | const getAdditionalMeta = () => _additionalMeta;
|
2029 |
|
2030 | let _cid = 0;
|
2031 | function createCoreContext(options = {}) {
|
2032 |
|
2033 | const version = isString(options.version) ? options.version : VERSION$1;
|
2034 | const locale = isString(options.locale) ? options.locale : DEFAULT_LOCALE;
|
2035 | const fallbackLocale = isArray(options.fallbackLocale) ||
|
2036 | isPlainObject(options.fallbackLocale) ||
|
2037 | isString(options.fallbackLocale) ||
|
2038 | options.fallbackLocale === false
|
2039 | ? options.fallbackLocale
|
2040 | : locale;
|
2041 | const messages = isPlainObject(options.messages)
|
2042 | ? options.messages
|
2043 | : { [locale]: {} };
|
2044 | const datetimeFormats = isPlainObject(options.datetimeFormats)
|
2045 | ? options.datetimeFormats
|
2046 | : { [locale]: {} }
|
2047 | ;
|
2048 | const numberFormats = isPlainObject(options.numberFormats)
|
2049 | ? options.numberFormats
|
2050 | : { [locale]: {} }
|
2051 | ;
|
2052 | const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
|
2053 | const pluralRules = options.pluralRules || {};
|
2054 | const missing = isFunction(options.missing) ? options.missing : null;
|
2055 | const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
|
2056 | ? options.missingWarn
|
2057 | : true;
|
2058 | const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
|
2059 | ? options.fallbackWarn
|
2060 | : true;
|
2061 | const fallbackFormat = !!options.fallbackFormat;
|
2062 | const unresolving = !!options.unresolving;
|
2063 | const postTranslation = isFunction(options.postTranslation)
|
2064 | ? options.postTranslation
|
2065 | : null;
|
2066 | const processor = isPlainObject(options.processor) ? options.processor : null;
|
2067 | const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
|
2068 | ? options.warnHtmlMessage
|
2069 | : true;
|
2070 | const escapeParameter = !!options.escapeParameter;
|
2071 | const messageCompiler = isFunction(options.messageCompiler)
|
2072 | ? options.messageCompiler
|
2073 | : _compiler;
|
2074 | const messageResolver = isFunction(options.messageResolver)
|
2075 | ? options.messageResolver
|
2076 | : _resolver || resolveWithKeyValue;
|
2077 | const localeFallbacker = isFunction(options.localeFallbacker)
|
2078 | ? options.localeFallbacker
|
2079 | : _fallbacker || fallbackWithSimple;
|
2080 | const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
|
2081 |
|
2082 | const internalOptions = options;
|
2083 | const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
|
2084 | ? internalOptions.__datetimeFormatters
|
2085 | : new Map()
|
2086 | ;
|
2087 | const __numberFormatters = isObject(internalOptions.__numberFormatters)
|
2088 | ? internalOptions.__numberFormatters
|
2089 | : new Map()
|
2090 | ;
|
2091 | const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
|
2092 | _cid++;
|
2093 | const context = {
|
2094 | version,
|
2095 | cid: _cid,
|
2096 | locale,
|
2097 | fallbackLocale,
|
2098 | messages,
|
2099 | modifiers,
|
2100 | pluralRules,
|
2101 | missing,
|
2102 | missingWarn,
|
2103 | fallbackWarn,
|
2104 | fallbackFormat,
|
2105 | unresolving,
|
2106 | postTranslation,
|
2107 | processor,
|
2108 | warnHtmlMessage,
|
2109 | escapeParameter,
|
2110 | messageCompiler,
|
2111 | messageResolver,
|
2112 | localeFallbacker,
|
2113 | onWarn,
|
2114 | __meta
|
2115 | };
|
2116 | {
|
2117 | context.datetimeFormats = datetimeFormats;
|
2118 | context.numberFormats = numberFormats;
|
2119 | context.__datetimeFormatters = __datetimeFormatters;
|
2120 | context.__numberFormatters = __numberFormatters;
|
2121 | }
|
2122 |
|
2123 | {
|
2124 | initI18nDevTools(context, version, __meta);
|
2125 | }
|
2126 | return context;
|
2127 | }
|
2128 |
|
2129 | function isTranslateFallbackWarn(fallback, key) {
|
2130 | return fallback instanceof RegExp ? fallback.test(key) : fallback;
|
2131 | }
|
2132 |
|
2133 | function isTranslateMissingWarn(missing, key) {
|
2134 | return missing instanceof RegExp ? missing.test(key) : missing;
|
2135 | }
|
2136 |
|
2137 | function handleMissing(context, key, locale, missingWarn, type) {
|
2138 | const { missing, onWarn } = context;
|
2139 | if (missing !== null) {
|
2140 | const ret = missing(context, locale, key, type);
|
2141 | return isString(ret) ? ret : key;
|
2142 | }
|
2143 | else {
|
2144 | if (isTranslateMissingWarn(missingWarn, key)) {
|
2145 | onWarn(getWarnMessage$1(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
|
2146 | }
|
2147 | return key;
|
2148 | }
|
2149 | }
|
2150 |
|
2151 | function updateFallbackLocale(ctx, locale, fallback) {
|
2152 | const context = ctx;
|
2153 | context.__localeChainCache = new Map();
|
2154 | ctx.localeFallbacker(ctx, fallback, locale);
|
2155 | }
|
2156 |
|
2157 |
|
2158 | const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
|
2159 | const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
|
2160 | function checkHtmlMessage(source, options) {
|
2161 | const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
|
2162 | ? options.warnHtmlMessage
|
2163 | : true;
|
2164 | if (warnHtmlMessage && RE_HTML_TAG.test(source)) {
|
2165 | warn(format(WARN_MESSAGE, { source }));
|
2166 | }
|
2167 | }
|
2168 | const defaultOnCacheKey = (source) => source;
|
2169 | let compileCache = Object.create(null);
|
2170 | function compileToFunction(source, options = {}) {
|
2171 | {
|
2172 |
|
2173 | checkHtmlMessage(source, options);
|
2174 |
|
2175 | const onCacheKey = options.onCacheKey || defaultOnCacheKey;
|
2176 | const key = onCacheKey(source);
|
2177 | const cached = compileCache[key];
|
2178 | if (cached) {
|
2179 | return cached;
|
2180 | }
|
2181 |
|
2182 | let occurred = false;
|
2183 | const onError = options.onError || defaultOnError;
|
2184 | options.onError = (err) => {
|
2185 | occurred = true;
|
2186 | onError(err);
|
2187 | };
|
2188 |
|
2189 | const { code } = baseCompile(source, options);
|
2190 |
|
2191 | const msg = new Function(`return ${code}`)();
|
2192 |
|
2193 | return !occurred ? (compileCache[key] = msg) : msg;
|
2194 | }
|
2195 | }
|
2196 |
|
2197 | let code$2 = CompileErrorCodes.__EXTEND_POINT__;
|
2198 | const inc$2 = () => code$2++;
|
2199 | const CoreErrorCodes = {
|
2200 | INVALID_ARGUMENT: code$2,
|
2201 | INVALID_DATE_ARGUMENT: inc$2(),
|
2202 | INVALID_ISO_DATE_ARGUMENT: inc$2(),
|
2203 | __EXTEND_POINT__: inc$2()
|
2204 | };
|
2205 | function createCoreError(code) {
|
2206 | return createCompileError(code, null, { messages: errorMessages$1 } );
|
2207 | }
|
2208 |
|
2209 | const errorMessages$1 = {
|
2210 | [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
|
2211 | [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
|
2212 | 'Make sure your Date represents a valid date.',
|
2213 | [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string'
|
2214 | };
|
2215 |
|
2216 | const NOOP_MESSAGE_FUNCTION = () => '';
|
2217 | const isMessageFunction = (val) => isFunction(val);
|
2218 |
|
2219 | function translate(context, ...args) {
|
2220 | const { fallbackFormat, postTranslation, unresolving, fallbackLocale, messages } = context;
|
2221 | const [key, options] = parseTranslateArgs(...args);
|
2222 | const missingWarn = isBoolean(options.missingWarn)
|
2223 | ? options.missingWarn
|
2224 | : context.missingWarn;
|
2225 | const fallbackWarn = isBoolean(options.fallbackWarn)
|
2226 | ? options.fallbackWarn
|
2227 | : context.fallbackWarn;
|
2228 | const escapeParameter = isBoolean(options.escapeParameter)
|
2229 | ? options.escapeParameter
|
2230 | : context.escapeParameter;
|
2231 | const resolvedMessage = !!options.resolvedMessage;
|
2232 |
|
2233 | const defaultMsgOrKey = isString(options.default) || isBoolean(options.default)
|
2234 | ? !isBoolean(options.default)
|
2235 | ? options.default
|
2236 | : key
|
2237 | : fallbackFormat
|
2238 | ? key
|
2239 | : '';
|
2240 | const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
|
2241 | const locale = isString(options.locale) ? options.locale : context.locale;
|
2242 |
|
2243 | escapeParameter && escapeParams(options);
|
2244 |
|
2245 |
|
2246 | let [format, targetLocale, message] = !resolvedMessage
|
2247 | ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
|
2248 | : [
|
2249 | key,
|
2250 | locale,
|
2251 | messages[locale] || {}
|
2252 | ];
|
2253 |
|
2254 | let cacheBaseKey = key;
|
2255 | if (!resolvedMessage &&
|
2256 | !(isString(format) || isMessageFunction(format))) {
|
2257 | if (enableDefaultMsg) {
|
2258 | format = defaultMsgOrKey;
|
2259 | cacheBaseKey = format;
|
2260 | }
|
2261 | }
|
2262 |
|
2263 | if (!resolvedMessage &&
|
2264 | (!(isString(format) || isMessageFunction(format)) ||
|
2265 | !isString(targetLocale))) {
|
2266 | return unresolving ? NOT_REOSLVED : key;
|
2267 | }
|
2268 | if (isString(format) && context.messageCompiler == null) {
|
2269 | warn(`The message format compilation is not supported in this build. ` +
|
2270 | `Because message compiler isn't included. ` +
|
2271 | `You need to pre-compilation all message format. ` +
|
2272 | `So translate function return '${key}'.`);
|
2273 | return key;
|
2274 | }
|
2275 |
|
2276 | let occurred = false;
|
2277 | const errorDetector = () => {
|
2278 | occurred = true;
|
2279 | };
|
2280 |
|
2281 | const msg = !isMessageFunction(format)
|
2282 | ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
|
2283 | : format;
|
2284 |
|
2285 | if (occurred) {
|
2286 | return format;
|
2287 | }
|
2288 |
|
2289 | const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
|
2290 | const msgContext = createMessageContext(ctxOptions);
|
2291 | const messaged = evaluateMessage(context, msg, msgContext);
|
2292 |
|
2293 | const ret = postTranslation ? postTranslation(messaged) : messaged;
|
2294 |
|
2295 | {
|
2296 |
|
2297 | const payloads = {
|
2298 | timestamp: Date.now(),
|
2299 | key: isString(key)
|
2300 | ? key
|
2301 | : isMessageFunction(format)
|
2302 | ? format.key
|
2303 | : '',
|
2304 | locale: targetLocale || (isMessageFunction(format)
|
2305 | ? format.locale
|
2306 | : ''),
|
2307 | format: isString(format)
|
2308 | ? format
|
2309 | : isMessageFunction(format)
|
2310 | ? format.source
|
2311 | : '',
|
2312 | message: ret
|
2313 | };
|
2314 | payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
|
2315 | translateDevTools(payloads);
|
2316 | }
|
2317 | return ret;
|
2318 | }
|
2319 | function escapeParams(options) {
|
2320 | if (isArray(options.list)) {
|
2321 | options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
|
2322 | }
|
2323 | else if (isObject(options.named)) {
|
2324 | Object.keys(options.named).forEach(key => {
|
2325 | if (isString(options.named[key])) {
|
2326 | options.named[key] = escapeHtml(options.named[key]);
|
2327 | }
|
2328 | });
|
2329 | }
|
2330 | }
|
2331 | function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
|
2332 | const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
|
2333 | const locales = localeFallbacker(context, fallbackLocale, locale);
|
2334 | let message = {};
|
2335 | let targetLocale;
|
2336 | let format = null;
|
2337 | const type = 'translate';
|
2338 | for (let i = 0; i < locales.length; i++) {
|
2339 | targetLocale = locales[i];
|
2340 | if (locale !== targetLocale &&
|
2341 | isTranslateFallbackWarn(fallbackWarn, key)) {
|
2342 | onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
|
2343 | key,
|
2344 | target: targetLocale
|
2345 | }));
|
2346 | }
|
2347 | message =
|
2348 | messages[targetLocale] || {};
|
2349 | let startTag;
|
2350 | if (inBrowser) {
|
2351 | window.performance.now();
|
2352 | startTag = 'intlify-message-resolve-start';
|
2353 | mark && mark(startTag);
|
2354 | }
|
2355 | if ((format = resolveValue(message, key)) === null) {
|
2356 |
|
2357 | format = message[key];
|
2358 | }
|
2359 | if (isString(format) || isFunction(format))
|
2360 | break;
|
2361 | const missingRet = handleMissing(context,
|
2362 | key, targetLocale, missingWarn, type);
|
2363 | if (missingRet !== key) {
|
2364 | format = missingRet;
|
2365 | }
|
2366 | }
|
2367 | return [format, targetLocale, message];
|
2368 | }
|
2369 | function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
|
2370 | const { messageCompiler, warnHtmlMessage } = context;
|
2371 | if (isMessageFunction(format)) {
|
2372 | const msg = format;
|
2373 | msg.locale = msg.locale || targetLocale;
|
2374 | msg.key = msg.key || key;
|
2375 | return msg;
|
2376 | }
|
2377 | let startTag;
|
2378 | if (inBrowser) {
|
2379 | window.performance.now();
|
2380 | startTag = 'intlify-message-compilation-start';
|
2381 | mark && mark(startTag);
|
2382 | }
|
2383 | const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
|
2384 | msg.locale = targetLocale;
|
2385 | msg.key = key;
|
2386 | msg.source = format;
|
2387 | return msg;
|
2388 | }
|
2389 | function evaluateMessage(context, msg, msgCtx) {
|
2390 | let startTag;
|
2391 | if (inBrowser) {
|
2392 | window.performance.now();
|
2393 | startTag = 'intlify-message-evaluation-start';
|
2394 | mark && mark(startTag);
|
2395 | }
|
2396 | const messaged = msg(msgCtx);
|
2397 | return messaged;
|
2398 | }
|
2399 |
|
2400 | function parseTranslateArgs(...args) {
|
2401 | const [arg1, arg2, arg3] = args;
|
2402 | const options = {};
|
2403 | if (!isString(arg1) && !isNumber(arg1) && !isMessageFunction(arg1)) {
|
2404 | throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
|
2405 | }
|
2406 |
|
2407 | const key = isNumber(arg1)
|
2408 | ? String(arg1)
|
2409 | : isMessageFunction(arg1)
|
2410 | ? arg1
|
2411 | : arg1;
|
2412 | if (isNumber(arg2)) {
|
2413 | options.plural = arg2;
|
2414 | }
|
2415 | else if (isString(arg2)) {
|
2416 | options.default = arg2;
|
2417 | }
|
2418 | else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
|
2419 | options.named = arg2;
|
2420 | }
|
2421 | else if (isArray(arg2)) {
|
2422 | options.list = arg2;
|
2423 | }
|
2424 | if (isNumber(arg3)) {
|
2425 | options.plural = arg3;
|
2426 | }
|
2427 | else if (isString(arg3)) {
|
2428 | options.default = arg3;
|
2429 | }
|
2430 | else if (isPlainObject(arg3)) {
|
2431 | assign(options, arg3);
|
2432 | }
|
2433 | return [key, options];
|
2434 | }
|
2435 | function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
|
2436 | return {
|
2437 | warnHtmlMessage,
|
2438 | onError: (err) => {
|
2439 | errorDetector && errorDetector(err);
|
2440 | {
|
2441 | throw err;
|
2442 | }
|
2443 | },
|
2444 | onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
|
2445 | };
|
2446 | }
|
2447 | function getMessageContextOptions(context, locale, message, options) {
|
2448 | const { modifiers, pluralRules, messageResolver: resolveValue } = context;
|
2449 | const resolveMessage = (key) => {
|
2450 | const val = resolveValue(message, key);
|
2451 | if (isString(val)) {
|
2452 | let occurred = false;
|
2453 | const errorDetector = () => {
|
2454 | occurred = true;
|
2455 | };
|
2456 | const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
|
2457 | return !occurred
|
2458 | ? msg
|
2459 | : NOOP_MESSAGE_FUNCTION;
|
2460 | }
|
2461 | else if (isMessageFunction(val)) {
|
2462 | return val;
|
2463 | }
|
2464 | else {
|
2465 |
|
2466 | return NOOP_MESSAGE_FUNCTION;
|
2467 | }
|
2468 | };
|
2469 | const ctxOptions = {
|
2470 | locale,
|
2471 | modifiers,
|
2472 | pluralRules,
|
2473 | messages: resolveMessage
|
2474 | };
|
2475 | if (context.processor) {
|
2476 | ctxOptions.processor = context.processor;
|
2477 | }
|
2478 | if (options.list) {
|
2479 | ctxOptions.list = options.list;
|
2480 | }
|
2481 | if (options.named) {
|
2482 | ctxOptions.named = options.named;
|
2483 | }
|
2484 | if (isNumber(options.plural)) {
|
2485 | ctxOptions.pluralIndex = options.plural;
|
2486 | }
|
2487 | return ctxOptions;
|
2488 | }
|
2489 |
|
2490 | const intlDefined = typeof Intl !== 'undefined';
|
2491 | const Availabilities = {
|
2492 | dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
|
2493 | numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
|
2494 | };
|
2495 |
|
2496 |
|
2497 | function datetime(context, ...args) {
|
2498 | const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
|
2499 | const { __datetimeFormatters } = context;
|
2500 | if (!Availabilities.dateTimeFormat) {
|
2501 | onWarn(getWarnMessage$1(CoreWarnCodes.CANNOT_FORMAT_DATE));
|
2502 | return MISSING_RESOLVE_VALUE;
|
2503 | }
|
2504 | const [key, value, options, overrides] = parseDateTimeArgs(...args);
|
2505 | const missingWarn = isBoolean(options.missingWarn)
|
2506 | ? options.missingWarn
|
2507 | : context.missingWarn;
|
2508 | const fallbackWarn = isBoolean(options.fallbackWarn)
|
2509 | ? options.fallbackWarn
|
2510 | : context.fallbackWarn;
|
2511 | const part = !!options.part;
|
2512 | const locale = isString(options.locale) ? options.locale : context.locale;
|
2513 | const locales = localeFallbacker(context,
|
2514 | fallbackLocale, locale);
|
2515 | if (!isString(key) || key === '') {
|
2516 | return new Intl.DateTimeFormat(locale).format(value);
|
2517 | }
|
2518 |
|
2519 | let datetimeFormat = {};
|
2520 | let targetLocale;
|
2521 | let format = null;
|
2522 | const type = 'datetime format';
|
2523 | for (let i = 0; i < locales.length; i++) {
|
2524 | targetLocale = locales[i];
|
2525 | if (locale !== targetLocale &&
|
2526 | isTranslateFallbackWarn(fallbackWarn, key)) {
|
2527 | onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
|
2528 | key,
|
2529 | target: targetLocale
|
2530 | }));
|
2531 | }
|
2532 | datetimeFormat =
|
2533 | datetimeFormats[targetLocale] || {};
|
2534 | format = datetimeFormat[key];
|
2535 | if (isPlainObject(format))
|
2536 | break;
|
2537 | handleMissing(context, key, targetLocale, missingWarn, type);
|
2538 | }
|
2539 |
|
2540 | if (!isPlainObject(format) || !isString(targetLocale)) {
|
2541 | return unresolving ? NOT_REOSLVED : key;
|
2542 | }
|
2543 | let id = `${targetLocale}__${key}`;
|
2544 | if (!isEmptyObject(overrides)) {
|
2545 | id = `${id}__${JSON.stringify(overrides)}`;
|
2546 | }
|
2547 | let formatter = __datetimeFormatters.get(id);
|
2548 | if (!formatter) {
|
2549 | formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
|
2550 | __datetimeFormatters.set(id, formatter);
|
2551 | }
|
2552 | return !part ? formatter.format(value) : formatter.formatToParts(value);
|
2553 | }
|
2554 |
|
2555 | function parseDateTimeArgs(...args) {
|
2556 | const [arg1, arg2, arg3, arg4] = args;
|
2557 | let options = {};
|
2558 | let overrides = {};
|
2559 | let value;
|
2560 | if (isString(arg1)) {
|
2561 |
|
2562 |
|
2563 | const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
|
2564 | if (!matches) {
|
2565 | throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
|
2566 | }
|
2567 |
|
2568 |
|
2569 | const dateTime = matches[3]
|
2570 | ? matches[3].trim().startsWith('T')
|
2571 | ? `${matches[1].trim()}${matches[3].trim()}`
|
2572 | : `${matches[1].trim()}T${matches[3].trim()}`
|
2573 | : matches[1].trim();
|
2574 | value = new Date(dateTime);
|
2575 | try {
|
2576 |
|
2577 | value.toISOString();
|
2578 | }
|
2579 | catch (e) {
|
2580 | throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
|
2581 | }
|
2582 | }
|
2583 | else if (isDate(arg1)) {
|
2584 | if (isNaN(arg1.getTime())) {
|
2585 | throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
|
2586 | }
|
2587 | value = arg1;
|
2588 | }
|
2589 | else if (isNumber(arg1)) {
|
2590 | value = arg1;
|
2591 | }
|
2592 | else {
|
2593 | throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
|
2594 | }
|
2595 | if (isString(arg2)) {
|
2596 | options.key = arg2;
|
2597 | }
|
2598 | else if (isPlainObject(arg2)) {
|
2599 | options = arg2;
|
2600 | }
|
2601 | if (isString(arg3)) {
|
2602 | options.locale = arg3;
|
2603 | }
|
2604 | else if (isPlainObject(arg3)) {
|
2605 | overrides = arg3;
|
2606 | }
|
2607 | if (isPlainObject(arg4)) {
|
2608 | overrides = arg4;
|
2609 | }
|
2610 | return [options.key || '', value, options, overrides];
|
2611 | }
|
2612 |
|
2613 | function clearDateTimeFormat(ctx, locale, format) {
|
2614 | const context = ctx;
|
2615 | for (const key in format) {
|
2616 | const id = `${locale}__${key}`;
|
2617 | if (!context.__datetimeFormatters.has(id)) {
|
2618 | continue;
|
2619 | }
|
2620 | context.__datetimeFormatters.delete(id);
|
2621 | }
|
2622 | }
|
2623 |
|
2624 |
|
2625 | function number(context, ...args) {
|
2626 | const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
|
2627 | const { __numberFormatters } = context;
|
2628 | if (!Availabilities.numberFormat) {
|
2629 | onWarn(getWarnMessage$1(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
|
2630 | return MISSING_RESOLVE_VALUE;
|
2631 | }
|
2632 | const [key, value, options, overrides] = parseNumberArgs(...args);
|
2633 | const missingWarn = isBoolean(options.missingWarn)
|
2634 | ? options.missingWarn
|
2635 | : context.missingWarn;
|
2636 | const fallbackWarn = isBoolean(options.fallbackWarn)
|
2637 | ? options.fallbackWarn
|
2638 | : context.fallbackWarn;
|
2639 | const part = !!options.part;
|
2640 | const locale = isString(options.locale) ? options.locale : context.locale;
|
2641 | const locales = localeFallbacker(context,
|
2642 | fallbackLocale, locale);
|
2643 | if (!isString(key) || key === '') {
|
2644 | return new Intl.NumberFormat(locale).format(value);
|
2645 | }
|
2646 |
|
2647 | let numberFormat = {};
|
2648 | let targetLocale;
|
2649 | let format = null;
|
2650 | const type = 'number format';
|
2651 | for (let i = 0; i < locales.length; i++) {
|
2652 | targetLocale = locales[i];
|
2653 | if (locale !== targetLocale &&
|
2654 | isTranslateFallbackWarn(fallbackWarn, key)) {
|
2655 | onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
|
2656 | key,
|
2657 | target: targetLocale
|
2658 | }));
|
2659 | }
|
2660 | numberFormat =
|
2661 | numberFormats[targetLocale] || {};
|
2662 | format = numberFormat[key];
|
2663 | if (isPlainObject(format))
|
2664 | break;
|
2665 | handleMissing(context, key, targetLocale, missingWarn, type);
|
2666 | }
|
2667 |
|
2668 | if (!isPlainObject(format) || !isString(targetLocale)) {
|
2669 | return unresolving ? NOT_REOSLVED : key;
|
2670 | }
|
2671 | let id = `${targetLocale}__${key}`;
|
2672 | if (!isEmptyObject(overrides)) {
|
2673 | id = `${id}__${JSON.stringify(overrides)}`;
|
2674 | }
|
2675 | let formatter = __numberFormatters.get(id);
|
2676 | if (!formatter) {
|
2677 | formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
|
2678 | __numberFormatters.set(id, formatter);
|
2679 | }
|
2680 | return !part ? formatter.format(value) : formatter.formatToParts(value);
|
2681 | }
|
2682 |
|
2683 | function parseNumberArgs(...args) {
|
2684 | const [arg1, arg2, arg3, arg4] = args;
|
2685 | let options = {};
|
2686 | let overrides = {};
|
2687 | if (!isNumber(arg1)) {
|
2688 | throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
|
2689 | }
|
2690 | const value = arg1;
|
2691 | if (isString(arg2)) {
|
2692 | options.key = arg2;
|
2693 | }
|
2694 | else if (isPlainObject(arg2)) {
|
2695 | options = arg2;
|
2696 | }
|
2697 | if (isString(arg3)) {
|
2698 | options.locale = arg3;
|
2699 | }
|
2700 | else if (isPlainObject(arg3)) {
|
2701 | overrides = arg3;
|
2702 | }
|
2703 | if (isPlainObject(arg4)) {
|
2704 | overrides = arg4;
|
2705 | }
|
2706 | return [options.key || '', value, options, overrides];
|
2707 | }
|
2708 |
|
2709 | function clearNumberFormat(ctx, locale, format) {
|
2710 | const context = ctx;
|
2711 | for (const key in format) {
|
2712 | const id = `${locale}__${key}`;
|
2713 | if (!context.__numberFormatters.has(id)) {
|
2714 | continue;
|
2715 | }
|
2716 | context.__numberFormatters.delete(id);
|
2717 | }
|
2718 | }
|
2719 |
|
2720 |
|
2721 |
|
2722 |
|
2723 |
|
2724 |
|
2725 |
|
2726 |
|
2727 |
|
2728 | const VERSION = '9.2.0-beta.6';
|
2729 |
|
2730 |
|
2731 |
|
2732 |
|
2733 | function initDev() {
|
2734 | {
|
2735 | {
|
2736 | console.info(`You are running a development build of vue-i18n.\n` +
|
2737 | `Make sure to use the production build (*.prod.js) when deploying for production.`);
|
2738 | }
|
2739 | }
|
2740 | }
|
2741 |
|
2742 | let code$1 = CoreWarnCodes.__EXTEND_POINT__;
|
2743 | const inc$1 = () => code$1++;
|
2744 | const I18nWarnCodes = {
|
2745 | FALLBACK_TO_ROOT: code$1,
|
2746 | NOT_SUPPORTED_PRESERVE: inc$1(),
|
2747 | NOT_SUPPORTED_FORMATTER: inc$1(),
|
2748 | NOT_SUPPORTED_PRESERVE_DIRECTIVE: inc$1(),
|
2749 | NOT_SUPPORTED_GET_CHOICE_INDEX: inc$1(),
|
2750 | COMPONENT_NAME_LEGACY_COMPATIBLE: inc$1(),
|
2751 | NOT_FOUND_PARENT_SCOPE: inc$1(),
|
2752 | NOT_SUPPORT_MULTI_I18N_INSTANCE: inc$1()
|
2753 | };
|
2754 | const warnMessages = {
|
2755 | [I18nWarnCodes.FALLBACK_TO_ROOT]: `Fall back to {type} '{key}' with root locale.`,
|
2756 | [I18nWarnCodes.NOT_SUPPORTED_PRESERVE]: `Not supported 'preserve'.`,
|
2757 | [I18nWarnCodes.NOT_SUPPORTED_FORMATTER]: `Not supported 'formatter'.`,
|
2758 | [I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE]: `Not supported 'preserveDirectiveContent'.`,
|
2759 | [I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX]: `Not supported 'getChoiceIndex'.`,
|
2760 | [I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE]: `Component name legacy compatible: '{name}' -> 'i18n'`,
|
2761 | [I18nWarnCodes.NOT_FOUND_PARENT_SCOPE]: `Not found parent scope. use the global scope.`,
|
2762 | [I18nWarnCodes.NOT_SUPPORT_MULTI_I18N_INSTANCE]: `Not support multi i18n instance.`
|
2763 | };
|
2764 | function getWarnMessage(code, ...args) {
|
2765 | return format(warnMessages[code], ...args);
|
2766 | }
|
2767 |
|
2768 | let code = CompileErrorCodes.__EXTEND_POINT__;
|
2769 | const inc = () => code++;
|
2770 | const I18nErrorCodes = {
|
2771 |
|
2772 | UNEXPECTED_RETURN_TYPE: code,
|
2773 |
|
2774 | INVALID_ARGUMENT: inc(),
|
2775 |
|
2776 | MUST_BE_CALL_SETUP_TOP: inc(),
|
2777 | NOT_INSLALLED: inc(),
|
2778 | NOT_AVAILABLE_IN_LEGACY_MODE: inc(),
|
2779 |
|
2780 | REQUIRED_VALUE: inc(),
|
2781 | INVALID_VALUE: inc(),
|
2782 |
|
2783 | CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN: inc(),
|
2784 | NOT_INSLALLED_WITH_PROVIDE: inc(),
|
2785 |
|
2786 | UNEXPECTED_ERROR: inc(),
|
2787 |
|
2788 | NOT_COMPATIBLE_LEGACY_VUE_I18N: inc(),
|
2789 |
|
2790 | BRIDGE_SUPPORT_VUE_2_ONLY: inc(),
|
2791 |
|
2792 | __EXTEND_POINT__: inc()
|
2793 | };
|
2794 | function createI18nError(code, ...args) {
|
2795 | return createCompileError(code, null, { messages: errorMessages, args } );
|
2796 | }
|
2797 | const errorMessages = {
|
2798 | [I18nErrorCodes.UNEXPECTED_RETURN_TYPE]: 'Unexpected return type in composer',
|
2799 | [I18nErrorCodes.INVALID_ARGUMENT]: 'Invalid argument',
|
2800 | [I18nErrorCodes.MUST_BE_CALL_SETUP_TOP]: 'Must be called at the top of a `setup` function',
|
2801 | [I18nErrorCodes.NOT_INSLALLED]: 'Need to install with `app.use` function',
|
2802 | [I18nErrorCodes.UNEXPECTED_ERROR]: 'Unexpected error',
|
2803 | [I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE]: 'Not available in legacy mode',
|
2804 | [I18nErrorCodes.REQUIRED_VALUE]: `Required in value: {0}`,
|
2805 | [I18nErrorCodes.INVALID_VALUE]: `Invalid value`,
|
2806 | [I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN]: `Cannot setup vue-devtools plugin`,
|
2807 | [I18nErrorCodes.NOT_INSLALLED_WITH_PROVIDE]: 'Need to install with `provide` function',
|
2808 | [I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N]: 'Not compatible legacy VueI18n.',
|
2809 | [I18nErrorCodes.BRIDGE_SUPPORT_VUE_2_ONLY]: 'vue-i18n-bridge support Vue 2.x only'
|
2810 | };
|
2811 |
|
2812 | const SetPluralRulesSymbol = makeSymbol('__setPluralRules');
|
2813 | const LegacyInstanceSymbol = makeSymbol('__legacyVueI18n');
|
2814 |
|
2815 |
|
2816 |
|
2817 | function isLegacyVueI18n(VueI18n) {
|
2818 | if (VueI18n == null || VueI18n.version == null) {
|
2819 | return false;
|
2820 | }
|
2821 | return (Number(VueI18n.version.split('.')[0]) || -1) >= 8;
|
2822 | }
|
2823 |
|
2824 |
|
2825 |
|
2826 | function handleFlatJson(obj) {
|
2827 |
|
2828 | if (!isObject(obj)) {
|
2829 | return obj;
|
2830 | }
|
2831 | for (const key in obj) {
|
2832 |
|
2833 | if (!hasOwn(obj, key)) {
|
2834 | continue;
|
2835 | }
|
2836 |
|
2837 | if (!key.includes('.')) {
|
2838 |
|
2839 | if (isObject(obj[key])) {
|
2840 | handleFlatJson(obj[key]);
|
2841 | }
|
2842 | }
|
2843 |
|
2844 | else {
|
2845 |
|
2846 | const subKeys = key.split('.');
|
2847 | const lastIndex = subKeys.length - 1;
|
2848 | let currentObj = obj;
|
2849 | for (let i = 0; i < lastIndex; i++) {
|
2850 | if (!(subKeys[i] in currentObj)) {
|
2851 | currentObj[subKeys[i]] = {};
|
2852 | }
|
2853 | currentObj = currentObj[subKeys[i]];
|
2854 | }
|
2855 |
|
2856 | currentObj[subKeys[lastIndex]] = obj[key];
|
2857 | delete obj[key];
|
2858 |
|
2859 | if (isObject(currentObj[subKeys[lastIndex]])) {
|
2860 | handleFlatJson(currentObj[subKeys[lastIndex]]);
|
2861 | }
|
2862 | }
|
2863 | }
|
2864 | return obj;
|
2865 | }
|
2866 | function getLocaleMessages(locale, options) {
|
2867 | const { messages, __i18n, messageResolver, flatJson } = options;
|
2868 |
|
2869 | const ret = isPlainObject(messages)
|
2870 | ? messages
|
2871 | : isArray(__i18n)
|
2872 | ? {}
|
2873 | : { [locale]: {} };
|
2874 |
|
2875 | if (isArray(__i18n)) {
|
2876 | __i18n.forEach(({ locale, resource }) => {
|
2877 | if (locale) {
|
2878 | ret[locale] = ret[locale] || {};
|
2879 | deepCopy(resource, ret[locale]);
|
2880 | }
|
2881 | else {
|
2882 | deepCopy(resource, ret);
|
2883 | }
|
2884 | });
|
2885 | }
|
2886 |
|
2887 | if (messageResolver == null && flatJson) {
|
2888 | for (const key in ret) {
|
2889 | if (hasOwn(ret, key)) {
|
2890 | handleFlatJson(ret[key]);
|
2891 | }
|
2892 | }
|
2893 | }
|
2894 | return ret;
|
2895 | }
|
2896 | const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val);
|
2897 |
|
2898 | function deepCopy(src, des) {
|
2899 |
|
2900 | if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {
|
2901 | throw createI18nError(I18nErrorCodes.INVALID_VALUE);
|
2902 | }
|
2903 | for (const key in src) {
|
2904 | if (hasOwn(src, key)) {
|
2905 | if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) {
|
2906 |
|
2907 |
|
2908 |
|
2909 | des[key] = src[key];
|
2910 | }
|
2911 | else {
|
2912 |
|
2913 | deepCopy(src[key], des[key]);
|
2914 | }
|
2915 | }
|
2916 | }
|
2917 | }
|
2918 |
|
2919 |
|
2920 |
|
2921 | const DEVTOOLS_META = '__INTLIFY_META__';
|
2922 | let composerID = 0;
|
2923 | function defineCoreMissingHandler(missing) {
|
2924 | return ((ctx, locale, key, type) => {
|
2925 | return missing(locale, key, getCurrentInstance() || undefined, type);
|
2926 | });
|
2927 | }
|
2928 |
|
2929 | const getMetaInfo = () => {
|
2930 | const instance = getCurrentInstance();
|
2931 | return instance && instance.type[DEVTOOLS_META]
|
2932 | ? { [DEVTOOLS_META]: instance.type[DEVTOOLS_META] }
|
2933 | : null;
|
2934 | };
|
2935 |
|
2936 |
|
2937 |
|
2938 |
|
2939 |
|
2940 |
|
2941 | function createComposer(options = {}, VueI18nLegacy) {
|
2942 | const { __root } = options;
|
2943 | const _isGlobal = __root === undefined;
|
2944 | let _inheritLocale = isBoolean(options.inheritLocale)
|
2945 | ? options.inheritLocale
|
2946 | : true;
|
2947 | const _locale = ref(
|
2948 |
|
2949 | __root && _inheritLocale
|
2950 | ? __root.locale.value
|
2951 | : isString(options.locale)
|
2952 | ? options.locale
|
2953 | : DEFAULT_LOCALE);
|
2954 | const _fallbackLocale = ref(
|
2955 |
|
2956 | __root && _inheritLocale
|
2957 | ? __root.fallbackLocale.value
|
2958 | : isString(options.fallbackLocale) ||
|
2959 | isArray(options.fallbackLocale) ||
|
2960 | isPlainObject(options.fallbackLocale) ||
|
2961 | options.fallbackLocale === false
|
2962 | ? options.fallbackLocale
|
2963 | : _locale.value);
|
2964 | const _messages = ref(getLocaleMessages(_locale.value, options));
|
2965 |
|
2966 | const _datetimeFormats = ref(isPlainObject(options.datetimeFormats)
|
2967 | ? options.datetimeFormats
|
2968 | : { [_locale.value]: {} })
|
2969 | ;
|
2970 |
|
2971 | const _numberFormats = ref(isPlainObject(options.numberFormats)
|
2972 | ? options.numberFormats
|
2973 | : { [_locale.value]: {} })
|
2974 | ;
|
2975 |
|
2976 |
|
2977 | let _missingWarn = __root
|
2978 | ? __root.missingWarn
|
2979 | : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
|
2980 | ? options.missingWarn
|
2981 | : true;
|
2982 |
|
2983 | let _fallbackWarn = __root
|
2984 | ? __root.fallbackWarn
|
2985 | : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
|
2986 | ? options.fallbackWarn
|
2987 | : true;
|
2988 |
|
2989 | let _fallbackRoot = __root
|
2990 | ? __root.fallbackRoot
|
2991 | : isBoolean(options.fallbackRoot)
|
2992 | ? options.fallbackRoot
|
2993 | : true;
|
2994 |
|
2995 | let _fallbackFormat = !!options.fallbackFormat;
|
2996 |
|
2997 | let _missing = isFunction(options.missing) ? options.missing : null;
|
2998 | let _runtimeMissing = isFunction(options.missing)
|
2999 | ? defineCoreMissingHandler(options.missing)
|
3000 | : null;
|
3001 |
|
3002 | let _postTranslation = isFunction(options.postTranslation)
|
3003 | ? options.postTranslation
|
3004 | : null;
|
3005 | let _warnHtmlMessage = isBoolean(options.warnHtmlMessage)
|
3006 | ? options.warnHtmlMessage
|
3007 | : true;
|
3008 | let _escapeParameter = !!options.escapeParameter;
|
3009 |
|
3010 |
|
3011 | const _modifiers = __root
|
3012 | ? __root.modifiers
|
3013 | : isPlainObject(options.modifiers)
|
3014 | ? options.modifiers
|
3015 | : {};
|
3016 |
|
3017 | let _pluralRules = options.pluralRules || (__root && __root.pluralRules);
|
3018 |
|
3019 | let __legacy;
|
3020 | {
|
3021 | if (!isLegacyVueI18n(VueI18nLegacy)) {
|
3022 | createI18nError(I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N);
|
3023 | }
|
3024 | const legacyOptions = {
|
3025 | locale: _locale.value,
|
3026 | fallbackLocale: _fallbackLocale.value,
|
3027 | messages: _messages.value,
|
3028 | dateTimeFormats: _datetimeFormats.value,
|
3029 | numberFormats: _numberFormats.value,
|
3030 | modifiers: _modifiers,
|
3031 | missing: _missing,
|
3032 | fallbackRoot: _fallbackRoot,
|
3033 | postTranslation: _postTranslation,
|
3034 | pluralizationRules: _pluralRules,
|
3035 | escapeParameterHtml: _escapeParameter,
|
3036 | sync: _inheritLocale,
|
3037 | silentFallbackWarn: isBoolean(_fallbackWarn)
|
3038 | ? !_fallbackWarn
|
3039 | : _fallbackWarn,
|
3040 | silentTranslationWarn: isBoolean(_missingWarn)
|
3041 | ? !_missingWarn
|
3042 | : _missingWarn,
|
3043 | formatFallbackMessages: isBoolean(_fallbackFormat)
|
3044 | ? !_fallbackFormat
|
3045 | : _fallbackFormat,
|
3046 | warnHtmlInMessage: isBoolean(_warnHtmlMessage)
|
3047 | ? _warnHtmlMessage
|
3048 | ? 'warn'
|
3049 | : 'off'
|
3050 | : 'off'
|
3051 | };
|
3052 | __legacy = new VueI18nLegacy(legacyOptions);
|
3053 | }
|
3054 |
|
3055 |
|
3056 | let _context;
|
3057 | function getCoreContext() {
|
3058 | const ctxOptions = {
|
3059 | version: VERSION,
|
3060 | locale: _locale.value,
|
3061 | fallbackLocale: _fallbackLocale.value,
|
3062 | messages: _messages.value,
|
3063 | modifiers: _modifiers,
|
3064 | pluralRules: _pluralRules,
|
3065 | missing: _runtimeMissing === null ? undefined : _runtimeMissing,
|
3066 | missingWarn: _missingWarn,
|
3067 | fallbackWarn: _fallbackWarn,
|
3068 | fallbackFormat: _fallbackFormat,
|
3069 | unresolving: true,
|
3070 | postTranslation: _postTranslation === null ? undefined : _postTranslation,
|
3071 | warnHtmlMessage: _warnHtmlMessage,
|
3072 | escapeParameter: _escapeParameter,
|
3073 | messageResolver: options.messageResolver,
|
3074 | __meta: { framework: 'vue' }
|
3075 | };
|
3076 | {
|
3077 | ctxOptions.datetimeFormats = _datetimeFormats.value;
|
3078 | ctxOptions.numberFormats = _numberFormats.value;
|
3079 | ctxOptions.__datetimeFormatters = isPlainObject(_context)
|
3080 | ? _context.__datetimeFormatters
|
3081 | : undefined;
|
3082 | ctxOptions.__numberFormatters = isPlainObject(_context)
|
3083 | ? _context.__numberFormatters
|
3084 | : undefined;
|
3085 | }
|
3086 | return createCoreContext(ctxOptions);
|
3087 | }
|
3088 | _context = getCoreContext();
|
3089 | updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
|
3090 |
|
3091 | function trackReactivityValues() {
|
3092 | return [
|
3093 | _locale.value,
|
3094 | _fallbackLocale.value,
|
3095 | _messages.value,
|
3096 | _datetimeFormats.value,
|
3097 | _numberFormats.value
|
3098 | ]
|
3099 | ;
|
3100 | }
|
3101 |
|
3102 | const locale = computed({
|
3103 | get: () => _locale.value,
|
3104 | set: val => {
|
3105 | _locale.value = val;
|
3106 | {
|
3107 | if (__legacy) {
|
3108 | __legacy.locale = val;
|
3109 | }
|
3110 | }
|
3111 | _context.locale = _locale.value;
|
3112 | }
|
3113 | });
|
3114 |
|
3115 | const fallbackLocale = computed({
|
3116 | get: () => _fallbackLocale.value,
|
3117 | set: val => {
|
3118 | _fallbackLocale.value = val;
|
3119 | {
|
3120 | if (__legacy) {
|
3121 | __legacy.fallbackLocale = val;
|
3122 | }
|
3123 | }
|
3124 | _context.fallbackLocale = _fallbackLocale.value;
|
3125 | updateFallbackLocale(_context, _locale.value, val);
|
3126 | }
|
3127 | });
|
3128 |
|
3129 | const messages = computed(() => _messages.value);
|
3130 |
|
3131 | const datetimeFormats = computed(() => _datetimeFormats.value);
|
3132 |
|
3133 | const numberFormats = computed(() => _numberFormats.value);
|
3134 |
|
3135 | function getPostTranslationHandler() {
|
3136 | return isFunction(_postTranslation) ? _postTranslation : null;
|
3137 | }
|
3138 |
|
3139 | function setPostTranslationHandler(handler) {
|
3140 | _postTranslation = handler;
|
3141 | _context.postTranslation = handler;
|
3142 | }
|
3143 |
|
3144 | function getMissingHandler() {
|
3145 | return _missing;
|
3146 | }
|
3147 |
|
3148 | function setMissingHandler(handler) {
|
3149 | if (handler !== null) {
|
3150 | _runtimeMissing = defineCoreMissingHandler(handler);
|
3151 | }
|
3152 | _missing = handler;
|
3153 | _context.missing = _runtimeMissing;
|
3154 | }
|
3155 | function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any
|
3156 | ) {
|
3157 | return type !== 'translate' || !arg.resolvedMessage;
|
3158 | }
|
3159 | function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) {
|
3160 | trackReactivityValues();
|
3161 |
|
3162 | let ret;
|
3163 | {
|
3164 | try {
|
3165 | setAdditionalMeta(getMetaInfo());
|
3166 | ret = fn(_context);
|
3167 | }
|
3168 | finally {
|
3169 | setAdditionalMeta(null);
|
3170 | }
|
3171 | }
|
3172 | if (isNumber(ret) && ret === NOT_REOSLVED) {
|
3173 | const [key, arg2] = argumentParser();
|
3174 | if (__root &&
|
3175 | isString(key) &&
|
3176 | isResolvedTranslateMessage(warnType, arg2)) {
|
3177 | if (_fallbackRoot &&
|
3178 | (isTranslateFallbackWarn(_fallbackWarn, key) ||
|
3179 | isTranslateMissingWarn(_missingWarn, key))) {
|
3180 | warn(getWarnMessage(I18nWarnCodes.FALLBACK_TO_ROOT, {
|
3181 | key,
|
3182 | type: warnType
|
3183 | }));
|
3184 | }
|
3185 | }
|
3186 | return __root && _fallbackRoot
|
3187 | ? fallbackSuccess(__root)
|
3188 | : fallbackFail(key);
|
3189 | }
|
3190 | else if (successCondition(ret)) {
|
3191 | return ret;
|
3192 | }
|
3193 | else {
|
3194 |
|
3195 | throw createI18nError(I18nErrorCodes.UNEXPECTED_RETURN_TYPE);
|
3196 | }
|
3197 | }
|
3198 |
|
3199 | function t(...args) {
|
3200 | return wrapWithDeps(context => Reflect.apply(translate, null, [context, ...args]), () => parseTranslateArgs(...args), 'translate', root => Reflect.apply(root.t, root, [...args]), key => key, val => isString(val));
|
3201 | }
|
3202 |
|
3203 | function rt(...args) {
|
3204 | const [arg1, arg2, arg3] = args;
|
3205 | if (arg3 && !isObject(arg3)) {
|
3206 | throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
|
3207 | }
|
3208 | return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]);
|
3209 | }
|
3210 |
|
3211 | function d(...args) {
|
3212 | return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format', root => Reflect.apply(root.d, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));
|
3213 | }
|
3214 |
|
3215 | function n(...args) {
|
3216 | return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format', root => Reflect.apply(root.n, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));
|
3217 | }
|
3218 | function setPluralRules(rules) {
|
3219 | _pluralRules = rules;
|
3220 | _context.pluralRules = _pluralRules;
|
3221 | }
|
3222 |
|
3223 | function te(key, locale) {
|
3224 | const targetLocale = isString(locale) ? locale : _locale.value;
|
3225 | const message = getLocaleMessage(targetLocale);
|
3226 | return _context.messageResolver(message, key) !== null;
|
3227 | }
|
3228 | function resolveMessages(key) {
|
3229 | let messages = null;
|
3230 | const locales = fallbackWithLocaleChain(_context, _fallbackLocale.value, _locale.value);
|
3231 | for (let i = 0; i < locales.length; i++) {
|
3232 | const targetLocaleMessages = _messages.value[locales[i]] || {};
|
3233 | const messageValue = _context.messageResolver(targetLocaleMessages, key);
|
3234 | if (messageValue != null) {
|
3235 | messages = messageValue;
|
3236 | break;
|
3237 | }
|
3238 | }
|
3239 | return messages;
|
3240 | }
|
3241 |
|
3242 | function tm(key) {
|
3243 | const messages = resolveMessages(key);
|
3244 |
|
3245 | return messages != null
|
3246 | ? messages
|
3247 | : __root
|
3248 | ? __root.tm(key) || {}
|
3249 | : {};
|
3250 | }
|
3251 |
|
3252 | function getLocaleMessage(locale) {
|
3253 | return (_messages.value[locale] || {});
|
3254 | }
|
3255 |
|
3256 | function setLocaleMessage(locale, message) {
|
3257 | _messages.value[locale] = message;
|
3258 | {
|
3259 | __legacy && __legacy.setLocaleMessage(locale, message);
|
3260 | }
|
3261 | _context.messages = _messages.value;
|
3262 | }
|
3263 |
|
3264 | function mergeLocaleMessage(locale, message) {
|
3265 | _messages.value[locale] = _messages.value[locale] || {};
|
3266 | {
|
3267 | __legacy && __legacy.mergeLocaleMessage(locale, message);
|
3268 | }
|
3269 | deepCopy(message, _messages.value[locale]);
|
3270 | _context.messages = _messages.value;
|
3271 | }
|
3272 |
|
3273 | function getDateTimeFormat(locale) {
|
3274 | return _datetimeFormats.value[locale] || {};
|
3275 | }
|
3276 |
|
3277 | function setDateTimeFormat(locale, format) {
|
3278 | _datetimeFormats.value[locale] = format;
|
3279 | {
|
3280 | __legacy && __legacy.setDateTimeFormat(locale, format);
|
3281 | }
|
3282 | _context.datetimeFormats = _datetimeFormats.value;
|
3283 | clearDateTimeFormat(_context, locale, format);
|
3284 | }
|
3285 |
|
3286 | function mergeDateTimeFormat(locale, format) {
|
3287 | _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format);
|
3288 | {
|
3289 | __legacy && __legacy.mergeDateTimeFormat(locale, format);
|
3290 | }
|
3291 | _context.datetimeFormats = _datetimeFormats.value;
|
3292 | clearDateTimeFormat(_context, locale, format);
|
3293 | }
|
3294 |
|
3295 | function getNumberFormat(locale) {
|
3296 | return _numberFormats.value[locale] || {};
|
3297 | }
|
3298 |
|
3299 | function setNumberFormat(locale, format) {
|
3300 | _numberFormats.value[locale] = format;
|
3301 | {
|
3302 | __legacy && __legacy.setNumberFormat(locale, format);
|
3303 | }
|
3304 | _context.numberFormats = _numberFormats.value;
|
3305 | clearNumberFormat(_context, locale, format);
|
3306 | }
|
3307 |
|
3308 | function mergeNumberFormat(locale, format) {
|
3309 | _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format);
|
3310 | {
|
3311 | __legacy && __legacy.mergeNumberFormat(locale, format);
|
3312 | }
|
3313 | _context.numberFormats = _numberFormats.value;
|
3314 | clearNumberFormat(_context, locale, format);
|
3315 | }
|
3316 |
|
3317 | composerID++;
|
3318 |
|
3319 | if (__root) {
|
3320 | watch(__root.locale, (val) => {
|
3321 | if (_inheritLocale) {
|
3322 | _locale.value = val;
|
3323 | {
|
3324 | if (__legacy) {
|
3325 | __legacy.locale = val;
|
3326 | }
|
3327 | }
|
3328 | _context.locale = val;
|
3329 | updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
|
3330 | }
|
3331 | });
|
3332 | watch(__root.fallbackLocale, (val) => {
|
3333 | if (_inheritLocale) {
|
3334 | _fallbackLocale.value = val;
|
3335 | {
|
3336 | if (__legacy) {
|
3337 | __legacy.fallbackLocale = val;
|
3338 | }
|
3339 | }
|
3340 | _context.fallbackLocale = val;
|
3341 | updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
|
3342 | }
|
3343 | });
|
3344 | }
|
3345 |
|
3346 | const composer = {
|
3347 | id: composerID,
|
3348 | locale,
|
3349 | fallbackLocale,
|
3350 | get inheritLocale() {
|
3351 | return _inheritLocale;
|
3352 | },
|
3353 | set inheritLocale(val) {
|
3354 | _inheritLocale = val;
|
3355 | {
|
3356 | if (__legacy) {
|
3357 | __legacy._sync = val;
|
3358 | }
|
3359 | }
|
3360 | if (val && __root) {
|
3361 | _locale.value = __root.locale.value;
|
3362 | _fallbackLocale.value = __root.fallbackLocale.value;
|
3363 | {
|
3364 | if (__legacy) {
|
3365 | __legacy.locale = __root.locale.value;
|
3366 | __legacy.fallbackLocale = __root.fallbackLocale.value;
|
3367 | }
|
3368 | }
|
3369 | updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
|
3370 | }
|
3371 | },
|
3372 | get availableLocales() {
|
3373 | return Object.keys(_messages.value).sort();
|
3374 | },
|
3375 | messages,
|
3376 | get modifiers() {
|
3377 | return _modifiers;
|
3378 | },
|
3379 | get pluralRules() {
|
3380 | return _pluralRules || {};
|
3381 | },
|
3382 | get isGlobal() {
|
3383 | return _isGlobal;
|
3384 | },
|
3385 | get missingWarn() {
|
3386 | return _missingWarn;
|
3387 | },
|
3388 | set missingWarn(val) {
|
3389 | _missingWarn = val;
|
3390 | _context.missingWarn = _missingWarn;
|
3391 | },
|
3392 | get fallbackWarn() {
|
3393 | return _fallbackWarn;
|
3394 | },
|
3395 | set fallbackWarn(val) {
|
3396 | _fallbackWarn = val;
|
3397 | _context.fallbackWarn = _fallbackWarn;
|
3398 | },
|
3399 | get fallbackRoot() {
|
3400 | return _fallbackRoot;
|
3401 | },
|
3402 | set fallbackRoot(val) {
|
3403 | _fallbackRoot = val;
|
3404 | },
|
3405 | get fallbackFormat() {
|
3406 | return _fallbackFormat;
|
3407 | },
|
3408 | set fallbackFormat(val) {
|
3409 | _fallbackFormat = val;
|
3410 | _context.fallbackFormat = _fallbackFormat;
|
3411 | },
|
3412 | get warnHtmlMessage() {
|
3413 | return _warnHtmlMessage;
|
3414 | },
|
3415 | set warnHtmlMessage(val) {
|
3416 | _warnHtmlMessage = val;
|
3417 | _context.warnHtmlMessage = val;
|
3418 | },
|
3419 | get escapeParameter() {
|
3420 | return _escapeParameter;
|
3421 | },
|
3422 | set escapeParameter(val) {
|
3423 | _escapeParameter = val;
|
3424 | _context.escapeParameter = val;
|
3425 | },
|
3426 | t,
|
3427 | getLocaleMessage,
|
3428 | setLocaleMessage,
|
3429 | mergeLocaleMessage,
|
3430 | getPostTranslationHandler,
|
3431 | setPostTranslationHandler,
|
3432 | getMissingHandler,
|
3433 | setMissingHandler,
|
3434 | [SetPluralRulesSymbol]: setPluralRules
|
3435 | };
|
3436 | {
|
3437 | composer.datetimeFormats = datetimeFormats;
|
3438 | composer.numberFormats = numberFormats;
|
3439 | composer.rt = rt;
|
3440 | composer.te = te;
|
3441 | composer.tm = tm;
|
3442 | composer.d = d;
|
3443 | composer.n = n;
|
3444 | composer.getDateTimeFormat = getDateTimeFormat;
|
3445 | composer.setDateTimeFormat = setDateTimeFormat;
|
3446 | composer.mergeDateTimeFormat = mergeDateTimeFormat;
|
3447 | composer.getNumberFormat = getNumberFormat;
|
3448 | composer.setNumberFormat = setNumberFormat;
|
3449 | composer.mergeNumberFormat = mergeNumberFormat;
|
3450 | }
|
3451 | {
|
3452 | composer[LegacyInstanceSymbol] = __legacy;
|
3453 | }
|
3454 | return composer;
|
3455 | }
|
3456 |
|
3457 |
|
3458 |
|
3459 |
|
3460 |
|
3461 |
|
3462 | function defineMixin(i18n, VueI18n // eslint-disable-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
|
3463 | ) {
|
3464 | return {
|
3465 | beforeCreate() {
|
3466 | const options = this.$options;
|
3467 | if (options.__VUE18N__INSTANCE__) {
|
3468 | return;
|
3469 | }
|
3470 | options.i18n = options.i18n || (options.__i18n ? {} : null);
|
3471 | this._i18nBridgeRoot = i18n;
|
3472 | if (i18n.mode === 'composition') {
|
3473 | this._i18n = i18n;
|
3474 | return;
|
3475 | }
|
3476 | if (options.i18n) {
|
3477 | if (options.i18n instanceof VueI18n) {
|
3478 |
|
3479 | if (options.__i18n) {
|
3480 | try {
|
3481 | const localeMessages = options.i18n && options.i18n.messages
|
3482 | ? options.i18n.messages
|
3483 | : {};
|
3484 | options.__i18n.forEach(resource => deepCopy(localeMessages, JSON.parse(resource)));
|
3485 | Object.keys(localeMessages).forEach((locale) => {
|
3486 | options.i18n.mergeLocaleMessage(locale, localeMessages[locale]);
|
3487 | });
|
3488 | }
|
3489 | catch (e) {
|
3490 | {
|
3491 | console.error(`Cannot parse locale messages via custom blocks.`, e);
|
3492 | }
|
3493 | }
|
3494 | }
|
3495 | this._i18n = options.i18n;
|
3496 | this._i18nWatcher = this._i18n.watchI18nData();
|
3497 | }
|
3498 | else if (isPlainObject(options.i18n)) {
|
3499 | const rootI18n = this.$root &&
|
3500 | this.$root.$i18n &&
|
3501 | this.$root.$i18n instanceof VueI18n
|
3502 | ? this.$root.$i18n
|
3503 | : null;
|
3504 |
|
3505 | if (rootI18n) {
|
3506 | options.i18n.root = this.$root;
|
3507 | options.i18n.formatter = rootI18n.formatter;
|
3508 | options.i18n.fallbackLocale = rootI18n.fallbackLocale;
|
3509 | options.i18n.formatFallbackMessages =
|
3510 | rootI18n.formatFallbackMessages;
|
3511 | options.i18n.silentTranslationWarn = rootI18n.silentTranslationWarn;
|
3512 | options.i18n.silentFallbackWarn = rootI18n.silentFallbackWarn;
|
3513 | options.i18n.pluralizationRules = rootI18n.pluralizationRules;
|
3514 | options.i18n.preserveDirectiveContent =
|
3515 | rootI18n.preserveDirectiveContent;
|
3516 | }
|
3517 |
|
3518 | if (options.__i18n) {
|
3519 | try {
|
3520 | const localeMessages = options.i18n && options.i18n.messages
|
3521 | ? options.i18n.messages
|
3522 | : {};
|
3523 | options.__i18n.forEach(resource => deepCopy(localeMessages, JSON.parse(resource)));
|
3524 | options.i18n.messages = localeMessages;
|
3525 | }
|
3526 | catch (e) {
|
3527 | {
|
3528 | warn(`Cannot parse locale messages via custom blocks.`, e);
|
3529 | }
|
3530 | }
|
3531 | }
|
3532 | const { sharedMessages } = options.i18n;
|
3533 | if (sharedMessages && isPlainObject(sharedMessages)) {
|
3534 | deepCopy(options.i18n.messages, sharedMessages);
|
3535 | }
|
3536 | this._i18n = new VueI18n(options.i18n);
|
3537 | this._i18nWatcher = this._i18n.watchI18nData();
|
3538 | if (options.i18n.sync === undefined || !!options.i18n.sync) {
|
3539 | this._localeWatcher = this.$i18n.watchLocale();
|
3540 | }
|
3541 | if (rootI18n) {
|
3542 | rootI18n.onComponentInstanceCreated(this._i18n);
|
3543 | }
|
3544 | }
|
3545 | else {
|
3546 | {
|
3547 | warn(`Cannot be interpreted 'i18n' option.`);
|
3548 | }
|
3549 | }
|
3550 | }
|
3551 | else if (this.$root &&
|
3552 | this.$root.$i18n &&
|
3553 | this.$root.$i18n instanceof VueI18n) {
|
3554 |
|
3555 | this._i18n = this.$root.$i18n;
|
3556 | }
|
3557 | else if (options.parent &&
|
3558 | options.parent.$i18n &&
|
3559 | options.parent.$i18n instanceof VueI18n) {
|
3560 |
|
3561 | this._i18n = options.parent.$i18n;
|
3562 | }
|
3563 | },
|
3564 | beforeMount() {
|
3565 | const options = this.$options;
|
3566 | if (options.__VUE18N__INSTANCE__) {
|
3567 | return;
|
3568 | }
|
3569 | options.i18n = options.i18n || (options.__i18n ? {} : null);
|
3570 | if (options.i18n) {
|
3571 | if (options.i18n instanceof VueI18n) {
|
3572 |
|
3573 | this._i18n.subscribeDataChanging(this);
|
3574 | this._subscribing = true;
|
3575 | }
|
3576 | else if (isPlainObject(options.i18n)) {
|
3577 | this._i18n.subscribeDataChanging(this);
|
3578 | this._subscribing = true;
|
3579 | }
|
3580 | else {
|
3581 | {
|
3582 | warn(`Cannot be interpreted 'i18n' option.`);
|
3583 | }
|
3584 | }
|
3585 | }
|
3586 | else if (this.$root &&
|
3587 | this.$root.$i18n &&
|
3588 | this.$root.$i18n instanceof VueI18n) {
|
3589 | this._i18n.subscribeDataChanging(this);
|
3590 | this._subscribing = true;
|
3591 | }
|
3592 | else if (options.parent &&
|
3593 | options.parent.$i18n &&
|
3594 | options.parent.$i18n instanceof VueI18n) {
|
3595 | this._i18n.subscribeDataChanging(this);
|
3596 | this._subscribing = true;
|
3597 | }
|
3598 | },
|
3599 | beforeDestroy() {
|
3600 | const options = this.$options;
|
3601 | if (options.__VUE18N__INSTANCE__) {
|
3602 | return;
|
3603 | }
|
3604 | if (this._i18nBridgeRoot) {
|
3605 | delete this._i18nBridgeRoot;
|
3606 | return;
|
3607 | }
|
3608 | if (i18n.mode === 'composition') {
|
3609 | delete this._i18n;
|
3610 | return;
|
3611 | }
|
3612 | if (!this._i18n) {
|
3613 | return;
|
3614 | }
|
3615 | const self = this;
|
3616 | this.$nextTick(() => {
|
3617 | if (self._subscribing) {
|
3618 | self._i18n.unsubscribeDataChanging(self);
|
3619 | delete self._subscribing;
|
3620 | }
|
3621 | if (self._i18nWatcher) {
|
3622 | self._i18nWatcher();
|
3623 | self._i18n.destroyVM();
|
3624 | delete self._i18nWatcher;
|
3625 | }
|
3626 | if (self._localeWatcher) {
|
3627 | self._localeWatcher();
|
3628 | delete self._localeWatcher;
|
3629 | }
|
3630 | });
|
3631 | }
|
3632 | };
|
3633 | }
|
3634 |
|
3635 |
|
3636 | let _legacyVueI18n = null;
|
3637 | let _legacyI18n = null;
|
3638 |
|
3639 |
|
3640 |
|
3641 |
|
3642 |
|
3643 |
|
3644 |
|
3645 |
|
3646 |
|
3647 | const I18nInjectionKey =
|
3648 | makeSymbol('global-vue-i18n');
|
3649 |
|
3650 | function createI18n(options = {}, VueI18nLegacy) {
|
3651 | if (_legacyI18n) {
|
3652 | warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORT_MULTI_I18N_INSTANCE));
|
3653 | return _legacyI18n;
|
3654 | }
|
3655 | {
|
3656 | _legacyVueI18n = VueI18nLegacy;
|
3657 | }
|
3658 |
|
3659 | const __legacyMode = isBoolean(options.legacy)
|
3660 | ? options.legacy
|
3661 | : true;
|
3662 | !!options.globalInjection;
|
3663 | const __instances = new Map();
|
3664 | const __global = createGlobal(options, __legacyMode, VueI18nLegacy);
|
3665 | function __getInstance(component) {
|
3666 | return __instances.get(component) || null;
|
3667 | }
|
3668 | function __setInstance(component, instance) {
|
3669 | __instances.set(component, instance);
|
3670 | }
|
3671 | function __deleteInstance(component) {
|
3672 | __instances.delete(component);
|
3673 | }
|
3674 | {
|
3675 |
|
3676 | const i18n = __global[LegacyInstanceSymbol];
|
3677 | Object.defineProperty(i18n, 'global', {
|
3678 | get() {
|
3679 | return __global;
|
3680 | }
|
3681 | });
|
3682 | Object.defineProperty(i18n, 'mode', {
|
3683 | get() {
|
3684 | return __legacyMode ? 'legacy' : 'composition';
|
3685 | }
|
3686 | });
|
3687 | Object.defineProperty(i18n, '__instances', {
|
3688 | get() {
|
3689 | return __instances;
|
3690 | }
|
3691 | });
|
3692 | Object.defineProperty(i18n, 'install', {
|
3693 |
|
3694 | value: (Vue) => {
|
3695 | const version = (Vue && Vue.version && Number(Vue.version.split('.')[0])) || -1;
|
3696 | if (version !== 2) {
|
3697 | throw createI18nError(I18nErrorCodes.BRIDGE_SUPPORT_VUE_2_ONLY);
|
3698 | }
|
3699 | Vue.mixin(defineMixin(i18n, _legacyVueI18n));
|
3700 | }
|
3701 | });
|
3702 | const methodMap = {
|
3703 | __getInstance,
|
3704 | __setInstance,
|
3705 | __deleteInstance
|
3706 | };
|
3707 | Object.keys(methodMap).forEach(key => Object.defineProperty(i18n, key, { value: methodMap[key] })
|
3708 | );
|
3709 | _legacyI18n = i18n;
|
3710 | return i18n;
|
3711 | }
|
3712 | }
|
3713 |
|
3714 | function useI18n(options = {}) {
|
3715 | const instance = getCurrentInstance();
|
3716 | if (instance == null) {
|
3717 | throw createI18nError(I18nErrorCodes.MUST_BE_CALL_SETUP_TOP);
|
3718 | }
|
3719 | {
|
3720 | if (_legacyVueI18n == null || _legacyI18n == null) {
|
3721 | throw createI18nError(I18nErrorCodes.NOT_INSLALLED);
|
3722 | }
|
3723 | }
|
3724 | const i18n = getI18nInstance(instance);
|
3725 | const global = getGlobalComposer(i18n);
|
3726 | const componentOptions = getComponentOptions(instance);
|
3727 | const scope = getScope(options, componentOptions);
|
3728 | if (scope === 'global') {
|
3729 | adjustI18nResources(global, options, componentOptions);
|
3730 | return global;
|
3731 | }
|
3732 | if (scope === 'parent') {
|
3733 | let composer = getComposer(i18n, instance);
|
3734 | if (composer == null) {
|
3735 | {
|
3736 | warn(getWarnMessage(I18nWarnCodes.NOT_FOUND_PARENT_SCOPE));
|
3737 | }
|
3738 | composer = global;
|
3739 | }
|
3740 | return composer;
|
3741 | }
|
3742 |
|
3743 | if (i18n.mode === 'legacy') {
|
3744 | throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE);
|
3745 | }
|
3746 | const i18nInternal = i18n;
|
3747 | let composer = i18nInternal.__getInstance(instance);
|
3748 | if (composer == null) {
|
3749 | const composerOptions = assign({}, options);
|
3750 | if ('__i18n' in componentOptions) {
|
3751 | composerOptions.__i18n = componentOptions.__i18n;
|
3752 | }
|
3753 | if (global) {
|
3754 | composerOptions.__root = global;
|
3755 | }
|
3756 | composer = createComposer(composerOptions, _legacyVueI18n);
|
3757 | setupLifeCycle(i18nInternal, instance, composer);
|
3758 | i18nInternal.__setInstance(instance, composer);
|
3759 | }
|
3760 | return composer;
|
3761 | }
|
3762 | function createGlobal(options, legacyMode, VueI18nLegacy // eslint-disable-line @typescript-eslint/no-explicit-any
|
3763 | ) {
|
3764 | {
|
3765 | if (!isLegacyVueI18n(VueI18nLegacy)) {
|
3766 | throw createI18nError(I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N);
|
3767 | }
|
3768 | return createComposer(options, VueI18nLegacy);
|
3769 | }
|
3770 | }
|
3771 | function getI18nInstance(instance) {
|
3772 | {
|
3773 | const vm = instance.proxy;
|
3774 |
|
3775 | if (vm == null) {
|
3776 | throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
|
3777 | }
|
3778 | const i18n = vm._i18nBridgeRoot;
|
3779 |
|
3780 | if (!i18n) {
|
3781 | throw createI18nError(I18nErrorCodes.NOT_INSLALLED);
|
3782 | }
|
3783 | return i18n;
|
3784 | }
|
3785 | }
|
3786 |
|
3787 | function getComponentOptions(instance) {
|
3788 | return instance.proxy.$options;
|
3789 | }
|
3790 |
|
3791 | function getScope(options, componentOptions) {
|
3792 |
|
3793 | return isEmptyObject(options)
|
3794 | ? ('__i18n' in componentOptions)
|
3795 | ? 'local'
|
3796 | : 'global'
|
3797 | : !options.useScope
|
3798 | ? 'local'
|
3799 | : options.useScope;
|
3800 | }
|
3801 | function getGlobalComposer(i18n) {
|
3802 |
|
3803 | return i18n.global;
|
3804 | }
|
3805 | function adjustI18nResources(global, options, componentOptions // eslint-disable-line @typescript-eslint/no-explicit-any
|
3806 | ) {
|
3807 | let messages = isObject(options.messages) ? options.messages : {};
|
3808 | if ('__i18nGlobal' in componentOptions) {
|
3809 | messages = getLocaleMessages(global.locale.value, {
|
3810 | messages,
|
3811 | __i18n: componentOptions.__i18nGlobal
|
3812 | });
|
3813 | }
|
3814 |
|
3815 | const locales = Object.keys(messages);
|
3816 | if (locales.length) {
|
3817 | locales.forEach(locale => {
|
3818 | global.mergeLocaleMessage(locale, messages[locale]);
|
3819 | });
|
3820 | }
|
3821 | {
|
3822 |
|
3823 | if (isObject(options.datetimeFormats)) {
|
3824 | const locales = Object.keys(options.datetimeFormats);
|
3825 | if (locales.length) {
|
3826 | locales.forEach(locale => {
|
3827 | global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
|
3828 | });
|
3829 | }
|
3830 | }
|
3831 |
|
3832 | if (isObject(options.numberFormats)) {
|
3833 | const locales = Object.keys(options.numberFormats);
|
3834 | if (locales.length) {
|
3835 | locales.forEach(locale => {
|
3836 | global.mergeNumberFormat(locale, options.numberFormats[locale]);
|
3837 | });
|
3838 | }
|
3839 | }
|
3840 | }
|
3841 | }
|
3842 | function getComposer(i18n, target) {
|
3843 | let composer = null;
|
3844 | const root = target.root;
|
3845 | let current = target.parent;
|
3846 | while (current != null) {
|
3847 | const i18nInternal = i18n;
|
3848 | if (i18n.mode === 'composition') {
|
3849 | composer = i18nInternal.__getInstance(current);
|
3850 | }
|
3851 | else {
|
3852 | {
|
3853 | const vueI18n = i18nInternal.__getInstance(current);
|
3854 | if (vueI18n != null) {
|
3855 | composer = vueI18n
|
3856 | .__composer;
|
3857 | }
|
3858 | }
|
3859 | }
|
3860 | if (composer != null) {
|
3861 | break;
|
3862 | }
|
3863 | if (root === current) {
|
3864 | break;
|
3865 | }
|
3866 | current = current.parent;
|
3867 | }
|
3868 | return composer;
|
3869 | }
|
3870 | function setupLifeCycle(i18n, target, composer) {
|
3871 | {
|
3872 |
|
3873 |
|
3874 | const vm = target.proxy;
|
3875 | if (vm == null) {
|
3876 | throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
|
3877 | }
|
3878 |
|
3879 | const _i18n = composer[LegacyInstanceSymbol];
|
3880 | if (_i18n === i18n) {
|
3881 | throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
|
3882 | }
|
3883 | vm._i18n = _i18n;
|
3884 | vm._i18n_bridge = true;
|
3885 | vm._i18nWatcher = vm._i18n.watchI18nData();
|
3886 | if (vm._i18n._sync) {
|
3887 | vm._localeWatcher = vm._i18n.watchLocale();
|
3888 | }
|
3889 | let subscribing = false;
|
3890 | onBeforeMount(() => {
|
3891 | vm._i18n.subscribeDataChanging(vm);
|
3892 | subscribing = true;
|
3893 | }, target);
|
3894 | onUnmounted(() => {
|
3895 | if (subscribing) {
|
3896 | vm._i18n.unsubscribeDataChanging(vm);
|
3897 | subscribing = false;
|
3898 | }
|
3899 | if (vm._i18nWatcher) {
|
3900 | vm._i18nWatcher();
|
3901 | vm._i18n.destroyVM();
|
3902 | delete vm._i18nWatcher;
|
3903 | }
|
3904 | if (vm._localeWatcher) {
|
3905 | vm._localeWatcher();
|
3906 | delete vm._localeWatcher;
|
3907 | }
|
3908 | delete vm._i18n_bridge;
|
3909 | delete vm._i18n;
|
3910 | }, target);
|
3911 | }
|
3912 | }
|
3913 |
|
3914 |
|
3915 | registerMessageCompiler(compileToFunction);
|
3916 |
|
3917 | registerMessageResolver(resolveValue);
|
3918 |
|
3919 | registerLocaleFallbacker(fallbackWithLocaleChain);
|
3920 |
|
3921 | {
|
3922 | const target = getGlobalThis();
|
3923 | target.__INTLIFY__ = true;
|
3924 | setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);
|
3925 | }
|
3926 | {
|
3927 | initDev();
|
3928 | }
|
3929 |
|
3930 | export { I18nInjectionKey, VERSION, createI18n, useI18n };
|