@intlify/core 10.0.0-beta.6 → 10.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * core v10.0.0-beta.6
2
+ * core v10.0.0-rc.1
3
3
  * (c) 2024 kazuya kawaguchi
4
4
  * Released under the MIT License.
5
5
  */
@@ -208,402 +208,102 @@ function createCompileError(code, loc, options = {}) {
208
208
  return error;
209
209
  }
210
210
 
211
- const pathStateMachine = [];
212
- pathStateMachine[0 /* States.BEFORE_PATH */] = {
213
- ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
214
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
215
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
216
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
217
- };
218
- pathStateMachine[1 /* States.IN_PATH */] = {
219
- ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
220
- ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
221
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
222
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
223
- };
224
- pathStateMachine[2 /* States.BEFORE_IDENT */] = {
225
- ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
226
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
227
- ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
228
- };
229
- pathStateMachine[3 /* States.IN_IDENT */] = {
230
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
231
- ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
232
- ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
233
- ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
234
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
235
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
236
- };
237
- pathStateMachine[4 /* States.IN_SUB_PATH */] = {
238
- ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
239
- ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
240
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [
241
- 4 /* States.IN_SUB_PATH */,
242
- 2 /* Actions.INC_SUB_PATH_DEPTH */
243
- ],
244
- ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
245
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
246
- ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
247
- };
248
- pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
249
- ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
250
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
251
- ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
252
- };
253
- pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
254
- ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
255
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
256
- ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
257
- };
258
- /**
259
- * Check if an expression is a literal value.
260
- */
261
- const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
262
- function isLiteral(exp) {
263
- return literalValueRE.test(exp);
264
- }
265
- /**
266
- * Strip quotes from a string
267
- */
268
- function stripQuotes(str) {
269
- const a = str.charCodeAt(0);
270
- const b = str.charCodeAt(str.length - 1);
271
- return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
211
+ function format(ast) {
212
+ const msg = (ctx) => formatParts(ctx, ast);
213
+ return msg;
272
214
  }
273
- /**
274
- * Determine the type of a character in a keypath.
275
- */
276
- function getPathCharType(ch) {
277
- if (ch === undefined || ch === null) {
278
- return "o" /* PathCharTypes.END_OF_FAIL */;
215
+ function formatParts(ctx, ast) {
216
+ const body = ast.b || ast.body;
217
+ if ((body.t || body.type) === 1 /* NodeTypes.Plural */) {
218
+ const plural = body;
219
+ const cases = plural.c || plural.cases;
220
+ return ctx.plural(cases.reduce((messages, c) => [
221
+ ...messages,
222
+ formatMessageParts(ctx, c)
223
+ ], []));
279
224
  }
280
- const code = ch.charCodeAt(0);
281
- switch (code) {
282
- case 0x5b: // [
283
- case 0x5d: // ]
284
- case 0x2e: // .
285
- case 0x22: // "
286
- case 0x27: // '
287
- return ch;
288
- case 0x5f: // _
289
- case 0x24: // $
290
- case 0x2d: // -
291
- return "i" /* PathCharTypes.IDENT */;
292
- case 0x09: // Tab (HT)
293
- case 0x0a: // Newline (LF)
294
- case 0x0d: // Return (CR)
295
- case 0xa0: // No-break space (NBSP)
296
- case 0xfeff: // Byte Order Mark (BOM)
297
- case 0x2028: // Line Separator (LS)
298
- case 0x2029: // Paragraph Separator (PS)
299
- return "w" /* PathCharTypes.WORKSPACE */;
225
+ else {
226
+ return formatMessageParts(ctx, body);
300
227
  }
301
- return "i" /* PathCharTypes.IDENT */;
302
228
  }
303
- /**
304
- * Format a subPath, return its plain form if it is
305
- * a literal string or number. Otherwise prepend the
306
- * dynamic indicator (*).
307
- */
308
- function formatSubPath(path) {
309
- const trimmed = path.trim();
310
- // invalid leading 0
311
- if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
312
- return false;
229
+ function formatMessageParts(ctx, node) {
230
+ const _static = node.s || node.static;
231
+ if (_static) {
232
+ return ctx.type === 'text'
233
+ ? _static
234
+ : ctx.normalize([_static]);
235
+ }
236
+ else {
237
+ const messages = (node.i || node.items).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
238
+ return ctx.normalize(messages);
313
239
  }
314
- return isLiteral(trimmed)
315
- ? stripQuotes(trimmed)
316
- : "*" /* PathCharTypes.ASTARISK */ + trimmed;
317
240
  }
318
- /**
319
- * Parse a string path into an array of segments
320
- */
321
- function parse(path) {
322
- const keys = [];
323
- let index = -1;
324
- let mode = 0 /* States.BEFORE_PATH */;
325
- let subPathDepth = 0;
326
- let c;
327
- let key; // eslint-disable-line
328
- let newChar;
329
- let type;
330
- let transition;
331
- let action;
332
- let typeMap;
333
- const actions = [];
334
- actions[0 /* Actions.APPEND */] = () => {
335
- if (key === undefined) {
336
- key = newChar;
241
+ function formatMessagePart(ctx, node) {
242
+ const type = node.t || node.type;
243
+ switch (type) {
244
+ case 3 /* NodeTypes.Text */: {
245
+ const text = node;
246
+ return (text.v || text.value);
337
247
  }
338
- else {
339
- key += newChar;
248
+ case 9 /* NodeTypes.Literal */: {
249
+ const literal = node;
250
+ return (literal.v || literal.value);
340
251
  }
341
- };
342
- actions[1 /* Actions.PUSH */] = () => {
343
- if (key !== undefined) {
344
- keys.push(key);
345
- key = undefined;
252
+ case 4 /* NodeTypes.Named */: {
253
+ const named = node;
254
+ return ctx.interpolate(ctx.named(named.k || named.key));
346
255
  }
347
- };
348
- actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
349
- actions[0 /* Actions.APPEND */]();
350
- subPathDepth++;
351
- };
352
- actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
353
- if (subPathDepth > 0) {
354
- subPathDepth--;
355
- mode = 4 /* States.IN_SUB_PATH */;
356
- actions[0 /* Actions.APPEND */]();
256
+ case 5 /* NodeTypes.List */: {
257
+ const list = node;
258
+ return ctx.interpolate(ctx.list(list.i != null ? list.i : list.index));
357
259
  }
358
- else {
359
- subPathDepth = 0;
360
- if (key === undefined) {
361
- return false;
362
- }
363
- key = formatSubPath(key);
364
- if (key === false) {
365
- return false;
366
- }
367
- else {
368
- actions[1 /* Actions.PUSH */]();
369
- }
260
+ case 6 /* NodeTypes.Linked */: {
261
+ const linked = node;
262
+ const modifier = linked.m || linked.modifier;
263
+ return ctx.linked(formatMessagePart(ctx, linked.k || linked.key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);
370
264
  }
371
- };
372
- function maybeUnescapeQuote() {
373
- const nextChar = path[index + 1];
374
- if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
375
- nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
376
- (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
377
- nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
378
- index++;
379
- newChar = '\\' + nextChar;
380
- actions[0 /* Actions.APPEND */]();
381
- return true;
265
+ case 7 /* NodeTypes.LinkedKey */: {
266
+ const linkedKey = node;
267
+ return (linkedKey.v || linkedKey.value);
382
268
  }
383
- }
384
- while (mode !== null) {
385
- index++;
386
- c = path[index];
387
- if (c === '\\' && maybeUnescapeQuote()) {
388
- continue;
269
+ case 8 /* NodeTypes.LinkedModifier */: {
270
+ const linkedModifier = node;
271
+ return (linkedModifier.v || linkedModifier.value);
389
272
  }
390
- type = getPathCharType(c);
391
- typeMap = pathStateMachine[mode];
392
- transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
393
- // check parse error
394
- if (transition === 8 /* States.ERROR */) {
395
- return;
273
+ default:
274
+ throw new Error(`unhandled node type on format message part: ${type}`);
275
+ }
276
+ }
277
+
278
+ let compileCache = Object.create(null);
279
+ function clearCompileCache() {
280
+ compileCache = Object.create(null);
281
+ }
282
+ const isMessageAST = (val) => isObject(val) &&
283
+ (val.t === 0 || val.type === 0) &&
284
+ ('b' in val || 'body' in val);
285
+ /* #__NO_SIDE_EFFECTS__ */
286
+ function compile(message, context) {
287
+ {
288
+ if (!isMessageAST(message)) {
289
+ warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);
290
+ return (() => message);
396
291
  }
397
- mode = transition[0];
398
- if (transition[1] !== undefined) {
399
- action = actions[transition[1]];
400
- if (action) {
401
- newChar = c;
402
- if (action() === false) {
403
- return;
404
- }
292
+ // AST case (passed from bundler)
293
+ const cacheKey = message.cacheKey;
294
+ if (cacheKey) {
295
+ const cached = compileCache[cacheKey];
296
+ if (cached) {
297
+ return cached;
405
298
  }
299
+ // compose message function from message (AST)
300
+ return (compileCache[cacheKey] =
301
+ format(message));
406
302
  }
407
- // check parse finish
408
- if (mode === 7 /* States.AFTER_PATH */) {
409
- return keys;
410
- }
411
- }
412
- }
413
- // path token cache
414
- const cache = new Map();
415
- /**
416
- * key-value message resolver
417
- *
418
- * @remarks
419
- * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
420
- *
421
- * @param obj - A target object to be resolved with path
422
- * @param path - A {@link Path | path} to resolve the value of message
423
- *
424
- * @returns A resolved {@link PathValue | path value}
425
- *
426
- * @VueI18nGeneral
427
- */
428
- function resolveWithKeyValue(obj, path) {
429
- return isObject(obj) ? obj[path] : null;
430
- }
431
- /**
432
- * message resolver
433
- *
434
- * @remarks
435
- * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
436
- *
437
- * @param obj - A target object to be resolved with path
438
- * @param path - A {@link Path | path} to resolve the value of message
439
- *
440
- * @returns A resolved {@link PathValue | path value}
441
- *
442
- * @VueI18nGeneral
443
- */
444
- function resolveValue(obj, path) {
445
- // check object
446
- if (!isObject(obj)) {
447
- return null;
448
- }
449
- // parse path
450
- let hit = cache.get(path);
451
- if (!hit) {
452
- hit = parse(path);
453
- if (hit) {
454
- cache.set(path, hit);
455
- }
456
- }
457
- // check hit
458
- if (!hit) {
459
- return null;
460
- }
461
- // resolve path value
462
- const len = hit.length;
463
- let last = obj;
464
- let i = 0;
465
- while (i < len) {
466
- const val = last[hit[i]];
467
- if (val === undefined) {
468
- return null;
469
- }
470
- if (isFunction(last)) {
471
- return null;
303
+ else {
304
+ return format(message);
472
305
  }
473
- last = val;
474
- i++;
475
- }
476
- return last;
477
- }
478
-
479
- const DEFAULT_MODIFIER = (str) => str;
480
- const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
481
- const DEFAULT_MESSAGE_DATA_TYPE = 'text';
482
- const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);
483
- const DEFAULT_INTERPOLATE = toDisplayString;
484
- function pluralDefault(choice, choicesLength) {
485
- choice = Math.abs(choice);
486
- if (choicesLength === 2) {
487
- // prettier-ignore
488
- return choice
489
- ? choice > 1
490
- ? 1
491
- : 0
492
- : 1;
493
- }
494
- return choice ? Math.min(choice, 2) : 0;
495
- }
496
- function getPluralIndex(options) {
497
- // prettier-ignore
498
- const index = isNumber(options.pluralIndex)
499
- ? options.pluralIndex
500
- : -1;
501
- // prettier-ignore
502
- return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
503
- ? isNumber(options.named.count)
504
- ? options.named.count
505
- : isNumber(options.named.n)
506
- ? options.named.n
507
- : index
508
- : index;
509
- }
510
- function normalizeNamed(pluralIndex, props) {
511
- if (!props.count) {
512
- props.count = pluralIndex;
513
- }
514
- if (!props.n) {
515
- props.n = pluralIndex;
516
- }
517
- }
518
- function createMessageContext(options = {}) {
519
- const locale = options.locale;
520
- const pluralIndex = getPluralIndex(options);
521
- const pluralRule = isObject(options.pluralRules) &&
522
- isString(locale) &&
523
- isFunction(options.pluralRules[locale])
524
- ? options.pluralRules[locale]
525
- : pluralDefault;
526
- const orgPluralRule = isObject(options.pluralRules) &&
527
- isString(locale) &&
528
- isFunction(options.pluralRules[locale])
529
- ? pluralDefault
530
- : undefined;
531
- const plural = (messages) => {
532
- return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
533
- };
534
- const _list = options.list || [];
535
- const list = (index) => _list[index];
536
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
537
- const _named = options.named || {};
538
- isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
539
- const named = (key) => _named[key];
540
- function message(key, useLinked) {
541
- // prettier-ignore
542
- const msg = isFunction(options.messages)
543
- ? options.messages(key, !!useLinked)
544
- : isObject(options.messages)
545
- ? options.messages[key]
546
- : false;
547
- return !msg
548
- ? options.parent
549
- ? options.parent.message(key) // resolve from parent messages
550
- : DEFAULT_MESSAGE
551
- : msg;
552
306
  }
553
- const _modifier = (name) => options.modifiers
554
- ? options.modifiers[name]
555
- : DEFAULT_MODIFIER;
556
- const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
557
- ? options.processor.normalize
558
- : DEFAULT_NORMALIZE;
559
- const interpolate = isPlainObject(options.processor) &&
560
- isFunction(options.processor.interpolate)
561
- ? options.processor.interpolate
562
- : DEFAULT_INTERPOLATE;
563
- const type = isPlainObject(options.processor) && isString(options.processor.type)
564
- ? options.processor.type
565
- : DEFAULT_MESSAGE_DATA_TYPE;
566
- const linked = (key, ...args) => {
567
- const [arg1, arg2] = args;
568
- let type = 'text';
569
- let modifier = '';
570
- if (args.length === 1) {
571
- if (isObject(arg1)) {
572
- modifier = arg1.modifier || modifier;
573
- type = arg1.type || type;
574
- }
575
- else if (isString(arg1)) {
576
- modifier = arg1 || modifier;
577
- }
578
- }
579
- else if (args.length === 2) {
580
- if (isString(arg1)) {
581
- modifier = arg1 || modifier;
582
- }
583
- if (isString(arg2)) {
584
- type = arg2 || type;
585
- }
586
- }
587
- const ret = message(key, true)(ctx);
588
- const msg =
589
- // The message in vnode resolved with linked are returned as an array by processor.nomalize
590
- type === 'vnode' && isArray(ret) && modifier
591
- ? ret[0]
592
- : ret;
593
- return modifier ? _modifier(modifier)(msg, type) : msg;
594
- };
595
- const ctx = {
596
- ["list" /* HelperNameMap.LIST */]: list,
597
- ["named" /* HelperNameMap.NAMED */]: named,
598
- ["plural" /* HelperNameMap.PLURAL */]: plural,
599
- ["linked" /* HelperNameMap.LINKED */]: linked,
600
- ["message" /* HelperNameMap.MESSAGE */]: message,
601
- ["type" /* HelperNameMap.TYPE */]: type,
602
- ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
603
- ["normalize" /* HelperNameMap.NORMALIZE */]: normalize,
604
- ["values" /* HelperNameMap.VALUES */]: assign({}, _list, _named)
605
- };
606
- return ctx;
607
307
  }
608
308
 
609
309
  let devtools = null;
@@ -629,30 +329,6 @@ function createDevToolsHook(hook) {
629
329
  return (payloads) => devtools && devtools.emit(hook, payloads);
630
330
  }
631
331
 
632
- const CoreWarnCodes = {
633
- NOT_FOUND_KEY: 1,
634
- FALLBACK_TO_TRANSLATE: 2,
635
- CANNOT_FORMAT_NUMBER: 3,
636
- FALLBACK_TO_NUMBER_FORMAT: 4,
637
- CANNOT_FORMAT_DATE: 5,
638
- FALLBACK_TO_DATE_FORMAT: 6,
639
- EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: 7
640
- };
641
- const CORE_WARN_CODES_EXTEND_POINT = 8;
642
- /** @internal */
643
- const warnMessages = {
644
- [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
645
- [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
646
- [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
647
- [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
648
- [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
649
- [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
650
- [CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER]: `This project is using Custom Message Compiler, which is an experimental feature. It may receive breaking changes or be removed in the future.`
651
- };
652
- function getWarnMessage(code, ...args) {
653
- return format$1(warnMessages[code], ...args);
654
- }
655
-
656
332
  const CoreErrorCodes = {
657
333
  INVALID_ARGUMENT: COMPILE_ERROR_CODES_EXTEND_POINT, // 17
658
334
  INVALID_DATE_ARGUMENT: 18,
@@ -826,39 +502,331 @@ function appendItemToChain(chain, target, blocks) {
826
502
  return follow;
827
503
  }
828
504
 
829
- /* eslint-disable @typescript-eslint/no-explicit-any */
830
- /**
831
- * Intlify core-base version
832
- * @internal
833
- */
834
- const VERSION = '10.0.0-beta.6';
835
- const NOT_REOSLVED = -1;
836
- const DEFAULT_LOCALE = 'en-US';
837
- const MISSING_RESOLVE_VALUE = '';
838
- const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
839
- function getDefaultLinkedModifiers() {
840
- return {
841
- upper: (val, type) => {
842
- // prettier-ignore
843
- return type === 'text' && isString(val)
844
- ? val.toUpperCase()
845
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
846
- ? val.children.toUpperCase()
847
- : val;
848
- },
849
- lower: (val, type) => {
850
- // prettier-ignore
851
- return type === 'text' && isString(val)
852
- ? val.toLowerCase()
853
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
854
- ? val.children.toLowerCase()
855
- : val;
856
- },
857
- capitalize: (val, type) => {
858
- // prettier-ignore
859
- return (type === 'text' && isString(val)
860
- ? capitalize(val)
861
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
505
+ const pathStateMachine = [];
506
+ pathStateMachine[0 /* States.BEFORE_PATH */] = {
507
+ ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
508
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
509
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
510
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
511
+ };
512
+ pathStateMachine[1 /* States.IN_PATH */] = {
513
+ ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
514
+ ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
515
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
516
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
517
+ };
518
+ pathStateMachine[2 /* States.BEFORE_IDENT */] = {
519
+ ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
520
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
521
+ ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
522
+ };
523
+ pathStateMachine[3 /* States.IN_IDENT */] = {
524
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
525
+ ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
526
+ ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
527
+ ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
528
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
529
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
530
+ };
531
+ pathStateMachine[4 /* States.IN_SUB_PATH */] = {
532
+ ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
533
+ ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
534
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [
535
+ 4 /* States.IN_SUB_PATH */,
536
+ 2 /* Actions.INC_SUB_PATH_DEPTH */
537
+ ],
538
+ ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
539
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
540
+ ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
541
+ };
542
+ pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
543
+ ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
544
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
545
+ ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
546
+ };
547
+ pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
548
+ ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
549
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
550
+ ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
551
+ };
552
+ /**
553
+ * Check if an expression is a literal value.
554
+ */
555
+ const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
556
+ function isLiteral(exp) {
557
+ return literalValueRE.test(exp);
558
+ }
559
+ /**
560
+ * Strip quotes from a string
561
+ */
562
+ function stripQuotes(str) {
563
+ const a = str.charCodeAt(0);
564
+ const b = str.charCodeAt(str.length - 1);
565
+ return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
566
+ }
567
+ /**
568
+ * Determine the type of a character in a keypath.
569
+ */
570
+ function getPathCharType(ch) {
571
+ if (ch === undefined || ch === null) {
572
+ return "o" /* PathCharTypes.END_OF_FAIL */;
573
+ }
574
+ const code = ch.charCodeAt(0);
575
+ switch (code) {
576
+ case 0x5b: // [
577
+ case 0x5d: // ]
578
+ case 0x2e: // .
579
+ case 0x22: // "
580
+ case 0x27: // '
581
+ return ch;
582
+ case 0x5f: // _
583
+ case 0x24: // $
584
+ case 0x2d: // -
585
+ return "i" /* PathCharTypes.IDENT */;
586
+ case 0x09: // Tab (HT)
587
+ case 0x0a: // Newline (LF)
588
+ case 0x0d: // Return (CR)
589
+ case 0xa0: // No-break space (NBSP)
590
+ case 0xfeff: // Byte Order Mark (BOM)
591
+ case 0x2028: // Line Separator (LS)
592
+ case 0x2029: // Paragraph Separator (PS)
593
+ return "w" /* PathCharTypes.WORKSPACE */;
594
+ }
595
+ return "i" /* PathCharTypes.IDENT */;
596
+ }
597
+ /**
598
+ * Format a subPath, return its plain form if it is
599
+ * a literal string or number. Otherwise prepend the
600
+ * dynamic indicator (*).
601
+ */
602
+ function formatSubPath(path) {
603
+ const trimmed = path.trim();
604
+ // invalid leading 0
605
+ if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
606
+ return false;
607
+ }
608
+ return isLiteral(trimmed)
609
+ ? stripQuotes(trimmed)
610
+ : "*" /* PathCharTypes.ASTARISK */ + trimmed;
611
+ }
612
+ /**
613
+ * Parse a string path into an array of segments
614
+ */
615
+ function parse(path) {
616
+ const keys = [];
617
+ let index = -1;
618
+ let mode = 0 /* States.BEFORE_PATH */;
619
+ let subPathDepth = 0;
620
+ let c;
621
+ let key; // eslint-disable-line
622
+ let newChar;
623
+ let type;
624
+ let transition;
625
+ let action;
626
+ let typeMap;
627
+ const actions = [];
628
+ actions[0 /* Actions.APPEND */] = () => {
629
+ if (key === undefined) {
630
+ key = newChar;
631
+ }
632
+ else {
633
+ key += newChar;
634
+ }
635
+ };
636
+ actions[1 /* Actions.PUSH */] = () => {
637
+ if (key !== undefined) {
638
+ keys.push(key);
639
+ key = undefined;
640
+ }
641
+ };
642
+ actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
643
+ actions[0 /* Actions.APPEND */]();
644
+ subPathDepth++;
645
+ };
646
+ actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
647
+ if (subPathDepth > 0) {
648
+ subPathDepth--;
649
+ mode = 4 /* States.IN_SUB_PATH */;
650
+ actions[0 /* Actions.APPEND */]();
651
+ }
652
+ else {
653
+ subPathDepth = 0;
654
+ if (key === undefined) {
655
+ return false;
656
+ }
657
+ key = formatSubPath(key);
658
+ if (key === false) {
659
+ return false;
660
+ }
661
+ else {
662
+ actions[1 /* Actions.PUSH */]();
663
+ }
664
+ }
665
+ };
666
+ function maybeUnescapeQuote() {
667
+ const nextChar = path[index + 1];
668
+ if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
669
+ nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
670
+ (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
671
+ nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
672
+ index++;
673
+ newChar = '\\' + nextChar;
674
+ actions[0 /* Actions.APPEND */]();
675
+ return true;
676
+ }
677
+ }
678
+ while (mode !== null) {
679
+ index++;
680
+ c = path[index];
681
+ if (c === '\\' && maybeUnescapeQuote()) {
682
+ continue;
683
+ }
684
+ type = getPathCharType(c);
685
+ typeMap = pathStateMachine[mode];
686
+ transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
687
+ // check parse error
688
+ if (transition === 8 /* States.ERROR */) {
689
+ return;
690
+ }
691
+ mode = transition[0];
692
+ if (transition[1] !== undefined) {
693
+ action = actions[transition[1]];
694
+ if (action) {
695
+ newChar = c;
696
+ if (action() === false) {
697
+ return;
698
+ }
699
+ }
700
+ }
701
+ // check parse finish
702
+ if (mode === 7 /* States.AFTER_PATH */) {
703
+ return keys;
704
+ }
705
+ }
706
+ }
707
+ // path token cache
708
+ const cache = new Map();
709
+ /**
710
+ * key-value message resolver
711
+ *
712
+ * @remarks
713
+ * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
714
+ *
715
+ * @param obj - A target object to be resolved with path
716
+ * @param path - A {@link Path | path} to resolve the value of message
717
+ *
718
+ * @returns A resolved {@link PathValue | path value}
719
+ *
720
+ * @VueI18nGeneral
721
+ */
722
+ function resolveWithKeyValue(obj, path) {
723
+ return isObject(obj) ? obj[path] : null;
724
+ }
725
+ /**
726
+ * message resolver
727
+ *
728
+ * @remarks
729
+ * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
730
+ *
731
+ * @param obj - A target object to be resolved with path
732
+ * @param path - A {@link Path | path} to resolve the value of message
733
+ *
734
+ * @returns A resolved {@link PathValue | path value}
735
+ *
736
+ * @VueI18nGeneral
737
+ */
738
+ function resolveValue(obj, path) {
739
+ // check object
740
+ if (!isObject(obj)) {
741
+ return null;
742
+ }
743
+ // parse path
744
+ let hit = cache.get(path);
745
+ if (!hit) {
746
+ hit = parse(path);
747
+ if (hit) {
748
+ cache.set(path, hit);
749
+ }
750
+ }
751
+ // check hit
752
+ if (!hit) {
753
+ return null;
754
+ }
755
+ // resolve path value
756
+ const len = hit.length;
757
+ let last = obj;
758
+ let i = 0;
759
+ while (i < len) {
760
+ const val = last[hit[i]];
761
+ if (val === undefined) {
762
+ return null;
763
+ }
764
+ if (isFunction(last)) {
765
+ return null;
766
+ }
767
+ last = val;
768
+ i++;
769
+ }
770
+ return last;
771
+ }
772
+
773
+ const CoreWarnCodes = {
774
+ NOT_FOUND_KEY: 1,
775
+ FALLBACK_TO_TRANSLATE: 2,
776
+ CANNOT_FORMAT_NUMBER: 3,
777
+ FALLBACK_TO_NUMBER_FORMAT: 4,
778
+ CANNOT_FORMAT_DATE: 5,
779
+ FALLBACK_TO_DATE_FORMAT: 6,
780
+ EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: 7
781
+ };
782
+ const CORE_WARN_CODES_EXTEND_POINT = 8;
783
+ /** @internal */
784
+ const warnMessages = {
785
+ [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
786
+ [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
787
+ [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
788
+ [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
789
+ [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
790
+ [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
791
+ [CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER]: `This project is using Custom Message Compiler, which is an experimental feature. It may receive breaking changes or be removed in the future.`
792
+ };
793
+ function getWarnMessage(code, ...args) {
794
+ return format$1(warnMessages[code], ...args);
795
+ }
796
+
797
+ /* eslint-disable @typescript-eslint/no-explicit-any */
798
+ /**
799
+ * Intlify core-base version
800
+ * @internal
801
+ */
802
+ const VERSION = '10.0.0-rc.1';
803
+ const NOT_REOSLVED = -1;
804
+ const DEFAULT_LOCALE = 'en-US';
805
+ const MISSING_RESOLVE_VALUE = '';
806
+ const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
807
+ function getDefaultLinkedModifiers() {
808
+ return {
809
+ upper: (val, type) => {
810
+ // prettier-ignore
811
+ return type === 'text' && isString(val)
812
+ ? val.toUpperCase()
813
+ : type === 'vnode' && isObject(val) && '__v_isVNode' in val
814
+ ? val.children.toUpperCase()
815
+ : val;
816
+ },
817
+ lower: (val, type) => {
818
+ // prettier-ignore
819
+ return type === 'text' && isString(val)
820
+ ? val.toLowerCase()
821
+ : type === 'vnode' && isObject(val) && '__v_isVNode' in val
822
+ ? val.children.toLowerCase()
823
+ : val;
824
+ },
825
+ capitalize: (val, type) => {
826
+ // prettier-ignore
827
+ return (type === 'text' && isString(val)
828
+ ? capitalize(val)
829
+ : type === 'vnode' && isObject(val) && '__v_isVNode' in val
862
830
  ? capitalize(val.children)
863
831
  : val);
864
832
  }
@@ -1006,608 +974,269 @@ function createCoreContext(options = {}) {
1006
974
  context.__datetimeFormatters = __datetimeFormatters;
1007
975
  context.__numberFormatters = __numberFormatters;
1008
976
  }
1009
- // for vue-devtools timeline event
1010
- {
1011
- context.__v_emitter =
1012
- internalOptions.__v_emitter != null
1013
- ? internalOptions.__v_emitter
1014
- : undefined;
1015
- }
1016
- // NOTE: experimental !!
1017
- {
1018
- initI18nDevTools(context, version, __meta);
1019
- }
1020
- return context;
1021
- }
1022
- /** @internal */
1023
- function isTranslateFallbackWarn(fallback, key) {
1024
- return fallback instanceof RegExp ? fallback.test(key) : fallback;
1025
- }
1026
- /** @internal */
1027
- function isTranslateMissingWarn(missing, key) {
1028
- return missing instanceof RegExp ? missing.test(key) : missing;
1029
- }
1030
- /** @internal */
1031
- function handleMissing(context, key, locale, missingWarn, type) {
1032
- const { missing, onWarn } = context;
1033
- // for vue-devtools timeline event
1034
- {
1035
- const emitter = context.__v_emitter;
1036
- if (emitter) {
1037
- emitter.emit('missing', {
1038
- locale,
1039
- key,
1040
- type,
1041
- groupId: `${type}:${key}`
1042
- });
1043
- }
1044
- }
1045
- if (missing !== null) {
1046
- const ret = missing(context, locale, key, type);
1047
- return isString(ret) ? ret : key;
1048
- }
1049
- else {
1050
- if (isTranslateMissingWarn(missingWarn, key)) {
1051
- onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
1052
- }
1053
- return key;
1054
- }
1055
- }
1056
- /** @internal */
1057
- function updateFallbackLocale(ctx, locale, fallback) {
1058
- const context = ctx;
1059
- context.__localeChainCache = new Map();
1060
- ctx.localeFallbacker(ctx, fallback, locale);
1061
- }
1062
- /** @internal */
1063
- function isAlmostSameLocale(locale, compareLocale) {
1064
- if (locale === compareLocale)
1065
- return false;
1066
- return locale.split('-')[0] === compareLocale.split('-')[0];
1067
- }
1068
- /** @internal */
1069
- function isImplicitFallback(targetLocale, locales) {
1070
- const index = locales.indexOf(targetLocale);
1071
- if (index === -1) {
1072
- return false;
1073
- }
1074
- for (let i = index + 1; i < locales.length; i++) {
1075
- if (isAlmostSameLocale(targetLocale, locales[i])) {
1076
- return true;
1077
- }
1078
- }
1079
- return false;
1080
- }
1081
- /* eslint-enable @typescript-eslint/no-explicit-any */
1082
-
1083
- function format(ast) {
1084
- const msg = (ctx) => formatParts(ctx, ast);
1085
- return msg;
1086
- }
1087
- function formatParts(ctx, ast) {
1088
- const body = ast.b || ast.body;
1089
- if ((body.t || body.type) === 1 /* NodeTypes.Plural */) {
1090
- const plural = body;
1091
- const cases = plural.c || plural.cases;
1092
- return ctx.plural(cases.reduce((messages, c) => [
1093
- ...messages,
1094
- formatMessageParts(ctx, c)
1095
- ], []));
1096
- }
1097
- else {
1098
- return formatMessageParts(ctx, body);
1099
- }
1100
- }
1101
- function formatMessageParts(ctx, node) {
1102
- const _static = node.s || node.static;
1103
- if (_static) {
1104
- return ctx.type === 'text'
1105
- ? _static
1106
- : ctx.normalize([_static]);
1107
- }
1108
- else {
1109
- const messages = (node.i || node.items).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
1110
- return ctx.normalize(messages);
1111
- }
1112
- }
1113
- function formatMessagePart(ctx, node) {
1114
- const type = node.t || node.type;
1115
- switch (type) {
1116
- case 3 /* NodeTypes.Text */: {
1117
- const text = node;
1118
- return (text.v || text.value);
1119
- }
1120
- case 9 /* NodeTypes.Literal */: {
1121
- const literal = node;
1122
- return (literal.v || literal.value);
1123
- }
1124
- case 4 /* NodeTypes.Named */: {
1125
- const named = node;
1126
- return ctx.interpolate(ctx.named(named.k || named.key));
1127
- }
1128
- case 5 /* NodeTypes.List */: {
1129
- const list = node;
1130
- return ctx.interpolate(ctx.list(list.i != null ? list.i : list.index));
1131
- }
1132
- case 6 /* NodeTypes.Linked */: {
1133
- const linked = node;
1134
- const modifier = linked.m || linked.modifier;
1135
- return ctx.linked(formatMessagePart(ctx, linked.k || linked.key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);
1136
- }
1137
- case 7 /* NodeTypes.LinkedKey */: {
1138
- const linkedKey = node;
1139
- return (linkedKey.v || linkedKey.value);
1140
- }
1141
- case 8 /* NodeTypes.LinkedModifier */: {
1142
- const linkedModifier = node;
1143
- return (linkedModifier.v || linkedModifier.value);
1144
- }
1145
- default:
1146
- throw new Error(`unhandled node type on format message part: ${type}`);
1147
- }
1148
- }
1149
-
1150
- let compileCache = Object.create(null);
1151
- function clearCompileCache() {
1152
- compileCache = Object.create(null);
1153
- }
1154
- const isMessageAST = (val) => isObject(val) &&
1155
- (val.t === 0 || val.type === 0) &&
1156
- ('b' in val || 'body' in val);
1157
- /* #__NO_SIDE_EFFECTS__ */
1158
- function compile(message, context) {
1159
- {
1160
- if (!isMessageAST(message)) {
1161
- warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);
1162
- return (() => message);
1163
- }
1164
- // AST case (passed from bundler)
1165
- const cacheKey = message.cacheKey;
1166
- if (cacheKey) {
1167
- const cached = compileCache[cacheKey];
1168
- if (cached) {
1169
- return cached;
1170
- }
1171
- // compose message function from message (AST)
1172
- return (compileCache[cacheKey] =
1173
- format(message));
1174
- }
1175
- else {
1176
- return format(message);
1177
- }
1178
- }
1179
- }
1180
-
1181
- const NOOP_MESSAGE_FUNCTION = () => '';
1182
- const isMessageFunction = (val) => isFunction(val);
1183
- // implementation of `translate` function
1184
- function translate(context, ...args) {
1185
- const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
1186
- const [key, options] = parseTranslateArgs(...args);
1187
- const missingWarn = isBoolean(options.missingWarn)
1188
- ? options.missingWarn
1189
- : context.missingWarn;
1190
- const fallbackWarn = isBoolean(options.fallbackWarn)
1191
- ? options.fallbackWarn
1192
- : context.fallbackWarn;
1193
- const escapeParameter = isBoolean(options.escapeParameter)
1194
- ? options.escapeParameter
1195
- : context.escapeParameter;
1196
- const resolvedMessage = !!options.resolvedMessage;
1197
- // prettier-ignore
1198
- const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
1199
- ? !isBoolean(options.default)
1200
- ? options.default
1201
- : (!messageCompiler ? () => key : key)
1202
- : fallbackFormat // default by `fallbackFormat` option
1203
- ? (!messageCompiler ? () => key : key)
1204
- : null;
1205
- const enableDefaultMsg = fallbackFormat ||
1206
- (defaultMsgOrKey != null &&
1207
- (isString(defaultMsgOrKey) || isFunction(defaultMsgOrKey)));
1208
- const locale = getLocale(context, options);
1209
- // escape params
1210
- escapeParameter && escapeParams(options);
1211
- // resolve message format
1212
- // eslint-disable-next-line prefer-const
1213
- let [formatScope, targetLocale, message] = !resolvedMessage
1214
- ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
1215
- : [
1216
- key,
1217
- locale,
1218
- messages[locale] || {}
1219
- ];
1220
- // NOTE:
1221
- // Fix to work around `ssrTransfrom` bug in Vite.
1222
- // https://github.com/vitejs/vite/issues/4306
1223
- // To get around this, use temporary variables.
1224
- // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
1225
- let format = formatScope;
1226
- // if you use default message, set it as message format!
1227
- let cacheBaseKey = key;
1228
- if (!resolvedMessage &&
1229
- !(isString(format) ||
1230
- isMessageAST(format) ||
1231
- isMessageFunction(format))) {
1232
- if (enableDefaultMsg) {
1233
- format = defaultMsgOrKey;
1234
- cacheBaseKey = format;
1235
- }
1236
- }
1237
- // checking message format and target locale
1238
- if (!resolvedMessage &&
1239
- (!(isString(format) ||
1240
- isMessageAST(format) ||
1241
- isMessageFunction(format)) ||
1242
- !isString(targetLocale))) {
1243
- return unresolving ? NOT_REOSLVED : key;
1244
- }
1245
- // TODO: refactor
1246
- if (isString(format) && context.messageCompiler == null) {
1247
- warn(`The message format compilation is not supported in this build. ` +
1248
- `Because message compiler isn't included. ` +
1249
- `You need to pre-compilation all message format. ` +
1250
- `So translate function return '${key}'.`);
1251
- return key;
1252
- }
1253
- // setup compile error detecting
1254
- let occurred = false;
1255
- const onError = () => {
1256
- occurred = true;
1257
- };
1258
- // compile message format
1259
- const msg = !isMessageFunction(format)
1260
- ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
1261
- : format;
1262
- // if occurred compile error, return the message format
1263
- if (occurred) {
1264
- return format;
977
+ // for vue-devtools timeline event
978
+ {
979
+ context.__v_emitter =
980
+ internalOptions.__v_emitter != null
981
+ ? internalOptions.__v_emitter
982
+ : undefined;
1265
983
  }
1266
- // evaluate message with context
1267
- const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
1268
- const msgContext = createMessageContext(ctxOptions);
1269
- const messaged = evaluateMessage(context, msg, msgContext);
1270
- // if use post translation option, proceed it with handler
1271
- const ret = postTranslation
1272
- ? postTranslation(messaged, key)
1273
- : messaged;
1274
984
  // NOTE: experimental !!
1275
985
  {
1276
- // prettier-ignore
1277
- const payloads = {
1278
- timestamp: Date.now(),
1279
- key: isString(key)
1280
- ? key
1281
- : isMessageFunction(format)
1282
- ? format.key
1283
- : '',
1284
- locale: targetLocale || (isMessageFunction(format)
1285
- ? format.locale
1286
- : ''),
1287
- format: isString(format)
1288
- ? format
1289
- : isMessageFunction(format)
1290
- ? format.source
1291
- : '',
1292
- message: ret
1293
- };
1294
- payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
1295
- translateDevTools(payloads);
986
+ initI18nDevTools(context, version, __meta);
1296
987
  }
1297
- return ret;
988
+ return context;
1298
989
  }
1299
- function escapeParams(options) {
1300
- if (isArray(options.list)) {
1301
- options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
1302
- }
1303
- else if (isObject(options.named)) {
1304
- Object.keys(options.named).forEach(key => {
1305
- if (isString(options.named[key])) {
1306
- options.named[key] = escapeHtml(options.named[key]);
1307
- }
1308
- });
1309
- }
990
+ /** @internal */
991
+ function isTranslateFallbackWarn(fallback, key) {
992
+ return fallback instanceof RegExp ? fallback.test(key) : fallback;
1310
993
  }
1311
- function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
1312
- const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
1313
- const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
1314
- let message = {};
1315
- let targetLocale;
1316
- let format = null;
1317
- let from = locale;
1318
- let to = null;
1319
- const type = 'translate';
1320
- for (let i = 0; i < locales.length; i++) {
1321
- targetLocale = to = locales[i];
1322
- if (locale !== targetLocale &&
1323
- !isAlmostSameLocale(locale, targetLocale) &&
1324
- isTranslateFallbackWarn(fallbackWarn, key)) {
1325
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
994
+ /** @internal */
995
+ function isTranslateMissingWarn(missing, key) {
996
+ return missing instanceof RegExp ? missing.test(key) : missing;
997
+ }
998
+ /** @internal */
999
+ function handleMissing(context, key, locale, missingWarn, type) {
1000
+ const { missing, onWarn } = context;
1001
+ // for vue-devtools timeline event
1002
+ {
1003
+ const emitter = context.__v_emitter;
1004
+ if (emitter) {
1005
+ emitter.emit('missing', {
1006
+ locale,
1326
1007
  key,
1327
- target: targetLocale
1328
- }));
1329
- }
1330
- // for vue-devtools timeline event
1331
- if (locale !== targetLocale) {
1332
- const emitter = context.__v_emitter;
1333
- if (emitter) {
1334
- emitter.emit('fallback', {
1335
- type,
1336
- key,
1337
- from,
1338
- to,
1339
- groupId: `${type}:${key}`
1340
- });
1341
- }
1342
- }
1343
- message =
1344
- messages[targetLocale] || {};
1345
- // for vue-devtools timeline event
1346
- let start = null;
1347
- let startTag;
1348
- let endTag;
1349
- if (inBrowser) {
1350
- start = window.performance.now();
1351
- startTag = 'intlify-message-resolve-start';
1352
- endTag = 'intlify-message-resolve-end';
1353
- mark && mark(startTag);
1354
- }
1355
- if ((format = resolveValue(message, key)) === null) {
1356
- // if null, resolve with object key path
1357
- format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
1358
- }
1359
- // for vue-devtools timeline event
1360
- if (inBrowser) {
1361
- const end = window.performance.now();
1362
- const emitter = context.__v_emitter;
1363
- if (emitter && start && format) {
1364
- emitter.emit('message-resolve', {
1365
- type: 'message-resolve',
1366
- key,
1367
- message: format,
1368
- time: end - start,
1369
- groupId: `${type}:${key}`
1370
- });
1371
- }
1372
- if (startTag && endTag && mark && measure) {
1373
- mark(endTag);
1374
- measure('intlify message resolve', startTag, endTag);
1375
- }
1376
- }
1377
- if (isString(format) || isMessageAST(format) || isMessageFunction(format)) {
1378
- break;
1008
+ type,
1009
+ groupId: `${type}:${key}`
1010
+ });
1379
1011
  }
1380
- if (!isImplicitFallback(targetLocale, locales)) {
1381
- const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1382
- key, targetLocale, missingWarn, type);
1383
- if (missingRet !== key) {
1384
- format = missingRet;
1385
- }
1012
+ }
1013
+ if (missing !== null) {
1014
+ const ret = missing(context, locale, key, type);
1015
+ return isString(ret) ? ret : key;
1016
+ }
1017
+ else {
1018
+ if (isTranslateMissingWarn(missingWarn, key)) {
1019
+ onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
1386
1020
  }
1387
- from = to;
1021
+ return key;
1388
1022
  }
1389
- return [format, targetLocale, message];
1390
1023
  }
1391
- function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
1392
- const { messageCompiler, warnHtmlMessage } = context;
1393
- if (isMessageFunction(format)) {
1394
- const msg = format;
1395
- msg.locale = msg.locale || targetLocale;
1396
- msg.key = msg.key || key;
1397
- return msg;
1024
+ /** @internal */
1025
+ function updateFallbackLocale(ctx, locale, fallback) {
1026
+ const context = ctx;
1027
+ context.__localeChainCache = new Map();
1028
+ ctx.localeFallbacker(ctx, fallback, locale);
1029
+ }
1030
+ /** @internal */
1031
+ function isAlmostSameLocale(locale, compareLocale) {
1032
+ if (locale === compareLocale)
1033
+ return false;
1034
+ return locale.split('-')[0] === compareLocale.split('-')[0];
1035
+ }
1036
+ /** @internal */
1037
+ function isImplicitFallback(targetLocale, locales) {
1038
+ const index = locales.indexOf(targetLocale);
1039
+ if (index === -1) {
1040
+ return false;
1398
1041
  }
1399
- if (messageCompiler == null) {
1400
- const msg = (() => format);
1401
- msg.locale = targetLocale;
1402
- msg.key = key;
1403
- return msg;
1042
+ for (let i = index + 1; i < locales.length; i++) {
1043
+ if (isAlmostSameLocale(targetLocale, locales[i])) {
1044
+ return true;
1045
+ }
1404
1046
  }
1405
- // for vue-devtools timeline event
1406
- let start = null;
1407
- let startTag;
1408
- let endTag;
1409
- if (inBrowser) {
1410
- start = window.performance.now();
1411
- startTag = 'intlify-message-compilation-start';
1412
- endTag = 'intlify-message-compilation-end';
1413
- mark && mark(startTag);
1047
+ return false;
1048
+ }
1049
+ /* eslint-enable @typescript-eslint/no-explicit-any */
1050
+
1051
+ const intlDefined = typeof Intl !== 'undefined';
1052
+ const Availabilities = {
1053
+ dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
1054
+ numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
1055
+ };
1056
+
1057
+ // implementation of `datetime` function
1058
+ function datetime(context, ...args) {
1059
+ const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1060
+ const { __datetimeFormatters } = context;
1061
+ if (!Availabilities.dateTimeFormat) {
1062
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
1063
+ return MISSING_RESOLVE_VALUE;
1414
1064
  }
1415
- const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
1416
- // for vue-devtools timeline event
1417
- if (inBrowser) {
1418
- const end = window.performance.now();
1419
- const emitter = context.__v_emitter;
1420
- if (emitter && start) {
1421
- emitter.emit('message-compilation', {
1422
- type: 'message-compilation',
1423
- message: format,
1424
- time: end - start,
1425
- groupId: `${'translate'}:${key}`
1426
- });
1065
+ const [key, value, options, overrides] = parseDateTimeArgs(...args);
1066
+ const missingWarn = isBoolean(options.missingWarn)
1067
+ ? options.missingWarn
1068
+ : context.missingWarn;
1069
+ const fallbackWarn = isBoolean(options.fallbackWarn)
1070
+ ? options.fallbackWarn
1071
+ : context.fallbackWarn;
1072
+ const part = !!options.part;
1073
+ const locale = getLocale(context, options);
1074
+ const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1075
+ fallbackLocale, locale);
1076
+ if (!isString(key) || key === '') {
1077
+ return new Intl.DateTimeFormat(locale, overrides).format(value);
1078
+ }
1079
+ // resolve format
1080
+ let datetimeFormat = {};
1081
+ let targetLocale;
1082
+ let format = null;
1083
+ let from = locale;
1084
+ let to = null;
1085
+ const type = 'datetime format';
1086
+ for (let i = 0; i < locales.length; i++) {
1087
+ targetLocale = to = locales[i];
1088
+ if (locale !== targetLocale &&
1089
+ isTranslateFallbackWarn(fallbackWarn, key)) {
1090
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
1091
+ key,
1092
+ target: targetLocale
1093
+ }));
1427
1094
  }
1428
- if (startTag && endTag && mark && measure) {
1429
- mark(endTag);
1430
- measure('intlify message compilation', startTag, endTag);
1095
+ // for vue-devtools timeline event
1096
+ if (locale !== targetLocale) {
1097
+ const emitter = context.__v_emitter;
1098
+ if (emitter) {
1099
+ emitter.emit('fallback', {
1100
+ type,
1101
+ key,
1102
+ from,
1103
+ to,
1104
+ groupId: `${type}:${key}`
1105
+ });
1106
+ }
1431
1107
  }
1108
+ datetimeFormat =
1109
+ datetimeFormats[targetLocale] || {};
1110
+ format = datetimeFormat[key];
1111
+ if (isPlainObject(format))
1112
+ break;
1113
+ handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1114
+ from = to;
1432
1115
  }
1433
- msg.locale = targetLocale;
1434
- msg.key = key;
1435
- msg.source = format;
1436
- return msg;
1437
- }
1438
- function evaluateMessage(context, msg, msgCtx) {
1439
- // for vue-devtools timeline event
1440
- let start = null;
1441
- let startTag;
1442
- let endTag;
1443
- if (inBrowser) {
1444
- start = window.performance.now();
1445
- startTag = 'intlify-message-evaluation-start';
1446
- endTag = 'intlify-message-evaluation-end';
1447
- mark && mark(startTag);
1116
+ // checking format and target locale
1117
+ if (!isPlainObject(format) || !isString(targetLocale)) {
1118
+ return unresolving ? NOT_REOSLVED : key;
1448
1119
  }
1449
- const messaged = msg(msgCtx);
1450
- // for vue-devtools timeline event
1451
- if (inBrowser) {
1452
- const end = window.performance.now();
1453
- const emitter = context.__v_emitter;
1454
- if (emitter && start) {
1455
- emitter.emit('message-evaluation', {
1456
- type: 'message-evaluation',
1457
- value: messaged,
1458
- time: end - start,
1459
- groupId: `${'translate'}:${msg.key}`
1460
- });
1461
- }
1462
- if (startTag && endTag && mark && measure) {
1463
- mark(endTag);
1464
- measure('intlify message evaluation', startTag, endTag);
1465
- }
1120
+ let id = `${targetLocale}__${key}`;
1121
+ if (!isEmptyObject(overrides)) {
1122
+ id = `${id}__${JSON.stringify(overrides)}`;
1466
1123
  }
1467
- return messaged;
1124
+ let formatter = __datetimeFormatters.get(id);
1125
+ if (!formatter) {
1126
+ formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
1127
+ __datetimeFormatters.set(id, formatter);
1128
+ }
1129
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
1468
1130
  }
1469
1131
  /** @internal */
1470
- function parseTranslateArgs(...args) {
1471
- const [arg1, arg2, arg3] = args;
1132
+ const DATETIME_FORMAT_OPTIONS_KEYS = [
1133
+ 'localeMatcher',
1134
+ 'weekday',
1135
+ 'era',
1136
+ 'year',
1137
+ 'month',
1138
+ 'day',
1139
+ 'hour',
1140
+ 'minute',
1141
+ 'second',
1142
+ 'timeZoneName',
1143
+ 'formatMatcher',
1144
+ 'hour12',
1145
+ 'timeZone',
1146
+ 'dateStyle',
1147
+ 'timeStyle',
1148
+ 'calendar',
1149
+ 'dayPeriod',
1150
+ 'numberingSystem',
1151
+ 'hourCycle',
1152
+ 'fractionalSecondDigits'
1153
+ ];
1154
+ /** @internal */
1155
+ function parseDateTimeArgs(...args) {
1156
+ const [arg1, arg2, arg3, arg4] = args;
1472
1157
  const options = {};
1473
- if (!isString(arg1) &&
1474
- !isNumber(arg1) &&
1475
- !isMessageFunction(arg1) &&
1476
- !isMessageAST(arg1)) {
1477
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1478
- }
1479
- // prettier-ignore
1480
- const key = isNumber(arg1)
1481
- ? String(arg1)
1482
- : isMessageFunction(arg1)
1483
- ? arg1
1484
- : arg1;
1485
- if (isNumber(arg2)) {
1486
- options.plural = arg2;
1487
- }
1488
- else if (isString(arg2)) {
1489
- options.default = arg2;
1490
- }
1491
- else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
1492
- options.named = arg2;
1158
+ let overrides = {};
1159
+ let value;
1160
+ if (isString(arg1)) {
1161
+ // Only allow ISO strings - other date formats are often supported,
1162
+ // but may cause different results in different browsers.
1163
+ const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
1164
+ if (!matches) {
1165
+ throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1166
+ }
1167
+ // Some browsers can not parse the iso datetime separated by space,
1168
+ // this is a compromise solution by replace the 'T'/' ' with 'T'
1169
+ const dateTime = matches[3]
1170
+ ? matches[3].trim().startsWith('T')
1171
+ ? `${matches[1].trim()}${matches[3].trim()}`
1172
+ : `${matches[1].trim()}T${matches[3].trim()}`
1173
+ : matches[1].trim();
1174
+ value = new Date(dateTime);
1175
+ try {
1176
+ // This will fail if the date is not valid
1177
+ value.toISOString();
1178
+ }
1179
+ catch {
1180
+ throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1181
+ }
1493
1182
  }
1494
- else if (isArray(arg2)) {
1495
- options.list = arg2;
1183
+ else if (isDate(arg1)) {
1184
+ if (isNaN(arg1.getTime())) {
1185
+ throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
1186
+ }
1187
+ value = arg1;
1496
1188
  }
1497
- if (isNumber(arg3)) {
1498
- options.plural = arg3;
1189
+ else if (isNumber(arg1)) {
1190
+ value = arg1;
1499
1191
  }
1500
- else if (isString(arg3)) {
1501
- options.default = arg3;
1192
+ else {
1193
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1502
1194
  }
1503
- else if (isPlainObject(arg3)) {
1504
- assign(options, arg3);
1195
+ if (isString(arg2)) {
1196
+ options.key = arg2;
1505
1197
  }
1506
- return [key, options];
1507
- }
1508
- function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
1509
- return {
1510
- locale,
1511
- key,
1512
- warnHtmlMessage,
1513
- onError: (err) => {
1514
- onError && onError(err);
1515
- {
1516
- const _source = getSourceForCodeFrame(source);
1517
- const message = `Message compilation error: ${err.message}`;
1518
- const codeFrame = err.location &&
1519
- _source &&
1520
- generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
1521
- const emitter = context.__v_emitter;
1522
- if (emitter && _source) {
1523
- emitter.emit('compile-error', {
1524
- message: _source,
1525
- error: err.message,
1526
- start: err.location && err.location.start.offset,
1527
- end: err.location && err.location.end.offset,
1528
- groupId: `${'translate'}:${key}`
1529
- });
1530
- }
1531
- console.error(codeFrame ? `${message}\n${codeFrame}` : message);
1198
+ else if (isPlainObject(arg2)) {
1199
+ Object.keys(arg2).forEach(key => {
1200
+ if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
1201
+ overrides[key] = arg2[key];
1532
1202
  }
1533
- },
1534
- onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
1535
- };
1536
- }
1537
- function getSourceForCodeFrame(source) {
1538
- if (isString(source)) {
1539
- return source;
1540
- }
1541
- else {
1542
- if (source.loc && source.loc.source) {
1543
- return source.loc.source;
1544
- }
1203
+ else {
1204
+ options[key] = arg2[key];
1205
+ }
1206
+ });
1545
1207
  }
1546
- }
1547
- function getMessageContextOptions(context, locale, message, options) {
1548
- const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
1549
- const resolveMessage = (key, useLinked) => {
1550
- let val = resolveValue(message, key);
1551
- // fallback
1552
- if (val == null && (fallbackContext || useLinked)) {
1553
- const [, , message] = resolveMessageFormat(fallbackContext || context, // NOTE: if has fallbackContext, fallback to root, else if use linked, fallback to local context
1554
- key, locale, fallbackLocale, fallbackWarn, missingWarn);
1555
- val = resolveValue(message, key);
1556
- }
1557
- if (isString(val) || isMessageAST(val)) {
1558
- let occurred = false;
1559
- const onError = () => {
1560
- occurred = true;
1561
- };
1562
- const msg = compileMessageFormat(context, key, locale, val, key, onError);
1563
- return !occurred
1564
- ? msg
1565
- : NOOP_MESSAGE_FUNCTION;
1566
- }
1567
- else if (isMessageFunction(val)) {
1568
- return val;
1569
- }
1570
- else {
1571
- // TODO: should be implemented warning message
1572
- return NOOP_MESSAGE_FUNCTION;
1573
- }
1574
- };
1575
- const ctxOptions = {
1576
- locale,
1577
- modifiers,
1578
- pluralRules,
1579
- messages: resolveMessage
1580
- };
1581
- if (context.processor) {
1582
- ctxOptions.processor = context.processor;
1208
+ if (isString(arg3)) {
1209
+ options.locale = arg3;
1583
1210
  }
1584
- if (options.list) {
1585
- ctxOptions.list = options.list;
1211
+ else if (isPlainObject(arg3)) {
1212
+ overrides = arg3;
1586
1213
  }
1587
- if (options.named) {
1588
- ctxOptions.named = options.named;
1214
+ if (isPlainObject(arg4)) {
1215
+ overrides = arg4;
1589
1216
  }
1590
- if (isNumber(options.plural)) {
1591
- ctxOptions.pluralIndex = options.plural;
1217
+ return [options.key || '', value, options, overrides];
1218
+ }
1219
+ /** @internal */
1220
+ function clearDateTimeFormat(ctx, locale, format) {
1221
+ const context = ctx;
1222
+ for (const key in format) {
1223
+ const id = `${locale}__${key}`;
1224
+ if (!context.__datetimeFormatters.has(id)) {
1225
+ continue;
1226
+ }
1227
+ context.__datetimeFormatters.delete(id);
1592
1228
  }
1593
- return ctxOptions;
1594
1229
  }
1595
1230
 
1596
- const intlDefined = typeof Intl !== 'undefined';
1597
- const Availabilities = {
1598
- dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
1599
- numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
1600
- };
1601
-
1602
- // implementation of `datetime` function
1603
- function datetime(context, ...args) {
1604
- const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1605
- const { __datetimeFormatters } = context;
1606
- if (!Availabilities.dateTimeFormat) {
1607
- onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
1231
+ // implementation of `number` function
1232
+ function number(context, ...args) {
1233
+ const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1234
+ const { __numberFormatters } = context;
1235
+ if (!Availabilities.numberFormat) {
1236
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
1608
1237
  return MISSING_RESOLVE_VALUE;
1609
1238
  }
1610
- const [key, value, options, overrides] = parseDateTimeArgs(...args);
1239
+ const [key, value, options, overrides] = parseNumberArgs(...args);
1611
1240
  const missingWarn = isBoolean(options.missingWarn)
1612
1241
  ? options.missingWarn
1613
1242
  : context.missingWarn;
@@ -1619,20 +1248,20 @@ function datetime(context, ...args) {
1619
1248
  const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1620
1249
  fallbackLocale, locale);
1621
1250
  if (!isString(key) || key === '') {
1622
- return new Intl.DateTimeFormat(locale, overrides).format(value);
1251
+ return new Intl.NumberFormat(locale, overrides).format(value);
1623
1252
  }
1624
1253
  // resolve format
1625
- let datetimeFormat = {};
1254
+ let numberFormat = {};
1626
1255
  let targetLocale;
1627
1256
  let format = null;
1628
1257
  let from = locale;
1629
1258
  let to = null;
1630
- const type = 'datetime format';
1259
+ const type = 'number format';
1631
1260
  for (let i = 0; i < locales.length; i++) {
1632
1261
  targetLocale = to = locales[i];
1633
1262
  if (locale !== targetLocale &&
1634
1263
  isTranslateFallbackWarn(fallbackWarn, key)) {
1635
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
1264
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
1636
1265
  key,
1637
1266
  target: targetLocale
1638
1267
  }));
@@ -1650,9 +1279,9 @@ function datetime(context, ...args) {
1650
1279
  });
1651
1280
  }
1652
1281
  }
1653
- datetimeFormat =
1654
- datetimeFormats[targetLocale] || {};
1655
- format = datetimeFormat[key];
1282
+ numberFormat =
1283
+ numberFormats[targetLocale] || {};
1284
+ format = numberFormat[key];
1656
1285
  if (isPlainObject(format))
1657
1286
  break;
1658
1287
  handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
@@ -1666,147 +1295,356 @@ function datetime(context, ...args) {
1666
1295
  if (!isEmptyObject(overrides)) {
1667
1296
  id = `${id}__${JSON.stringify(overrides)}`;
1668
1297
  }
1669
- let formatter = __datetimeFormatters.get(id);
1298
+ let formatter = __numberFormatters.get(id);
1670
1299
  if (!formatter) {
1671
- formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
1672
- __datetimeFormatters.set(id, formatter);
1300
+ formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
1301
+ __numberFormatters.set(id, formatter);
1673
1302
  }
1674
1303
  return !part ? formatter.format(value) : formatter.formatToParts(value);
1675
1304
  }
1676
1305
  /** @internal */
1677
- const DATETIME_FORMAT_OPTIONS_KEYS = [
1306
+ const NUMBER_FORMAT_OPTIONS_KEYS = [
1678
1307
  'localeMatcher',
1679
- 'weekday',
1680
- 'era',
1681
- 'year',
1682
- 'month',
1683
- 'day',
1684
- 'hour',
1685
- 'minute',
1686
- 'second',
1687
- 'timeZoneName',
1688
- 'formatMatcher',
1689
- 'hour12',
1690
- 'timeZone',
1691
- 'dateStyle',
1692
- 'timeStyle',
1693
- 'calendar',
1694
- 'dayPeriod',
1695
- 'numberingSystem',
1696
- 'hourCycle',
1697
- 'fractionalSecondDigits'
1308
+ 'style',
1309
+ 'currency',
1310
+ 'currencyDisplay',
1311
+ 'currencySign',
1312
+ 'useGrouping',
1313
+ 'minimumIntegerDigits',
1314
+ 'minimumFractionDigits',
1315
+ 'maximumFractionDigits',
1316
+ 'minimumSignificantDigits',
1317
+ 'maximumSignificantDigits',
1318
+ 'compactDisplay',
1319
+ 'notation',
1320
+ 'signDisplay',
1321
+ 'unit',
1322
+ 'unitDisplay',
1323
+ 'roundingMode',
1324
+ 'roundingPriority',
1325
+ 'roundingIncrement',
1326
+ 'trailingZeroDisplay'
1698
1327
  ];
1699
1328
  /** @internal */
1700
- function parseDateTimeArgs(...args) {
1329
+ function parseNumberArgs(...args) {
1701
1330
  const [arg1, arg2, arg3, arg4] = args;
1702
1331
  const options = {};
1703
1332
  let overrides = {};
1704
- let value;
1705
- if (isString(arg1)) {
1706
- // Only allow ISO strings - other date formats are often supported,
1707
- // but may cause different results in different browsers.
1708
- const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
1709
- if (!matches) {
1710
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1711
- }
1712
- // Some browsers can not parse the iso datetime separated by space,
1713
- // this is a compromise solution by replace the 'T'/' ' with 'T'
1714
- const dateTime = matches[3]
1715
- ? matches[3].trim().startsWith('T')
1716
- ? `${matches[1].trim()}${matches[3].trim()}`
1717
- : `${matches[1].trim()}T${matches[3].trim()}`
1718
- : matches[1].trim();
1719
- value = new Date(dateTime);
1720
- try {
1721
- // This will fail if the date is not valid
1722
- value.toISOString();
1723
- }
1724
- catch (e) {
1725
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1333
+ if (!isNumber(arg1)) {
1334
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1335
+ }
1336
+ const value = arg1;
1337
+ if (isString(arg2)) {
1338
+ options.key = arg2;
1339
+ }
1340
+ else if (isPlainObject(arg2)) {
1341
+ Object.keys(arg2).forEach(key => {
1342
+ if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
1343
+ overrides[key] = arg2[key];
1344
+ }
1345
+ else {
1346
+ options[key] = arg2[key];
1347
+ }
1348
+ });
1349
+ }
1350
+ if (isString(arg3)) {
1351
+ options.locale = arg3;
1352
+ }
1353
+ else if (isPlainObject(arg3)) {
1354
+ overrides = arg3;
1355
+ }
1356
+ if (isPlainObject(arg4)) {
1357
+ overrides = arg4;
1358
+ }
1359
+ return [options.key || '', value, options, overrides];
1360
+ }
1361
+ /** @internal */
1362
+ function clearNumberFormat(ctx, locale, format) {
1363
+ const context = ctx;
1364
+ for (const key in format) {
1365
+ const id = `${locale}__${key}`;
1366
+ if (!context.__numberFormatters.has(id)) {
1367
+ continue;
1726
1368
  }
1369
+ context.__numberFormatters.delete(id);
1727
1370
  }
1728
- else if (isDate(arg1)) {
1729
- if (isNaN(arg1.getTime())) {
1730
- throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
1371
+ }
1372
+
1373
+ const DEFAULT_MODIFIER = (str) => str;
1374
+ const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
1375
+ const DEFAULT_MESSAGE_DATA_TYPE = 'text';
1376
+ const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);
1377
+ const DEFAULT_INTERPOLATE = toDisplayString;
1378
+ function pluralDefault(choice, choicesLength) {
1379
+ choice = Math.abs(choice);
1380
+ if (choicesLength === 2) {
1381
+ // prettier-ignore
1382
+ return choice
1383
+ ? choice > 1
1384
+ ? 1
1385
+ : 0
1386
+ : 1;
1387
+ }
1388
+ return choice ? Math.min(choice, 2) : 0;
1389
+ }
1390
+ function getPluralIndex(options) {
1391
+ // prettier-ignore
1392
+ const index = isNumber(options.pluralIndex)
1393
+ ? options.pluralIndex
1394
+ : -1;
1395
+ // prettier-ignore
1396
+ return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
1397
+ ? isNumber(options.named.count)
1398
+ ? options.named.count
1399
+ : isNumber(options.named.n)
1400
+ ? options.named.n
1401
+ : index
1402
+ : index;
1403
+ }
1404
+ function normalizeNamed(pluralIndex, props) {
1405
+ if (!props.count) {
1406
+ props.count = pluralIndex;
1407
+ }
1408
+ if (!props.n) {
1409
+ props.n = pluralIndex;
1410
+ }
1411
+ }
1412
+ function createMessageContext(options = {}) {
1413
+ const locale = options.locale;
1414
+ const pluralIndex = getPluralIndex(options);
1415
+ const pluralRule = isObject(options.pluralRules) &&
1416
+ isString(locale) &&
1417
+ isFunction(options.pluralRules[locale])
1418
+ ? options.pluralRules[locale]
1419
+ : pluralDefault;
1420
+ const orgPluralRule = isObject(options.pluralRules) &&
1421
+ isString(locale) &&
1422
+ isFunction(options.pluralRules[locale])
1423
+ ? pluralDefault
1424
+ : undefined;
1425
+ const plural = (messages) => {
1426
+ return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
1427
+ };
1428
+ const _list = options.list || [];
1429
+ const list = (index) => _list[index];
1430
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1431
+ const _named = options.named || {};
1432
+ isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
1433
+ const named = (key) => _named[key];
1434
+ function message(key, useLinked) {
1435
+ // prettier-ignore
1436
+ const msg = isFunction(options.messages)
1437
+ ? options.messages(key, !!useLinked)
1438
+ : isObject(options.messages)
1439
+ ? options.messages[key]
1440
+ : false;
1441
+ return !msg
1442
+ ? options.parent
1443
+ ? options.parent.message(key) // resolve from parent messages
1444
+ : DEFAULT_MESSAGE
1445
+ : msg;
1446
+ }
1447
+ const _modifier = (name) => options.modifiers
1448
+ ? options.modifiers[name]
1449
+ : DEFAULT_MODIFIER;
1450
+ const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
1451
+ ? options.processor.normalize
1452
+ : DEFAULT_NORMALIZE;
1453
+ const interpolate = isPlainObject(options.processor) &&
1454
+ isFunction(options.processor.interpolate)
1455
+ ? options.processor.interpolate
1456
+ : DEFAULT_INTERPOLATE;
1457
+ const type = isPlainObject(options.processor) && isString(options.processor.type)
1458
+ ? options.processor.type
1459
+ : DEFAULT_MESSAGE_DATA_TYPE;
1460
+ const linked = (key, ...args) => {
1461
+ const [arg1, arg2] = args;
1462
+ let type = 'text';
1463
+ let modifier = '';
1464
+ if (args.length === 1) {
1465
+ if (isObject(arg1)) {
1466
+ modifier = arg1.modifier || modifier;
1467
+ type = arg1.type || type;
1468
+ }
1469
+ else if (isString(arg1)) {
1470
+ modifier = arg1 || modifier;
1471
+ }
1731
1472
  }
1732
- value = arg1;
1733
- }
1734
- else if (isNumber(arg1)) {
1735
- value = arg1;
1736
- }
1737
- else {
1738
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1739
- }
1740
- if (isString(arg2)) {
1741
- options.key = arg2;
1742
- }
1743
- else if (isPlainObject(arg2)) {
1744
- Object.keys(arg2).forEach(key => {
1745
- if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
1746
- overrides[key] = arg2[key];
1473
+ else if (args.length === 2) {
1474
+ if (isString(arg1)) {
1475
+ modifier = arg1 || modifier;
1747
1476
  }
1748
- else {
1749
- options[key] = arg2[key];
1477
+ if (isString(arg2)) {
1478
+ type = arg2 || type;
1750
1479
  }
1751
- });
1752
- }
1753
- if (isString(arg3)) {
1754
- options.locale = arg3;
1755
- }
1756
- else if (isPlainObject(arg3)) {
1757
- overrides = arg3;
1758
- }
1759
- if (isPlainObject(arg4)) {
1760
- overrides = arg4;
1761
- }
1762
- return [options.key || '', value, options, overrides];
1763
- }
1764
- /** @internal */
1765
- function clearDateTimeFormat(ctx, locale, format) {
1766
- const context = ctx;
1767
- for (const key in format) {
1768
- const id = `${locale}__${key}`;
1769
- if (!context.__datetimeFormatters.has(id)) {
1770
- continue;
1771
1480
  }
1772
- context.__datetimeFormatters.delete(id);
1773
- }
1481
+ const ret = message(key, true)(ctx);
1482
+ const msg =
1483
+ // The message in vnode resolved with linked are returned as an array by processor.nomalize
1484
+ type === 'vnode' && isArray(ret) && modifier
1485
+ ? ret[0]
1486
+ : ret;
1487
+ return modifier ? _modifier(modifier)(msg, type) : msg;
1488
+ };
1489
+ const ctx = {
1490
+ ["list" /* HelperNameMap.LIST */]: list,
1491
+ ["named" /* HelperNameMap.NAMED */]: named,
1492
+ ["plural" /* HelperNameMap.PLURAL */]: plural,
1493
+ ["linked" /* HelperNameMap.LINKED */]: linked,
1494
+ ["message" /* HelperNameMap.MESSAGE */]: message,
1495
+ ["type" /* HelperNameMap.TYPE */]: type,
1496
+ ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
1497
+ ["normalize" /* HelperNameMap.NORMALIZE */]: normalize,
1498
+ ["values" /* HelperNameMap.VALUES */]: assign({}, _list, _named)
1499
+ };
1500
+ return ctx;
1774
1501
  }
1775
1502
 
1776
- // implementation of `number` function
1777
- function number(context, ...args) {
1778
- const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1779
- const { __numberFormatters } = context;
1780
- if (!Availabilities.numberFormat) {
1781
- onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
1782
- return MISSING_RESOLVE_VALUE;
1783
- }
1784
- const [key, value, options, overrides] = parseNumberArgs(...args);
1503
+ const NOOP_MESSAGE_FUNCTION = () => '';
1504
+ const isMessageFunction = (val) => isFunction(val);
1505
+ // implementation of `translate` function
1506
+ function translate(context, ...args) {
1507
+ const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
1508
+ const [key, options] = parseTranslateArgs(...args);
1785
1509
  const missingWarn = isBoolean(options.missingWarn)
1786
1510
  ? options.missingWarn
1787
1511
  : context.missingWarn;
1788
1512
  const fallbackWarn = isBoolean(options.fallbackWarn)
1789
1513
  ? options.fallbackWarn
1790
1514
  : context.fallbackWarn;
1791
- const part = !!options.part;
1515
+ const escapeParameter = isBoolean(options.escapeParameter)
1516
+ ? options.escapeParameter
1517
+ : context.escapeParameter;
1518
+ const resolvedMessage = !!options.resolvedMessage;
1519
+ // prettier-ignore
1520
+ const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
1521
+ ? !isBoolean(options.default)
1522
+ ? options.default
1523
+ : (!messageCompiler ? () => key : key)
1524
+ : fallbackFormat // default by `fallbackFormat` option
1525
+ ? (!messageCompiler ? () => key : key)
1526
+ : null;
1527
+ const enableDefaultMsg = fallbackFormat ||
1528
+ (defaultMsgOrKey != null &&
1529
+ (isString(defaultMsgOrKey) || isFunction(defaultMsgOrKey)));
1792
1530
  const locale = getLocale(context, options);
1793
- const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1794
- fallbackLocale, locale);
1795
- if (!isString(key) || key === '') {
1796
- return new Intl.NumberFormat(locale, overrides).format(value);
1531
+ // escape params
1532
+ escapeParameter && escapeParams(options);
1533
+ // resolve message format
1534
+ // eslint-disable-next-line prefer-const
1535
+ let [formatScope, targetLocale, message] = !resolvedMessage
1536
+ ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
1537
+ : [
1538
+ key,
1539
+ locale,
1540
+ messages[locale] || {}
1541
+ ];
1542
+ // NOTE:
1543
+ // Fix to work around `ssrTransfrom` bug in Vite.
1544
+ // https://github.com/vitejs/vite/issues/4306
1545
+ // To get around this, use temporary variables.
1546
+ // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
1547
+ let format = formatScope;
1548
+ // if you use default message, set it as message format!
1549
+ let cacheBaseKey = key;
1550
+ if (!resolvedMessage &&
1551
+ !(isString(format) ||
1552
+ isMessageAST(format) ||
1553
+ isMessageFunction(format))) {
1554
+ if (enableDefaultMsg) {
1555
+ format = defaultMsgOrKey;
1556
+ cacheBaseKey = format;
1557
+ }
1797
1558
  }
1798
- // resolve format
1799
- let numberFormat = {};
1559
+ // checking message format and target locale
1560
+ if (!resolvedMessage &&
1561
+ (!(isString(format) ||
1562
+ isMessageAST(format) ||
1563
+ isMessageFunction(format)) ||
1564
+ !isString(targetLocale))) {
1565
+ return unresolving ? NOT_REOSLVED : key;
1566
+ }
1567
+ // TODO: refactor
1568
+ if (isString(format) && context.messageCompiler == null) {
1569
+ warn(`The message format compilation is not supported in this build. ` +
1570
+ `Because message compiler isn't included. ` +
1571
+ `You need to pre-compilation all message format. ` +
1572
+ `So translate function return '${key}'.`);
1573
+ return key;
1574
+ }
1575
+ // setup compile error detecting
1576
+ let occurred = false;
1577
+ const onError = () => {
1578
+ occurred = true;
1579
+ };
1580
+ // compile message format
1581
+ const msg = !isMessageFunction(format)
1582
+ ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
1583
+ : format;
1584
+ // if occurred compile error, return the message format
1585
+ if (occurred) {
1586
+ return format;
1587
+ }
1588
+ // evaluate message with context
1589
+ const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
1590
+ const msgContext = createMessageContext(ctxOptions);
1591
+ const messaged = evaluateMessage(context, msg, msgContext);
1592
+ // if use post translation option, proceed it with handler
1593
+ const ret = postTranslation
1594
+ ? postTranslation(messaged, key)
1595
+ : messaged;
1596
+ // NOTE: experimental !!
1597
+ {
1598
+ // prettier-ignore
1599
+ const payloads = {
1600
+ timestamp: Date.now(),
1601
+ key: isString(key)
1602
+ ? key
1603
+ : isMessageFunction(format)
1604
+ ? format.key
1605
+ : '',
1606
+ locale: targetLocale || (isMessageFunction(format)
1607
+ ? format.locale
1608
+ : ''),
1609
+ format: isString(format)
1610
+ ? format
1611
+ : isMessageFunction(format)
1612
+ ? format.source
1613
+ : '',
1614
+ message: ret
1615
+ };
1616
+ payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
1617
+ translateDevTools(payloads);
1618
+ }
1619
+ return ret;
1620
+ }
1621
+ function escapeParams(options) {
1622
+ if (isArray(options.list)) {
1623
+ options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
1624
+ }
1625
+ else if (isObject(options.named)) {
1626
+ Object.keys(options.named).forEach(key => {
1627
+ if (isString(options.named[key])) {
1628
+ options.named[key] = escapeHtml(options.named[key]);
1629
+ }
1630
+ });
1631
+ }
1632
+ }
1633
+ function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
1634
+ const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
1635
+ const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
1636
+ let message = {};
1800
1637
  let targetLocale;
1801
1638
  let format = null;
1802
1639
  let from = locale;
1803
1640
  let to = null;
1804
- const type = 'number format';
1641
+ const type = 'translate';
1805
1642
  for (let i = 0; i < locales.length; i++) {
1806
1643
  targetLocale = to = locales[i];
1807
1644
  if (locale !== targetLocale &&
1645
+ !isAlmostSameLocale(locale, targetLocale) &&
1808
1646
  isTranslateFallbackWarn(fallbackWarn, key)) {
1809
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
1647
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
1810
1648
  key,
1811
1649
  target: targetLocale
1812
1650
  }));
@@ -1824,95 +1662,257 @@ function number(context, ...args) {
1824
1662
  });
1825
1663
  }
1826
1664
  }
1827
- numberFormat =
1828
- numberFormats[targetLocale] || {};
1829
- format = numberFormat[key];
1830
- if (isPlainObject(format))
1665
+ message =
1666
+ messages[targetLocale] || {};
1667
+ // for vue-devtools timeline event
1668
+ let start = null;
1669
+ let startTag;
1670
+ let endTag;
1671
+ if (inBrowser) {
1672
+ start = window.performance.now();
1673
+ startTag = 'intlify-message-resolve-start';
1674
+ endTag = 'intlify-message-resolve-end';
1675
+ mark && mark(startTag);
1676
+ }
1677
+ if ((format = resolveValue(message, key)) === null) {
1678
+ // if null, resolve with object key path
1679
+ format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
1680
+ }
1681
+ // for vue-devtools timeline event
1682
+ if (inBrowser) {
1683
+ const end = window.performance.now();
1684
+ const emitter = context.__v_emitter;
1685
+ if (emitter && start && format) {
1686
+ emitter.emit('message-resolve', {
1687
+ type: 'message-resolve',
1688
+ key,
1689
+ message: format,
1690
+ time: end - start,
1691
+ groupId: `${type}:${key}`
1692
+ });
1693
+ }
1694
+ if (startTag && endTag && mark && measure) {
1695
+ mark(endTag);
1696
+ measure('intlify message resolve', startTag, endTag);
1697
+ }
1698
+ }
1699
+ if (isString(format) || isMessageAST(format) || isMessageFunction(format)) {
1831
1700
  break;
1832
- handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1701
+ }
1702
+ if (!isImplicitFallback(targetLocale, locales)) {
1703
+ const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1704
+ key, targetLocale, missingWarn, type);
1705
+ if (missingRet !== key) {
1706
+ format = missingRet;
1707
+ }
1708
+ }
1833
1709
  from = to;
1834
1710
  }
1835
- // checking format and target locale
1836
- if (!isPlainObject(format) || !isString(targetLocale)) {
1837
- return unresolving ? NOT_REOSLVED : key;
1711
+ return [format, targetLocale, message];
1712
+ }
1713
+ function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
1714
+ const { messageCompiler, warnHtmlMessage } = context;
1715
+ if (isMessageFunction(format)) {
1716
+ const msg = format;
1717
+ msg.locale = msg.locale || targetLocale;
1718
+ msg.key = msg.key || key;
1719
+ return msg;
1838
1720
  }
1839
- let id = `${targetLocale}__${key}`;
1840
- if (!isEmptyObject(overrides)) {
1841
- id = `${id}__${JSON.stringify(overrides)}`;
1721
+ if (messageCompiler == null) {
1722
+ const msg = (() => format);
1723
+ msg.locale = targetLocale;
1724
+ msg.key = key;
1725
+ return msg;
1842
1726
  }
1843
- let formatter = __numberFormatters.get(id);
1844
- if (!formatter) {
1845
- formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
1846
- __numberFormatters.set(id, formatter);
1727
+ // for vue-devtools timeline event
1728
+ let start = null;
1729
+ let startTag;
1730
+ let endTag;
1731
+ if (inBrowser) {
1732
+ start = window.performance.now();
1733
+ startTag = 'intlify-message-compilation-start';
1734
+ endTag = 'intlify-message-compilation-end';
1735
+ mark && mark(startTag);
1847
1736
  }
1848
- return !part ? formatter.format(value) : formatter.formatToParts(value);
1737
+ const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
1738
+ // for vue-devtools timeline event
1739
+ if (inBrowser) {
1740
+ const end = window.performance.now();
1741
+ const emitter = context.__v_emitter;
1742
+ if (emitter && start) {
1743
+ emitter.emit('message-compilation', {
1744
+ type: 'message-compilation',
1745
+ message: format,
1746
+ time: end - start,
1747
+ groupId: `${'translate'}:${key}`
1748
+ });
1749
+ }
1750
+ if (startTag && endTag && mark && measure) {
1751
+ mark(endTag);
1752
+ measure('intlify message compilation', startTag, endTag);
1753
+ }
1754
+ }
1755
+ msg.locale = targetLocale;
1756
+ msg.key = key;
1757
+ msg.source = format;
1758
+ return msg;
1759
+ }
1760
+ function evaluateMessage(context, msg, msgCtx) {
1761
+ // for vue-devtools timeline event
1762
+ let start = null;
1763
+ let startTag;
1764
+ let endTag;
1765
+ if (inBrowser) {
1766
+ start = window.performance.now();
1767
+ startTag = 'intlify-message-evaluation-start';
1768
+ endTag = 'intlify-message-evaluation-end';
1769
+ mark && mark(startTag);
1770
+ }
1771
+ const messaged = msg(msgCtx);
1772
+ // for vue-devtools timeline event
1773
+ if (inBrowser) {
1774
+ const end = window.performance.now();
1775
+ const emitter = context.__v_emitter;
1776
+ if (emitter && start) {
1777
+ emitter.emit('message-evaluation', {
1778
+ type: 'message-evaluation',
1779
+ value: messaged,
1780
+ time: end - start,
1781
+ groupId: `${'translate'}:${msg.key}`
1782
+ });
1783
+ }
1784
+ if (startTag && endTag && mark && measure) {
1785
+ mark(endTag);
1786
+ measure('intlify message evaluation', startTag, endTag);
1787
+ }
1788
+ }
1789
+ return messaged;
1849
1790
  }
1850
1791
  /** @internal */
1851
- const NUMBER_FORMAT_OPTIONS_KEYS = [
1852
- 'localeMatcher',
1853
- 'style',
1854
- 'currency',
1855
- 'currencyDisplay',
1856
- 'currencySign',
1857
- 'useGrouping',
1858
- 'minimumIntegerDigits',
1859
- 'minimumFractionDigits',
1860
- 'maximumFractionDigits',
1861
- 'minimumSignificantDigits',
1862
- 'maximumSignificantDigits',
1863
- 'compactDisplay',
1864
- 'notation',
1865
- 'signDisplay',
1866
- 'unit',
1867
- 'unitDisplay',
1868
- 'roundingMode',
1869
- 'roundingPriority',
1870
- 'roundingIncrement',
1871
- 'trailingZeroDisplay'
1872
- ];
1873
- /** @internal */
1874
- function parseNumberArgs(...args) {
1875
- const [arg1, arg2, arg3, arg4] = args;
1792
+ function parseTranslateArgs(...args) {
1793
+ const [arg1, arg2, arg3] = args;
1876
1794
  const options = {};
1877
- let overrides = {};
1878
- if (!isNumber(arg1)) {
1795
+ if (!isString(arg1) &&
1796
+ !isNumber(arg1) &&
1797
+ !isMessageFunction(arg1) &&
1798
+ !isMessageAST(arg1)) {
1879
1799
  throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1880
1800
  }
1881
- const value = arg1;
1882
- if (isString(arg2)) {
1883
- options.key = arg2;
1801
+ // prettier-ignore
1802
+ const key = isNumber(arg1)
1803
+ ? String(arg1)
1804
+ : isMessageFunction(arg1)
1805
+ ? arg1
1806
+ : arg1;
1807
+ if (isNumber(arg2)) {
1808
+ options.plural = arg2;
1884
1809
  }
1885
- else if (isPlainObject(arg2)) {
1886
- Object.keys(arg2).forEach(key => {
1887
- if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
1888
- overrides[key] = arg2[key];
1889
- }
1890
- else {
1891
- options[key] = arg2[key];
1892
- }
1893
- });
1810
+ else if (isString(arg2)) {
1811
+ options.default = arg2;
1894
1812
  }
1895
- if (isString(arg3)) {
1896
- options.locale = arg3;
1813
+ else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
1814
+ options.named = arg2;
1815
+ }
1816
+ else if (isArray(arg2)) {
1817
+ options.list = arg2;
1818
+ }
1819
+ if (isNumber(arg3)) {
1820
+ options.plural = arg3;
1821
+ }
1822
+ else if (isString(arg3)) {
1823
+ options.default = arg3;
1897
1824
  }
1898
1825
  else if (isPlainObject(arg3)) {
1899
- overrides = arg3;
1826
+ assign(options, arg3);
1900
1827
  }
1901
- if (isPlainObject(arg4)) {
1902
- overrides = arg4;
1828
+ return [key, options];
1829
+ }
1830
+ function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
1831
+ return {
1832
+ locale,
1833
+ key,
1834
+ warnHtmlMessage,
1835
+ onError: (err) => {
1836
+ onError && onError(err);
1837
+ {
1838
+ const _source = getSourceForCodeFrame(source);
1839
+ const message = `Message compilation error: ${err.message}`;
1840
+ const codeFrame = err.location &&
1841
+ _source &&
1842
+ generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
1843
+ const emitter = context.__v_emitter;
1844
+ if (emitter && _source) {
1845
+ emitter.emit('compile-error', {
1846
+ message: _source,
1847
+ error: err.message,
1848
+ start: err.location && err.location.start.offset,
1849
+ end: err.location && err.location.end.offset,
1850
+ groupId: `${'translate'}:${key}`
1851
+ });
1852
+ }
1853
+ console.error(codeFrame ? `${message}\n${codeFrame}` : message);
1854
+ }
1855
+ },
1856
+ onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
1857
+ };
1858
+ }
1859
+ function getSourceForCodeFrame(source) {
1860
+ if (isString(source)) {
1861
+ return source;
1862
+ }
1863
+ else {
1864
+ if (source.loc && source.loc.source) {
1865
+ return source.loc.source;
1866
+ }
1903
1867
  }
1904
- return [options.key || '', value, options, overrides];
1905
1868
  }
1906
- /** @internal */
1907
- function clearNumberFormat(ctx, locale, format) {
1908
- const context = ctx;
1909
- for (const key in format) {
1910
- const id = `${locale}__${key}`;
1911
- if (!context.__numberFormatters.has(id)) {
1912
- continue;
1869
+ function getMessageContextOptions(context, locale, message, options) {
1870
+ const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
1871
+ const resolveMessage = (key, useLinked) => {
1872
+ let val = resolveValue(message, key);
1873
+ // fallback
1874
+ if (val == null && (fallbackContext || useLinked)) {
1875
+ const [, , message] = resolveMessageFormat(fallbackContext || context, // NOTE: if has fallbackContext, fallback to root, else if use linked, fallback to local context
1876
+ key, locale, fallbackLocale, fallbackWarn, missingWarn);
1877
+ val = resolveValue(message, key);
1913
1878
  }
1914
- context.__numberFormatters.delete(id);
1879
+ if (isString(val) || isMessageAST(val)) {
1880
+ let occurred = false;
1881
+ const onError = () => {
1882
+ occurred = true;
1883
+ };
1884
+ const msg = compileMessageFormat(context, key, locale, val, key, onError);
1885
+ return !occurred
1886
+ ? msg
1887
+ : NOOP_MESSAGE_FUNCTION;
1888
+ }
1889
+ else if (isMessageFunction(val)) {
1890
+ return val;
1891
+ }
1892
+ else {
1893
+ // TODO: should be implemented warning message
1894
+ return NOOP_MESSAGE_FUNCTION;
1895
+ }
1896
+ };
1897
+ const ctxOptions = {
1898
+ locale,
1899
+ modifiers,
1900
+ pluralRules,
1901
+ messages: resolveMessage
1902
+ };
1903
+ if (context.processor) {
1904
+ ctxOptions.processor = context.processor;
1905
+ }
1906
+ if (options.list) {
1907
+ ctxOptions.list = options.list;
1908
+ }
1909
+ if (options.named) {
1910
+ ctxOptions.named = options.named;
1915
1911
  }
1912
+ if (isNumber(options.plural)) {
1913
+ ctxOptions.pluralIndex = options.plural;
1914
+ }
1915
+ return ctxOptions;
1916
1916
  }
1917
1917
 
1918
1918
  // register message compiler for jit compilation