core-base.global.js 127 KB

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