core-base.esm-browser.js 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497
  1. /*!
  2. * core-base v11.1.3
  3. * (c) 2025 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. // @ts-ignore browser compat
  20. perf.clearMeasures) {
  21. mark = (tag) => {
  22. perf.mark(tag);
  23. };
  24. measure = (name, startTag, endTag) => {
  25. perf.measure(name, startTag, endTag);
  26. perf.clearMarks(startTag);
  27. perf.clearMarks(endTag);
  28. };
  29. }
  30. }
  31. const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
  32. /* eslint-disable */
  33. function format$1(message, ...args) {
  34. if (args.length === 1 && isObject(args[0])) {
  35. args = args[0];
  36. }
  37. if (!args || !args.hasOwnProperty) {
  38. args = {};
  39. }
  40. return message.replace(RE_ARGS, (match, identifier) => {
  41. return args.hasOwnProperty(identifier) ? args[identifier] : '';
  42. });
  43. }
  44. const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
  45. const friendlyJSONstringify = (json) => JSON.stringify(json)
  46. .replace(/\u2028/g, '\\u2028')
  47. .replace(/\u2029/g, '\\u2029')
  48. .replace(/\u0027/g, '\\u0027');
  49. const isNumber = (val) => typeof val === 'number' && isFinite(val);
  50. const isDate = (val) => toTypeString(val) === '[object Date]';
  51. const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
  52. const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
  53. const assign = Object.assign;
  54. const _create = Object.create;
  55. const create = (obj = null) => _create(obj);
  56. function escapeHtml(rawText) {
  57. return rawText
  58. .replace(/</g, '&lt;')
  59. .replace(/>/g, '&gt;')
  60. .replace(/"/g, '&quot;')
  61. .replace(/'/g, '&apos;');
  62. }
  63. const hasOwnProperty = Object.prototype.hasOwnProperty;
  64. function hasOwn(obj, key) {
  65. return hasOwnProperty.call(obj, key);
  66. }
  67. /* eslint-enable */
  68. /**
  69. * Useful Utilities By Evan you
  70. * Modified by kazuya kawaguchi
  71. * MIT License
  72. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
  73. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
  74. */
  75. const isArray = Array.isArray;
  76. const isFunction = (val) => typeof val === 'function';
  77. const isString = (val) => typeof val === 'string';
  78. const isBoolean = (val) => typeof val === 'boolean';
  79. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  80. const isObject = (val) => val !== null && typeof val === 'object';
  81. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  82. const isPromise = (val) => {
  83. return isObject(val) && isFunction(val.then) && isFunction(val.catch);
  84. };
  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. function join(items, separator = '') {
  97. return items.reduce((str, item, index) => (index === 0 ? str + item : str + separator + item), '');
  98. }
  99. const RANGE = 2;
  100. function generateCodeFrame(source, start = 0, end = source.length) {
  101. const lines = source.split(/\r?\n/);
  102. let count = 0;
  103. const res = [];
  104. for (let i = 0; i < lines.length; i++) {
  105. count += lines[i].length + 1;
  106. if (count >= start) {
  107. for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
  108. if (j < 0 || j >= lines.length)
  109. continue;
  110. const line = j + 1;
  111. res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
  112. const lineLength = lines[j].length;
  113. if (j === i) {
  114. // push underline
  115. const pad = start - (count - lineLength) + 1;
  116. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  117. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  118. }
  119. else if (j > i) {
  120. if (end > count) {
  121. const length = Math.max(Math.min(end - count, lineLength), 1);
  122. res.push(` | ` + '^'.repeat(length));
  123. }
  124. count += lineLength + 1;
  125. }
  126. }
  127. break;
  128. }
  129. }
  130. return res.join('\n');
  131. }
  132. function warn(msg, err) {
  133. if (typeof console !== 'undefined') {
  134. console.warn(`[intlify] ` + msg);
  135. /* istanbul ignore if */
  136. if (err) {
  137. console.warn(err.stack);
  138. }
  139. }
  140. }
  141. const hasWarned = {};
  142. function warnOnce(msg) {
  143. if (!hasWarned[msg]) {
  144. hasWarned[msg] = true;
  145. warn(msg);
  146. }
  147. }
  148. function createPosition(line, column, offset) {
  149. return { line, column, offset };
  150. }
  151. function createLocation(start, end, source) {
  152. const loc = { start, end };
  153. return loc;
  154. }
  155. const CompileErrorCodes = {
  156. // tokenizer error codes
  157. EXPECTED_TOKEN: 1,
  158. INVALID_TOKEN_IN_PLACEHOLDER: 2,
  159. UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
  160. UNKNOWN_ESCAPE_SEQUENCE: 4,
  161. INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
  162. UNBALANCED_CLOSING_BRACE: 6,
  163. UNTERMINATED_CLOSING_BRACE: 7,
  164. EMPTY_PLACEHOLDER: 8,
  165. NOT_ALLOW_NEST_PLACEHOLDER: 9,
  166. INVALID_LINKED_FORMAT: 10,
  167. // parser error codes
  168. MUST_HAVE_MESSAGES_IN_PLURAL: 11,
  169. UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
  170. UNEXPECTED_EMPTY_LINKED_KEY: 13,
  171. UNEXPECTED_LEXICAL_ANALYSIS: 14,
  172. // generator error codes
  173. UNHANDLED_CODEGEN_NODE_TYPE: 15,
  174. // minifier error codes
  175. UNHANDLED_MINIFIER_NODE_TYPE: 16
  176. };
  177. // Special value for higher-order compilers to pick up the last code
  178. // to avoid collision of error codes.
  179. // This should always be kept as the last item.
  180. const COMPILE_ERROR_CODES_EXTEND_POINT = 17;
  181. /** @internal */
  182. const errorMessages$1 = {
  183. // tokenizer error messages
  184. [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
  185. [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
  186. [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
  187. [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
  188. [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
  189. [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
  190. [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
  191. [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
  192. [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
  193. [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
  194. // parser error messages
  195. [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
  196. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
  197. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
  198. [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,
  199. // generator error messages
  200. [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,
  201. // minimizer error messages
  202. [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`
  203. };
  204. function createCompileError(code, loc, options = {}) {
  205. const { domain, messages, args } = options;
  206. const msg = format$1((messages || errorMessages$1)[code] || '', ...(args || []))
  207. ;
  208. const error = new SyntaxError(String(msg));
  209. error.code = code;
  210. if (loc) {
  211. error.location = loc;
  212. }
  213. error.domain = domain;
  214. return error;
  215. }
  216. /** @internal */
  217. function defaultOnError(error) {
  218. throw error;
  219. }
  220. // eslint-disable-next-line no-useless-escape
  221. const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
  222. const detectHtmlTag = (source) => RE_HTML_TAG.test(source);
  223. const CHAR_SP = ' ';
  224. const CHAR_CR = '\r';
  225. const CHAR_LF = '\n';
  226. const CHAR_LS = String.fromCharCode(0x2028);
  227. const CHAR_PS = String.fromCharCode(0x2029);
  228. function createScanner(str) {
  229. const _buf = str;
  230. let _index = 0;
  231. let _line = 1;
  232. let _column = 1;
  233. let _peekOffset = 0;
  234. const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
  235. const isLF = (index) => _buf[index] === CHAR_LF;
  236. const isPS = (index) => _buf[index] === CHAR_PS;
  237. const isLS = (index) => _buf[index] === CHAR_LS;
  238. const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
  239. const index = () => _index;
  240. const line = () => _line;
  241. const column = () => _column;
  242. const peekOffset = () => _peekOffset;
  243. const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
  244. const currentChar = () => charAt(_index);
  245. const currentPeek = () => charAt(_index + _peekOffset);
  246. function next() {
  247. _peekOffset = 0;
  248. if (isLineEnd(_index)) {
  249. _line++;
  250. _column = 0;
  251. }
  252. if (isCRLF(_index)) {
  253. _index++;
  254. }
  255. _index++;
  256. _column++;
  257. return _buf[_index];
  258. }
  259. function peek() {
  260. if (isCRLF(_index + _peekOffset)) {
  261. _peekOffset++;
  262. }
  263. _peekOffset++;
  264. return _buf[_index + _peekOffset];
  265. }
  266. function reset() {
  267. _index = 0;
  268. _line = 1;
  269. _column = 1;
  270. _peekOffset = 0;
  271. }
  272. function resetPeek(offset = 0) {
  273. _peekOffset = offset;
  274. }
  275. function skipToPeek() {
  276. const target = _index + _peekOffset;
  277. while (target !== _index) {
  278. next();
  279. }
  280. _peekOffset = 0;
  281. }
  282. return {
  283. index,
  284. line,
  285. column,
  286. peekOffset,
  287. charAt,
  288. currentChar,
  289. currentPeek,
  290. next,
  291. peek,
  292. reset,
  293. resetPeek,
  294. skipToPeek
  295. };
  296. }
  297. const EOF = undefined;
  298. const DOT = '.';
  299. const LITERAL_DELIMITER = "'";
  300. const ERROR_DOMAIN$3 = 'tokenizer';
  301. function createTokenizer(source, options = {}) {
  302. const location = options.location !== false;
  303. const _scnr = createScanner(source);
  304. const currentOffset = () => _scnr.index();
  305. const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
  306. const _initLoc = currentPosition();
  307. const _initOffset = currentOffset();
  308. const _context = {
  309. currentType: 13 /* TokenTypes.EOF */,
  310. offset: _initOffset,
  311. startLoc: _initLoc,
  312. endLoc: _initLoc,
  313. lastType: 13 /* TokenTypes.EOF */,
  314. lastOffset: _initOffset,
  315. lastStartLoc: _initLoc,
  316. lastEndLoc: _initLoc,
  317. braceNest: 0,
  318. inLinked: false,
  319. text: ''
  320. };
  321. const context = () => _context;
  322. const { onError } = options;
  323. function emitError(code, pos, offset, ...args) {
  324. const ctx = context();
  325. pos.column += offset;
  326. pos.offset += offset;
  327. if (onError) {
  328. const loc = location ? createLocation(ctx.startLoc, pos) : null;
  329. const err = createCompileError(code, loc, {
  330. domain: ERROR_DOMAIN$3,
  331. args
  332. });
  333. onError(err);
  334. }
  335. }
  336. function getToken(context, type, value) {
  337. context.endLoc = currentPosition();
  338. context.currentType = type;
  339. const token = { type };
  340. if (location) {
  341. token.loc = createLocation(context.startLoc, context.endLoc);
  342. }
  343. if (value != null) {
  344. token.value = value;
  345. }
  346. return token;
  347. }
  348. const getEndToken = (context) => getToken(context, 13 /* TokenTypes.EOF */);
  349. function eat(scnr, ch) {
  350. if (scnr.currentChar() === ch) {
  351. scnr.next();
  352. return ch;
  353. }
  354. else {
  355. emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
  356. return '';
  357. }
  358. }
  359. function peekSpaces(scnr) {
  360. let buf = '';
  361. while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
  362. buf += scnr.currentPeek();
  363. scnr.peek();
  364. }
  365. return buf;
  366. }
  367. function skipSpaces(scnr) {
  368. const buf = peekSpaces(scnr);
  369. scnr.skipToPeek();
  370. return buf;
  371. }
  372. function isIdentifierStart(ch) {
  373. if (ch === EOF) {
  374. return false;
  375. }
  376. const cc = ch.charCodeAt(0);
  377. return ((cc >= 97 && cc <= 122) || // a-z
  378. (cc >= 65 && cc <= 90) || // A-Z
  379. cc === 95 // _
  380. );
  381. }
  382. function isNumberStart(ch) {
  383. if (ch === EOF) {
  384. return false;
  385. }
  386. const cc = ch.charCodeAt(0);
  387. return cc >= 48 && cc <= 57; // 0-9
  388. }
  389. function isNamedIdentifierStart(scnr, context) {
  390. const { currentType } = context;
  391. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  392. return false;
  393. }
  394. peekSpaces(scnr);
  395. const ret = isIdentifierStart(scnr.currentPeek());
  396. scnr.resetPeek();
  397. return ret;
  398. }
  399. function isListIdentifierStart(scnr, context) {
  400. const { currentType } = context;
  401. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  402. return false;
  403. }
  404. peekSpaces(scnr);
  405. const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
  406. const ret = isNumberStart(ch);
  407. scnr.resetPeek();
  408. return ret;
  409. }
  410. function isLiteralStart(scnr, context) {
  411. const { currentType } = context;
  412. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  413. return false;
  414. }
  415. peekSpaces(scnr);
  416. const ret = scnr.currentPeek() === LITERAL_DELIMITER;
  417. scnr.resetPeek();
  418. return ret;
  419. }
  420. function isLinkedDotStart(scnr, context) {
  421. const { currentType } = context;
  422. if (currentType !== 7 /* TokenTypes.LinkedAlias */) {
  423. return false;
  424. }
  425. peekSpaces(scnr);
  426. const ret = scnr.currentPeek() === "." /* TokenChars.LinkedDot */;
  427. scnr.resetPeek();
  428. return ret;
  429. }
  430. function isLinkedModifierStart(scnr, context) {
  431. const { currentType } = context;
  432. if (currentType !== 8 /* TokenTypes.LinkedDot */) {
  433. return false;
  434. }
  435. peekSpaces(scnr);
  436. const ret = isIdentifierStart(scnr.currentPeek());
  437. scnr.resetPeek();
  438. return ret;
  439. }
  440. function isLinkedDelimiterStart(scnr, context) {
  441. const { currentType } = context;
  442. if (!(currentType === 7 /* TokenTypes.LinkedAlias */ ||
  443. currentType === 11 /* TokenTypes.LinkedModifier */)) {
  444. return false;
  445. }
  446. peekSpaces(scnr);
  447. const ret = scnr.currentPeek() === ":" /* TokenChars.LinkedDelimiter */;
  448. scnr.resetPeek();
  449. return ret;
  450. }
  451. function isLinkedReferStart(scnr, context) {
  452. const { currentType } = context;
  453. if (currentType !== 9 /* TokenTypes.LinkedDelimiter */) {
  454. return false;
  455. }
  456. const fn = () => {
  457. const ch = scnr.currentPeek();
  458. if (ch === "{" /* TokenChars.BraceLeft */) {
  459. return isIdentifierStart(scnr.peek());
  460. }
  461. else if (ch === "@" /* TokenChars.LinkedAlias */ ||
  462. ch === "|" /* TokenChars.Pipe */ ||
  463. ch === ":" /* TokenChars.LinkedDelimiter */ ||
  464. ch === "." /* TokenChars.LinkedDot */ ||
  465. ch === CHAR_SP ||
  466. !ch) {
  467. return false;
  468. }
  469. else if (ch === CHAR_LF) {
  470. scnr.peek();
  471. return fn();
  472. }
  473. else {
  474. // other characters
  475. return isTextStart(scnr, false);
  476. }
  477. };
  478. const ret = fn();
  479. scnr.resetPeek();
  480. return ret;
  481. }
  482. function isPluralStart(scnr) {
  483. peekSpaces(scnr);
  484. const ret = scnr.currentPeek() === "|" /* TokenChars.Pipe */;
  485. scnr.resetPeek();
  486. return ret;
  487. }
  488. function isTextStart(scnr, reset = true) {
  489. const fn = (hasSpace = false, prev = '') => {
  490. const ch = scnr.currentPeek();
  491. if (ch === "{" /* TokenChars.BraceLeft */) {
  492. return hasSpace;
  493. }
  494. else if (ch === "@" /* TokenChars.LinkedAlias */ || !ch) {
  495. return hasSpace;
  496. }
  497. else if (ch === "|" /* TokenChars.Pipe */) {
  498. return !(prev === CHAR_SP || prev === CHAR_LF);
  499. }
  500. else if (ch === CHAR_SP) {
  501. scnr.peek();
  502. return fn(true, CHAR_SP);
  503. }
  504. else if (ch === CHAR_LF) {
  505. scnr.peek();
  506. return fn(true, CHAR_LF);
  507. }
  508. else {
  509. return true;
  510. }
  511. };
  512. const ret = fn();
  513. reset && scnr.resetPeek();
  514. return ret;
  515. }
  516. function takeChar(scnr, fn) {
  517. const ch = scnr.currentChar();
  518. if (ch === EOF) {
  519. return EOF;
  520. }
  521. if (fn(ch)) {
  522. scnr.next();
  523. return ch;
  524. }
  525. return null;
  526. }
  527. function isIdentifier(ch) {
  528. const cc = ch.charCodeAt(0);
  529. return ((cc >= 97 && cc <= 122) || // a-z
  530. (cc >= 65 && cc <= 90) || // A-Z
  531. (cc >= 48 && cc <= 57) || // 0-9
  532. cc === 95 || // _
  533. cc === 36 // $
  534. );
  535. }
  536. function takeIdentifierChar(scnr) {
  537. return takeChar(scnr, isIdentifier);
  538. }
  539. function isNamedIdentifier(ch) {
  540. const cc = ch.charCodeAt(0);
  541. return ((cc >= 97 && cc <= 122) || // a-z
  542. (cc >= 65 && cc <= 90) || // A-Z
  543. (cc >= 48 && cc <= 57) || // 0-9
  544. cc === 95 || // _
  545. cc === 36 || // $
  546. cc === 45 // -
  547. );
  548. }
  549. function takeNamedIdentifierChar(scnr) {
  550. return takeChar(scnr, isNamedIdentifier);
  551. }
  552. function isDigit(ch) {
  553. const cc = ch.charCodeAt(0);
  554. return cc >= 48 && cc <= 57; // 0-9
  555. }
  556. function takeDigit(scnr) {
  557. return takeChar(scnr, isDigit);
  558. }
  559. function isHexDigit(ch) {
  560. const cc = ch.charCodeAt(0);
  561. return ((cc >= 48 && cc <= 57) || // 0-9
  562. (cc >= 65 && cc <= 70) || // A-F
  563. (cc >= 97 && cc <= 102)); // a-f
  564. }
  565. function takeHexDigit(scnr) {
  566. return takeChar(scnr, isHexDigit);
  567. }
  568. function getDigits(scnr) {
  569. let ch = '';
  570. let num = '';
  571. while ((ch = takeDigit(scnr))) {
  572. num += ch;
  573. }
  574. return num;
  575. }
  576. function readText(scnr) {
  577. let buf = '';
  578. while (true) {
  579. const ch = scnr.currentChar();
  580. if (ch === "{" /* TokenChars.BraceLeft */ ||
  581. ch === "}" /* TokenChars.BraceRight */ ||
  582. ch === "@" /* TokenChars.LinkedAlias */ ||
  583. ch === "|" /* TokenChars.Pipe */ ||
  584. !ch) {
  585. break;
  586. }
  587. else if (ch === CHAR_SP || ch === CHAR_LF) {
  588. if (isTextStart(scnr)) {
  589. buf += ch;
  590. scnr.next();
  591. }
  592. else if (isPluralStart(scnr)) {
  593. break;
  594. }
  595. else {
  596. buf += ch;
  597. scnr.next();
  598. }
  599. }
  600. else {
  601. buf += ch;
  602. scnr.next();
  603. }
  604. }
  605. return buf;
  606. }
  607. function readNamedIdentifier(scnr) {
  608. skipSpaces(scnr);
  609. let ch = '';
  610. let name = '';
  611. while ((ch = takeNamedIdentifierChar(scnr))) {
  612. name += ch;
  613. }
  614. if (scnr.currentChar() === EOF) {
  615. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  616. }
  617. return name;
  618. }
  619. function readListIdentifier(scnr) {
  620. skipSpaces(scnr);
  621. let value = '';
  622. if (scnr.currentChar() === '-') {
  623. scnr.next();
  624. value += `-${getDigits(scnr)}`;
  625. }
  626. else {
  627. value += getDigits(scnr);
  628. }
  629. if (scnr.currentChar() === EOF) {
  630. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  631. }
  632. return value;
  633. }
  634. function isLiteral(ch) {
  635. return ch !== LITERAL_DELIMITER && ch !== CHAR_LF;
  636. }
  637. function readLiteral(scnr) {
  638. skipSpaces(scnr);
  639. // eslint-disable-next-line no-useless-escape
  640. eat(scnr, `\'`);
  641. let ch = '';
  642. let literal = '';
  643. while ((ch = takeChar(scnr, isLiteral))) {
  644. if (ch === '\\') {
  645. literal += readEscapeSequence(scnr);
  646. }
  647. else {
  648. literal += ch;
  649. }
  650. }
  651. const current = scnr.currentChar();
  652. if (current === CHAR_LF || current === EOF) {
  653. emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
  654. // TODO: Is it correct really?
  655. if (current === CHAR_LF) {
  656. scnr.next();
  657. // eslint-disable-next-line no-useless-escape
  658. eat(scnr, `\'`);
  659. }
  660. return literal;
  661. }
  662. // eslint-disable-next-line no-useless-escape
  663. eat(scnr, `\'`);
  664. return literal;
  665. }
  666. function readEscapeSequence(scnr) {
  667. const ch = scnr.currentChar();
  668. switch (ch) {
  669. case '\\':
  670. case `\'`: // eslint-disable-line no-useless-escape
  671. scnr.next();
  672. return `\\${ch}`;
  673. case 'u':
  674. return readUnicodeEscapeSequence(scnr, ch, 4);
  675. case 'U':
  676. return readUnicodeEscapeSequence(scnr, ch, 6);
  677. default:
  678. emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
  679. return '';
  680. }
  681. }
  682. function readUnicodeEscapeSequence(scnr, unicode, digits) {
  683. eat(scnr, unicode);
  684. let sequence = '';
  685. for (let i = 0; i < digits; i++) {
  686. const ch = takeHexDigit(scnr);
  687. if (!ch) {
  688. emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
  689. break;
  690. }
  691. sequence += ch;
  692. }
  693. return `\\${unicode}${sequence}`;
  694. }
  695. function isInvalidIdentifier(ch) {
  696. return (ch !== "{" /* TokenChars.BraceLeft */ &&
  697. ch !== "}" /* TokenChars.BraceRight */ &&
  698. ch !== CHAR_SP &&
  699. ch !== CHAR_LF);
  700. }
  701. function readInvalidIdentifier(scnr) {
  702. skipSpaces(scnr);
  703. let ch = '';
  704. let identifiers = '';
  705. while ((ch = takeChar(scnr, isInvalidIdentifier))) {
  706. identifiers += ch;
  707. }
  708. return identifiers;
  709. }
  710. function readLinkedModifier(scnr) {
  711. let ch = '';
  712. let name = '';
  713. while ((ch = takeIdentifierChar(scnr))) {
  714. name += ch;
  715. }
  716. return name;
  717. }
  718. function readLinkedRefer(scnr) {
  719. const fn = (buf) => {
  720. const ch = scnr.currentChar();
  721. if (ch === "{" /* TokenChars.BraceLeft */ ||
  722. ch === "@" /* TokenChars.LinkedAlias */ ||
  723. ch === "|" /* TokenChars.Pipe */ ||
  724. ch === "(" /* TokenChars.ParenLeft */ ||
  725. ch === ")" /* TokenChars.ParenRight */ ||
  726. !ch) {
  727. return buf;
  728. }
  729. else if (ch === CHAR_SP) {
  730. return buf;
  731. }
  732. else if (ch === CHAR_LF || ch === DOT) {
  733. buf += ch;
  734. scnr.next();
  735. return fn(buf);
  736. }
  737. else {
  738. buf += ch;
  739. scnr.next();
  740. return fn(buf);
  741. }
  742. };
  743. return fn('');
  744. }
  745. function readPlural(scnr) {
  746. skipSpaces(scnr);
  747. const plural = eat(scnr, "|" /* TokenChars.Pipe */);
  748. skipSpaces(scnr);
  749. return plural;
  750. }
  751. // TODO: We need refactoring of token parsing ...
  752. function readTokenInPlaceholder(scnr, context) {
  753. let token = null;
  754. const ch = scnr.currentChar();
  755. switch (ch) {
  756. case "{" /* TokenChars.BraceLeft */:
  757. if (context.braceNest >= 1) {
  758. emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
  759. }
  760. scnr.next();
  761. token = getToken(context, 2 /* TokenTypes.BraceLeft */, "{" /* TokenChars.BraceLeft */);
  762. skipSpaces(scnr);
  763. context.braceNest++;
  764. return token;
  765. case "}" /* TokenChars.BraceRight */:
  766. if (context.braceNest > 0 &&
  767. context.currentType === 2 /* TokenTypes.BraceLeft */) {
  768. emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
  769. }
  770. scnr.next();
  771. token = getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
  772. context.braceNest--;
  773. context.braceNest > 0 && skipSpaces(scnr);
  774. if (context.inLinked && context.braceNest === 0) {
  775. context.inLinked = false;
  776. }
  777. return token;
  778. case "@" /* TokenChars.LinkedAlias */:
  779. if (context.braceNest > 0) {
  780. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  781. }
  782. token = readTokenInLinked(scnr, context) || getEndToken(context);
  783. context.braceNest = 0;
  784. return token;
  785. default: {
  786. let validNamedIdentifier = true;
  787. let validListIdentifier = true;
  788. let validLiteral = true;
  789. if (isPluralStart(scnr)) {
  790. if (context.braceNest > 0) {
  791. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  792. }
  793. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  794. // reset
  795. context.braceNest = 0;
  796. context.inLinked = false;
  797. return token;
  798. }
  799. if (context.braceNest > 0 &&
  800. (context.currentType === 4 /* TokenTypes.Named */ ||
  801. context.currentType === 5 /* TokenTypes.List */ ||
  802. context.currentType === 6 /* TokenTypes.Literal */)) {
  803. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  804. context.braceNest = 0;
  805. return readToken(scnr, context);
  806. }
  807. if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
  808. token = getToken(context, 4 /* TokenTypes.Named */, readNamedIdentifier(scnr));
  809. skipSpaces(scnr);
  810. return token;
  811. }
  812. if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
  813. token = getToken(context, 5 /* TokenTypes.List */, readListIdentifier(scnr));
  814. skipSpaces(scnr);
  815. return token;
  816. }
  817. if ((validLiteral = isLiteralStart(scnr, context))) {
  818. token = getToken(context, 6 /* TokenTypes.Literal */, readLiteral(scnr));
  819. skipSpaces(scnr);
  820. return token;
  821. }
  822. if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
  823. // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
  824. token = getToken(context, 12 /* TokenTypes.InvalidPlace */, readInvalidIdentifier(scnr));
  825. emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
  826. skipSpaces(scnr);
  827. return token;
  828. }
  829. break;
  830. }
  831. }
  832. return token;
  833. }
  834. // TODO: We need refactoring of token parsing ...
  835. function readTokenInLinked(scnr, context) {
  836. const { currentType } = context;
  837. let token = null;
  838. const ch = scnr.currentChar();
  839. if ((currentType === 7 /* TokenTypes.LinkedAlias */ ||
  840. currentType === 8 /* TokenTypes.LinkedDot */ ||
  841. currentType === 11 /* TokenTypes.LinkedModifier */ ||
  842. currentType === 9 /* TokenTypes.LinkedDelimiter */) &&
  843. (ch === CHAR_LF || ch === CHAR_SP)) {
  844. emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
  845. }
  846. switch (ch) {
  847. case "@" /* TokenChars.LinkedAlias */:
  848. scnr.next();
  849. token = getToken(context, 7 /* TokenTypes.LinkedAlias */, "@" /* TokenChars.LinkedAlias */);
  850. context.inLinked = true;
  851. return token;
  852. case "." /* TokenChars.LinkedDot */:
  853. skipSpaces(scnr);
  854. scnr.next();
  855. return getToken(context, 8 /* TokenTypes.LinkedDot */, "." /* TokenChars.LinkedDot */);
  856. case ":" /* TokenChars.LinkedDelimiter */:
  857. skipSpaces(scnr);
  858. scnr.next();
  859. return getToken(context, 9 /* TokenTypes.LinkedDelimiter */, ":" /* TokenChars.LinkedDelimiter */);
  860. default:
  861. if (isPluralStart(scnr)) {
  862. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  863. // reset
  864. context.braceNest = 0;
  865. context.inLinked = false;
  866. return token;
  867. }
  868. if (isLinkedDotStart(scnr, context) ||
  869. isLinkedDelimiterStart(scnr, context)) {
  870. skipSpaces(scnr);
  871. return readTokenInLinked(scnr, context);
  872. }
  873. if (isLinkedModifierStart(scnr, context)) {
  874. skipSpaces(scnr);
  875. return getToken(context, 11 /* TokenTypes.LinkedModifier */, readLinkedModifier(scnr));
  876. }
  877. if (isLinkedReferStart(scnr, context)) {
  878. skipSpaces(scnr);
  879. if (ch === "{" /* TokenChars.BraceLeft */) {
  880. // scan the placeholder
  881. return readTokenInPlaceholder(scnr, context) || token;
  882. }
  883. else {
  884. return getToken(context, 10 /* TokenTypes.LinkedKey */, readLinkedRefer(scnr));
  885. }
  886. }
  887. if (currentType === 7 /* TokenTypes.LinkedAlias */) {
  888. emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
  889. }
  890. context.braceNest = 0;
  891. context.inLinked = false;
  892. return readToken(scnr, context);
  893. }
  894. }
  895. // TODO: We need refactoring of token parsing ...
  896. function readToken(scnr, context) {
  897. let token = { type: 13 /* TokenTypes.EOF */ };
  898. if (context.braceNest > 0) {
  899. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  900. }
  901. if (context.inLinked) {
  902. return readTokenInLinked(scnr, context) || getEndToken(context);
  903. }
  904. const ch = scnr.currentChar();
  905. switch (ch) {
  906. case "{" /* TokenChars.BraceLeft */:
  907. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  908. case "}" /* TokenChars.BraceRight */:
  909. emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
  910. scnr.next();
  911. return getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
  912. case "@" /* TokenChars.LinkedAlias */:
  913. return readTokenInLinked(scnr, context) || getEndToken(context);
  914. default: {
  915. if (isPluralStart(scnr)) {
  916. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  917. // reset
  918. context.braceNest = 0;
  919. context.inLinked = false;
  920. return token;
  921. }
  922. if (isTextStart(scnr)) {
  923. return getToken(context, 0 /* TokenTypes.Text */, readText(scnr));
  924. }
  925. break;
  926. }
  927. }
  928. return token;
  929. }
  930. function nextToken() {
  931. const { currentType, offset, startLoc, endLoc } = _context;
  932. _context.lastType = currentType;
  933. _context.lastOffset = offset;
  934. _context.lastStartLoc = startLoc;
  935. _context.lastEndLoc = endLoc;
  936. _context.offset = currentOffset();
  937. _context.startLoc = currentPosition();
  938. if (_scnr.currentChar() === EOF) {
  939. return getToken(_context, 13 /* TokenTypes.EOF */);
  940. }
  941. return readToken(_scnr, _context);
  942. }
  943. return {
  944. nextToken,
  945. currentOffset,
  946. currentPosition,
  947. context
  948. };
  949. }
  950. const ERROR_DOMAIN$2 = 'parser';
  951. // Backslash backslash, backslash quote, uHHHH, UHHHHHH.
  952. const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
  953. function fromEscapeSequence(match, codePoint4, codePoint6) {
  954. switch (match) {
  955. case `\\\\`:
  956. return `\\`;
  957. // eslint-disable-next-line no-useless-escape
  958. case `\\\'`:
  959. // eslint-disable-next-line no-useless-escape
  960. return `\'`;
  961. default: {
  962. const codePoint = parseInt(codePoint4 || codePoint6, 16);
  963. if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
  964. return String.fromCodePoint(codePoint);
  965. }
  966. // invalid ...
  967. // Replace them with U+FFFD REPLACEMENT CHARACTER.
  968. return '�';
  969. }
  970. }
  971. }
  972. function createParser(options = {}) {
  973. const location = options.location !== false;
  974. const { onError } = options;
  975. function emitError(tokenzer, code, start, offset, ...args) {
  976. const end = tokenzer.currentPosition();
  977. end.offset += offset;
  978. end.column += offset;
  979. if (onError) {
  980. const loc = location ? createLocation(start, end) : null;
  981. const err = createCompileError(code, loc, {
  982. domain: ERROR_DOMAIN$2,
  983. args
  984. });
  985. onError(err);
  986. }
  987. }
  988. function startNode(type, offset, loc) {
  989. const node = { type };
  990. if (location) {
  991. node.start = offset;
  992. node.end = offset;
  993. node.loc = { start: loc, end: loc };
  994. }
  995. return node;
  996. }
  997. function endNode(node, offset, pos, type) {
  998. if (location) {
  999. node.end = offset;
  1000. if (node.loc) {
  1001. node.loc.end = pos;
  1002. }
  1003. }
  1004. }
  1005. function parseText(tokenizer, value) {
  1006. const context = tokenizer.context();
  1007. const node = startNode(3 /* NodeTypes.Text */, context.offset, context.startLoc);
  1008. node.value = value;
  1009. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1010. return node;
  1011. }
  1012. function parseList(tokenizer, index) {
  1013. const context = tokenizer.context();
  1014. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1015. const node = startNode(5 /* NodeTypes.List */, offset, loc);
  1016. node.index = parseInt(index, 10);
  1017. tokenizer.nextToken(); // skip brach right
  1018. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1019. return node;
  1020. }
  1021. function parseNamed(tokenizer, key) {
  1022. const context = tokenizer.context();
  1023. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1024. const node = startNode(4 /* NodeTypes.Named */, offset, loc);
  1025. node.key = key;
  1026. tokenizer.nextToken(); // skip brach right
  1027. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1028. return node;
  1029. }
  1030. function parseLiteral(tokenizer, value) {
  1031. const context = tokenizer.context();
  1032. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1033. const node = startNode(9 /* NodeTypes.Literal */, offset, loc);
  1034. node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
  1035. tokenizer.nextToken(); // skip brach right
  1036. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1037. return node;
  1038. }
  1039. function parseLinkedModifier(tokenizer) {
  1040. const token = tokenizer.nextToken();
  1041. const context = tokenizer.context();
  1042. const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
  1043. const node = startNode(8 /* NodeTypes.LinkedModifier */, offset, loc);
  1044. if (token.type !== 11 /* TokenTypes.LinkedModifier */) {
  1045. // empty modifier
  1046. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
  1047. node.value = '';
  1048. endNode(node, offset, loc);
  1049. return {
  1050. nextConsumeToken: token,
  1051. node
  1052. };
  1053. }
  1054. // check token
  1055. if (token.value == null) {
  1056. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1057. }
  1058. node.value = token.value || '';
  1059. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1060. return {
  1061. node
  1062. };
  1063. }
  1064. function parseLinkedKey(tokenizer, value) {
  1065. const context = tokenizer.context();
  1066. const node = startNode(7 /* NodeTypes.LinkedKey */, context.offset, context.startLoc);
  1067. node.value = value;
  1068. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1069. return node;
  1070. }
  1071. function parseLinked(tokenizer) {
  1072. const context = tokenizer.context();
  1073. const linkedNode = startNode(6 /* NodeTypes.Linked */, context.offset, context.startLoc);
  1074. let token = tokenizer.nextToken();
  1075. if (token.type === 8 /* TokenTypes.LinkedDot */) {
  1076. const parsed = parseLinkedModifier(tokenizer);
  1077. linkedNode.modifier = parsed.node;
  1078. token = parsed.nextConsumeToken || tokenizer.nextToken();
  1079. }
  1080. // asset check token
  1081. if (token.type !== 9 /* TokenTypes.LinkedDelimiter */) {
  1082. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1083. }
  1084. token = tokenizer.nextToken();
  1085. // skip brace left
  1086. if (token.type === 2 /* TokenTypes.BraceLeft */) {
  1087. token = tokenizer.nextToken();
  1088. }
  1089. switch (token.type) {
  1090. case 10 /* TokenTypes.LinkedKey */:
  1091. if (token.value == null) {
  1092. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1093. }
  1094. linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
  1095. break;
  1096. case 4 /* TokenTypes.Named */:
  1097. if (token.value == null) {
  1098. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1099. }
  1100. linkedNode.key = parseNamed(tokenizer, token.value || '');
  1101. break;
  1102. case 5 /* TokenTypes.List */:
  1103. if (token.value == null) {
  1104. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1105. }
  1106. linkedNode.key = parseList(tokenizer, token.value || '');
  1107. break;
  1108. case 6 /* TokenTypes.Literal */:
  1109. if (token.value == null) {
  1110. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1111. }
  1112. linkedNode.key = parseLiteral(tokenizer, token.value || '');
  1113. break;
  1114. default: {
  1115. // empty key
  1116. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
  1117. const nextContext = tokenizer.context();
  1118. const emptyLinkedKeyNode = startNode(7 /* NodeTypes.LinkedKey */, nextContext.offset, nextContext.startLoc);
  1119. emptyLinkedKeyNode.value = '';
  1120. endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
  1121. linkedNode.key = emptyLinkedKeyNode;
  1122. endNode(linkedNode, nextContext.offset, nextContext.startLoc);
  1123. return {
  1124. nextConsumeToken: token,
  1125. node: linkedNode
  1126. };
  1127. }
  1128. }
  1129. endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
  1130. return {
  1131. node: linkedNode
  1132. };
  1133. }
  1134. function parseMessage(tokenizer) {
  1135. const context = tokenizer.context();
  1136. const startOffset = context.currentType === 1 /* TokenTypes.Pipe */
  1137. ? tokenizer.currentOffset()
  1138. : context.offset;
  1139. const startLoc = context.currentType === 1 /* TokenTypes.Pipe */
  1140. ? context.endLoc
  1141. : context.startLoc;
  1142. const node = startNode(2 /* NodeTypes.Message */, startOffset, startLoc);
  1143. node.items = [];
  1144. let nextToken = null;
  1145. do {
  1146. const token = nextToken || tokenizer.nextToken();
  1147. nextToken = null;
  1148. switch (token.type) {
  1149. case 0 /* TokenTypes.Text */:
  1150. if (token.value == null) {
  1151. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1152. }
  1153. node.items.push(parseText(tokenizer, token.value || ''));
  1154. break;
  1155. case 5 /* TokenTypes.List */:
  1156. if (token.value == null) {
  1157. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1158. }
  1159. node.items.push(parseList(tokenizer, token.value || ''));
  1160. break;
  1161. case 4 /* TokenTypes.Named */:
  1162. if (token.value == null) {
  1163. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1164. }
  1165. node.items.push(parseNamed(tokenizer, token.value || ''));
  1166. break;
  1167. case 6 /* TokenTypes.Literal */:
  1168. if (token.value == null) {
  1169. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1170. }
  1171. node.items.push(parseLiteral(tokenizer, token.value || ''));
  1172. break;
  1173. case 7 /* TokenTypes.LinkedAlias */: {
  1174. const parsed = parseLinked(tokenizer);
  1175. node.items.push(parsed.node);
  1176. nextToken = parsed.nextConsumeToken || null;
  1177. break;
  1178. }
  1179. }
  1180. } while (context.currentType !== 13 /* TokenTypes.EOF */ &&
  1181. context.currentType !== 1 /* TokenTypes.Pipe */);
  1182. // adjust message node loc
  1183. const endOffset = context.currentType === 1 /* TokenTypes.Pipe */
  1184. ? context.lastOffset
  1185. : tokenizer.currentOffset();
  1186. const endLoc = context.currentType === 1 /* TokenTypes.Pipe */
  1187. ? context.lastEndLoc
  1188. : tokenizer.currentPosition();
  1189. endNode(node, endOffset, endLoc);
  1190. return node;
  1191. }
  1192. function parsePlural(tokenizer, offset, loc, msgNode) {
  1193. const context = tokenizer.context();
  1194. let hasEmptyMessage = msgNode.items.length === 0;
  1195. const node = startNode(1 /* NodeTypes.Plural */, offset, loc);
  1196. node.cases = [];
  1197. node.cases.push(msgNode);
  1198. do {
  1199. const msg = parseMessage(tokenizer);
  1200. if (!hasEmptyMessage) {
  1201. hasEmptyMessage = msg.items.length === 0;
  1202. }
  1203. node.cases.push(msg);
  1204. } while (context.currentType !== 13 /* TokenTypes.EOF */);
  1205. if (hasEmptyMessage) {
  1206. emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
  1207. }
  1208. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1209. return node;
  1210. }
  1211. function parseResource(tokenizer) {
  1212. const context = tokenizer.context();
  1213. const { offset, startLoc } = context;
  1214. const msgNode = parseMessage(tokenizer);
  1215. if (context.currentType === 13 /* TokenTypes.EOF */) {
  1216. return msgNode;
  1217. }
  1218. else {
  1219. return parsePlural(tokenizer, offset, startLoc, msgNode);
  1220. }
  1221. }
  1222. function parse(source) {
  1223. const tokenizer = createTokenizer(source, assign({}, options));
  1224. const context = tokenizer.context();
  1225. const node = startNode(0 /* NodeTypes.Resource */, context.offset, context.startLoc);
  1226. if (location && node.loc) {
  1227. node.loc.source = source;
  1228. }
  1229. node.body = parseResource(tokenizer);
  1230. if (options.onCacheKey) {
  1231. node.cacheKey = options.onCacheKey(source);
  1232. }
  1233. // assert whether achieved to EOF
  1234. if (context.currentType !== 13 /* TokenTypes.EOF */) {
  1235. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');
  1236. }
  1237. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1238. return node;
  1239. }
  1240. return { parse };
  1241. }
  1242. function getTokenCaption(token) {
  1243. if (token.type === 13 /* TokenTypes.EOF */) {
  1244. return 'EOF';
  1245. }
  1246. const name = (token.value || '').replace(/\r?\n/gu, '\\n');
  1247. return name.length > 10 ? name.slice(0, 9) + '…' : name;
  1248. }
  1249. function createTransformer(ast, options = {} // eslint-disable-line
  1250. ) {
  1251. const _context = {
  1252. ast,
  1253. helpers: new Set()
  1254. };
  1255. const context = () => _context;
  1256. const helper = (name) => {
  1257. _context.helpers.add(name);
  1258. return name;
  1259. };
  1260. return { context, helper };
  1261. }
  1262. function traverseNodes(nodes, transformer) {
  1263. for (let i = 0; i < nodes.length; i++) {
  1264. traverseNode(nodes[i], transformer);
  1265. }
  1266. }
  1267. function traverseNode(node, transformer) {
  1268. // TODO: if we need pre-hook of transform, should be implemented to here
  1269. switch (node.type) {
  1270. case 1 /* NodeTypes.Plural */:
  1271. traverseNodes(node.cases, transformer);
  1272. transformer.helper("plural" /* HelperNameMap.PLURAL */);
  1273. break;
  1274. case 2 /* NodeTypes.Message */:
  1275. traverseNodes(node.items, transformer);
  1276. break;
  1277. case 6 /* NodeTypes.Linked */: {
  1278. const linked = node;
  1279. traverseNode(linked.key, transformer);
  1280. transformer.helper("linked" /* HelperNameMap.LINKED */);
  1281. transformer.helper("type" /* HelperNameMap.TYPE */);
  1282. break;
  1283. }
  1284. case 5 /* NodeTypes.List */:
  1285. transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
  1286. transformer.helper("list" /* HelperNameMap.LIST */);
  1287. break;
  1288. case 4 /* NodeTypes.Named */:
  1289. transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
  1290. transformer.helper("named" /* HelperNameMap.NAMED */);
  1291. break;
  1292. }
  1293. // TODO: if we need post-hook of transform, should be implemented to here
  1294. }
  1295. // transform AST
  1296. function transform(ast, options = {} // eslint-disable-line
  1297. ) {
  1298. const transformer = createTransformer(ast);
  1299. transformer.helper("normalize" /* HelperNameMap.NORMALIZE */);
  1300. // traverse
  1301. ast.body && traverseNode(ast.body, transformer);
  1302. // set meta information
  1303. const context = transformer.context();
  1304. ast.helpers = Array.from(context.helpers);
  1305. }
  1306. function optimize(ast) {
  1307. const body = ast.body;
  1308. if (body.type === 2 /* NodeTypes.Message */) {
  1309. optimizeMessageNode(body);
  1310. }
  1311. else {
  1312. body.cases.forEach(c => optimizeMessageNode(c));
  1313. }
  1314. return ast;
  1315. }
  1316. function optimizeMessageNode(message) {
  1317. if (message.items.length === 1) {
  1318. const item = message.items[0];
  1319. if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
  1320. message.static = item.value;
  1321. delete item.value; // optimization for size
  1322. }
  1323. }
  1324. else {
  1325. const values = [];
  1326. for (let i = 0; i < message.items.length; i++) {
  1327. const item = message.items[i];
  1328. if (!(item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */)) {
  1329. break;
  1330. }
  1331. if (item.value == null) {
  1332. break;
  1333. }
  1334. values.push(item.value);
  1335. }
  1336. if (values.length === message.items.length) {
  1337. message.static = join(values);
  1338. for (let i = 0; i < message.items.length; i++) {
  1339. const item = message.items[i];
  1340. if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
  1341. delete item.value; // optimization for size
  1342. }
  1343. }
  1344. }
  1345. }
  1346. }
  1347. const ERROR_DOMAIN$1 = 'minifier';
  1348. /* eslint-disable @typescript-eslint/no-explicit-any */
  1349. function minify(node) {
  1350. node.t = node.type;
  1351. switch (node.type) {
  1352. case 0 /* NodeTypes.Resource */: {
  1353. const resource = node;
  1354. minify(resource.body);
  1355. resource.b = resource.body;
  1356. delete resource.body;
  1357. break;
  1358. }
  1359. case 1 /* NodeTypes.Plural */: {
  1360. const plural = node;
  1361. const cases = plural.cases;
  1362. for (let i = 0; i < cases.length; i++) {
  1363. minify(cases[i]);
  1364. }
  1365. plural.c = cases;
  1366. delete plural.cases;
  1367. break;
  1368. }
  1369. case 2 /* NodeTypes.Message */: {
  1370. const message = node;
  1371. const items = message.items;
  1372. for (let i = 0; i < items.length; i++) {
  1373. minify(items[i]);
  1374. }
  1375. message.i = items;
  1376. delete message.items;
  1377. if (message.static) {
  1378. message.s = message.static;
  1379. delete message.static;
  1380. }
  1381. break;
  1382. }
  1383. case 3 /* NodeTypes.Text */:
  1384. case 9 /* NodeTypes.Literal */:
  1385. case 8 /* NodeTypes.LinkedModifier */:
  1386. case 7 /* NodeTypes.LinkedKey */: {
  1387. const valueNode = node;
  1388. if (valueNode.value) {
  1389. valueNode.v = valueNode.value;
  1390. delete valueNode.value;
  1391. }
  1392. break;
  1393. }
  1394. case 6 /* NodeTypes.Linked */: {
  1395. const linked = node;
  1396. minify(linked.key);
  1397. linked.k = linked.key;
  1398. delete linked.key;
  1399. if (linked.modifier) {
  1400. minify(linked.modifier);
  1401. linked.m = linked.modifier;
  1402. delete linked.modifier;
  1403. }
  1404. break;
  1405. }
  1406. case 5 /* NodeTypes.List */: {
  1407. const list = node;
  1408. list.i = list.index;
  1409. delete list.index;
  1410. break;
  1411. }
  1412. case 4 /* NodeTypes.Named */: {
  1413. const named = node;
  1414. named.k = named.key;
  1415. delete named.key;
  1416. break;
  1417. }
  1418. default:
  1419. {
  1420. throw createCompileError(CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE, null, {
  1421. domain: ERROR_DOMAIN$1,
  1422. args: [node.type]
  1423. });
  1424. }
  1425. }
  1426. delete node.type;
  1427. }
  1428. /* eslint-enable @typescript-eslint/no-explicit-any */
  1429. // eslint-disable-next-line @typescript-eslint/triple-slash-reference
  1430. /// <reference types="source-map-js" />
  1431. const ERROR_DOMAIN = 'parser';
  1432. function createCodeGenerator(ast, options) {
  1433. const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
  1434. const location = options.location !== false;
  1435. const _context = {
  1436. filename,
  1437. code: '',
  1438. column: 1,
  1439. line: 1,
  1440. offset: 0,
  1441. map: undefined,
  1442. breakLineCode,
  1443. needIndent: _needIndent,
  1444. indentLevel: 0
  1445. };
  1446. if (location && ast.loc) {
  1447. _context.source = ast.loc.source;
  1448. }
  1449. const context = () => _context;
  1450. function push(code, node) {
  1451. _context.code += code;
  1452. }
  1453. function _newline(n, withBreakLine = true) {
  1454. const _breakLineCode = withBreakLine ? breakLineCode : '';
  1455. push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
  1456. }
  1457. function indent(withNewLine = true) {
  1458. const level = ++_context.indentLevel;
  1459. withNewLine && _newline(level);
  1460. }
  1461. function deindent(withNewLine = true) {
  1462. const level = --_context.indentLevel;
  1463. withNewLine && _newline(level);
  1464. }
  1465. function newline() {
  1466. _newline(_context.indentLevel);
  1467. }
  1468. const helper = (key) => `_${key}`;
  1469. const needIndent = () => _context.needIndent;
  1470. return {
  1471. context,
  1472. push,
  1473. indent,
  1474. deindent,
  1475. newline,
  1476. helper,
  1477. needIndent
  1478. };
  1479. }
  1480. function generateLinkedNode(generator, node) {
  1481. const { helper } = generator;
  1482. generator.push(`${helper("linked" /* HelperNameMap.LINKED */)}(`);
  1483. generateNode(generator, node.key);
  1484. if (node.modifier) {
  1485. generator.push(`, `);
  1486. generateNode(generator, node.modifier);
  1487. generator.push(`, _type`);
  1488. }
  1489. else {
  1490. generator.push(`, undefined, _type`);
  1491. }
  1492. generator.push(`)`);
  1493. }
  1494. function generateMessageNode(generator, node) {
  1495. const { helper, needIndent } = generator;
  1496. generator.push(`${helper("normalize" /* HelperNameMap.NORMALIZE */)}([`);
  1497. generator.indent(needIndent());
  1498. const length = node.items.length;
  1499. for (let i = 0; i < length; i++) {
  1500. generateNode(generator, node.items[i]);
  1501. if (i === length - 1) {
  1502. break;
  1503. }
  1504. generator.push(', ');
  1505. }
  1506. generator.deindent(needIndent());
  1507. generator.push('])');
  1508. }
  1509. function generatePluralNode(generator, node) {
  1510. const { helper, needIndent } = generator;
  1511. if (node.cases.length > 1) {
  1512. generator.push(`${helper("plural" /* HelperNameMap.PLURAL */)}([`);
  1513. generator.indent(needIndent());
  1514. const length = node.cases.length;
  1515. for (let i = 0; i < length; i++) {
  1516. generateNode(generator, node.cases[i]);
  1517. if (i === length - 1) {
  1518. break;
  1519. }
  1520. generator.push(', ');
  1521. }
  1522. generator.deindent(needIndent());
  1523. generator.push(`])`);
  1524. }
  1525. }
  1526. function generateResource(generator, node) {
  1527. if (node.body) {
  1528. generateNode(generator, node.body);
  1529. }
  1530. else {
  1531. generator.push('null');
  1532. }
  1533. }
  1534. function generateNode(generator, node) {
  1535. const { helper } = generator;
  1536. switch (node.type) {
  1537. case 0 /* NodeTypes.Resource */:
  1538. generateResource(generator, node);
  1539. break;
  1540. case 1 /* NodeTypes.Plural */:
  1541. generatePluralNode(generator, node);
  1542. break;
  1543. case 2 /* NodeTypes.Message */:
  1544. generateMessageNode(generator, node);
  1545. break;
  1546. case 6 /* NodeTypes.Linked */:
  1547. generateLinkedNode(generator, node);
  1548. break;
  1549. case 8 /* NodeTypes.LinkedModifier */:
  1550. generator.push(JSON.stringify(node.value), node);
  1551. break;
  1552. case 7 /* NodeTypes.LinkedKey */:
  1553. generator.push(JSON.stringify(node.value), node);
  1554. break;
  1555. case 5 /* NodeTypes.List */:
  1556. generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("list" /* HelperNameMap.LIST */)}(${node.index}))`, node);
  1557. break;
  1558. case 4 /* NodeTypes.Named */:
  1559. generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("named" /* HelperNameMap.NAMED */)}(${JSON.stringify(node.key)}))`, node);
  1560. break;
  1561. case 9 /* NodeTypes.Literal */:
  1562. generator.push(JSON.stringify(node.value), node);
  1563. break;
  1564. case 3 /* NodeTypes.Text */:
  1565. generator.push(JSON.stringify(node.value), node);
  1566. break;
  1567. default:
  1568. {
  1569. throw createCompileError(CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE, null, {
  1570. domain: ERROR_DOMAIN,
  1571. args: [node.type]
  1572. });
  1573. }
  1574. }
  1575. }
  1576. // generate code from AST
  1577. const generate = (ast, options = {}) => {
  1578. const mode = isString(options.mode) ? options.mode : 'normal';
  1579. const filename = isString(options.filename)
  1580. ? options.filename
  1581. : 'message.intl';
  1582. const sourceMap = !!options.sourceMap;
  1583. // prettier-ignore
  1584. const breakLineCode = options.breakLineCode != null
  1585. ? options.breakLineCode
  1586. : mode === 'arrow'
  1587. ? ';'
  1588. : '\n';
  1589. const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
  1590. const helpers = ast.helpers || [];
  1591. const generator = createCodeGenerator(ast, {
  1592. mode,
  1593. filename,
  1594. sourceMap,
  1595. breakLineCode,
  1596. needIndent
  1597. });
  1598. generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
  1599. generator.indent(needIndent);
  1600. if (helpers.length > 0) {
  1601. generator.push(`const { ${join(helpers.map(s => `${s}: _${s}`), ', ')} } = ctx`);
  1602. generator.newline();
  1603. }
  1604. generator.push(`return `);
  1605. generateNode(generator, ast);
  1606. generator.deindent(needIndent);
  1607. generator.push(`}`);
  1608. delete ast.helpers;
  1609. const { code, map } = generator.context();
  1610. return {
  1611. ast,
  1612. code,
  1613. map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
  1614. };
  1615. };
  1616. function baseCompile$1(source, options = {}) {
  1617. const assignedOptions = assign({}, options);
  1618. const jit = !!assignedOptions.jit;
  1619. const enalbeMinify = !!assignedOptions.minify;
  1620. const enambeOptimize = assignedOptions.optimize == null ? true : assignedOptions.optimize;
  1621. // parse source codes
  1622. const parser = createParser(assignedOptions);
  1623. const ast = parser.parse(source);
  1624. if (!jit) {
  1625. // transform ASTs
  1626. transform(ast, assignedOptions);
  1627. // generate javascript codes
  1628. return generate(ast, assignedOptions);
  1629. }
  1630. else {
  1631. // optimize ASTs
  1632. enambeOptimize && optimize(ast);
  1633. // minimize ASTs
  1634. enalbeMinify && minify(ast);
  1635. // In JIT mode, no ast transform, no code generation.
  1636. return { ast, code: '' };
  1637. }
  1638. }
  1639. function isMessageAST(val) {
  1640. return (isObject(val) &&
  1641. resolveType(val) === 0 &&
  1642. (hasOwn(val, 'b') || hasOwn(val, 'body')));
  1643. }
  1644. const PROPS_BODY = ['b', 'body'];
  1645. function resolveBody(node) {
  1646. return resolveProps(node, PROPS_BODY);
  1647. }
  1648. const PROPS_CASES = ['c', 'cases'];
  1649. function resolveCases(node) {
  1650. return resolveProps(node, PROPS_CASES, []);
  1651. }
  1652. const PROPS_STATIC = ['s', 'static'];
  1653. function resolveStatic(node) {
  1654. return resolveProps(node, PROPS_STATIC);
  1655. }
  1656. const PROPS_ITEMS = ['i', 'items'];
  1657. function resolveItems(node) {
  1658. return resolveProps(node, PROPS_ITEMS, []);
  1659. }
  1660. const PROPS_TYPE = ['t', 'type'];
  1661. function resolveType(node) {
  1662. return resolveProps(node, PROPS_TYPE);
  1663. }
  1664. const PROPS_VALUE = ['v', 'value'];
  1665. function resolveValue$1(node, type) {
  1666. const resolved = resolveProps(node, PROPS_VALUE);
  1667. if (resolved != null) {
  1668. return resolved;
  1669. }
  1670. else {
  1671. throw createUnhandleNodeError(type);
  1672. }
  1673. }
  1674. const PROPS_MODIFIER = ['m', 'modifier'];
  1675. function resolveLinkedModifier(node) {
  1676. return resolveProps(node, PROPS_MODIFIER);
  1677. }
  1678. const PROPS_KEY = ['k', 'key'];
  1679. function resolveLinkedKey(node) {
  1680. const resolved = resolveProps(node, PROPS_KEY);
  1681. if (resolved) {
  1682. return resolved;
  1683. }
  1684. else {
  1685. throw createUnhandleNodeError(6 /* NodeTypes.Linked */);
  1686. }
  1687. }
  1688. function resolveProps(node, props, defaultValue) {
  1689. for (let i = 0; i < props.length; i++) {
  1690. const prop = props[i];
  1691. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1692. if (hasOwn(node, prop) && node[prop] != null) {
  1693. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1694. return node[prop];
  1695. }
  1696. }
  1697. return defaultValue;
  1698. }
  1699. const AST_NODE_PROPS_KEYS = [
  1700. ...PROPS_BODY,
  1701. ...PROPS_CASES,
  1702. ...PROPS_STATIC,
  1703. ...PROPS_ITEMS,
  1704. ...PROPS_KEY,
  1705. ...PROPS_MODIFIER,
  1706. ...PROPS_VALUE,
  1707. ...PROPS_TYPE
  1708. ];
  1709. function createUnhandleNodeError(type) {
  1710. return new Error(`unhandled node type: ${type}`);
  1711. }
  1712. function format(ast) {
  1713. const msg = (ctx) => formatParts(ctx, ast);
  1714. return msg;
  1715. }
  1716. function formatParts(ctx, ast) {
  1717. const body = resolveBody(ast);
  1718. if (body == null) {
  1719. throw createUnhandleNodeError(0 /* NodeTypes.Resource */);
  1720. }
  1721. const type = resolveType(body);
  1722. if (type === 1 /* NodeTypes.Plural */) {
  1723. const plural = body;
  1724. const cases = resolveCases(plural);
  1725. return ctx.plural(cases.reduce((messages, c) => [
  1726. ...messages,
  1727. formatMessageParts(ctx, c)
  1728. ], []));
  1729. }
  1730. else {
  1731. return formatMessageParts(ctx, body);
  1732. }
  1733. }
  1734. function formatMessageParts(ctx, node) {
  1735. const static_ = resolveStatic(node);
  1736. if (static_ != null) {
  1737. return ctx.type === 'text'
  1738. ? static_
  1739. : ctx.normalize([static_]);
  1740. }
  1741. else {
  1742. const messages = resolveItems(node).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
  1743. return ctx.normalize(messages);
  1744. }
  1745. }
  1746. function formatMessagePart(ctx, node) {
  1747. const type = resolveType(node);
  1748. switch (type) {
  1749. case 3 /* NodeTypes.Text */: {
  1750. return resolveValue$1(node, type);
  1751. }
  1752. case 9 /* NodeTypes.Literal */: {
  1753. return resolveValue$1(node, type);
  1754. }
  1755. case 4 /* NodeTypes.Named */: {
  1756. const named = node;
  1757. if (hasOwn(named, 'k') && named.k) {
  1758. return ctx.interpolate(ctx.named(named.k));
  1759. }
  1760. if (hasOwn(named, 'key') && named.key) {
  1761. return ctx.interpolate(ctx.named(named.key));
  1762. }
  1763. throw createUnhandleNodeError(type);
  1764. }
  1765. case 5 /* NodeTypes.List */: {
  1766. const list = node;
  1767. if (hasOwn(list, 'i') && isNumber(list.i)) {
  1768. return ctx.interpolate(ctx.list(list.i));
  1769. }
  1770. if (hasOwn(list, 'index') && isNumber(list.index)) {
  1771. return ctx.interpolate(ctx.list(list.index));
  1772. }
  1773. throw createUnhandleNodeError(type);
  1774. }
  1775. case 6 /* NodeTypes.Linked */: {
  1776. const linked = node;
  1777. const modifier = resolveLinkedModifier(linked);
  1778. const key = resolveLinkedKey(linked);
  1779. return ctx.linked(formatMessagePart(ctx, key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);
  1780. }
  1781. case 7 /* NodeTypes.LinkedKey */: {
  1782. return resolveValue$1(node, type);
  1783. }
  1784. case 8 /* NodeTypes.LinkedModifier */: {
  1785. return resolveValue$1(node, type);
  1786. }
  1787. default:
  1788. throw new Error(`unhandled node on format message part: ${type}`);
  1789. }
  1790. }
  1791. const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
  1792. function checkHtmlMessage(source, warnHtmlMessage) {
  1793. if (warnHtmlMessage && detectHtmlTag(source)) {
  1794. warn(format$1(WARN_MESSAGE, { source }));
  1795. }
  1796. }
  1797. const defaultOnCacheKey = (message) => message;
  1798. let compileCache = create();
  1799. function clearCompileCache() {
  1800. compileCache = create();
  1801. }
  1802. function baseCompile(message, options = {}) {
  1803. // error detecting on compile
  1804. let detectError = false;
  1805. const onError = options.onError || defaultOnError;
  1806. options.onError = (err) => {
  1807. detectError = true;
  1808. onError(err);
  1809. };
  1810. // compile with mesasge-compiler
  1811. return { ...baseCompile$1(message, options), detectError };
  1812. }
  1813. /* #__NO_SIDE_EFFECTS__ */
  1814. function compile(message, context) {
  1815. if (isString(message)) {
  1816. // check HTML message
  1817. const warnHtmlMessage = isBoolean(context.warnHtmlMessage)
  1818. ? context.warnHtmlMessage
  1819. : true;
  1820. checkHtmlMessage(message, warnHtmlMessage);
  1821. // check caches
  1822. const onCacheKey = context.onCacheKey || defaultOnCacheKey;
  1823. const cacheKey = onCacheKey(message);
  1824. const cached = compileCache[cacheKey];
  1825. if (cached) {
  1826. return cached;
  1827. }
  1828. // compile with JIT mode
  1829. const { ast, detectError } = baseCompile(message, {
  1830. ...context,
  1831. location: true,
  1832. jit: true
  1833. });
  1834. // compose message function from AST
  1835. const msg = format(ast);
  1836. // if occurred compile error, don't cache
  1837. return !detectError
  1838. ? (compileCache[cacheKey] = msg)
  1839. : msg;
  1840. }
  1841. else {
  1842. if (!isMessageAST(message)) {
  1843. warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);
  1844. return (() => message);
  1845. }
  1846. // AST case (passed from bundler)
  1847. const cacheKey = message.cacheKey;
  1848. if (cacheKey) {
  1849. const cached = compileCache[cacheKey];
  1850. if (cached) {
  1851. return cached;
  1852. }
  1853. // compose message function from message (AST)
  1854. return (compileCache[cacheKey] =
  1855. format(message));
  1856. }
  1857. else {
  1858. return format(message);
  1859. }
  1860. }
  1861. }
  1862. let devtools = null;
  1863. function setDevToolsHook(hook) {
  1864. devtools = hook;
  1865. }
  1866. function getDevToolsHook() {
  1867. return devtools;
  1868. }
  1869. function initI18nDevTools(i18n, version, meta) {
  1870. // TODO: queue if devtools is undefined
  1871. devtools &&
  1872. devtools.emit('i18n:init', {
  1873. timestamp: Date.now(),
  1874. i18n,
  1875. version,
  1876. meta
  1877. });
  1878. }
  1879. const translateDevTools =
  1880. /* #__PURE__*/ createDevToolsHook('function:translate');
  1881. function createDevToolsHook(hook) {
  1882. return (payloads) => devtools && devtools.emit(hook, payloads);
  1883. }
  1884. const CoreErrorCodes = {
  1885. INVALID_ARGUMENT: COMPILE_ERROR_CODES_EXTEND_POINT, // 17
  1886. INVALID_DATE_ARGUMENT: 18,
  1887. INVALID_ISO_DATE_ARGUMENT: 19,
  1888. NOT_SUPPORT_NON_STRING_MESSAGE: 20,
  1889. NOT_SUPPORT_LOCALE_PROMISE_VALUE: 21,
  1890. NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: 22,
  1891. NOT_SUPPORT_LOCALE_TYPE: 23
  1892. };
  1893. const CORE_ERROR_CODES_EXTEND_POINT = 24;
  1894. function createCoreError(code) {
  1895. return createCompileError(code, null, { messages: errorMessages } );
  1896. }
  1897. /** @internal */
  1898. const errorMessages = {
  1899. [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
  1900. [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
  1901. 'Make sure your Date represents a valid date.',
  1902. [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string',
  1903. [CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE]: 'Not support non-string message',
  1904. [CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE]: 'cannot support promise value',
  1905. [CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]: 'cannot support async function',
  1906. [CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE]: 'cannot support locale type'
  1907. };
  1908. /** @internal */
  1909. function getLocale(context, options) {
  1910. return options.locale != null
  1911. ? resolveLocale(options.locale)
  1912. : resolveLocale(context.locale);
  1913. }
  1914. let _resolveLocale;
  1915. /** @internal */
  1916. function resolveLocale(locale) {
  1917. if (isString(locale)) {
  1918. return locale;
  1919. }
  1920. else {
  1921. if (isFunction(locale)) {
  1922. if (locale.resolvedOnce && _resolveLocale != null) {
  1923. return _resolveLocale;
  1924. }
  1925. else if (locale.constructor.name === 'Function') {
  1926. const resolve = locale();
  1927. if (isPromise(resolve)) {
  1928. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);
  1929. }
  1930. return (_resolveLocale = resolve);
  1931. }
  1932. else {
  1933. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);
  1934. }
  1935. }
  1936. else {
  1937. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);
  1938. }
  1939. }
  1940. }
  1941. /**
  1942. * Fallback with simple implemenation
  1943. *
  1944. * @remarks
  1945. * A fallback locale function implemented with a simple fallback algorithm.
  1946. *
  1947. * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
  1948. *
  1949. * @param ctx - A {@link CoreContext | context}
  1950. * @param fallback - A {@link FallbackLocale | fallback locale}
  1951. * @param start - A starting {@link Locale | locale}
  1952. *
  1953. * @returns Fallback locales
  1954. *
  1955. * @VueI18nGeneral
  1956. */
  1957. function fallbackWithSimple(ctx, fallback, start) {
  1958. // prettier-ignore
  1959. return [...new Set([
  1960. start,
  1961. ...(isArray(fallback)
  1962. ? fallback
  1963. : isObject(fallback)
  1964. ? Object.keys(fallback)
  1965. : isString(fallback)
  1966. ? [fallback]
  1967. : [start])
  1968. ])];
  1969. }
  1970. /**
  1971. * Fallback with locale chain
  1972. *
  1973. * @remarks
  1974. * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
  1975. *
  1976. * @param ctx - A {@link CoreContext | context}
  1977. * @param fallback - A {@link FallbackLocale | fallback locale}
  1978. * @param start - A starting {@link Locale | locale}
  1979. *
  1980. * @returns Fallback locales
  1981. *
  1982. * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
  1983. *
  1984. * @VueI18nGeneral
  1985. */
  1986. function fallbackWithLocaleChain(ctx, fallback, start) {
  1987. const startLocale = isString(start) ? start : DEFAULT_LOCALE;
  1988. const context = ctx;
  1989. if (!context.__localeChainCache) {
  1990. context.__localeChainCache = new Map();
  1991. }
  1992. let chain = context.__localeChainCache.get(startLocale);
  1993. if (!chain) {
  1994. chain = [];
  1995. // first block defined by start
  1996. let block = [start];
  1997. // while any intervening block found
  1998. while (isArray(block)) {
  1999. block = appendBlockToChain(chain, block, fallback);
  2000. }
  2001. // prettier-ignore
  2002. // last block defined by default
  2003. const defaults = isArray(fallback) || !isPlainObject(fallback)
  2004. ? fallback
  2005. : fallback['default']
  2006. ? fallback['default']
  2007. : null;
  2008. // convert defaults to array
  2009. block = isString(defaults) ? [defaults] : defaults;
  2010. if (isArray(block)) {
  2011. appendBlockToChain(chain, block, false);
  2012. }
  2013. context.__localeChainCache.set(startLocale, chain);
  2014. }
  2015. return chain;
  2016. }
  2017. function appendBlockToChain(chain, block, blocks) {
  2018. let follow = true;
  2019. for (let i = 0; i < block.length && isBoolean(follow); i++) {
  2020. const locale = block[i];
  2021. if (isString(locale)) {
  2022. follow = appendLocaleToChain(chain, block[i], blocks);
  2023. }
  2024. }
  2025. return follow;
  2026. }
  2027. function appendLocaleToChain(chain, locale, blocks) {
  2028. let follow;
  2029. const tokens = locale.split('-');
  2030. do {
  2031. const target = tokens.join('-');
  2032. follow = appendItemToChain(chain, target, blocks);
  2033. tokens.splice(-1, 1);
  2034. } while (tokens.length && follow === true);
  2035. return follow;
  2036. }
  2037. function appendItemToChain(chain, target, blocks) {
  2038. let follow = false;
  2039. if (!chain.includes(target)) {
  2040. follow = true;
  2041. if (target) {
  2042. follow = target[target.length - 1] !== '!';
  2043. const locale = target.replace(/!/g, '');
  2044. chain.push(locale);
  2045. if ((isArray(blocks) || isPlainObject(blocks)) &&
  2046. blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
  2047. ) {
  2048. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2049. follow = blocks[locale];
  2050. }
  2051. }
  2052. }
  2053. return follow;
  2054. }
  2055. const pathStateMachine = [];
  2056. pathStateMachine[0 /* States.BEFORE_PATH */] = {
  2057. ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
  2058. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  2059. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  2060. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  2061. };
  2062. pathStateMachine[1 /* States.IN_PATH */] = {
  2063. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
  2064. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
  2065. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  2066. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  2067. };
  2068. pathStateMachine[2 /* States.BEFORE_IDENT */] = {
  2069. ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
  2070. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  2071. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
  2072. };
  2073. pathStateMachine[3 /* States.IN_IDENT */] = {
  2074. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  2075. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  2076. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
  2077. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
  2078. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
  2079. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
  2080. };
  2081. pathStateMachine[4 /* States.IN_SUB_PATH */] = {
  2082. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
  2083. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
  2084. ["[" /* PathCharTypes.LEFT_BRACKET */]: [
  2085. 4 /* States.IN_SUB_PATH */,
  2086. 2 /* Actions.INC_SUB_PATH_DEPTH */
  2087. ],
  2088. ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
  2089. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  2090. ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
  2091. };
  2092. pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
  2093. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  2094. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  2095. ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
  2096. };
  2097. pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
  2098. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  2099. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  2100. ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
  2101. };
  2102. /**
  2103. * Check if an expression is a literal value.
  2104. */
  2105. const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
  2106. function isLiteral(exp) {
  2107. return literalValueRE.test(exp);
  2108. }
  2109. /**
  2110. * Strip quotes from a string
  2111. */
  2112. function stripQuotes(str) {
  2113. const a = str.charCodeAt(0);
  2114. const b = str.charCodeAt(str.length - 1);
  2115. return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
  2116. }
  2117. /**
  2118. * Determine the type of a character in a keypath.
  2119. */
  2120. function getPathCharType(ch) {
  2121. if (ch === undefined || ch === null) {
  2122. return "o" /* PathCharTypes.END_OF_FAIL */;
  2123. }
  2124. const code = ch.charCodeAt(0);
  2125. switch (code) {
  2126. case 0x5b: // [
  2127. case 0x5d: // ]
  2128. case 0x2e: // .
  2129. case 0x22: // "
  2130. case 0x27: // '
  2131. return ch;
  2132. case 0x5f: // _
  2133. case 0x24: // $
  2134. case 0x2d: // -
  2135. return "i" /* PathCharTypes.IDENT */;
  2136. case 0x09: // Tab (HT)
  2137. case 0x0a: // Newline (LF)
  2138. case 0x0d: // Return (CR)
  2139. case 0xa0: // No-break space (NBSP)
  2140. case 0xfeff: // Byte Order Mark (BOM)
  2141. case 0x2028: // Line Separator (LS)
  2142. case 0x2029: // Paragraph Separator (PS)
  2143. return "w" /* PathCharTypes.WORKSPACE */;
  2144. }
  2145. return "i" /* PathCharTypes.IDENT */;
  2146. }
  2147. /**
  2148. * Format a subPath, return its plain form if it is
  2149. * a literal string or number. Otherwise prepend the
  2150. * dynamic indicator (*).
  2151. */
  2152. function formatSubPath(path) {
  2153. const trimmed = path.trim();
  2154. // invalid leading 0
  2155. if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
  2156. return false;
  2157. }
  2158. return isLiteral(trimmed)
  2159. ? stripQuotes(trimmed)
  2160. : "*" /* PathCharTypes.ASTARISK */ + trimmed;
  2161. }
  2162. /**
  2163. * Parse a string path into an array of segments
  2164. */
  2165. function parse(path) {
  2166. const keys = [];
  2167. let index = -1;
  2168. let mode = 0 /* States.BEFORE_PATH */;
  2169. let subPathDepth = 0;
  2170. let c;
  2171. let key; // eslint-disable-line
  2172. let newChar;
  2173. let type;
  2174. let transition;
  2175. let action;
  2176. let typeMap;
  2177. const actions = [];
  2178. actions[0 /* Actions.APPEND */] = () => {
  2179. if (key === undefined) {
  2180. key = newChar;
  2181. }
  2182. else {
  2183. key += newChar;
  2184. }
  2185. };
  2186. actions[1 /* Actions.PUSH */] = () => {
  2187. if (key !== undefined) {
  2188. keys.push(key);
  2189. key = undefined;
  2190. }
  2191. };
  2192. actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
  2193. actions[0 /* Actions.APPEND */]();
  2194. subPathDepth++;
  2195. };
  2196. actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
  2197. if (subPathDepth > 0) {
  2198. subPathDepth--;
  2199. mode = 4 /* States.IN_SUB_PATH */;
  2200. actions[0 /* Actions.APPEND */]();
  2201. }
  2202. else {
  2203. subPathDepth = 0;
  2204. if (key === undefined) {
  2205. return false;
  2206. }
  2207. key = formatSubPath(key);
  2208. if (key === false) {
  2209. return false;
  2210. }
  2211. else {
  2212. actions[1 /* Actions.PUSH */]();
  2213. }
  2214. }
  2215. };
  2216. function maybeUnescapeQuote() {
  2217. const nextChar = path[index + 1];
  2218. if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
  2219. nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
  2220. (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
  2221. nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
  2222. index++;
  2223. newChar = '\\' + nextChar;
  2224. actions[0 /* Actions.APPEND */]();
  2225. return true;
  2226. }
  2227. }
  2228. while (mode !== null) {
  2229. index++;
  2230. c = path[index];
  2231. if (c === '\\' && maybeUnescapeQuote()) {
  2232. continue;
  2233. }
  2234. type = getPathCharType(c);
  2235. typeMap = pathStateMachine[mode];
  2236. transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
  2237. // check parse error
  2238. if (transition === 8 /* States.ERROR */) {
  2239. return;
  2240. }
  2241. mode = transition[0];
  2242. if (transition[1] !== undefined) {
  2243. action = actions[transition[1]];
  2244. if (action) {
  2245. newChar = c;
  2246. if (action() === false) {
  2247. return;
  2248. }
  2249. }
  2250. }
  2251. // check parse finish
  2252. if (mode === 7 /* States.AFTER_PATH */) {
  2253. return keys;
  2254. }
  2255. }
  2256. }
  2257. // path token cache
  2258. const cache = new Map();
  2259. /**
  2260. * key-value message resolver
  2261. *
  2262. * @remarks
  2263. * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
  2264. *
  2265. * @param obj - A target object to be resolved with path
  2266. * @param path - A {@link Path | path} to resolve the value of message
  2267. *
  2268. * @returns A resolved {@link PathValue | path value}
  2269. *
  2270. * @VueI18nGeneral
  2271. */
  2272. function resolveWithKeyValue(obj, path) {
  2273. return isObject(obj) ? obj[path] : null;
  2274. }
  2275. /**
  2276. * message resolver
  2277. *
  2278. * @remarks
  2279. * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
  2280. *
  2281. * @param obj - A target object to be resolved with path
  2282. * @param path - A {@link Path | path} to resolve the value of message
  2283. *
  2284. * @returns A resolved {@link PathValue | path value}
  2285. *
  2286. * @VueI18nGeneral
  2287. */
  2288. function resolveValue(obj, path) {
  2289. // check object
  2290. if (!isObject(obj)) {
  2291. return null;
  2292. }
  2293. // parse path
  2294. let hit = cache.get(path);
  2295. if (!hit) {
  2296. hit = parse(path);
  2297. if (hit) {
  2298. cache.set(path, hit);
  2299. }
  2300. }
  2301. // check hit
  2302. if (!hit) {
  2303. return null;
  2304. }
  2305. // resolve path value
  2306. const len = hit.length;
  2307. let last = obj;
  2308. let i = 0;
  2309. while (i < len) {
  2310. const key = hit[i];
  2311. /**
  2312. * NOTE:
  2313. * if `key` is intlify message format AST node key and `last` is intlify message format AST, skip it.
  2314. * because the AST node is not a key-value structure.
  2315. */
  2316. if (AST_NODE_PROPS_KEYS.includes(key) && isMessageAST(last)) {
  2317. return null;
  2318. }
  2319. const val = last[key];
  2320. if (val === undefined) {
  2321. return null;
  2322. }
  2323. if (isFunction(last)) {
  2324. return null;
  2325. }
  2326. last = val;
  2327. i++;
  2328. }
  2329. return last;
  2330. }
  2331. const CoreWarnCodes = {
  2332. NOT_FOUND_KEY: 1,
  2333. FALLBACK_TO_TRANSLATE: 2,
  2334. CANNOT_FORMAT_NUMBER: 3,
  2335. FALLBACK_TO_NUMBER_FORMAT: 4,
  2336. CANNOT_FORMAT_DATE: 5,
  2337. FALLBACK_TO_DATE_FORMAT: 6,
  2338. EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: 7
  2339. };
  2340. const CORE_WARN_CODES_EXTEND_POINT = 8;
  2341. /** @internal */
  2342. const warnMessages = {
  2343. [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
  2344. [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
  2345. [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
  2346. [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
  2347. [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
  2348. [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
  2349. [CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER]: `This project is using Custom Message Compiler, which is an experimental feature. It may receive breaking changes or be removed in the future.`
  2350. };
  2351. function getWarnMessage(code, ...args) {
  2352. return format$1(warnMessages[code], ...args);
  2353. }
  2354. /* eslint-disable @typescript-eslint/no-explicit-any */
  2355. /**
  2356. * Intlify core-base version
  2357. * @internal
  2358. */
  2359. const VERSION = '11.1.3';
  2360. const NOT_REOSLVED = -1;
  2361. const DEFAULT_LOCALE = 'en-US';
  2362. const MISSING_RESOLVE_VALUE = '';
  2363. const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
  2364. function getDefaultLinkedModifiers() {
  2365. return {
  2366. upper: (val, type) => {
  2367. // prettier-ignore
  2368. return type === 'text' && isString(val)
  2369. ? val.toUpperCase()
  2370. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  2371. ? val.children.toUpperCase()
  2372. : val;
  2373. },
  2374. lower: (val, type) => {
  2375. // prettier-ignore
  2376. return type === 'text' && isString(val)
  2377. ? val.toLowerCase()
  2378. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  2379. ? val.children.toLowerCase()
  2380. : val;
  2381. },
  2382. capitalize: (val, type) => {
  2383. // prettier-ignore
  2384. return (type === 'text' && isString(val)
  2385. ? capitalize(val)
  2386. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  2387. ? capitalize(val.children)
  2388. : val);
  2389. }
  2390. };
  2391. }
  2392. let _compiler;
  2393. function registerMessageCompiler(compiler) {
  2394. _compiler = compiler;
  2395. }
  2396. let _resolver;
  2397. /**
  2398. * Register the message resolver
  2399. *
  2400. * @param resolver - A {@link MessageResolver} function
  2401. *
  2402. * @VueI18nGeneral
  2403. */
  2404. function registerMessageResolver(resolver) {
  2405. _resolver = resolver;
  2406. }
  2407. let _fallbacker;
  2408. /**
  2409. * Register the locale fallbacker
  2410. *
  2411. * @param fallbacker - A {@link LocaleFallbacker} function
  2412. *
  2413. * @VueI18nGeneral
  2414. */
  2415. function registerLocaleFallbacker(fallbacker) {
  2416. _fallbacker = fallbacker;
  2417. }
  2418. // Additional Meta for Intlify DevTools
  2419. let _additionalMeta = null;
  2420. /* #__NO_SIDE_EFFECTS__ */
  2421. const setAdditionalMeta = (meta) => {
  2422. _additionalMeta = meta;
  2423. };
  2424. /* #__NO_SIDE_EFFECTS__ */
  2425. const getAdditionalMeta = () => _additionalMeta;
  2426. let _fallbackContext = null;
  2427. const setFallbackContext = (context) => {
  2428. _fallbackContext = context;
  2429. };
  2430. const getFallbackContext = () => _fallbackContext;
  2431. // ID for CoreContext
  2432. let _cid = 0;
  2433. function createCoreContext(options = {}) {
  2434. // setup options
  2435. const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
  2436. const version = isString(options.version) ? options.version : VERSION;
  2437. const locale = isString(options.locale) || isFunction(options.locale)
  2438. ? options.locale
  2439. : DEFAULT_LOCALE;
  2440. const _locale = isFunction(locale) ? DEFAULT_LOCALE : locale;
  2441. const fallbackLocale = isArray(options.fallbackLocale) ||
  2442. isPlainObject(options.fallbackLocale) ||
  2443. isString(options.fallbackLocale) ||
  2444. options.fallbackLocale === false
  2445. ? options.fallbackLocale
  2446. : _locale;
  2447. const messages = isPlainObject(options.messages)
  2448. ? options.messages
  2449. : createResources(_locale);
  2450. const datetimeFormats = isPlainObject(options.datetimeFormats)
  2451. ? options.datetimeFormats
  2452. : createResources(_locale)
  2453. ;
  2454. const numberFormats = isPlainObject(options.numberFormats)
  2455. ? options.numberFormats
  2456. : createResources(_locale)
  2457. ;
  2458. const modifiers = assign(create(), options.modifiers, getDefaultLinkedModifiers());
  2459. const pluralRules = options.pluralRules || create();
  2460. const missing = isFunction(options.missing) ? options.missing : null;
  2461. const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  2462. ? options.missingWarn
  2463. : true;
  2464. const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  2465. ? options.fallbackWarn
  2466. : true;
  2467. const fallbackFormat = !!options.fallbackFormat;
  2468. const unresolving = !!options.unresolving;
  2469. const postTranslation = isFunction(options.postTranslation)
  2470. ? options.postTranslation
  2471. : null;
  2472. const processor = isPlainObject(options.processor) ? options.processor : null;
  2473. const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
  2474. ? options.warnHtmlMessage
  2475. : true;
  2476. const escapeParameter = !!options.escapeParameter;
  2477. const messageCompiler = isFunction(options.messageCompiler)
  2478. ? options.messageCompiler
  2479. : _compiler;
  2480. if (isFunction(options.messageCompiler)) {
  2481. warnOnce(getWarnMessage(CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER));
  2482. }
  2483. const messageResolver = isFunction(options.messageResolver)
  2484. ? options.messageResolver
  2485. : _resolver || resolveWithKeyValue;
  2486. const localeFallbacker = isFunction(options.localeFallbacker)
  2487. ? options.localeFallbacker
  2488. : _fallbacker || fallbackWithSimple;
  2489. const fallbackContext = isObject(options.fallbackContext)
  2490. ? options.fallbackContext
  2491. : undefined;
  2492. // setup internal options
  2493. const internalOptions = options;
  2494. const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
  2495. ? internalOptions.__datetimeFormatters
  2496. : new Map()
  2497. ;
  2498. const __numberFormatters = isObject(internalOptions.__numberFormatters)
  2499. ? internalOptions.__numberFormatters
  2500. : new Map()
  2501. ;
  2502. const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
  2503. _cid++;
  2504. const context = {
  2505. version,
  2506. cid: _cid,
  2507. locale,
  2508. fallbackLocale,
  2509. messages,
  2510. modifiers,
  2511. pluralRules,
  2512. missing,
  2513. missingWarn,
  2514. fallbackWarn,
  2515. fallbackFormat,
  2516. unresolving,
  2517. postTranslation,
  2518. processor,
  2519. warnHtmlMessage,
  2520. escapeParameter,
  2521. messageCompiler,
  2522. messageResolver,
  2523. localeFallbacker,
  2524. fallbackContext,
  2525. onWarn,
  2526. __meta
  2527. };
  2528. {
  2529. context.datetimeFormats = datetimeFormats;
  2530. context.numberFormats = numberFormats;
  2531. context.__datetimeFormatters = __datetimeFormatters;
  2532. context.__numberFormatters = __numberFormatters;
  2533. }
  2534. // for vue-devtools timeline event
  2535. {
  2536. context.__v_emitter =
  2537. internalOptions.__v_emitter != null
  2538. ? internalOptions.__v_emitter
  2539. : undefined;
  2540. }
  2541. // NOTE: experimental !!
  2542. {
  2543. initI18nDevTools(context, version, __meta);
  2544. }
  2545. return context;
  2546. }
  2547. const createResources = (locale) => ({ [locale]: create() });
  2548. /** @internal */
  2549. function isTranslateFallbackWarn(fallback, key) {
  2550. return fallback instanceof RegExp ? fallback.test(key) : fallback;
  2551. }
  2552. /** @internal */
  2553. function isTranslateMissingWarn(missing, key) {
  2554. return missing instanceof RegExp ? missing.test(key) : missing;
  2555. }
  2556. /** @internal */
  2557. function handleMissing(context, key, locale, missingWarn, type) {
  2558. const { missing, onWarn } = context;
  2559. // for vue-devtools timeline event
  2560. {
  2561. const emitter = context.__v_emitter;
  2562. if (emitter) {
  2563. emitter.emit('missing', {
  2564. locale,
  2565. key,
  2566. type,
  2567. groupId: `${type}:${key}`
  2568. });
  2569. }
  2570. }
  2571. if (missing !== null) {
  2572. const ret = missing(context, locale, key, type);
  2573. return isString(ret) ? ret : key;
  2574. }
  2575. else {
  2576. if (isTranslateMissingWarn(missingWarn, key)) {
  2577. onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
  2578. }
  2579. return key;
  2580. }
  2581. }
  2582. /** @internal */
  2583. function updateFallbackLocale(ctx, locale, fallback) {
  2584. const context = ctx;
  2585. context.__localeChainCache = new Map();
  2586. ctx.localeFallbacker(ctx, fallback, locale);
  2587. }
  2588. /** @internal */
  2589. function isAlmostSameLocale(locale, compareLocale) {
  2590. if (locale === compareLocale)
  2591. return false;
  2592. return locale.split('-')[0] === compareLocale.split('-')[0];
  2593. }
  2594. /** @internal */
  2595. function isImplicitFallback(targetLocale, locales) {
  2596. const index = locales.indexOf(targetLocale);
  2597. if (index === -1) {
  2598. return false;
  2599. }
  2600. for (let i = index + 1; i < locales.length; i++) {
  2601. if (isAlmostSameLocale(targetLocale, locales[i])) {
  2602. return true;
  2603. }
  2604. }
  2605. return false;
  2606. }
  2607. /* eslint-enable @typescript-eslint/no-explicit-any */
  2608. const intlDefined = typeof Intl !== 'undefined';
  2609. const Availabilities = {
  2610. dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
  2611. numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
  2612. };
  2613. // implementation of `datetime` function
  2614. function datetime(context, ...args) {
  2615. const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  2616. const { __datetimeFormatters } = context;
  2617. if (!Availabilities.dateTimeFormat) {
  2618. onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
  2619. return MISSING_RESOLVE_VALUE;
  2620. }
  2621. const [key, value, options, overrides] = parseDateTimeArgs(...args);
  2622. const missingWarn = isBoolean(options.missingWarn)
  2623. ? options.missingWarn
  2624. : context.missingWarn;
  2625. const fallbackWarn = isBoolean(options.fallbackWarn)
  2626. ? options.fallbackWarn
  2627. : context.fallbackWarn;
  2628. const part = !!options.part;
  2629. const locale = getLocale(context, options);
  2630. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  2631. fallbackLocale, locale);
  2632. if (!isString(key) || key === '') {
  2633. return new Intl.DateTimeFormat(locale, overrides).format(value);
  2634. }
  2635. // resolve format
  2636. let datetimeFormat = {};
  2637. let targetLocale;
  2638. let format = null;
  2639. let from = locale;
  2640. let to = null;
  2641. const type = 'datetime format';
  2642. for (let i = 0; i < locales.length; i++) {
  2643. targetLocale = to = locales[i];
  2644. if (locale !== targetLocale &&
  2645. isTranslateFallbackWarn(fallbackWarn, key)) {
  2646. onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
  2647. key,
  2648. target: targetLocale
  2649. }));
  2650. }
  2651. // for vue-devtools timeline event
  2652. if (locale !== targetLocale) {
  2653. const emitter = context.__v_emitter;
  2654. if (emitter) {
  2655. emitter.emit('fallback', {
  2656. type,
  2657. key,
  2658. from,
  2659. to,
  2660. groupId: `${type}:${key}`
  2661. });
  2662. }
  2663. }
  2664. datetimeFormat =
  2665. datetimeFormats[targetLocale] || {};
  2666. format = datetimeFormat[key];
  2667. if (isPlainObject(format))
  2668. break;
  2669. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  2670. from = to;
  2671. }
  2672. // checking format and target locale
  2673. if (!isPlainObject(format) || !isString(targetLocale)) {
  2674. return unresolving ? NOT_REOSLVED : key;
  2675. }
  2676. let id = `${targetLocale}__${key}`;
  2677. if (!isEmptyObject(overrides)) {
  2678. id = `${id}__${JSON.stringify(overrides)}`;
  2679. }
  2680. let formatter = __datetimeFormatters.get(id);
  2681. if (!formatter) {
  2682. formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
  2683. __datetimeFormatters.set(id, formatter);
  2684. }
  2685. return !part ? formatter.format(value) : formatter.formatToParts(value);
  2686. }
  2687. /** @internal */
  2688. const DATETIME_FORMAT_OPTIONS_KEYS = [
  2689. 'localeMatcher',
  2690. 'weekday',
  2691. 'era',
  2692. 'year',
  2693. 'month',
  2694. 'day',
  2695. 'hour',
  2696. 'minute',
  2697. 'second',
  2698. 'timeZoneName',
  2699. 'formatMatcher',
  2700. 'hour12',
  2701. 'timeZone',
  2702. 'dateStyle',
  2703. 'timeStyle',
  2704. 'calendar',
  2705. 'dayPeriod',
  2706. 'numberingSystem',
  2707. 'hourCycle',
  2708. 'fractionalSecondDigits'
  2709. ];
  2710. /** @internal */
  2711. function parseDateTimeArgs(...args) {
  2712. const [arg1, arg2, arg3, arg4] = args;
  2713. const options = create();
  2714. let overrides = create();
  2715. let value;
  2716. if (isString(arg1)) {
  2717. // Only allow ISO strings - other date formats are often supported,
  2718. // but may cause different results in different browsers.
  2719. const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
  2720. if (!matches) {
  2721. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  2722. }
  2723. // Some browsers can not parse the iso datetime separated by space,
  2724. // this is a compromise solution by replace the 'T'/' ' with 'T'
  2725. const dateTime = matches[3]
  2726. ? matches[3].trim().startsWith('T')
  2727. ? `${matches[1].trim()}${matches[3].trim()}`
  2728. : `${matches[1].trim()}T${matches[3].trim()}`
  2729. : matches[1].trim();
  2730. value = new Date(dateTime);
  2731. try {
  2732. // This will fail if the date is not valid
  2733. value.toISOString();
  2734. }
  2735. catch {
  2736. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  2737. }
  2738. }
  2739. else if (isDate(arg1)) {
  2740. if (isNaN(arg1.getTime())) {
  2741. throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
  2742. }
  2743. value = arg1;
  2744. }
  2745. else if (isNumber(arg1)) {
  2746. value = arg1;
  2747. }
  2748. else {
  2749. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  2750. }
  2751. if (isString(arg2)) {
  2752. options.key = arg2;
  2753. }
  2754. else if (isPlainObject(arg2)) {
  2755. Object.keys(arg2).forEach(key => {
  2756. if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
  2757. overrides[key] = arg2[key];
  2758. }
  2759. else {
  2760. options[key] = arg2[key];
  2761. }
  2762. });
  2763. }
  2764. if (isString(arg3)) {
  2765. options.locale = arg3;
  2766. }
  2767. else if (isPlainObject(arg3)) {
  2768. overrides = arg3;
  2769. }
  2770. if (isPlainObject(arg4)) {
  2771. overrides = arg4;
  2772. }
  2773. return [options.key || '', value, options, overrides];
  2774. }
  2775. /** @internal */
  2776. function clearDateTimeFormat(ctx, locale, format) {
  2777. const context = ctx;
  2778. for (const key in format) {
  2779. const id = `${locale}__${key}`;
  2780. if (!context.__datetimeFormatters.has(id)) {
  2781. continue;
  2782. }
  2783. context.__datetimeFormatters.delete(id);
  2784. }
  2785. }
  2786. // implementation of `number` function
  2787. function number(context, ...args) {
  2788. const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  2789. const { __numberFormatters } = context;
  2790. if (!Availabilities.numberFormat) {
  2791. onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
  2792. return MISSING_RESOLVE_VALUE;
  2793. }
  2794. const [key, value, options, overrides] = parseNumberArgs(...args);
  2795. const missingWarn = isBoolean(options.missingWarn)
  2796. ? options.missingWarn
  2797. : context.missingWarn;
  2798. const fallbackWarn = isBoolean(options.fallbackWarn)
  2799. ? options.fallbackWarn
  2800. : context.fallbackWarn;
  2801. const part = !!options.part;
  2802. const locale = getLocale(context, options);
  2803. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  2804. fallbackLocale, locale);
  2805. if (!isString(key) || key === '') {
  2806. return new Intl.NumberFormat(locale, overrides).format(value);
  2807. }
  2808. // resolve format
  2809. let numberFormat = {};
  2810. let targetLocale;
  2811. let format = null;
  2812. let from = locale;
  2813. let to = null;
  2814. const type = 'number format';
  2815. for (let i = 0; i < locales.length; i++) {
  2816. targetLocale = to = locales[i];
  2817. if (locale !== targetLocale &&
  2818. isTranslateFallbackWarn(fallbackWarn, key)) {
  2819. onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
  2820. key,
  2821. target: targetLocale
  2822. }));
  2823. }
  2824. // for vue-devtools timeline event
  2825. if (locale !== targetLocale) {
  2826. const emitter = context.__v_emitter;
  2827. if (emitter) {
  2828. emitter.emit('fallback', {
  2829. type,
  2830. key,
  2831. from,
  2832. to,
  2833. groupId: `${type}:${key}`
  2834. });
  2835. }
  2836. }
  2837. numberFormat =
  2838. numberFormats[targetLocale] || {};
  2839. format = numberFormat[key];
  2840. if (isPlainObject(format))
  2841. break;
  2842. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  2843. from = to;
  2844. }
  2845. // checking format and target locale
  2846. if (!isPlainObject(format) || !isString(targetLocale)) {
  2847. return unresolving ? NOT_REOSLVED : key;
  2848. }
  2849. let id = `${targetLocale}__${key}`;
  2850. if (!isEmptyObject(overrides)) {
  2851. id = `${id}__${JSON.stringify(overrides)}`;
  2852. }
  2853. let formatter = __numberFormatters.get(id);
  2854. if (!formatter) {
  2855. formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
  2856. __numberFormatters.set(id, formatter);
  2857. }
  2858. return !part ? formatter.format(value) : formatter.formatToParts(value);
  2859. }
  2860. /** @internal */
  2861. const NUMBER_FORMAT_OPTIONS_KEYS = [
  2862. 'localeMatcher',
  2863. 'style',
  2864. 'currency',
  2865. 'currencyDisplay',
  2866. 'currencySign',
  2867. 'useGrouping',
  2868. 'minimumIntegerDigits',
  2869. 'minimumFractionDigits',
  2870. 'maximumFractionDigits',
  2871. 'minimumSignificantDigits',
  2872. 'maximumSignificantDigits',
  2873. 'compactDisplay',
  2874. 'notation',
  2875. 'signDisplay',
  2876. 'unit',
  2877. 'unitDisplay',
  2878. 'roundingMode',
  2879. 'roundingPriority',
  2880. 'roundingIncrement',
  2881. 'trailingZeroDisplay'
  2882. ];
  2883. /** @internal */
  2884. function parseNumberArgs(...args) {
  2885. const [arg1, arg2, arg3, arg4] = args;
  2886. const options = create();
  2887. let overrides = create();
  2888. if (!isNumber(arg1)) {
  2889. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  2890. }
  2891. const value = arg1;
  2892. if (isString(arg2)) {
  2893. options.key = arg2;
  2894. }
  2895. else if (isPlainObject(arg2)) {
  2896. Object.keys(arg2).forEach(key => {
  2897. if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
  2898. overrides[key] = arg2[key];
  2899. }
  2900. else {
  2901. options[key] = arg2[key];
  2902. }
  2903. });
  2904. }
  2905. if (isString(arg3)) {
  2906. options.locale = arg3;
  2907. }
  2908. else if (isPlainObject(arg3)) {
  2909. overrides = arg3;
  2910. }
  2911. if (isPlainObject(arg4)) {
  2912. overrides = arg4;
  2913. }
  2914. return [options.key || '', value, options, overrides];
  2915. }
  2916. /** @internal */
  2917. function clearNumberFormat(ctx, locale, format) {
  2918. const context = ctx;
  2919. for (const key in format) {
  2920. const id = `${locale}__${key}`;
  2921. if (!context.__numberFormatters.has(id)) {
  2922. continue;
  2923. }
  2924. context.__numberFormatters.delete(id);
  2925. }
  2926. }
  2927. const DEFAULT_MODIFIER = (str) => str;
  2928. const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
  2929. const DEFAULT_MESSAGE_DATA_TYPE = 'text';
  2930. const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);
  2931. const DEFAULT_INTERPOLATE = toDisplayString;
  2932. function pluralDefault(choice, choicesLength) {
  2933. choice = Math.abs(choice);
  2934. if (choicesLength === 2) {
  2935. // prettier-ignore
  2936. return choice
  2937. ? choice > 1
  2938. ? 1
  2939. : 0
  2940. : 1;
  2941. }
  2942. return choice ? Math.min(choice, 2) : 0;
  2943. }
  2944. function getPluralIndex(options) {
  2945. // prettier-ignore
  2946. const index = isNumber(options.pluralIndex)
  2947. ? options.pluralIndex
  2948. : -1;
  2949. // prettier-ignore
  2950. return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
  2951. ? isNumber(options.named.count)
  2952. ? options.named.count
  2953. : isNumber(options.named.n)
  2954. ? options.named.n
  2955. : index
  2956. : index;
  2957. }
  2958. function normalizeNamed(pluralIndex, props) {
  2959. if (!props.count) {
  2960. props.count = pluralIndex;
  2961. }
  2962. if (!props.n) {
  2963. props.n = pluralIndex;
  2964. }
  2965. }
  2966. function createMessageContext(options = {}) {
  2967. const locale = options.locale;
  2968. const pluralIndex = getPluralIndex(options);
  2969. const pluralRule = isObject(options.pluralRules) &&
  2970. isString(locale) &&
  2971. isFunction(options.pluralRules[locale])
  2972. ? options.pluralRules[locale]
  2973. : pluralDefault;
  2974. const orgPluralRule = isObject(options.pluralRules) &&
  2975. isString(locale) &&
  2976. isFunction(options.pluralRules[locale])
  2977. ? pluralDefault
  2978. : undefined;
  2979. const plural = (messages) => {
  2980. return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
  2981. };
  2982. const _list = options.list || [];
  2983. const list = (index) => _list[index];
  2984. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2985. const _named = options.named || create();
  2986. isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
  2987. const named = (key) => _named[key];
  2988. function message(key, useLinked) {
  2989. // prettier-ignore
  2990. const msg = isFunction(options.messages)
  2991. ? options.messages(key, !!useLinked)
  2992. : isObject(options.messages)
  2993. ? options.messages[key]
  2994. : false;
  2995. return !msg
  2996. ? options.parent
  2997. ? options.parent.message(key) // resolve from parent messages
  2998. : DEFAULT_MESSAGE
  2999. : msg;
  3000. }
  3001. const _modifier = (name) => options.modifiers
  3002. ? options.modifiers[name]
  3003. : DEFAULT_MODIFIER;
  3004. const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
  3005. ? options.processor.normalize
  3006. : DEFAULT_NORMALIZE;
  3007. const interpolate = isPlainObject(options.processor) &&
  3008. isFunction(options.processor.interpolate)
  3009. ? options.processor.interpolate
  3010. : DEFAULT_INTERPOLATE;
  3011. const type = isPlainObject(options.processor) && isString(options.processor.type)
  3012. ? options.processor.type
  3013. : DEFAULT_MESSAGE_DATA_TYPE;
  3014. const linked = (key, ...args) => {
  3015. const [arg1, arg2] = args;
  3016. let type = 'text';
  3017. let modifier = '';
  3018. if (args.length === 1) {
  3019. if (isObject(arg1)) {
  3020. modifier = arg1.modifier || modifier;
  3021. type = arg1.type || type;
  3022. }
  3023. else if (isString(arg1)) {
  3024. modifier = arg1 || modifier;
  3025. }
  3026. }
  3027. else if (args.length === 2) {
  3028. if (isString(arg1)) {
  3029. modifier = arg1 || modifier;
  3030. }
  3031. if (isString(arg2)) {
  3032. type = arg2 || type;
  3033. }
  3034. }
  3035. const ret = message(key, true)(ctx);
  3036. const msg =
  3037. // The message in vnode resolved with linked are returned as an array by processor.nomalize
  3038. type === 'vnode' && isArray(ret) && modifier
  3039. ? ret[0]
  3040. : ret;
  3041. return modifier ? _modifier(modifier)(msg, type) : msg;
  3042. };
  3043. const ctx = {
  3044. ["list" /* HelperNameMap.LIST */]: list,
  3045. ["named" /* HelperNameMap.NAMED */]: named,
  3046. ["plural" /* HelperNameMap.PLURAL */]: plural,
  3047. ["linked" /* HelperNameMap.LINKED */]: linked,
  3048. ["message" /* HelperNameMap.MESSAGE */]: message,
  3049. ["type" /* HelperNameMap.TYPE */]: type,
  3050. ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
  3051. ["normalize" /* HelperNameMap.NORMALIZE */]: normalize,
  3052. ["values" /* HelperNameMap.VALUES */]: assign(create(), _list, _named)
  3053. };
  3054. return ctx;
  3055. }
  3056. const NOOP_MESSAGE_FUNCTION = () => '';
  3057. const isMessageFunction = (val) => isFunction(val);
  3058. // implementation of `translate` function
  3059. function translate(context, ...args) {
  3060. const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
  3061. const [key, options] = parseTranslateArgs(...args);
  3062. const missingWarn = isBoolean(options.missingWarn)
  3063. ? options.missingWarn
  3064. : context.missingWarn;
  3065. const fallbackWarn = isBoolean(options.fallbackWarn)
  3066. ? options.fallbackWarn
  3067. : context.fallbackWarn;
  3068. const escapeParameter = isBoolean(options.escapeParameter)
  3069. ? options.escapeParameter
  3070. : context.escapeParameter;
  3071. const resolvedMessage = !!options.resolvedMessage;
  3072. // prettier-ignore
  3073. const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
  3074. ? !isBoolean(options.default)
  3075. ? options.default
  3076. : (!messageCompiler ? () => key : key)
  3077. : fallbackFormat // default by `fallbackFormat` option
  3078. ? (!messageCompiler ? () => key : key)
  3079. : null;
  3080. const enableDefaultMsg = fallbackFormat ||
  3081. (defaultMsgOrKey != null &&
  3082. (isString(defaultMsgOrKey) || isFunction(defaultMsgOrKey)));
  3083. const locale = getLocale(context, options);
  3084. // escape params
  3085. escapeParameter && escapeParams(options);
  3086. // resolve message format
  3087. // eslint-disable-next-line prefer-const
  3088. let [formatScope, targetLocale, message] = !resolvedMessage
  3089. ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
  3090. : [
  3091. key,
  3092. locale,
  3093. messages[locale] || create()
  3094. ];
  3095. // NOTE:
  3096. // Fix to work around `ssrTransfrom` bug in Vite.
  3097. // https://github.com/vitejs/vite/issues/4306
  3098. // To get around this, use temporary variables.
  3099. // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
  3100. let format = formatScope;
  3101. // if you use default message, set it as message format!
  3102. let cacheBaseKey = key;
  3103. if (!resolvedMessage &&
  3104. !(isString(format) ||
  3105. isMessageAST(format) ||
  3106. isMessageFunction(format))) {
  3107. if (enableDefaultMsg) {
  3108. format = defaultMsgOrKey;
  3109. cacheBaseKey = format;
  3110. }
  3111. }
  3112. // checking message format and target locale
  3113. if (!resolvedMessage &&
  3114. (!(isString(format) ||
  3115. isMessageAST(format) ||
  3116. isMessageFunction(format)) ||
  3117. !isString(targetLocale))) {
  3118. return unresolving ? NOT_REOSLVED : key;
  3119. }
  3120. // TODO: refactor
  3121. if (isString(format) && context.messageCompiler == null) {
  3122. warn(`The message format compilation is not supported in this build. ` +
  3123. `Because message compiler isn't included. ` +
  3124. `You need to pre-compilation all message format. ` +
  3125. `So translate function return '${key}'.`);
  3126. return key;
  3127. }
  3128. // setup compile error detecting
  3129. let occurred = false;
  3130. const onError = () => {
  3131. occurred = true;
  3132. };
  3133. // compile message format
  3134. const msg = !isMessageFunction(format)
  3135. ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
  3136. : format;
  3137. // if occurred compile error, return the message format
  3138. if (occurred) {
  3139. return format;
  3140. }
  3141. // evaluate message with context
  3142. const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
  3143. const msgContext = createMessageContext(ctxOptions);
  3144. const messaged = evaluateMessage(context, msg, msgContext);
  3145. // if use post translation option, proceed it with handler
  3146. const ret = postTranslation
  3147. ? postTranslation(messaged, key)
  3148. : messaged;
  3149. // NOTE: experimental !!
  3150. {
  3151. // prettier-ignore
  3152. const payloads = {
  3153. timestamp: Date.now(),
  3154. key: isString(key)
  3155. ? key
  3156. : isMessageFunction(format)
  3157. ? format.key
  3158. : '',
  3159. locale: targetLocale || (isMessageFunction(format)
  3160. ? format.locale
  3161. : ''),
  3162. format: isString(format)
  3163. ? format
  3164. : isMessageFunction(format)
  3165. ? format.source
  3166. : '',
  3167. message: ret
  3168. };
  3169. payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
  3170. translateDevTools(payloads);
  3171. }
  3172. return ret;
  3173. }
  3174. function escapeParams(options) {
  3175. if (isArray(options.list)) {
  3176. options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
  3177. }
  3178. else if (isObject(options.named)) {
  3179. Object.keys(options.named).forEach(key => {
  3180. if (isString(options.named[key])) {
  3181. options.named[key] = escapeHtml(options.named[key]);
  3182. }
  3183. });
  3184. }
  3185. }
  3186. function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
  3187. const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
  3188. const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
  3189. let message = create();
  3190. let targetLocale;
  3191. let format = null;
  3192. let from = locale;
  3193. let to = null;
  3194. const type = 'translate';
  3195. for (let i = 0; i < locales.length; i++) {
  3196. targetLocale = to = locales[i];
  3197. if (locale !== targetLocale &&
  3198. !isAlmostSameLocale(locale, targetLocale) &&
  3199. isTranslateFallbackWarn(fallbackWarn, key)) {
  3200. onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
  3201. key,
  3202. target: targetLocale
  3203. }));
  3204. }
  3205. // for vue-devtools timeline event
  3206. if (locale !== targetLocale) {
  3207. const emitter = context.__v_emitter;
  3208. if (emitter) {
  3209. emitter.emit('fallback', {
  3210. type,
  3211. key,
  3212. from,
  3213. to,
  3214. groupId: `${type}:${key}`
  3215. });
  3216. }
  3217. }
  3218. message =
  3219. messages[targetLocale] || create();
  3220. // for vue-devtools timeline event
  3221. let start = null;
  3222. let startTag;
  3223. let endTag;
  3224. if (inBrowser) {
  3225. start = window.performance.now();
  3226. startTag = 'intlify-message-resolve-start';
  3227. endTag = 'intlify-message-resolve-end';
  3228. mark && mark(startTag);
  3229. }
  3230. if ((format = resolveValue(message, key)) === null) {
  3231. // if null, resolve with object key path
  3232. format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
  3233. }
  3234. // for vue-devtools timeline event
  3235. if (inBrowser) {
  3236. const end = window.performance.now();
  3237. const emitter = context.__v_emitter;
  3238. if (emitter && start && format) {
  3239. emitter.emit('message-resolve', {
  3240. type: 'message-resolve',
  3241. key,
  3242. message: format,
  3243. time: end - start,
  3244. groupId: `${type}:${key}`
  3245. });
  3246. }
  3247. if (startTag && endTag && mark && measure) {
  3248. mark(endTag);
  3249. measure('intlify message resolve', startTag, endTag);
  3250. }
  3251. }
  3252. if (isString(format) || isMessageAST(format) || isMessageFunction(format)) {
  3253. break;
  3254. }
  3255. if (!isImplicitFallback(targetLocale, locales)) {
  3256. const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  3257. key, targetLocale, missingWarn, type);
  3258. if (missingRet !== key) {
  3259. format = missingRet;
  3260. }
  3261. }
  3262. from = to;
  3263. }
  3264. return [format, targetLocale, message];
  3265. }
  3266. function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
  3267. const { messageCompiler, warnHtmlMessage } = context;
  3268. if (isMessageFunction(format)) {
  3269. const msg = format;
  3270. msg.locale = msg.locale || targetLocale;
  3271. msg.key = msg.key || key;
  3272. return msg;
  3273. }
  3274. if (messageCompiler == null) {
  3275. const msg = (() => format);
  3276. msg.locale = targetLocale;
  3277. msg.key = key;
  3278. return msg;
  3279. }
  3280. // for vue-devtools timeline event
  3281. let start = null;
  3282. let startTag;
  3283. let endTag;
  3284. if (inBrowser) {
  3285. start = window.performance.now();
  3286. startTag = 'intlify-message-compilation-start';
  3287. endTag = 'intlify-message-compilation-end';
  3288. mark && mark(startTag);
  3289. }
  3290. const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
  3291. // for vue-devtools timeline event
  3292. if (inBrowser) {
  3293. const end = window.performance.now();
  3294. const emitter = context.__v_emitter;
  3295. if (emitter && start) {
  3296. emitter.emit('message-compilation', {
  3297. type: 'message-compilation',
  3298. message: format,
  3299. time: end - start,
  3300. groupId: `${'translate'}:${key}`
  3301. });
  3302. }
  3303. if (startTag && endTag && mark && measure) {
  3304. mark(endTag);
  3305. measure('intlify message compilation', startTag, endTag);
  3306. }
  3307. }
  3308. msg.locale = targetLocale;
  3309. msg.key = key;
  3310. msg.source = format;
  3311. return msg;
  3312. }
  3313. function evaluateMessage(context, msg, msgCtx) {
  3314. // for vue-devtools timeline event
  3315. let start = null;
  3316. let startTag;
  3317. let endTag;
  3318. if (inBrowser) {
  3319. start = window.performance.now();
  3320. startTag = 'intlify-message-evaluation-start';
  3321. endTag = 'intlify-message-evaluation-end';
  3322. mark && mark(startTag);
  3323. }
  3324. const messaged = msg(msgCtx);
  3325. // for vue-devtools timeline event
  3326. if (inBrowser) {
  3327. const end = window.performance.now();
  3328. const emitter = context.__v_emitter;
  3329. if (emitter && start) {
  3330. emitter.emit('message-evaluation', {
  3331. type: 'message-evaluation',
  3332. value: messaged,
  3333. time: end - start,
  3334. groupId: `${'translate'}:${msg.key}`
  3335. });
  3336. }
  3337. if (startTag && endTag && mark && measure) {
  3338. mark(endTag);
  3339. measure('intlify message evaluation', startTag, endTag);
  3340. }
  3341. }
  3342. return messaged;
  3343. }
  3344. /** @internal */
  3345. function parseTranslateArgs(...args) {
  3346. const [arg1, arg2, arg3] = args;
  3347. const options = create();
  3348. if (!isString(arg1) &&
  3349. !isNumber(arg1) &&
  3350. !isMessageFunction(arg1) &&
  3351. !isMessageAST(arg1)) {
  3352. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  3353. }
  3354. // prettier-ignore
  3355. const key = isNumber(arg1)
  3356. ? String(arg1)
  3357. : isMessageFunction(arg1)
  3358. ? arg1
  3359. : arg1;
  3360. if (isNumber(arg2)) {
  3361. options.plural = arg2;
  3362. }
  3363. else if (isString(arg2)) {
  3364. options.default = arg2;
  3365. }
  3366. else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
  3367. options.named = arg2;
  3368. }
  3369. else if (isArray(arg2)) {
  3370. options.list = arg2;
  3371. }
  3372. if (isNumber(arg3)) {
  3373. options.plural = arg3;
  3374. }
  3375. else if (isString(arg3)) {
  3376. options.default = arg3;
  3377. }
  3378. else if (isPlainObject(arg3)) {
  3379. assign(options, arg3);
  3380. }
  3381. return [key, options];
  3382. }
  3383. function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
  3384. return {
  3385. locale,
  3386. key,
  3387. warnHtmlMessage,
  3388. onError: (err) => {
  3389. onError && onError(err);
  3390. {
  3391. const _source = getSourceForCodeFrame(source);
  3392. const message = `Message compilation error: ${err.message}`;
  3393. const codeFrame = err.location &&
  3394. _source &&
  3395. generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
  3396. const emitter = context.__v_emitter;
  3397. if (emitter && _source) {
  3398. emitter.emit('compile-error', {
  3399. message: _source,
  3400. error: err.message,
  3401. start: err.location && err.location.start.offset,
  3402. end: err.location && err.location.end.offset,
  3403. groupId: `${'translate'}:${key}`
  3404. });
  3405. }
  3406. console.error(codeFrame ? `${message}\n${codeFrame}` : message);
  3407. }
  3408. },
  3409. onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
  3410. };
  3411. }
  3412. function getSourceForCodeFrame(source) {
  3413. if (isString(source)) {
  3414. return source;
  3415. }
  3416. else {
  3417. if (source.loc && source.loc.source) {
  3418. return source.loc.source;
  3419. }
  3420. }
  3421. }
  3422. function getMessageContextOptions(context, locale, message, options) {
  3423. const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
  3424. const resolveMessage = (key, useLinked) => {
  3425. let val = resolveValue(message, key);
  3426. // fallback
  3427. if (val == null && (fallbackContext || useLinked)) {
  3428. const [, , message] = resolveMessageFormat(fallbackContext || context, // NOTE: if has fallbackContext, fallback to root, else if use linked, fallback to local context
  3429. key, locale, fallbackLocale, fallbackWarn, missingWarn);
  3430. val = resolveValue(message, key);
  3431. }
  3432. if (isString(val) || isMessageAST(val)) {
  3433. let occurred = false;
  3434. const onError = () => {
  3435. occurred = true;
  3436. };
  3437. const msg = compileMessageFormat(context, key, locale, val, key, onError);
  3438. return !occurred
  3439. ? msg
  3440. : NOOP_MESSAGE_FUNCTION;
  3441. }
  3442. else if (isMessageFunction(val)) {
  3443. return val;
  3444. }
  3445. else {
  3446. // TODO: should be implemented warning message
  3447. return NOOP_MESSAGE_FUNCTION;
  3448. }
  3449. };
  3450. const ctxOptions = {
  3451. locale,
  3452. modifiers,
  3453. pluralRules,
  3454. messages: resolveMessage
  3455. };
  3456. if (context.processor) {
  3457. ctxOptions.processor = context.processor;
  3458. }
  3459. if (options.list) {
  3460. ctxOptions.list = options.list;
  3461. }
  3462. if (options.named) {
  3463. ctxOptions.named = options.named;
  3464. }
  3465. if (isNumber(options.plural)) {
  3466. ctxOptions.pluralIndex = options.plural;
  3467. }
  3468. return ctxOptions;
  3469. }
  3470. export { AST_NODE_PROPS_KEYS, CORE_ERROR_CODES_EXTEND_POINT, CORE_WARN_CODES_EXTEND_POINT, CompileErrorCodes, CoreErrorCodes, CoreWarnCodes, DATETIME_FORMAT_OPTIONS_KEYS, DEFAULT_LOCALE, DEFAULT_MESSAGE_DATA_TYPE, MISSING_RESOLVE_VALUE, NOT_REOSLVED, NUMBER_FORMAT_OPTIONS_KEYS, VERSION, clearCompileCache, clearDateTimeFormat, clearNumberFormat, compile, createCompileError, createCoreContext, createCoreError, createMessageContext, datetime, fallbackWithLocaleChain, fallbackWithSimple, getAdditionalMeta, getDevToolsHook, getFallbackContext, getLocale, getWarnMessage, handleMissing, initI18nDevTools, isAlmostSameLocale, isImplicitFallback, isMessageAST, isMessageFunction, isTranslateFallbackWarn, isTranslateMissingWarn, number, parse, parseDateTimeArgs, parseNumberArgs, parseTranslateArgs, registerLocaleFallbacker, registerMessageCompiler, registerMessageResolver, resolveLocale, resolveValue, resolveWithKeyValue, setAdditionalMeta, setDevToolsHook, setFallbackContext, translate, translateDevTools, updateFallbackLocale };