@intlify/core-base 10.0.0-beta.5 → 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-base v10.0.0-beta.5
2
+ * core-base v10.0.0-rc.1
3
3
  * (c) 2024 kazuya kawaguchi
4
4
  * Released under the MIT License.
5
5
  */
@@ -1650,402 +1650,146 @@ var IntlifyCoreBase = (function (exports) {
1650
1650
  }
1651
1651
  }
1652
1652
 
1653
- const pathStateMachine = [];
1654
- pathStateMachine[0 /* States.BEFORE_PATH */] = {
1655
- ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
1656
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
1657
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
1658
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
1659
- };
1660
- pathStateMachine[1 /* States.IN_PATH */] = {
1661
- ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
1662
- ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
1663
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
1664
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
1665
- };
1666
- pathStateMachine[2 /* States.BEFORE_IDENT */] = {
1667
- ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
1668
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
1669
- ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
1670
- };
1671
- pathStateMachine[3 /* States.IN_IDENT */] = {
1672
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
1673
- ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
1674
- ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
1675
- ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
1676
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
1677
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
1678
- };
1679
- pathStateMachine[4 /* States.IN_SUB_PATH */] = {
1680
- ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
1681
- ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
1682
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [
1683
- 4 /* States.IN_SUB_PATH */,
1684
- 2 /* Actions.INC_SUB_PATH_DEPTH */
1685
- ],
1686
- ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
1687
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
1688
- ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
1689
- };
1690
- pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
1691
- ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
1692
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
1693
- ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
1694
- };
1695
- pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
1696
- ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
1697
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
1698
- ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
1699
- };
1700
- /**
1701
- * Check if an expression is a literal value.
1702
- */
1703
- const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
1704
- function isLiteral(exp) {
1705
- return literalValueRE.test(exp);
1706
- }
1707
- /**
1708
- * Strip quotes from a string
1709
- */
1710
- function stripQuotes(str) {
1711
- const a = str.charCodeAt(0);
1712
- const b = str.charCodeAt(str.length - 1);
1713
- return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
1653
+ function format(ast) {
1654
+ const msg = (ctx) => formatParts(ctx, ast);
1655
+ return msg;
1714
1656
  }
1715
- /**
1716
- * Determine the type of a character in a keypath.
1717
- */
1718
- function getPathCharType(ch) {
1719
- if (ch === undefined || ch === null) {
1720
- return "o" /* PathCharTypes.END_OF_FAIL */;
1657
+ function formatParts(ctx, ast) {
1658
+ const body = ast.b || ast.body;
1659
+ if ((body.t || body.type) === 1 /* NodeTypes.Plural */) {
1660
+ const plural = body;
1661
+ const cases = plural.c || plural.cases;
1662
+ return ctx.plural(cases.reduce((messages, c) => [
1663
+ ...messages,
1664
+ formatMessageParts(ctx, c)
1665
+ ], []));
1721
1666
  }
1722
- const code = ch.charCodeAt(0);
1723
- switch (code) {
1724
- case 0x5b: // [
1725
- case 0x5d: // ]
1726
- case 0x2e: // .
1727
- case 0x22: // "
1728
- case 0x27: // '
1729
- return ch;
1730
- case 0x5f: // _
1731
- case 0x24: // $
1732
- case 0x2d: // -
1733
- return "i" /* PathCharTypes.IDENT */;
1734
- case 0x09: // Tab (HT)
1735
- case 0x0a: // Newline (LF)
1736
- case 0x0d: // Return (CR)
1737
- case 0xa0: // No-break space (NBSP)
1738
- case 0xfeff: // Byte Order Mark (BOM)
1739
- case 0x2028: // Line Separator (LS)
1740
- case 0x2029: // Paragraph Separator (PS)
1741
- return "w" /* PathCharTypes.WORKSPACE */;
1667
+ else {
1668
+ return formatMessageParts(ctx, body);
1742
1669
  }
1743
- return "i" /* PathCharTypes.IDENT */;
1744
1670
  }
1745
- /**
1746
- * Format a subPath, return its plain form if it is
1747
- * a literal string or number. Otherwise prepend the
1748
- * dynamic indicator (*).
1749
- */
1750
- function formatSubPath(path) {
1751
- const trimmed = path.trim();
1752
- // invalid leading 0
1753
- if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
1754
- return false;
1671
+ function formatMessageParts(ctx, node) {
1672
+ const _static = node.s || node.static;
1673
+ if (_static) {
1674
+ return ctx.type === 'text'
1675
+ ? _static
1676
+ : ctx.normalize([_static]);
1677
+ }
1678
+ else {
1679
+ const messages = (node.i || node.items).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
1680
+ return ctx.normalize(messages);
1755
1681
  }
1756
- return isLiteral(trimmed)
1757
- ? stripQuotes(trimmed)
1758
- : "*" /* PathCharTypes.ASTARISK */ + trimmed;
1759
1682
  }
1760
- /**
1761
- * Parse a string path into an array of segments
1762
- */
1763
- function parse(path) {
1764
- const keys = [];
1765
- let index = -1;
1766
- let mode = 0 /* States.BEFORE_PATH */;
1767
- let subPathDepth = 0;
1768
- let c;
1769
- let key; // eslint-disable-line
1770
- let newChar;
1771
- let type;
1772
- let transition;
1773
- let action;
1774
- let typeMap;
1775
- const actions = [];
1776
- actions[0 /* Actions.APPEND */] = () => {
1777
- if (key === undefined) {
1778
- key = newChar;
1779
- }
1780
- else {
1781
- key += newChar;
1782
- }
1783
- };
1784
- actions[1 /* Actions.PUSH */] = () => {
1785
- if (key !== undefined) {
1786
- keys.push(key);
1787
- key = undefined;
1788
- }
1789
- };
1790
- actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
1791
- actions[0 /* Actions.APPEND */]();
1792
- subPathDepth++;
1793
- };
1794
- actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
1795
- if (subPathDepth > 0) {
1796
- subPathDepth--;
1797
- mode = 4 /* States.IN_SUB_PATH */;
1798
- actions[0 /* Actions.APPEND */]();
1683
+ function formatMessagePart(ctx, node) {
1684
+ const type = node.t || node.type;
1685
+ switch (type) {
1686
+ case 3 /* NodeTypes.Text */: {
1687
+ const text = node;
1688
+ return (text.v || text.value);
1799
1689
  }
1800
- else {
1801
- subPathDepth = 0;
1802
- if (key === undefined) {
1803
- return false;
1804
- }
1805
- key = formatSubPath(key);
1806
- if (key === false) {
1807
- return false;
1808
- }
1809
- else {
1810
- actions[1 /* Actions.PUSH */]();
1811
- }
1690
+ case 9 /* NodeTypes.Literal */: {
1691
+ const literal = node;
1692
+ return (literal.v || literal.value);
1812
1693
  }
1813
- };
1814
- function maybeUnescapeQuote() {
1815
- const nextChar = path[index + 1];
1816
- if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
1817
- nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
1818
- (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
1819
- nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
1820
- index++;
1821
- newChar = '\\' + nextChar;
1822
- actions[0 /* Actions.APPEND */]();
1823
- return true;
1694
+ case 4 /* NodeTypes.Named */: {
1695
+ const named = node;
1696
+ return ctx.interpolate(ctx.named(named.k || named.key));
1824
1697
  }
1825
- }
1826
- while (mode !== null) {
1827
- index++;
1828
- c = path[index];
1829
- if (c === '\\' && maybeUnescapeQuote()) {
1830
- continue;
1698
+ case 5 /* NodeTypes.List */: {
1699
+ const list = node;
1700
+ return ctx.interpolate(ctx.list(list.i != null ? list.i : list.index));
1831
1701
  }
1832
- type = getPathCharType(c);
1833
- typeMap = pathStateMachine[mode];
1834
- transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
1835
- // check parse error
1836
- if (transition === 8 /* States.ERROR */) {
1837
- return;
1702
+ case 6 /* NodeTypes.Linked */: {
1703
+ const linked = node;
1704
+ const modifier = linked.m || linked.modifier;
1705
+ return ctx.linked(formatMessagePart(ctx, linked.k || linked.key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);
1838
1706
  }
1839
- mode = transition[0];
1840
- if (transition[1] !== undefined) {
1841
- action = actions[transition[1]];
1842
- if (action) {
1843
- newChar = c;
1844
- if (action() === false) {
1845
- return;
1846
- }
1847
- }
1707
+ case 7 /* NodeTypes.LinkedKey */: {
1708
+ const linkedKey = node;
1709
+ return (linkedKey.v || linkedKey.value);
1848
1710
  }
1849
- // check parse finish
1850
- if (mode === 7 /* States.AFTER_PATH */) {
1851
- return keys;
1711
+ case 8 /* NodeTypes.LinkedModifier */: {
1712
+ const linkedModifier = node;
1713
+ return (linkedModifier.v || linkedModifier.value);
1852
1714
  }
1715
+ default:
1716
+ throw new Error(`unhandled node type on format message part: ${type}`);
1853
1717
  }
1854
1718
  }
1855
- // path token cache
1856
- const cache = new Map();
1857
- /**
1858
- * key-value message resolver
1859
- *
1860
- * @remarks
1861
- * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
1862
- *
1863
- * @param obj - A target object to be resolved with path
1864
- * @param path - A {@link Path | path} to resolve the value of message
1865
- *
1866
- * @returns A resolved {@link PathValue | path value}
1867
- *
1868
- * @VueI18nGeneral
1869
- */
1870
- function resolveWithKeyValue(obj, path) {
1871
- return isObject(obj) ? obj[path] : null;
1872
- }
1873
- /**
1874
- * message resolver
1875
- *
1876
- * @remarks
1877
- * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
1878
- *
1879
- * @param obj - A target object to be resolved with path
1880
- * @param path - A {@link Path | path} to resolve the value of message
1881
- *
1882
- * @returns A resolved {@link PathValue | path value}
1883
- *
1884
- * @VueI18nGeneral
1885
- */
1886
- function resolveValue(obj, path) {
1887
- // check object
1888
- if (!isObject(obj)) {
1889
- return null;
1890
- }
1891
- // parse path
1892
- let hit = cache.get(path);
1893
- if (!hit) {
1894
- hit = parse(path);
1895
- if (hit) {
1896
- cache.set(path, hit);
1897
- }
1898
- }
1899
- // check hit
1900
- if (!hit) {
1901
- return null;
1902
- }
1903
- // resolve path value
1904
- const len = hit.length;
1905
- let last = obj;
1906
- let i = 0;
1907
- while (i < len) {
1908
- const val = last[hit[i]];
1909
- if (val === undefined) {
1910
- return null;
1911
- }
1912
- if (isFunction(last)) {
1913
- return null;
1914
- }
1915
- last = val;
1916
- i++;
1917
- }
1918
- return last;
1919
- }
1920
1719
 
1921
- const DEFAULT_MODIFIER = (str) => str;
1922
- const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
1923
- const DEFAULT_MESSAGE_DATA_TYPE = 'text';
1924
- const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);
1925
- const DEFAULT_INTERPOLATE = toDisplayString;
1926
- function pluralDefault(choice, choicesLength) {
1927
- choice = Math.abs(choice);
1928
- if (choicesLength === 2) {
1929
- // prettier-ignore
1930
- return choice
1931
- ? choice > 1
1932
- ? 1
1933
- : 0
1934
- : 1;
1720
+ const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
1721
+ function checkHtmlMessage(source, warnHtmlMessage) {
1722
+ if (warnHtmlMessage && detectHtmlTag(source)) {
1723
+ warn(format$1(WARN_MESSAGE, { source }));
1935
1724
  }
1936
- return choice ? Math.min(choice, 2) : 0;
1937
- }
1938
- function getPluralIndex(options) {
1939
- // prettier-ignore
1940
- const index = isNumber(options.pluralIndex)
1941
- ? options.pluralIndex
1942
- : -1;
1943
- // prettier-ignore
1944
- return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
1945
- ? isNumber(options.named.count)
1946
- ? options.named.count
1947
- : isNumber(options.named.n)
1948
- ? options.named.n
1949
- : index
1950
- : index;
1951
1725
  }
1952
- function normalizeNamed(pluralIndex, props) {
1953
- if (!props.count) {
1954
- props.count = pluralIndex;
1955
- }
1956
- if (!props.n) {
1957
- props.n = pluralIndex;
1958
- }
1726
+ const defaultOnCacheKey = (message) => message;
1727
+ let compileCache = Object.create(null);
1728
+ function clearCompileCache() {
1729
+ compileCache = Object.create(null);
1959
1730
  }
1960
- function createMessageContext(options = {}) {
1961
- const locale = options.locale;
1962
- const pluralIndex = getPluralIndex(options);
1963
- const pluralRule = isObject(options.pluralRules) &&
1964
- isString(locale) &&
1965
- isFunction(options.pluralRules[locale])
1966
- ? options.pluralRules[locale]
1967
- : pluralDefault;
1968
- const orgPluralRule = isObject(options.pluralRules) &&
1969
- isString(locale) &&
1970
- isFunction(options.pluralRules[locale])
1971
- ? pluralDefault
1972
- : undefined;
1973
- const plural = (messages) => {
1974
- return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
1731
+ const isMessageAST = (val) => isObject(val) &&
1732
+ (val.t === 0 || val.type === 0) &&
1733
+ ('b' in val || 'body' in val);
1734
+ function baseCompile(message, options = {}) {
1735
+ // error detecting on compile
1736
+ let detectError = false;
1737
+ const onError = options.onError || defaultOnError;
1738
+ options.onError = (err) => {
1739
+ detectError = true;
1740
+ onError(err);
1975
1741
  };
1976
- const _list = options.list || [];
1977
- const list = (index) => _list[index];
1978
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1979
- const _named = options.named || {};
1980
- isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
1981
- const named = (key) => _named[key];
1982
- function message(key) {
1983
- // prettier-ignore
1984
- const msg = isFunction(options.messages)
1985
- ? options.messages(key)
1986
- : isObject(options.messages)
1987
- ? options.messages[key]
1988
- : false;
1989
- return !msg
1990
- ? options.parent
1991
- ? options.parent.message(key) // resolve from parent messages
1992
- : DEFAULT_MESSAGE
1742
+ // compile with mesasge-compiler
1743
+ return { ...baseCompile$1(message, options), detectError };
1744
+ }
1745
+ /* #__NO_SIDE_EFFECTS__ */
1746
+ function compile(message, context) {
1747
+ if (isString(message)) {
1748
+ // check HTML message
1749
+ const warnHtmlMessage = isBoolean(context.warnHtmlMessage)
1750
+ ? context.warnHtmlMessage
1751
+ : true;
1752
+ checkHtmlMessage(message, warnHtmlMessage);
1753
+ // check caches
1754
+ const onCacheKey = context.onCacheKey || defaultOnCacheKey;
1755
+ const cacheKey = onCacheKey(message);
1756
+ const cached = compileCache[cacheKey];
1757
+ if (cached) {
1758
+ return cached;
1759
+ }
1760
+ // compile with JIT mode
1761
+ const { ast, detectError } = baseCompile(message, {
1762
+ ...context,
1763
+ location: true,
1764
+ jit: true
1765
+ });
1766
+ // compose message function from AST
1767
+ const msg = format(ast);
1768
+ // if occurred compile error, don't cache
1769
+ return !detectError
1770
+ ? (compileCache[cacheKey] = msg)
1993
1771
  : msg;
1994
1772
  }
1995
- const _modifier = (name) => options.modifiers
1996
- ? options.modifiers[name]
1997
- : DEFAULT_MODIFIER;
1998
- const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
1999
- ? options.processor.normalize
2000
- : DEFAULT_NORMALIZE;
2001
- const interpolate = isPlainObject(options.processor) &&
2002
- isFunction(options.processor.interpolate)
2003
- ? options.processor.interpolate
2004
- : DEFAULT_INTERPOLATE;
2005
- const type = isPlainObject(options.processor) && isString(options.processor.type)
2006
- ? options.processor.type
2007
- : DEFAULT_MESSAGE_DATA_TYPE;
2008
- const linked = (key, ...args) => {
2009
- const [arg1, arg2] = args;
2010
- let type = 'text';
2011
- let modifier = '';
2012
- if (args.length === 1) {
2013
- if (isObject(arg1)) {
2014
- modifier = arg1.modifier || modifier;
2015
- type = arg1.type || type;
2016
- }
2017
- else if (isString(arg1)) {
2018
- modifier = arg1 || modifier;
2019
- }
1773
+ else {
1774
+ if (!isMessageAST(message)) {
1775
+ warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);
1776
+ return (() => message);
2020
1777
  }
2021
- else if (args.length === 2) {
2022
- if (isString(arg1)) {
2023
- modifier = arg1 || modifier;
2024
- }
2025
- if (isString(arg2)) {
2026
- type = arg2 || type;
1778
+ // AST case (passed from bundler)
1779
+ const cacheKey = message.cacheKey;
1780
+ if (cacheKey) {
1781
+ const cached = compileCache[cacheKey];
1782
+ if (cached) {
1783
+ return cached;
2027
1784
  }
1785
+ // compose message function from message (AST)
1786
+ return (compileCache[cacheKey] =
1787
+ format(message));
2028
1788
  }
2029
- const ret = message(key)(ctx);
2030
- const msg =
2031
- // The message in vnode resolved with linked are returned as an array by processor.nomalize
2032
- type === 'vnode' && isArray(ret) && modifier
2033
- ? ret[0]
2034
- : ret;
2035
- return modifier ? _modifier(modifier)(msg, type) : msg;
2036
- };
2037
- const ctx = {
2038
- ["list" /* HelperNameMap.LIST */]: list,
2039
- ["named" /* HelperNameMap.NAMED */]: named,
2040
- ["plural" /* HelperNameMap.PLURAL */]: plural,
2041
- ["linked" /* HelperNameMap.LINKED */]: linked,
2042
- ["message" /* HelperNameMap.MESSAGE */]: message,
2043
- ["type" /* HelperNameMap.TYPE */]: type,
2044
- ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
2045
- ["normalize" /* HelperNameMap.NORMALIZE */]: normalize,
2046
- ["values" /* HelperNameMap.VALUES */]: assign({}, _list, _named)
2047
- };
2048
- return ctx;
1789
+ else {
1790
+ return format(message);
1791
+ }
1792
+ }
2049
1793
  }
2050
1794
 
2051
1795
  let devtools = null;
@@ -2071,30 +1815,6 @@ var IntlifyCoreBase = (function (exports) {
2071
1815
  return (payloads) => devtools && devtools.emit(hook, payloads);
2072
1816
  }
2073
1817
 
2074
- const CoreWarnCodes = {
2075
- NOT_FOUND_KEY: 1,
2076
- FALLBACK_TO_TRANSLATE: 2,
2077
- CANNOT_FORMAT_NUMBER: 3,
2078
- FALLBACK_TO_NUMBER_FORMAT: 4,
2079
- CANNOT_FORMAT_DATE: 5,
2080
- FALLBACK_TO_DATE_FORMAT: 6,
2081
- EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: 7
2082
- };
2083
- const CORE_WARN_CODES_EXTEND_POINT = 8;
2084
- /** @internal */
2085
- const warnMessages = {
2086
- [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
2087
- [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
2088
- [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
2089
- [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
2090
- [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
2091
- [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
2092
- [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.`
2093
- };
2094
- function getWarnMessage(code, ...args) {
2095
- return format$1(warnMessages[code], ...args);
2096
- }
2097
-
2098
1818
  const CoreErrorCodes = {
2099
1819
  INVALID_ARGUMENT: COMPILE_ERROR_CODES_EXTEND_POINT, // 17
2100
1820
  INVALID_DATE_ARGUMENT: 18,
@@ -2268,66 +1988,358 @@ var IntlifyCoreBase = (function (exports) {
2268
1988
  return follow;
2269
1989
  }
2270
1990
 
2271
- /* eslint-disable @typescript-eslint/no-explicit-any */
2272
- /**
2273
- * Intlify core-base version
2274
- * @internal
2275
- */
2276
- const VERSION = '10.0.0-beta.5';
2277
- const NOT_REOSLVED = -1;
2278
- const DEFAULT_LOCALE = 'en-US';
2279
- const MISSING_RESOLVE_VALUE = '';
2280
- const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
2281
- function getDefaultLinkedModifiers() {
2282
- return {
2283
- upper: (val, type) => {
2284
- // prettier-ignore
2285
- return type === 'text' && isString(val)
2286
- ? val.toUpperCase()
2287
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
2288
- ? val.children.toUpperCase()
2289
- : val;
2290
- },
2291
- lower: (val, type) => {
2292
- // prettier-ignore
2293
- return type === 'text' && isString(val)
2294
- ? val.toLowerCase()
2295
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
2296
- ? val.children.toLowerCase()
2297
- : val;
2298
- },
2299
- capitalize: (val, type) => {
2300
- // prettier-ignore
2301
- return (type === 'text' && isString(val)
2302
- ? capitalize(val)
2303
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
2304
- ? capitalize(val.children)
2305
- : val);
1991
+ const pathStateMachine = [];
1992
+ pathStateMachine[0 /* States.BEFORE_PATH */] = {
1993
+ ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
1994
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
1995
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
1996
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
1997
+ };
1998
+ pathStateMachine[1 /* States.IN_PATH */] = {
1999
+ ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
2000
+ ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
2001
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
2002
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
2003
+ };
2004
+ pathStateMachine[2 /* States.BEFORE_IDENT */] = {
2005
+ ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
2006
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
2007
+ ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
2008
+ };
2009
+ pathStateMachine[3 /* States.IN_IDENT */] = {
2010
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
2011
+ ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
2012
+ ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
2013
+ ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
2014
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
2015
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
2016
+ };
2017
+ pathStateMachine[4 /* States.IN_SUB_PATH */] = {
2018
+ ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
2019
+ ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
2020
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [
2021
+ 4 /* States.IN_SUB_PATH */,
2022
+ 2 /* Actions.INC_SUB_PATH_DEPTH */
2023
+ ],
2024
+ ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
2025
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
2026
+ ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
2027
+ };
2028
+ pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
2029
+ ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
2030
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
2031
+ ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
2032
+ };
2033
+ pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
2034
+ ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
2035
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
2036
+ ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
2037
+ };
2038
+ /**
2039
+ * Check if an expression is a literal value.
2040
+ */
2041
+ const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
2042
+ function isLiteral(exp) {
2043
+ return literalValueRE.test(exp);
2044
+ }
2045
+ /**
2046
+ * Strip quotes from a string
2047
+ */
2048
+ function stripQuotes(str) {
2049
+ const a = str.charCodeAt(0);
2050
+ const b = str.charCodeAt(str.length - 1);
2051
+ return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
2052
+ }
2053
+ /**
2054
+ * Determine the type of a character in a keypath.
2055
+ */
2056
+ function getPathCharType(ch) {
2057
+ if (ch === undefined || ch === null) {
2058
+ return "o" /* PathCharTypes.END_OF_FAIL */;
2059
+ }
2060
+ const code = ch.charCodeAt(0);
2061
+ switch (code) {
2062
+ case 0x5b: // [
2063
+ case 0x5d: // ]
2064
+ case 0x2e: // .
2065
+ case 0x22: // "
2066
+ case 0x27: // '
2067
+ return ch;
2068
+ case 0x5f: // _
2069
+ case 0x24: // $
2070
+ case 0x2d: // -
2071
+ return "i" /* PathCharTypes.IDENT */;
2072
+ case 0x09: // Tab (HT)
2073
+ case 0x0a: // Newline (LF)
2074
+ case 0x0d: // Return (CR)
2075
+ case 0xa0: // No-break space (NBSP)
2076
+ case 0xfeff: // Byte Order Mark (BOM)
2077
+ case 0x2028: // Line Separator (LS)
2078
+ case 0x2029: // Paragraph Separator (PS)
2079
+ return "w" /* PathCharTypes.WORKSPACE */;
2080
+ }
2081
+ return "i" /* PathCharTypes.IDENT */;
2082
+ }
2083
+ /**
2084
+ * Format a subPath, return its plain form if it is
2085
+ * a literal string or number. Otherwise prepend the
2086
+ * dynamic indicator (*).
2087
+ */
2088
+ function formatSubPath(path) {
2089
+ const trimmed = path.trim();
2090
+ // invalid leading 0
2091
+ if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
2092
+ return false;
2093
+ }
2094
+ return isLiteral(trimmed)
2095
+ ? stripQuotes(trimmed)
2096
+ : "*" /* PathCharTypes.ASTARISK */ + trimmed;
2097
+ }
2098
+ /**
2099
+ * Parse a string path into an array of segments
2100
+ */
2101
+ function parse(path) {
2102
+ const keys = [];
2103
+ let index = -1;
2104
+ let mode = 0 /* States.BEFORE_PATH */;
2105
+ let subPathDepth = 0;
2106
+ let c;
2107
+ let key; // eslint-disable-line
2108
+ let newChar;
2109
+ let type;
2110
+ let transition;
2111
+ let action;
2112
+ let typeMap;
2113
+ const actions = [];
2114
+ actions[0 /* Actions.APPEND */] = () => {
2115
+ if (key === undefined) {
2116
+ key = newChar;
2117
+ }
2118
+ else {
2119
+ key += newChar;
2306
2120
  }
2307
2121
  };
2122
+ actions[1 /* Actions.PUSH */] = () => {
2123
+ if (key !== undefined) {
2124
+ keys.push(key);
2125
+ key = undefined;
2126
+ }
2127
+ };
2128
+ actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
2129
+ actions[0 /* Actions.APPEND */]();
2130
+ subPathDepth++;
2131
+ };
2132
+ actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
2133
+ if (subPathDepth > 0) {
2134
+ subPathDepth--;
2135
+ mode = 4 /* States.IN_SUB_PATH */;
2136
+ actions[0 /* Actions.APPEND */]();
2137
+ }
2138
+ else {
2139
+ subPathDepth = 0;
2140
+ if (key === undefined) {
2141
+ return false;
2142
+ }
2143
+ key = formatSubPath(key);
2144
+ if (key === false) {
2145
+ return false;
2146
+ }
2147
+ else {
2148
+ actions[1 /* Actions.PUSH */]();
2149
+ }
2150
+ }
2151
+ };
2152
+ function maybeUnescapeQuote() {
2153
+ const nextChar = path[index + 1];
2154
+ if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
2155
+ nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
2156
+ (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
2157
+ nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
2158
+ index++;
2159
+ newChar = '\\' + nextChar;
2160
+ actions[0 /* Actions.APPEND */]();
2161
+ return true;
2162
+ }
2163
+ }
2164
+ while (mode !== null) {
2165
+ index++;
2166
+ c = path[index];
2167
+ if (c === '\\' && maybeUnescapeQuote()) {
2168
+ continue;
2169
+ }
2170
+ type = getPathCharType(c);
2171
+ typeMap = pathStateMachine[mode];
2172
+ transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
2173
+ // check parse error
2174
+ if (transition === 8 /* States.ERROR */) {
2175
+ return;
2176
+ }
2177
+ mode = transition[0];
2178
+ if (transition[1] !== undefined) {
2179
+ action = actions[transition[1]];
2180
+ if (action) {
2181
+ newChar = c;
2182
+ if (action() === false) {
2183
+ return;
2184
+ }
2185
+ }
2186
+ }
2187
+ // check parse finish
2188
+ if (mode === 7 /* States.AFTER_PATH */) {
2189
+ return keys;
2190
+ }
2191
+ }
2308
2192
  }
2309
- let _compiler;
2310
- function registerMessageCompiler(compiler) {
2311
- _compiler = compiler;
2312
- }
2313
- let _resolver;
2193
+ // path token cache
2194
+ const cache = new Map();
2314
2195
  /**
2315
- * Register the message resolver
2196
+ * key-value message resolver
2316
2197
  *
2317
- * @param resolver - A {@link MessageResolver} function
2198
+ * @remarks
2199
+ * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
2200
+ *
2201
+ * @param obj - A target object to be resolved with path
2202
+ * @param path - A {@link Path | path} to resolve the value of message
2203
+ *
2204
+ * @returns A resolved {@link PathValue | path value}
2318
2205
  *
2319
2206
  * @VueI18nGeneral
2320
2207
  */
2321
- function registerMessageResolver(resolver) {
2322
- _resolver = resolver;
2208
+ function resolveWithKeyValue(obj, path) {
2209
+ return isObject(obj) ? obj[path] : null;
2323
2210
  }
2324
- let _fallbacker;
2325
2211
  /**
2326
- * Register the locale fallbacker
2212
+ * message resolver
2327
2213
  *
2328
- * @param fallbacker - A {@link LocaleFallbacker} function
2214
+ * @remarks
2215
+ * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
2329
2216
  *
2330
- * @VueI18nGeneral
2217
+ * @param obj - A target object to be resolved with path
2218
+ * @param path - A {@link Path | path} to resolve the value of message
2219
+ *
2220
+ * @returns A resolved {@link PathValue | path value}
2221
+ *
2222
+ * @VueI18nGeneral
2223
+ */
2224
+ function resolveValue(obj, path) {
2225
+ // check object
2226
+ if (!isObject(obj)) {
2227
+ return null;
2228
+ }
2229
+ // parse path
2230
+ let hit = cache.get(path);
2231
+ if (!hit) {
2232
+ hit = parse(path);
2233
+ if (hit) {
2234
+ cache.set(path, hit);
2235
+ }
2236
+ }
2237
+ // check hit
2238
+ if (!hit) {
2239
+ return null;
2240
+ }
2241
+ // resolve path value
2242
+ const len = hit.length;
2243
+ let last = obj;
2244
+ let i = 0;
2245
+ while (i < len) {
2246
+ const val = last[hit[i]];
2247
+ if (val === undefined) {
2248
+ return null;
2249
+ }
2250
+ if (isFunction(last)) {
2251
+ return null;
2252
+ }
2253
+ last = val;
2254
+ i++;
2255
+ }
2256
+ return last;
2257
+ }
2258
+
2259
+ const CoreWarnCodes = {
2260
+ NOT_FOUND_KEY: 1,
2261
+ FALLBACK_TO_TRANSLATE: 2,
2262
+ CANNOT_FORMAT_NUMBER: 3,
2263
+ FALLBACK_TO_NUMBER_FORMAT: 4,
2264
+ CANNOT_FORMAT_DATE: 5,
2265
+ FALLBACK_TO_DATE_FORMAT: 6,
2266
+ EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: 7
2267
+ };
2268
+ const CORE_WARN_CODES_EXTEND_POINT = 8;
2269
+ /** @internal */
2270
+ const warnMessages = {
2271
+ [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
2272
+ [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
2273
+ [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
2274
+ [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
2275
+ [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
2276
+ [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
2277
+ [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.`
2278
+ };
2279
+ function getWarnMessage(code, ...args) {
2280
+ return format$1(warnMessages[code], ...args);
2281
+ }
2282
+
2283
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2284
+ /**
2285
+ * Intlify core-base version
2286
+ * @internal
2287
+ */
2288
+ const VERSION = '10.0.0-rc.1';
2289
+ const NOT_REOSLVED = -1;
2290
+ const DEFAULT_LOCALE = 'en-US';
2291
+ const MISSING_RESOLVE_VALUE = '';
2292
+ const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
2293
+ function getDefaultLinkedModifiers() {
2294
+ return {
2295
+ upper: (val, type) => {
2296
+ // prettier-ignore
2297
+ return type === 'text' && isString(val)
2298
+ ? val.toUpperCase()
2299
+ : type === 'vnode' && isObject(val) && '__v_isVNode' in val
2300
+ ? val.children.toUpperCase()
2301
+ : val;
2302
+ },
2303
+ lower: (val, type) => {
2304
+ // prettier-ignore
2305
+ return type === 'text' && isString(val)
2306
+ ? val.toLowerCase()
2307
+ : type === 'vnode' && isObject(val) && '__v_isVNode' in val
2308
+ ? val.children.toLowerCase()
2309
+ : val;
2310
+ },
2311
+ capitalize: (val, type) => {
2312
+ // prettier-ignore
2313
+ return (type === 'text' && isString(val)
2314
+ ? capitalize(val)
2315
+ : type === 'vnode' && isObject(val) && '__v_isVNode' in val
2316
+ ? capitalize(val.children)
2317
+ : val);
2318
+ }
2319
+ };
2320
+ }
2321
+ let _compiler;
2322
+ function registerMessageCompiler(compiler) {
2323
+ _compiler = compiler;
2324
+ }
2325
+ let _resolver;
2326
+ /**
2327
+ * Register the message resolver
2328
+ *
2329
+ * @param resolver - A {@link MessageResolver} function
2330
+ *
2331
+ * @VueI18nGeneral
2332
+ */
2333
+ function registerMessageResolver(resolver) {
2334
+ _resolver = resolver;
2335
+ }
2336
+ let _fallbacker;
2337
+ /**
2338
+ * Register the locale fallbacker
2339
+ *
2340
+ * @param fallbacker - A {@link LocaleFallbacker} function
2341
+ *
2342
+ * @VueI18nGeneral
2331
2343
  */
2332
2344
  function registerLocaleFallbacker(fallbacker) {
2333
2345
  _fallbacker = fallbacker;
@@ -2426,670 +2438,288 @@ var IntlifyCoreBase = (function (exports) {
2426
2438
  missing,
2427
2439
  missingWarn,
2428
2440
  fallbackWarn,
2429
- fallbackFormat,
2430
- unresolving,
2431
- postTranslation,
2432
- processor,
2433
- warnHtmlMessage,
2434
- escapeParameter,
2435
- messageCompiler,
2436
- messageResolver,
2437
- localeFallbacker,
2438
- fallbackContext,
2439
- onWarn,
2440
- __meta
2441
- };
2442
- {
2443
- context.datetimeFormats = datetimeFormats;
2444
- context.numberFormats = numberFormats;
2445
- context.__datetimeFormatters = __datetimeFormatters;
2446
- context.__numberFormatters = __numberFormatters;
2447
- }
2448
- // for vue-devtools timeline event
2449
- {
2450
- context.__v_emitter =
2451
- internalOptions.__v_emitter != null
2452
- ? internalOptions.__v_emitter
2453
- : undefined;
2454
- }
2455
- // NOTE: experimental !!
2456
- {
2457
- initI18nDevTools(context, version, __meta);
2458
- }
2459
- return context;
2460
- }
2461
- /** @internal */
2462
- function isTranslateFallbackWarn(fallback, key) {
2463
- return fallback instanceof RegExp ? fallback.test(key) : fallback;
2464
- }
2465
- /** @internal */
2466
- function isTranslateMissingWarn(missing, key) {
2467
- return missing instanceof RegExp ? missing.test(key) : missing;
2468
- }
2469
- /** @internal */
2470
- function handleMissing(context, key, locale, missingWarn, type) {
2471
- const { missing, onWarn } = context;
2472
- // for vue-devtools timeline event
2473
- {
2474
- const emitter = context.__v_emitter;
2475
- if (emitter) {
2476
- emitter.emit('missing', {
2477
- locale,
2478
- key,
2479
- type,
2480
- groupId: `${type}:${key}`
2481
- });
2482
- }
2483
- }
2484
- if (missing !== null) {
2485
- const ret = missing(context, locale, key, type);
2486
- return isString(ret) ? ret : key;
2487
- }
2488
- else {
2489
- if (isTranslateMissingWarn(missingWarn, key)) {
2490
- onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
2491
- }
2492
- return key;
2493
- }
2494
- }
2495
- /** @internal */
2496
- function updateFallbackLocale(ctx, locale, fallback) {
2497
- const context = ctx;
2498
- context.__localeChainCache = new Map();
2499
- ctx.localeFallbacker(ctx, fallback, locale);
2500
- }
2501
- /** @internal */
2502
- function isAlmostSameLocale(locale, compareLocale) {
2503
- if (locale === compareLocale)
2504
- return false;
2505
- return locale.split('-')[0] === compareLocale.split('-')[0];
2506
- }
2507
- /** @internal */
2508
- function isImplicitFallback(targetLocale, locales) {
2509
- const index = locales.indexOf(targetLocale);
2510
- if (index === -1) {
2511
- return false;
2512
- }
2513
- for (let i = index + 1; i < locales.length; i++) {
2514
- if (isAlmostSameLocale(targetLocale, locales[i])) {
2515
- return true;
2516
- }
2517
- }
2518
- return false;
2519
- }
2520
- /* eslint-enable @typescript-eslint/no-explicit-any */
2521
-
2522
- function format(ast) {
2523
- const msg = (ctx) => formatParts(ctx, ast);
2524
- return msg;
2525
- }
2526
- function formatParts(ctx, ast) {
2527
- const body = ast.b || ast.body;
2528
- if ((body.t || body.type) === 1 /* NodeTypes.Plural */) {
2529
- const plural = body;
2530
- const cases = plural.c || plural.cases;
2531
- return ctx.plural(cases.reduce((messages, c) => [
2532
- ...messages,
2533
- formatMessageParts(ctx, c)
2534
- ], []));
2535
- }
2536
- else {
2537
- return formatMessageParts(ctx, body);
2538
- }
2539
- }
2540
- function formatMessageParts(ctx, node) {
2541
- const _static = node.s || node.static;
2542
- if (_static) {
2543
- return ctx.type === 'text'
2544
- ? _static
2545
- : ctx.normalize([_static]);
2546
- }
2547
- else {
2548
- const messages = (node.i || node.items).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
2549
- return ctx.normalize(messages);
2550
- }
2551
- }
2552
- function formatMessagePart(ctx, node) {
2553
- const type = node.t || node.type;
2554
- switch (type) {
2555
- case 3 /* NodeTypes.Text */: {
2556
- const text = node;
2557
- return (text.v || text.value);
2558
- }
2559
- case 9 /* NodeTypes.Literal */: {
2560
- const literal = node;
2561
- return (literal.v || literal.value);
2562
- }
2563
- case 4 /* NodeTypes.Named */: {
2564
- const named = node;
2565
- return ctx.interpolate(ctx.named(named.k || named.key));
2566
- }
2567
- case 5 /* NodeTypes.List */: {
2568
- const list = node;
2569
- return ctx.interpolate(ctx.list(list.i != null ? list.i : list.index));
2570
- }
2571
- case 6 /* NodeTypes.Linked */: {
2572
- const linked = node;
2573
- const modifier = linked.m || linked.modifier;
2574
- return ctx.linked(formatMessagePart(ctx, linked.k || linked.key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);
2575
- }
2576
- case 7 /* NodeTypes.LinkedKey */: {
2577
- const linkedKey = node;
2578
- return (linkedKey.v || linkedKey.value);
2579
- }
2580
- case 8 /* NodeTypes.LinkedModifier */: {
2581
- const linkedModifier = node;
2582
- return (linkedModifier.v || linkedModifier.value);
2583
- }
2584
- default:
2585
- throw new Error(`unhandled node type on format message part: ${type}`);
2586
- }
2587
- }
2588
-
2589
- const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
2590
- function checkHtmlMessage(source, warnHtmlMessage) {
2591
- if (warnHtmlMessage && detectHtmlTag(source)) {
2592
- warn(format$1(WARN_MESSAGE, { source }));
2593
- }
2594
- }
2595
- const defaultOnCacheKey = (message) => message;
2596
- let compileCache = Object.create(null);
2597
- function clearCompileCache() {
2598
- compileCache = Object.create(null);
2599
- }
2600
- const isMessageAST = (val) => isObject(val) &&
2601
- (val.t === 0 || val.type === 0) &&
2602
- ('b' in val || 'body' in val);
2603
- function baseCompile(message, options = {}) {
2604
- // error detecting on compile
2605
- let detectError = false;
2606
- const onError = options.onError || defaultOnError;
2607
- options.onError = (err) => {
2608
- detectError = true;
2609
- onError(err);
2610
- };
2611
- // compile with mesasge-compiler
2612
- return { ...baseCompile$1(message, options), detectError };
2613
- }
2614
- /* #__NO_SIDE_EFFECTS__ */
2615
- function compile(message, context) {
2616
- if (isString(message)) {
2617
- // check HTML message
2618
- const warnHtmlMessage = isBoolean(context.warnHtmlMessage)
2619
- ? context.warnHtmlMessage
2620
- : true;
2621
- checkHtmlMessage(message, warnHtmlMessage);
2622
- // check caches
2623
- const onCacheKey = context.onCacheKey || defaultOnCacheKey;
2624
- const cacheKey = onCacheKey(message);
2625
- const cached = compileCache[cacheKey];
2626
- if (cached) {
2627
- return cached;
2628
- }
2629
- // compile with JIT mode
2630
- const { ast, detectError } = baseCompile(message, {
2631
- ...context,
2632
- location: true,
2633
- jit: true
2634
- });
2635
- // compose message function from AST
2636
- const msg = format(ast);
2637
- // if occurred compile error, don't cache
2638
- return !detectError
2639
- ? (compileCache[cacheKey] = msg)
2640
- : msg;
2641
- }
2642
- else {
2643
- if (!isMessageAST(message)) {
2644
- warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);
2645
- return (() => message);
2646
- }
2647
- // AST case (passed from bundler)
2648
- const cacheKey = message.cacheKey;
2649
- if (cacheKey) {
2650
- const cached = compileCache[cacheKey];
2651
- if (cached) {
2652
- return cached;
2653
- }
2654
- // compose message function from message (AST)
2655
- return (compileCache[cacheKey] =
2656
- format(message));
2657
- }
2658
- else {
2659
- return format(message);
2660
- }
2661
- }
2662
- }
2663
-
2664
- const NOOP_MESSAGE_FUNCTION = () => '';
2665
- const isMessageFunction = (val) => isFunction(val);
2666
- // implementation of `translate` function
2667
- function translate(context, ...args) {
2668
- const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
2669
- const [key, options] = parseTranslateArgs(...args);
2670
- const missingWarn = isBoolean(options.missingWarn)
2671
- ? options.missingWarn
2672
- : context.missingWarn;
2673
- const fallbackWarn = isBoolean(options.fallbackWarn)
2674
- ? options.fallbackWarn
2675
- : context.fallbackWarn;
2676
- const escapeParameter = isBoolean(options.escapeParameter)
2677
- ? options.escapeParameter
2678
- : context.escapeParameter;
2679
- const resolvedMessage = !!options.resolvedMessage;
2680
- // prettier-ignore
2681
- const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
2682
- ? !isBoolean(options.default)
2683
- ? options.default
2684
- : (!messageCompiler ? () => key : key)
2685
- : fallbackFormat // default by `fallbackFormat` option
2686
- ? (!messageCompiler ? () => key : key)
2687
- : null;
2688
- const enableDefaultMsg = fallbackFormat ||
2689
- (defaultMsgOrKey != null &&
2690
- (isString(defaultMsgOrKey) || isFunction(defaultMsgOrKey)));
2691
- const locale = getLocale(context, options);
2692
- // escape params
2693
- escapeParameter && escapeParams(options);
2694
- // resolve message format
2695
- // eslint-disable-next-line prefer-const
2696
- let [formatScope, targetLocale, message] = !resolvedMessage
2697
- ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
2698
- : [
2699
- key,
2700
- locale,
2701
- messages[locale] || {}
2702
- ];
2703
- // NOTE:
2704
- // Fix to work around `ssrTransfrom` bug in Vite.
2705
- // https://github.com/vitejs/vite/issues/4306
2706
- // To get around this, use temporary variables.
2707
- // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
2708
- let format = formatScope;
2709
- // if you use default message, set it as message format!
2710
- let cacheBaseKey = key;
2711
- if (!resolvedMessage &&
2712
- !(isString(format) ||
2713
- isMessageAST(format) ||
2714
- isMessageFunction(format))) {
2715
- if (enableDefaultMsg) {
2716
- format = defaultMsgOrKey;
2717
- cacheBaseKey = format;
2718
- }
2719
- }
2720
- // checking message format and target locale
2721
- if (!resolvedMessage &&
2722
- (!(isString(format) ||
2723
- isMessageAST(format) ||
2724
- isMessageFunction(format)) ||
2725
- !isString(targetLocale))) {
2726
- return unresolving ? NOT_REOSLVED : key;
2727
- }
2728
- // TODO: refactor
2729
- if (isString(format) && context.messageCompiler == null) {
2730
- warn(`The message format compilation is not supported in this build. ` +
2731
- `Because message compiler isn't included. ` +
2732
- `You need to pre-compilation all message format. ` +
2733
- `So translate function return '${key}'.`);
2734
- return key;
2735
- }
2736
- // setup compile error detecting
2737
- let occurred = false;
2738
- const onError = () => {
2739
- occurred = true;
2441
+ fallbackFormat,
2442
+ unresolving,
2443
+ postTranslation,
2444
+ processor,
2445
+ warnHtmlMessage,
2446
+ escapeParameter,
2447
+ messageCompiler,
2448
+ messageResolver,
2449
+ localeFallbacker,
2450
+ fallbackContext,
2451
+ onWarn,
2452
+ __meta
2740
2453
  };
2741
- // compile message format
2742
- const msg = !isMessageFunction(format)
2743
- ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
2744
- : format;
2745
- // if occurred compile error, return the message format
2746
- if (occurred) {
2747
- return format;
2454
+ {
2455
+ context.datetimeFormats = datetimeFormats;
2456
+ context.numberFormats = numberFormats;
2457
+ context.__datetimeFormatters = __datetimeFormatters;
2458
+ context.__numberFormatters = __numberFormatters;
2459
+ }
2460
+ // for vue-devtools timeline event
2461
+ {
2462
+ context.__v_emitter =
2463
+ internalOptions.__v_emitter != null
2464
+ ? internalOptions.__v_emitter
2465
+ : undefined;
2748
2466
  }
2749
- // evaluate message with context
2750
- const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
2751
- const msgContext = createMessageContext(ctxOptions);
2752
- const messaged = evaluateMessage(context, msg, msgContext);
2753
- // if use post translation option, proceed it with handler
2754
- const ret = postTranslation
2755
- ? postTranslation(messaged, key)
2756
- : messaged;
2757
2467
  // NOTE: experimental !!
2758
2468
  {
2759
- // prettier-ignore
2760
- const payloads = {
2761
- timestamp: Date.now(),
2762
- key: isString(key)
2763
- ? key
2764
- : isMessageFunction(format)
2765
- ? format.key
2766
- : '',
2767
- locale: targetLocale || (isMessageFunction(format)
2768
- ? format.locale
2769
- : ''),
2770
- format: isString(format)
2771
- ? format
2772
- : isMessageFunction(format)
2773
- ? format.source
2774
- : '',
2775
- message: ret
2776
- };
2777
- payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
2778
- translateDevTools(payloads);
2469
+ initI18nDevTools(context, version, __meta);
2779
2470
  }
2780
- return ret;
2471
+ return context;
2781
2472
  }
2782
- function escapeParams(options) {
2783
- if (isArray(options.list)) {
2784
- options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
2785
- }
2786
- else if (isObject(options.named)) {
2787
- Object.keys(options.named).forEach(key => {
2788
- if (isString(options.named[key])) {
2789
- options.named[key] = escapeHtml(options.named[key]);
2790
- }
2791
- });
2792
- }
2473
+ /** @internal */
2474
+ function isTranslateFallbackWarn(fallback, key) {
2475
+ return fallback instanceof RegExp ? fallback.test(key) : fallback;
2793
2476
  }
2794
- function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
2795
- const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
2796
- const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
2797
- let message = {};
2798
- let targetLocale;
2799
- let format = null;
2800
- let from = locale;
2801
- let to = null;
2802
- const type = 'translate';
2803
- for (let i = 0; i < locales.length; i++) {
2804
- targetLocale = to = locales[i];
2805
- if (locale !== targetLocale &&
2806
- !isAlmostSameLocale(locale, targetLocale) &&
2807
- isTranslateFallbackWarn(fallbackWarn, key)) {
2808
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
2809
- key,
2810
- target: targetLocale
2811
- }));
2812
- }
2813
- // for vue-devtools timeline event
2814
- if (locale !== targetLocale) {
2815
- const emitter = context.__v_emitter;
2816
- if (emitter) {
2817
- emitter.emit('fallback', {
2818
- type,
2819
- key,
2820
- from,
2821
- to,
2822
- groupId: `${type}:${key}`
2823
- });
2824
- }
2825
- }
2826
- message =
2827
- messages[targetLocale] || {};
2828
- // for vue-devtools timeline event
2829
- let start = null;
2830
- let startTag;
2831
- let endTag;
2832
- if (inBrowser) {
2833
- start = window.performance.now();
2834
- startTag = 'intlify-message-resolve-start';
2835
- endTag = 'intlify-message-resolve-end';
2836
- mark && mark(startTag);
2837
- }
2838
- if ((format = resolveValue(message, key)) === null) {
2839
- // if null, resolve with object key path
2840
- format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
2841
- }
2842
- // for vue-devtools timeline event
2843
- if (inBrowser) {
2844
- const end = window.performance.now();
2845
- const emitter = context.__v_emitter;
2846
- if (emitter && start && format) {
2847
- emitter.emit('message-resolve', {
2848
- type: 'message-resolve',
2849
- key,
2850
- message: format,
2851
- time: end - start,
2852
- groupId: `${type}:${key}`
2853
- });
2854
- }
2855
- if (startTag && endTag && mark && measure) {
2856
- mark(endTag);
2857
- measure('intlify message resolve', startTag, endTag);
2858
- }
2859
- }
2860
- if (isString(format) || isMessageAST(format) || isMessageFunction(format)) {
2861
- break;
2862
- }
2863
- if (!isImplicitFallback(targetLocale, locales)) {
2864
- const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
2865
- key, targetLocale, missingWarn, type);
2866
- if (missingRet !== key) {
2867
- format = missingRet;
2868
- }
2869
- }
2870
- from = to;
2871
- }
2872
- return [format, targetLocale, message];
2477
+ /** @internal */
2478
+ function isTranslateMissingWarn(missing, key) {
2479
+ return missing instanceof RegExp ? missing.test(key) : missing;
2873
2480
  }
2874
- function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
2875
- const { messageCompiler, warnHtmlMessage } = context;
2876
- if (isMessageFunction(format)) {
2877
- const msg = format;
2878
- msg.locale = msg.locale || targetLocale;
2879
- msg.key = msg.key || key;
2880
- return msg;
2881
- }
2882
- if (messageCompiler == null) {
2883
- const msg = (() => format);
2884
- msg.locale = targetLocale;
2885
- msg.key = key;
2886
- return msg;
2887
- }
2888
- // for vue-devtools timeline event
2889
- let start = null;
2890
- let startTag;
2891
- let endTag;
2892
- if (inBrowser) {
2893
- start = window.performance.now();
2894
- startTag = 'intlify-message-compilation-start';
2895
- endTag = 'intlify-message-compilation-end';
2896
- mark && mark(startTag);
2897
- }
2898
- const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
2481
+ /** @internal */
2482
+ function handleMissing(context, key, locale, missingWarn, type) {
2483
+ const { missing, onWarn } = context;
2899
2484
  // for vue-devtools timeline event
2900
- if (inBrowser) {
2901
- const end = window.performance.now();
2485
+ {
2902
2486
  const emitter = context.__v_emitter;
2903
- if (emitter && start) {
2904
- emitter.emit('message-compilation', {
2905
- type: 'message-compilation',
2906
- message: format,
2907
- time: end - start,
2908
- groupId: `${'translate'}:${key}`
2487
+ if (emitter) {
2488
+ emitter.emit('missing', {
2489
+ locale,
2490
+ key,
2491
+ type,
2492
+ groupId: `${type}:${key}`
2909
2493
  });
2910
2494
  }
2911
- if (startTag && endTag && mark && measure) {
2912
- mark(endTag);
2913
- measure('intlify message compilation', startTag, endTag);
2914
- }
2915
2495
  }
2916
- msg.locale = targetLocale;
2917
- msg.key = key;
2918
- msg.source = format;
2919
- return msg;
2920
- }
2921
- function evaluateMessage(context, msg, msgCtx) {
2922
- // for vue-devtools timeline event
2923
- let start = null;
2924
- let startTag;
2925
- let endTag;
2926
- if (inBrowser) {
2927
- start = window.performance.now();
2928
- startTag = 'intlify-message-evaluation-start';
2929
- endTag = 'intlify-message-evaluation-end';
2930
- mark && mark(startTag);
2496
+ if (missing !== null) {
2497
+ const ret = missing(context, locale, key, type);
2498
+ return isString(ret) ? ret : key;
2931
2499
  }
2932
- const messaged = msg(msgCtx);
2933
- // for vue-devtools timeline event
2934
- if (inBrowser) {
2935
- const end = window.performance.now();
2936
- const emitter = context.__v_emitter;
2937
- if (emitter && start) {
2938
- emitter.emit('message-evaluation', {
2939
- type: 'message-evaluation',
2940
- value: messaged,
2941
- time: end - start,
2942
- groupId: `${'translate'}:${msg.key}`
2943
- });
2944
- }
2945
- if (startTag && endTag && mark && measure) {
2946
- mark(endTag);
2947
- measure('intlify message evaluation', startTag, endTag);
2500
+ else {
2501
+ if (isTranslateMissingWarn(missingWarn, key)) {
2502
+ onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
2948
2503
  }
2504
+ return key;
2949
2505
  }
2950
- return messaged;
2951
2506
  }
2952
2507
  /** @internal */
2953
- function parseTranslateArgs(...args) {
2954
- const [arg1, arg2, arg3] = args;
2955
- const options = {};
2956
- if (!isString(arg1) &&
2957
- !isNumber(arg1) &&
2958
- !isMessageFunction(arg1) &&
2959
- !isMessageAST(arg1)) {
2960
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
2961
- }
2962
- // prettier-ignore
2963
- const key = isNumber(arg1)
2964
- ? String(arg1)
2965
- : isMessageFunction(arg1)
2966
- ? arg1
2967
- : arg1;
2968
- if (isNumber(arg2)) {
2969
- options.plural = arg2;
2970
- }
2971
- else if (isString(arg2)) {
2972
- options.default = arg2;
2508
+ function updateFallbackLocale(ctx, locale, fallback) {
2509
+ const context = ctx;
2510
+ context.__localeChainCache = new Map();
2511
+ ctx.localeFallbacker(ctx, fallback, locale);
2512
+ }
2513
+ /** @internal */
2514
+ function isAlmostSameLocale(locale, compareLocale) {
2515
+ if (locale === compareLocale)
2516
+ return false;
2517
+ return locale.split('-')[0] === compareLocale.split('-')[0];
2518
+ }
2519
+ /** @internal */
2520
+ function isImplicitFallback(targetLocale, locales) {
2521
+ const index = locales.indexOf(targetLocale);
2522
+ if (index === -1) {
2523
+ return false;
2973
2524
  }
2974
- else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
2975
- options.named = arg2;
2525
+ for (let i = index + 1; i < locales.length; i++) {
2526
+ if (isAlmostSameLocale(targetLocale, locales[i])) {
2527
+ return true;
2528
+ }
2976
2529
  }
2977
- else if (isArray(arg2)) {
2978
- options.list = arg2;
2530
+ return false;
2531
+ }
2532
+ /* eslint-enable @typescript-eslint/no-explicit-any */
2533
+
2534
+ const intlDefined = typeof Intl !== 'undefined';
2535
+ const Availabilities = {
2536
+ dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
2537
+ numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
2538
+ };
2539
+
2540
+ // implementation of `datetime` function
2541
+ function datetime(context, ...args) {
2542
+ const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
2543
+ const { __datetimeFormatters } = context;
2544
+ if (!Availabilities.dateTimeFormat) {
2545
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
2546
+ return MISSING_RESOLVE_VALUE;
2979
2547
  }
2980
- if (isNumber(arg3)) {
2981
- options.plural = arg3;
2548
+ const [key, value, options, overrides] = parseDateTimeArgs(...args);
2549
+ const missingWarn = isBoolean(options.missingWarn)
2550
+ ? options.missingWarn
2551
+ : context.missingWarn;
2552
+ const fallbackWarn = isBoolean(options.fallbackWarn)
2553
+ ? options.fallbackWarn
2554
+ : context.fallbackWarn;
2555
+ const part = !!options.part;
2556
+ const locale = getLocale(context, options);
2557
+ const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
2558
+ fallbackLocale, locale);
2559
+ if (!isString(key) || key === '') {
2560
+ return new Intl.DateTimeFormat(locale, overrides).format(value);
2982
2561
  }
2983
- else if (isString(arg3)) {
2984
- options.default = arg3;
2562
+ // resolve format
2563
+ let datetimeFormat = {};
2564
+ let targetLocale;
2565
+ let format = null;
2566
+ let from = locale;
2567
+ let to = null;
2568
+ const type = 'datetime format';
2569
+ for (let i = 0; i < locales.length; i++) {
2570
+ targetLocale = to = locales[i];
2571
+ if (locale !== targetLocale &&
2572
+ isTranslateFallbackWarn(fallbackWarn, key)) {
2573
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
2574
+ key,
2575
+ target: targetLocale
2576
+ }));
2577
+ }
2578
+ // for vue-devtools timeline event
2579
+ if (locale !== targetLocale) {
2580
+ const emitter = context.__v_emitter;
2581
+ if (emitter) {
2582
+ emitter.emit('fallback', {
2583
+ type,
2584
+ key,
2585
+ from,
2586
+ to,
2587
+ groupId: `${type}:${key}`
2588
+ });
2589
+ }
2590
+ }
2591
+ datetimeFormat =
2592
+ datetimeFormats[targetLocale] || {};
2593
+ format = datetimeFormat[key];
2594
+ if (isPlainObject(format))
2595
+ break;
2596
+ handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
2597
+ from = to;
2985
2598
  }
2986
- else if (isPlainObject(arg3)) {
2987
- assign(options, arg3);
2599
+ // checking format and target locale
2600
+ if (!isPlainObject(format) || !isString(targetLocale)) {
2601
+ return unresolving ? NOT_REOSLVED : key;
2988
2602
  }
2989
- return [key, options];
2990
- }
2991
- function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
2992
- return {
2993
- locale,
2994
- key,
2995
- warnHtmlMessage,
2996
- onError: (err) => {
2997
- onError && onError(err);
2998
- {
2999
- const _source = getSourceForCodeFrame(source);
3000
- const message = `Message compilation error: ${err.message}`;
3001
- const codeFrame = err.location &&
3002
- _source &&
3003
- generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
3004
- const emitter = context.__v_emitter;
3005
- if (emitter && _source) {
3006
- emitter.emit('compile-error', {
3007
- message: _source,
3008
- error: err.message,
3009
- start: err.location && err.location.start.offset,
3010
- end: err.location && err.location.end.offset,
3011
- groupId: `${'translate'}:${key}`
3012
- });
3013
- }
3014
- console.error(codeFrame ? `${message}\n${codeFrame}` : message);
3015
- }
3016
- },
3017
- onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
3018
- };
3019
- }
3020
- function getSourceForCodeFrame(source) {
3021
- if (isString(source)) {
3022
- return source;
2603
+ let id = `${targetLocale}__${key}`;
2604
+ if (!isEmptyObject(overrides)) {
2605
+ id = `${id}__${JSON.stringify(overrides)}`;
3023
2606
  }
3024
- else {
3025
- if (source.loc && source.loc.source) {
3026
- return source.loc.source;
3027
- }
2607
+ let formatter = __datetimeFormatters.get(id);
2608
+ if (!formatter) {
2609
+ formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
2610
+ __datetimeFormatters.set(id, formatter);
3028
2611
  }
2612
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
3029
2613
  }
3030
- function getMessageContextOptions(context, locale, message, options) {
3031
- const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
3032
- const resolveMessage = (key) => {
3033
- let val = resolveValue(message, key);
3034
- // fallback to root context
3035
- if (val == null && fallbackContext) {
3036
- const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
3037
- val = resolveValue(message, key);
2614
+ /** @internal */
2615
+ const DATETIME_FORMAT_OPTIONS_KEYS = [
2616
+ 'localeMatcher',
2617
+ 'weekday',
2618
+ 'era',
2619
+ 'year',
2620
+ 'month',
2621
+ 'day',
2622
+ 'hour',
2623
+ 'minute',
2624
+ 'second',
2625
+ 'timeZoneName',
2626
+ 'formatMatcher',
2627
+ 'hour12',
2628
+ 'timeZone',
2629
+ 'dateStyle',
2630
+ 'timeStyle',
2631
+ 'calendar',
2632
+ 'dayPeriod',
2633
+ 'numberingSystem',
2634
+ 'hourCycle',
2635
+ 'fractionalSecondDigits'
2636
+ ];
2637
+ /** @internal */
2638
+ function parseDateTimeArgs(...args) {
2639
+ const [arg1, arg2, arg3, arg4] = args;
2640
+ const options = {};
2641
+ let overrides = {};
2642
+ let value;
2643
+ if (isString(arg1)) {
2644
+ // Only allow ISO strings - other date formats are often supported,
2645
+ // but may cause different results in different browsers.
2646
+ const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
2647
+ if (!matches) {
2648
+ throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
3038
2649
  }
3039
- if (isString(val) || isMessageAST(val)) {
3040
- let occurred = false;
3041
- const onError = () => {
3042
- occurred = true;
3043
- };
3044
- const msg = compileMessageFormat(context, key, locale, val, key, onError);
3045
- return !occurred
3046
- ? msg
3047
- : NOOP_MESSAGE_FUNCTION;
2650
+ // Some browsers can not parse the iso datetime separated by space,
2651
+ // this is a compromise solution by replace the 'T'/' ' with 'T'
2652
+ const dateTime = matches[3]
2653
+ ? matches[3].trim().startsWith('T')
2654
+ ? `${matches[1].trim()}${matches[3].trim()}`
2655
+ : `${matches[1].trim()}T${matches[3].trim()}`
2656
+ : matches[1].trim();
2657
+ value = new Date(dateTime);
2658
+ try {
2659
+ // This will fail if the date is not valid
2660
+ value.toISOString();
3048
2661
  }
3049
- else if (isMessageFunction(val)) {
3050
- return val;
2662
+ catch {
2663
+ throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
3051
2664
  }
3052
- else {
3053
- // TODO: should be implemented warning message
3054
- return NOOP_MESSAGE_FUNCTION;
2665
+ }
2666
+ else if (isDate(arg1)) {
2667
+ if (isNaN(arg1.getTime())) {
2668
+ throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
3055
2669
  }
3056
- };
3057
- const ctxOptions = {
3058
- locale,
3059
- modifiers,
3060
- pluralRules,
3061
- messages: resolveMessage
3062
- };
3063
- if (context.processor) {
3064
- ctxOptions.processor = context.processor;
2670
+ value = arg1;
3065
2671
  }
3066
- if (options.list) {
3067
- ctxOptions.list = options.list;
2672
+ else if (isNumber(arg1)) {
2673
+ value = arg1;
2674
+ }
2675
+ else {
2676
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
2677
+ }
2678
+ if (isString(arg2)) {
2679
+ options.key = arg2;
2680
+ }
2681
+ else if (isPlainObject(arg2)) {
2682
+ Object.keys(arg2).forEach(key => {
2683
+ if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
2684
+ overrides[key] = arg2[key];
2685
+ }
2686
+ else {
2687
+ options[key] = arg2[key];
2688
+ }
2689
+ });
2690
+ }
2691
+ if (isString(arg3)) {
2692
+ options.locale = arg3;
2693
+ }
2694
+ else if (isPlainObject(arg3)) {
2695
+ overrides = arg3;
3068
2696
  }
3069
- if (options.named) {
3070
- ctxOptions.named = options.named;
2697
+ if (isPlainObject(arg4)) {
2698
+ overrides = arg4;
3071
2699
  }
3072
- if (isNumber(options.plural)) {
3073
- ctxOptions.pluralIndex = options.plural;
2700
+ return [options.key || '', value, options, overrides];
2701
+ }
2702
+ /** @internal */
2703
+ function clearDateTimeFormat(ctx, locale, format) {
2704
+ const context = ctx;
2705
+ for (const key in format) {
2706
+ const id = `${locale}__${key}`;
2707
+ if (!context.__datetimeFormatters.has(id)) {
2708
+ continue;
2709
+ }
2710
+ context.__datetimeFormatters.delete(id);
3074
2711
  }
3075
- return ctxOptions;
3076
2712
  }
3077
2713
 
3078
- const intlDefined = typeof Intl !== 'undefined';
3079
- const Availabilities = {
3080
- dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
3081
- numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
3082
- };
3083
-
3084
- // implementation of `datetime` function
3085
- function datetime(context, ...args) {
3086
- const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
3087
- const { __datetimeFormatters } = context;
3088
- if (!Availabilities.dateTimeFormat) {
3089
- onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
2714
+ // implementation of `number` function
2715
+ function number(context, ...args) {
2716
+ const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
2717
+ const { __numberFormatters } = context;
2718
+ if (!Availabilities.numberFormat) {
2719
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
3090
2720
  return MISSING_RESOLVE_VALUE;
3091
2721
  }
3092
- const [key, value, options, overrides] = parseDateTimeArgs(...args);
2722
+ const [key, value, options, overrides] = parseNumberArgs(...args);
3093
2723
  const missingWarn = isBoolean(options.missingWarn)
3094
2724
  ? options.missingWarn
3095
2725
  : context.missingWarn;
@@ -3101,20 +2731,20 @@ var IntlifyCoreBase = (function (exports) {
3101
2731
  const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
3102
2732
  fallbackLocale, locale);
3103
2733
  if (!isString(key) || key === '') {
3104
- return new Intl.DateTimeFormat(locale, overrides).format(value);
2734
+ return new Intl.NumberFormat(locale, overrides).format(value);
3105
2735
  }
3106
2736
  // resolve format
3107
- let datetimeFormat = {};
2737
+ let numberFormat = {};
3108
2738
  let targetLocale;
3109
2739
  let format = null;
3110
2740
  let from = locale;
3111
2741
  let to = null;
3112
- const type = 'datetime format';
2742
+ const type = 'number format';
3113
2743
  for (let i = 0; i < locales.length; i++) {
3114
2744
  targetLocale = to = locales[i];
3115
2745
  if (locale !== targetLocale &&
3116
2746
  isTranslateFallbackWarn(fallbackWarn, key)) {
3117
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
2747
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
3118
2748
  key,
3119
2749
  target: targetLocale
3120
2750
  }));
@@ -3132,9 +2762,9 @@ var IntlifyCoreBase = (function (exports) {
3132
2762
  });
3133
2763
  }
3134
2764
  }
3135
- datetimeFormat =
3136
- datetimeFormats[targetLocale] || {};
3137
- format = datetimeFormat[key];
2765
+ numberFormat =
2766
+ numberFormats[targetLocale] || {};
2767
+ format = numberFormat[key];
3138
2768
  if (isPlainObject(format))
3139
2769
  break;
3140
2770
  handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
@@ -3148,147 +2778,356 @@ var IntlifyCoreBase = (function (exports) {
3148
2778
  if (!isEmptyObject(overrides)) {
3149
2779
  id = `${id}__${JSON.stringify(overrides)}`;
3150
2780
  }
3151
- let formatter = __datetimeFormatters.get(id);
2781
+ let formatter = __numberFormatters.get(id);
3152
2782
  if (!formatter) {
3153
- formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
3154
- __datetimeFormatters.set(id, formatter);
2783
+ formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
2784
+ __numberFormatters.set(id, formatter);
3155
2785
  }
3156
2786
  return !part ? formatter.format(value) : formatter.formatToParts(value);
3157
2787
  }
3158
2788
  /** @internal */
3159
- const DATETIME_FORMAT_OPTIONS_KEYS = [
2789
+ const NUMBER_FORMAT_OPTIONS_KEYS = [
3160
2790
  'localeMatcher',
3161
- 'weekday',
3162
- 'era',
3163
- 'year',
3164
- 'month',
3165
- 'day',
3166
- 'hour',
3167
- 'minute',
3168
- 'second',
3169
- 'timeZoneName',
3170
- 'formatMatcher',
3171
- 'hour12',
3172
- 'timeZone',
3173
- 'dateStyle',
3174
- 'timeStyle',
3175
- 'calendar',
3176
- 'dayPeriod',
3177
- 'numberingSystem',
3178
- 'hourCycle',
3179
- 'fractionalSecondDigits'
2791
+ 'style',
2792
+ 'currency',
2793
+ 'currencyDisplay',
2794
+ 'currencySign',
2795
+ 'useGrouping',
2796
+ 'minimumIntegerDigits',
2797
+ 'minimumFractionDigits',
2798
+ 'maximumFractionDigits',
2799
+ 'minimumSignificantDigits',
2800
+ 'maximumSignificantDigits',
2801
+ 'compactDisplay',
2802
+ 'notation',
2803
+ 'signDisplay',
2804
+ 'unit',
2805
+ 'unitDisplay',
2806
+ 'roundingMode',
2807
+ 'roundingPriority',
2808
+ 'roundingIncrement',
2809
+ 'trailingZeroDisplay'
3180
2810
  ];
3181
2811
  /** @internal */
3182
- function parseDateTimeArgs(...args) {
2812
+ function parseNumberArgs(...args) {
3183
2813
  const [arg1, arg2, arg3, arg4] = args;
3184
2814
  const options = {};
3185
2815
  let overrides = {};
3186
- let value;
3187
- if (isString(arg1)) {
3188
- // Only allow ISO strings - other date formats are often supported,
3189
- // but may cause different results in different browsers.
3190
- const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
3191
- if (!matches) {
3192
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
3193
- }
3194
- // Some browsers can not parse the iso datetime separated by space,
3195
- // this is a compromise solution by replace the 'T'/' ' with 'T'
3196
- const dateTime = matches[3]
3197
- ? matches[3].trim().startsWith('T')
3198
- ? `${matches[1].trim()}${matches[3].trim()}`
3199
- : `${matches[1].trim()}T${matches[3].trim()}`
3200
- : matches[1].trim();
3201
- value = new Date(dateTime);
3202
- try {
3203
- // This will fail if the date is not valid
3204
- value.toISOString();
3205
- }
3206
- catch (e) {
3207
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
2816
+ if (!isNumber(arg1)) {
2817
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
2818
+ }
2819
+ const value = arg1;
2820
+ if (isString(arg2)) {
2821
+ options.key = arg2;
2822
+ }
2823
+ else if (isPlainObject(arg2)) {
2824
+ Object.keys(arg2).forEach(key => {
2825
+ if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
2826
+ overrides[key] = arg2[key];
2827
+ }
2828
+ else {
2829
+ options[key] = arg2[key];
2830
+ }
2831
+ });
2832
+ }
2833
+ if (isString(arg3)) {
2834
+ options.locale = arg3;
2835
+ }
2836
+ else if (isPlainObject(arg3)) {
2837
+ overrides = arg3;
2838
+ }
2839
+ if (isPlainObject(arg4)) {
2840
+ overrides = arg4;
2841
+ }
2842
+ return [options.key || '', value, options, overrides];
2843
+ }
2844
+ /** @internal */
2845
+ function clearNumberFormat(ctx, locale, format) {
2846
+ const context = ctx;
2847
+ for (const key in format) {
2848
+ const id = `${locale}__${key}`;
2849
+ if (!context.__numberFormatters.has(id)) {
2850
+ continue;
3208
2851
  }
2852
+ context.__numberFormatters.delete(id);
3209
2853
  }
3210
- else if (isDate(arg1)) {
3211
- if (isNaN(arg1.getTime())) {
3212
- throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
2854
+ }
2855
+
2856
+ const DEFAULT_MODIFIER = (str) => str;
2857
+ const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
2858
+ const DEFAULT_MESSAGE_DATA_TYPE = 'text';
2859
+ const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);
2860
+ const DEFAULT_INTERPOLATE = toDisplayString;
2861
+ function pluralDefault(choice, choicesLength) {
2862
+ choice = Math.abs(choice);
2863
+ if (choicesLength === 2) {
2864
+ // prettier-ignore
2865
+ return choice
2866
+ ? choice > 1
2867
+ ? 1
2868
+ : 0
2869
+ : 1;
2870
+ }
2871
+ return choice ? Math.min(choice, 2) : 0;
2872
+ }
2873
+ function getPluralIndex(options) {
2874
+ // prettier-ignore
2875
+ const index = isNumber(options.pluralIndex)
2876
+ ? options.pluralIndex
2877
+ : -1;
2878
+ // prettier-ignore
2879
+ return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
2880
+ ? isNumber(options.named.count)
2881
+ ? options.named.count
2882
+ : isNumber(options.named.n)
2883
+ ? options.named.n
2884
+ : index
2885
+ : index;
2886
+ }
2887
+ function normalizeNamed(pluralIndex, props) {
2888
+ if (!props.count) {
2889
+ props.count = pluralIndex;
2890
+ }
2891
+ if (!props.n) {
2892
+ props.n = pluralIndex;
2893
+ }
2894
+ }
2895
+ function createMessageContext(options = {}) {
2896
+ const locale = options.locale;
2897
+ const pluralIndex = getPluralIndex(options);
2898
+ const pluralRule = isObject(options.pluralRules) &&
2899
+ isString(locale) &&
2900
+ isFunction(options.pluralRules[locale])
2901
+ ? options.pluralRules[locale]
2902
+ : pluralDefault;
2903
+ const orgPluralRule = isObject(options.pluralRules) &&
2904
+ isString(locale) &&
2905
+ isFunction(options.pluralRules[locale])
2906
+ ? pluralDefault
2907
+ : undefined;
2908
+ const plural = (messages) => {
2909
+ return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
2910
+ };
2911
+ const _list = options.list || [];
2912
+ const list = (index) => _list[index];
2913
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2914
+ const _named = options.named || {};
2915
+ isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
2916
+ const named = (key) => _named[key];
2917
+ function message(key, useLinked) {
2918
+ // prettier-ignore
2919
+ const msg = isFunction(options.messages)
2920
+ ? options.messages(key, !!useLinked)
2921
+ : isObject(options.messages)
2922
+ ? options.messages[key]
2923
+ : false;
2924
+ return !msg
2925
+ ? options.parent
2926
+ ? options.parent.message(key) // resolve from parent messages
2927
+ : DEFAULT_MESSAGE
2928
+ : msg;
2929
+ }
2930
+ const _modifier = (name) => options.modifiers
2931
+ ? options.modifiers[name]
2932
+ : DEFAULT_MODIFIER;
2933
+ const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
2934
+ ? options.processor.normalize
2935
+ : DEFAULT_NORMALIZE;
2936
+ const interpolate = isPlainObject(options.processor) &&
2937
+ isFunction(options.processor.interpolate)
2938
+ ? options.processor.interpolate
2939
+ : DEFAULT_INTERPOLATE;
2940
+ const type = isPlainObject(options.processor) && isString(options.processor.type)
2941
+ ? options.processor.type
2942
+ : DEFAULT_MESSAGE_DATA_TYPE;
2943
+ const linked = (key, ...args) => {
2944
+ const [arg1, arg2] = args;
2945
+ let type = 'text';
2946
+ let modifier = '';
2947
+ if (args.length === 1) {
2948
+ if (isObject(arg1)) {
2949
+ modifier = arg1.modifier || modifier;
2950
+ type = arg1.type || type;
2951
+ }
2952
+ else if (isString(arg1)) {
2953
+ modifier = arg1 || modifier;
2954
+ }
3213
2955
  }
3214
- value = arg1;
3215
- }
3216
- else if (isNumber(arg1)) {
3217
- value = arg1;
3218
- }
3219
- else {
3220
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
3221
- }
3222
- if (isString(arg2)) {
3223
- options.key = arg2;
3224
- }
3225
- else if (isPlainObject(arg2)) {
3226
- Object.keys(arg2).forEach(key => {
3227
- if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
3228
- overrides[key] = arg2[key];
2956
+ else if (args.length === 2) {
2957
+ if (isString(arg1)) {
2958
+ modifier = arg1 || modifier;
3229
2959
  }
3230
- else {
3231
- options[key] = arg2[key];
2960
+ if (isString(arg2)) {
2961
+ type = arg2 || type;
3232
2962
  }
3233
- });
3234
- }
3235
- if (isString(arg3)) {
3236
- options.locale = arg3;
3237
- }
3238
- else if (isPlainObject(arg3)) {
3239
- overrides = arg3;
3240
- }
3241
- if (isPlainObject(arg4)) {
3242
- overrides = arg4;
3243
- }
3244
- return [options.key || '', value, options, overrides];
3245
- }
3246
- /** @internal */
3247
- function clearDateTimeFormat(ctx, locale, format) {
3248
- const context = ctx;
3249
- for (const key in format) {
3250
- const id = `${locale}__${key}`;
3251
- if (!context.__datetimeFormatters.has(id)) {
3252
- continue;
3253
2963
  }
3254
- context.__datetimeFormatters.delete(id);
3255
- }
2964
+ const ret = message(key, true)(ctx);
2965
+ const msg =
2966
+ // The message in vnode resolved with linked are returned as an array by processor.nomalize
2967
+ type === 'vnode' && isArray(ret) && modifier
2968
+ ? ret[0]
2969
+ : ret;
2970
+ return modifier ? _modifier(modifier)(msg, type) : msg;
2971
+ };
2972
+ const ctx = {
2973
+ ["list" /* HelperNameMap.LIST */]: list,
2974
+ ["named" /* HelperNameMap.NAMED */]: named,
2975
+ ["plural" /* HelperNameMap.PLURAL */]: plural,
2976
+ ["linked" /* HelperNameMap.LINKED */]: linked,
2977
+ ["message" /* HelperNameMap.MESSAGE */]: message,
2978
+ ["type" /* HelperNameMap.TYPE */]: type,
2979
+ ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
2980
+ ["normalize" /* HelperNameMap.NORMALIZE */]: normalize,
2981
+ ["values" /* HelperNameMap.VALUES */]: assign({}, _list, _named)
2982
+ };
2983
+ return ctx;
3256
2984
  }
3257
2985
 
3258
- // implementation of `number` function
3259
- function number(context, ...args) {
3260
- const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
3261
- const { __numberFormatters } = context;
3262
- if (!Availabilities.numberFormat) {
3263
- onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
3264
- return MISSING_RESOLVE_VALUE;
3265
- }
3266
- const [key, value, options, overrides] = parseNumberArgs(...args);
2986
+ const NOOP_MESSAGE_FUNCTION = () => '';
2987
+ const isMessageFunction = (val) => isFunction(val);
2988
+ // implementation of `translate` function
2989
+ function translate(context, ...args) {
2990
+ const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
2991
+ const [key, options] = parseTranslateArgs(...args);
3267
2992
  const missingWarn = isBoolean(options.missingWarn)
3268
2993
  ? options.missingWarn
3269
2994
  : context.missingWarn;
3270
2995
  const fallbackWarn = isBoolean(options.fallbackWarn)
3271
2996
  ? options.fallbackWarn
3272
2997
  : context.fallbackWarn;
3273
- const part = !!options.part;
2998
+ const escapeParameter = isBoolean(options.escapeParameter)
2999
+ ? options.escapeParameter
3000
+ : context.escapeParameter;
3001
+ const resolvedMessage = !!options.resolvedMessage;
3002
+ // prettier-ignore
3003
+ const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
3004
+ ? !isBoolean(options.default)
3005
+ ? options.default
3006
+ : (!messageCompiler ? () => key : key)
3007
+ : fallbackFormat // default by `fallbackFormat` option
3008
+ ? (!messageCompiler ? () => key : key)
3009
+ : null;
3010
+ const enableDefaultMsg = fallbackFormat ||
3011
+ (defaultMsgOrKey != null &&
3012
+ (isString(defaultMsgOrKey) || isFunction(defaultMsgOrKey)));
3274
3013
  const locale = getLocale(context, options);
3275
- const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
3276
- fallbackLocale, locale);
3277
- if (!isString(key) || key === '') {
3278
- return new Intl.NumberFormat(locale, overrides).format(value);
3014
+ // escape params
3015
+ escapeParameter && escapeParams(options);
3016
+ // resolve message format
3017
+ // eslint-disable-next-line prefer-const
3018
+ let [formatScope, targetLocale, message] = !resolvedMessage
3019
+ ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
3020
+ : [
3021
+ key,
3022
+ locale,
3023
+ messages[locale] || {}
3024
+ ];
3025
+ // NOTE:
3026
+ // Fix to work around `ssrTransfrom` bug in Vite.
3027
+ // https://github.com/vitejs/vite/issues/4306
3028
+ // To get around this, use temporary variables.
3029
+ // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
3030
+ let format = formatScope;
3031
+ // if you use default message, set it as message format!
3032
+ let cacheBaseKey = key;
3033
+ if (!resolvedMessage &&
3034
+ !(isString(format) ||
3035
+ isMessageAST(format) ||
3036
+ isMessageFunction(format))) {
3037
+ if (enableDefaultMsg) {
3038
+ format = defaultMsgOrKey;
3039
+ cacheBaseKey = format;
3040
+ }
3279
3041
  }
3280
- // resolve format
3281
- let numberFormat = {};
3042
+ // checking message format and target locale
3043
+ if (!resolvedMessage &&
3044
+ (!(isString(format) ||
3045
+ isMessageAST(format) ||
3046
+ isMessageFunction(format)) ||
3047
+ !isString(targetLocale))) {
3048
+ return unresolving ? NOT_REOSLVED : key;
3049
+ }
3050
+ // TODO: refactor
3051
+ if (isString(format) && context.messageCompiler == null) {
3052
+ warn(`The message format compilation is not supported in this build. ` +
3053
+ `Because message compiler isn't included. ` +
3054
+ `You need to pre-compilation all message format. ` +
3055
+ `So translate function return '${key}'.`);
3056
+ return key;
3057
+ }
3058
+ // setup compile error detecting
3059
+ let occurred = false;
3060
+ const onError = () => {
3061
+ occurred = true;
3062
+ };
3063
+ // compile message format
3064
+ const msg = !isMessageFunction(format)
3065
+ ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
3066
+ : format;
3067
+ // if occurred compile error, return the message format
3068
+ if (occurred) {
3069
+ return format;
3070
+ }
3071
+ // evaluate message with context
3072
+ const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
3073
+ const msgContext = createMessageContext(ctxOptions);
3074
+ const messaged = evaluateMessage(context, msg, msgContext);
3075
+ // if use post translation option, proceed it with handler
3076
+ const ret = postTranslation
3077
+ ? postTranslation(messaged, key)
3078
+ : messaged;
3079
+ // NOTE: experimental !!
3080
+ {
3081
+ // prettier-ignore
3082
+ const payloads = {
3083
+ timestamp: Date.now(),
3084
+ key: isString(key)
3085
+ ? key
3086
+ : isMessageFunction(format)
3087
+ ? format.key
3088
+ : '',
3089
+ locale: targetLocale || (isMessageFunction(format)
3090
+ ? format.locale
3091
+ : ''),
3092
+ format: isString(format)
3093
+ ? format
3094
+ : isMessageFunction(format)
3095
+ ? format.source
3096
+ : '',
3097
+ message: ret
3098
+ };
3099
+ payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
3100
+ translateDevTools(payloads);
3101
+ }
3102
+ return ret;
3103
+ }
3104
+ function escapeParams(options) {
3105
+ if (isArray(options.list)) {
3106
+ options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
3107
+ }
3108
+ else if (isObject(options.named)) {
3109
+ Object.keys(options.named).forEach(key => {
3110
+ if (isString(options.named[key])) {
3111
+ options.named[key] = escapeHtml(options.named[key]);
3112
+ }
3113
+ });
3114
+ }
3115
+ }
3116
+ function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
3117
+ const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
3118
+ const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
3119
+ let message = {};
3282
3120
  let targetLocale;
3283
3121
  let format = null;
3284
3122
  let from = locale;
3285
3123
  let to = null;
3286
- const type = 'number format';
3124
+ const type = 'translate';
3287
3125
  for (let i = 0; i < locales.length; i++) {
3288
3126
  targetLocale = to = locales[i];
3289
3127
  if (locale !== targetLocale &&
3128
+ !isAlmostSameLocale(locale, targetLocale) &&
3290
3129
  isTranslateFallbackWarn(fallbackWarn, key)) {
3291
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
3130
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
3292
3131
  key,
3293
3132
  target: targetLocale
3294
3133
  }));
@@ -3306,95 +3145,257 @@ var IntlifyCoreBase = (function (exports) {
3306
3145
  });
3307
3146
  }
3308
3147
  }
3309
- numberFormat =
3310
- numberFormats[targetLocale] || {};
3311
- format = numberFormat[key];
3312
- if (isPlainObject(format))
3313
- break;
3314
- handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
3148
+ message =
3149
+ messages[targetLocale] || {};
3150
+ // for vue-devtools timeline event
3151
+ let start = null;
3152
+ let startTag;
3153
+ let endTag;
3154
+ if (inBrowser) {
3155
+ start = window.performance.now();
3156
+ startTag = 'intlify-message-resolve-start';
3157
+ endTag = 'intlify-message-resolve-end';
3158
+ mark && mark(startTag);
3159
+ }
3160
+ if ((format = resolveValue(message, key)) === null) {
3161
+ // if null, resolve with object key path
3162
+ format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
3163
+ }
3164
+ // for vue-devtools timeline event
3165
+ if (inBrowser) {
3166
+ const end = window.performance.now();
3167
+ const emitter = context.__v_emitter;
3168
+ if (emitter && start && format) {
3169
+ emitter.emit('message-resolve', {
3170
+ type: 'message-resolve',
3171
+ key,
3172
+ message: format,
3173
+ time: end - start,
3174
+ groupId: `${type}:${key}`
3175
+ });
3176
+ }
3177
+ if (startTag && endTag && mark && measure) {
3178
+ mark(endTag);
3179
+ measure('intlify message resolve', startTag, endTag);
3180
+ }
3181
+ }
3182
+ if (isString(format) || isMessageAST(format) || isMessageFunction(format)) {
3183
+ break;
3184
+ }
3185
+ if (!isImplicitFallback(targetLocale, locales)) {
3186
+ const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
3187
+ key, targetLocale, missingWarn, type);
3188
+ if (missingRet !== key) {
3189
+ format = missingRet;
3190
+ }
3191
+ }
3315
3192
  from = to;
3316
3193
  }
3317
- // checking format and target locale
3318
- if (!isPlainObject(format) || !isString(targetLocale)) {
3319
- return unresolving ? NOT_REOSLVED : key;
3194
+ return [format, targetLocale, message];
3195
+ }
3196
+ function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
3197
+ const { messageCompiler, warnHtmlMessage } = context;
3198
+ if (isMessageFunction(format)) {
3199
+ const msg = format;
3200
+ msg.locale = msg.locale || targetLocale;
3201
+ msg.key = msg.key || key;
3202
+ return msg;
3320
3203
  }
3321
- let id = `${targetLocale}__${key}`;
3322
- if (!isEmptyObject(overrides)) {
3323
- id = `${id}__${JSON.stringify(overrides)}`;
3204
+ if (messageCompiler == null) {
3205
+ const msg = (() => format);
3206
+ msg.locale = targetLocale;
3207
+ msg.key = key;
3208
+ return msg;
3324
3209
  }
3325
- let formatter = __numberFormatters.get(id);
3326
- if (!formatter) {
3327
- formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
3328
- __numberFormatters.set(id, formatter);
3210
+ // for vue-devtools timeline event
3211
+ let start = null;
3212
+ let startTag;
3213
+ let endTag;
3214
+ if (inBrowser) {
3215
+ start = window.performance.now();
3216
+ startTag = 'intlify-message-compilation-start';
3217
+ endTag = 'intlify-message-compilation-end';
3218
+ mark && mark(startTag);
3329
3219
  }
3330
- return !part ? formatter.format(value) : formatter.formatToParts(value);
3220
+ const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
3221
+ // for vue-devtools timeline event
3222
+ if (inBrowser) {
3223
+ const end = window.performance.now();
3224
+ const emitter = context.__v_emitter;
3225
+ if (emitter && start) {
3226
+ emitter.emit('message-compilation', {
3227
+ type: 'message-compilation',
3228
+ message: format,
3229
+ time: end - start,
3230
+ groupId: `${'translate'}:${key}`
3231
+ });
3232
+ }
3233
+ if (startTag && endTag && mark && measure) {
3234
+ mark(endTag);
3235
+ measure('intlify message compilation', startTag, endTag);
3236
+ }
3237
+ }
3238
+ msg.locale = targetLocale;
3239
+ msg.key = key;
3240
+ msg.source = format;
3241
+ return msg;
3242
+ }
3243
+ function evaluateMessage(context, msg, msgCtx) {
3244
+ // for vue-devtools timeline event
3245
+ let start = null;
3246
+ let startTag;
3247
+ let endTag;
3248
+ if (inBrowser) {
3249
+ start = window.performance.now();
3250
+ startTag = 'intlify-message-evaluation-start';
3251
+ endTag = 'intlify-message-evaluation-end';
3252
+ mark && mark(startTag);
3253
+ }
3254
+ const messaged = msg(msgCtx);
3255
+ // for vue-devtools timeline event
3256
+ if (inBrowser) {
3257
+ const end = window.performance.now();
3258
+ const emitter = context.__v_emitter;
3259
+ if (emitter && start) {
3260
+ emitter.emit('message-evaluation', {
3261
+ type: 'message-evaluation',
3262
+ value: messaged,
3263
+ time: end - start,
3264
+ groupId: `${'translate'}:${msg.key}`
3265
+ });
3266
+ }
3267
+ if (startTag && endTag && mark && measure) {
3268
+ mark(endTag);
3269
+ measure('intlify message evaluation', startTag, endTag);
3270
+ }
3271
+ }
3272
+ return messaged;
3331
3273
  }
3332
3274
  /** @internal */
3333
- const NUMBER_FORMAT_OPTIONS_KEYS = [
3334
- 'localeMatcher',
3335
- 'style',
3336
- 'currency',
3337
- 'currencyDisplay',
3338
- 'currencySign',
3339
- 'useGrouping',
3340
- 'minimumIntegerDigits',
3341
- 'minimumFractionDigits',
3342
- 'maximumFractionDigits',
3343
- 'minimumSignificantDigits',
3344
- 'maximumSignificantDigits',
3345
- 'compactDisplay',
3346
- 'notation',
3347
- 'signDisplay',
3348
- 'unit',
3349
- 'unitDisplay',
3350
- 'roundingMode',
3351
- 'roundingPriority',
3352
- 'roundingIncrement',
3353
- 'trailingZeroDisplay'
3354
- ];
3355
- /** @internal */
3356
- function parseNumberArgs(...args) {
3357
- const [arg1, arg2, arg3, arg4] = args;
3275
+ function parseTranslateArgs(...args) {
3276
+ const [arg1, arg2, arg3] = args;
3358
3277
  const options = {};
3359
- let overrides = {};
3360
- if (!isNumber(arg1)) {
3278
+ if (!isString(arg1) &&
3279
+ !isNumber(arg1) &&
3280
+ !isMessageFunction(arg1) &&
3281
+ !isMessageAST(arg1)) {
3361
3282
  throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
3362
3283
  }
3363
- const value = arg1;
3364
- if (isString(arg2)) {
3365
- options.key = arg2;
3284
+ // prettier-ignore
3285
+ const key = isNumber(arg1)
3286
+ ? String(arg1)
3287
+ : isMessageFunction(arg1)
3288
+ ? arg1
3289
+ : arg1;
3290
+ if (isNumber(arg2)) {
3291
+ options.plural = arg2;
3366
3292
  }
3367
- else if (isPlainObject(arg2)) {
3368
- Object.keys(arg2).forEach(key => {
3369
- if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
3370
- overrides[key] = arg2[key];
3371
- }
3372
- else {
3373
- options[key] = arg2[key];
3374
- }
3375
- });
3293
+ else if (isString(arg2)) {
3294
+ options.default = arg2;
3376
3295
  }
3377
- if (isString(arg3)) {
3378
- options.locale = arg3;
3296
+ else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
3297
+ options.named = arg2;
3298
+ }
3299
+ else if (isArray(arg2)) {
3300
+ options.list = arg2;
3301
+ }
3302
+ if (isNumber(arg3)) {
3303
+ options.plural = arg3;
3304
+ }
3305
+ else if (isString(arg3)) {
3306
+ options.default = arg3;
3379
3307
  }
3380
3308
  else if (isPlainObject(arg3)) {
3381
- overrides = arg3;
3309
+ assign(options, arg3);
3382
3310
  }
3383
- if (isPlainObject(arg4)) {
3384
- overrides = arg4;
3311
+ return [key, options];
3312
+ }
3313
+ function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
3314
+ return {
3315
+ locale,
3316
+ key,
3317
+ warnHtmlMessage,
3318
+ onError: (err) => {
3319
+ onError && onError(err);
3320
+ {
3321
+ const _source = getSourceForCodeFrame(source);
3322
+ const message = `Message compilation error: ${err.message}`;
3323
+ const codeFrame = err.location &&
3324
+ _source &&
3325
+ generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
3326
+ const emitter = context.__v_emitter;
3327
+ if (emitter && _source) {
3328
+ emitter.emit('compile-error', {
3329
+ message: _source,
3330
+ error: err.message,
3331
+ start: err.location && err.location.start.offset,
3332
+ end: err.location && err.location.end.offset,
3333
+ groupId: `${'translate'}:${key}`
3334
+ });
3335
+ }
3336
+ console.error(codeFrame ? `${message}\n${codeFrame}` : message);
3337
+ }
3338
+ },
3339
+ onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
3340
+ };
3341
+ }
3342
+ function getSourceForCodeFrame(source) {
3343
+ if (isString(source)) {
3344
+ return source;
3345
+ }
3346
+ else {
3347
+ if (source.loc && source.loc.source) {
3348
+ return source.loc.source;
3349
+ }
3385
3350
  }
3386
- return [options.key || '', value, options, overrides];
3387
3351
  }
3388
- /** @internal */
3389
- function clearNumberFormat(ctx, locale, format) {
3390
- const context = ctx;
3391
- for (const key in format) {
3392
- const id = `${locale}__${key}`;
3393
- if (!context.__numberFormatters.has(id)) {
3394
- continue;
3352
+ function getMessageContextOptions(context, locale, message, options) {
3353
+ const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
3354
+ const resolveMessage = (key, useLinked) => {
3355
+ let val = resolveValue(message, key);
3356
+ // fallback
3357
+ if (val == null && (fallbackContext || useLinked)) {
3358
+ const [, , message] = resolveMessageFormat(fallbackContext || context, // NOTE: if has fallbackContext, fallback to root, else if use linked, fallback to local context
3359
+ key, locale, fallbackLocale, fallbackWarn, missingWarn);
3360
+ val = resolveValue(message, key);
3395
3361
  }
3396
- context.__numberFormatters.delete(id);
3362
+ if (isString(val) || isMessageAST(val)) {
3363
+ let occurred = false;
3364
+ const onError = () => {
3365
+ occurred = true;
3366
+ };
3367
+ const msg = compileMessageFormat(context, key, locale, val, key, onError);
3368
+ return !occurred
3369
+ ? msg
3370
+ : NOOP_MESSAGE_FUNCTION;
3371
+ }
3372
+ else if (isMessageFunction(val)) {
3373
+ return val;
3374
+ }
3375
+ else {
3376
+ // TODO: should be implemented warning message
3377
+ return NOOP_MESSAGE_FUNCTION;
3378
+ }
3379
+ };
3380
+ const ctxOptions = {
3381
+ locale,
3382
+ modifiers,
3383
+ pluralRules,
3384
+ messages: resolveMessage
3385
+ };
3386
+ if (context.processor) {
3387
+ ctxOptions.processor = context.processor;
3388
+ }
3389
+ if (options.list) {
3390
+ ctxOptions.list = options.list;
3391
+ }
3392
+ if (options.named) {
3393
+ ctxOptions.named = options.named;
3397
3394
  }
3395
+ if (isNumber(options.plural)) {
3396
+ ctxOptions.pluralIndex = options.plural;
3397
+ }
3398
+ return ctxOptions;
3398
3399
  }
3399
3400
 
3400
3401
  exports.CORE_ERROR_CODES_EXTEND_POINT = CORE_ERROR_CODES_EXTEND_POINT;