core-base.global.js 126 KB

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