core-base.esm-browser.js 123 KB

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