core-base.prod.cjs 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546
  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, undefined);
  463. }
  464. /** @internal */
  465. ({
  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. const messageResolver = shared.isFunction(options.messageResolver)
  750. ? options.messageResolver
  751. : _resolver || resolveWithKeyValue;
  752. const localeFallbacker = shared.isFunction(options.localeFallbacker)
  753. ? options.localeFallbacker
  754. : _fallbacker || fallbackWithSimple;
  755. const fallbackContext = shared.isObject(options.fallbackContext)
  756. ? options.fallbackContext
  757. : undefined;
  758. // setup internal options
  759. const internalOptions = options;
  760. const __datetimeFormatters = shared.isObject(internalOptions.__datetimeFormatters)
  761. ? internalOptions.__datetimeFormatters
  762. : new Map()
  763. ;
  764. const __numberFormatters = shared.isObject(internalOptions.__numberFormatters)
  765. ? internalOptions.__numberFormatters
  766. : new Map()
  767. ;
  768. const __meta = shared.isObject(internalOptions.__meta) ? internalOptions.__meta : {};
  769. _cid++;
  770. const context = {
  771. version,
  772. cid: _cid,
  773. locale,
  774. fallbackLocale,
  775. messages,
  776. modifiers,
  777. pluralRules,
  778. missing,
  779. missingWarn,
  780. fallbackWarn,
  781. fallbackFormat,
  782. unresolving,
  783. postTranslation,
  784. processor,
  785. warnHtmlMessage,
  786. escapeParameter,
  787. messageCompiler,
  788. messageResolver,
  789. localeFallbacker,
  790. fallbackContext,
  791. onWarn,
  792. __meta
  793. };
  794. {
  795. context.datetimeFormats = datetimeFormats;
  796. context.numberFormats = numberFormats;
  797. context.__datetimeFormatters = __datetimeFormatters;
  798. context.__numberFormatters = __numberFormatters;
  799. }
  800. return context;
  801. }
  802. /** @internal */
  803. function isTranslateFallbackWarn(fallback, key) {
  804. return fallback instanceof RegExp ? fallback.test(key) : fallback;
  805. }
  806. /** @internal */
  807. function isTranslateMissingWarn(missing, key) {
  808. return missing instanceof RegExp ? missing.test(key) : missing;
  809. }
  810. /** @internal */
  811. function handleMissing(context, key, locale, missingWarn, type) {
  812. const { missing, onWarn } = context;
  813. if (missing !== null) {
  814. const ret = missing(context, locale, key, type);
  815. return shared.isString(ret) ? ret : key;
  816. }
  817. else {
  818. return key;
  819. }
  820. }
  821. /** @internal */
  822. function updateFallbackLocale(ctx, locale, fallback) {
  823. const context = ctx;
  824. context.__localeChainCache = new Map();
  825. ctx.localeFallbacker(ctx, fallback, locale);
  826. }
  827. /* eslint-enable @typescript-eslint/no-explicit-any */
  828. function format(ast) {
  829. const msg = (ctx) => formatParts(ctx, ast);
  830. return msg;
  831. }
  832. function formatParts(ctx, ast) {
  833. const body = ast.b || ast.body;
  834. if ((body.t || body.type) === 1 /* NodeTypes.Plural */) {
  835. const plural = body;
  836. const cases = plural.c || plural.cases;
  837. return ctx.plural(cases.reduce((messages, c) => [
  838. ...messages,
  839. formatMessageParts(ctx, c)
  840. ], []));
  841. }
  842. else {
  843. return formatMessageParts(ctx, body);
  844. }
  845. }
  846. function formatMessageParts(ctx, node) {
  847. const _static = node.s || node.static;
  848. if (_static) {
  849. return ctx.type === 'text'
  850. ? _static
  851. : ctx.normalize([_static]);
  852. }
  853. else {
  854. const messages = (node.i || node.items).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
  855. return ctx.normalize(messages);
  856. }
  857. }
  858. function formatMessagePart(ctx, node) {
  859. const type = node.t || node.type;
  860. switch (type) {
  861. case 3 /* NodeTypes.Text */:
  862. const text = node;
  863. return (text.v || text.value);
  864. case 9 /* NodeTypes.Literal */:
  865. const literal = node;
  866. return (literal.v || literal.value);
  867. case 4 /* NodeTypes.Named */:
  868. const named = node;
  869. return ctx.interpolate(ctx.named(named.k || named.key));
  870. case 5 /* NodeTypes.List */:
  871. const list = node;
  872. return ctx.interpolate(ctx.list(list.i != null ? list.i : list.index));
  873. case 6 /* NodeTypes.Linked */:
  874. const linked = node;
  875. const modifier = linked.m || linked.modifier;
  876. return ctx.linked(formatMessagePart(ctx, linked.k || linked.key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);
  877. case 7 /* NodeTypes.LinkedKey */:
  878. const linkedKey = node;
  879. return (linkedKey.v || linkedKey.value);
  880. case 8 /* NodeTypes.LinkedModifier */:
  881. const linkedModifier = node;
  882. return (linkedModifier.v || linkedModifier.value);
  883. default:
  884. throw new Error(`unhandled node type on format message part: ${type}`);
  885. }
  886. }
  887. const defaultOnCacheKey = (message) => message;
  888. let compileCache = Object.create(null);
  889. function clearCompileCache() {
  890. compileCache = Object.create(null);
  891. }
  892. const isMessageAST = (val) => shared.isObject(val) &&
  893. (val.t === 0 || val.type === 0) &&
  894. ('b' in val || 'body' in val);
  895. function baseCompile(message, options = {}) {
  896. // error detecting on compile
  897. let detectError = false;
  898. const onError = options.onError || messageCompiler.defaultOnError;
  899. options.onError = (err) => {
  900. detectError = true;
  901. onError(err);
  902. };
  903. // compile with mesasge-compiler
  904. return { ...messageCompiler.baseCompile(message, options), detectError };
  905. }
  906. /* #__NO_SIDE_EFFECTS__ */
  907. const compileToFunction = (message, context) => {
  908. if (!shared.isString(message)) {
  909. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE);
  910. }
  911. {
  912. // check HTML message
  913. shared.isBoolean(context.warnHtmlMessage)
  914. ? context.warnHtmlMessage
  915. : true;
  916. // check caches
  917. const onCacheKey = context.onCacheKey || defaultOnCacheKey;
  918. const cacheKey = onCacheKey(message);
  919. const cached = compileCache[cacheKey];
  920. if (cached) {
  921. return cached;
  922. }
  923. // compile
  924. const { code, detectError } = baseCompile(message, context);
  925. // evaluate function
  926. const msg = new Function(`return ${code}`)();
  927. // if occurred compile error, don't cache
  928. return !detectError
  929. ? (compileCache[cacheKey] = msg)
  930. : msg;
  931. }
  932. };
  933. function compile(message, context) {
  934. if (shared.isString(message)) {
  935. // check HTML message
  936. shared.isBoolean(context.warnHtmlMessage)
  937. ? context.warnHtmlMessage
  938. : true;
  939. // check caches
  940. const onCacheKey = context.onCacheKey || defaultOnCacheKey;
  941. const cacheKey = onCacheKey(message);
  942. const cached = compileCache[cacheKey];
  943. if (cached) {
  944. return cached;
  945. }
  946. // compile with JIT mode
  947. const { ast, detectError } = baseCompile(message, {
  948. ...context,
  949. location: false,
  950. jit: true
  951. });
  952. // compose message function from AST
  953. const msg = format(ast);
  954. // if occurred compile error, don't cache
  955. return !detectError
  956. ? (compileCache[cacheKey] = msg)
  957. : msg;
  958. }
  959. else {
  960. // AST case (passed from bundler)
  961. const cacheKey = message.cacheKey;
  962. if (cacheKey) {
  963. const cached = compileCache[cacheKey];
  964. if (cached) {
  965. return cached;
  966. }
  967. // compose message function from message (AST)
  968. return (compileCache[cacheKey] =
  969. format(message));
  970. }
  971. else {
  972. return format(message);
  973. }
  974. }
  975. }
  976. const NOOP_MESSAGE_FUNCTION = () => '';
  977. const isMessageFunction = (val) => shared.isFunction(val);
  978. // implementation of `translate` function
  979. function translate(context, ...args) {
  980. const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
  981. const [key, options] = parseTranslateArgs(...args);
  982. const missingWarn = shared.isBoolean(options.missingWarn)
  983. ? options.missingWarn
  984. : context.missingWarn;
  985. const fallbackWarn = shared.isBoolean(options.fallbackWarn)
  986. ? options.fallbackWarn
  987. : context.fallbackWarn;
  988. const escapeParameter = shared.isBoolean(options.escapeParameter)
  989. ? options.escapeParameter
  990. : context.escapeParameter;
  991. const resolvedMessage = !!options.resolvedMessage;
  992. // prettier-ignore
  993. const defaultMsgOrKey = shared.isString(options.default) || shared.isBoolean(options.default) // default by function option
  994. ? !shared.isBoolean(options.default)
  995. ? options.default
  996. : (!messageCompiler ? () => key : key)
  997. : fallbackFormat // default by `fallbackFormat` option
  998. ? (!messageCompiler ? () => key : key)
  999. : '';
  1000. const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
  1001. const locale = getLocale(context, options);
  1002. // escape params
  1003. escapeParameter && escapeParams(options);
  1004. // resolve message format
  1005. // eslint-disable-next-line prefer-const
  1006. let [formatScope, targetLocale, message] = !resolvedMessage
  1007. ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
  1008. : [
  1009. key,
  1010. locale,
  1011. messages[locale] || {}
  1012. ];
  1013. // NOTE:
  1014. // Fix to work around `ssrTransfrom` bug in Vite.
  1015. // https://github.com/vitejs/vite/issues/4306
  1016. // To get around this, use temporary variables.
  1017. // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
  1018. let format = formatScope;
  1019. // if you use default message, set it as message format!
  1020. let cacheBaseKey = key;
  1021. if (!resolvedMessage &&
  1022. !(shared.isString(format) ||
  1023. isMessageAST(format) ||
  1024. isMessageFunction(format))) {
  1025. if (enableDefaultMsg) {
  1026. format = defaultMsgOrKey;
  1027. cacheBaseKey = format;
  1028. }
  1029. }
  1030. // checking message format and target locale
  1031. if (!resolvedMessage &&
  1032. (!(shared.isString(format) ||
  1033. isMessageAST(format) ||
  1034. isMessageFunction(format)) ||
  1035. !shared.isString(targetLocale))) {
  1036. return unresolving ? NOT_REOSLVED : key;
  1037. }
  1038. // setup compile error detecting
  1039. let occurred = false;
  1040. const onError = () => {
  1041. occurred = true;
  1042. };
  1043. // compile message format
  1044. const msg = !isMessageFunction(format)
  1045. ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
  1046. : format;
  1047. // if occurred compile error, return the message format
  1048. if (occurred) {
  1049. return format;
  1050. }
  1051. // evaluate message with context
  1052. const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
  1053. const msgContext = createMessageContext(ctxOptions);
  1054. const messaged = evaluateMessage(context, msg, msgContext);
  1055. // if use post translation option, proceed it with handler
  1056. const ret = postTranslation
  1057. ? postTranslation(messaged, key)
  1058. : messaged;
  1059. return ret;
  1060. }
  1061. function escapeParams(options) {
  1062. if (shared.isArray(options.list)) {
  1063. options.list = options.list.map(item => shared.isString(item) ? shared.escapeHtml(item) : item);
  1064. }
  1065. else if (shared.isObject(options.named)) {
  1066. Object.keys(options.named).forEach(key => {
  1067. if (shared.isString(options.named[key])) {
  1068. options.named[key] = shared.escapeHtml(options.named[key]);
  1069. }
  1070. });
  1071. }
  1072. }
  1073. function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
  1074. const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
  1075. const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
  1076. let message = {};
  1077. let targetLocale;
  1078. let format = null;
  1079. const type = 'translate';
  1080. for (let i = 0; i < locales.length; i++) {
  1081. targetLocale = locales[i];
  1082. message =
  1083. messages[targetLocale] || {};
  1084. if ((format = resolveValue(message, key)) === null) {
  1085. // if null, resolve with object key path
  1086. format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
  1087. }
  1088. if (shared.isString(format) || isMessageAST(format) || isMessageFunction(format)) {
  1089. break;
  1090. }
  1091. const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  1092. key, targetLocale, missingWarn, type);
  1093. if (missingRet !== key) {
  1094. format = missingRet;
  1095. }
  1096. }
  1097. return [format, targetLocale, message];
  1098. }
  1099. function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
  1100. const { messageCompiler, warnHtmlMessage } = context;
  1101. if (isMessageFunction(format)) {
  1102. const msg = format;
  1103. msg.locale = msg.locale || targetLocale;
  1104. msg.key = msg.key || key;
  1105. return msg;
  1106. }
  1107. if (messageCompiler == null) {
  1108. const msg = (() => format);
  1109. msg.locale = targetLocale;
  1110. msg.key = key;
  1111. return msg;
  1112. }
  1113. const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
  1114. msg.locale = targetLocale;
  1115. msg.key = key;
  1116. msg.source = format;
  1117. return msg;
  1118. }
  1119. function evaluateMessage(context, msg, msgCtx) {
  1120. const messaged = msg(msgCtx);
  1121. return messaged;
  1122. }
  1123. /** @internal */
  1124. function parseTranslateArgs(...args) {
  1125. const [arg1, arg2, arg3] = args;
  1126. const options = {};
  1127. if (!shared.isString(arg1) &&
  1128. !shared.isNumber(arg1) &&
  1129. !isMessageFunction(arg1) &&
  1130. !isMessageAST(arg1)) {
  1131. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  1132. }
  1133. // prettier-ignore
  1134. const key = shared.isNumber(arg1)
  1135. ? String(arg1)
  1136. : isMessageFunction(arg1)
  1137. ? arg1
  1138. : arg1;
  1139. if (shared.isNumber(arg2)) {
  1140. options.plural = arg2;
  1141. }
  1142. else if (shared.isString(arg2)) {
  1143. options.default = arg2;
  1144. }
  1145. else if (shared.isPlainObject(arg2) && !shared.isEmptyObject(arg2)) {
  1146. options.named = arg2;
  1147. }
  1148. else if (shared.isArray(arg2)) {
  1149. options.list = arg2;
  1150. }
  1151. if (shared.isNumber(arg3)) {
  1152. options.plural = arg3;
  1153. }
  1154. else if (shared.isString(arg3)) {
  1155. options.default = arg3;
  1156. }
  1157. else if (shared.isPlainObject(arg3)) {
  1158. shared.assign(options, arg3);
  1159. }
  1160. return [key, options];
  1161. }
  1162. function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
  1163. return {
  1164. locale,
  1165. key,
  1166. warnHtmlMessage,
  1167. onError: (err) => {
  1168. onError && onError(err);
  1169. {
  1170. throw err;
  1171. }
  1172. },
  1173. onCacheKey: (source) => shared.generateFormatCacheKey(locale, key, source)
  1174. };
  1175. }
  1176. function getMessageContextOptions(context, locale, message, options) {
  1177. const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
  1178. const resolveMessage = (key) => {
  1179. let val = resolveValue(message, key);
  1180. // fallback to root context
  1181. if (val == null && fallbackContext) {
  1182. const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
  1183. val = resolveValue(message, key);
  1184. }
  1185. if (shared.isString(val) || isMessageAST(val)) {
  1186. let occurred = false;
  1187. const onError = () => {
  1188. occurred = true;
  1189. };
  1190. const msg = compileMessageFormat(context, key, locale, val, key, onError);
  1191. return !occurred
  1192. ? msg
  1193. : NOOP_MESSAGE_FUNCTION;
  1194. }
  1195. else if (isMessageFunction(val)) {
  1196. return val;
  1197. }
  1198. else {
  1199. // TODO: should be implemented warning message
  1200. return NOOP_MESSAGE_FUNCTION;
  1201. }
  1202. };
  1203. const ctxOptions = {
  1204. locale,
  1205. modifiers,
  1206. pluralRules,
  1207. messages: resolveMessage
  1208. };
  1209. if (context.processor) {
  1210. ctxOptions.processor = context.processor;
  1211. }
  1212. if (options.list) {
  1213. ctxOptions.list = options.list;
  1214. }
  1215. if (options.named) {
  1216. ctxOptions.named = options.named;
  1217. }
  1218. if (shared.isNumber(options.plural)) {
  1219. ctxOptions.pluralIndex = options.plural;
  1220. }
  1221. return ctxOptions;
  1222. }
  1223. // implementation of `datetime` function
  1224. function datetime(context, ...args) {
  1225. const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  1226. const { __datetimeFormatters } = context;
  1227. const [key, value, options, overrides] = parseDateTimeArgs(...args);
  1228. const missingWarn = shared.isBoolean(options.missingWarn)
  1229. ? options.missingWarn
  1230. : context.missingWarn;
  1231. shared.isBoolean(options.fallbackWarn)
  1232. ? options.fallbackWarn
  1233. : context.fallbackWarn;
  1234. const part = !!options.part;
  1235. const locale = getLocale(context, options);
  1236. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  1237. fallbackLocale, locale);
  1238. if (!shared.isString(key) || key === '') {
  1239. return new Intl.DateTimeFormat(locale, overrides).format(value);
  1240. }
  1241. // resolve format
  1242. let datetimeFormat = {};
  1243. let targetLocale;
  1244. let format = null;
  1245. const type = 'datetime format';
  1246. for (let i = 0; i < locales.length; i++) {
  1247. targetLocale = locales[i];
  1248. datetimeFormat =
  1249. datetimeFormats[targetLocale] || {};
  1250. format = datetimeFormat[key];
  1251. if (shared.isPlainObject(format))
  1252. break;
  1253. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  1254. }
  1255. // checking format and target locale
  1256. if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
  1257. return unresolving ? NOT_REOSLVED : key;
  1258. }
  1259. let id = `${targetLocale}__${key}`;
  1260. if (!shared.isEmptyObject(overrides)) {
  1261. id = `${id}__${JSON.stringify(overrides)}`;
  1262. }
  1263. let formatter = __datetimeFormatters.get(id);
  1264. if (!formatter) {
  1265. formatter = new Intl.DateTimeFormat(targetLocale, shared.assign({}, format, overrides));
  1266. __datetimeFormatters.set(id, formatter);
  1267. }
  1268. return !part ? formatter.format(value) : formatter.formatToParts(value);
  1269. }
  1270. /** @internal */
  1271. const DATETIME_FORMAT_OPTIONS_KEYS = [
  1272. 'localeMatcher',
  1273. 'weekday',
  1274. 'era',
  1275. 'year',
  1276. 'month',
  1277. 'day',
  1278. 'hour',
  1279. 'minute',
  1280. 'second',
  1281. 'timeZoneName',
  1282. 'formatMatcher',
  1283. 'hour12',
  1284. 'timeZone',
  1285. 'dateStyle',
  1286. 'timeStyle',
  1287. 'calendar',
  1288. 'dayPeriod',
  1289. 'numberingSystem',
  1290. 'hourCycle',
  1291. 'fractionalSecondDigits'
  1292. ];
  1293. /** @internal */
  1294. function parseDateTimeArgs(...args) {
  1295. const [arg1, arg2, arg3, arg4] = args;
  1296. const options = {};
  1297. let overrides = {};
  1298. let value;
  1299. if (shared.isString(arg1)) {
  1300. // Only allow ISO strings - other date formats are often supported,
  1301. // but may cause different results in different browsers.
  1302. const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
  1303. if (!matches) {
  1304. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  1305. }
  1306. // Some browsers can not parse the iso datetime separated by space,
  1307. // this is a compromise solution by replace the 'T'/' ' with 'T'
  1308. const dateTime = matches[3]
  1309. ? matches[3].trim().startsWith('T')
  1310. ? `${matches[1].trim()}${matches[3].trim()}`
  1311. : `${matches[1].trim()}T${matches[3].trim()}`
  1312. : matches[1].trim();
  1313. value = new Date(dateTime);
  1314. try {
  1315. // This will fail if the date is not valid
  1316. value.toISOString();
  1317. }
  1318. catch (e) {
  1319. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  1320. }
  1321. }
  1322. else if (shared.isDate(arg1)) {
  1323. if (isNaN(arg1.getTime())) {
  1324. throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
  1325. }
  1326. value = arg1;
  1327. }
  1328. else if (shared.isNumber(arg1)) {
  1329. value = arg1;
  1330. }
  1331. else {
  1332. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  1333. }
  1334. if (shared.isString(arg2)) {
  1335. options.key = arg2;
  1336. }
  1337. else if (shared.isPlainObject(arg2)) {
  1338. Object.keys(arg2).forEach(key => {
  1339. if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
  1340. overrides[key] = arg2[key];
  1341. }
  1342. else {
  1343. options[key] = arg2[key];
  1344. }
  1345. });
  1346. }
  1347. if (shared.isString(arg3)) {
  1348. options.locale = arg3;
  1349. }
  1350. else if (shared.isPlainObject(arg3)) {
  1351. overrides = arg3;
  1352. }
  1353. if (shared.isPlainObject(arg4)) {
  1354. overrides = arg4;
  1355. }
  1356. return [options.key || '', value, options, overrides];
  1357. }
  1358. /** @internal */
  1359. function clearDateTimeFormat(ctx, locale, format) {
  1360. const context = ctx;
  1361. for (const key in format) {
  1362. const id = `${locale}__${key}`;
  1363. if (!context.__datetimeFormatters.has(id)) {
  1364. continue;
  1365. }
  1366. context.__datetimeFormatters.delete(id);
  1367. }
  1368. }
  1369. // implementation of `number` function
  1370. function number(context, ...args) {
  1371. const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  1372. const { __numberFormatters } = context;
  1373. const [key, value, options, overrides] = parseNumberArgs(...args);
  1374. const missingWarn = shared.isBoolean(options.missingWarn)
  1375. ? options.missingWarn
  1376. : context.missingWarn;
  1377. shared.isBoolean(options.fallbackWarn)
  1378. ? options.fallbackWarn
  1379. : context.fallbackWarn;
  1380. const part = !!options.part;
  1381. const locale = getLocale(context, options);
  1382. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  1383. fallbackLocale, locale);
  1384. if (!shared.isString(key) || key === '') {
  1385. return new Intl.NumberFormat(locale, overrides).format(value);
  1386. }
  1387. // resolve format
  1388. let numberFormat = {};
  1389. let targetLocale;
  1390. let format = null;
  1391. const type = 'number format';
  1392. for (let i = 0; i < locales.length; i++) {
  1393. targetLocale = locales[i];
  1394. numberFormat =
  1395. numberFormats[targetLocale] || {};
  1396. format = numberFormat[key];
  1397. if (shared.isPlainObject(format))
  1398. break;
  1399. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  1400. }
  1401. // checking format and target locale
  1402. if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
  1403. return unresolving ? NOT_REOSLVED : key;
  1404. }
  1405. let id = `${targetLocale}__${key}`;
  1406. if (!shared.isEmptyObject(overrides)) {
  1407. id = `${id}__${JSON.stringify(overrides)}`;
  1408. }
  1409. let formatter = __numberFormatters.get(id);
  1410. if (!formatter) {
  1411. formatter = new Intl.NumberFormat(targetLocale, shared.assign({}, format, overrides));
  1412. __numberFormatters.set(id, formatter);
  1413. }
  1414. return !part ? formatter.format(value) : formatter.formatToParts(value);
  1415. }
  1416. /** @internal */
  1417. const NUMBER_FORMAT_OPTIONS_KEYS = [
  1418. 'localeMatcher',
  1419. 'style',
  1420. 'currency',
  1421. 'currencyDisplay',
  1422. 'currencySign',
  1423. 'useGrouping',
  1424. 'minimumIntegerDigits',
  1425. 'minimumFractionDigits',
  1426. 'maximumFractionDigits',
  1427. 'minimumSignificantDigits',
  1428. 'maximumSignificantDigits',
  1429. 'compactDisplay',
  1430. 'notation',
  1431. 'signDisplay',
  1432. 'unit',
  1433. 'unitDisplay',
  1434. 'roundingMode',
  1435. 'roundingPriority',
  1436. 'roundingIncrement',
  1437. 'trailingZeroDisplay'
  1438. ];
  1439. /** @internal */
  1440. function parseNumberArgs(...args) {
  1441. const [arg1, arg2, arg3, arg4] = args;
  1442. const options = {};
  1443. let overrides = {};
  1444. if (!shared.isNumber(arg1)) {
  1445. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  1446. }
  1447. const value = arg1;
  1448. if (shared.isString(arg2)) {
  1449. options.key = arg2;
  1450. }
  1451. else if (shared.isPlainObject(arg2)) {
  1452. Object.keys(arg2).forEach(key => {
  1453. if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
  1454. overrides[key] = arg2[key];
  1455. }
  1456. else {
  1457. options[key] = arg2[key];
  1458. }
  1459. });
  1460. }
  1461. if (shared.isString(arg3)) {
  1462. options.locale = arg3;
  1463. }
  1464. else if (shared.isPlainObject(arg3)) {
  1465. overrides = arg3;
  1466. }
  1467. if (shared.isPlainObject(arg4)) {
  1468. overrides = arg4;
  1469. }
  1470. return [options.key || '', value, options, overrides];
  1471. }
  1472. /** @internal */
  1473. function clearNumberFormat(ctx, locale, format) {
  1474. const context = ctx;
  1475. for (const key in format) {
  1476. const id = `${locale}__${key}`;
  1477. if (!context.__numberFormatters.has(id)) {
  1478. continue;
  1479. }
  1480. context.__numberFormatters.delete(id);
  1481. }
  1482. }
  1483. exports.CompileErrorCodes = messageCompiler.CompileErrorCodes;
  1484. exports.createCompileError = messageCompiler.createCompileError;
  1485. exports.CoreErrorCodes = CoreErrorCodes;
  1486. exports.CoreWarnCodes = CoreWarnCodes;
  1487. exports.DATETIME_FORMAT_OPTIONS_KEYS = DATETIME_FORMAT_OPTIONS_KEYS;
  1488. exports.DEFAULT_LOCALE = DEFAULT_LOCALE;
  1489. exports.DEFAULT_MESSAGE_DATA_TYPE = DEFAULT_MESSAGE_DATA_TYPE;
  1490. exports.MISSING_RESOLVE_VALUE = MISSING_RESOLVE_VALUE;
  1491. exports.NOT_REOSLVED = NOT_REOSLVED;
  1492. exports.NUMBER_FORMAT_OPTIONS_KEYS = NUMBER_FORMAT_OPTIONS_KEYS;
  1493. exports.VERSION = VERSION;
  1494. exports.clearCompileCache = clearCompileCache;
  1495. exports.clearDateTimeFormat = clearDateTimeFormat;
  1496. exports.clearNumberFormat = clearNumberFormat;
  1497. exports.compile = compile;
  1498. exports.compileToFunction = compileToFunction;
  1499. exports.createCoreContext = createCoreContext;
  1500. exports.createCoreError = createCoreError;
  1501. exports.createMessageContext = createMessageContext;
  1502. exports.datetime = datetime;
  1503. exports.fallbackWithLocaleChain = fallbackWithLocaleChain;
  1504. exports.fallbackWithSimple = fallbackWithSimple;
  1505. exports.getAdditionalMeta = getAdditionalMeta;
  1506. exports.getDevToolsHook = getDevToolsHook;
  1507. exports.getFallbackContext = getFallbackContext;
  1508. exports.getLocale = getLocale;
  1509. exports.getWarnMessage = getWarnMessage;
  1510. exports.handleMissing = handleMissing;
  1511. exports.initI18nDevTools = initI18nDevTools;
  1512. exports.isMessageAST = isMessageAST;
  1513. exports.isMessageFunction = isMessageFunction;
  1514. exports.isTranslateFallbackWarn = isTranslateFallbackWarn;
  1515. exports.isTranslateMissingWarn = isTranslateMissingWarn;
  1516. exports.number = number;
  1517. exports.parse = parse;
  1518. exports.parseDateTimeArgs = parseDateTimeArgs;
  1519. exports.parseNumberArgs = parseNumberArgs;
  1520. exports.parseTranslateArgs = parseTranslateArgs;
  1521. exports.registerLocaleFallbacker = registerLocaleFallbacker;
  1522. exports.registerMessageCompiler = registerMessageCompiler;
  1523. exports.registerMessageResolver = registerMessageResolver;
  1524. exports.resolveLocale = resolveLocale;
  1525. exports.resolveValue = resolveValue;
  1526. exports.resolveWithKeyValue = resolveWithKeyValue;
  1527. exports.setAdditionalMeta = setAdditionalMeta;
  1528. exports.setDevToolsHook = setDevToolsHook;
  1529. exports.setFallbackContext = setFallbackContext;
  1530. exports.translate = translate;
  1531. exports.translateDevTools = translateDevTools;
  1532. exports.updateFallbackLocale = updateFallbackLocale;