core-base.esm-browser.js 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766
  1. /*!
  2. * @intlify/core-base v9.1.9
  3. * (c) 2021 kazuya kawaguchi
  4. * Released under the MIT License.
  5. */
  6. /**
  7. * Original Utilities
  8. * written by kazuya kawaguchi
  9. */
  10. const inBrowser = typeof window !== 'undefined';
  11. let mark;
  12. let measure;
  13. {
  14. const perf = inBrowser && window.performance;
  15. if (perf &&
  16. perf.mark &&
  17. perf.measure &&
  18. perf.clearMarks &&
  19. perf.clearMeasures) {
  20. mark = (tag) => perf.mark(tag);
  21. measure = (name, startTag, endTag) => {
  22. perf.measure(name, startTag, endTag);
  23. perf.clearMarks(startTag);
  24. perf.clearMarks(endTag);
  25. };
  26. }
  27. }
  28. const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
  29. /* eslint-disable */
  30. function format(message, ...args) {
  31. if (args.length === 1 && isObject(args[0])) {
  32. args = args[0];
  33. }
  34. if (!args || !args.hasOwnProperty) {
  35. args = {};
  36. }
  37. return message.replace(RE_ARGS, (match, identifier) => {
  38. return args.hasOwnProperty(identifier) ? args[identifier] : '';
  39. });
  40. }
  41. const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
  42. const friendlyJSONstringify = (json) => JSON.stringify(json)
  43. .replace(/\u2028/g, '\\u2028')
  44. .replace(/\u2029/g, '\\u2029')
  45. .replace(/\u0027/g, '\\u0027');
  46. const isNumber = (val) => typeof val === 'number' && isFinite(val);
  47. const isDate = (val) => toTypeString(val) === '[object Date]';
  48. const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
  49. const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
  50. function warn(msg, err) {
  51. if (typeof console !== 'undefined') {
  52. console.warn(`[intlify] ` + msg);
  53. /* istanbul ignore if */
  54. if (err) {
  55. console.warn(err.stack);
  56. }
  57. }
  58. }
  59. const assign = Object.assign;
  60. function escapeHtml(rawText) {
  61. return rawText
  62. .replace(/</g, '&lt;')
  63. .replace(/>/g, '&gt;')
  64. .replace(/"/g, '&quot;')
  65. .replace(/'/g, '&apos;');
  66. }
  67. const hasOwnProperty = Object.prototype.hasOwnProperty;
  68. function hasOwn(obj, key) {
  69. return hasOwnProperty.call(obj, key);
  70. }
  71. /* eslint-enable */
  72. /**
  73. * Useful Utilities By Evan you
  74. * Modified by kazuya kawaguchi
  75. * MIT License
  76. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
  77. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
  78. */
  79. const isArray = Array.isArray;
  80. const isFunction = (val) => typeof val === 'function';
  81. const isString = (val) => typeof val === 'string';
  82. const isBoolean = (val) => typeof val === 'boolean';
  83. const isObject = (val) => // eslint-disable-line
  84. val !== null && typeof val === 'object';
  85. const objectToString = Object.prototype.toString;
  86. const toTypeString = (value) => objectToString.call(value);
  87. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  88. // for converting list and named values to displayed strings.
  89. const toDisplayString = (val) => {
  90. return val == null
  91. ? ''
  92. : isArray(val) || (isPlainObject(val) && val.toString === objectToString)
  93. ? JSON.stringify(val, null, 2)
  94. : String(val);
  95. };
  96. const RANGE = 2;
  97. function generateCodeFrame(source, start = 0, end = source.length) {
  98. const lines = source.split(/\r?\n/);
  99. let count = 0;
  100. const res = [];
  101. for (let i = 0; i < lines.length; i++) {
  102. count += lines[i].length + 1;
  103. if (count >= start) {
  104. for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
  105. if (j < 0 || j >= lines.length)
  106. continue;
  107. const line = j + 1;
  108. res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
  109. const lineLength = lines[j].length;
  110. if (j === i) {
  111. // push underline
  112. const pad = start - (count - lineLength) + 1;
  113. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  114. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  115. }
  116. else if (j > i) {
  117. if (end > count) {
  118. const length = Math.max(Math.min(end - count, lineLength), 1);
  119. res.push(` | ` + '^'.repeat(length));
  120. }
  121. count += lineLength + 1;
  122. }
  123. }
  124. break;
  125. }
  126. }
  127. return res.join('\n');
  128. }
  129. const pathStateMachine = [];
  130. pathStateMachine[0 /* BEFORE_PATH */] = {
  131. ["w" /* WORKSPACE */]: [0 /* BEFORE_PATH */],
  132. ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
  133. ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
  134. ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
  135. };
  136. pathStateMachine[1 /* IN_PATH */] = {
  137. ["w" /* WORKSPACE */]: [1 /* IN_PATH */],
  138. ["." /* DOT */]: [2 /* BEFORE_IDENT */],
  139. ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
  140. ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
  141. };
  142. pathStateMachine[2 /* BEFORE_IDENT */] = {
  143. ["w" /* WORKSPACE */]: [2 /* BEFORE_IDENT */],
  144. ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
  145. ["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */]
  146. };
  147. pathStateMachine[3 /* IN_IDENT */] = {
  148. ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
  149. ["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */],
  150. ["w" /* WORKSPACE */]: [1 /* IN_PATH */, 1 /* PUSH */],
  151. ["." /* DOT */]: [2 /* BEFORE_IDENT */, 1 /* PUSH */],
  152. ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */, 1 /* PUSH */],
  153. ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */, 1 /* PUSH */]
  154. };
  155. pathStateMachine[4 /* IN_SUB_PATH */] = {
  156. ["'" /* SINGLE_QUOTE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */],
  157. ["\"" /* DOUBLE_QUOTE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */],
  158. ["[" /* LEFT_BRACKET */]: [
  159. 4 /* IN_SUB_PATH */,
  160. 2 /* INC_SUB_PATH_DEPTH */
  161. ],
  162. ["]" /* RIGHT_BRACKET */]: [1 /* IN_PATH */, 3 /* PUSH_SUB_PATH */],
  163. ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
  164. ["l" /* ELSE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */]
  165. };
  166. pathStateMachine[5 /* IN_SINGLE_QUOTE */] = {
  167. ["'" /* SINGLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
  168. ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
  169. ["l" /* ELSE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */]
  170. };
  171. pathStateMachine[6 /* IN_DOUBLE_QUOTE */] = {
  172. ["\"" /* DOUBLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
  173. ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
  174. ["l" /* ELSE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */]
  175. };
  176. /**
  177. * Check if an expression is a literal value.
  178. */
  179. const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
  180. function isLiteral(exp) {
  181. return literalValueRE.test(exp);
  182. }
  183. /**
  184. * Strip quotes from a string
  185. */
  186. function stripQuotes(str) {
  187. const a = str.charCodeAt(0);
  188. const b = str.charCodeAt(str.length - 1);
  189. return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
  190. }
  191. /**
  192. * Determine the type of a character in a keypath.
  193. */
  194. function getPathCharType(ch) {
  195. if (ch === undefined || ch === null) {
  196. return "o" /* END_OF_FAIL */;
  197. }
  198. const code = ch.charCodeAt(0);
  199. switch (code) {
  200. case 0x5b: // [
  201. case 0x5d: // ]
  202. case 0x2e: // .
  203. case 0x22: // "
  204. case 0x27: // '
  205. return ch;
  206. case 0x5f: // _
  207. case 0x24: // $
  208. case 0x2d: // -
  209. return "i" /* IDENT */;
  210. case 0x09: // Tab (HT)
  211. case 0x0a: // Newline (LF)
  212. case 0x0d: // Return (CR)
  213. case 0xa0: // No-break space (NBSP)
  214. case 0xfeff: // Byte Order Mark (BOM)
  215. case 0x2028: // Line Separator (LS)
  216. case 0x2029: // Paragraph Separator (PS)
  217. return "w" /* WORKSPACE */;
  218. }
  219. return "i" /* IDENT */;
  220. }
  221. /**
  222. * Format a subPath, return its plain form if it is
  223. * a literal string or number. Otherwise prepend the
  224. * dynamic indicator (*).
  225. */
  226. function formatSubPath(path) {
  227. const trimmed = path.trim();
  228. // invalid leading 0
  229. if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
  230. return false;
  231. }
  232. return isLiteral(trimmed)
  233. ? stripQuotes(trimmed)
  234. : "*" /* ASTARISK */ + trimmed;
  235. }
  236. /**
  237. * Parse a string path into an array of segments
  238. */
  239. function parse(path) {
  240. const keys = [];
  241. let index = -1;
  242. let mode = 0 /* BEFORE_PATH */;
  243. let subPathDepth = 0;
  244. let c;
  245. let key; // eslint-disable-line
  246. let newChar;
  247. let type;
  248. let transition;
  249. let action;
  250. let typeMap;
  251. const actions = [];
  252. actions[0 /* APPEND */] = () => {
  253. if (key === undefined) {
  254. key = newChar;
  255. }
  256. else {
  257. key += newChar;
  258. }
  259. };
  260. actions[1 /* PUSH */] = () => {
  261. if (key !== undefined) {
  262. keys.push(key);
  263. key = undefined;
  264. }
  265. };
  266. actions[2 /* INC_SUB_PATH_DEPTH */] = () => {
  267. actions[0 /* APPEND */]();
  268. subPathDepth++;
  269. };
  270. actions[3 /* PUSH_SUB_PATH */] = () => {
  271. if (subPathDepth > 0) {
  272. subPathDepth--;
  273. mode = 4 /* IN_SUB_PATH */;
  274. actions[0 /* APPEND */]();
  275. }
  276. else {
  277. subPathDepth = 0;
  278. if (key === undefined) {
  279. return false;
  280. }
  281. key = formatSubPath(key);
  282. if (key === false) {
  283. return false;
  284. }
  285. else {
  286. actions[1 /* PUSH */]();
  287. }
  288. }
  289. };
  290. function maybeUnescapeQuote() {
  291. const nextChar = path[index + 1];
  292. if ((mode === 5 /* IN_SINGLE_QUOTE */ &&
  293. nextChar === "'" /* SINGLE_QUOTE */) ||
  294. (mode === 6 /* IN_DOUBLE_QUOTE */ &&
  295. nextChar === "\"" /* DOUBLE_QUOTE */)) {
  296. index++;
  297. newChar = '\\' + nextChar;
  298. actions[0 /* APPEND */]();
  299. return true;
  300. }
  301. }
  302. while (mode !== null) {
  303. index++;
  304. c = path[index];
  305. if (c === '\\' && maybeUnescapeQuote()) {
  306. continue;
  307. }
  308. type = getPathCharType(c);
  309. typeMap = pathStateMachine[mode];
  310. transition = typeMap[type] || typeMap["l" /* ELSE */] || 8 /* ERROR */;
  311. // check parse error
  312. if (transition === 8 /* ERROR */) {
  313. return;
  314. }
  315. mode = transition[0];
  316. if (transition[1] !== undefined) {
  317. action = actions[transition[1]];
  318. if (action) {
  319. newChar = c;
  320. if (action() === false) {
  321. return;
  322. }
  323. }
  324. }
  325. // check parse finish
  326. if (mode === 7 /* AFTER_PATH */) {
  327. return keys;
  328. }
  329. }
  330. }
  331. // path token cache
  332. const cache = new Map();
  333. function resolveValue(obj, path) {
  334. // check object
  335. if (!isObject(obj)) {
  336. return null;
  337. }
  338. // parse path
  339. let hit = cache.get(path);
  340. if (!hit) {
  341. hit = parse(path);
  342. if (hit) {
  343. cache.set(path, hit);
  344. }
  345. }
  346. // check hit
  347. if (!hit) {
  348. return null;
  349. }
  350. // resolve path value
  351. const len = hit.length;
  352. let last = obj;
  353. let i = 0;
  354. while (i < len) {
  355. const val = last[hit[i]];
  356. if (val === undefined) {
  357. return null;
  358. }
  359. last = val;
  360. i++;
  361. }
  362. return last;
  363. }
  364. /**
  365. * Transform flat json in obj to normal json in obj
  366. */
  367. function handleFlatJson(obj) {
  368. // check obj
  369. if (!isObject(obj)) {
  370. return obj;
  371. }
  372. for (const key in obj) {
  373. // check key
  374. if (!hasOwn(obj, key)) {
  375. continue;
  376. }
  377. // handle for normal json
  378. if (!key.includes("." /* DOT */)) {
  379. // recursive process value if value is also a object
  380. if (isObject(obj[key])) {
  381. handleFlatJson(obj[key]);
  382. }
  383. }
  384. // handle for flat json, transform to normal json
  385. else {
  386. // go to the last object
  387. const subKeys = key.split("." /* DOT */);
  388. const lastIndex = subKeys.length - 1;
  389. let currentObj = obj;
  390. for (let i = 0; i < lastIndex; i++) {
  391. if (!(subKeys[i] in currentObj)) {
  392. currentObj[subKeys[i]] = {};
  393. }
  394. currentObj = currentObj[subKeys[i]];
  395. }
  396. // update last object value, delete old property
  397. currentObj[subKeys[lastIndex]] = obj[key];
  398. delete obj[key];
  399. // recursive process value if value is also a object
  400. if (isObject(currentObj[subKeys[lastIndex]])) {
  401. handleFlatJson(currentObj[subKeys[lastIndex]]);
  402. }
  403. }
  404. }
  405. return obj;
  406. }
  407. const DEFAULT_MODIFIER = (str) => str;
  408. const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
  409. const DEFAULT_MESSAGE_DATA_TYPE = 'text';
  410. const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join('');
  411. const DEFAULT_INTERPOLATE = toDisplayString;
  412. function pluralDefault(choice, choicesLength) {
  413. choice = Math.abs(choice);
  414. if (choicesLength === 2) {
  415. // prettier-ignore
  416. return choice
  417. ? choice > 1
  418. ? 1
  419. : 0
  420. : 1;
  421. }
  422. return choice ? Math.min(choice, 2) : 0;
  423. }
  424. function getPluralIndex(options) {
  425. // prettier-ignore
  426. const index = isNumber(options.pluralIndex)
  427. ? options.pluralIndex
  428. : -1;
  429. // prettier-ignore
  430. return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
  431. ? isNumber(options.named.count)
  432. ? options.named.count
  433. : isNumber(options.named.n)
  434. ? options.named.n
  435. : index
  436. : index;
  437. }
  438. function normalizeNamed(pluralIndex, props) {
  439. if (!props.count) {
  440. props.count = pluralIndex;
  441. }
  442. if (!props.n) {
  443. props.n = pluralIndex;
  444. }
  445. }
  446. function createMessageContext(options = {}) {
  447. const locale = options.locale;
  448. const pluralIndex = getPluralIndex(options);
  449. const pluralRule = isObject(options.pluralRules) &&
  450. isString(locale) &&
  451. isFunction(options.pluralRules[locale])
  452. ? options.pluralRules[locale]
  453. : pluralDefault;
  454. const orgPluralRule = isObject(options.pluralRules) &&
  455. isString(locale) &&
  456. isFunction(options.pluralRules[locale])
  457. ? pluralDefault
  458. : undefined;
  459. const plural = (messages) => messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
  460. const _list = options.list || [];
  461. const list = (index) => _list[index];
  462. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  463. const _named = options.named || {};
  464. isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
  465. const named = (key) => _named[key];
  466. // TODO: need to design resolve message function?
  467. function message(key) {
  468. // prettier-ignore
  469. const msg = isFunction(options.messages)
  470. ? options.messages(key)
  471. : isObject(options.messages)
  472. ? options.messages[key]
  473. : false;
  474. return !msg
  475. ? options.parent
  476. ? options.parent.message(key) // resolve from parent messages
  477. : DEFAULT_MESSAGE
  478. : msg;
  479. }
  480. const _modifier = (name) => options.modifiers
  481. ? options.modifiers[name]
  482. : DEFAULT_MODIFIER;
  483. const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
  484. ? options.processor.normalize
  485. : DEFAULT_NORMALIZE;
  486. const interpolate = isPlainObject(options.processor) &&
  487. isFunction(options.processor.interpolate)
  488. ? options.processor.interpolate
  489. : DEFAULT_INTERPOLATE;
  490. const type = isPlainObject(options.processor) && isString(options.processor.type)
  491. ? options.processor.type
  492. : DEFAULT_MESSAGE_DATA_TYPE;
  493. const ctx = {
  494. ["list" /* LIST */]: list,
  495. ["named" /* NAMED */]: named,
  496. ["plural" /* PLURAL */]: plural,
  497. ["linked" /* LINKED */]: (key, modifier) => {
  498. // TODO: should check `key`
  499. const msg = message(key)(ctx);
  500. return isString(modifier) ? _modifier(modifier)(msg) : msg;
  501. },
  502. ["message" /* MESSAGE */]: message,
  503. ["type" /* TYPE */]: type,
  504. ["interpolate" /* INTERPOLATE */]: interpolate,
  505. ["normalize" /* NORMALIZE */]: normalize
  506. };
  507. return ctx;
  508. }
  509. /** @internal */
  510. const errorMessages$1 = {
  511. // tokenizer error messages
  512. [0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`,
  513. [1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`,
  514. [2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`,
  515. [3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`,
  516. [4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`,
  517. [5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`,
  518. [6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`,
  519. [7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`,
  520. [8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`,
  521. [9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`,
  522. // parser error messages
  523. [10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`,
  524. [11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */]: `Unexpected empty linked modifier`,
  525. [12 /* UNEXPECTED_EMPTY_LINKED_KEY */]: `Unexpected empty linked key`,
  526. [13 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'`
  527. };
  528. function createCompileError(code, loc, options = {}) {
  529. const { domain, messages, args } = options;
  530. const msg = format((messages || errorMessages$1)[code] || '', ...(args || []))
  531. ;
  532. const error = new SyntaxError(String(msg));
  533. error.code = code;
  534. if (loc) {
  535. error.location = loc;
  536. }
  537. error.domain = domain;
  538. return error;
  539. }
  540. /** @internal */
  541. function defaultOnError(error) {
  542. throw error;
  543. }
  544. function createPosition(line, column, offset) {
  545. return { line, column, offset };
  546. }
  547. function createLocation(start, end, source) {
  548. const loc = { start, end };
  549. if (source != null) {
  550. loc.source = source;
  551. }
  552. return loc;
  553. }
  554. const CHAR_SP = ' ';
  555. const CHAR_CR = '\r';
  556. const CHAR_LF = '\n';
  557. const CHAR_LS = String.fromCharCode(0x2028);
  558. const CHAR_PS = String.fromCharCode(0x2029);
  559. function createScanner(str) {
  560. const _buf = str;
  561. let _index = 0;
  562. let _line = 1;
  563. let _column = 1;
  564. let _peekOffset = 0;
  565. const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
  566. const isLF = (index) => _buf[index] === CHAR_LF;
  567. const isPS = (index) => _buf[index] === CHAR_PS;
  568. const isLS = (index) => _buf[index] === CHAR_LS;
  569. const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
  570. const index = () => _index;
  571. const line = () => _line;
  572. const column = () => _column;
  573. const peekOffset = () => _peekOffset;
  574. const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
  575. const currentChar = () => charAt(_index);
  576. const currentPeek = () => charAt(_index + _peekOffset);
  577. function next() {
  578. _peekOffset = 0;
  579. if (isLineEnd(_index)) {
  580. _line++;
  581. _column = 0;
  582. }
  583. if (isCRLF(_index)) {
  584. _index++;
  585. }
  586. _index++;
  587. _column++;
  588. return _buf[_index];
  589. }
  590. function peek() {
  591. if (isCRLF(_index + _peekOffset)) {
  592. _peekOffset++;
  593. }
  594. _peekOffset++;
  595. return _buf[_index + _peekOffset];
  596. }
  597. function reset() {
  598. _index = 0;
  599. _line = 1;
  600. _column = 1;
  601. _peekOffset = 0;
  602. }
  603. function resetPeek(offset = 0) {
  604. _peekOffset = offset;
  605. }
  606. function skipToPeek() {
  607. const target = _index + _peekOffset;
  608. // eslint-disable-next-line no-unmodified-loop-condition
  609. while (target !== _index) {
  610. next();
  611. }
  612. _peekOffset = 0;
  613. }
  614. return {
  615. index,
  616. line,
  617. column,
  618. peekOffset,
  619. charAt,
  620. currentChar,
  621. currentPeek,
  622. next,
  623. peek,
  624. reset,
  625. resetPeek,
  626. skipToPeek
  627. };
  628. }
  629. const EOF = undefined;
  630. const LITERAL_DELIMITER = "'";
  631. const ERROR_DOMAIN$1 = 'tokenizer';
  632. function createTokenizer(source, options = {}) {
  633. const location = options.location !== false;
  634. const _scnr = createScanner(source);
  635. const currentOffset = () => _scnr.index();
  636. const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
  637. const _initLoc = currentPosition();
  638. const _initOffset = currentOffset();
  639. const _context = {
  640. currentType: 14 /* EOF */,
  641. offset: _initOffset,
  642. startLoc: _initLoc,
  643. endLoc: _initLoc,
  644. lastType: 14 /* EOF */,
  645. lastOffset: _initOffset,
  646. lastStartLoc: _initLoc,
  647. lastEndLoc: _initLoc,
  648. braceNest: 0,
  649. inLinked: false,
  650. text: ''
  651. };
  652. const context = () => _context;
  653. const { onError } = options;
  654. function emitError(code, pos, offset, ...args) {
  655. const ctx = context();
  656. pos.column += offset;
  657. pos.offset += offset;
  658. if (onError) {
  659. const loc = createLocation(ctx.startLoc, pos);
  660. const err = createCompileError(code, loc, {
  661. domain: ERROR_DOMAIN$1,
  662. args
  663. });
  664. onError(err);
  665. }
  666. }
  667. function getToken(context, type, value) {
  668. context.endLoc = currentPosition();
  669. context.currentType = type;
  670. const token = { type };
  671. if (location) {
  672. token.loc = createLocation(context.startLoc, context.endLoc);
  673. }
  674. if (value != null) {
  675. token.value = value;
  676. }
  677. return token;
  678. }
  679. const getEndToken = (context) => getToken(context, 14 /* EOF */);
  680. function eat(scnr, ch) {
  681. if (scnr.currentChar() === ch) {
  682. scnr.next();
  683. return ch;
  684. }
  685. else {
  686. emitError(0 /* EXPECTED_TOKEN */, currentPosition(), 0, ch);
  687. return '';
  688. }
  689. }
  690. function peekSpaces(scnr) {
  691. let buf = '';
  692. while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
  693. buf += scnr.currentPeek();
  694. scnr.peek();
  695. }
  696. return buf;
  697. }
  698. function skipSpaces(scnr) {
  699. const buf = peekSpaces(scnr);
  700. scnr.skipToPeek();
  701. return buf;
  702. }
  703. function isIdentifierStart(ch) {
  704. if (ch === EOF) {
  705. return false;
  706. }
  707. const cc = ch.charCodeAt(0);
  708. return ((cc >= 97 && cc <= 122) || // a-z
  709. (cc >= 65 && cc <= 90) || // A-Z
  710. cc === 95 // _
  711. );
  712. }
  713. function isNumberStart(ch) {
  714. if (ch === EOF) {
  715. return false;
  716. }
  717. const cc = ch.charCodeAt(0);
  718. return cc >= 48 && cc <= 57; // 0-9
  719. }
  720. function isNamedIdentifierStart(scnr, context) {
  721. const { currentType } = context;
  722. if (currentType !== 2 /* BraceLeft */) {
  723. return false;
  724. }
  725. peekSpaces(scnr);
  726. const ret = isIdentifierStart(scnr.currentPeek());
  727. scnr.resetPeek();
  728. return ret;
  729. }
  730. function isListIdentifierStart(scnr, context) {
  731. const { currentType } = context;
  732. if (currentType !== 2 /* BraceLeft */) {
  733. return false;
  734. }
  735. peekSpaces(scnr);
  736. const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
  737. const ret = isNumberStart(ch);
  738. scnr.resetPeek();
  739. return ret;
  740. }
  741. function isLiteralStart(scnr, context) {
  742. const { currentType } = context;
  743. if (currentType !== 2 /* BraceLeft */) {
  744. return false;
  745. }
  746. peekSpaces(scnr);
  747. const ret = scnr.currentPeek() === LITERAL_DELIMITER;
  748. scnr.resetPeek();
  749. return ret;
  750. }
  751. function isLinkedDotStart(scnr, context) {
  752. const { currentType } = context;
  753. if (currentType !== 8 /* LinkedAlias */) {
  754. return false;
  755. }
  756. peekSpaces(scnr);
  757. const ret = scnr.currentPeek() === "." /* LinkedDot */;
  758. scnr.resetPeek();
  759. return ret;
  760. }
  761. function isLinkedModifierStart(scnr, context) {
  762. const { currentType } = context;
  763. if (currentType !== 9 /* LinkedDot */) {
  764. return false;
  765. }
  766. peekSpaces(scnr);
  767. const ret = isIdentifierStart(scnr.currentPeek());
  768. scnr.resetPeek();
  769. return ret;
  770. }
  771. function isLinkedDelimiterStart(scnr, context) {
  772. const { currentType } = context;
  773. if (!(currentType === 8 /* LinkedAlias */ ||
  774. currentType === 12 /* LinkedModifier */)) {
  775. return false;
  776. }
  777. peekSpaces(scnr);
  778. const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */;
  779. scnr.resetPeek();
  780. return ret;
  781. }
  782. function isLinkedReferStart(scnr, context) {
  783. const { currentType } = context;
  784. if (currentType !== 10 /* LinkedDelimiter */) {
  785. return false;
  786. }
  787. const fn = () => {
  788. const ch = scnr.currentPeek();
  789. if (ch === "{" /* BraceLeft */) {
  790. return isIdentifierStart(scnr.peek());
  791. }
  792. else if (ch === "@" /* LinkedAlias */ ||
  793. ch === "%" /* Modulo */ ||
  794. ch === "|" /* Pipe */ ||
  795. ch === ":" /* LinkedDelimiter */ ||
  796. ch === "." /* LinkedDot */ ||
  797. ch === CHAR_SP ||
  798. !ch) {
  799. return false;
  800. }
  801. else if (ch === CHAR_LF) {
  802. scnr.peek();
  803. return fn();
  804. }
  805. else {
  806. // other characters
  807. return isIdentifierStart(ch);
  808. }
  809. };
  810. const ret = fn();
  811. scnr.resetPeek();
  812. return ret;
  813. }
  814. function isPluralStart(scnr) {
  815. peekSpaces(scnr);
  816. const ret = scnr.currentPeek() === "|" /* Pipe */;
  817. scnr.resetPeek();
  818. return ret;
  819. }
  820. function isTextStart(scnr, reset = true) {
  821. const fn = (hasSpace = false, prev = '', detectModulo = false) => {
  822. const ch = scnr.currentPeek();
  823. if (ch === "{" /* BraceLeft */) {
  824. return prev === "%" /* Modulo */ ? false : hasSpace;
  825. }
  826. else if (ch === "@" /* LinkedAlias */ || !ch) {
  827. return prev === "%" /* Modulo */ ? true : hasSpace;
  828. }
  829. else if (ch === "%" /* Modulo */) {
  830. scnr.peek();
  831. return fn(hasSpace, "%" /* Modulo */, true);
  832. }
  833. else if (ch === "|" /* Pipe */) {
  834. return prev === "%" /* Modulo */ || detectModulo
  835. ? true
  836. : !(prev === CHAR_SP || prev === CHAR_LF);
  837. }
  838. else if (ch === CHAR_SP) {
  839. scnr.peek();
  840. return fn(true, CHAR_SP, detectModulo);
  841. }
  842. else if (ch === CHAR_LF) {
  843. scnr.peek();
  844. return fn(true, CHAR_LF, detectModulo);
  845. }
  846. else {
  847. return true;
  848. }
  849. };
  850. const ret = fn();
  851. reset && scnr.resetPeek();
  852. return ret;
  853. }
  854. function takeChar(scnr, fn) {
  855. const ch = scnr.currentChar();
  856. if (ch === EOF) {
  857. return EOF;
  858. }
  859. if (fn(ch)) {
  860. scnr.next();
  861. return ch;
  862. }
  863. return null;
  864. }
  865. function takeIdentifierChar(scnr) {
  866. const closure = (ch) => {
  867. const cc = ch.charCodeAt(0);
  868. return ((cc >= 97 && cc <= 122) || // a-z
  869. (cc >= 65 && cc <= 90) || // A-Z
  870. (cc >= 48 && cc <= 57) || // 0-9
  871. cc === 95 || // _
  872. cc === 36 // $
  873. );
  874. };
  875. return takeChar(scnr, closure);
  876. }
  877. function takeDigit(scnr) {
  878. const closure = (ch) => {
  879. const cc = ch.charCodeAt(0);
  880. return cc >= 48 && cc <= 57; // 0-9
  881. };
  882. return takeChar(scnr, closure);
  883. }
  884. function takeHexDigit(scnr) {
  885. const closure = (ch) => {
  886. const cc = ch.charCodeAt(0);
  887. return ((cc >= 48 && cc <= 57) || // 0-9
  888. (cc >= 65 && cc <= 70) || // A-F
  889. (cc >= 97 && cc <= 102)); // a-f
  890. };
  891. return takeChar(scnr, closure);
  892. }
  893. function getDigits(scnr) {
  894. let ch = '';
  895. let num = '';
  896. while ((ch = takeDigit(scnr))) {
  897. num += ch;
  898. }
  899. return num;
  900. }
  901. function readText(scnr) {
  902. let buf = '';
  903. while (true) {
  904. const ch = scnr.currentChar();
  905. if (ch === "{" /* BraceLeft */ ||
  906. ch === "}" /* BraceRight */ ||
  907. ch === "@" /* LinkedAlias */ ||
  908. ch === "|" /* Pipe */ ||
  909. !ch) {
  910. break;
  911. }
  912. else if (ch === "%" /* Modulo */) {
  913. if (isTextStart(scnr)) {
  914. buf += ch;
  915. scnr.next();
  916. }
  917. else {
  918. break;
  919. }
  920. }
  921. else if (ch === CHAR_SP || ch === CHAR_LF) {
  922. if (isTextStart(scnr)) {
  923. buf += ch;
  924. scnr.next();
  925. }
  926. else if (isPluralStart(scnr)) {
  927. break;
  928. }
  929. else {
  930. buf += ch;
  931. scnr.next();
  932. }
  933. }
  934. else {
  935. buf += ch;
  936. scnr.next();
  937. }
  938. }
  939. return buf;
  940. }
  941. function readNamedIdentifier(scnr) {
  942. skipSpaces(scnr);
  943. let ch = '';
  944. let name = '';
  945. while ((ch = takeIdentifierChar(scnr))) {
  946. name += ch;
  947. }
  948. if (scnr.currentChar() === EOF) {
  949. emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
  950. }
  951. return name;
  952. }
  953. function readListIdentifier(scnr) {
  954. skipSpaces(scnr);
  955. let value = '';
  956. if (scnr.currentChar() === '-') {
  957. scnr.next();
  958. value += `-${getDigits(scnr)}`;
  959. }
  960. else {
  961. value += getDigits(scnr);
  962. }
  963. if (scnr.currentChar() === EOF) {
  964. emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
  965. }
  966. return value;
  967. }
  968. function readLiteral(scnr) {
  969. skipSpaces(scnr);
  970. eat(scnr, `\'`);
  971. let ch = '';
  972. let literal = '';
  973. const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF;
  974. while ((ch = takeChar(scnr, fn))) {
  975. if (ch === '\\') {
  976. literal += readEscapeSequence(scnr);
  977. }
  978. else {
  979. literal += ch;
  980. }
  981. }
  982. const current = scnr.currentChar();
  983. if (current === CHAR_LF || current === EOF) {
  984. emitError(2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */, currentPosition(), 0);
  985. // TODO: Is it correct really?
  986. if (current === CHAR_LF) {
  987. scnr.next();
  988. eat(scnr, `\'`);
  989. }
  990. return literal;
  991. }
  992. eat(scnr, `\'`);
  993. return literal;
  994. }
  995. function readEscapeSequence(scnr) {
  996. const ch = scnr.currentChar();
  997. switch (ch) {
  998. case '\\':
  999. case `\'`:
  1000. scnr.next();
  1001. return `\\${ch}`;
  1002. case 'u':
  1003. return readUnicodeEscapeSequence(scnr, ch, 4);
  1004. case 'U':
  1005. return readUnicodeEscapeSequence(scnr, ch, 6);
  1006. default:
  1007. emitError(3 /* UNKNOWN_ESCAPE_SEQUENCE */, currentPosition(), 0, ch);
  1008. return '';
  1009. }
  1010. }
  1011. function readUnicodeEscapeSequence(scnr, unicode, digits) {
  1012. eat(scnr, unicode);
  1013. let sequence = '';
  1014. for (let i = 0; i < digits; i++) {
  1015. const ch = takeHexDigit(scnr);
  1016. if (!ch) {
  1017. emitError(4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
  1018. break;
  1019. }
  1020. sequence += ch;
  1021. }
  1022. return `\\${unicode}${sequence}`;
  1023. }
  1024. function readInvalidIdentifier(scnr) {
  1025. skipSpaces(scnr);
  1026. let ch = '';
  1027. let identifiers = '';
  1028. const closure = (ch) => ch !== "{" /* BraceLeft */ &&
  1029. ch !== "}" /* BraceRight */ &&
  1030. ch !== CHAR_SP &&
  1031. ch !== CHAR_LF;
  1032. while ((ch = takeChar(scnr, closure))) {
  1033. identifiers += ch;
  1034. }
  1035. return identifiers;
  1036. }
  1037. function readLinkedModifier(scnr) {
  1038. let ch = '';
  1039. let name = '';
  1040. while ((ch = takeIdentifierChar(scnr))) {
  1041. name += ch;
  1042. }
  1043. return name;
  1044. }
  1045. function readLinkedRefer(scnr) {
  1046. const fn = (detect = false, buf) => {
  1047. const ch = scnr.currentChar();
  1048. if (ch === "{" /* BraceLeft */ ||
  1049. ch === "%" /* Modulo */ ||
  1050. ch === "@" /* LinkedAlias */ ||
  1051. ch === "|" /* Pipe */ ||
  1052. !ch) {
  1053. return buf;
  1054. }
  1055. else if (ch === CHAR_SP) {
  1056. return buf;
  1057. }
  1058. else if (ch === CHAR_LF) {
  1059. buf += ch;
  1060. scnr.next();
  1061. return fn(detect, buf);
  1062. }
  1063. else {
  1064. buf += ch;
  1065. scnr.next();
  1066. return fn(true, buf);
  1067. }
  1068. };
  1069. return fn(false, '');
  1070. }
  1071. function readPlural(scnr) {
  1072. skipSpaces(scnr);
  1073. const plural = eat(scnr, "|" /* Pipe */);
  1074. skipSpaces(scnr);
  1075. return plural;
  1076. }
  1077. // TODO: We need refactoring of token parsing ...
  1078. function readTokenInPlaceholder(scnr, context) {
  1079. let token = null;
  1080. const ch = scnr.currentChar();
  1081. switch (ch) {
  1082. case "{" /* BraceLeft */:
  1083. if (context.braceNest >= 1) {
  1084. emitError(8 /* NOT_ALLOW_NEST_PLACEHOLDER */, currentPosition(), 0);
  1085. }
  1086. scnr.next();
  1087. token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */);
  1088. skipSpaces(scnr);
  1089. context.braceNest++;
  1090. return token;
  1091. case "}" /* BraceRight */:
  1092. if (context.braceNest > 0 &&
  1093. context.currentType === 2 /* BraceLeft */) {
  1094. emitError(7 /* EMPTY_PLACEHOLDER */, currentPosition(), 0);
  1095. }
  1096. scnr.next();
  1097. token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */);
  1098. context.braceNest--;
  1099. context.braceNest > 0 && skipSpaces(scnr);
  1100. if (context.inLinked && context.braceNest === 0) {
  1101. context.inLinked = false;
  1102. }
  1103. return token;
  1104. case "@" /* LinkedAlias */:
  1105. if (context.braceNest > 0) {
  1106. emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
  1107. }
  1108. token = readTokenInLinked(scnr, context) || getEndToken(context);
  1109. context.braceNest = 0;
  1110. return token;
  1111. default:
  1112. let validNamedIdentifier = true;
  1113. let validListIdentifier = true;
  1114. let validLiteral = true;
  1115. if (isPluralStart(scnr)) {
  1116. if (context.braceNest > 0) {
  1117. emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
  1118. }
  1119. token = getToken(context, 1 /* Pipe */, readPlural(scnr));
  1120. // reset
  1121. context.braceNest = 0;
  1122. context.inLinked = false;
  1123. return token;
  1124. }
  1125. if (context.braceNest > 0 &&
  1126. (context.currentType === 5 /* Named */ ||
  1127. context.currentType === 6 /* List */ ||
  1128. context.currentType === 7 /* Literal */)) {
  1129. emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
  1130. context.braceNest = 0;
  1131. return readToken(scnr, context);
  1132. }
  1133. if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
  1134. token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr));
  1135. skipSpaces(scnr);
  1136. return token;
  1137. }
  1138. if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
  1139. token = getToken(context, 6 /* List */, readListIdentifier(scnr));
  1140. skipSpaces(scnr);
  1141. return token;
  1142. }
  1143. if ((validLiteral = isLiteralStart(scnr, context))) {
  1144. token = getToken(context, 7 /* Literal */, readLiteral(scnr));
  1145. skipSpaces(scnr);
  1146. return token;
  1147. }
  1148. if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
  1149. // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
  1150. token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr));
  1151. emitError(1 /* INVALID_TOKEN_IN_PLACEHOLDER */, currentPosition(), 0, token.value);
  1152. skipSpaces(scnr);
  1153. return token;
  1154. }
  1155. break;
  1156. }
  1157. return token;
  1158. }
  1159. // TODO: We need refactoring of token parsing ...
  1160. function readTokenInLinked(scnr, context) {
  1161. const { currentType } = context;
  1162. let token = null;
  1163. const ch = scnr.currentChar();
  1164. if ((currentType === 8 /* LinkedAlias */ ||
  1165. currentType === 9 /* LinkedDot */ ||
  1166. currentType === 12 /* LinkedModifier */ ||
  1167. currentType === 10 /* LinkedDelimiter */) &&
  1168. (ch === CHAR_LF || ch === CHAR_SP)) {
  1169. emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0);
  1170. }
  1171. switch (ch) {
  1172. case "@" /* LinkedAlias */:
  1173. scnr.next();
  1174. token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */);
  1175. context.inLinked = true;
  1176. return token;
  1177. case "." /* LinkedDot */:
  1178. skipSpaces(scnr);
  1179. scnr.next();
  1180. return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */);
  1181. case ":" /* LinkedDelimiter */:
  1182. skipSpaces(scnr);
  1183. scnr.next();
  1184. return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */);
  1185. default:
  1186. if (isPluralStart(scnr)) {
  1187. token = getToken(context, 1 /* Pipe */, readPlural(scnr));
  1188. // reset
  1189. context.braceNest = 0;
  1190. context.inLinked = false;
  1191. return token;
  1192. }
  1193. if (isLinkedDotStart(scnr, context) ||
  1194. isLinkedDelimiterStart(scnr, context)) {
  1195. skipSpaces(scnr);
  1196. return readTokenInLinked(scnr, context);
  1197. }
  1198. if (isLinkedModifierStart(scnr, context)) {
  1199. skipSpaces(scnr);
  1200. return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr));
  1201. }
  1202. if (isLinkedReferStart(scnr, context)) {
  1203. skipSpaces(scnr);
  1204. if (ch === "{" /* BraceLeft */) {
  1205. // scan the placeholder
  1206. return readTokenInPlaceholder(scnr, context) || token;
  1207. }
  1208. else {
  1209. return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr));
  1210. }
  1211. }
  1212. if (currentType === 8 /* LinkedAlias */) {
  1213. emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0);
  1214. }
  1215. context.braceNest = 0;
  1216. context.inLinked = false;
  1217. return readToken(scnr, context);
  1218. }
  1219. }
  1220. // TODO: We need refactoring of token parsing ...
  1221. function readToken(scnr, context) {
  1222. let token = { type: 14 /* EOF */ };
  1223. if (context.braceNest > 0) {
  1224. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  1225. }
  1226. if (context.inLinked) {
  1227. return readTokenInLinked(scnr, context) || getEndToken(context);
  1228. }
  1229. const ch = scnr.currentChar();
  1230. switch (ch) {
  1231. case "{" /* BraceLeft */:
  1232. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  1233. case "}" /* BraceRight */:
  1234. emitError(5 /* UNBALANCED_CLOSING_BRACE */, currentPosition(), 0);
  1235. scnr.next();
  1236. return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */);
  1237. case "@" /* LinkedAlias */:
  1238. return readTokenInLinked(scnr, context) || getEndToken(context);
  1239. default:
  1240. if (isPluralStart(scnr)) {
  1241. token = getToken(context, 1 /* Pipe */, readPlural(scnr));
  1242. // reset
  1243. context.braceNest = 0;
  1244. context.inLinked = false;
  1245. return token;
  1246. }
  1247. if (isTextStart(scnr)) {
  1248. return getToken(context, 0 /* Text */, readText(scnr));
  1249. }
  1250. if (ch === "%" /* Modulo */) {
  1251. scnr.next();
  1252. return getToken(context, 4 /* Modulo */, "%" /* Modulo */);
  1253. }
  1254. break;
  1255. }
  1256. return token;
  1257. }
  1258. function nextToken() {
  1259. const { currentType, offset, startLoc, endLoc } = _context;
  1260. _context.lastType = currentType;
  1261. _context.lastOffset = offset;
  1262. _context.lastStartLoc = startLoc;
  1263. _context.lastEndLoc = endLoc;
  1264. _context.offset = currentOffset();
  1265. _context.startLoc = currentPosition();
  1266. if (_scnr.currentChar() === EOF) {
  1267. return getToken(_context, 14 /* EOF */);
  1268. }
  1269. return readToken(_scnr, _context);
  1270. }
  1271. return {
  1272. nextToken,
  1273. currentOffset,
  1274. currentPosition,
  1275. context
  1276. };
  1277. }
  1278. const ERROR_DOMAIN = 'parser';
  1279. // Backslash backslash, backslash quote, uHHHH, UHHHHHH.
  1280. const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
  1281. function fromEscapeSequence(match, codePoint4, codePoint6) {
  1282. switch (match) {
  1283. case `\\\\`:
  1284. return `\\`;
  1285. case `\\\'`:
  1286. return `\'`;
  1287. default: {
  1288. const codePoint = parseInt(codePoint4 || codePoint6, 16);
  1289. if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
  1290. return String.fromCodePoint(codePoint);
  1291. }
  1292. // invalid ...
  1293. // Replace them with U+FFFD REPLACEMENT CHARACTER.
  1294. return '�';
  1295. }
  1296. }
  1297. }
  1298. function createParser(options = {}) {
  1299. const location = options.location !== false;
  1300. const { onError } = options;
  1301. function emitError(tokenzer, code, start, offset, ...args) {
  1302. const end = tokenzer.currentPosition();
  1303. end.offset += offset;
  1304. end.column += offset;
  1305. if (onError) {
  1306. const loc = createLocation(start, end);
  1307. const err = createCompileError(code, loc, {
  1308. domain: ERROR_DOMAIN,
  1309. args
  1310. });
  1311. onError(err);
  1312. }
  1313. }
  1314. function startNode(type, offset, loc) {
  1315. const node = {
  1316. type,
  1317. start: offset,
  1318. end: offset
  1319. };
  1320. if (location) {
  1321. node.loc = { start: loc, end: loc };
  1322. }
  1323. return node;
  1324. }
  1325. function endNode(node, offset, pos, type) {
  1326. node.end = offset;
  1327. if (type) {
  1328. node.type = type;
  1329. }
  1330. if (location && node.loc) {
  1331. node.loc.end = pos;
  1332. }
  1333. }
  1334. function parseText(tokenizer, value) {
  1335. const context = tokenizer.context();
  1336. const node = startNode(3 /* Text */, context.offset, context.startLoc);
  1337. node.value = value;
  1338. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1339. return node;
  1340. }
  1341. function parseList(tokenizer, index) {
  1342. const context = tokenizer.context();
  1343. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1344. const node = startNode(5 /* List */, offset, loc);
  1345. node.index = parseInt(index, 10);
  1346. tokenizer.nextToken(); // skip brach right
  1347. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1348. return node;
  1349. }
  1350. function parseNamed(tokenizer, key) {
  1351. const context = tokenizer.context();
  1352. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1353. const node = startNode(4 /* Named */, offset, loc);
  1354. node.key = key;
  1355. tokenizer.nextToken(); // skip brach right
  1356. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1357. return node;
  1358. }
  1359. function parseLiteral(tokenizer, value) {
  1360. const context = tokenizer.context();
  1361. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1362. const node = startNode(9 /* Literal */, offset, loc);
  1363. node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
  1364. tokenizer.nextToken(); // skip brach right
  1365. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1366. return node;
  1367. }
  1368. function parseLinkedModifier(tokenizer) {
  1369. const token = tokenizer.nextToken();
  1370. const context = tokenizer.context();
  1371. const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
  1372. const node = startNode(8 /* LinkedModifier */, offset, loc);
  1373. if (token.type !== 12 /* LinkedModifier */) {
  1374. // empty modifier
  1375. emitError(tokenizer, 11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */, context.lastStartLoc, 0);
  1376. node.value = '';
  1377. endNode(node, offset, loc);
  1378. return {
  1379. nextConsumeToken: token,
  1380. node
  1381. };
  1382. }
  1383. // check token
  1384. if (token.value == null) {
  1385. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1386. }
  1387. node.value = token.value || '';
  1388. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1389. return {
  1390. node
  1391. };
  1392. }
  1393. function parseLinkedKey(tokenizer, value) {
  1394. const context = tokenizer.context();
  1395. const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc);
  1396. node.value = value;
  1397. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1398. return node;
  1399. }
  1400. function parseLinked(tokenizer) {
  1401. const context = tokenizer.context();
  1402. const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc);
  1403. let token = tokenizer.nextToken();
  1404. if (token.type === 9 /* LinkedDot */) {
  1405. const parsed = parseLinkedModifier(tokenizer);
  1406. linkedNode.modifier = parsed.node;
  1407. token = parsed.nextConsumeToken || tokenizer.nextToken();
  1408. }
  1409. // asset check token
  1410. if (token.type !== 10 /* LinkedDelimiter */) {
  1411. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1412. }
  1413. token = tokenizer.nextToken();
  1414. // skip brace left
  1415. if (token.type === 2 /* BraceLeft */) {
  1416. token = tokenizer.nextToken();
  1417. }
  1418. switch (token.type) {
  1419. case 11 /* LinkedKey */:
  1420. if (token.value == null) {
  1421. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1422. }
  1423. linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
  1424. break;
  1425. case 5 /* Named */:
  1426. if (token.value == null) {
  1427. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1428. }
  1429. linkedNode.key = parseNamed(tokenizer, token.value || '');
  1430. break;
  1431. case 6 /* List */:
  1432. if (token.value == null) {
  1433. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1434. }
  1435. linkedNode.key = parseList(tokenizer, token.value || '');
  1436. break;
  1437. case 7 /* Literal */:
  1438. if (token.value == null) {
  1439. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1440. }
  1441. linkedNode.key = parseLiteral(tokenizer, token.value || '');
  1442. break;
  1443. default:
  1444. // empty key
  1445. emitError(tokenizer, 12 /* UNEXPECTED_EMPTY_LINKED_KEY */, context.lastStartLoc, 0);
  1446. const nextContext = tokenizer.context();
  1447. const emptyLinkedKeyNode = startNode(7 /* LinkedKey */, nextContext.offset, nextContext.startLoc);
  1448. emptyLinkedKeyNode.value = '';
  1449. endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
  1450. linkedNode.key = emptyLinkedKeyNode;
  1451. endNode(linkedNode, nextContext.offset, nextContext.startLoc);
  1452. return {
  1453. nextConsumeToken: token,
  1454. node: linkedNode
  1455. };
  1456. }
  1457. endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
  1458. return {
  1459. node: linkedNode
  1460. };
  1461. }
  1462. function parseMessage(tokenizer) {
  1463. const context = tokenizer.context();
  1464. const startOffset = context.currentType === 1 /* Pipe */
  1465. ? tokenizer.currentOffset()
  1466. : context.offset;
  1467. const startLoc = context.currentType === 1 /* Pipe */
  1468. ? context.endLoc
  1469. : context.startLoc;
  1470. const node = startNode(2 /* Message */, startOffset, startLoc);
  1471. node.items = [];
  1472. let nextToken = null;
  1473. do {
  1474. const token = nextToken || tokenizer.nextToken();
  1475. nextToken = null;
  1476. switch (token.type) {
  1477. case 0 /* Text */:
  1478. if (token.value == null) {
  1479. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1480. }
  1481. node.items.push(parseText(tokenizer, token.value || ''));
  1482. break;
  1483. case 6 /* List */:
  1484. if (token.value == null) {
  1485. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1486. }
  1487. node.items.push(parseList(tokenizer, token.value || ''));
  1488. break;
  1489. case 5 /* Named */:
  1490. if (token.value == null) {
  1491. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1492. }
  1493. node.items.push(parseNamed(tokenizer, token.value || ''));
  1494. break;
  1495. case 7 /* Literal */:
  1496. if (token.value == null) {
  1497. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1498. }
  1499. node.items.push(parseLiteral(tokenizer, token.value || ''));
  1500. break;
  1501. case 8 /* LinkedAlias */:
  1502. const parsed = parseLinked(tokenizer);
  1503. node.items.push(parsed.node);
  1504. nextToken = parsed.nextConsumeToken || null;
  1505. break;
  1506. }
  1507. } while (context.currentType !== 14 /* EOF */ &&
  1508. context.currentType !== 1 /* Pipe */);
  1509. // adjust message node loc
  1510. const endOffset = context.currentType === 1 /* Pipe */
  1511. ? context.lastOffset
  1512. : tokenizer.currentOffset();
  1513. const endLoc = context.currentType === 1 /* Pipe */
  1514. ? context.lastEndLoc
  1515. : tokenizer.currentPosition();
  1516. endNode(node, endOffset, endLoc);
  1517. return node;
  1518. }
  1519. function parsePlural(tokenizer, offset, loc, msgNode) {
  1520. const context = tokenizer.context();
  1521. let hasEmptyMessage = msgNode.items.length === 0;
  1522. const node = startNode(1 /* Plural */, offset, loc);
  1523. node.cases = [];
  1524. node.cases.push(msgNode);
  1525. do {
  1526. const msg = parseMessage(tokenizer);
  1527. if (!hasEmptyMessage) {
  1528. hasEmptyMessage = msg.items.length === 0;
  1529. }
  1530. node.cases.push(msg);
  1531. } while (context.currentType !== 14 /* EOF */);
  1532. if (hasEmptyMessage) {
  1533. emitError(tokenizer, 10 /* MUST_HAVE_MESSAGES_IN_PLURAL */, loc, 0);
  1534. }
  1535. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1536. return node;
  1537. }
  1538. function parseResource(tokenizer) {
  1539. const context = tokenizer.context();
  1540. const { offset, startLoc } = context;
  1541. const msgNode = parseMessage(tokenizer);
  1542. if (context.currentType === 14 /* EOF */) {
  1543. return msgNode;
  1544. }
  1545. else {
  1546. return parsePlural(tokenizer, offset, startLoc, msgNode);
  1547. }
  1548. }
  1549. function parse(source) {
  1550. const tokenizer = createTokenizer(source, assign({}, options));
  1551. const context = tokenizer.context();
  1552. const node = startNode(0 /* Resource */, context.offset, context.startLoc);
  1553. if (location && node.loc) {
  1554. node.loc.source = source;
  1555. }
  1556. node.body = parseResource(tokenizer);
  1557. // assert whether achieved to EOF
  1558. if (context.currentType !== 14 /* EOF */) {
  1559. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, source[context.offset] || '');
  1560. }
  1561. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1562. return node;
  1563. }
  1564. return { parse };
  1565. }
  1566. function getTokenCaption(token) {
  1567. if (token.type === 14 /* EOF */) {
  1568. return 'EOF';
  1569. }
  1570. const name = (token.value || '').replace(/\r?\n/gu, '\\n');
  1571. return name.length > 10 ? name.slice(0, 9) + '…' : name;
  1572. }
  1573. function createTransformer(ast, options = {} // eslint-disable-line
  1574. ) {
  1575. const _context = {
  1576. ast,
  1577. helpers: new Set()
  1578. };
  1579. const context = () => _context;
  1580. const helper = (name) => {
  1581. _context.helpers.add(name);
  1582. return name;
  1583. };
  1584. return { context, helper };
  1585. }
  1586. function traverseNodes(nodes, transformer) {
  1587. for (let i = 0; i < nodes.length; i++) {
  1588. traverseNode(nodes[i], transformer);
  1589. }
  1590. }
  1591. function traverseNode(node, transformer) {
  1592. // TODO: if we need pre-hook of transform, should be implemented to here
  1593. switch (node.type) {
  1594. case 1 /* Plural */:
  1595. traverseNodes(node.cases, transformer);
  1596. transformer.helper("plural" /* PLURAL */);
  1597. break;
  1598. case 2 /* Message */:
  1599. traverseNodes(node.items, transformer);
  1600. break;
  1601. case 6 /* Linked */:
  1602. const linked = node;
  1603. traverseNode(linked.key, transformer);
  1604. transformer.helper("linked" /* LINKED */);
  1605. break;
  1606. case 5 /* List */:
  1607. transformer.helper("interpolate" /* INTERPOLATE */);
  1608. transformer.helper("list" /* LIST */);
  1609. break;
  1610. case 4 /* Named */:
  1611. transformer.helper("interpolate" /* INTERPOLATE */);
  1612. transformer.helper("named" /* NAMED */);
  1613. break;
  1614. }
  1615. // TODO: if we need post-hook of transform, should be implemented to here
  1616. }
  1617. // transform AST
  1618. function transform(ast, options = {} // eslint-disable-line
  1619. ) {
  1620. const transformer = createTransformer(ast);
  1621. transformer.helper("normalize" /* NORMALIZE */);
  1622. // traverse
  1623. ast.body && traverseNode(ast.body, transformer);
  1624. // set meta information
  1625. const context = transformer.context();
  1626. ast.helpers = Array.from(context.helpers);
  1627. }
  1628. function createCodeGenerator(ast, options) {
  1629. const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
  1630. const _context = {
  1631. source: ast.loc.source,
  1632. filename,
  1633. code: '',
  1634. column: 1,
  1635. line: 1,
  1636. offset: 0,
  1637. map: undefined,
  1638. breakLineCode,
  1639. needIndent: _needIndent,
  1640. indentLevel: 0
  1641. };
  1642. const context = () => _context;
  1643. function push(code, node) {
  1644. _context.code += code;
  1645. }
  1646. function _newline(n, withBreakLine = true) {
  1647. const _breakLineCode = withBreakLine ? breakLineCode : '';
  1648. push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
  1649. }
  1650. function indent(withNewLine = true) {
  1651. const level = ++_context.indentLevel;
  1652. withNewLine && _newline(level);
  1653. }
  1654. function deindent(withNewLine = true) {
  1655. const level = --_context.indentLevel;
  1656. withNewLine && _newline(level);
  1657. }
  1658. function newline() {
  1659. _newline(_context.indentLevel);
  1660. }
  1661. const helper = (key) => `_${key}`;
  1662. const needIndent = () => _context.needIndent;
  1663. return {
  1664. context,
  1665. push,
  1666. indent,
  1667. deindent,
  1668. newline,
  1669. helper,
  1670. needIndent
  1671. };
  1672. }
  1673. function generateLinkedNode(generator, node) {
  1674. const { helper } = generator;
  1675. generator.push(`${helper("linked" /* LINKED */)}(`);
  1676. generateNode(generator, node.key);
  1677. if (node.modifier) {
  1678. generator.push(`, `);
  1679. generateNode(generator, node.modifier);
  1680. }
  1681. generator.push(`)`);
  1682. }
  1683. function generateMessageNode(generator, node) {
  1684. const { helper, needIndent } = generator;
  1685. generator.push(`${helper("normalize" /* NORMALIZE */)}([`);
  1686. generator.indent(needIndent());
  1687. const length = node.items.length;
  1688. for (let i = 0; i < length; i++) {
  1689. generateNode(generator, node.items[i]);
  1690. if (i === length - 1) {
  1691. break;
  1692. }
  1693. generator.push(', ');
  1694. }
  1695. generator.deindent(needIndent());
  1696. generator.push('])');
  1697. }
  1698. function generatePluralNode(generator, node) {
  1699. const { helper, needIndent } = generator;
  1700. if (node.cases.length > 1) {
  1701. generator.push(`${helper("plural" /* PLURAL */)}([`);
  1702. generator.indent(needIndent());
  1703. const length = node.cases.length;
  1704. for (let i = 0; i < length; i++) {
  1705. generateNode(generator, node.cases[i]);
  1706. if (i === length - 1) {
  1707. break;
  1708. }
  1709. generator.push(', ');
  1710. }
  1711. generator.deindent(needIndent());
  1712. generator.push(`])`);
  1713. }
  1714. }
  1715. function generateResource(generator, node) {
  1716. if (node.body) {
  1717. generateNode(generator, node.body);
  1718. }
  1719. else {
  1720. generator.push('null');
  1721. }
  1722. }
  1723. function generateNode(generator, node) {
  1724. const { helper } = generator;
  1725. switch (node.type) {
  1726. case 0 /* Resource */:
  1727. generateResource(generator, node);
  1728. break;
  1729. case 1 /* Plural */:
  1730. generatePluralNode(generator, node);
  1731. break;
  1732. case 2 /* Message */:
  1733. generateMessageNode(generator, node);
  1734. break;
  1735. case 6 /* Linked */:
  1736. generateLinkedNode(generator, node);
  1737. break;
  1738. case 8 /* LinkedModifier */:
  1739. generator.push(JSON.stringify(node.value), node);
  1740. break;
  1741. case 7 /* LinkedKey */:
  1742. generator.push(JSON.stringify(node.value), node);
  1743. break;
  1744. case 5 /* List */:
  1745. generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node);
  1746. break;
  1747. case 4 /* Named */:
  1748. generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node);
  1749. break;
  1750. case 9 /* Literal */:
  1751. generator.push(JSON.stringify(node.value), node);
  1752. break;
  1753. case 3 /* Text */:
  1754. generator.push(JSON.stringify(node.value), node);
  1755. break;
  1756. default:
  1757. {
  1758. throw new Error(`unhandled codegen node type: ${node.type}`);
  1759. }
  1760. }
  1761. }
  1762. // generate code from AST
  1763. const generate = (ast, options = {} // eslint-disable-line
  1764. ) => {
  1765. const mode = isString(options.mode) ? options.mode : 'normal';
  1766. const filename = isString(options.filename)
  1767. ? options.filename
  1768. : 'message.intl';
  1769. const sourceMap = !!options.sourceMap;
  1770. // prettier-ignore
  1771. const breakLineCode = options.breakLineCode != null
  1772. ? options.breakLineCode
  1773. : mode === 'arrow'
  1774. ? ';'
  1775. : '\n';
  1776. const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
  1777. const helpers = ast.helpers || [];
  1778. const generator = createCodeGenerator(ast, {
  1779. mode,
  1780. filename,
  1781. sourceMap,
  1782. breakLineCode,
  1783. needIndent
  1784. });
  1785. generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
  1786. generator.indent(needIndent);
  1787. if (helpers.length > 0) {
  1788. generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`);
  1789. generator.newline();
  1790. }
  1791. generator.push(`return `);
  1792. generateNode(generator, ast);
  1793. generator.deindent(needIndent);
  1794. generator.push(`}`);
  1795. const { code, map } = generator.context();
  1796. return {
  1797. ast,
  1798. code,
  1799. map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
  1800. };
  1801. };
  1802. function baseCompile(source, options = {}) {
  1803. const assignedOptions = assign({}, options);
  1804. // parse source codes
  1805. const parser = createParser(assignedOptions);
  1806. const ast = parser.parse(source);
  1807. // transform ASTs
  1808. transform(ast, assignedOptions);
  1809. // generate javascript codes
  1810. return generate(ast, assignedOptions);
  1811. }
  1812. const IntlifyDevToolsHooks = {
  1813. I18nInit: 'i18n:init',
  1814. FunctionTranslate: 'function:translate'
  1815. };
  1816. let devtools = null;
  1817. function setDevToolsHook(hook) {
  1818. devtools = hook;
  1819. }
  1820. function getDevToolsHook() {
  1821. return devtools;
  1822. }
  1823. function initI18nDevTools(i18n, version, meta) {
  1824. // TODO: queue if devtools is undefined
  1825. devtools &&
  1826. devtools.emit(IntlifyDevToolsHooks.I18nInit, {
  1827. timestamp: Date.now(),
  1828. i18n,
  1829. version,
  1830. meta
  1831. });
  1832. }
  1833. const translateDevTools = /* #__PURE__*/ createDevToolsHook(IntlifyDevToolsHooks.FunctionTranslate);
  1834. function createDevToolsHook(hook) {
  1835. return (payloads) => devtools && devtools.emit(hook, payloads);
  1836. }
  1837. /** @internal */
  1838. const warnMessages = {
  1839. [0 /* NOT_FOUND_KEY */]: `Not found '{key}' key in '{locale}' locale messages.`,
  1840. [1 /* FALLBACK_TO_TRANSLATE */]: `Fall back to translate '{key}' key with '{target}' locale.`,
  1841. [2 /* CANNOT_FORMAT_NUMBER */]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
  1842. [3 /* FALLBACK_TO_NUMBER_FORMAT */]: `Fall back to number format '{key}' key with '{target}' locale.`,
  1843. [4 /* CANNOT_FORMAT_DATE */]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
  1844. [5 /* FALLBACK_TO_DATE_FORMAT */]: `Fall back to datetime format '{key}' key with '{target}' locale.`
  1845. };
  1846. function getWarnMessage(code, ...args) {
  1847. return format(warnMessages[code], ...args);
  1848. }
  1849. /**
  1850. * Intlify core-base version
  1851. * @internal
  1852. */
  1853. const VERSION = '9.1.9';
  1854. const NOT_REOSLVED = -1;
  1855. const MISSING_RESOLVE_VALUE = '';
  1856. function getDefaultLinkedModifiers() {
  1857. return {
  1858. upper: (val) => (isString(val) ? val.toUpperCase() : val),
  1859. lower: (val) => (isString(val) ? val.toLowerCase() : val),
  1860. // prettier-ignore
  1861. capitalize: (val) => (isString(val)
  1862. ? `${val.charAt(0).toLocaleUpperCase()}${val.substr(1)}`
  1863. : val)
  1864. };
  1865. }
  1866. let _compiler;
  1867. function registerMessageCompiler(compiler) {
  1868. _compiler = compiler;
  1869. }
  1870. // Additional Meta for Intlify DevTools
  1871. let _additionalMeta = null;
  1872. const setAdditionalMeta = /* #__PURE__*/ (meta) => {
  1873. _additionalMeta = meta;
  1874. };
  1875. const getAdditionalMeta = /* #__PURE__*/ () => _additionalMeta;
  1876. // ID for CoreContext
  1877. let _cid = 0;
  1878. function createCoreContext(options = {}) {
  1879. // setup options
  1880. const version = isString(options.version) ? options.version : VERSION;
  1881. const locale = isString(options.locale) ? options.locale : 'en-US';
  1882. const fallbackLocale = isArray(options.fallbackLocale) ||
  1883. isPlainObject(options.fallbackLocale) ||
  1884. isString(options.fallbackLocale) ||
  1885. options.fallbackLocale === false
  1886. ? options.fallbackLocale
  1887. : locale;
  1888. const messages = isPlainObject(options.messages)
  1889. ? options.messages
  1890. : { [locale]: {} };
  1891. const datetimeFormats = isPlainObject(options.datetimeFormats)
  1892. ? options.datetimeFormats
  1893. : { [locale]: {} };
  1894. const numberFormats = isPlainObject(options.numberFormats)
  1895. ? options.numberFormats
  1896. : { [locale]: {} };
  1897. const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
  1898. const pluralRules = options.pluralRules || {};
  1899. const missing = isFunction(options.missing) ? options.missing : null;
  1900. const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  1901. ? options.missingWarn
  1902. : true;
  1903. const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  1904. ? options.fallbackWarn
  1905. : true;
  1906. const fallbackFormat = !!options.fallbackFormat;
  1907. const unresolving = !!options.unresolving;
  1908. const postTranslation = isFunction(options.postTranslation)
  1909. ? options.postTranslation
  1910. : null;
  1911. const processor = isPlainObject(options.processor) ? options.processor : null;
  1912. const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
  1913. ? options.warnHtmlMessage
  1914. : true;
  1915. const escapeParameter = !!options.escapeParameter;
  1916. const messageCompiler = isFunction(options.messageCompiler)
  1917. ? options.messageCompiler
  1918. : _compiler;
  1919. const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
  1920. // setup internal options
  1921. const internalOptions = options;
  1922. const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
  1923. ? internalOptions.__datetimeFormatters
  1924. : new Map();
  1925. const __numberFormatters = isObject(internalOptions.__numberFormatters)
  1926. ? internalOptions.__numberFormatters
  1927. : new Map();
  1928. const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
  1929. _cid++;
  1930. const context = {
  1931. version,
  1932. cid: _cid,
  1933. locale,
  1934. fallbackLocale,
  1935. messages,
  1936. datetimeFormats,
  1937. numberFormats,
  1938. modifiers,
  1939. pluralRules,
  1940. missing,
  1941. missingWarn,
  1942. fallbackWarn,
  1943. fallbackFormat,
  1944. unresolving,
  1945. postTranslation,
  1946. processor,
  1947. warnHtmlMessage,
  1948. escapeParameter,
  1949. messageCompiler,
  1950. onWarn,
  1951. __datetimeFormatters,
  1952. __numberFormatters,
  1953. __meta
  1954. };
  1955. // for vue-devtools timeline event
  1956. {
  1957. context.__v_emitter =
  1958. internalOptions.__v_emitter != null
  1959. ? internalOptions.__v_emitter
  1960. : undefined;
  1961. }
  1962. // NOTE: experimental !!
  1963. {
  1964. initI18nDevTools(context, version, __meta);
  1965. }
  1966. return context;
  1967. }
  1968. /** @internal */
  1969. function isTranslateFallbackWarn(fallback, key) {
  1970. return fallback instanceof RegExp ? fallback.test(key) : fallback;
  1971. }
  1972. /** @internal */
  1973. function isTranslateMissingWarn(missing, key) {
  1974. return missing instanceof RegExp ? missing.test(key) : missing;
  1975. }
  1976. /** @internal */
  1977. function handleMissing(context, key, locale, missingWarn, type) {
  1978. const { missing, onWarn } = context;
  1979. // for vue-devtools timeline event
  1980. {
  1981. const emitter = context.__v_emitter;
  1982. if (emitter) {
  1983. emitter.emit("missing" /* MISSING */, {
  1984. locale,
  1985. key,
  1986. type,
  1987. groupId: `${type}:${key}`
  1988. });
  1989. }
  1990. }
  1991. if (missing !== null) {
  1992. const ret = missing(context, locale, key, type);
  1993. return isString(ret) ? ret : key;
  1994. }
  1995. else {
  1996. if (isTranslateMissingWarn(missingWarn, key)) {
  1997. onWarn(getWarnMessage(0 /* NOT_FOUND_KEY */, { key, locale }));
  1998. }
  1999. return key;
  2000. }
  2001. }
  2002. /** @internal */
  2003. function getLocaleChain(ctx, fallback, start) {
  2004. const context = ctx;
  2005. if (!context.__localeChainCache) {
  2006. context.__localeChainCache = new Map();
  2007. }
  2008. let chain = context.__localeChainCache.get(start);
  2009. if (!chain) {
  2010. chain = [];
  2011. // first block defined by start
  2012. let block = [start];
  2013. // while any intervening block found
  2014. while (isArray(block)) {
  2015. block = appendBlockToChain(chain, block, fallback);
  2016. }
  2017. // prettier-ignore
  2018. // last block defined by default
  2019. const defaults = isArray(fallback)
  2020. ? fallback
  2021. : isPlainObject(fallback)
  2022. ? fallback['default']
  2023. ? fallback['default']
  2024. : null
  2025. : fallback;
  2026. // convert defaults to array
  2027. block = isString(defaults) ? [defaults] : defaults;
  2028. if (isArray(block)) {
  2029. appendBlockToChain(chain, block, false);
  2030. }
  2031. context.__localeChainCache.set(start, chain);
  2032. }
  2033. return chain;
  2034. }
  2035. function appendBlockToChain(chain, block, blocks) {
  2036. let follow = true;
  2037. for (let i = 0; i < block.length && isBoolean(follow); i++) {
  2038. const locale = block[i];
  2039. if (isString(locale)) {
  2040. follow = appendLocaleToChain(chain, block[i], blocks);
  2041. }
  2042. }
  2043. return follow;
  2044. }
  2045. function appendLocaleToChain(chain, locale, blocks) {
  2046. let follow;
  2047. const tokens = locale.split('-');
  2048. do {
  2049. const target = tokens.join('-');
  2050. follow = appendItemToChain(chain, target, blocks);
  2051. tokens.splice(-1, 1);
  2052. } while (tokens.length && follow === true);
  2053. return follow;
  2054. }
  2055. function appendItemToChain(chain, target, blocks) {
  2056. let follow = false;
  2057. if (!chain.includes(target)) {
  2058. follow = true;
  2059. if (target) {
  2060. follow = target[target.length - 1] !== '!';
  2061. const locale = target.replace(/!/g, '');
  2062. chain.push(locale);
  2063. if ((isArray(blocks) || isPlainObject(blocks)) &&
  2064. blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
  2065. ) {
  2066. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2067. follow = blocks[locale];
  2068. }
  2069. }
  2070. }
  2071. return follow;
  2072. }
  2073. /** @internal */
  2074. function updateFallbackLocale(ctx, locale, fallback) {
  2075. const context = ctx;
  2076. context.__localeChainCache = new Map();
  2077. getLocaleChain(ctx, fallback, locale);
  2078. }
  2079. const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
  2080. const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
  2081. function checkHtmlMessage(source, options) {
  2082. const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
  2083. ? options.warnHtmlMessage
  2084. : true;
  2085. if (warnHtmlMessage && RE_HTML_TAG.test(source)) {
  2086. warn(format(WARN_MESSAGE, { source }));
  2087. }
  2088. }
  2089. const defaultOnCacheKey = (source) => source;
  2090. let compileCache = Object.create(null);
  2091. function clearCompileCache() {
  2092. compileCache = Object.create(null);
  2093. }
  2094. function compileToFunction(source, options = {}) {
  2095. {
  2096. // check HTML message
  2097. checkHtmlMessage(source, options);
  2098. // check caches
  2099. const onCacheKey = options.onCacheKey || defaultOnCacheKey;
  2100. const key = onCacheKey(source);
  2101. const cached = compileCache[key];
  2102. if (cached) {
  2103. return cached;
  2104. }
  2105. // compile error detecting
  2106. let occurred = false;
  2107. const onError = options.onError || defaultOnError;
  2108. options.onError = (err) => {
  2109. occurred = true;
  2110. onError(err);
  2111. };
  2112. // compile
  2113. const { code } = baseCompile(source, options);
  2114. // evaluate function
  2115. const msg = new Function(`return ${code}`)();
  2116. // if occurred compile error, don't cache
  2117. return !occurred ? (compileCache[key] = msg) : msg;
  2118. }
  2119. }
  2120. function createCoreError(code) {
  2121. return createCompileError(code, null, { messages: errorMessages } );
  2122. }
  2123. /** @internal */
  2124. const errorMessages = {
  2125. [14 /* INVALID_ARGUMENT */]: 'Invalid arguments',
  2126. [15 /* INVALID_DATE_ARGUMENT */]: 'The date provided is an invalid Date object.' +
  2127. 'Make sure your Date represents a valid date.',
  2128. [16 /* INVALID_ISO_DATE_ARGUMENT */]: 'The argument provided is not a valid ISO date string'
  2129. };
  2130. const NOOP_MESSAGE_FUNCTION = () => '';
  2131. const isMessageFunction = (val) => isFunction(val);
  2132. // implementation of `translate` function
  2133. function translate(context, ...args) {
  2134. const { fallbackFormat, postTranslation, unresolving, fallbackLocale, messages } = context;
  2135. const [key, options] = parseTranslateArgs(...args);
  2136. const missingWarn = isBoolean(options.missingWarn)
  2137. ? options.missingWarn
  2138. : context.missingWarn;
  2139. const fallbackWarn = isBoolean(options.fallbackWarn)
  2140. ? options.fallbackWarn
  2141. : context.fallbackWarn;
  2142. const escapeParameter = isBoolean(options.escapeParameter)
  2143. ? options.escapeParameter
  2144. : context.escapeParameter;
  2145. const resolvedMessage = !!options.resolvedMessage;
  2146. // prettier-ignore
  2147. const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
  2148. ? !isBoolean(options.default)
  2149. ? options.default
  2150. : key
  2151. : fallbackFormat // default by `fallbackFormat` option
  2152. ? key
  2153. : '';
  2154. const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
  2155. const locale = isString(options.locale) ? options.locale : context.locale;
  2156. // escape params
  2157. escapeParameter && escapeParams(options);
  2158. // resolve message format
  2159. // eslint-disable-next-line prefer-const
  2160. let [format, targetLocale, message] = !resolvedMessage
  2161. ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
  2162. : [
  2163. key,
  2164. locale,
  2165. messages[locale] || {}
  2166. ];
  2167. // if you use default message, set it as message format!
  2168. let cacheBaseKey = key;
  2169. if (!resolvedMessage &&
  2170. !(isString(format) || isMessageFunction(format))) {
  2171. if (enableDefaultMsg) {
  2172. format = defaultMsgOrKey;
  2173. cacheBaseKey = format;
  2174. }
  2175. }
  2176. // checking message format and target locale
  2177. if (!resolvedMessage &&
  2178. (!(isString(format) || isMessageFunction(format)) ||
  2179. !isString(targetLocale))) {
  2180. return unresolving ? NOT_REOSLVED : key;
  2181. }
  2182. if (isString(format) && context.messageCompiler == null) {
  2183. warn(`The message format compilation is not supported in this build. ` +
  2184. `Because message compiler isn't included. ` +
  2185. `You need to pre-compilation all message format. ` +
  2186. `So translate function return '${key}'.`);
  2187. return key;
  2188. }
  2189. // setup compile error detecting
  2190. let occurred = false;
  2191. const errorDetector = () => {
  2192. occurred = true;
  2193. };
  2194. // compile message format
  2195. const msg = !isMessageFunction(format)
  2196. ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
  2197. : format;
  2198. // if occurred compile error, return the message format
  2199. if (occurred) {
  2200. return format;
  2201. }
  2202. // evaluate message with context
  2203. const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
  2204. const msgContext = createMessageContext(ctxOptions);
  2205. const messaged = evaluateMessage(context, msg, msgContext);
  2206. // if use post translation option, proceed it with handler
  2207. const ret = postTranslation ? postTranslation(messaged) : messaged;
  2208. // NOTE: experimental !!
  2209. {
  2210. // prettier-ignore
  2211. const payloads = {
  2212. timestamp: Date.now(),
  2213. key: isString(key)
  2214. ? key
  2215. : isMessageFunction(format)
  2216. ? format.key
  2217. : '',
  2218. locale: targetLocale || (isMessageFunction(format)
  2219. ? format.locale
  2220. : ''),
  2221. format: isString(format)
  2222. ? format
  2223. : isMessageFunction(format)
  2224. ? format.source
  2225. : '',
  2226. message: ret
  2227. };
  2228. payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
  2229. translateDevTools(payloads);
  2230. }
  2231. return ret;
  2232. }
  2233. function escapeParams(options) {
  2234. if (isArray(options.list)) {
  2235. options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
  2236. }
  2237. else if (isObject(options.named)) {
  2238. Object.keys(options.named).forEach(key => {
  2239. if (isString(options.named[key])) {
  2240. options.named[key] = escapeHtml(options.named[key]);
  2241. }
  2242. });
  2243. }
  2244. }
  2245. function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
  2246. const { messages, onWarn } = context;
  2247. const locales = getLocaleChain(context, fallbackLocale, locale);
  2248. let message = {};
  2249. let targetLocale;
  2250. let format = null;
  2251. let from = locale;
  2252. let to = null;
  2253. const type = 'translate';
  2254. for (let i = 0; i < locales.length; i++) {
  2255. targetLocale = to = locales[i];
  2256. if (locale !== targetLocale &&
  2257. isTranslateFallbackWarn(fallbackWarn, key)) {
  2258. onWarn(getWarnMessage(1 /* FALLBACK_TO_TRANSLATE */, {
  2259. key,
  2260. target: targetLocale
  2261. }));
  2262. }
  2263. // for vue-devtools timeline event
  2264. if (locale !== targetLocale) {
  2265. const emitter = context.__v_emitter;
  2266. if (emitter) {
  2267. emitter.emit("fallback" /* FALBACK */, {
  2268. type,
  2269. key,
  2270. from,
  2271. to,
  2272. groupId: `${type}:${key}`
  2273. });
  2274. }
  2275. }
  2276. message =
  2277. messages[targetLocale] || {};
  2278. // for vue-devtools timeline event
  2279. let start = null;
  2280. let startTag;
  2281. let endTag;
  2282. if (inBrowser) {
  2283. start = window.performance.now();
  2284. startTag = 'intlify-message-resolve-start';
  2285. endTag = 'intlify-message-resolve-end';
  2286. mark && mark(startTag);
  2287. }
  2288. if ((format = resolveValue(message, key)) === null) {
  2289. // if null, resolve with object key path
  2290. format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
  2291. }
  2292. // for vue-devtools timeline event
  2293. if (inBrowser) {
  2294. const end = window.performance.now();
  2295. const emitter = context.__v_emitter;
  2296. if (emitter && start && format) {
  2297. emitter.emit("message-resolve" /* MESSAGE_RESOLVE */, {
  2298. type: "message-resolve" /* MESSAGE_RESOLVE */,
  2299. key,
  2300. message: format,
  2301. time: end - start,
  2302. groupId: `${type}:${key}`
  2303. });
  2304. }
  2305. if (startTag && endTag && mark && measure) {
  2306. mark(endTag);
  2307. measure('intlify message resolve', startTag, endTag);
  2308. }
  2309. }
  2310. if (isString(format) || isFunction(format))
  2311. break;
  2312. const missingRet = handleMissing(context, key, targetLocale, missingWarn, type);
  2313. if (missingRet !== key) {
  2314. format = missingRet;
  2315. }
  2316. from = to;
  2317. }
  2318. return [format, targetLocale, message];
  2319. }
  2320. function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
  2321. const { messageCompiler, warnHtmlMessage } = context;
  2322. if (isMessageFunction(format)) {
  2323. const msg = format;
  2324. msg.locale = msg.locale || targetLocale;
  2325. msg.key = msg.key || key;
  2326. return msg;
  2327. }
  2328. // for vue-devtools timeline event
  2329. let start = null;
  2330. let startTag;
  2331. let endTag;
  2332. if (inBrowser) {
  2333. start = window.performance.now();
  2334. startTag = 'intlify-message-compilation-start';
  2335. endTag = 'intlify-message-compilation-end';
  2336. mark && mark(startTag);
  2337. }
  2338. const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
  2339. // for vue-devtools timeline event
  2340. if (inBrowser) {
  2341. const end = window.performance.now();
  2342. const emitter = context.__v_emitter;
  2343. if (emitter && start) {
  2344. emitter.emit("message-compilation" /* MESSAGE_COMPILATION */, {
  2345. type: "message-compilation" /* MESSAGE_COMPILATION */,
  2346. message: format,
  2347. time: end - start,
  2348. groupId: `${'translate'}:${key}`
  2349. });
  2350. }
  2351. if (startTag && endTag && mark && measure) {
  2352. mark(endTag);
  2353. measure('intlify message compilation', startTag, endTag);
  2354. }
  2355. }
  2356. msg.locale = targetLocale;
  2357. msg.key = key;
  2358. msg.source = format;
  2359. return msg;
  2360. }
  2361. function evaluateMessage(context, msg, msgCtx) {
  2362. // for vue-devtools timeline event
  2363. let start = null;
  2364. let startTag;
  2365. let endTag;
  2366. if (inBrowser) {
  2367. start = window.performance.now();
  2368. startTag = 'intlify-message-evaluation-start';
  2369. endTag = 'intlify-message-evaluation-end';
  2370. mark && mark(startTag);
  2371. }
  2372. const messaged = msg(msgCtx);
  2373. // for vue-devtools timeline event
  2374. if (inBrowser) {
  2375. const end = window.performance.now();
  2376. const emitter = context.__v_emitter;
  2377. if (emitter && start) {
  2378. emitter.emit("message-evaluation" /* MESSAGE_EVALUATION */, {
  2379. type: "message-evaluation" /* MESSAGE_EVALUATION */,
  2380. value: messaged,
  2381. time: end - start,
  2382. groupId: `${'translate'}:${msg.key}`
  2383. });
  2384. }
  2385. if (startTag && endTag && mark && measure) {
  2386. mark(endTag);
  2387. measure('intlify message evaluation', startTag, endTag);
  2388. }
  2389. }
  2390. return messaged;
  2391. }
  2392. /** @internal */
  2393. function parseTranslateArgs(...args) {
  2394. const [arg1, arg2, arg3] = args;
  2395. const options = {};
  2396. if (!isString(arg1) && !isNumber(arg1) && !isMessageFunction(arg1)) {
  2397. throw createCoreError(14 /* INVALID_ARGUMENT */);
  2398. }
  2399. // prettier-ignore
  2400. const key = isNumber(arg1)
  2401. ? String(arg1)
  2402. : isMessageFunction(arg1)
  2403. ? arg1
  2404. : arg1;
  2405. if (isNumber(arg2)) {
  2406. options.plural = arg2;
  2407. }
  2408. else if (isString(arg2)) {
  2409. options.default = arg2;
  2410. }
  2411. else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
  2412. options.named = arg2;
  2413. }
  2414. else if (isArray(arg2)) {
  2415. options.list = arg2;
  2416. }
  2417. if (isNumber(arg3)) {
  2418. options.plural = arg3;
  2419. }
  2420. else if (isString(arg3)) {
  2421. options.default = arg3;
  2422. }
  2423. else if (isPlainObject(arg3)) {
  2424. assign(options, arg3);
  2425. }
  2426. return [key, options];
  2427. }
  2428. function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
  2429. return {
  2430. warnHtmlMessage,
  2431. onError: (err) => {
  2432. errorDetector && errorDetector(err);
  2433. {
  2434. const message = `Message compilation error: ${err.message}`;
  2435. const codeFrame = err.location &&
  2436. generateCodeFrame(source, err.location.start.offset, err.location.end.offset);
  2437. const emitter = context
  2438. .__v_emitter;
  2439. if (emitter) {
  2440. emitter.emit("compile-error" /* COMPILE_ERROR */, {
  2441. message: source,
  2442. error: err.message,
  2443. start: err.location && err.location.start.offset,
  2444. end: err.location && err.location.end.offset,
  2445. groupId: `${'translate'}:${key}`
  2446. });
  2447. }
  2448. console.error(codeFrame ? `${message}\n${codeFrame}` : message);
  2449. }
  2450. },
  2451. onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
  2452. };
  2453. }
  2454. function getMessageContextOptions(context, locale, message, options) {
  2455. const { modifiers, pluralRules } = context;
  2456. const resolveMessage = (key) => {
  2457. const val = resolveValue(message, key);
  2458. if (isString(val)) {
  2459. let occurred = false;
  2460. const errorDetector = () => {
  2461. occurred = true;
  2462. };
  2463. const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
  2464. return !occurred
  2465. ? msg
  2466. : NOOP_MESSAGE_FUNCTION;
  2467. }
  2468. else if (isMessageFunction(val)) {
  2469. return val;
  2470. }
  2471. else {
  2472. // TODO: should be implemented warning message
  2473. return NOOP_MESSAGE_FUNCTION;
  2474. }
  2475. };
  2476. const ctxOptions = {
  2477. locale,
  2478. modifiers,
  2479. pluralRules,
  2480. messages: resolveMessage
  2481. };
  2482. if (context.processor) {
  2483. ctxOptions.processor = context.processor;
  2484. }
  2485. if (options.list) {
  2486. ctxOptions.list = options.list;
  2487. }
  2488. if (options.named) {
  2489. ctxOptions.named = options.named;
  2490. }
  2491. if (isNumber(options.plural)) {
  2492. ctxOptions.pluralIndex = options.plural;
  2493. }
  2494. return ctxOptions;
  2495. }
  2496. const intlDefined = typeof Intl !== 'undefined';
  2497. const Availabilities = {
  2498. dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
  2499. numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
  2500. };
  2501. // implementation of `datetime` function
  2502. function datetime(context, ...args) {
  2503. const { datetimeFormats, unresolving, fallbackLocale, onWarn } = context;
  2504. const { __datetimeFormatters } = context;
  2505. if (!Availabilities.dateTimeFormat) {
  2506. onWarn(getWarnMessage(4 /* CANNOT_FORMAT_DATE */));
  2507. return MISSING_RESOLVE_VALUE;
  2508. }
  2509. const [key, value, options, overrides] = parseDateTimeArgs(...args);
  2510. const missingWarn = isBoolean(options.missingWarn)
  2511. ? options.missingWarn
  2512. : context.missingWarn;
  2513. const fallbackWarn = isBoolean(options.fallbackWarn)
  2514. ? options.fallbackWarn
  2515. : context.fallbackWarn;
  2516. const part = !!options.part;
  2517. const locale = isString(options.locale) ? options.locale : context.locale;
  2518. const locales = getLocaleChain(context, fallbackLocale, locale);
  2519. if (!isString(key) || key === '') {
  2520. return new Intl.DateTimeFormat(locale).format(value);
  2521. }
  2522. // resolve format
  2523. let datetimeFormat = {};
  2524. let targetLocale;
  2525. let format = null;
  2526. let from = locale;
  2527. let to = null;
  2528. const type = 'datetime format';
  2529. for (let i = 0; i < locales.length; i++) {
  2530. targetLocale = to = locales[i];
  2531. if (locale !== targetLocale &&
  2532. isTranslateFallbackWarn(fallbackWarn, key)) {
  2533. onWarn(getWarnMessage(5 /* FALLBACK_TO_DATE_FORMAT */, {
  2534. key,
  2535. target: targetLocale
  2536. }));
  2537. }
  2538. // for vue-devtools timeline event
  2539. if (locale !== targetLocale) {
  2540. const emitter = context.__v_emitter;
  2541. if (emitter) {
  2542. emitter.emit("fallback" /* FALBACK */, {
  2543. type,
  2544. key,
  2545. from,
  2546. to,
  2547. groupId: `${type}:${key}`
  2548. });
  2549. }
  2550. }
  2551. datetimeFormat =
  2552. datetimeFormats[targetLocale] || {};
  2553. format = datetimeFormat[key];
  2554. if (isPlainObject(format))
  2555. break;
  2556. handleMissing(context, key, targetLocale, missingWarn, type);
  2557. from = to;
  2558. }
  2559. // checking format and target locale
  2560. if (!isPlainObject(format) || !isString(targetLocale)) {
  2561. return unresolving ? NOT_REOSLVED : key;
  2562. }
  2563. let id = `${targetLocale}__${key}`;
  2564. if (!isEmptyObject(overrides)) {
  2565. id = `${id}__${JSON.stringify(overrides)}`;
  2566. }
  2567. let formatter = __datetimeFormatters.get(id);
  2568. if (!formatter) {
  2569. formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
  2570. __datetimeFormatters.set(id, formatter);
  2571. }
  2572. return !part ? formatter.format(value) : formatter.formatToParts(value);
  2573. }
  2574. /** @internal */
  2575. function parseDateTimeArgs(...args) {
  2576. const [arg1, arg2, arg3, arg4] = args;
  2577. let options = {};
  2578. let overrides = {};
  2579. let value;
  2580. if (isString(arg1)) {
  2581. // Only allow ISO strings - other date formats are often supported,
  2582. // but may cause different results in different browsers.
  2583. if (!/\d{4}-\d{2}-\d{2}(T.*)?/.test(arg1)) {
  2584. throw createCoreError(16 /* INVALID_ISO_DATE_ARGUMENT */);
  2585. }
  2586. value = new Date(arg1);
  2587. try {
  2588. // This will fail if the date is not valid
  2589. value.toISOString();
  2590. }
  2591. catch (e) {
  2592. throw createCoreError(16 /* INVALID_ISO_DATE_ARGUMENT */);
  2593. }
  2594. }
  2595. else if (isDate(arg1)) {
  2596. if (isNaN(arg1.getTime())) {
  2597. throw createCoreError(15 /* INVALID_DATE_ARGUMENT */);
  2598. }
  2599. value = arg1;
  2600. }
  2601. else if (isNumber(arg1)) {
  2602. value = arg1;
  2603. }
  2604. else {
  2605. throw createCoreError(14 /* INVALID_ARGUMENT */);
  2606. }
  2607. if (isString(arg2)) {
  2608. options.key = arg2;
  2609. }
  2610. else if (isPlainObject(arg2)) {
  2611. options = arg2;
  2612. }
  2613. if (isString(arg3)) {
  2614. options.locale = arg3;
  2615. }
  2616. else if (isPlainObject(arg3)) {
  2617. overrides = arg3;
  2618. }
  2619. if (isPlainObject(arg4)) {
  2620. overrides = arg4;
  2621. }
  2622. return [options.key || '', value, options, overrides];
  2623. }
  2624. /** @internal */
  2625. function clearDateTimeFormat(ctx, locale, format) {
  2626. const context = ctx;
  2627. for (const key in format) {
  2628. const id = `${locale}__${key}`;
  2629. if (!context.__datetimeFormatters.has(id)) {
  2630. continue;
  2631. }
  2632. context.__datetimeFormatters.delete(id);
  2633. }
  2634. }
  2635. // implementation of `number` function
  2636. function number(context, ...args) {
  2637. const { numberFormats, unresolving, fallbackLocale, onWarn } = context;
  2638. const { __numberFormatters } = context;
  2639. if (!Availabilities.numberFormat) {
  2640. onWarn(getWarnMessage(2 /* CANNOT_FORMAT_NUMBER */));
  2641. return MISSING_RESOLVE_VALUE;
  2642. }
  2643. const [key, value, options, overrides] = parseNumberArgs(...args);
  2644. const missingWarn = isBoolean(options.missingWarn)
  2645. ? options.missingWarn
  2646. : context.missingWarn;
  2647. const fallbackWarn = isBoolean(options.fallbackWarn)
  2648. ? options.fallbackWarn
  2649. : context.fallbackWarn;
  2650. const part = !!options.part;
  2651. const locale = isString(options.locale) ? options.locale : context.locale;
  2652. const locales = getLocaleChain(context, fallbackLocale, locale);
  2653. if (!isString(key) || key === '') {
  2654. return new Intl.NumberFormat(locale).format(value);
  2655. }
  2656. // resolve format
  2657. let numberFormat = {};
  2658. let targetLocale;
  2659. let format = null;
  2660. let from = locale;
  2661. let to = null;
  2662. const type = 'number format';
  2663. for (let i = 0; i < locales.length; i++) {
  2664. targetLocale = to = locales[i];
  2665. if (locale !== targetLocale &&
  2666. isTranslateFallbackWarn(fallbackWarn, key)) {
  2667. onWarn(getWarnMessage(3 /* FALLBACK_TO_NUMBER_FORMAT */, {
  2668. key,
  2669. target: targetLocale
  2670. }));
  2671. }
  2672. // for vue-devtools timeline event
  2673. if (locale !== targetLocale) {
  2674. const emitter = context.__v_emitter;
  2675. if (emitter) {
  2676. emitter.emit("fallback" /* FALBACK */, {
  2677. type,
  2678. key,
  2679. from,
  2680. to,
  2681. groupId: `${type}:${key}`
  2682. });
  2683. }
  2684. }
  2685. numberFormat =
  2686. numberFormats[targetLocale] || {};
  2687. format = numberFormat[key];
  2688. if (isPlainObject(format))
  2689. break;
  2690. handleMissing(context, key, targetLocale, missingWarn, type);
  2691. from = to;
  2692. }
  2693. // checking format and target locale
  2694. if (!isPlainObject(format) || !isString(targetLocale)) {
  2695. return unresolving ? NOT_REOSLVED : key;
  2696. }
  2697. let id = `${targetLocale}__${key}`;
  2698. if (!isEmptyObject(overrides)) {
  2699. id = `${id}__${JSON.stringify(overrides)}`;
  2700. }
  2701. let formatter = __numberFormatters.get(id);
  2702. if (!formatter) {
  2703. formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
  2704. __numberFormatters.set(id, formatter);
  2705. }
  2706. return !part ? formatter.format(value) : formatter.formatToParts(value);
  2707. }
  2708. /** @internal */
  2709. function parseNumberArgs(...args) {
  2710. const [arg1, arg2, arg3, arg4] = args;
  2711. let options = {};
  2712. let overrides = {};
  2713. if (!isNumber(arg1)) {
  2714. throw createCoreError(14 /* INVALID_ARGUMENT */);
  2715. }
  2716. const value = arg1;
  2717. if (isString(arg2)) {
  2718. options.key = arg2;
  2719. }
  2720. else if (isPlainObject(arg2)) {
  2721. options = arg2;
  2722. }
  2723. if (isString(arg3)) {
  2724. options.locale = arg3;
  2725. }
  2726. else if (isPlainObject(arg3)) {
  2727. overrides = arg3;
  2728. }
  2729. if (isPlainObject(arg4)) {
  2730. overrides = arg4;
  2731. }
  2732. return [options.key || '', value, options, overrides];
  2733. }
  2734. /** @internal */
  2735. function clearNumberFormat(ctx, locale, format) {
  2736. const context = ctx;
  2737. for (const key in format) {
  2738. const id = `${locale}__${key}`;
  2739. if (!context.__numberFormatters.has(id)) {
  2740. continue;
  2741. }
  2742. context.__numberFormatters.delete(id);
  2743. }
  2744. }
  2745. export { DEFAULT_MESSAGE_DATA_TYPE, MISSING_RESOLVE_VALUE, NOT_REOSLVED, VERSION, clearCompileCache, clearDateTimeFormat, clearNumberFormat, compileToFunction, createCompileError, createCoreContext, createCoreError, createMessageContext, datetime, getAdditionalMeta, getDevToolsHook, getLocaleChain, getWarnMessage, handleFlatJson, handleMissing, initI18nDevTools, isMessageFunction, isTranslateFallbackWarn, isTranslateMissingWarn, number, parse, parseDateTimeArgs, parseNumberArgs, parseTranslateArgs, registerMessageCompiler, resolveValue, setAdditionalMeta, setDevToolsHook, translate, translateDevTools, updateFallbackLocale };