core-base.cjs 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808
  1. /*!
  2. * core-base v9.8.0
  3. * (c) 2023 kazuya kawaguchi
  4. * Released under the MIT License.
  5. */
  6. 'use strict';
  7. var messageCompiler = require('@intlify/message-compiler');
  8. var shared = require('@intlify/shared');
  9. const pathStateMachine = [];
  10. pathStateMachine[0 /* States.BEFORE_PATH */] = {
  11. ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
  12. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  13. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  14. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  15. };
  16. pathStateMachine[1 /* States.IN_PATH */] = {
  17. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
  18. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
  19. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  20. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  21. };
  22. pathStateMachine[2 /* States.BEFORE_IDENT */] = {
  23. ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
  24. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  25. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
  26. };
  27. pathStateMachine[3 /* States.IN_IDENT */] = {
  28. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  29. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  30. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
  31. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
  32. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
  33. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
  34. };
  35. pathStateMachine[4 /* States.IN_SUB_PATH */] = {
  36. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
  37. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
  38. ["[" /* PathCharTypes.LEFT_BRACKET */]: [
  39. 4 /* States.IN_SUB_PATH */,
  40. 2 /* Actions.INC_SUB_PATH_DEPTH */
  41. ],
  42. ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
  43. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  44. ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
  45. };
  46. pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
  47. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  48. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  49. ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
  50. };
  51. pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
  52. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  53. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  54. ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
  55. };
  56. /**
  57. * Check if an expression is a literal value.
  58. */
  59. const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
  60. function isLiteral(exp) {
  61. return literalValueRE.test(exp);
  62. }
  63. /**
  64. * Strip quotes from a string
  65. */
  66. function stripQuotes(str) {
  67. const a = str.charCodeAt(0);
  68. const b = str.charCodeAt(str.length - 1);
  69. return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
  70. }
  71. /**
  72. * Determine the type of a character in a keypath.
  73. */
  74. function getPathCharType(ch) {
  75. if (ch === undefined || ch === null) {
  76. return "o" /* PathCharTypes.END_OF_FAIL */;
  77. }
  78. const code = ch.charCodeAt(0);
  79. switch (code) {
  80. case 0x5b: // [
  81. case 0x5d: // ]
  82. case 0x2e: // .
  83. case 0x22: // "
  84. case 0x27: // '
  85. return ch;
  86. case 0x5f: // _
  87. case 0x24: // $
  88. case 0x2d: // -
  89. return "i" /* PathCharTypes.IDENT */;
  90. case 0x09: // Tab (HT)
  91. case 0x0a: // Newline (LF)
  92. case 0x0d: // Return (CR)
  93. case 0xa0: // No-break space (NBSP)
  94. case 0xfeff: // Byte Order Mark (BOM)
  95. case 0x2028: // Line Separator (LS)
  96. case 0x2029: // Paragraph Separator (PS)
  97. return "w" /* PathCharTypes.WORKSPACE */;
  98. }
  99. return "i" /* PathCharTypes.IDENT */;
  100. }
  101. /**
  102. * Format a subPath, return its plain form if it is
  103. * a literal string or number. Otherwise prepend the
  104. * dynamic indicator (*).
  105. */
  106. function formatSubPath(path) {
  107. const trimmed = path.trim();
  108. // invalid leading 0
  109. if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
  110. return false;
  111. }
  112. return isLiteral(trimmed)
  113. ? stripQuotes(trimmed)
  114. : "*" /* PathCharTypes.ASTARISK */ + trimmed;
  115. }
  116. /**
  117. * Parse a string path into an array of segments
  118. */
  119. function parse(path) {
  120. const keys = [];
  121. let index = -1;
  122. let mode = 0 /* States.BEFORE_PATH */;
  123. let subPathDepth = 0;
  124. let c;
  125. let key; // eslint-disable-line
  126. let newChar;
  127. let type;
  128. let transition;
  129. let action;
  130. let typeMap;
  131. const actions = [];
  132. actions[0 /* Actions.APPEND */] = () => {
  133. if (key === undefined) {
  134. key = newChar;
  135. }
  136. else {
  137. key += newChar;
  138. }
  139. };
  140. actions[1 /* Actions.PUSH */] = () => {
  141. if (key !== undefined) {
  142. keys.push(key);
  143. key = undefined;
  144. }
  145. };
  146. actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
  147. actions[0 /* Actions.APPEND */]();
  148. subPathDepth++;
  149. };
  150. actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
  151. if (subPathDepth > 0) {
  152. subPathDepth--;
  153. mode = 4 /* States.IN_SUB_PATH */;
  154. actions[0 /* Actions.APPEND */]();
  155. }
  156. else {
  157. subPathDepth = 0;
  158. if (key === undefined) {
  159. return false;
  160. }
  161. key = formatSubPath(key);
  162. if (key === false) {
  163. return false;
  164. }
  165. else {
  166. actions[1 /* Actions.PUSH */]();
  167. }
  168. }
  169. };
  170. function maybeUnescapeQuote() {
  171. const nextChar = path[index + 1];
  172. if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
  173. nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
  174. (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
  175. nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
  176. index++;
  177. newChar = '\\' + nextChar;
  178. actions[0 /* Actions.APPEND */]();
  179. return true;
  180. }
  181. }
  182. while (mode !== null) {
  183. index++;
  184. c = path[index];
  185. if (c === '\\' && maybeUnescapeQuote()) {
  186. continue;
  187. }
  188. type = getPathCharType(c);
  189. typeMap = pathStateMachine[mode];
  190. transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
  191. // check parse error
  192. if (transition === 8 /* States.ERROR */) {
  193. return;
  194. }
  195. mode = transition[0];
  196. if (transition[1] !== undefined) {
  197. action = actions[transition[1]];
  198. if (action) {
  199. newChar = c;
  200. if (action() === false) {
  201. return;
  202. }
  203. }
  204. }
  205. // check parse finish
  206. if (mode === 7 /* States.AFTER_PATH */) {
  207. return keys;
  208. }
  209. }
  210. }
  211. // path token cache
  212. const cache = new Map();
  213. /**
  214. * key-value message resolver
  215. *
  216. * @remarks
  217. * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
  218. *
  219. * @param obj - A target object to be resolved with path
  220. * @param path - A {@link Path | path} to resolve the value of message
  221. *
  222. * @returns A resolved {@link PathValue | path value}
  223. *
  224. * @VueI18nGeneral
  225. */
  226. function resolveWithKeyValue(obj, path) {
  227. return shared.isObject(obj) ? obj[path] : null;
  228. }
  229. /**
  230. * message resolver
  231. *
  232. * @remarks
  233. * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
  234. *
  235. * @param obj - A target object to be resolved with path
  236. * @param path - A {@link Path | path} to resolve the value of message
  237. *
  238. * @returns A resolved {@link PathValue | path value}
  239. *
  240. * @VueI18nGeneral
  241. */
  242. function resolveValue(obj, path) {
  243. // check object
  244. if (!shared.isObject(obj)) {
  245. return null;
  246. }
  247. // parse path
  248. let hit = cache.get(path);
  249. if (!hit) {
  250. hit = parse(path);
  251. if (hit) {
  252. cache.set(path, hit);
  253. }
  254. }
  255. // check hit
  256. if (!hit) {
  257. return null;
  258. }
  259. // resolve path value
  260. const len = hit.length;
  261. let last = obj;
  262. let i = 0;
  263. while (i < len) {
  264. const val = last[hit[i]];
  265. if (val === undefined) {
  266. return null;
  267. }
  268. if (shared.isFunction(last)) {
  269. return null;
  270. }
  271. last = val;
  272. i++;
  273. }
  274. return last;
  275. }
  276. const DEFAULT_MODIFIER = (str) => str;
  277. const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
  278. const DEFAULT_MESSAGE_DATA_TYPE = 'text';
  279. const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : shared.join(values);
  280. const DEFAULT_INTERPOLATE = shared.toDisplayString;
  281. function pluralDefault(choice, choicesLength) {
  282. choice = Math.abs(choice);
  283. if (choicesLength === 2) {
  284. // prettier-ignore
  285. return choice
  286. ? choice > 1
  287. ? 1
  288. : 0
  289. : 1;
  290. }
  291. return choice ? Math.min(choice, 2) : 0;
  292. }
  293. function getPluralIndex(options) {
  294. // prettier-ignore
  295. const index = shared.isNumber(options.pluralIndex)
  296. ? options.pluralIndex
  297. : -1;
  298. // prettier-ignore
  299. return options.named && (shared.isNumber(options.named.count) || shared.isNumber(options.named.n))
  300. ? shared.isNumber(options.named.count)
  301. ? options.named.count
  302. : shared.isNumber(options.named.n)
  303. ? options.named.n
  304. : index
  305. : index;
  306. }
  307. function normalizeNamed(pluralIndex, props) {
  308. if (!props.count) {
  309. props.count = pluralIndex;
  310. }
  311. if (!props.n) {
  312. props.n = pluralIndex;
  313. }
  314. }
  315. function createMessageContext(options = {}) {
  316. const locale = options.locale;
  317. const pluralIndex = getPluralIndex(options);
  318. const pluralRule = shared.isObject(options.pluralRules) &&
  319. shared.isString(locale) &&
  320. shared.isFunction(options.pluralRules[locale])
  321. ? options.pluralRules[locale]
  322. : pluralDefault;
  323. const orgPluralRule = shared.isObject(options.pluralRules) &&
  324. shared.isString(locale) &&
  325. shared.isFunction(options.pluralRules[locale])
  326. ? pluralDefault
  327. : undefined;
  328. const plural = (messages) => {
  329. return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
  330. };
  331. const _list = options.list || [];
  332. const list = (index) => _list[index];
  333. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  334. const _named = options.named || {};
  335. shared.isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
  336. const named = (key) => _named[key];
  337. function message(key) {
  338. // prettier-ignore
  339. const msg = shared.isFunction(options.messages)
  340. ? options.messages(key)
  341. : shared.isObject(options.messages)
  342. ? options.messages[key]
  343. : false;
  344. return !msg
  345. ? options.parent
  346. ? options.parent.message(key) // resolve from parent messages
  347. : DEFAULT_MESSAGE
  348. : msg;
  349. }
  350. const _modifier = (name) => options.modifiers
  351. ? options.modifiers[name]
  352. : DEFAULT_MODIFIER;
  353. const normalize = shared.isPlainObject(options.processor) && shared.isFunction(options.processor.normalize)
  354. ? options.processor.normalize
  355. : DEFAULT_NORMALIZE;
  356. const interpolate = shared.isPlainObject(options.processor) &&
  357. shared.isFunction(options.processor.interpolate)
  358. ? options.processor.interpolate
  359. : DEFAULT_INTERPOLATE;
  360. const type = shared.isPlainObject(options.processor) && shared.isString(options.processor.type)
  361. ? options.processor.type
  362. : DEFAULT_MESSAGE_DATA_TYPE;
  363. const linked = (key, ...args) => {
  364. const [arg1, arg2] = args;
  365. let type = 'text';
  366. let modifier = '';
  367. if (args.length === 1) {
  368. if (shared.isObject(arg1)) {
  369. modifier = arg1.modifier || modifier;
  370. type = arg1.type || type;
  371. }
  372. else if (shared.isString(arg1)) {
  373. modifier = arg1 || modifier;
  374. }
  375. }
  376. else if (args.length === 2) {
  377. if (shared.isString(arg1)) {
  378. modifier = arg1 || modifier;
  379. }
  380. if (shared.isString(arg2)) {
  381. type = arg2 || type;
  382. }
  383. }
  384. const ret = message(key)(ctx);
  385. const msg =
  386. // The message in vnode resolved with linked are returned as an array by processor.nomalize
  387. type === 'vnode' && shared.isArray(ret) && modifier
  388. ? ret[0]
  389. : ret;
  390. return modifier ? _modifier(modifier)(msg, type) : msg;
  391. };
  392. const ctx = {
  393. ["list" /* HelperNameMap.LIST */]: list,
  394. ["named" /* HelperNameMap.NAMED */]: named,
  395. ["plural" /* HelperNameMap.PLURAL */]: plural,
  396. ["linked" /* HelperNameMap.LINKED */]: linked,
  397. ["message" /* HelperNameMap.MESSAGE */]: message,
  398. ["type" /* HelperNameMap.TYPE */]: type,
  399. ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
  400. ["normalize" /* HelperNameMap.NORMALIZE */]: normalize,
  401. ["values" /* HelperNameMap.VALUES */]: shared.assign({}, _list, _named)
  402. };
  403. return ctx;
  404. }
  405. let devtools = null;
  406. function setDevToolsHook(hook) {
  407. devtools = hook;
  408. }
  409. function getDevToolsHook() {
  410. return devtools;
  411. }
  412. function initI18nDevTools(i18n, version, meta) {
  413. // TODO: queue if devtools is undefined
  414. devtools &&
  415. devtools.emit("i18n:init" /* IntlifyDevToolsHooks.I18nInit */, {
  416. timestamp: Date.now(),
  417. i18n,
  418. version,
  419. meta
  420. });
  421. }
  422. const translateDevTools = /* #__PURE__*/ createDevToolsHook("function:translate" /* IntlifyDevToolsHooks.FunctionTranslate */);
  423. function createDevToolsHook(hook) {
  424. return (payloads) => devtools && devtools.emit(hook, payloads);
  425. }
  426. const CoreWarnCodes = {
  427. NOT_FOUND_KEY: 1,
  428. FALLBACK_TO_TRANSLATE: 2,
  429. CANNOT_FORMAT_NUMBER: 3,
  430. FALLBACK_TO_NUMBER_FORMAT: 4,
  431. CANNOT_FORMAT_DATE: 5,
  432. FALLBACK_TO_DATE_FORMAT: 6,
  433. EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: 7,
  434. __EXTEND_POINT__: 8
  435. };
  436. /** @internal */
  437. const warnMessages = {
  438. [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
  439. [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
  440. [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
  441. [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
  442. [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
  443. [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
  444. [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.`
  445. };
  446. function getWarnMessage(code, ...args) {
  447. return shared.format(warnMessages[code], ...args);
  448. }
  449. const code = messageCompiler.CompileErrorCodes.__EXTEND_POINT__;
  450. const inc = shared.incrementer(code);
  451. const CoreErrorCodes = {
  452. INVALID_ARGUMENT: code,
  453. INVALID_DATE_ARGUMENT: inc(),
  454. INVALID_ISO_DATE_ARGUMENT: inc(),
  455. NOT_SUPPORT_NON_STRING_MESSAGE: inc(),
  456. NOT_SUPPORT_LOCALE_PROMISE_VALUE: inc(),
  457. NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: inc(),
  458. NOT_SUPPORT_LOCALE_TYPE: inc(),
  459. __EXTEND_POINT__: inc() // 25
  460. };
  461. function createCoreError(code) {
  462. return messageCompiler.createCompileError(code, null, { messages: errorMessages } );
  463. }
  464. /** @internal */
  465. const errorMessages = {
  466. [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
  467. [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
  468. 'Make sure your Date represents a valid date.',
  469. [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string',
  470. [CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE]: 'Not support non-string message',
  471. [CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE]: 'cannot support promise value',
  472. [CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]: 'cannot support async function',
  473. [CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE]: 'cannot support locale type'
  474. };
  475. /** @internal */
  476. function getLocale(context, options) {
  477. return options.locale != null
  478. ? resolveLocale(options.locale)
  479. : resolveLocale(context.locale);
  480. }
  481. let _resolveLocale;
  482. /** @internal */
  483. function resolveLocale(locale) {
  484. if (shared.isString(locale)) {
  485. return locale;
  486. }
  487. else {
  488. if (shared.isFunction(locale)) {
  489. if (locale.resolvedOnce && _resolveLocale != null) {
  490. return _resolveLocale;
  491. }
  492. else if (locale.constructor.name === 'Function') {
  493. const resolve = locale();
  494. if (shared.isPromise(resolve)) {
  495. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);
  496. }
  497. return (_resolveLocale = resolve);
  498. }
  499. else {
  500. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);
  501. }
  502. }
  503. else {
  504. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);
  505. }
  506. }
  507. }
  508. /**
  509. * Fallback with simple implemenation
  510. *
  511. * @remarks
  512. * A fallback locale function implemented with a simple fallback algorithm.
  513. *
  514. * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
  515. *
  516. * @param ctx - A {@link CoreContext | context}
  517. * @param fallback - A {@link FallbackLocale | fallback locale}
  518. * @param start - A starting {@link Locale | locale}
  519. *
  520. * @returns Fallback locales
  521. *
  522. * @VueI18nGeneral
  523. */
  524. function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
  525. ) {
  526. // prettier-ignore
  527. return [...new Set([
  528. start,
  529. ...(shared.isArray(fallback)
  530. ? fallback
  531. : shared.isObject(fallback)
  532. ? Object.keys(fallback)
  533. : shared.isString(fallback)
  534. ? [fallback]
  535. : [start])
  536. ])];
  537. }
  538. /**
  539. * Fallback with locale chain
  540. *
  541. * @remarks
  542. * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
  543. *
  544. * @param ctx - A {@link CoreContext | context}
  545. * @param fallback - A {@link FallbackLocale | fallback locale}
  546. * @param start - A starting {@link Locale | locale}
  547. *
  548. * @returns Fallback locales
  549. *
  550. * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
  551. *
  552. * @VueI18nGeneral
  553. */
  554. function fallbackWithLocaleChain(ctx, fallback, start) {
  555. const startLocale = shared.isString(start) ? start : DEFAULT_LOCALE;
  556. const context = ctx;
  557. if (!context.__localeChainCache) {
  558. context.__localeChainCache = new Map();
  559. }
  560. let chain = context.__localeChainCache.get(startLocale);
  561. if (!chain) {
  562. chain = [];
  563. // first block defined by start
  564. let block = [start];
  565. // while any intervening block found
  566. while (shared.isArray(block)) {
  567. block = appendBlockToChain(chain, block, fallback);
  568. }
  569. // prettier-ignore
  570. // last block defined by default
  571. const defaults = shared.isArray(fallback) || !shared.isPlainObject(fallback)
  572. ? fallback
  573. : fallback['default']
  574. ? fallback['default']
  575. : null;
  576. // convert defaults to array
  577. block = shared.isString(defaults) ? [defaults] : defaults;
  578. if (shared.isArray(block)) {
  579. appendBlockToChain(chain, block, false);
  580. }
  581. context.__localeChainCache.set(startLocale, chain);
  582. }
  583. return chain;
  584. }
  585. function appendBlockToChain(chain, block, blocks) {
  586. let follow = true;
  587. for (let i = 0; i < block.length && shared.isBoolean(follow); i++) {
  588. const locale = block[i];
  589. if (shared.isString(locale)) {
  590. follow = appendLocaleToChain(chain, block[i], blocks);
  591. }
  592. }
  593. return follow;
  594. }
  595. function appendLocaleToChain(chain, locale, blocks) {
  596. let follow;
  597. const tokens = locale.split('-');
  598. do {
  599. const target = tokens.join('-');
  600. follow = appendItemToChain(chain, target, blocks);
  601. tokens.splice(-1, 1);
  602. } while (tokens.length && follow === true);
  603. return follow;
  604. }
  605. function appendItemToChain(chain, target, blocks) {
  606. let follow = false;
  607. if (!chain.includes(target)) {
  608. follow = true;
  609. if (target) {
  610. follow = target[target.length - 1] !== '!';
  611. const locale = target.replace(/!/g, '');
  612. chain.push(locale);
  613. if ((shared.isArray(blocks) || shared.isPlainObject(blocks)) &&
  614. blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
  615. ) {
  616. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  617. follow = blocks[locale];
  618. }
  619. }
  620. }
  621. return follow;
  622. }
  623. /* eslint-disable @typescript-eslint/no-explicit-any */
  624. /**
  625. * Intlify core-base version
  626. * @internal
  627. */
  628. const VERSION = '9.8.0';
  629. const NOT_REOSLVED = -1;
  630. const DEFAULT_LOCALE = 'en-US';
  631. const MISSING_RESOLVE_VALUE = '';
  632. const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
  633. function getDefaultLinkedModifiers() {
  634. return {
  635. upper: (val, type) => {
  636. // prettier-ignore
  637. return type === 'text' && shared.isString(val)
  638. ? val.toUpperCase()
  639. : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
  640. ? val.children.toUpperCase()
  641. : val;
  642. },
  643. lower: (val, type) => {
  644. // prettier-ignore
  645. return type === 'text' && shared.isString(val)
  646. ? val.toLowerCase()
  647. : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
  648. ? val.children.toLowerCase()
  649. : val;
  650. },
  651. capitalize: (val, type) => {
  652. // prettier-ignore
  653. return (type === 'text' && shared.isString(val)
  654. ? capitalize(val)
  655. : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
  656. ? capitalize(val.children)
  657. : val);
  658. }
  659. };
  660. }
  661. let _compiler;
  662. function registerMessageCompiler(compiler) {
  663. _compiler = compiler;
  664. }
  665. let _resolver;
  666. /**
  667. * Register the message resolver
  668. *
  669. * @param resolver - A {@link MessageResolver} function
  670. *
  671. * @VueI18nGeneral
  672. */
  673. function registerMessageResolver(resolver) {
  674. _resolver = resolver;
  675. }
  676. let _fallbacker;
  677. /**
  678. * Register the locale fallbacker
  679. *
  680. * @param fallbacker - A {@link LocaleFallbacker} function
  681. *
  682. * @VueI18nGeneral
  683. */
  684. function registerLocaleFallbacker(fallbacker) {
  685. _fallbacker = fallbacker;
  686. }
  687. // Additional Meta for Intlify DevTools
  688. let _additionalMeta = null;
  689. /* #__NO_SIDE_EFFECTS__ */
  690. const setAdditionalMeta = (meta) => {
  691. _additionalMeta = meta;
  692. };
  693. /* #__NO_SIDE_EFFECTS__ */
  694. const getAdditionalMeta = () => _additionalMeta;
  695. let _fallbackContext = null;
  696. const setFallbackContext = (context) => {
  697. _fallbackContext = context;
  698. };
  699. const getFallbackContext = () => _fallbackContext;
  700. // ID for CoreContext
  701. let _cid = 0;
  702. function createCoreContext(options = {}) {
  703. // setup options
  704. const onWarn = shared.isFunction(options.onWarn) ? options.onWarn : shared.warn;
  705. const version = shared.isString(options.version) ? options.version : VERSION;
  706. const locale = shared.isString(options.locale) || shared.isFunction(options.locale)
  707. ? options.locale
  708. : DEFAULT_LOCALE;
  709. const _locale = shared.isFunction(locale) ? DEFAULT_LOCALE : locale;
  710. const fallbackLocale = shared.isArray(options.fallbackLocale) ||
  711. shared.isPlainObject(options.fallbackLocale) ||
  712. shared.isString(options.fallbackLocale) ||
  713. options.fallbackLocale === false
  714. ? options.fallbackLocale
  715. : _locale;
  716. const messages = shared.isPlainObject(options.messages)
  717. ? options.messages
  718. : { [_locale]: {} };
  719. const datetimeFormats = shared.isPlainObject(options.datetimeFormats)
  720. ? options.datetimeFormats
  721. : { [_locale]: {} }
  722. ;
  723. const numberFormats = shared.isPlainObject(options.numberFormats)
  724. ? options.numberFormats
  725. : { [_locale]: {} }
  726. ;
  727. const modifiers = shared.assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
  728. const pluralRules = options.pluralRules || {};
  729. const missing = shared.isFunction(options.missing) ? options.missing : null;
  730. const missingWarn = shared.isBoolean(options.missingWarn) || shared.isRegExp(options.missingWarn)
  731. ? options.missingWarn
  732. : true;
  733. const fallbackWarn = shared.isBoolean(options.fallbackWarn) || shared.isRegExp(options.fallbackWarn)
  734. ? options.fallbackWarn
  735. : true;
  736. const fallbackFormat = !!options.fallbackFormat;
  737. const unresolving = !!options.unresolving;
  738. const postTranslation = shared.isFunction(options.postTranslation)
  739. ? options.postTranslation
  740. : null;
  741. const processor = shared.isPlainObject(options.processor) ? options.processor : null;
  742. const warnHtmlMessage = shared.isBoolean(options.warnHtmlMessage)
  743. ? options.warnHtmlMessage
  744. : true;
  745. const escapeParameter = !!options.escapeParameter;
  746. const messageCompiler = shared.isFunction(options.messageCompiler)
  747. ? options.messageCompiler
  748. : _compiler;
  749. if (shared.isFunction(options.messageCompiler)) {
  750. shared.warnOnce(getWarnMessage(CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER));
  751. }
  752. const messageResolver = shared.isFunction(options.messageResolver)
  753. ? options.messageResolver
  754. : _resolver || resolveWithKeyValue;
  755. const localeFallbacker = shared.isFunction(options.localeFallbacker)
  756. ? options.localeFallbacker
  757. : _fallbacker || fallbackWithSimple;
  758. const fallbackContext = shared.isObject(options.fallbackContext)
  759. ? options.fallbackContext
  760. : undefined;
  761. // setup internal options
  762. const internalOptions = options;
  763. const __datetimeFormatters = shared.isObject(internalOptions.__datetimeFormatters)
  764. ? internalOptions.__datetimeFormatters
  765. : new Map()
  766. ;
  767. const __numberFormatters = shared.isObject(internalOptions.__numberFormatters)
  768. ? internalOptions.__numberFormatters
  769. : new Map()
  770. ;
  771. const __meta = shared.isObject(internalOptions.__meta) ? internalOptions.__meta : {};
  772. _cid++;
  773. const context = {
  774. version,
  775. cid: _cid,
  776. locale,
  777. fallbackLocale,
  778. messages,
  779. modifiers,
  780. pluralRules,
  781. missing,
  782. missingWarn,
  783. fallbackWarn,
  784. fallbackFormat,
  785. unresolving,
  786. postTranslation,
  787. processor,
  788. warnHtmlMessage,
  789. escapeParameter,
  790. messageCompiler,
  791. messageResolver,
  792. localeFallbacker,
  793. fallbackContext,
  794. onWarn,
  795. __meta
  796. };
  797. {
  798. context.datetimeFormats = datetimeFormats;
  799. context.numberFormats = numberFormats;
  800. context.__datetimeFormatters = __datetimeFormatters;
  801. context.__numberFormatters = __numberFormatters;
  802. }
  803. // for vue-devtools timeline event
  804. {
  805. context.__v_emitter =
  806. internalOptions.__v_emitter != null
  807. ? internalOptions.__v_emitter
  808. : undefined;
  809. }
  810. // NOTE: experimental !!
  811. {
  812. initI18nDevTools(context, version, __meta);
  813. }
  814. return context;
  815. }
  816. /** @internal */
  817. function isTranslateFallbackWarn(fallback, key) {
  818. return fallback instanceof RegExp ? fallback.test(key) : fallback;
  819. }
  820. /** @internal */
  821. function isTranslateMissingWarn(missing, key) {
  822. return missing instanceof RegExp ? missing.test(key) : missing;
  823. }
  824. /** @internal */
  825. function handleMissing(context, key, locale, missingWarn, type) {
  826. const { missing, onWarn } = context;
  827. // for vue-devtools timeline event
  828. {
  829. const emitter = context.__v_emitter;
  830. if (emitter) {
  831. emitter.emit("missing" /* VueDevToolsTimelineEvents.MISSING */, {
  832. locale,
  833. key,
  834. type,
  835. groupId: `${type}:${key}`
  836. });
  837. }
  838. }
  839. if (missing !== null) {
  840. const ret = missing(context, locale, key, type);
  841. return shared.isString(ret) ? ret : key;
  842. }
  843. else {
  844. if (isTranslateMissingWarn(missingWarn, key)) {
  845. onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
  846. }
  847. return key;
  848. }
  849. }
  850. /** @internal */
  851. function updateFallbackLocale(ctx, locale, fallback) {
  852. const context = ctx;
  853. context.__localeChainCache = new Map();
  854. ctx.localeFallbacker(ctx, fallback, locale);
  855. }
  856. /* eslint-enable @typescript-eslint/no-explicit-any */
  857. function format(ast) {
  858. const msg = (ctx) => formatParts(ctx, ast);
  859. return msg;
  860. }
  861. function formatParts(ctx, ast) {
  862. const body = ast.b || ast.body;
  863. if ((body.t || body.type) === 1 /* NodeTypes.Plural */) {
  864. const plural = body;
  865. const cases = plural.c || plural.cases;
  866. return ctx.plural(cases.reduce((messages, c) => [
  867. ...messages,
  868. formatMessageParts(ctx, c)
  869. ], []));
  870. }
  871. else {
  872. return formatMessageParts(ctx, body);
  873. }
  874. }
  875. function formatMessageParts(ctx, node) {
  876. const _static = node.s || node.static;
  877. if (_static) {
  878. return ctx.type === 'text'
  879. ? _static
  880. : ctx.normalize([_static]);
  881. }
  882. else {
  883. const messages = (node.i || node.items).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
  884. return ctx.normalize(messages);
  885. }
  886. }
  887. function formatMessagePart(ctx, node) {
  888. const type = node.t || node.type;
  889. switch (type) {
  890. case 3 /* NodeTypes.Text */:
  891. const text = node;
  892. return (text.v || text.value);
  893. case 9 /* NodeTypes.Literal */:
  894. const literal = node;
  895. return (literal.v || literal.value);
  896. case 4 /* NodeTypes.Named */:
  897. const named = node;
  898. return ctx.interpolate(ctx.named(named.k || named.key));
  899. case 5 /* NodeTypes.List */:
  900. const list = node;
  901. return ctx.interpolate(ctx.list(list.i != null ? list.i : list.index));
  902. case 6 /* NodeTypes.Linked */:
  903. const linked = node;
  904. const modifier = linked.m || linked.modifier;
  905. return ctx.linked(formatMessagePart(ctx, linked.k || linked.key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);
  906. case 7 /* NodeTypes.LinkedKey */:
  907. const linkedKey = node;
  908. return (linkedKey.v || linkedKey.value);
  909. case 8 /* NodeTypes.LinkedModifier */:
  910. const linkedModifier = node;
  911. return (linkedModifier.v || linkedModifier.value);
  912. default:
  913. throw new Error(`unhandled node type on format message part: ${type}`);
  914. }
  915. }
  916. const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
  917. function checkHtmlMessage(source, warnHtmlMessage) {
  918. if (warnHtmlMessage && messageCompiler.detectHtmlTag(source)) {
  919. shared.warn(shared.format(WARN_MESSAGE, { source }));
  920. }
  921. }
  922. const defaultOnCacheKey = (message) => message;
  923. let compileCache = Object.create(null);
  924. function clearCompileCache() {
  925. compileCache = Object.create(null);
  926. }
  927. const isMessageAST = (val) => shared.isObject(val) &&
  928. (val.t === 0 || val.type === 0) &&
  929. ('b' in val || 'body' in val);
  930. function baseCompile(message, options = {}) {
  931. // error detecting on compile
  932. let detectError = false;
  933. const onError = options.onError || messageCompiler.defaultOnError;
  934. options.onError = (err) => {
  935. detectError = true;
  936. onError(err);
  937. };
  938. // compile with mesasge-compiler
  939. return { ...messageCompiler.baseCompile(message, options), detectError };
  940. }
  941. /* #__NO_SIDE_EFFECTS__ */
  942. const compileToFunction = (message, context) => {
  943. if (!shared.isString(message)) {
  944. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE);
  945. }
  946. {
  947. // check HTML message
  948. const warnHtmlMessage = shared.isBoolean(context.warnHtmlMessage)
  949. ? context.warnHtmlMessage
  950. : true;
  951. checkHtmlMessage(message, warnHtmlMessage);
  952. // check caches
  953. const onCacheKey = context.onCacheKey || defaultOnCacheKey;
  954. const cacheKey = onCacheKey(message);
  955. const cached = compileCache[cacheKey];
  956. if (cached) {
  957. return cached;
  958. }
  959. // compile
  960. const { code, detectError } = baseCompile(message, context);
  961. // evaluate function
  962. const msg = new Function(`return ${code}`)();
  963. // if occurred compile error, don't cache
  964. return !detectError
  965. ? (compileCache[cacheKey] = msg)
  966. : msg;
  967. }
  968. };
  969. function compile(message, context) {
  970. if (shared.isString(message)) {
  971. // check HTML message
  972. const warnHtmlMessage = shared.isBoolean(context.warnHtmlMessage)
  973. ? context.warnHtmlMessage
  974. : true;
  975. checkHtmlMessage(message, warnHtmlMessage);
  976. // check caches
  977. const onCacheKey = context.onCacheKey || defaultOnCacheKey;
  978. const cacheKey = onCacheKey(message);
  979. const cached = compileCache[cacheKey];
  980. if (cached) {
  981. return cached;
  982. }
  983. // compile with JIT mode
  984. const { ast, detectError } = baseCompile(message, {
  985. ...context,
  986. location: true,
  987. jit: true
  988. });
  989. // compose message function from AST
  990. const msg = format(ast);
  991. // if occurred compile error, don't cache
  992. return !detectError
  993. ? (compileCache[cacheKey] = msg)
  994. : msg;
  995. }
  996. else {
  997. if (!isMessageAST(message)) {
  998. shared.warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);
  999. return (() => message);
  1000. }
  1001. // AST case (passed from bundler)
  1002. const cacheKey = message.cacheKey;
  1003. if (cacheKey) {
  1004. const cached = compileCache[cacheKey];
  1005. if (cached) {
  1006. return cached;
  1007. }
  1008. // compose message function from message (AST)
  1009. return (compileCache[cacheKey] =
  1010. format(message));
  1011. }
  1012. else {
  1013. return format(message);
  1014. }
  1015. }
  1016. }
  1017. const NOOP_MESSAGE_FUNCTION = () => '';
  1018. const isMessageFunction = (val) => shared.isFunction(val);
  1019. // implementation of `translate` function
  1020. function translate(context, ...args) {
  1021. const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
  1022. const [key, options] = parseTranslateArgs(...args);
  1023. const missingWarn = shared.isBoolean(options.missingWarn)
  1024. ? options.missingWarn
  1025. : context.missingWarn;
  1026. const fallbackWarn = shared.isBoolean(options.fallbackWarn)
  1027. ? options.fallbackWarn
  1028. : context.fallbackWarn;
  1029. const escapeParameter = shared.isBoolean(options.escapeParameter)
  1030. ? options.escapeParameter
  1031. : context.escapeParameter;
  1032. const resolvedMessage = !!options.resolvedMessage;
  1033. // prettier-ignore
  1034. const defaultMsgOrKey = shared.isString(options.default) || shared.isBoolean(options.default) // default by function option
  1035. ? !shared.isBoolean(options.default)
  1036. ? options.default
  1037. : (!messageCompiler ? () => key : key)
  1038. : fallbackFormat // default by `fallbackFormat` option
  1039. ? (!messageCompiler ? () => key : key)
  1040. : '';
  1041. const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
  1042. const locale = getLocale(context, options);
  1043. // escape params
  1044. escapeParameter && escapeParams(options);
  1045. // resolve message format
  1046. // eslint-disable-next-line prefer-const
  1047. let [formatScope, targetLocale, message] = !resolvedMessage
  1048. ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
  1049. : [
  1050. key,
  1051. locale,
  1052. messages[locale] || {}
  1053. ];
  1054. // NOTE:
  1055. // Fix to work around `ssrTransfrom` bug in Vite.
  1056. // https://github.com/vitejs/vite/issues/4306
  1057. // To get around this, use temporary variables.
  1058. // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
  1059. let format = formatScope;
  1060. // if you use default message, set it as message format!
  1061. let cacheBaseKey = key;
  1062. if (!resolvedMessage &&
  1063. !(shared.isString(format) ||
  1064. isMessageAST(format) ||
  1065. isMessageFunction(format))) {
  1066. if (enableDefaultMsg) {
  1067. format = defaultMsgOrKey;
  1068. cacheBaseKey = format;
  1069. }
  1070. }
  1071. // checking message format and target locale
  1072. if (!resolvedMessage &&
  1073. (!(shared.isString(format) ||
  1074. isMessageAST(format) ||
  1075. isMessageFunction(format)) ||
  1076. !shared.isString(targetLocale))) {
  1077. return unresolving ? NOT_REOSLVED : key;
  1078. }
  1079. // TODO: refactor
  1080. if (shared.isString(format) && context.messageCompiler == null) {
  1081. shared.warn(`The message format compilation is not supported in this build. ` +
  1082. `Because message compiler isn't included. ` +
  1083. `You need to pre-compilation all message format. ` +
  1084. `So translate function return '${key}'.`);
  1085. return key;
  1086. }
  1087. // setup compile error detecting
  1088. let occurred = false;
  1089. const onError = () => {
  1090. occurred = true;
  1091. };
  1092. // compile message format
  1093. const msg = !isMessageFunction(format)
  1094. ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
  1095. : format;
  1096. // if occurred compile error, return the message format
  1097. if (occurred) {
  1098. return format;
  1099. }
  1100. // evaluate message with context
  1101. const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
  1102. const msgContext = createMessageContext(ctxOptions);
  1103. const messaged = evaluateMessage(context, msg, msgContext);
  1104. // if use post translation option, proceed it with handler
  1105. const ret = postTranslation
  1106. ? postTranslation(messaged, key)
  1107. : messaged;
  1108. // NOTE: experimental !!
  1109. {
  1110. // prettier-ignore
  1111. const payloads = {
  1112. timestamp: Date.now(),
  1113. key: shared.isString(key)
  1114. ? key
  1115. : isMessageFunction(format)
  1116. ? format.key
  1117. : '',
  1118. locale: targetLocale || (isMessageFunction(format)
  1119. ? format.locale
  1120. : ''),
  1121. format: shared.isString(format)
  1122. ? format
  1123. : isMessageFunction(format)
  1124. ? format.source
  1125. : '',
  1126. message: ret
  1127. };
  1128. payloads.meta = shared.assign({}, context.__meta, getAdditionalMeta() || {});
  1129. translateDevTools(payloads);
  1130. }
  1131. return ret;
  1132. }
  1133. function escapeParams(options) {
  1134. if (shared.isArray(options.list)) {
  1135. options.list = options.list.map(item => shared.isString(item) ? shared.escapeHtml(item) : item);
  1136. }
  1137. else if (shared.isObject(options.named)) {
  1138. Object.keys(options.named).forEach(key => {
  1139. if (shared.isString(options.named[key])) {
  1140. options.named[key] = shared.escapeHtml(options.named[key]);
  1141. }
  1142. });
  1143. }
  1144. }
  1145. function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
  1146. const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
  1147. const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
  1148. let message = {};
  1149. let targetLocale;
  1150. let format = null;
  1151. let from = locale;
  1152. let to = null;
  1153. const type = 'translate';
  1154. for (let i = 0; i < locales.length; i++) {
  1155. targetLocale = to = locales[i];
  1156. if (locale !== targetLocale &&
  1157. isTranslateFallbackWarn(fallbackWarn, key)) {
  1158. onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
  1159. key,
  1160. target: targetLocale
  1161. }));
  1162. }
  1163. // for vue-devtools timeline event
  1164. if (locale !== targetLocale) {
  1165. const emitter = context.__v_emitter;
  1166. if (emitter) {
  1167. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  1168. type,
  1169. key,
  1170. from,
  1171. to,
  1172. groupId: `${type}:${key}`
  1173. });
  1174. }
  1175. }
  1176. message =
  1177. messages[targetLocale] || {};
  1178. // for vue-devtools timeline event
  1179. let start = null;
  1180. let startTag;
  1181. let endTag;
  1182. if (shared.inBrowser) {
  1183. start = window.performance.now();
  1184. startTag = 'intlify-message-resolve-start';
  1185. endTag = 'intlify-message-resolve-end';
  1186. shared.mark && shared.mark(startTag);
  1187. }
  1188. if ((format = resolveValue(message, key)) === null) {
  1189. // if null, resolve with object key path
  1190. format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
  1191. }
  1192. // for vue-devtools timeline event
  1193. if (shared.inBrowser) {
  1194. const end = window.performance.now();
  1195. const emitter = context.__v_emitter;
  1196. if (emitter && start && format) {
  1197. emitter.emit("message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */, {
  1198. type: "message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */,
  1199. key,
  1200. message: format,
  1201. time: end - start,
  1202. groupId: `${type}:${key}`
  1203. });
  1204. }
  1205. if (startTag && endTag && shared.mark && shared.measure) {
  1206. shared.mark(endTag);
  1207. shared.measure('intlify message resolve', startTag, endTag);
  1208. }
  1209. }
  1210. if (shared.isString(format) || isMessageAST(format) || isMessageFunction(format)) {
  1211. break;
  1212. }
  1213. const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  1214. key, targetLocale, missingWarn, type);
  1215. if (missingRet !== key) {
  1216. format = missingRet;
  1217. }
  1218. from = to;
  1219. }
  1220. return [format, targetLocale, message];
  1221. }
  1222. function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
  1223. const { messageCompiler, warnHtmlMessage } = context;
  1224. if (isMessageFunction(format)) {
  1225. const msg = format;
  1226. msg.locale = msg.locale || targetLocale;
  1227. msg.key = msg.key || key;
  1228. return msg;
  1229. }
  1230. if (messageCompiler == null) {
  1231. const msg = (() => format);
  1232. msg.locale = targetLocale;
  1233. msg.key = key;
  1234. return msg;
  1235. }
  1236. // for vue-devtools timeline event
  1237. let start = null;
  1238. let startTag;
  1239. let endTag;
  1240. if (shared.inBrowser) {
  1241. start = window.performance.now();
  1242. startTag = 'intlify-message-compilation-start';
  1243. endTag = 'intlify-message-compilation-end';
  1244. shared.mark && shared.mark(startTag);
  1245. }
  1246. const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
  1247. // for vue-devtools timeline event
  1248. if (shared.inBrowser) {
  1249. const end = window.performance.now();
  1250. const emitter = context.__v_emitter;
  1251. if (emitter && start) {
  1252. emitter.emit("message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */, {
  1253. type: "message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */,
  1254. message: format,
  1255. time: end - start,
  1256. groupId: `${'translate'}:${key}`
  1257. });
  1258. }
  1259. if (startTag && endTag && shared.mark && shared.measure) {
  1260. shared.mark(endTag);
  1261. shared.measure('intlify message compilation', startTag, endTag);
  1262. }
  1263. }
  1264. msg.locale = targetLocale;
  1265. msg.key = key;
  1266. msg.source = format;
  1267. return msg;
  1268. }
  1269. function evaluateMessage(context, msg, msgCtx) {
  1270. // for vue-devtools timeline event
  1271. let start = null;
  1272. let startTag;
  1273. let endTag;
  1274. if (shared.inBrowser) {
  1275. start = window.performance.now();
  1276. startTag = 'intlify-message-evaluation-start';
  1277. endTag = 'intlify-message-evaluation-end';
  1278. shared.mark && shared.mark(startTag);
  1279. }
  1280. const messaged = msg(msgCtx);
  1281. // for vue-devtools timeline event
  1282. if (shared.inBrowser) {
  1283. const end = window.performance.now();
  1284. const emitter = context.__v_emitter;
  1285. if (emitter && start) {
  1286. emitter.emit("message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */, {
  1287. type: "message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */,
  1288. value: messaged,
  1289. time: end - start,
  1290. groupId: `${'translate'}:${msg.key}`
  1291. });
  1292. }
  1293. if (startTag && endTag && shared.mark && shared.measure) {
  1294. shared.mark(endTag);
  1295. shared.measure('intlify message evaluation', startTag, endTag);
  1296. }
  1297. }
  1298. return messaged;
  1299. }
  1300. /** @internal */
  1301. function parseTranslateArgs(...args) {
  1302. const [arg1, arg2, arg3] = args;
  1303. const options = {};
  1304. if (!shared.isString(arg1) &&
  1305. !shared.isNumber(arg1) &&
  1306. !isMessageFunction(arg1) &&
  1307. !isMessageAST(arg1)) {
  1308. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  1309. }
  1310. // prettier-ignore
  1311. const key = shared.isNumber(arg1)
  1312. ? String(arg1)
  1313. : isMessageFunction(arg1)
  1314. ? arg1
  1315. : arg1;
  1316. if (shared.isNumber(arg2)) {
  1317. options.plural = arg2;
  1318. }
  1319. else if (shared.isString(arg2)) {
  1320. options.default = arg2;
  1321. }
  1322. else if (shared.isPlainObject(arg2) && !shared.isEmptyObject(arg2)) {
  1323. options.named = arg2;
  1324. }
  1325. else if (shared.isArray(arg2)) {
  1326. options.list = arg2;
  1327. }
  1328. if (shared.isNumber(arg3)) {
  1329. options.plural = arg3;
  1330. }
  1331. else if (shared.isString(arg3)) {
  1332. options.default = arg3;
  1333. }
  1334. else if (shared.isPlainObject(arg3)) {
  1335. shared.assign(options, arg3);
  1336. }
  1337. return [key, options];
  1338. }
  1339. function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
  1340. return {
  1341. locale,
  1342. key,
  1343. warnHtmlMessage,
  1344. onError: (err) => {
  1345. onError && onError(err);
  1346. {
  1347. const _source = getSourceForCodeFrame(source);
  1348. const message = `Message compilation error: ${err.message}`;
  1349. const codeFrame = err.location &&
  1350. _source &&
  1351. shared.generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
  1352. const emitter = context.__v_emitter;
  1353. if (emitter && _source) {
  1354. emitter.emit("compile-error" /* VueDevToolsTimelineEvents.COMPILE_ERROR */, {
  1355. message: _source,
  1356. error: err.message,
  1357. start: err.location && err.location.start.offset,
  1358. end: err.location && err.location.end.offset,
  1359. groupId: `${'translate'}:${key}`
  1360. });
  1361. }
  1362. console.error(codeFrame ? `${message}\n${codeFrame}` : message);
  1363. }
  1364. },
  1365. onCacheKey: (source) => shared.generateFormatCacheKey(locale, key, source)
  1366. };
  1367. }
  1368. function getSourceForCodeFrame(source) {
  1369. if (shared.isString(source)) {
  1370. return source;
  1371. }
  1372. else {
  1373. if (source.loc && source.loc.source) {
  1374. return source.loc.source;
  1375. }
  1376. }
  1377. }
  1378. function getMessageContextOptions(context, locale, message, options) {
  1379. const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
  1380. const resolveMessage = (key) => {
  1381. let val = resolveValue(message, key);
  1382. // fallback to root context
  1383. if (val == null && fallbackContext) {
  1384. const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
  1385. val = resolveValue(message, key);
  1386. }
  1387. if (shared.isString(val) || isMessageAST(val)) {
  1388. let occurred = false;
  1389. const onError = () => {
  1390. occurred = true;
  1391. };
  1392. const msg = compileMessageFormat(context, key, locale, val, key, onError);
  1393. return !occurred
  1394. ? msg
  1395. : NOOP_MESSAGE_FUNCTION;
  1396. }
  1397. else if (isMessageFunction(val)) {
  1398. return val;
  1399. }
  1400. else {
  1401. // TODO: should be implemented warning message
  1402. return NOOP_MESSAGE_FUNCTION;
  1403. }
  1404. };
  1405. const ctxOptions = {
  1406. locale,
  1407. modifiers,
  1408. pluralRules,
  1409. messages: resolveMessage
  1410. };
  1411. if (context.processor) {
  1412. ctxOptions.processor = context.processor;
  1413. }
  1414. if (options.list) {
  1415. ctxOptions.list = options.list;
  1416. }
  1417. if (options.named) {
  1418. ctxOptions.named = options.named;
  1419. }
  1420. if (shared.isNumber(options.plural)) {
  1421. ctxOptions.pluralIndex = options.plural;
  1422. }
  1423. return ctxOptions;
  1424. }
  1425. const intlDefined = typeof Intl !== 'undefined';
  1426. const Availabilities = {
  1427. dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
  1428. numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
  1429. };
  1430. // implementation of `datetime` function
  1431. function datetime(context, ...args) {
  1432. const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  1433. const { __datetimeFormatters } = context;
  1434. if (!Availabilities.dateTimeFormat) {
  1435. onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
  1436. return MISSING_RESOLVE_VALUE;
  1437. }
  1438. const [key, value, options, overrides] = parseDateTimeArgs(...args);
  1439. const missingWarn = shared.isBoolean(options.missingWarn)
  1440. ? options.missingWarn
  1441. : context.missingWarn;
  1442. const fallbackWarn = shared.isBoolean(options.fallbackWarn)
  1443. ? options.fallbackWarn
  1444. : context.fallbackWarn;
  1445. const part = !!options.part;
  1446. const locale = getLocale(context, options);
  1447. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  1448. fallbackLocale, locale);
  1449. if (!shared.isString(key) || key === '') {
  1450. return new Intl.DateTimeFormat(locale, overrides).format(value);
  1451. }
  1452. // resolve format
  1453. let datetimeFormat = {};
  1454. let targetLocale;
  1455. let format = null;
  1456. let from = locale;
  1457. let to = null;
  1458. const type = 'datetime format';
  1459. for (let i = 0; i < locales.length; i++) {
  1460. targetLocale = to = locales[i];
  1461. if (locale !== targetLocale &&
  1462. isTranslateFallbackWarn(fallbackWarn, key)) {
  1463. onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
  1464. key,
  1465. target: targetLocale
  1466. }));
  1467. }
  1468. // for vue-devtools timeline event
  1469. if (locale !== targetLocale) {
  1470. const emitter = context.__v_emitter;
  1471. if (emitter) {
  1472. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  1473. type,
  1474. key,
  1475. from,
  1476. to,
  1477. groupId: `${type}:${key}`
  1478. });
  1479. }
  1480. }
  1481. datetimeFormat =
  1482. datetimeFormats[targetLocale] || {};
  1483. format = datetimeFormat[key];
  1484. if (shared.isPlainObject(format))
  1485. break;
  1486. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  1487. from = to;
  1488. }
  1489. // checking format and target locale
  1490. if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
  1491. return unresolving ? NOT_REOSLVED : key;
  1492. }
  1493. let id = `${targetLocale}__${key}`;
  1494. if (!shared.isEmptyObject(overrides)) {
  1495. id = `${id}__${JSON.stringify(overrides)}`;
  1496. }
  1497. let formatter = __datetimeFormatters.get(id);
  1498. if (!formatter) {
  1499. formatter = new Intl.DateTimeFormat(targetLocale, shared.assign({}, format, overrides));
  1500. __datetimeFormatters.set(id, formatter);
  1501. }
  1502. return !part ? formatter.format(value) : formatter.formatToParts(value);
  1503. }
  1504. /** @internal */
  1505. const DATETIME_FORMAT_OPTIONS_KEYS = [
  1506. 'localeMatcher',
  1507. 'weekday',
  1508. 'era',
  1509. 'year',
  1510. 'month',
  1511. 'day',
  1512. 'hour',
  1513. 'minute',
  1514. 'second',
  1515. 'timeZoneName',
  1516. 'formatMatcher',
  1517. 'hour12',
  1518. 'timeZone',
  1519. 'dateStyle',
  1520. 'timeStyle',
  1521. 'calendar',
  1522. 'dayPeriod',
  1523. 'numberingSystem',
  1524. 'hourCycle',
  1525. 'fractionalSecondDigits'
  1526. ];
  1527. /** @internal */
  1528. function parseDateTimeArgs(...args) {
  1529. const [arg1, arg2, arg3, arg4] = args;
  1530. const options = {};
  1531. let overrides = {};
  1532. let value;
  1533. if (shared.isString(arg1)) {
  1534. // Only allow ISO strings - other date formats are often supported,
  1535. // but may cause different results in different browsers.
  1536. const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
  1537. if (!matches) {
  1538. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  1539. }
  1540. // Some browsers can not parse the iso datetime separated by space,
  1541. // this is a compromise solution by replace the 'T'/' ' with 'T'
  1542. const dateTime = matches[3]
  1543. ? matches[3].trim().startsWith('T')
  1544. ? `${matches[1].trim()}${matches[3].trim()}`
  1545. : `${matches[1].trim()}T${matches[3].trim()}`
  1546. : matches[1].trim();
  1547. value = new Date(dateTime);
  1548. try {
  1549. // This will fail if the date is not valid
  1550. value.toISOString();
  1551. }
  1552. catch (e) {
  1553. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  1554. }
  1555. }
  1556. else if (shared.isDate(arg1)) {
  1557. if (isNaN(arg1.getTime())) {
  1558. throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
  1559. }
  1560. value = arg1;
  1561. }
  1562. else if (shared.isNumber(arg1)) {
  1563. value = arg1;
  1564. }
  1565. else {
  1566. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  1567. }
  1568. if (shared.isString(arg2)) {
  1569. options.key = arg2;
  1570. }
  1571. else if (shared.isPlainObject(arg2)) {
  1572. Object.keys(arg2).forEach(key => {
  1573. if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
  1574. overrides[key] = arg2[key];
  1575. }
  1576. else {
  1577. options[key] = arg2[key];
  1578. }
  1579. });
  1580. }
  1581. if (shared.isString(arg3)) {
  1582. options.locale = arg3;
  1583. }
  1584. else if (shared.isPlainObject(arg3)) {
  1585. overrides = arg3;
  1586. }
  1587. if (shared.isPlainObject(arg4)) {
  1588. overrides = arg4;
  1589. }
  1590. return [options.key || '', value, options, overrides];
  1591. }
  1592. /** @internal */
  1593. function clearDateTimeFormat(ctx, locale, format) {
  1594. const context = ctx;
  1595. for (const key in format) {
  1596. const id = `${locale}__${key}`;
  1597. if (!context.__datetimeFormatters.has(id)) {
  1598. continue;
  1599. }
  1600. context.__datetimeFormatters.delete(id);
  1601. }
  1602. }
  1603. // implementation of `number` function
  1604. function number(context, ...args) {
  1605. const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  1606. const { __numberFormatters } = context;
  1607. if (!Availabilities.numberFormat) {
  1608. onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
  1609. return MISSING_RESOLVE_VALUE;
  1610. }
  1611. const [key, value, options, overrides] = parseNumberArgs(...args);
  1612. const missingWarn = shared.isBoolean(options.missingWarn)
  1613. ? options.missingWarn
  1614. : context.missingWarn;
  1615. const fallbackWarn = shared.isBoolean(options.fallbackWarn)
  1616. ? options.fallbackWarn
  1617. : context.fallbackWarn;
  1618. const part = !!options.part;
  1619. const locale = getLocale(context, options);
  1620. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  1621. fallbackLocale, locale);
  1622. if (!shared.isString(key) || key === '') {
  1623. return new Intl.NumberFormat(locale, overrides).format(value);
  1624. }
  1625. // resolve format
  1626. let numberFormat = {};
  1627. let targetLocale;
  1628. let format = null;
  1629. let from = locale;
  1630. let to = null;
  1631. const type = 'number format';
  1632. for (let i = 0; i < locales.length; i++) {
  1633. targetLocale = to = locales[i];
  1634. if (locale !== targetLocale &&
  1635. isTranslateFallbackWarn(fallbackWarn, key)) {
  1636. onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
  1637. key,
  1638. target: targetLocale
  1639. }));
  1640. }
  1641. // for vue-devtools timeline event
  1642. if (locale !== targetLocale) {
  1643. const emitter = context.__v_emitter;
  1644. if (emitter) {
  1645. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  1646. type,
  1647. key,
  1648. from,
  1649. to,
  1650. groupId: `${type}:${key}`
  1651. });
  1652. }
  1653. }
  1654. numberFormat =
  1655. numberFormats[targetLocale] || {};
  1656. format = numberFormat[key];
  1657. if (shared.isPlainObject(format))
  1658. break;
  1659. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  1660. from = to;
  1661. }
  1662. // checking format and target locale
  1663. if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
  1664. return unresolving ? NOT_REOSLVED : key;
  1665. }
  1666. let id = `${targetLocale}__${key}`;
  1667. if (!shared.isEmptyObject(overrides)) {
  1668. id = `${id}__${JSON.stringify(overrides)}`;
  1669. }
  1670. let formatter = __numberFormatters.get(id);
  1671. if (!formatter) {
  1672. formatter = new Intl.NumberFormat(targetLocale, shared.assign({}, format, overrides));
  1673. __numberFormatters.set(id, formatter);
  1674. }
  1675. return !part ? formatter.format(value) : formatter.formatToParts(value);
  1676. }
  1677. /** @internal */
  1678. const NUMBER_FORMAT_OPTIONS_KEYS = [
  1679. 'localeMatcher',
  1680. 'style',
  1681. 'currency',
  1682. 'currencyDisplay',
  1683. 'currencySign',
  1684. 'useGrouping',
  1685. 'minimumIntegerDigits',
  1686. 'minimumFractionDigits',
  1687. 'maximumFractionDigits',
  1688. 'minimumSignificantDigits',
  1689. 'maximumSignificantDigits',
  1690. 'compactDisplay',
  1691. 'notation',
  1692. 'signDisplay',
  1693. 'unit',
  1694. 'unitDisplay',
  1695. 'roundingMode',
  1696. 'roundingPriority',
  1697. 'roundingIncrement',
  1698. 'trailingZeroDisplay'
  1699. ];
  1700. /** @internal */
  1701. function parseNumberArgs(...args) {
  1702. const [arg1, arg2, arg3, arg4] = args;
  1703. const options = {};
  1704. let overrides = {};
  1705. if (!shared.isNumber(arg1)) {
  1706. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  1707. }
  1708. const value = arg1;
  1709. if (shared.isString(arg2)) {
  1710. options.key = arg2;
  1711. }
  1712. else if (shared.isPlainObject(arg2)) {
  1713. Object.keys(arg2).forEach(key => {
  1714. if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
  1715. overrides[key] = arg2[key];
  1716. }
  1717. else {
  1718. options[key] = arg2[key];
  1719. }
  1720. });
  1721. }
  1722. if (shared.isString(arg3)) {
  1723. options.locale = arg3;
  1724. }
  1725. else if (shared.isPlainObject(arg3)) {
  1726. overrides = arg3;
  1727. }
  1728. if (shared.isPlainObject(arg4)) {
  1729. overrides = arg4;
  1730. }
  1731. return [options.key || '', value, options, overrides];
  1732. }
  1733. /** @internal */
  1734. function clearNumberFormat(ctx, locale, format) {
  1735. const context = ctx;
  1736. for (const key in format) {
  1737. const id = `${locale}__${key}`;
  1738. if (!context.__numberFormatters.has(id)) {
  1739. continue;
  1740. }
  1741. context.__numberFormatters.delete(id);
  1742. }
  1743. }
  1744. exports.CompileErrorCodes = messageCompiler.CompileErrorCodes;
  1745. exports.createCompileError = messageCompiler.createCompileError;
  1746. exports.CoreErrorCodes = CoreErrorCodes;
  1747. exports.CoreWarnCodes = CoreWarnCodes;
  1748. exports.DATETIME_FORMAT_OPTIONS_KEYS = DATETIME_FORMAT_OPTIONS_KEYS;
  1749. exports.DEFAULT_LOCALE = DEFAULT_LOCALE;
  1750. exports.DEFAULT_MESSAGE_DATA_TYPE = DEFAULT_MESSAGE_DATA_TYPE;
  1751. exports.MISSING_RESOLVE_VALUE = MISSING_RESOLVE_VALUE;
  1752. exports.NOT_REOSLVED = NOT_REOSLVED;
  1753. exports.NUMBER_FORMAT_OPTIONS_KEYS = NUMBER_FORMAT_OPTIONS_KEYS;
  1754. exports.VERSION = VERSION;
  1755. exports.clearCompileCache = clearCompileCache;
  1756. exports.clearDateTimeFormat = clearDateTimeFormat;
  1757. exports.clearNumberFormat = clearNumberFormat;
  1758. exports.compile = compile;
  1759. exports.compileToFunction = compileToFunction;
  1760. exports.createCoreContext = createCoreContext;
  1761. exports.createCoreError = createCoreError;
  1762. exports.createMessageContext = createMessageContext;
  1763. exports.datetime = datetime;
  1764. exports.fallbackWithLocaleChain = fallbackWithLocaleChain;
  1765. exports.fallbackWithSimple = fallbackWithSimple;
  1766. exports.getAdditionalMeta = getAdditionalMeta;
  1767. exports.getDevToolsHook = getDevToolsHook;
  1768. exports.getFallbackContext = getFallbackContext;
  1769. exports.getLocale = getLocale;
  1770. exports.getWarnMessage = getWarnMessage;
  1771. exports.handleMissing = handleMissing;
  1772. exports.initI18nDevTools = initI18nDevTools;
  1773. exports.isMessageAST = isMessageAST;
  1774. exports.isMessageFunction = isMessageFunction;
  1775. exports.isTranslateFallbackWarn = isTranslateFallbackWarn;
  1776. exports.isTranslateMissingWarn = isTranslateMissingWarn;
  1777. exports.number = number;
  1778. exports.parse = parse;
  1779. exports.parseDateTimeArgs = parseDateTimeArgs;
  1780. exports.parseNumberArgs = parseNumberArgs;
  1781. exports.parseTranslateArgs = parseTranslateArgs;
  1782. exports.registerLocaleFallbacker = registerLocaleFallbacker;
  1783. exports.registerMessageCompiler = registerMessageCompiler;
  1784. exports.registerMessageResolver = registerMessageResolver;
  1785. exports.resolveLocale = resolveLocale;
  1786. exports.resolveValue = resolveValue;
  1787. exports.resolveWithKeyValue = resolveWithKeyValue;
  1788. exports.setAdditionalMeta = setAdditionalMeta;
  1789. exports.setDevToolsHook = setDevToolsHook;
  1790. exports.setFallbackContext = setFallbackContext;
  1791. exports.translate = translate;
  1792. exports.translateDevTools = translateDevTools;
  1793. exports.updateFallbackLocale = updateFallbackLocale;