vue-i18n.runtime.global.js 180 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960
  1. /*!
  2. * vue-i18n v9.8.0
  3. * (c) 2023 kazuya kawaguchi
  4. * Released under the MIT License.
  5. */
  6. var VueI18n = (function (exports, vue) {
  7. 'use strict';
  8. /**
  9. * Original Utilities
  10. * written by kazuya kawaguchi
  11. */
  12. const inBrowser = typeof window !== 'undefined';
  13. let mark;
  14. let measure;
  15. {
  16. const perf = inBrowser && window.performance;
  17. if (perf &&
  18. perf.mark &&
  19. perf.measure &&
  20. perf.clearMarks &&
  21. // @ts-ignore browser compat
  22. perf.clearMeasures) {
  23. mark = (tag) => {
  24. perf.mark(tag);
  25. };
  26. measure = (name, startTag, endTag) => {
  27. perf.measure(name, startTag, endTag);
  28. perf.clearMarks(startTag);
  29. perf.clearMarks(endTag);
  30. };
  31. }
  32. }
  33. const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
  34. /* eslint-disable */
  35. function format(message, ...args) {
  36. if (args.length === 1 && isObject(args[0])) {
  37. args = args[0];
  38. }
  39. if (!args || !args.hasOwnProperty) {
  40. args = {};
  41. }
  42. return message.replace(RE_ARGS, (match, identifier) => {
  43. return args.hasOwnProperty(identifier) ? args[identifier] : '';
  44. });
  45. }
  46. const makeSymbol = (name, shareable = false) => !shareable ? Symbol(name) : Symbol.for(name);
  47. const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
  48. const friendlyJSONstringify = (json) => JSON.stringify(json)
  49. .replace(/\u2028/g, '\\u2028')
  50. .replace(/\u2029/g, '\\u2029')
  51. .replace(/\u0027/g, '\\u0027');
  52. const isNumber = (val) => typeof val === 'number' && isFinite(val);
  53. const isDate = (val) => toTypeString(val) === '[object Date]';
  54. const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
  55. const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
  56. const assign = Object.assign;
  57. let _globalThis;
  58. const getGlobalThis = () => {
  59. // prettier-ignore
  60. return (_globalThis ||
  61. (_globalThis =
  62. typeof globalThis !== 'undefined'
  63. ? globalThis
  64. : typeof self !== 'undefined'
  65. ? self
  66. : typeof window !== 'undefined'
  67. ? window
  68. : typeof global !== 'undefined'
  69. ? global
  70. : {}));
  71. };
  72. function escapeHtml(rawText) {
  73. return rawText
  74. .replace(/</g, '&lt;')
  75. .replace(/>/g, '&gt;')
  76. .replace(/"/g, '&quot;')
  77. .replace(/'/g, '&apos;');
  78. }
  79. const hasOwnProperty = Object.prototype.hasOwnProperty;
  80. function hasOwn(obj, key) {
  81. return hasOwnProperty.call(obj, key);
  82. }
  83. /* eslint-enable */
  84. /**
  85. * Useful Utilities By Evan you
  86. * Modified by kazuya kawaguchi
  87. * MIT License
  88. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
  89. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
  90. */
  91. const isArray = Array.isArray;
  92. const isFunction = (val) => typeof val === 'function';
  93. const isString = (val) => typeof val === 'string';
  94. const isBoolean = (val) => typeof val === 'boolean';
  95. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  96. const isObject = (val) => val !== null && typeof val === 'object';
  97. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  98. const isPromise = (val) => {
  99. return isObject(val) && isFunction(val.then) && isFunction(val.catch);
  100. };
  101. const objectToString = Object.prototype.toString;
  102. const toTypeString = (value) => objectToString.call(value);
  103. const isPlainObject = (val) => {
  104. if (!isObject(val))
  105. return false;
  106. const proto = Object.getPrototypeOf(val);
  107. return proto === null || proto.constructor === Object;
  108. };
  109. // for converting list and named values to displayed strings.
  110. const toDisplayString = (val) => {
  111. return val == null
  112. ? ''
  113. : isArray(val) || (isPlainObject(val) && val.toString === objectToString)
  114. ? JSON.stringify(val, null, 2)
  115. : String(val);
  116. };
  117. function join(items, separator = '') {
  118. return items.reduce((str, item, index) => (index === 0 ? str + item : str + separator + item), '');
  119. }
  120. const RANGE = 2;
  121. function generateCodeFrame(source, start = 0, end = source.length) {
  122. const lines = source.split(/\r?\n/);
  123. let count = 0;
  124. const res = [];
  125. for (let i = 0; i < lines.length; i++) {
  126. count += lines[i].length + 1;
  127. if (count >= start) {
  128. for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
  129. if (j < 0 || j >= lines.length)
  130. continue;
  131. const line = j + 1;
  132. res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
  133. const lineLength = lines[j].length;
  134. if (j === i) {
  135. // push underline
  136. const pad = start - (count - lineLength) + 1;
  137. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  138. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  139. }
  140. else if (j > i) {
  141. if (end > count) {
  142. const length = Math.max(Math.min(end - count, lineLength), 1);
  143. res.push(` | ` + '^'.repeat(length));
  144. }
  145. count += lineLength + 1;
  146. }
  147. }
  148. break;
  149. }
  150. }
  151. return res.join('\n');
  152. }
  153. function incrementer(code) {
  154. let current = code;
  155. return () => ++current;
  156. }
  157. function warn(msg, err) {
  158. if (typeof console !== 'undefined') {
  159. console.warn(`[intlify] ` + msg);
  160. /* istanbul ignore if */
  161. if (err) {
  162. console.warn(err.stack);
  163. }
  164. }
  165. }
  166. /**
  167. * Event emitter, forked from the below:
  168. * - original repository url: https://github.com/developit/mitt
  169. * - code url: https://github.com/developit/mitt/blob/master/src/index.ts
  170. * - author: Jason Miller (https://github.com/developit)
  171. * - license: MIT
  172. */
  173. /**
  174. * Create a event emitter
  175. *
  176. * @returns An event emitter
  177. */
  178. function createEmitter() {
  179. const events = new Map();
  180. const emitter = {
  181. events,
  182. on(event, handler) {
  183. const handlers = events.get(event);
  184. const added = handlers && handlers.push(handler);
  185. if (!added) {
  186. events.set(event, [handler]);
  187. }
  188. },
  189. off(event, handler) {
  190. const handlers = events.get(event);
  191. if (handlers) {
  192. handlers.splice(handlers.indexOf(handler) >>> 0, 1);
  193. }
  194. },
  195. emit(event, payload) {
  196. (events.get(event) || [])
  197. .slice()
  198. .map(handler => handler(payload));
  199. (events.get('*') || [])
  200. .slice()
  201. .map(handler => handler(event, payload));
  202. }
  203. };
  204. return emitter;
  205. }
  206. const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val);
  207. // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
  208. function deepCopy(src, des) {
  209. // src and des should both be objects, and none of them can be a array
  210. if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {
  211. throw new Error('Invalid value');
  212. }
  213. for (const key in src) {
  214. if (hasOwn(src, key)) {
  215. if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) {
  216. // replace with src[key] when:
  217. // src[key] or des[key] is not an object, or
  218. // src[key] or des[key] is an array
  219. des[key] = src[key];
  220. }
  221. else {
  222. // src[key] and des[key] are both objects, merge them
  223. deepCopy(src[key], des[key]);
  224. }
  225. }
  226. }
  227. }
  228. const CompileErrorCodes = {
  229. // tokenizer error codes
  230. EXPECTED_TOKEN: 1,
  231. INVALID_TOKEN_IN_PLACEHOLDER: 2,
  232. UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
  233. UNKNOWN_ESCAPE_SEQUENCE: 4,
  234. INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
  235. UNBALANCED_CLOSING_BRACE: 6,
  236. UNTERMINATED_CLOSING_BRACE: 7,
  237. EMPTY_PLACEHOLDER: 8,
  238. NOT_ALLOW_NEST_PLACEHOLDER: 9,
  239. INVALID_LINKED_FORMAT: 10,
  240. // parser error codes
  241. MUST_HAVE_MESSAGES_IN_PLURAL: 11,
  242. UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
  243. UNEXPECTED_EMPTY_LINKED_KEY: 13,
  244. UNEXPECTED_LEXICAL_ANALYSIS: 14,
  245. // generator error codes
  246. UNHANDLED_CODEGEN_NODE_TYPE: 15,
  247. // minifier error codes
  248. UNHANDLED_MINIFIER_NODE_TYPE: 16,
  249. // Special value for higher-order compilers to pick up the last code
  250. // to avoid collision of error codes. This should always be kept as the last
  251. // item.
  252. __EXTEND_POINT__: 17
  253. };
  254. /** @internal */
  255. const errorMessages$2 = {
  256. // tokenizer error messages
  257. [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
  258. [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
  259. [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
  260. [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
  261. [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
  262. [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
  263. [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
  264. [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
  265. [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
  266. [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
  267. // parser error messages
  268. [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
  269. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
  270. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
  271. [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,
  272. // generator error messages
  273. [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,
  274. // minimizer error messages
  275. [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`
  276. };
  277. function createCompileError(code, loc, options = {}) {
  278. const { domain, messages, args } = options;
  279. const msg = format((messages || errorMessages$2)[code] || '', ...(args || []))
  280. ;
  281. const error = new SyntaxError(String(msg));
  282. error.code = code;
  283. if (loc) {
  284. error.location = loc;
  285. }
  286. error.domain = domain;
  287. return error;
  288. }
  289. const pathStateMachine = [];
  290. pathStateMachine[0 /* States.BEFORE_PATH */] = {
  291. ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
  292. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  293. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  294. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  295. };
  296. pathStateMachine[1 /* States.IN_PATH */] = {
  297. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
  298. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
  299. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  300. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  301. };
  302. pathStateMachine[2 /* States.BEFORE_IDENT */] = {
  303. ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
  304. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  305. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
  306. };
  307. pathStateMachine[3 /* States.IN_IDENT */] = {
  308. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  309. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  310. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
  311. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
  312. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
  313. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
  314. };
  315. pathStateMachine[4 /* States.IN_SUB_PATH */] = {
  316. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
  317. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
  318. ["[" /* PathCharTypes.LEFT_BRACKET */]: [
  319. 4 /* States.IN_SUB_PATH */,
  320. 2 /* Actions.INC_SUB_PATH_DEPTH */
  321. ],
  322. ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
  323. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  324. ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
  325. };
  326. pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
  327. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  328. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  329. ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
  330. };
  331. pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
  332. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  333. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  334. ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
  335. };
  336. /**
  337. * Check if an expression is a literal value.
  338. */
  339. const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
  340. function isLiteral(exp) {
  341. return literalValueRE.test(exp);
  342. }
  343. /**
  344. * Strip quotes from a string
  345. */
  346. function stripQuotes(str) {
  347. const a = str.charCodeAt(0);
  348. const b = str.charCodeAt(str.length - 1);
  349. return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
  350. }
  351. /**
  352. * Determine the type of a character in a keypath.
  353. */
  354. function getPathCharType(ch) {
  355. if (ch === undefined || ch === null) {
  356. return "o" /* PathCharTypes.END_OF_FAIL */;
  357. }
  358. const code = ch.charCodeAt(0);
  359. switch (code) {
  360. case 0x5b: // [
  361. case 0x5d: // ]
  362. case 0x2e: // .
  363. case 0x22: // "
  364. case 0x27: // '
  365. return ch;
  366. case 0x5f: // _
  367. case 0x24: // $
  368. case 0x2d: // -
  369. return "i" /* PathCharTypes.IDENT */;
  370. case 0x09: // Tab (HT)
  371. case 0x0a: // Newline (LF)
  372. case 0x0d: // Return (CR)
  373. case 0xa0: // No-break space (NBSP)
  374. case 0xfeff: // Byte Order Mark (BOM)
  375. case 0x2028: // Line Separator (LS)
  376. case 0x2029: // Paragraph Separator (PS)
  377. return "w" /* PathCharTypes.WORKSPACE */;
  378. }
  379. return "i" /* PathCharTypes.IDENT */;
  380. }
  381. /**
  382. * Format a subPath, return its plain form if it is
  383. * a literal string or number. Otherwise prepend the
  384. * dynamic indicator (*).
  385. */
  386. function formatSubPath(path) {
  387. const trimmed = path.trim();
  388. // invalid leading 0
  389. if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
  390. return false;
  391. }
  392. return isLiteral(trimmed)
  393. ? stripQuotes(trimmed)
  394. : "*" /* PathCharTypes.ASTARISK */ + trimmed;
  395. }
  396. /**
  397. * Parse a string path into an array of segments
  398. */
  399. function parse(path) {
  400. const keys = [];
  401. let index = -1;
  402. let mode = 0 /* States.BEFORE_PATH */;
  403. let subPathDepth = 0;
  404. let c;
  405. let key; // eslint-disable-line
  406. let newChar;
  407. let type;
  408. let transition;
  409. let action;
  410. let typeMap;
  411. const actions = [];
  412. actions[0 /* Actions.APPEND */] = () => {
  413. if (key === undefined) {
  414. key = newChar;
  415. }
  416. else {
  417. key += newChar;
  418. }
  419. };
  420. actions[1 /* Actions.PUSH */] = () => {
  421. if (key !== undefined) {
  422. keys.push(key);
  423. key = undefined;
  424. }
  425. };
  426. actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
  427. actions[0 /* Actions.APPEND */]();
  428. subPathDepth++;
  429. };
  430. actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
  431. if (subPathDepth > 0) {
  432. subPathDepth--;
  433. mode = 4 /* States.IN_SUB_PATH */;
  434. actions[0 /* Actions.APPEND */]();
  435. }
  436. else {
  437. subPathDepth = 0;
  438. if (key === undefined) {
  439. return false;
  440. }
  441. key = formatSubPath(key);
  442. if (key === false) {
  443. return false;
  444. }
  445. else {
  446. actions[1 /* Actions.PUSH */]();
  447. }
  448. }
  449. };
  450. function maybeUnescapeQuote() {
  451. const nextChar = path[index + 1];
  452. if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
  453. nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
  454. (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
  455. nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
  456. index++;
  457. newChar = '\\' + nextChar;
  458. actions[0 /* Actions.APPEND */]();
  459. return true;
  460. }
  461. }
  462. while (mode !== null) {
  463. index++;
  464. c = path[index];
  465. if (c === '\\' && maybeUnescapeQuote()) {
  466. continue;
  467. }
  468. type = getPathCharType(c);
  469. typeMap = pathStateMachine[mode];
  470. transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
  471. // check parse error
  472. if (transition === 8 /* States.ERROR */) {
  473. return;
  474. }
  475. mode = transition[0];
  476. if (transition[1] !== undefined) {
  477. action = actions[transition[1]];
  478. if (action) {
  479. newChar = c;
  480. if (action() === false) {
  481. return;
  482. }
  483. }
  484. }
  485. // check parse finish
  486. if (mode === 7 /* States.AFTER_PATH */) {
  487. return keys;
  488. }
  489. }
  490. }
  491. // path token cache
  492. const cache = new Map();
  493. /**
  494. * key-value message resolver
  495. *
  496. * @remarks
  497. * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
  498. *
  499. * @param obj - A target object to be resolved with path
  500. * @param path - A {@link Path | path} to resolve the value of message
  501. *
  502. * @returns A resolved {@link PathValue | path value}
  503. *
  504. * @VueI18nGeneral
  505. */
  506. function resolveWithKeyValue(obj, path) {
  507. return isObject(obj) ? obj[path] : null;
  508. }
  509. /**
  510. * message resolver
  511. *
  512. * @remarks
  513. * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
  514. *
  515. * @param obj - A target object to be resolved with path
  516. * @param path - A {@link Path | path} to resolve the value of message
  517. *
  518. * @returns A resolved {@link PathValue | path value}
  519. *
  520. * @VueI18nGeneral
  521. */
  522. function resolveValue(obj, path) {
  523. // check object
  524. if (!isObject(obj)) {
  525. return null;
  526. }
  527. // parse path
  528. let hit = cache.get(path);
  529. if (!hit) {
  530. hit = parse(path);
  531. if (hit) {
  532. cache.set(path, hit);
  533. }
  534. }
  535. // check hit
  536. if (!hit) {
  537. return null;
  538. }
  539. // resolve path value
  540. const len = hit.length;
  541. let last = obj;
  542. let i = 0;
  543. while (i < len) {
  544. const val = last[hit[i]];
  545. if (val === undefined) {
  546. return null;
  547. }
  548. if (isFunction(last)) {
  549. return null;
  550. }
  551. last = val;
  552. i++;
  553. }
  554. return last;
  555. }
  556. const DEFAULT_MODIFIER = (str) => str;
  557. const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
  558. const DEFAULT_MESSAGE_DATA_TYPE = 'text';
  559. const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);
  560. const DEFAULT_INTERPOLATE = toDisplayString;
  561. function pluralDefault(choice, choicesLength) {
  562. choice = Math.abs(choice);
  563. if (choicesLength === 2) {
  564. // prettier-ignore
  565. return choice
  566. ? choice > 1
  567. ? 1
  568. : 0
  569. : 1;
  570. }
  571. return choice ? Math.min(choice, 2) : 0;
  572. }
  573. function getPluralIndex(options) {
  574. // prettier-ignore
  575. const index = isNumber(options.pluralIndex)
  576. ? options.pluralIndex
  577. : -1;
  578. // prettier-ignore
  579. return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
  580. ? isNumber(options.named.count)
  581. ? options.named.count
  582. : isNumber(options.named.n)
  583. ? options.named.n
  584. : index
  585. : index;
  586. }
  587. function normalizeNamed(pluralIndex, props) {
  588. if (!props.count) {
  589. props.count = pluralIndex;
  590. }
  591. if (!props.n) {
  592. props.n = pluralIndex;
  593. }
  594. }
  595. function createMessageContext(options = {}) {
  596. const locale = options.locale;
  597. const pluralIndex = getPluralIndex(options);
  598. const pluralRule = isObject(options.pluralRules) &&
  599. isString(locale) &&
  600. isFunction(options.pluralRules[locale])
  601. ? options.pluralRules[locale]
  602. : pluralDefault;
  603. const orgPluralRule = isObject(options.pluralRules) &&
  604. isString(locale) &&
  605. isFunction(options.pluralRules[locale])
  606. ? pluralDefault
  607. : undefined;
  608. const plural = (messages) => {
  609. return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
  610. };
  611. const _list = options.list || [];
  612. const list = (index) => _list[index];
  613. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  614. const _named = options.named || {};
  615. isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
  616. const named = (key) => _named[key];
  617. function message(key) {
  618. // prettier-ignore
  619. const msg = isFunction(options.messages)
  620. ? options.messages(key)
  621. : isObject(options.messages)
  622. ? options.messages[key]
  623. : false;
  624. return !msg
  625. ? options.parent
  626. ? options.parent.message(key) // resolve from parent messages
  627. : DEFAULT_MESSAGE
  628. : msg;
  629. }
  630. const _modifier = (name) => options.modifiers
  631. ? options.modifiers[name]
  632. : DEFAULT_MODIFIER;
  633. const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
  634. ? options.processor.normalize
  635. : DEFAULT_NORMALIZE;
  636. const interpolate = isPlainObject(options.processor) &&
  637. isFunction(options.processor.interpolate)
  638. ? options.processor.interpolate
  639. : DEFAULT_INTERPOLATE;
  640. const type = isPlainObject(options.processor) && isString(options.processor.type)
  641. ? options.processor.type
  642. : DEFAULT_MESSAGE_DATA_TYPE;
  643. const linked = (key, ...args) => {
  644. const [arg1, arg2] = args;
  645. let type = 'text';
  646. let modifier = '';
  647. if (args.length === 1) {
  648. if (isObject(arg1)) {
  649. modifier = arg1.modifier || modifier;
  650. type = arg1.type || type;
  651. }
  652. else if (isString(arg1)) {
  653. modifier = arg1 || modifier;
  654. }
  655. }
  656. else if (args.length === 2) {
  657. if (isString(arg1)) {
  658. modifier = arg1 || modifier;
  659. }
  660. if (isString(arg2)) {
  661. type = arg2 || type;
  662. }
  663. }
  664. const ret = message(key)(ctx);
  665. const msg =
  666. // The message in vnode resolved with linked are returned as an array by processor.nomalize
  667. type === 'vnode' && isArray(ret) && modifier
  668. ? ret[0]
  669. : ret;
  670. return modifier ? _modifier(modifier)(msg, type) : msg;
  671. };
  672. const ctx = {
  673. ["list" /* HelperNameMap.LIST */]: list,
  674. ["named" /* HelperNameMap.NAMED */]: named,
  675. ["plural" /* HelperNameMap.PLURAL */]: plural,
  676. ["linked" /* HelperNameMap.LINKED */]: linked,
  677. ["message" /* HelperNameMap.MESSAGE */]: message,
  678. ["type" /* HelperNameMap.TYPE */]: type,
  679. ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
  680. ["normalize" /* HelperNameMap.NORMALIZE */]: normalize,
  681. ["values" /* HelperNameMap.VALUES */]: assign({}, _list, _named)
  682. };
  683. return ctx;
  684. }
  685. let devtools = null;
  686. function setDevToolsHook(hook) {
  687. devtools = hook;
  688. }
  689. function initI18nDevTools(i18n, version, meta) {
  690. // TODO: queue if devtools is undefined
  691. devtools &&
  692. devtools.emit("i18n:init" /* IntlifyDevToolsHooks.I18nInit */, {
  693. timestamp: Date.now(),
  694. i18n,
  695. version,
  696. meta
  697. });
  698. }
  699. const translateDevTools = /* #__PURE__*/ createDevToolsHook("function:translate" /* IntlifyDevToolsHooks.FunctionTranslate */);
  700. function createDevToolsHook(hook) {
  701. return (payloads) => devtools && devtools.emit(hook, payloads);
  702. }
  703. const CoreWarnCodes = {
  704. NOT_FOUND_KEY: 1,
  705. FALLBACK_TO_TRANSLATE: 2,
  706. CANNOT_FORMAT_NUMBER: 3,
  707. FALLBACK_TO_NUMBER_FORMAT: 4,
  708. CANNOT_FORMAT_DATE: 5,
  709. FALLBACK_TO_DATE_FORMAT: 6,
  710. EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: 7,
  711. __EXTEND_POINT__: 8
  712. };
  713. /** @internal */
  714. const warnMessages$1 = {
  715. [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
  716. [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
  717. [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
  718. [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
  719. [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
  720. [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
  721. [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.`
  722. };
  723. function getWarnMessage$1(code, ...args) {
  724. return format(warnMessages$1[code], ...args);
  725. }
  726. const code$2 = CompileErrorCodes.__EXTEND_POINT__;
  727. const inc$2 = incrementer(code$2);
  728. const CoreErrorCodes = {
  729. INVALID_ARGUMENT: code$2,
  730. INVALID_DATE_ARGUMENT: inc$2(),
  731. INVALID_ISO_DATE_ARGUMENT: inc$2(),
  732. NOT_SUPPORT_NON_STRING_MESSAGE: inc$2(),
  733. NOT_SUPPORT_LOCALE_PROMISE_VALUE: inc$2(),
  734. NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: inc$2(),
  735. NOT_SUPPORT_LOCALE_TYPE: inc$2(),
  736. __EXTEND_POINT__: inc$2() // 25
  737. };
  738. function createCoreError(code) {
  739. return createCompileError(code, null, { messages: errorMessages$1 } );
  740. }
  741. /** @internal */
  742. const errorMessages$1 = {
  743. [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
  744. [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
  745. 'Make sure your Date represents a valid date.',
  746. [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string',
  747. [CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE]: 'Not support non-string message',
  748. [CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE]: 'cannot support promise value',
  749. [CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]: 'cannot support async function',
  750. [CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE]: 'cannot support locale type'
  751. };
  752. /** @internal */
  753. function getLocale(context, options) {
  754. return options.locale != null
  755. ? resolveLocale(options.locale)
  756. : resolveLocale(context.locale);
  757. }
  758. let _resolveLocale;
  759. /** @internal */
  760. function resolveLocale(locale) {
  761. if (isString(locale)) {
  762. return locale;
  763. }
  764. else {
  765. if (isFunction(locale)) {
  766. if (locale.resolvedOnce && _resolveLocale != null) {
  767. return _resolveLocale;
  768. }
  769. else if (locale.constructor.name === 'Function') {
  770. const resolve = locale();
  771. if (isPromise(resolve)) {
  772. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);
  773. }
  774. return (_resolveLocale = resolve);
  775. }
  776. else {
  777. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);
  778. }
  779. }
  780. else {
  781. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);
  782. }
  783. }
  784. }
  785. /**
  786. * Fallback with simple implemenation
  787. *
  788. * @remarks
  789. * A fallback locale function implemented with a simple fallback algorithm.
  790. *
  791. * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
  792. *
  793. * @param ctx - A {@link CoreContext | context}
  794. * @param fallback - A {@link FallbackLocale | fallback locale}
  795. * @param start - A starting {@link Locale | locale}
  796. *
  797. * @returns Fallback locales
  798. *
  799. * @VueI18nGeneral
  800. */
  801. function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
  802. ) {
  803. // prettier-ignore
  804. return [...new Set([
  805. start,
  806. ...(isArray(fallback)
  807. ? fallback
  808. : isObject(fallback)
  809. ? Object.keys(fallback)
  810. : isString(fallback)
  811. ? [fallback]
  812. : [start])
  813. ])];
  814. }
  815. /**
  816. * Fallback with locale chain
  817. *
  818. * @remarks
  819. * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
  820. *
  821. * @param ctx - A {@link CoreContext | context}
  822. * @param fallback - A {@link FallbackLocale | fallback locale}
  823. * @param start - A starting {@link Locale | locale}
  824. *
  825. * @returns Fallback locales
  826. *
  827. * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
  828. *
  829. * @VueI18nGeneral
  830. */
  831. function fallbackWithLocaleChain(ctx, fallback, start) {
  832. const startLocale = isString(start) ? start : DEFAULT_LOCALE;
  833. const context = ctx;
  834. if (!context.__localeChainCache) {
  835. context.__localeChainCache = new Map();
  836. }
  837. let chain = context.__localeChainCache.get(startLocale);
  838. if (!chain) {
  839. chain = [];
  840. // first block defined by start
  841. let block = [start];
  842. // while any intervening block found
  843. while (isArray(block)) {
  844. block = appendBlockToChain(chain, block, fallback);
  845. }
  846. // prettier-ignore
  847. // last block defined by default
  848. const defaults = isArray(fallback) || !isPlainObject(fallback)
  849. ? fallback
  850. : fallback['default']
  851. ? fallback['default']
  852. : null;
  853. // convert defaults to array
  854. block = isString(defaults) ? [defaults] : defaults;
  855. if (isArray(block)) {
  856. appendBlockToChain(chain, block, false);
  857. }
  858. context.__localeChainCache.set(startLocale, chain);
  859. }
  860. return chain;
  861. }
  862. function appendBlockToChain(chain, block, blocks) {
  863. let follow = true;
  864. for (let i = 0; i < block.length && isBoolean(follow); i++) {
  865. const locale = block[i];
  866. if (isString(locale)) {
  867. follow = appendLocaleToChain(chain, block[i], blocks);
  868. }
  869. }
  870. return follow;
  871. }
  872. function appendLocaleToChain(chain, locale, blocks) {
  873. let follow;
  874. const tokens = locale.split('-');
  875. do {
  876. const target = tokens.join('-');
  877. follow = appendItemToChain(chain, target, blocks);
  878. tokens.splice(-1, 1);
  879. } while (tokens.length && follow === true);
  880. return follow;
  881. }
  882. function appendItemToChain(chain, target, blocks) {
  883. let follow = false;
  884. if (!chain.includes(target)) {
  885. follow = true;
  886. if (target) {
  887. follow = target[target.length - 1] !== '!';
  888. const locale = target.replace(/!/g, '');
  889. chain.push(locale);
  890. if ((isArray(blocks) || isPlainObject(blocks)) &&
  891. blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
  892. ) {
  893. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  894. follow = blocks[locale];
  895. }
  896. }
  897. }
  898. return follow;
  899. }
  900. /* eslint-disable @typescript-eslint/no-explicit-any */
  901. /**
  902. * Intlify core-base version
  903. * @internal
  904. */
  905. const VERSION$1 = '9.8.0';
  906. const NOT_REOSLVED = -1;
  907. const DEFAULT_LOCALE = 'en-US';
  908. const MISSING_RESOLVE_VALUE = '';
  909. const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
  910. function getDefaultLinkedModifiers() {
  911. return {
  912. upper: (val, type) => {
  913. // prettier-ignore
  914. return type === 'text' && isString(val)
  915. ? val.toUpperCase()
  916. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  917. ? val.children.toUpperCase()
  918. : val;
  919. },
  920. lower: (val, type) => {
  921. // prettier-ignore
  922. return type === 'text' && isString(val)
  923. ? val.toLowerCase()
  924. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  925. ? val.children.toLowerCase()
  926. : val;
  927. },
  928. capitalize: (val, type) => {
  929. // prettier-ignore
  930. return (type === 'text' && isString(val)
  931. ? capitalize(val)
  932. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  933. ? capitalize(val.children)
  934. : val);
  935. }
  936. };
  937. }
  938. let _compiler;
  939. let _resolver;
  940. /**
  941. * Register the message resolver
  942. *
  943. * @param resolver - A {@link MessageResolver} function
  944. *
  945. * @VueI18nGeneral
  946. */
  947. function registerMessageResolver(resolver) {
  948. _resolver = resolver;
  949. }
  950. let _fallbacker;
  951. /**
  952. * Register the locale fallbacker
  953. *
  954. * @param fallbacker - A {@link LocaleFallbacker} function
  955. *
  956. * @VueI18nGeneral
  957. */
  958. function registerLocaleFallbacker(fallbacker) {
  959. _fallbacker = fallbacker;
  960. }
  961. // Additional Meta for Intlify DevTools
  962. let _additionalMeta = null;
  963. /* #__NO_SIDE_EFFECTS__ */
  964. const setAdditionalMeta = (meta) => {
  965. _additionalMeta = meta;
  966. };
  967. /* #__NO_SIDE_EFFECTS__ */
  968. const getAdditionalMeta = () => _additionalMeta;
  969. let _fallbackContext = null;
  970. const setFallbackContext = (context) => {
  971. _fallbackContext = context;
  972. };
  973. const getFallbackContext = () => _fallbackContext;
  974. // ID for CoreContext
  975. let _cid = 0;
  976. function createCoreContext(options = {}) {
  977. // setup options
  978. const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
  979. const version = isString(options.version) ? options.version : VERSION$1;
  980. const locale = isString(options.locale) || isFunction(options.locale)
  981. ? options.locale
  982. : DEFAULT_LOCALE;
  983. const _locale = isFunction(locale) ? DEFAULT_LOCALE : locale;
  984. const fallbackLocale = isArray(options.fallbackLocale) ||
  985. isPlainObject(options.fallbackLocale) ||
  986. isString(options.fallbackLocale) ||
  987. options.fallbackLocale === false
  988. ? options.fallbackLocale
  989. : _locale;
  990. const messages = isPlainObject(options.messages)
  991. ? options.messages
  992. : { [_locale]: {} };
  993. const datetimeFormats = isPlainObject(options.datetimeFormats)
  994. ? options.datetimeFormats
  995. : { [_locale]: {} }
  996. ;
  997. const numberFormats = isPlainObject(options.numberFormats)
  998. ? options.numberFormats
  999. : { [_locale]: {} }
  1000. ;
  1001. const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
  1002. const pluralRules = options.pluralRules || {};
  1003. const missing = isFunction(options.missing) ? options.missing : null;
  1004. const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  1005. ? options.missingWarn
  1006. : true;
  1007. const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  1008. ? options.fallbackWarn
  1009. : true;
  1010. const fallbackFormat = !!options.fallbackFormat;
  1011. const unresolving = !!options.unresolving;
  1012. const postTranslation = isFunction(options.postTranslation)
  1013. ? options.postTranslation
  1014. : null;
  1015. const processor = isPlainObject(options.processor) ? options.processor : null;
  1016. const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
  1017. ? options.warnHtmlMessage
  1018. : true;
  1019. const escapeParameter = !!options.escapeParameter;
  1020. const messageCompiler = isFunction(options.messageCompiler)
  1021. ? options.messageCompiler
  1022. : _compiler;
  1023. const messageResolver = isFunction(options.messageResolver)
  1024. ? options.messageResolver
  1025. : _resolver || resolveWithKeyValue;
  1026. const localeFallbacker = isFunction(options.localeFallbacker)
  1027. ? options.localeFallbacker
  1028. : _fallbacker || fallbackWithSimple;
  1029. const fallbackContext = isObject(options.fallbackContext)
  1030. ? options.fallbackContext
  1031. : undefined;
  1032. // setup internal options
  1033. const internalOptions = options;
  1034. const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
  1035. ? internalOptions.__datetimeFormatters
  1036. : new Map()
  1037. ;
  1038. const __numberFormatters = isObject(internalOptions.__numberFormatters)
  1039. ? internalOptions.__numberFormatters
  1040. : new Map()
  1041. ;
  1042. const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
  1043. _cid++;
  1044. const context = {
  1045. version,
  1046. cid: _cid,
  1047. locale,
  1048. fallbackLocale,
  1049. messages,
  1050. modifiers,
  1051. pluralRules,
  1052. missing,
  1053. missingWarn,
  1054. fallbackWarn,
  1055. fallbackFormat,
  1056. unresolving,
  1057. postTranslation,
  1058. processor,
  1059. warnHtmlMessage,
  1060. escapeParameter,
  1061. messageCompiler,
  1062. messageResolver,
  1063. localeFallbacker,
  1064. fallbackContext,
  1065. onWarn,
  1066. __meta
  1067. };
  1068. {
  1069. context.datetimeFormats = datetimeFormats;
  1070. context.numberFormats = numberFormats;
  1071. context.__datetimeFormatters = __datetimeFormatters;
  1072. context.__numberFormatters = __numberFormatters;
  1073. }
  1074. // for vue-devtools timeline event
  1075. {
  1076. context.__v_emitter =
  1077. internalOptions.__v_emitter != null
  1078. ? internalOptions.__v_emitter
  1079. : undefined;
  1080. }
  1081. // NOTE: experimental !!
  1082. {
  1083. initI18nDevTools(context, version, __meta);
  1084. }
  1085. return context;
  1086. }
  1087. /** @internal */
  1088. function isTranslateFallbackWarn(fallback, key) {
  1089. return fallback instanceof RegExp ? fallback.test(key) : fallback;
  1090. }
  1091. /** @internal */
  1092. function isTranslateMissingWarn(missing, key) {
  1093. return missing instanceof RegExp ? missing.test(key) : missing;
  1094. }
  1095. /** @internal */
  1096. function handleMissing(context, key, locale, missingWarn, type) {
  1097. const { missing, onWarn } = context;
  1098. // for vue-devtools timeline event
  1099. {
  1100. const emitter = context.__v_emitter;
  1101. if (emitter) {
  1102. emitter.emit("missing" /* VueDevToolsTimelineEvents.MISSING */, {
  1103. locale,
  1104. key,
  1105. type,
  1106. groupId: `${type}:${key}`
  1107. });
  1108. }
  1109. }
  1110. if (missing !== null) {
  1111. const ret = missing(context, locale, key, type);
  1112. return isString(ret) ? ret : key;
  1113. }
  1114. else {
  1115. if (isTranslateMissingWarn(missingWarn, key)) {
  1116. onWarn(getWarnMessage$1(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
  1117. }
  1118. return key;
  1119. }
  1120. }
  1121. /** @internal */
  1122. function updateFallbackLocale(ctx, locale, fallback) {
  1123. const context = ctx;
  1124. context.__localeChainCache = new Map();
  1125. ctx.localeFallbacker(ctx, fallback, locale);
  1126. }
  1127. /* eslint-enable @typescript-eslint/no-explicit-any */
  1128. const isMessageAST = (val) => isObject(val) &&
  1129. (val.t === 0 || val.type === 0) &&
  1130. ('b' in val || 'body' in val);
  1131. const NOOP_MESSAGE_FUNCTION = () => '';
  1132. const isMessageFunction = (val) => isFunction(val);
  1133. // implementation of `translate` function
  1134. function translate(context, ...args) {
  1135. const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
  1136. const [key, options] = parseTranslateArgs(...args);
  1137. const missingWarn = isBoolean(options.missingWarn)
  1138. ? options.missingWarn
  1139. : context.missingWarn;
  1140. const fallbackWarn = isBoolean(options.fallbackWarn)
  1141. ? options.fallbackWarn
  1142. : context.fallbackWarn;
  1143. const escapeParameter = isBoolean(options.escapeParameter)
  1144. ? options.escapeParameter
  1145. : context.escapeParameter;
  1146. const resolvedMessage = !!options.resolvedMessage;
  1147. // prettier-ignore
  1148. const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
  1149. ? !isBoolean(options.default)
  1150. ? options.default
  1151. : (!messageCompiler ? () => key : key)
  1152. : fallbackFormat // default by `fallbackFormat` option
  1153. ? (!messageCompiler ? () => key : key)
  1154. : '';
  1155. const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
  1156. const locale = getLocale(context, options);
  1157. // escape params
  1158. escapeParameter && escapeParams(options);
  1159. // resolve message format
  1160. // eslint-disable-next-line prefer-const
  1161. let [formatScope, targetLocale, message] = !resolvedMessage
  1162. ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
  1163. : [
  1164. key,
  1165. locale,
  1166. messages[locale] || {}
  1167. ];
  1168. // NOTE:
  1169. // Fix to work around `ssrTransfrom` bug in Vite.
  1170. // https://github.com/vitejs/vite/issues/4306
  1171. // To get around this, use temporary variables.
  1172. // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
  1173. let format = formatScope;
  1174. // if you use default message, set it as message format!
  1175. let cacheBaseKey = key;
  1176. if (!resolvedMessage &&
  1177. !(isString(format) ||
  1178. isMessageAST(format) ||
  1179. isMessageFunction(format))) {
  1180. if (enableDefaultMsg) {
  1181. format = defaultMsgOrKey;
  1182. cacheBaseKey = format;
  1183. }
  1184. }
  1185. // checking message format and target locale
  1186. if (!resolvedMessage &&
  1187. (!(isString(format) ||
  1188. isMessageAST(format) ||
  1189. isMessageFunction(format)) ||
  1190. !isString(targetLocale))) {
  1191. return unresolving ? NOT_REOSLVED : key;
  1192. }
  1193. // TODO: refactor
  1194. if (isString(format) && context.messageCompiler == null) {
  1195. warn(`The message format compilation is not supported in this build. ` +
  1196. `Because message compiler isn't included. ` +
  1197. `You need to pre-compilation all message format. ` +
  1198. `So translate function return '${key}'.`);
  1199. return key;
  1200. }
  1201. // setup compile error detecting
  1202. let occurred = false;
  1203. const onError = () => {
  1204. occurred = true;
  1205. };
  1206. // compile message format
  1207. const msg = !isMessageFunction(format)
  1208. ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
  1209. : format;
  1210. // if occurred compile error, return the message format
  1211. if (occurred) {
  1212. return format;
  1213. }
  1214. // evaluate message with context
  1215. const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
  1216. const msgContext = createMessageContext(ctxOptions);
  1217. const messaged = evaluateMessage(context, msg, msgContext);
  1218. // if use post translation option, proceed it with handler
  1219. const ret = postTranslation
  1220. ? postTranslation(messaged, key)
  1221. : messaged;
  1222. // NOTE: experimental !!
  1223. {
  1224. // prettier-ignore
  1225. const payloads = {
  1226. timestamp: Date.now(),
  1227. key: isString(key)
  1228. ? key
  1229. : isMessageFunction(format)
  1230. ? format.key
  1231. : '',
  1232. locale: targetLocale || (isMessageFunction(format)
  1233. ? format.locale
  1234. : ''),
  1235. format: isString(format)
  1236. ? format
  1237. : isMessageFunction(format)
  1238. ? format.source
  1239. : '',
  1240. message: ret
  1241. };
  1242. payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
  1243. translateDevTools(payloads);
  1244. }
  1245. return ret;
  1246. }
  1247. function escapeParams(options) {
  1248. if (isArray(options.list)) {
  1249. options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
  1250. }
  1251. else if (isObject(options.named)) {
  1252. Object.keys(options.named).forEach(key => {
  1253. if (isString(options.named[key])) {
  1254. options.named[key] = escapeHtml(options.named[key]);
  1255. }
  1256. });
  1257. }
  1258. }
  1259. function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
  1260. const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
  1261. const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
  1262. let message = {};
  1263. let targetLocale;
  1264. let format = null;
  1265. let from = locale;
  1266. let to = null;
  1267. const type = 'translate';
  1268. for (let i = 0; i < locales.length; i++) {
  1269. targetLocale = to = locales[i];
  1270. if (locale !== targetLocale &&
  1271. isTranslateFallbackWarn(fallbackWarn, key)) {
  1272. onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
  1273. key,
  1274. target: targetLocale
  1275. }));
  1276. }
  1277. // for vue-devtools timeline event
  1278. if (locale !== targetLocale) {
  1279. const emitter = context.__v_emitter;
  1280. if (emitter) {
  1281. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  1282. type,
  1283. key,
  1284. from,
  1285. to,
  1286. groupId: `${type}:${key}`
  1287. });
  1288. }
  1289. }
  1290. message =
  1291. messages[targetLocale] || {};
  1292. // for vue-devtools timeline event
  1293. let start = null;
  1294. let startTag;
  1295. let endTag;
  1296. if (inBrowser) {
  1297. start = window.performance.now();
  1298. startTag = 'intlify-message-resolve-start';
  1299. endTag = 'intlify-message-resolve-end';
  1300. mark && mark(startTag);
  1301. }
  1302. if ((format = resolveValue(message, key)) === null) {
  1303. // if null, resolve with object key path
  1304. format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
  1305. }
  1306. // for vue-devtools timeline event
  1307. if (inBrowser) {
  1308. const end = window.performance.now();
  1309. const emitter = context.__v_emitter;
  1310. if (emitter && start && format) {
  1311. emitter.emit("message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */, {
  1312. type: "message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */,
  1313. key,
  1314. message: format,
  1315. time: end - start,
  1316. groupId: `${type}:${key}`
  1317. });
  1318. }
  1319. if (startTag && endTag && mark && measure) {
  1320. mark(endTag);
  1321. measure('intlify message resolve', startTag, endTag);
  1322. }
  1323. }
  1324. if (isString(format) || isMessageAST(format) || isMessageFunction(format)) {
  1325. break;
  1326. }
  1327. const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  1328. key, targetLocale, missingWarn, type);
  1329. if (missingRet !== key) {
  1330. format = missingRet;
  1331. }
  1332. from = to;
  1333. }
  1334. return [format, targetLocale, message];
  1335. }
  1336. function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
  1337. const { messageCompiler, warnHtmlMessage } = context;
  1338. if (isMessageFunction(format)) {
  1339. const msg = format;
  1340. msg.locale = msg.locale || targetLocale;
  1341. msg.key = msg.key || key;
  1342. return msg;
  1343. }
  1344. if (messageCompiler == null) {
  1345. const msg = (() => format);
  1346. msg.locale = targetLocale;
  1347. msg.key = key;
  1348. return msg;
  1349. }
  1350. // for vue-devtools timeline event
  1351. let start = null;
  1352. let startTag;
  1353. let endTag;
  1354. if (inBrowser) {
  1355. start = window.performance.now();
  1356. startTag = 'intlify-message-compilation-start';
  1357. endTag = 'intlify-message-compilation-end';
  1358. mark && mark(startTag);
  1359. }
  1360. const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
  1361. // for vue-devtools timeline event
  1362. if (inBrowser) {
  1363. const end = window.performance.now();
  1364. const emitter = context.__v_emitter;
  1365. if (emitter && start) {
  1366. emitter.emit("message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */, {
  1367. type: "message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */,
  1368. message: format,
  1369. time: end - start,
  1370. groupId: `${'translate'}:${key}`
  1371. });
  1372. }
  1373. if (startTag && endTag && mark && measure) {
  1374. mark(endTag);
  1375. measure('intlify message compilation', startTag, endTag);
  1376. }
  1377. }
  1378. msg.locale = targetLocale;
  1379. msg.key = key;
  1380. msg.source = format;
  1381. return msg;
  1382. }
  1383. function evaluateMessage(context, msg, msgCtx) {
  1384. // for vue-devtools timeline event
  1385. let start = null;
  1386. let startTag;
  1387. let endTag;
  1388. if (inBrowser) {
  1389. start = window.performance.now();
  1390. startTag = 'intlify-message-evaluation-start';
  1391. endTag = 'intlify-message-evaluation-end';
  1392. mark && mark(startTag);
  1393. }
  1394. const messaged = msg(msgCtx);
  1395. // for vue-devtools timeline event
  1396. if (inBrowser) {
  1397. const end = window.performance.now();
  1398. const emitter = context.__v_emitter;
  1399. if (emitter && start) {
  1400. emitter.emit("message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */, {
  1401. type: "message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */,
  1402. value: messaged,
  1403. time: end - start,
  1404. groupId: `${'translate'}:${msg.key}`
  1405. });
  1406. }
  1407. if (startTag && endTag && mark && measure) {
  1408. mark(endTag);
  1409. measure('intlify message evaluation', startTag, endTag);
  1410. }
  1411. }
  1412. return messaged;
  1413. }
  1414. /** @internal */
  1415. function parseTranslateArgs(...args) {
  1416. const [arg1, arg2, arg3] = args;
  1417. const options = {};
  1418. if (!isString(arg1) &&
  1419. !isNumber(arg1) &&
  1420. !isMessageFunction(arg1) &&
  1421. !isMessageAST(arg1)) {
  1422. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  1423. }
  1424. // prettier-ignore
  1425. const key = isNumber(arg1)
  1426. ? String(arg1)
  1427. : isMessageFunction(arg1)
  1428. ? arg1
  1429. : arg1;
  1430. if (isNumber(arg2)) {
  1431. options.plural = arg2;
  1432. }
  1433. else if (isString(arg2)) {
  1434. options.default = arg2;
  1435. }
  1436. else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
  1437. options.named = arg2;
  1438. }
  1439. else if (isArray(arg2)) {
  1440. options.list = arg2;
  1441. }
  1442. if (isNumber(arg3)) {
  1443. options.plural = arg3;
  1444. }
  1445. else if (isString(arg3)) {
  1446. options.default = arg3;
  1447. }
  1448. else if (isPlainObject(arg3)) {
  1449. assign(options, arg3);
  1450. }
  1451. return [key, options];
  1452. }
  1453. function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
  1454. return {
  1455. locale,
  1456. key,
  1457. warnHtmlMessage,
  1458. onError: (err) => {
  1459. onError && onError(err);
  1460. {
  1461. const _source = getSourceForCodeFrame(source);
  1462. const message = `Message compilation error: ${err.message}`;
  1463. const codeFrame = err.location &&
  1464. _source &&
  1465. generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
  1466. const emitter = context.__v_emitter;
  1467. if (emitter && _source) {
  1468. emitter.emit("compile-error" /* VueDevToolsTimelineEvents.COMPILE_ERROR */, {
  1469. message: _source,
  1470. error: err.message,
  1471. start: err.location && err.location.start.offset,
  1472. end: err.location && err.location.end.offset,
  1473. groupId: `${'translate'}:${key}`
  1474. });
  1475. }
  1476. console.error(codeFrame ? `${message}\n${codeFrame}` : message);
  1477. }
  1478. },
  1479. onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
  1480. };
  1481. }
  1482. function getSourceForCodeFrame(source) {
  1483. if (isString(source)) {
  1484. return source;
  1485. }
  1486. else {
  1487. if (source.loc && source.loc.source) {
  1488. return source.loc.source;
  1489. }
  1490. }
  1491. }
  1492. function getMessageContextOptions(context, locale, message, options) {
  1493. const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
  1494. const resolveMessage = (key) => {
  1495. let val = resolveValue(message, key);
  1496. // fallback to root context
  1497. if (val == null && fallbackContext) {
  1498. const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
  1499. val = resolveValue(message, key);
  1500. }
  1501. if (isString(val) || isMessageAST(val)) {
  1502. let occurred = false;
  1503. const onError = () => {
  1504. occurred = true;
  1505. };
  1506. const msg = compileMessageFormat(context, key, locale, val, key, onError);
  1507. return !occurred
  1508. ? msg
  1509. : NOOP_MESSAGE_FUNCTION;
  1510. }
  1511. else if (isMessageFunction(val)) {
  1512. return val;
  1513. }
  1514. else {
  1515. // TODO: should be implemented warning message
  1516. return NOOP_MESSAGE_FUNCTION;
  1517. }
  1518. };
  1519. const ctxOptions = {
  1520. locale,
  1521. modifiers,
  1522. pluralRules,
  1523. messages: resolveMessage
  1524. };
  1525. if (context.processor) {
  1526. ctxOptions.processor = context.processor;
  1527. }
  1528. if (options.list) {
  1529. ctxOptions.list = options.list;
  1530. }
  1531. if (options.named) {
  1532. ctxOptions.named = options.named;
  1533. }
  1534. if (isNumber(options.plural)) {
  1535. ctxOptions.pluralIndex = options.plural;
  1536. }
  1537. return ctxOptions;
  1538. }
  1539. const intlDefined = typeof Intl !== 'undefined';
  1540. const Availabilities = {
  1541. dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
  1542. numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
  1543. };
  1544. // implementation of `datetime` function
  1545. function datetime(context, ...args) {
  1546. const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  1547. const { __datetimeFormatters } = context;
  1548. if (!Availabilities.dateTimeFormat) {
  1549. onWarn(getWarnMessage$1(CoreWarnCodes.CANNOT_FORMAT_DATE));
  1550. return MISSING_RESOLVE_VALUE;
  1551. }
  1552. const [key, value, options, overrides] = parseDateTimeArgs(...args);
  1553. const missingWarn = isBoolean(options.missingWarn)
  1554. ? options.missingWarn
  1555. : context.missingWarn;
  1556. const fallbackWarn = isBoolean(options.fallbackWarn)
  1557. ? options.fallbackWarn
  1558. : context.fallbackWarn;
  1559. const part = !!options.part;
  1560. const locale = getLocale(context, options);
  1561. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  1562. fallbackLocale, locale);
  1563. if (!isString(key) || key === '') {
  1564. return new Intl.DateTimeFormat(locale, overrides).format(value);
  1565. }
  1566. // resolve format
  1567. let datetimeFormat = {};
  1568. let targetLocale;
  1569. let format = null;
  1570. let from = locale;
  1571. let to = null;
  1572. const type = 'datetime format';
  1573. for (let i = 0; i < locales.length; i++) {
  1574. targetLocale = to = locales[i];
  1575. if (locale !== targetLocale &&
  1576. isTranslateFallbackWarn(fallbackWarn, key)) {
  1577. onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
  1578. key,
  1579. target: targetLocale
  1580. }));
  1581. }
  1582. // for vue-devtools timeline event
  1583. if (locale !== targetLocale) {
  1584. const emitter = context.__v_emitter;
  1585. if (emitter) {
  1586. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  1587. type,
  1588. key,
  1589. from,
  1590. to,
  1591. groupId: `${type}:${key}`
  1592. });
  1593. }
  1594. }
  1595. datetimeFormat =
  1596. datetimeFormats[targetLocale] || {};
  1597. format = datetimeFormat[key];
  1598. if (isPlainObject(format))
  1599. break;
  1600. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  1601. from = to;
  1602. }
  1603. // checking format and target locale
  1604. if (!isPlainObject(format) || !isString(targetLocale)) {
  1605. return unresolving ? NOT_REOSLVED : key;
  1606. }
  1607. let id = `${targetLocale}__${key}`;
  1608. if (!isEmptyObject(overrides)) {
  1609. id = `${id}__${JSON.stringify(overrides)}`;
  1610. }
  1611. let formatter = __datetimeFormatters.get(id);
  1612. if (!formatter) {
  1613. formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
  1614. __datetimeFormatters.set(id, formatter);
  1615. }
  1616. return !part ? formatter.format(value) : formatter.formatToParts(value);
  1617. }
  1618. /** @internal */
  1619. const DATETIME_FORMAT_OPTIONS_KEYS = [
  1620. 'localeMatcher',
  1621. 'weekday',
  1622. 'era',
  1623. 'year',
  1624. 'month',
  1625. 'day',
  1626. 'hour',
  1627. 'minute',
  1628. 'second',
  1629. 'timeZoneName',
  1630. 'formatMatcher',
  1631. 'hour12',
  1632. 'timeZone',
  1633. 'dateStyle',
  1634. 'timeStyle',
  1635. 'calendar',
  1636. 'dayPeriod',
  1637. 'numberingSystem',
  1638. 'hourCycle',
  1639. 'fractionalSecondDigits'
  1640. ];
  1641. /** @internal */
  1642. function parseDateTimeArgs(...args) {
  1643. const [arg1, arg2, arg3, arg4] = args;
  1644. const options = {};
  1645. let overrides = {};
  1646. let value;
  1647. if (isString(arg1)) {
  1648. // Only allow ISO strings - other date formats are often supported,
  1649. // but may cause different results in different browsers.
  1650. const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
  1651. if (!matches) {
  1652. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  1653. }
  1654. // Some browsers can not parse the iso datetime separated by space,
  1655. // this is a compromise solution by replace the 'T'/' ' with 'T'
  1656. const dateTime = matches[3]
  1657. ? matches[3].trim().startsWith('T')
  1658. ? `${matches[1].trim()}${matches[3].trim()}`
  1659. : `${matches[1].trim()}T${matches[3].trim()}`
  1660. : matches[1].trim();
  1661. value = new Date(dateTime);
  1662. try {
  1663. // This will fail if the date is not valid
  1664. value.toISOString();
  1665. }
  1666. catch (e) {
  1667. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  1668. }
  1669. }
  1670. else if (isDate(arg1)) {
  1671. if (isNaN(arg1.getTime())) {
  1672. throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
  1673. }
  1674. value = arg1;
  1675. }
  1676. else if (isNumber(arg1)) {
  1677. value = arg1;
  1678. }
  1679. else {
  1680. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  1681. }
  1682. if (isString(arg2)) {
  1683. options.key = arg2;
  1684. }
  1685. else if (isPlainObject(arg2)) {
  1686. Object.keys(arg2).forEach(key => {
  1687. if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
  1688. overrides[key] = arg2[key];
  1689. }
  1690. else {
  1691. options[key] = arg2[key];
  1692. }
  1693. });
  1694. }
  1695. if (isString(arg3)) {
  1696. options.locale = arg3;
  1697. }
  1698. else if (isPlainObject(arg3)) {
  1699. overrides = arg3;
  1700. }
  1701. if (isPlainObject(arg4)) {
  1702. overrides = arg4;
  1703. }
  1704. return [options.key || '', value, options, overrides];
  1705. }
  1706. /** @internal */
  1707. function clearDateTimeFormat(ctx, locale, format) {
  1708. const context = ctx;
  1709. for (const key in format) {
  1710. const id = `${locale}__${key}`;
  1711. if (!context.__datetimeFormatters.has(id)) {
  1712. continue;
  1713. }
  1714. context.__datetimeFormatters.delete(id);
  1715. }
  1716. }
  1717. // implementation of `number` function
  1718. function number(context, ...args) {
  1719. const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  1720. const { __numberFormatters } = context;
  1721. if (!Availabilities.numberFormat) {
  1722. onWarn(getWarnMessage$1(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
  1723. return MISSING_RESOLVE_VALUE;
  1724. }
  1725. const [key, value, options, overrides] = parseNumberArgs(...args);
  1726. const missingWarn = isBoolean(options.missingWarn)
  1727. ? options.missingWarn
  1728. : context.missingWarn;
  1729. const fallbackWarn = isBoolean(options.fallbackWarn)
  1730. ? options.fallbackWarn
  1731. : context.fallbackWarn;
  1732. const part = !!options.part;
  1733. const locale = getLocale(context, options);
  1734. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  1735. fallbackLocale, locale);
  1736. if (!isString(key) || key === '') {
  1737. return new Intl.NumberFormat(locale, overrides).format(value);
  1738. }
  1739. // resolve format
  1740. let numberFormat = {};
  1741. let targetLocale;
  1742. let format = null;
  1743. let from = locale;
  1744. let to = null;
  1745. const type = 'number format';
  1746. for (let i = 0; i < locales.length; i++) {
  1747. targetLocale = to = locales[i];
  1748. if (locale !== targetLocale &&
  1749. isTranslateFallbackWarn(fallbackWarn, key)) {
  1750. onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
  1751. key,
  1752. target: targetLocale
  1753. }));
  1754. }
  1755. // for vue-devtools timeline event
  1756. if (locale !== targetLocale) {
  1757. const emitter = context.__v_emitter;
  1758. if (emitter) {
  1759. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  1760. type,
  1761. key,
  1762. from,
  1763. to,
  1764. groupId: `${type}:${key}`
  1765. });
  1766. }
  1767. }
  1768. numberFormat =
  1769. numberFormats[targetLocale] || {};
  1770. format = numberFormat[key];
  1771. if (isPlainObject(format))
  1772. break;
  1773. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  1774. from = to;
  1775. }
  1776. // checking format and target locale
  1777. if (!isPlainObject(format) || !isString(targetLocale)) {
  1778. return unresolving ? NOT_REOSLVED : key;
  1779. }
  1780. let id = `${targetLocale}__${key}`;
  1781. if (!isEmptyObject(overrides)) {
  1782. id = `${id}__${JSON.stringify(overrides)}`;
  1783. }
  1784. let formatter = __numberFormatters.get(id);
  1785. if (!formatter) {
  1786. formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
  1787. __numberFormatters.set(id, formatter);
  1788. }
  1789. return !part ? formatter.format(value) : formatter.formatToParts(value);
  1790. }
  1791. /** @internal */
  1792. const NUMBER_FORMAT_OPTIONS_KEYS = [
  1793. 'localeMatcher',
  1794. 'style',
  1795. 'currency',
  1796. 'currencyDisplay',
  1797. 'currencySign',
  1798. 'useGrouping',
  1799. 'minimumIntegerDigits',
  1800. 'minimumFractionDigits',
  1801. 'maximumFractionDigits',
  1802. 'minimumSignificantDigits',
  1803. 'maximumSignificantDigits',
  1804. 'compactDisplay',
  1805. 'notation',
  1806. 'signDisplay',
  1807. 'unit',
  1808. 'unitDisplay',
  1809. 'roundingMode',
  1810. 'roundingPriority',
  1811. 'roundingIncrement',
  1812. 'trailingZeroDisplay'
  1813. ];
  1814. /** @internal */
  1815. function parseNumberArgs(...args) {
  1816. const [arg1, arg2, arg3, arg4] = args;
  1817. const options = {};
  1818. let overrides = {};
  1819. if (!isNumber(arg1)) {
  1820. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  1821. }
  1822. const value = arg1;
  1823. if (isString(arg2)) {
  1824. options.key = arg2;
  1825. }
  1826. else if (isPlainObject(arg2)) {
  1827. Object.keys(arg2).forEach(key => {
  1828. if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
  1829. overrides[key] = arg2[key];
  1830. }
  1831. else {
  1832. options[key] = arg2[key];
  1833. }
  1834. });
  1835. }
  1836. if (isString(arg3)) {
  1837. options.locale = arg3;
  1838. }
  1839. else if (isPlainObject(arg3)) {
  1840. overrides = arg3;
  1841. }
  1842. if (isPlainObject(arg4)) {
  1843. overrides = arg4;
  1844. }
  1845. return [options.key || '', value, options, overrides];
  1846. }
  1847. /** @internal */
  1848. function clearNumberFormat(ctx, locale, format) {
  1849. const context = ctx;
  1850. for (const key in format) {
  1851. const id = `${locale}__${key}`;
  1852. if (!context.__numberFormatters.has(id)) {
  1853. continue;
  1854. }
  1855. context.__numberFormatters.delete(id);
  1856. }
  1857. }
  1858. /**
  1859. * Vue I18n Version
  1860. *
  1861. * @remarks
  1862. * Semver format. Same format as the package.json `version` field.
  1863. *
  1864. * @VueI18nGeneral
  1865. */
  1866. const VERSION = '9.8.0';
  1867. /**
  1868. * This is only called development env
  1869. * istanbul-ignore-next
  1870. */
  1871. function initDev() {
  1872. {
  1873. {
  1874. console.info(`You are running a development build of vue-i18n.\n` +
  1875. `Make sure to use the production build (*.prod.js) when deploying for production.`);
  1876. }
  1877. }
  1878. }
  1879. const code$1 = CoreWarnCodes.__EXTEND_POINT__;
  1880. const inc$1 = incrementer(code$1);
  1881. const I18nWarnCodes = {
  1882. FALLBACK_TO_ROOT: code$1,
  1883. NOT_SUPPORTED_PRESERVE: inc$1(),
  1884. NOT_SUPPORTED_FORMATTER: inc$1(),
  1885. NOT_SUPPORTED_PRESERVE_DIRECTIVE: inc$1(),
  1886. NOT_SUPPORTED_GET_CHOICE_INDEX: inc$1(),
  1887. COMPONENT_NAME_LEGACY_COMPATIBLE: inc$1(),
  1888. NOT_FOUND_PARENT_SCOPE: inc$1(),
  1889. IGNORE_OBJ_FLATTEN: inc$1(),
  1890. NOTICE_DROP_ALLOW_COMPOSITION: inc$1() // 17
  1891. };
  1892. const warnMessages = {
  1893. [I18nWarnCodes.FALLBACK_TO_ROOT]: `Fall back to {type} '{key}' with root locale.`,
  1894. [I18nWarnCodes.NOT_SUPPORTED_PRESERVE]: `Not supported 'preserve'.`,
  1895. [I18nWarnCodes.NOT_SUPPORTED_FORMATTER]: `Not supported 'formatter'.`,
  1896. [I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE]: `Not supported 'preserveDirectiveContent'.`,
  1897. [I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX]: `Not supported 'getChoiceIndex'.`,
  1898. [I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE]: `Component name legacy compatible: '{name}' -> 'i18n'`,
  1899. [I18nWarnCodes.NOT_FOUND_PARENT_SCOPE]: `Not found parent scope. use the global scope.`,
  1900. [I18nWarnCodes.IGNORE_OBJ_FLATTEN]: `Ignore object flatten: '{key}' key has an string value`,
  1901. [I18nWarnCodes.NOTICE_DROP_ALLOW_COMPOSITION]: `'allowComposition' option will be dropped in the next major version. For more information, please see 👉 https://tinyurl.com/2p97mcze`
  1902. };
  1903. function getWarnMessage(code, ...args) {
  1904. return format(warnMessages[code], ...args);
  1905. }
  1906. const code = CoreErrorCodes.__EXTEND_POINT__;
  1907. const inc = incrementer(code);
  1908. const I18nErrorCodes = {
  1909. // composer module errors
  1910. UNEXPECTED_RETURN_TYPE: code,
  1911. // legacy module errors
  1912. INVALID_ARGUMENT: inc(),
  1913. // i18n module errors
  1914. MUST_BE_CALL_SETUP_TOP: inc(),
  1915. NOT_INSTALLED: inc(),
  1916. NOT_AVAILABLE_IN_LEGACY_MODE: inc(),
  1917. // directive module errors
  1918. REQUIRED_VALUE: inc(),
  1919. INVALID_VALUE: inc(),
  1920. // vue-devtools errors
  1921. CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN: inc(),
  1922. NOT_INSTALLED_WITH_PROVIDE: inc(),
  1923. // unexpected error
  1924. UNEXPECTED_ERROR: inc(),
  1925. // not compatible legacy vue-i18n constructor
  1926. NOT_COMPATIBLE_LEGACY_VUE_I18N: inc(),
  1927. // bridge support vue 2.x only
  1928. BRIDGE_SUPPORT_VUE_2_ONLY: inc(),
  1929. // need to define `i18n` option in `allowComposition: true` and `useScope: 'local' at `useI18n``
  1930. MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION: inc(),
  1931. // Not available Compostion API in Legacy API mode. Please make sure that the legacy API mode is working properly
  1932. NOT_AVAILABLE_COMPOSITION_IN_LEGACY: inc(),
  1933. // for enhancement
  1934. __EXTEND_POINT__: inc() // 40
  1935. };
  1936. function createI18nError(code, ...args) {
  1937. return createCompileError(code, null, { messages: errorMessages, args } );
  1938. }
  1939. const errorMessages = {
  1940. [I18nErrorCodes.UNEXPECTED_RETURN_TYPE]: 'Unexpected return type in composer',
  1941. [I18nErrorCodes.INVALID_ARGUMENT]: 'Invalid argument',
  1942. [I18nErrorCodes.MUST_BE_CALL_SETUP_TOP]: 'Must be called at the top of a `setup` function',
  1943. [I18nErrorCodes.NOT_INSTALLED]: 'Need to install with `app.use` function',
  1944. [I18nErrorCodes.UNEXPECTED_ERROR]: 'Unexpected error',
  1945. [I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE]: 'Not available in legacy mode',
  1946. [I18nErrorCodes.REQUIRED_VALUE]: `Required in value: {0}`,
  1947. [I18nErrorCodes.INVALID_VALUE]: `Invalid value`,
  1948. [I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN]: `Cannot setup vue-devtools plugin`,
  1949. [I18nErrorCodes.NOT_INSTALLED_WITH_PROVIDE]: 'Need to install with `provide` function',
  1950. [I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N]: 'Not compatible legacy VueI18n.',
  1951. [I18nErrorCodes.BRIDGE_SUPPORT_VUE_2_ONLY]: 'vue-i18n-bridge support Vue 2.x only',
  1952. [I18nErrorCodes.MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION]: 'Must define ‘i18n’ option or custom block in Composition API with using local scope in Legacy API mode',
  1953. [I18nErrorCodes.NOT_AVAILABLE_COMPOSITION_IN_LEGACY]: 'Not available Compostion API in Legacy API mode. Please make sure that the legacy API mode is working properly'
  1954. };
  1955. const TranslateVNodeSymbol =
  1956. /* #__PURE__*/ makeSymbol('__translateVNode');
  1957. const DatetimePartsSymbol = /* #__PURE__*/ makeSymbol('__datetimeParts');
  1958. const NumberPartsSymbol = /* #__PURE__*/ makeSymbol('__numberParts');
  1959. const EnableEmitter = /* #__PURE__*/ makeSymbol('__enableEmitter');
  1960. const DisableEmitter = /* #__PURE__*/ makeSymbol('__disableEmitter');
  1961. const SetPluralRulesSymbol = makeSymbol('__setPluralRules');
  1962. const InejctWithOptionSymbol =
  1963. /* #__PURE__*/ makeSymbol('__injectWithOption');
  1964. const DisposeSymbol = /* #__PURE__*/ makeSymbol('__dispose');
  1965. const __VUE_I18N_BRIDGE__ = '__VUE_I18N_BRIDGE__';
  1966. /* eslint-disable @typescript-eslint/no-explicit-any */
  1967. /**
  1968. * Transform flat json in obj to normal json in obj
  1969. */
  1970. function handleFlatJson(obj) {
  1971. // check obj
  1972. if (!isObject(obj)) {
  1973. return obj;
  1974. }
  1975. for (const key in obj) {
  1976. // check key
  1977. if (!hasOwn(obj, key)) {
  1978. continue;
  1979. }
  1980. // handle for normal json
  1981. if (!key.includes('.')) {
  1982. // recursive process value if value is also a object
  1983. if (isObject(obj[key])) {
  1984. handleFlatJson(obj[key]);
  1985. }
  1986. }
  1987. // handle for flat json, transform to normal json
  1988. else {
  1989. // go to the last object
  1990. const subKeys = key.split('.');
  1991. const lastIndex = subKeys.length - 1;
  1992. let currentObj = obj;
  1993. let hasStringValue = false;
  1994. for (let i = 0; i < lastIndex; i++) {
  1995. if (!(subKeys[i] in currentObj)) {
  1996. currentObj[subKeys[i]] = {};
  1997. }
  1998. if (!isObject(currentObj[subKeys[i]])) {
  1999. warn(getWarnMessage(I18nWarnCodes.IGNORE_OBJ_FLATTEN, {
  2000. key: subKeys[i]
  2001. }));
  2002. hasStringValue = true;
  2003. break;
  2004. }
  2005. currentObj = currentObj[subKeys[i]];
  2006. }
  2007. // update last object value, delete old property
  2008. if (!hasStringValue) {
  2009. currentObj[subKeys[lastIndex]] = obj[key];
  2010. delete obj[key];
  2011. }
  2012. // recursive process value if value is also a object
  2013. if (isObject(currentObj[subKeys[lastIndex]])) {
  2014. handleFlatJson(currentObj[subKeys[lastIndex]]);
  2015. }
  2016. }
  2017. }
  2018. return obj;
  2019. }
  2020. function getLocaleMessages(locale, options) {
  2021. const { messages, __i18n, messageResolver, flatJson } = options;
  2022. // prettier-ignore
  2023. const ret = (isPlainObject(messages)
  2024. ? messages
  2025. : isArray(__i18n)
  2026. ? {}
  2027. : { [locale]: {} });
  2028. // merge locale messages of i18n custom block
  2029. if (isArray(__i18n)) {
  2030. __i18n.forEach(custom => {
  2031. if ('locale' in custom && 'resource' in custom) {
  2032. const { locale, resource } = custom;
  2033. if (locale) {
  2034. ret[locale] = ret[locale] || {};
  2035. deepCopy(resource, ret[locale]);
  2036. }
  2037. else {
  2038. deepCopy(resource, ret);
  2039. }
  2040. }
  2041. else {
  2042. isString(custom) && deepCopy(JSON.parse(custom), ret);
  2043. }
  2044. });
  2045. }
  2046. // handle messages for flat json
  2047. if (messageResolver == null && flatJson) {
  2048. for (const key in ret) {
  2049. if (hasOwn(ret, key)) {
  2050. handleFlatJson(ret[key]);
  2051. }
  2052. }
  2053. }
  2054. return ret;
  2055. }
  2056. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2057. function getComponentOptions(instance) {
  2058. return instance.type ;
  2059. }
  2060. function adjustI18nResources(gl, options, componentOptions // eslint-disable-line @typescript-eslint/no-explicit-any
  2061. ) {
  2062. let messages = isObject(options.messages) ? options.messages : {};
  2063. if ('__i18nGlobal' in componentOptions) {
  2064. messages = getLocaleMessages(gl.locale.value, {
  2065. messages,
  2066. __i18n: componentOptions.__i18nGlobal
  2067. });
  2068. }
  2069. // merge locale messages
  2070. const locales = Object.keys(messages);
  2071. if (locales.length) {
  2072. locales.forEach(locale => {
  2073. gl.mergeLocaleMessage(locale, messages[locale]);
  2074. });
  2075. }
  2076. {
  2077. // merge datetime formats
  2078. if (isObject(options.datetimeFormats)) {
  2079. const locales = Object.keys(options.datetimeFormats);
  2080. if (locales.length) {
  2081. locales.forEach(locale => {
  2082. gl.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
  2083. });
  2084. }
  2085. }
  2086. // merge number formats
  2087. if (isObject(options.numberFormats)) {
  2088. const locales = Object.keys(options.numberFormats);
  2089. if (locales.length) {
  2090. locales.forEach(locale => {
  2091. gl.mergeNumberFormat(locale, options.numberFormats[locale]);
  2092. });
  2093. }
  2094. }
  2095. }
  2096. }
  2097. function createTextNode(key) {
  2098. return vue.createVNode(vue.Text, null, key, 0)
  2099. ;
  2100. }
  2101. /* eslint-enable @typescript-eslint/no-explicit-any */
  2102. /* eslint-disable @typescript-eslint/no-explicit-any */
  2103. // extend VNode interface
  2104. const DEVTOOLS_META = '__INTLIFY_META__';
  2105. const NOOP_RETURN_ARRAY = () => [];
  2106. const NOOP_RETURN_FALSE = () => false;
  2107. let composerID = 0;
  2108. function defineCoreMissingHandler(missing) {
  2109. return ((ctx, locale, key, type) => {
  2110. return missing(locale, key, vue.getCurrentInstance() || undefined, type);
  2111. });
  2112. }
  2113. // for Intlify DevTools
  2114. /* #__NO_SIDE_EFFECTS__ */
  2115. const getMetaInfo = () => {
  2116. const instance = vue.getCurrentInstance();
  2117. let meta = null; // eslint-disable-line @typescript-eslint/no-explicit-any
  2118. return instance && (meta = getComponentOptions(instance)[DEVTOOLS_META])
  2119. ? { [DEVTOOLS_META]: meta } // eslint-disable-line @typescript-eslint/no-explicit-any
  2120. : null;
  2121. };
  2122. /**
  2123. * Create composer interface factory
  2124. *
  2125. * @internal
  2126. */
  2127. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  2128. function createComposer(options = {}, VueI18nLegacy) {
  2129. const { __root, __injectWithOption } = options;
  2130. const _isGlobal = __root === undefined;
  2131. const flatJson = options.flatJson;
  2132. let _inheritLocale = isBoolean(options.inheritLocale)
  2133. ? options.inheritLocale
  2134. : true;
  2135. const _locale = vue.ref(
  2136. // prettier-ignore
  2137. __root && _inheritLocale
  2138. ? __root.locale.value
  2139. : isString(options.locale)
  2140. ? options.locale
  2141. : DEFAULT_LOCALE);
  2142. const _fallbackLocale = vue.ref(
  2143. // prettier-ignore
  2144. __root && _inheritLocale
  2145. ? __root.fallbackLocale.value
  2146. : isString(options.fallbackLocale) ||
  2147. isArray(options.fallbackLocale) ||
  2148. isPlainObject(options.fallbackLocale) ||
  2149. options.fallbackLocale === false
  2150. ? options.fallbackLocale
  2151. : _locale.value);
  2152. const _messages = vue.ref(getLocaleMessages(_locale.value, options));
  2153. // prettier-ignore
  2154. const _datetimeFormats = vue.ref(isPlainObject(options.datetimeFormats)
  2155. ? options.datetimeFormats
  2156. : { [_locale.value]: {} })
  2157. ;
  2158. // prettier-ignore
  2159. const _numberFormats = vue.ref(isPlainObject(options.numberFormats)
  2160. ? options.numberFormats
  2161. : { [_locale.value]: {} })
  2162. ;
  2163. // warning suppress options
  2164. // prettier-ignore
  2165. let _missingWarn = __root
  2166. ? __root.missingWarn
  2167. : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  2168. ? options.missingWarn
  2169. : true;
  2170. // prettier-ignore
  2171. let _fallbackWarn = __root
  2172. ? __root.fallbackWarn
  2173. : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  2174. ? options.fallbackWarn
  2175. : true;
  2176. // prettier-ignore
  2177. let _fallbackRoot = __root
  2178. ? __root.fallbackRoot
  2179. : isBoolean(options.fallbackRoot)
  2180. ? options.fallbackRoot
  2181. : true;
  2182. // configure fall back to root
  2183. let _fallbackFormat = !!options.fallbackFormat;
  2184. // runtime missing
  2185. let _missing = isFunction(options.missing) ? options.missing : null;
  2186. let _runtimeMissing = isFunction(options.missing)
  2187. ? defineCoreMissingHandler(options.missing)
  2188. : null;
  2189. // postTranslation handler
  2190. let _postTranslation = isFunction(options.postTranslation)
  2191. ? options.postTranslation
  2192. : null;
  2193. // prettier-ignore
  2194. let _warnHtmlMessage = __root
  2195. ? __root.warnHtmlMessage
  2196. : isBoolean(options.warnHtmlMessage)
  2197. ? options.warnHtmlMessage
  2198. : true;
  2199. let _escapeParameter = !!options.escapeParameter;
  2200. // custom linked modifiers
  2201. // prettier-ignore
  2202. const _modifiers = __root
  2203. ? __root.modifiers
  2204. : isPlainObject(options.modifiers)
  2205. ? options.modifiers
  2206. : {};
  2207. // pluralRules
  2208. let _pluralRules = options.pluralRules || (__root && __root.pluralRules);
  2209. // runtime context
  2210. // eslint-disable-next-line prefer-const
  2211. let _context;
  2212. const getCoreContext = () => {
  2213. _isGlobal && setFallbackContext(null);
  2214. const ctxOptions = {
  2215. version: VERSION,
  2216. locale: _locale.value,
  2217. fallbackLocale: _fallbackLocale.value,
  2218. messages: _messages.value,
  2219. modifiers: _modifiers,
  2220. pluralRules: _pluralRules,
  2221. missing: _runtimeMissing === null ? undefined : _runtimeMissing,
  2222. missingWarn: _missingWarn,
  2223. fallbackWarn: _fallbackWarn,
  2224. fallbackFormat: _fallbackFormat,
  2225. unresolving: true,
  2226. postTranslation: _postTranslation === null ? undefined : _postTranslation,
  2227. warnHtmlMessage: _warnHtmlMessage,
  2228. escapeParameter: _escapeParameter,
  2229. messageResolver: options.messageResolver,
  2230. messageCompiler: options.messageCompiler,
  2231. __meta: { framework: 'vue' }
  2232. };
  2233. {
  2234. ctxOptions.datetimeFormats = _datetimeFormats.value;
  2235. ctxOptions.numberFormats = _numberFormats.value;
  2236. ctxOptions.__datetimeFormatters = isPlainObject(_context)
  2237. ? _context.__datetimeFormatters
  2238. : undefined;
  2239. ctxOptions.__numberFormatters = isPlainObject(_context)
  2240. ? _context.__numberFormatters
  2241. : undefined;
  2242. }
  2243. {
  2244. ctxOptions.__v_emitter = isPlainObject(_context)
  2245. ? _context.__v_emitter
  2246. : undefined;
  2247. }
  2248. const ctx = createCoreContext(ctxOptions);
  2249. _isGlobal && setFallbackContext(ctx);
  2250. return ctx;
  2251. };
  2252. _context = getCoreContext();
  2253. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  2254. // track reactivity
  2255. function trackReactivityValues() {
  2256. return [
  2257. _locale.value,
  2258. _fallbackLocale.value,
  2259. _messages.value,
  2260. _datetimeFormats.value,
  2261. _numberFormats.value
  2262. ]
  2263. ;
  2264. }
  2265. // locale
  2266. const locale = vue.computed({
  2267. get: () => _locale.value,
  2268. set: val => {
  2269. _locale.value = val;
  2270. _context.locale = _locale.value;
  2271. }
  2272. });
  2273. // fallbackLocale
  2274. const fallbackLocale = vue.computed({
  2275. get: () => _fallbackLocale.value,
  2276. set: val => {
  2277. _fallbackLocale.value = val;
  2278. _context.fallbackLocale = _fallbackLocale.value;
  2279. updateFallbackLocale(_context, _locale.value, val);
  2280. }
  2281. });
  2282. // messages
  2283. const messages = vue.computed(() => _messages.value);
  2284. // datetimeFormats
  2285. const datetimeFormats = /* #__PURE__*/ vue.computed(() => _datetimeFormats.value);
  2286. // numberFormats
  2287. const numberFormats = /* #__PURE__*/ vue.computed(() => _numberFormats.value);
  2288. // getPostTranslationHandler
  2289. function getPostTranslationHandler() {
  2290. return isFunction(_postTranslation) ? _postTranslation : null;
  2291. }
  2292. // setPostTranslationHandler
  2293. function setPostTranslationHandler(handler) {
  2294. _postTranslation = handler;
  2295. _context.postTranslation = handler;
  2296. }
  2297. // getMissingHandler
  2298. function getMissingHandler() {
  2299. return _missing;
  2300. }
  2301. // setMissingHandler
  2302. function setMissingHandler(handler) {
  2303. if (handler !== null) {
  2304. _runtimeMissing = defineCoreMissingHandler(handler);
  2305. }
  2306. _missing = handler;
  2307. _context.missing = _runtimeMissing;
  2308. }
  2309. function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any
  2310. ) {
  2311. return type !== 'translate' || !arg.resolvedMessage;
  2312. }
  2313. const wrapWithDeps = (fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) => {
  2314. trackReactivityValues(); // track reactive dependency
  2315. // NOTE: experimental !!
  2316. let ret;
  2317. try {
  2318. if (true || false) {
  2319. setAdditionalMeta(getMetaInfo());
  2320. }
  2321. if (!_isGlobal) {
  2322. _context.fallbackContext = __root
  2323. ? getFallbackContext()
  2324. : undefined;
  2325. }
  2326. ret = fn(_context);
  2327. }
  2328. finally {
  2329. if (!_isGlobal) {
  2330. _context.fallbackContext = undefined;
  2331. }
  2332. }
  2333. if ((warnType !== 'translate exists' && // for not `te` (e.g `t`)
  2334. isNumber(ret) &&
  2335. ret === NOT_REOSLVED) ||
  2336. (warnType === 'translate exists' && !ret) // for `te`
  2337. ) {
  2338. const [key, arg2] = argumentParser();
  2339. if (__root &&
  2340. isString(key) &&
  2341. isResolvedTranslateMessage(warnType, arg2)) {
  2342. if (_fallbackRoot &&
  2343. (isTranslateFallbackWarn(_fallbackWarn, key) ||
  2344. isTranslateMissingWarn(_missingWarn, key))) {
  2345. warn(getWarnMessage(I18nWarnCodes.FALLBACK_TO_ROOT, {
  2346. key,
  2347. type: warnType
  2348. }));
  2349. }
  2350. // for vue-devtools timeline event
  2351. {
  2352. const { __v_emitter: emitter } = _context;
  2353. if (emitter && _fallbackRoot) {
  2354. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  2355. type: warnType,
  2356. key,
  2357. to: 'global',
  2358. groupId: `${warnType}:${key}`
  2359. });
  2360. }
  2361. }
  2362. }
  2363. return __root && _fallbackRoot
  2364. ? fallbackSuccess(__root)
  2365. : fallbackFail(key);
  2366. }
  2367. else if (successCondition(ret)) {
  2368. return ret;
  2369. }
  2370. else {
  2371. /* istanbul ignore next */
  2372. throw createI18nError(I18nErrorCodes.UNEXPECTED_RETURN_TYPE);
  2373. }
  2374. };
  2375. // t
  2376. function t(...args) {
  2377. return wrapWithDeps(context => Reflect.apply(translate, null, [context, ...args]), () => parseTranslateArgs(...args), 'translate', root => Reflect.apply(root.t, root, [...args]), key => key, val => isString(val));
  2378. }
  2379. // rt
  2380. function rt(...args) {
  2381. const [arg1, arg2, arg3] = args;
  2382. if (arg3 && !isObject(arg3)) {
  2383. throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
  2384. }
  2385. return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]);
  2386. }
  2387. // d
  2388. function d(...args) {
  2389. return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format', root => Reflect.apply(root.d, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));
  2390. }
  2391. // n
  2392. function n(...args) {
  2393. return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format', root => Reflect.apply(root.n, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));
  2394. }
  2395. // for custom processor
  2396. function normalize(values) {
  2397. return values.map(val => isString(val) || isNumber(val) || isBoolean(val)
  2398. ? createTextNode(String(val))
  2399. : val);
  2400. }
  2401. const interpolate = (val) => val;
  2402. const processor = {
  2403. normalize,
  2404. interpolate,
  2405. type: 'vnode'
  2406. };
  2407. // translateVNode, using for `i18n-t` component
  2408. function translateVNode(...args) {
  2409. return wrapWithDeps(context => {
  2410. let ret;
  2411. const _context = context;
  2412. try {
  2413. _context.processor = processor;
  2414. ret = Reflect.apply(translate, null, [_context, ...args]);
  2415. }
  2416. finally {
  2417. _context.processor = null;
  2418. }
  2419. return ret;
  2420. }, () => parseTranslateArgs(...args), 'translate',
  2421. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2422. root => root[TranslateVNodeSymbol](...args), key => [createTextNode(key)], val => isArray(val));
  2423. }
  2424. // numberParts, using for `i18n-n` component
  2425. function numberParts(...args) {
  2426. return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format',
  2427. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2428. root => root[NumberPartsSymbol](...args), NOOP_RETURN_ARRAY, val => isString(val) || isArray(val));
  2429. }
  2430. // datetimeParts, using for `i18n-d` component
  2431. function datetimeParts(...args) {
  2432. return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format',
  2433. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2434. root => root[DatetimePartsSymbol](...args), NOOP_RETURN_ARRAY, val => isString(val) || isArray(val));
  2435. }
  2436. function setPluralRules(rules) {
  2437. _pluralRules = rules;
  2438. _context.pluralRules = _pluralRules;
  2439. }
  2440. // te
  2441. function te(key, locale) {
  2442. return wrapWithDeps(() => {
  2443. if (!key) {
  2444. return false;
  2445. }
  2446. const targetLocale = isString(locale) ? locale : _locale.value;
  2447. const message = getLocaleMessage(targetLocale);
  2448. const resolved = _context.messageResolver(message, key);
  2449. return (isMessageAST(resolved) ||
  2450. isMessageFunction(resolved) ||
  2451. isString(resolved));
  2452. }, () => [key], 'translate exists', root => {
  2453. return Reflect.apply(root.te, root, [key, locale]);
  2454. }, NOOP_RETURN_FALSE, val => isBoolean(val));
  2455. }
  2456. function resolveMessages(key) {
  2457. let messages = null;
  2458. const locales = fallbackWithLocaleChain(_context, _fallbackLocale.value, _locale.value);
  2459. for (let i = 0; i < locales.length; i++) {
  2460. const targetLocaleMessages = _messages.value[locales[i]] || {};
  2461. const messageValue = _context.messageResolver(targetLocaleMessages, key);
  2462. if (messageValue != null) {
  2463. messages = messageValue;
  2464. break;
  2465. }
  2466. }
  2467. return messages;
  2468. }
  2469. // tm
  2470. function tm(key) {
  2471. const messages = resolveMessages(key);
  2472. // prettier-ignore
  2473. return messages != null
  2474. ? messages
  2475. : __root
  2476. ? __root.tm(key) || {}
  2477. : {};
  2478. }
  2479. // getLocaleMessage
  2480. function getLocaleMessage(locale) {
  2481. return (_messages.value[locale] || {});
  2482. }
  2483. // setLocaleMessage
  2484. function setLocaleMessage(locale, message) {
  2485. if (flatJson) {
  2486. const _message = { [locale]: message };
  2487. for (const key in _message) {
  2488. if (hasOwn(_message, key)) {
  2489. handleFlatJson(_message[key]);
  2490. }
  2491. }
  2492. message = _message[locale];
  2493. }
  2494. _messages.value[locale] = message;
  2495. _context.messages = _messages.value;
  2496. }
  2497. // mergeLocaleMessage
  2498. function mergeLocaleMessage(locale, message) {
  2499. _messages.value[locale] = _messages.value[locale] || {};
  2500. const _message = { [locale]: message };
  2501. for (const key in _message) {
  2502. if (hasOwn(_message, key)) {
  2503. handleFlatJson(_message[key]);
  2504. }
  2505. }
  2506. message = _message[locale];
  2507. deepCopy(message, _messages.value[locale]);
  2508. _context.messages = _messages.value;
  2509. }
  2510. // getDateTimeFormat
  2511. function getDateTimeFormat(locale) {
  2512. return _datetimeFormats.value[locale] || {};
  2513. }
  2514. // setDateTimeFormat
  2515. function setDateTimeFormat(locale, format) {
  2516. _datetimeFormats.value[locale] = format;
  2517. _context.datetimeFormats = _datetimeFormats.value;
  2518. clearDateTimeFormat(_context, locale, format);
  2519. }
  2520. // mergeDateTimeFormat
  2521. function mergeDateTimeFormat(locale, format) {
  2522. _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format);
  2523. _context.datetimeFormats = _datetimeFormats.value;
  2524. clearDateTimeFormat(_context, locale, format);
  2525. }
  2526. // getNumberFormat
  2527. function getNumberFormat(locale) {
  2528. return _numberFormats.value[locale] || {};
  2529. }
  2530. // setNumberFormat
  2531. function setNumberFormat(locale, format) {
  2532. _numberFormats.value[locale] = format;
  2533. _context.numberFormats = _numberFormats.value;
  2534. clearNumberFormat(_context, locale, format);
  2535. }
  2536. // mergeNumberFormat
  2537. function mergeNumberFormat(locale, format) {
  2538. _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format);
  2539. _context.numberFormats = _numberFormats.value;
  2540. clearNumberFormat(_context, locale, format);
  2541. }
  2542. // for debug
  2543. composerID++;
  2544. // watch root locale & fallbackLocale
  2545. if (__root && inBrowser) {
  2546. vue.watch(__root.locale, (val) => {
  2547. if (_inheritLocale) {
  2548. _locale.value = val;
  2549. _context.locale = val;
  2550. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  2551. }
  2552. });
  2553. vue.watch(__root.fallbackLocale, (val) => {
  2554. if (_inheritLocale) {
  2555. _fallbackLocale.value = val;
  2556. _context.fallbackLocale = val;
  2557. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  2558. }
  2559. });
  2560. }
  2561. // define basic composition API!
  2562. const composer = {
  2563. id: composerID,
  2564. locale,
  2565. fallbackLocale,
  2566. get inheritLocale() {
  2567. return _inheritLocale;
  2568. },
  2569. set inheritLocale(val) {
  2570. _inheritLocale = val;
  2571. if (val && __root) {
  2572. _locale.value = __root.locale.value;
  2573. _fallbackLocale.value = __root.fallbackLocale.value;
  2574. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  2575. }
  2576. },
  2577. get availableLocales() {
  2578. return Object.keys(_messages.value).sort();
  2579. },
  2580. messages,
  2581. get modifiers() {
  2582. return _modifiers;
  2583. },
  2584. get pluralRules() {
  2585. return _pluralRules || {};
  2586. },
  2587. get isGlobal() {
  2588. return _isGlobal;
  2589. },
  2590. get missingWarn() {
  2591. return _missingWarn;
  2592. },
  2593. set missingWarn(val) {
  2594. _missingWarn = val;
  2595. _context.missingWarn = _missingWarn;
  2596. },
  2597. get fallbackWarn() {
  2598. return _fallbackWarn;
  2599. },
  2600. set fallbackWarn(val) {
  2601. _fallbackWarn = val;
  2602. _context.fallbackWarn = _fallbackWarn;
  2603. },
  2604. get fallbackRoot() {
  2605. return _fallbackRoot;
  2606. },
  2607. set fallbackRoot(val) {
  2608. _fallbackRoot = val;
  2609. },
  2610. get fallbackFormat() {
  2611. return _fallbackFormat;
  2612. },
  2613. set fallbackFormat(val) {
  2614. _fallbackFormat = val;
  2615. _context.fallbackFormat = _fallbackFormat;
  2616. },
  2617. get warnHtmlMessage() {
  2618. return _warnHtmlMessage;
  2619. },
  2620. set warnHtmlMessage(val) {
  2621. _warnHtmlMessage = val;
  2622. _context.warnHtmlMessage = val;
  2623. },
  2624. get escapeParameter() {
  2625. return _escapeParameter;
  2626. },
  2627. set escapeParameter(val) {
  2628. _escapeParameter = val;
  2629. _context.escapeParameter = val;
  2630. },
  2631. t,
  2632. getLocaleMessage,
  2633. setLocaleMessage,
  2634. mergeLocaleMessage,
  2635. getPostTranslationHandler,
  2636. setPostTranslationHandler,
  2637. getMissingHandler,
  2638. setMissingHandler,
  2639. [SetPluralRulesSymbol]: setPluralRules
  2640. };
  2641. {
  2642. composer.datetimeFormats = datetimeFormats;
  2643. composer.numberFormats = numberFormats;
  2644. composer.rt = rt;
  2645. composer.te = te;
  2646. composer.tm = tm;
  2647. composer.d = d;
  2648. composer.n = n;
  2649. composer.getDateTimeFormat = getDateTimeFormat;
  2650. composer.setDateTimeFormat = setDateTimeFormat;
  2651. composer.mergeDateTimeFormat = mergeDateTimeFormat;
  2652. composer.getNumberFormat = getNumberFormat;
  2653. composer.setNumberFormat = setNumberFormat;
  2654. composer.mergeNumberFormat = mergeNumberFormat;
  2655. composer[InejctWithOptionSymbol] = __injectWithOption;
  2656. composer[TranslateVNodeSymbol] = translateVNode;
  2657. composer[DatetimePartsSymbol] = datetimeParts;
  2658. composer[NumberPartsSymbol] = numberParts;
  2659. }
  2660. // for vue-devtools timeline event
  2661. {
  2662. composer[EnableEmitter] = (emitter) => {
  2663. _context.__v_emitter = emitter;
  2664. };
  2665. composer[DisableEmitter] = () => {
  2666. _context.__v_emitter = undefined;
  2667. };
  2668. }
  2669. return composer;
  2670. }
  2671. /* eslint-enable @typescript-eslint/no-explicit-any */
  2672. /* eslint-disable @typescript-eslint/no-explicit-any */
  2673. /**
  2674. * Convert to I18n Composer Options from VueI18n Options
  2675. *
  2676. * @internal
  2677. */
  2678. function convertComposerOptions(options) {
  2679. const locale = isString(options.locale) ? options.locale : DEFAULT_LOCALE;
  2680. const fallbackLocale = isString(options.fallbackLocale) ||
  2681. isArray(options.fallbackLocale) ||
  2682. isPlainObject(options.fallbackLocale) ||
  2683. options.fallbackLocale === false
  2684. ? options.fallbackLocale
  2685. : locale;
  2686. const missing = isFunction(options.missing) ? options.missing : undefined;
  2687. const missingWarn = isBoolean(options.silentTranslationWarn) ||
  2688. isRegExp(options.silentTranslationWarn)
  2689. ? !options.silentTranslationWarn
  2690. : true;
  2691. const fallbackWarn = isBoolean(options.silentFallbackWarn) ||
  2692. isRegExp(options.silentFallbackWarn)
  2693. ? !options.silentFallbackWarn
  2694. : true;
  2695. const fallbackRoot = isBoolean(options.fallbackRoot)
  2696. ? options.fallbackRoot
  2697. : true;
  2698. const fallbackFormat = !!options.formatFallbackMessages;
  2699. const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};
  2700. const pluralizationRules = options.pluralizationRules;
  2701. const postTranslation = isFunction(options.postTranslation)
  2702. ? options.postTranslation
  2703. : undefined;
  2704. const warnHtmlMessage = isString(options.warnHtmlInMessage)
  2705. ? options.warnHtmlInMessage !== 'off'
  2706. : true;
  2707. const escapeParameter = !!options.escapeParameterHtml;
  2708. const inheritLocale = isBoolean(options.sync) ? options.sync : true;
  2709. if (options.formatter) {
  2710. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
  2711. }
  2712. if (options.preserveDirectiveContent) {
  2713. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
  2714. }
  2715. let messages = options.messages;
  2716. if (isPlainObject(options.sharedMessages)) {
  2717. const sharedMessages = options.sharedMessages;
  2718. const locales = Object.keys(sharedMessages);
  2719. messages = locales.reduce((messages, locale) => {
  2720. const message = messages[locale] || (messages[locale] = {});
  2721. assign(message, sharedMessages[locale]);
  2722. return messages;
  2723. }, (messages || {}));
  2724. }
  2725. const { __i18n, __root, __injectWithOption } = options;
  2726. const datetimeFormats = options.datetimeFormats;
  2727. const numberFormats = options.numberFormats;
  2728. const flatJson = options.flatJson;
  2729. return {
  2730. locale,
  2731. fallbackLocale,
  2732. messages,
  2733. flatJson,
  2734. datetimeFormats,
  2735. numberFormats,
  2736. missing,
  2737. missingWarn,
  2738. fallbackWarn,
  2739. fallbackRoot,
  2740. fallbackFormat,
  2741. modifiers,
  2742. pluralRules: pluralizationRules,
  2743. postTranslation,
  2744. warnHtmlMessage,
  2745. escapeParameter,
  2746. messageResolver: options.messageResolver,
  2747. inheritLocale,
  2748. __i18n,
  2749. __root,
  2750. __injectWithOption
  2751. };
  2752. }
  2753. /**
  2754. * create VueI18n interface factory
  2755. *
  2756. * @internal
  2757. */
  2758. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  2759. function createVueI18n(options = {}, VueI18nLegacy) {
  2760. {
  2761. const composer = createComposer(convertComposerOptions(options));
  2762. const { __extender } = options;
  2763. // defines VueI18n
  2764. const vueI18n = {
  2765. // id
  2766. id: composer.id,
  2767. // locale
  2768. get locale() {
  2769. return composer.locale.value;
  2770. },
  2771. set locale(val) {
  2772. composer.locale.value = val;
  2773. },
  2774. // fallbackLocale
  2775. get fallbackLocale() {
  2776. return composer.fallbackLocale.value;
  2777. },
  2778. set fallbackLocale(val) {
  2779. composer.fallbackLocale.value = val;
  2780. },
  2781. // messages
  2782. get messages() {
  2783. return composer.messages.value;
  2784. },
  2785. // datetimeFormats
  2786. get datetimeFormats() {
  2787. return composer.datetimeFormats.value;
  2788. },
  2789. // numberFormats
  2790. get numberFormats() {
  2791. return composer.numberFormats.value;
  2792. },
  2793. // availableLocales
  2794. get availableLocales() {
  2795. return composer.availableLocales;
  2796. },
  2797. // formatter
  2798. get formatter() {
  2799. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
  2800. // dummy
  2801. return {
  2802. interpolate() {
  2803. return [];
  2804. }
  2805. };
  2806. },
  2807. set formatter(val) {
  2808. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
  2809. },
  2810. // missing
  2811. get missing() {
  2812. return composer.getMissingHandler();
  2813. },
  2814. set missing(handler) {
  2815. composer.setMissingHandler(handler);
  2816. },
  2817. // silentTranslationWarn
  2818. get silentTranslationWarn() {
  2819. return isBoolean(composer.missingWarn)
  2820. ? !composer.missingWarn
  2821. : composer.missingWarn;
  2822. },
  2823. set silentTranslationWarn(val) {
  2824. composer.missingWarn = isBoolean(val) ? !val : val;
  2825. },
  2826. // silentFallbackWarn
  2827. get silentFallbackWarn() {
  2828. return isBoolean(composer.fallbackWarn)
  2829. ? !composer.fallbackWarn
  2830. : composer.fallbackWarn;
  2831. },
  2832. set silentFallbackWarn(val) {
  2833. composer.fallbackWarn = isBoolean(val) ? !val : val;
  2834. },
  2835. // modifiers
  2836. get modifiers() {
  2837. return composer.modifiers;
  2838. },
  2839. // formatFallbackMessages
  2840. get formatFallbackMessages() {
  2841. return composer.fallbackFormat;
  2842. },
  2843. set formatFallbackMessages(val) {
  2844. composer.fallbackFormat = val;
  2845. },
  2846. // postTranslation
  2847. get postTranslation() {
  2848. return composer.getPostTranslationHandler();
  2849. },
  2850. set postTranslation(handler) {
  2851. composer.setPostTranslationHandler(handler);
  2852. },
  2853. // sync
  2854. get sync() {
  2855. return composer.inheritLocale;
  2856. },
  2857. set sync(val) {
  2858. composer.inheritLocale = val;
  2859. },
  2860. // warnInHtmlMessage
  2861. get warnHtmlInMessage() {
  2862. return composer.warnHtmlMessage ? 'warn' : 'off';
  2863. },
  2864. set warnHtmlInMessage(val) {
  2865. composer.warnHtmlMessage = val !== 'off';
  2866. },
  2867. // escapeParameterHtml
  2868. get escapeParameterHtml() {
  2869. return composer.escapeParameter;
  2870. },
  2871. set escapeParameterHtml(val) {
  2872. composer.escapeParameter = val;
  2873. },
  2874. // preserveDirectiveContent
  2875. get preserveDirectiveContent() {
  2876. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
  2877. return true;
  2878. },
  2879. set preserveDirectiveContent(val) {
  2880. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
  2881. },
  2882. // pluralizationRules
  2883. get pluralizationRules() {
  2884. return composer.pluralRules || {};
  2885. },
  2886. // for internal
  2887. __composer: composer,
  2888. // t
  2889. t(...args) {
  2890. const [arg1, arg2, arg3] = args;
  2891. const options = {};
  2892. let list = null;
  2893. let named = null;
  2894. if (!isString(arg1)) {
  2895. throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
  2896. }
  2897. const key = arg1;
  2898. if (isString(arg2)) {
  2899. options.locale = arg2;
  2900. }
  2901. else if (isArray(arg2)) {
  2902. list = arg2;
  2903. }
  2904. else if (isPlainObject(arg2)) {
  2905. named = arg2;
  2906. }
  2907. if (isArray(arg3)) {
  2908. list = arg3;
  2909. }
  2910. else if (isPlainObject(arg3)) {
  2911. named = arg3;
  2912. }
  2913. // return composer.t(key, (list || named || {}) as any, options)
  2914. return Reflect.apply(composer.t, composer, [
  2915. key,
  2916. (list || named || {}),
  2917. options
  2918. ]);
  2919. },
  2920. rt(...args) {
  2921. return Reflect.apply(composer.rt, composer, [...args]);
  2922. },
  2923. // tc
  2924. tc(...args) {
  2925. const [arg1, arg2, arg3] = args;
  2926. const options = { plural: 1 };
  2927. let list = null;
  2928. let named = null;
  2929. if (!isString(arg1)) {
  2930. throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
  2931. }
  2932. const key = arg1;
  2933. if (isString(arg2)) {
  2934. options.locale = arg2;
  2935. }
  2936. else if (isNumber(arg2)) {
  2937. options.plural = arg2;
  2938. }
  2939. else if (isArray(arg2)) {
  2940. list = arg2;
  2941. }
  2942. else if (isPlainObject(arg2)) {
  2943. named = arg2;
  2944. }
  2945. if (isString(arg3)) {
  2946. options.locale = arg3;
  2947. }
  2948. else if (isArray(arg3)) {
  2949. list = arg3;
  2950. }
  2951. else if (isPlainObject(arg3)) {
  2952. named = arg3;
  2953. }
  2954. // return composer.t(key, (list || named || {}) as any, options)
  2955. return Reflect.apply(composer.t, composer, [
  2956. key,
  2957. (list || named || {}),
  2958. options
  2959. ]);
  2960. },
  2961. // te
  2962. te(key, locale) {
  2963. return composer.te(key, locale);
  2964. },
  2965. // tm
  2966. tm(key) {
  2967. return composer.tm(key);
  2968. },
  2969. // getLocaleMessage
  2970. getLocaleMessage(locale) {
  2971. return composer.getLocaleMessage(locale);
  2972. },
  2973. // setLocaleMessage
  2974. setLocaleMessage(locale, message) {
  2975. composer.setLocaleMessage(locale, message);
  2976. },
  2977. // mergeLocaleMessage
  2978. mergeLocaleMessage(locale, message) {
  2979. composer.mergeLocaleMessage(locale, message);
  2980. },
  2981. // d
  2982. d(...args) {
  2983. return Reflect.apply(composer.d, composer, [...args]);
  2984. },
  2985. // getDateTimeFormat
  2986. getDateTimeFormat(locale) {
  2987. return composer.getDateTimeFormat(locale);
  2988. },
  2989. // setDateTimeFormat
  2990. setDateTimeFormat(locale, format) {
  2991. composer.setDateTimeFormat(locale, format);
  2992. },
  2993. // mergeDateTimeFormat
  2994. mergeDateTimeFormat(locale, format) {
  2995. composer.mergeDateTimeFormat(locale, format);
  2996. },
  2997. // n
  2998. n(...args) {
  2999. return Reflect.apply(composer.n, composer, [...args]);
  3000. },
  3001. // getNumberFormat
  3002. getNumberFormat(locale) {
  3003. return composer.getNumberFormat(locale);
  3004. },
  3005. // setNumberFormat
  3006. setNumberFormat(locale, format) {
  3007. composer.setNumberFormat(locale, format);
  3008. },
  3009. // mergeNumberFormat
  3010. mergeNumberFormat(locale, format) {
  3011. composer.mergeNumberFormat(locale, format);
  3012. },
  3013. // getChoiceIndex
  3014. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  3015. getChoiceIndex(choice, choicesLength) {
  3016. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX));
  3017. return -1;
  3018. }
  3019. };
  3020. vueI18n.__extender = __extender;
  3021. // for vue-devtools timeline event
  3022. {
  3023. vueI18n.__enableEmitter = (emitter) => {
  3024. const __composer = composer;
  3025. __composer[EnableEmitter] && __composer[EnableEmitter](emitter);
  3026. };
  3027. vueI18n.__disableEmitter = () => {
  3028. const __composer = composer;
  3029. __composer[DisableEmitter] && __composer[DisableEmitter]();
  3030. };
  3031. }
  3032. return vueI18n;
  3033. }
  3034. }
  3035. /* eslint-enable @typescript-eslint/no-explicit-any */
  3036. const baseFormatProps = {
  3037. tag: {
  3038. type: [String, Object]
  3039. },
  3040. locale: {
  3041. type: String
  3042. },
  3043. scope: {
  3044. type: String,
  3045. // NOTE: avoid https://github.com/microsoft/rushstack/issues/1050
  3046. validator: (val /* ComponentI18nScope */) => val === 'parent' || val === 'global',
  3047. default: 'parent' /* ComponentI18nScope */
  3048. },
  3049. i18n: {
  3050. type: Object
  3051. }
  3052. };
  3053. function getInterpolateArg(
  3054. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3055. { slots }, // SetupContext,
  3056. keys) {
  3057. if (keys.length === 1 && keys[0] === 'default') {
  3058. // default slot with list
  3059. const ret = slots.default ? slots.default() : [];
  3060. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3061. return ret.reduce((slot, current) => {
  3062. return [
  3063. ...slot,
  3064. // prettier-ignore
  3065. ...(current.type === vue.Fragment ? current.children : [current]
  3066. )
  3067. ];
  3068. }, []);
  3069. }
  3070. else {
  3071. // named slots
  3072. return keys.reduce((arg, key) => {
  3073. const slot = slots[key];
  3074. if (slot) {
  3075. arg[key] = slot();
  3076. }
  3077. return arg;
  3078. }, {});
  3079. }
  3080. }
  3081. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3082. function getFragmentableTag(tag) {
  3083. return vue.Fragment ;
  3084. }
  3085. const TranslationImpl = /*#__PURE__*/ vue.defineComponent({
  3086. /* eslint-disable */
  3087. name: 'i18n-t',
  3088. props: assign({
  3089. keypath: {
  3090. type: String,
  3091. required: true
  3092. },
  3093. plural: {
  3094. type: [Number, String],
  3095. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3096. validator: (val) => isNumber(val) || !isNaN(val)
  3097. }
  3098. }, baseFormatProps),
  3099. /* eslint-enable */
  3100. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3101. setup(props, context) {
  3102. const { slots, attrs } = context;
  3103. // NOTE: avoid https://github.com/microsoft/rushstack/issues/1050
  3104. const i18n = props.i18n ||
  3105. useI18n({
  3106. useScope: props.scope,
  3107. __useComponent: true
  3108. });
  3109. return () => {
  3110. const keys = Object.keys(slots).filter(key => key !== '_');
  3111. const options = {};
  3112. if (props.locale) {
  3113. options.locale = props.locale;
  3114. }
  3115. if (props.plural !== undefined) {
  3116. options.plural = isString(props.plural) ? +props.plural : props.plural;
  3117. }
  3118. const arg = getInterpolateArg(context, keys);
  3119. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3120. const children = i18n[TranslateVNodeSymbol](props.keypath, arg, options);
  3121. const assignedAttrs = assign({}, attrs);
  3122. const tag = isString(props.tag) || isObject(props.tag)
  3123. ? props.tag
  3124. : getFragmentableTag();
  3125. return vue.h(tag, assignedAttrs, children);
  3126. };
  3127. }
  3128. });
  3129. /**
  3130. * export the public type for h/tsx inference
  3131. * also to avoid inline import() in generated d.ts files
  3132. */
  3133. /**
  3134. * Translation Component
  3135. *
  3136. * @remarks
  3137. * See the following items for property about details
  3138. *
  3139. * @VueI18nSee [TranslationProps](component#translationprops)
  3140. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  3141. * @VueI18nSee [Component Interpolation](../guide/advanced/component)
  3142. *
  3143. * @example
  3144. * ```html
  3145. * <div id="app">
  3146. * <!-- ... -->
  3147. * <i18n keypath="term" tag="label" for="tos">
  3148. * <a :href="url" target="_blank">{{ $t('tos') }}</a>
  3149. * </i18n>
  3150. * <!-- ... -->
  3151. * </div>
  3152. * ```
  3153. * ```js
  3154. * import { createApp } from 'vue'
  3155. * import { createI18n } from 'vue-i18n'
  3156. *
  3157. * const messages = {
  3158. * en: {
  3159. * tos: 'Term of Service',
  3160. * term: 'I accept xxx {0}.'
  3161. * },
  3162. * ja: {
  3163. * tos: '利用規約',
  3164. * term: '私は xxx の{0}に同意します。'
  3165. * }
  3166. * }
  3167. *
  3168. * const i18n = createI18n({
  3169. * locale: 'en',
  3170. * messages
  3171. * })
  3172. *
  3173. * const app = createApp({
  3174. * data: {
  3175. * url: '/term'
  3176. * }
  3177. * }).use(i18n).mount('#app')
  3178. * ```
  3179. *
  3180. * @VueI18nComponent
  3181. */
  3182. const Translation = TranslationImpl;
  3183. const I18nT = Translation;
  3184. function isVNode(target) {
  3185. return isArray(target) && !isString(target[0]);
  3186. }
  3187. function renderFormatter(props, context, slotKeys, partFormatter) {
  3188. const { slots, attrs } = context;
  3189. return () => {
  3190. const options = { part: true };
  3191. let overrides = {};
  3192. if (props.locale) {
  3193. options.locale = props.locale;
  3194. }
  3195. if (isString(props.format)) {
  3196. options.key = props.format;
  3197. }
  3198. else if (isObject(props.format)) {
  3199. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3200. if (isString(props.format.key)) {
  3201. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3202. options.key = props.format.key;
  3203. }
  3204. // Filter out number format options only
  3205. overrides = Object.keys(props.format).reduce((options, prop) => {
  3206. return slotKeys.includes(prop)
  3207. ? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
  3208. : options;
  3209. }, {});
  3210. }
  3211. const parts = partFormatter(...[props.value, options, overrides]);
  3212. let children = [options.key];
  3213. if (isArray(parts)) {
  3214. children = parts.map((part, index) => {
  3215. const slot = slots[part.type];
  3216. const node = slot
  3217. ? slot({ [part.type]: part.value, index, parts })
  3218. : [part.value];
  3219. if (isVNode(node)) {
  3220. node[0].key = `${part.type}-${index}`;
  3221. }
  3222. return node;
  3223. });
  3224. }
  3225. else if (isString(parts)) {
  3226. children = [parts];
  3227. }
  3228. const assignedAttrs = assign({}, attrs);
  3229. const tag = isString(props.tag) || isObject(props.tag)
  3230. ? props.tag
  3231. : getFragmentableTag();
  3232. return vue.h(tag, assignedAttrs, children);
  3233. };
  3234. }
  3235. const NumberFormatImpl = /*#__PURE__*/ vue.defineComponent({
  3236. /* eslint-disable */
  3237. name: 'i18n-n',
  3238. props: assign({
  3239. value: {
  3240. type: Number,
  3241. required: true
  3242. },
  3243. format: {
  3244. type: [String, Object]
  3245. }
  3246. }, baseFormatProps),
  3247. /* eslint-enable */
  3248. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3249. setup(props, context) {
  3250. const i18n = props.i18n ||
  3251. useI18n({
  3252. useScope: 'parent',
  3253. __useComponent: true
  3254. });
  3255. return renderFormatter(props, context, NUMBER_FORMAT_OPTIONS_KEYS, (...args) =>
  3256. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3257. i18n[NumberPartsSymbol](...args));
  3258. }
  3259. });
  3260. /**
  3261. * export the public type for h/tsx inference
  3262. * also to avoid inline import() in generated d.ts files
  3263. */
  3264. /**
  3265. * Number Format Component
  3266. *
  3267. * @remarks
  3268. * See the following items for property about details
  3269. *
  3270. * @VueI18nSee [FormattableProps](component#formattableprops)
  3271. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  3272. * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting)
  3273. *
  3274. * @VueI18nDanger
  3275. * Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts)
  3276. *
  3277. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)
  3278. *
  3279. * @VueI18nComponent
  3280. */
  3281. const NumberFormat = NumberFormatImpl;
  3282. const I18nN = NumberFormat;
  3283. const DatetimeFormatImpl = /* #__PURE__*/ vue.defineComponent({
  3284. /* eslint-disable */
  3285. name: 'i18n-d',
  3286. props: assign({
  3287. value: {
  3288. type: [Number, Date],
  3289. required: true
  3290. },
  3291. format: {
  3292. type: [String, Object]
  3293. }
  3294. }, baseFormatProps),
  3295. /* eslint-enable */
  3296. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3297. setup(props, context) {
  3298. const i18n = props.i18n ||
  3299. useI18n({
  3300. useScope: 'parent',
  3301. __useComponent: true
  3302. });
  3303. return renderFormatter(props, context, DATETIME_FORMAT_OPTIONS_KEYS, (...args) =>
  3304. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3305. i18n[DatetimePartsSymbol](...args));
  3306. }
  3307. });
  3308. /**
  3309. * Datetime Format Component
  3310. *
  3311. * @remarks
  3312. * See the following items for property about details
  3313. *
  3314. * @VueI18nSee [FormattableProps](component#formattableprops)
  3315. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  3316. * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting)
  3317. *
  3318. * @VueI18nDanger
  3319. * Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts)
  3320. *
  3321. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)
  3322. *
  3323. * @VueI18nComponent
  3324. */
  3325. const DatetimeFormat = DatetimeFormatImpl;
  3326. const I18nD = DatetimeFormat;
  3327. function getComposer$2(i18n, instance) {
  3328. const i18nInternal = i18n;
  3329. if (i18n.mode === 'composition') {
  3330. return (i18nInternal.__getInstance(instance) || i18n.global);
  3331. }
  3332. else {
  3333. const vueI18n = i18nInternal.__getInstance(instance);
  3334. return vueI18n != null
  3335. ? vueI18n.__composer
  3336. : i18n.global.__composer;
  3337. }
  3338. }
  3339. function vTDirective(i18n) {
  3340. const _process = (binding) => {
  3341. const { instance, modifiers, value } = binding;
  3342. /* istanbul ignore if */
  3343. if (!instance || !instance.$) {
  3344. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  3345. }
  3346. const composer = getComposer$2(i18n, instance.$);
  3347. if (modifiers.preserve) {
  3348. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE));
  3349. }
  3350. const parsedValue = parseValue(value);
  3351. return [
  3352. Reflect.apply(composer.t, composer, [...makeParams(parsedValue)]),
  3353. composer
  3354. ];
  3355. };
  3356. const register = (el, binding) => {
  3357. const [textContent, composer] = _process(binding);
  3358. if (inBrowser && i18n.global === composer) {
  3359. // global scope only
  3360. el.__i18nWatcher = vue.watch(composer.locale, () => {
  3361. binding.instance && binding.instance.$forceUpdate();
  3362. });
  3363. }
  3364. el.__composer = composer;
  3365. el.textContent = textContent;
  3366. };
  3367. const unregister = (el) => {
  3368. if (inBrowser && el.__i18nWatcher) {
  3369. el.__i18nWatcher();
  3370. el.__i18nWatcher = undefined;
  3371. delete el.__i18nWatcher;
  3372. }
  3373. if (el.__composer) {
  3374. el.__composer = undefined;
  3375. delete el.__composer;
  3376. }
  3377. };
  3378. const update = (el, { value }) => {
  3379. if (el.__composer) {
  3380. const composer = el.__composer;
  3381. const parsedValue = parseValue(value);
  3382. el.textContent = Reflect.apply(composer.t, composer, [
  3383. ...makeParams(parsedValue)
  3384. ]);
  3385. }
  3386. };
  3387. const getSSRProps = (binding) => {
  3388. const [textContent] = _process(binding);
  3389. return { textContent };
  3390. };
  3391. return {
  3392. created: register,
  3393. unmounted: unregister,
  3394. beforeUpdate: update,
  3395. getSSRProps
  3396. };
  3397. }
  3398. function parseValue(value) {
  3399. if (isString(value)) {
  3400. return { path: value };
  3401. }
  3402. else if (isPlainObject(value)) {
  3403. if (!('path' in value)) {
  3404. throw createI18nError(I18nErrorCodes.REQUIRED_VALUE, 'path');
  3405. }
  3406. return value;
  3407. }
  3408. else {
  3409. throw createI18nError(I18nErrorCodes.INVALID_VALUE);
  3410. }
  3411. }
  3412. function makeParams(value) {
  3413. const { path, locale, args, choice, plural } = value;
  3414. const options = {};
  3415. const named = args || {};
  3416. if (isString(locale)) {
  3417. options.locale = locale;
  3418. }
  3419. if (isNumber(choice)) {
  3420. options.plural = choice;
  3421. }
  3422. if (isNumber(plural)) {
  3423. options.plural = plural;
  3424. }
  3425. return [path, named, options];
  3426. }
  3427. function apply(app, i18n, ...options) {
  3428. const pluginOptions = isPlainObject(options[0])
  3429. ? options[0]
  3430. : {};
  3431. const useI18nComponentName = !!pluginOptions.useI18nComponentName;
  3432. const globalInstall = isBoolean(pluginOptions.globalInstall)
  3433. ? pluginOptions.globalInstall
  3434. : true;
  3435. if (globalInstall && useI18nComponentName) {
  3436. warn(getWarnMessage(I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE, {
  3437. name: Translation.name
  3438. }));
  3439. }
  3440. if (globalInstall) {
  3441. [!useI18nComponentName ? Translation.name : 'i18n', 'I18nT'].forEach(name => app.component(name, Translation));
  3442. [NumberFormat.name, 'I18nN'].forEach(name => app.component(name, NumberFormat));
  3443. [DatetimeFormat.name, 'I18nD'].forEach(name => app.component(name, DatetimeFormat));
  3444. }
  3445. // install directive
  3446. {
  3447. app.directive('t', vTDirective(i18n));
  3448. }
  3449. }
  3450. var global$1 = (typeof global !== "undefined" ? global :
  3451. typeof self !== "undefined" ? self :
  3452. typeof window !== "undefined" ? window : {});
  3453. function getDevtoolsGlobalHook() {
  3454. return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
  3455. }
  3456. function getTarget() {
  3457. // @ts-ignore
  3458. return (typeof navigator !== 'undefined' && typeof window !== 'undefined')
  3459. ? window
  3460. : typeof global$1 !== 'undefined'
  3461. ? global$1
  3462. : {};
  3463. }
  3464. const isProxyAvailable = typeof Proxy === 'function';
  3465. const HOOK_SETUP = 'devtools-plugin:setup';
  3466. const HOOK_PLUGIN_SETTINGS_SET = 'plugin:settings:set';
  3467. let supported;
  3468. let perf;
  3469. function isPerformanceSupported() {
  3470. var _a;
  3471. if (supported !== undefined) {
  3472. return supported;
  3473. }
  3474. if (typeof window !== 'undefined' && window.performance) {
  3475. supported = true;
  3476. perf = window.performance;
  3477. }
  3478. else if (typeof global$1 !== 'undefined' && ((_a = global$1.perf_hooks) === null || _a === void 0 ? void 0 : _a.performance)) {
  3479. supported = true;
  3480. perf = global$1.perf_hooks.performance;
  3481. }
  3482. else {
  3483. supported = false;
  3484. }
  3485. return supported;
  3486. }
  3487. function now() {
  3488. return isPerformanceSupported() ? perf.now() : Date.now();
  3489. }
  3490. class ApiProxy {
  3491. constructor(plugin, hook) {
  3492. this.target = null;
  3493. this.targetQueue = [];
  3494. this.onQueue = [];
  3495. this.plugin = plugin;
  3496. this.hook = hook;
  3497. const defaultSettings = {};
  3498. if (plugin.settings) {
  3499. for (const id in plugin.settings) {
  3500. const item = plugin.settings[id];
  3501. defaultSettings[id] = item.defaultValue;
  3502. }
  3503. }
  3504. const localSettingsSaveId = `__vue-devtools-plugin-settings__${plugin.id}`;
  3505. let currentSettings = Object.assign({}, defaultSettings);
  3506. try {
  3507. const raw = localStorage.getItem(localSettingsSaveId);
  3508. const data = JSON.parse(raw);
  3509. Object.assign(currentSettings, data);
  3510. }
  3511. catch (e) {
  3512. // noop
  3513. }
  3514. this.fallbacks = {
  3515. getSettings() {
  3516. return currentSettings;
  3517. },
  3518. setSettings(value) {
  3519. try {
  3520. localStorage.setItem(localSettingsSaveId, JSON.stringify(value));
  3521. }
  3522. catch (e) {
  3523. // noop
  3524. }
  3525. currentSettings = value;
  3526. },
  3527. now() {
  3528. return now();
  3529. },
  3530. };
  3531. if (hook) {
  3532. hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => {
  3533. if (pluginId === this.plugin.id) {
  3534. this.fallbacks.setSettings(value);
  3535. }
  3536. });
  3537. }
  3538. this.proxiedOn = new Proxy({}, {
  3539. get: (_target, prop) => {
  3540. if (this.target) {
  3541. return this.target.on[prop];
  3542. }
  3543. else {
  3544. return (...args) => {
  3545. this.onQueue.push({
  3546. method: prop,
  3547. args,
  3548. });
  3549. };
  3550. }
  3551. },
  3552. });
  3553. this.proxiedTarget = new Proxy({}, {
  3554. get: (_target, prop) => {
  3555. if (this.target) {
  3556. return this.target[prop];
  3557. }
  3558. else if (prop === 'on') {
  3559. return this.proxiedOn;
  3560. }
  3561. else if (Object.keys(this.fallbacks).includes(prop)) {
  3562. return (...args) => {
  3563. this.targetQueue.push({
  3564. method: prop,
  3565. args,
  3566. resolve: () => { },
  3567. });
  3568. return this.fallbacks[prop](...args);
  3569. };
  3570. }
  3571. else {
  3572. return (...args) => {
  3573. return new Promise(resolve => {
  3574. this.targetQueue.push({
  3575. method: prop,
  3576. args,
  3577. resolve,
  3578. });
  3579. });
  3580. };
  3581. }
  3582. },
  3583. });
  3584. }
  3585. async setRealTarget(target) {
  3586. this.target = target;
  3587. for (const item of this.onQueue) {
  3588. this.target.on[item.method](...item.args);
  3589. }
  3590. for (const item of this.targetQueue) {
  3591. item.resolve(await this.target[item.method](...item.args));
  3592. }
  3593. }
  3594. }
  3595. function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
  3596. const descriptor = pluginDescriptor;
  3597. const target = getTarget();
  3598. const hook = getDevtoolsGlobalHook();
  3599. const enableProxy = isProxyAvailable && descriptor.enableEarlyProxy;
  3600. if (hook && (target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__ || !enableProxy)) {
  3601. hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
  3602. }
  3603. else {
  3604. const proxy = enableProxy ? new ApiProxy(descriptor, hook) : null;
  3605. const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
  3606. list.push({
  3607. pluginDescriptor: descriptor,
  3608. setupFn,
  3609. proxy,
  3610. });
  3611. if (proxy)
  3612. setupFn(proxy.proxiedTarget);
  3613. }
  3614. }
  3615. const VueDevToolsLabels = {
  3616. ["vue-devtools-plugin-vue-i18n" /* VueDevToolsIDs.PLUGIN */]: 'Vue I18n devtools',
  3617. ["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]: 'I18n Resources',
  3618. ["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */]: 'Vue I18n'
  3619. };
  3620. const VueDevToolsPlaceholders = {
  3621. ["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]: 'Search for scopes ...'
  3622. };
  3623. const VueDevToolsTimelineColors = {
  3624. ["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */]: 0xffcd19
  3625. };
  3626. const VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties';
  3627. let devtoolsApi;
  3628. async function enableDevTools(app, i18n) {
  3629. return new Promise((resolve, reject) => {
  3630. try {
  3631. setupDevtoolsPlugin({
  3632. id: "vue-devtools-plugin-vue-i18n" /* VueDevToolsIDs.PLUGIN */,
  3633. label: VueDevToolsLabels["vue-devtools-plugin-vue-i18n" /* VueDevToolsIDs.PLUGIN */],
  3634. packageName: 'vue-i18n',
  3635. homepage: 'https://vue-i18n.intlify.dev',
  3636. logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png',
  3637. componentStateTypes: [VUE_I18N_COMPONENT_TYPES],
  3638. app: app // eslint-disable-line @typescript-eslint/no-explicit-any
  3639. }, api => {
  3640. devtoolsApi = api;
  3641. api.on.visitComponentTree(({ componentInstance, treeNode }) => {
  3642. updateComponentTreeTags(componentInstance, treeNode, i18n);
  3643. });
  3644. api.on.inspectComponent(({ componentInstance, instanceData }) => {
  3645. if (componentInstance.vnode.el &&
  3646. componentInstance.vnode.el.__VUE_I18N__ &&
  3647. instanceData) {
  3648. if (i18n.mode === 'legacy') {
  3649. // ignore global scope on legacy mode
  3650. if (componentInstance.vnode.el.__VUE_I18N__ !==
  3651. i18n.global.__composer) {
  3652. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  3653. }
  3654. }
  3655. else {
  3656. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  3657. }
  3658. }
  3659. });
  3660. api.addInspector({
  3661. id: "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */,
  3662. label: VueDevToolsLabels["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */],
  3663. icon: 'language',
  3664. treeFilterPlaceholder: VueDevToolsPlaceholders["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]
  3665. });
  3666. api.on.getInspectorTree(payload => {
  3667. if (payload.app === app &&
  3668. payload.inspectorId === "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {
  3669. registerScope(payload, i18n);
  3670. }
  3671. });
  3672. const roots = new Map();
  3673. api.on.getInspectorState(async (payload) => {
  3674. if (payload.app === app &&
  3675. payload.inspectorId === "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {
  3676. api.unhighlightElement();
  3677. inspectScope(payload, i18n);
  3678. if (payload.nodeId === 'global') {
  3679. if (!roots.has(payload.app)) {
  3680. const [root] = await api.getComponentInstances(payload.app);
  3681. roots.set(payload.app, root);
  3682. }
  3683. api.highlightElement(roots.get(payload.app));
  3684. }
  3685. else {
  3686. const instance = getComponentInstance(payload.nodeId, i18n);
  3687. instance && api.highlightElement(instance);
  3688. }
  3689. }
  3690. });
  3691. api.on.editInspectorState(payload => {
  3692. if (payload.app === app &&
  3693. payload.inspectorId === "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {
  3694. editScope(payload, i18n);
  3695. }
  3696. });
  3697. api.addTimelineLayer({
  3698. id: "vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */,
  3699. label: VueDevToolsLabels["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */],
  3700. color: VueDevToolsTimelineColors["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */]
  3701. });
  3702. resolve(true);
  3703. });
  3704. }
  3705. catch (e) {
  3706. console.error(e);
  3707. reject(false);
  3708. }
  3709. });
  3710. }
  3711. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3712. function getI18nScopeLable(instance) {
  3713. return (instance.type.name ||
  3714. instance.type.displayName ||
  3715. instance.type.__file ||
  3716. 'Anonymous');
  3717. }
  3718. function updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any
  3719. treeNode, i18n) {
  3720. // prettier-ignore
  3721. const global = i18n.mode === 'composition'
  3722. ? i18n.global
  3723. : i18n.global.__composer;
  3724. if (instance && instance.vnode.el && instance.vnode.el.__VUE_I18N__) {
  3725. // add custom tags local scope only
  3726. if (instance.vnode.el.__VUE_I18N__ !== global) {
  3727. const tag = {
  3728. label: `i18n (${getI18nScopeLable(instance)} Scope)`,
  3729. textColor: 0x000000,
  3730. backgroundColor: 0xffcd19
  3731. };
  3732. treeNode.tags.push(tag);
  3733. }
  3734. }
  3735. }
  3736. function inspectComposer(instanceData, composer) {
  3737. const type = VUE_I18N_COMPONENT_TYPES;
  3738. instanceData.state.push({
  3739. type,
  3740. key: 'locale',
  3741. editable: true,
  3742. value: composer.locale.value
  3743. });
  3744. instanceData.state.push({
  3745. type,
  3746. key: 'availableLocales',
  3747. editable: false,
  3748. value: composer.availableLocales
  3749. });
  3750. instanceData.state.push({
  3751. type,
  3752. key: 'fallbackLocale',
  3753. editable: true,
  3754. value: composer.fallbackLocale.value
  3755. });
  3756. instanceData.state.push({
  3757. type,
  3758. key: 'inheritLocale',
  3759. editable: true,
  3760. value: composer.inheritLocale
  3761. });
  3762. instanceData.state.push({
  3763. type,
  3764. key: 'messages',
  3765. editable: false,
  3766. value: getLocaleMessageValue(composer.messages.value)
  3767. });
  3768. {
  3769. instanceData.state.push({
  3770. type,
  3771. key: 'datetimeFormats',
  3772. editable: false,
  3773. value: composer.datetimeFormats.value
  3774. });
  3775. instanceData.state.push({
  3776. type,
  3777. key: 'numberFormats',
  3778. editable: false,
  3779. value: composer.numberFormats.value
  3780. });
  3781. }
  3782. }
  3783. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3784. function getLocaleMessageValue(messages) {
  3785. const value = {};
  3786. Object.keys(messages).forEach((key) => {
  3787. const v = messages[key];
  3788. if (isFunction(v) && 'source' in v) {
  3789. value[key] = getMessageFunctionDetails(v);
  3790. }
  3791. else if (isMessageAST(v) && v.loc && v.loc.source) {
  3792. value[key] = v.loc.source;
  3793. }
  3794. else if (isObject(v)) {
  3795. value[key] = getLocaleMessageValue(v);
  3796. }
  3797. else {
  3798. value[key] = v;
  3799. }
  3800. });
  3801. return value;
  3802. }
  3803. const ESC = {
  3804. '<': '&lt;',
  3805. '>': '&gt;',
  3806. '"': '&quot;',
  3807. '&': '&amp;'
  3808. };
  3809. function escape(s) {
  3810. return s.replace(/[<>"&]/g, escapeChar);
  3811. }
  3812. function escapeChar(a) {
  3813. return ESC[a] || a;
  3814. }
  3815. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3816. function getMessageFunctionDetails(func) {
  3817. const argString = func.source ? `("${escape(func.source)}")` : `(?)`;
  3818. return {
  3819. _custom: {
  3820. type: 'function',
  3821. display: `<span>ƒ</span> ${argString}`
  3822. }
  3823. };
  3824. }
  3825. function registerScope(payload, i18n) {
  3826. payload.rootNodes.push({
  3827. id: 'global',
  3828. label: 'Global Scope'
  3829. });
  3830. // prettier-ignore
  3831. const global = i18n.mode === 'composition'
  3832. ? i18n.global
  3833. : i18n.global.__composer;
  3834. for (const [keyInstance, instance] of i18n.__instances) {
  3835. // prettier-ignore
  3836. const composer = i18n.mode === 'composition'
  3837. ? instance
  3838. : instance.__composer;
  3839. if (global === composer) {
  3840. continue;
  3841. }
  3842. payload.rootNodes.push({
  3843. id: composer.id.toString(),
  3844. label: `${getI18nScopeLable(keyInstance)} Scope`
  3845. });
  3846. }
  3847. }
  3848. function getComponentInstance(nodeId, i18n) {
  3849. let instance = null;
  3850. if (nodeId !== 'global') {
  3851. for (const [component, composer] of i18n.__instances.entries()) {
  3852. if (composer.id.toString() === nodeId) {
  3853. instance = component;
  3854. break;
  3855. }
  3856. }
  3857. }
  3858. return instance;
  3859. }
  3860. function getComposer$1(nodeId, i18n) {
  3861. if (nodeId === 'global') {
  3862. return i18n.mode === 'composition'
  3863. ? i18n.global
  3864. : i18n.global.__composer;
  3865. }
  3866. else {
  3867. const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId);
  3868. if (instance) {
  3869. return i18n.mode === 'composition'
  3870. ? instance
  3871. : instance.__composer;
  3872. }
  3873. else {
  3874. return null;
  3875. }
  3876. }
  3877. }
  3878. function inspectScope(payload, i18n
  3879. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3880. ) {
  3881. const composer = getComposer$1(payload.nodeId, i18n);
  3882. if (composer) {
  3883. // TODO:
  3884. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3885. payload.state = makeScopeInspectState(composer);
  3886. }
  3887. return null;
  3888. }
  3889. function makeScopeInspectState(composer) {
  3890. const state = {};
  3891. const localeType = 'Locale related info';
  3892. const localeStates = [
  3893. {
  3894. type: localeType,
  3895. key: 'locale',
  3896. editable: true,
  3897. value: composer.locale.value
  3898. },
  3899. {
  3900. type: localeType,
  3901. key: 'fallbackLocale',
  3902. editable: true,
  3903. value: composer.fallbackLocale.value
  3904. },
  3905. {
  3906. type: localeType,
  3907. key: 'availableLocales',
  3908. editable: false,
  3909. value: composer.availableLocales
  3910. },
  3911. {
  3912. type: localeType,
  3913. key: 'inheritLocale',
  3914. editable: true,
  3915. value: composer.inheritLocale
  3916. }
  3917. ];
  3918. state[localeType] = localeStates;
  3919. const localeMessagesType = 'Locale messages info';
  3920. const localeMessagesStates = [
  3921. {
  3922. type: localeMessagesType,
  3923. key: 'messages',
  3924. editable: false,
  3925. value: getLocaleMessageValue(composer.messages.value)
  3926. }
  3927. ];
  3928. state[localeMessagesType] = localeMessagesStates;
  3929. {
  3930. const datetimeFormatsType = 'Datetime formats info';
  3931. const datetimeFormatsStates = [
  3932. {
  3933. type: datetimeFormatsType,
  3934. key: 'datetimeFormats',
  3935. editable: false,
  3936. value: composer.datetimeFormats.value
  3937. }
  3938. ];
  3939. state[datetimeFormatsType] = datetimeFormatsStates;
  3940. const numberFormatsType = 'Datetime formats info';
  3941. const numberFormatsStates = [
  3942. {
  3943. type: numberFormatsType,
  3944. key: 'numberFormats',
  3945. editable: false,
  3946. value: composer.numberFormats.value
  3947. }
  3948. ];
  3949. state[numberFormatsType] = numberFormatsStates;
  3950. }
  3951. return state;
  3952. }
  3953. function addTimelineEvent(event, payload) {
  3954. if (devtoolsApi) {
  3955. let groupId;
  3956. if (payload && 'groupId' in payload) {
  3957. groupId = payload.groupId;
  3958. delete payload.groupId;
  3959. }
  3960. devtoolsApi.addTimelineEvent({
  3961. layerId: "vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */,
  3962. event: {
  3963. title: event,
  3964. groupId,
  3965. time: Date.now(),
  3966. meta: {},
  3967. data: payload || {},
  3968. logType: event === "compile-error" /* VueDevToolsTimelineEvents.COMPILE_ERROR */
  3969. ? 'error'
  3970. : event === "fallback" /* VueDevToolsTimelineEvents.FALBACK */ ||
  3971. event === "missing" /* VueDevToolsTimelineEvents.MISSING */
  3972. ? 'warning'
  3973. : 'default'
  3974. }
  3975. });
  3976. }
  3977. }
  3978. function editScope(payload, i18n) {
  3979. const composer = getComposer$1(payload.nodeId, i18n);
  3980. if (composer) {
  3981. const [field] = payload.path;
  3982. if (field === 'locale' && isString(payload.state.value)) {
  3983. composer.locale.value = payload.state.value;
  3984. }
  3985. else if (field === 'fallbackLocale' &&
  3986. (isString(payload.state.value) ||
  3987. isArray(payload.state.value) ||
  3988. isObject(payload.state.value))) {
  3989. composer.fallbackLocale.value = payload.state.value;
  3990. }
  3991. else if (field === 'inheritLocale' && isBoolean(payload.state.value)) {
  3992. composer.inheritLocale = payload.state.value;
  3993. }
  3994. }
  3995. }
  3996. /**
  3997. * Supports compatibility for legacy vue-i18n APIs
  3998. * This mixin is used when we use vue-i18n@v9.x or later
  3999. */
  4000. function defineMixin(vuei18n, composer, i18n) {
  4001. return {
  4002. beforeCreate() {
  4003. const instance = vue.getCurrentInstance();
  4004. /* istanbul ignore if */
  4005. if (!instance) {
  4006. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  4007. }
  4008. const options = this.$options;
  4009. if (options.i18n) {
  4010. const optionsI18n = options.i18n;
  4011. if (options.__i18n) {
  4012. optionsI18n.__i18n = options.__i18n;
  4013. }
  4014. optionsI18n.__root = composer;
  4015. if (this === this.$root) {
  4016. // merge option and gttach global
  4017. this.$i18n = mergeToGlobal(vuei18n, optionsI18n);
  4018. }
  4019. else {
  4020. optionsI18n.__injectWithOption = true;
  4021. optionsI18n.__extender = i18n.__vueI18nExtend;
  4022. // atttach local VueI18n instance
  4023. this.$i18n = createVueI18n(optionsI18n);
  4024. // extend VueI18n instance
  4025. const _vueI18n = this.$i18n;
  4026. if (_vueI18n.__extender) {
  4027. _vueI18n.__disposer = _vueI18n.__extender(this.$i18n);
  4028. }
  4029. }
  4030. }
  4031. else if (options.__i18n) {
  4032. if (this === this.$root) {
  4033. // merge option and gttach global
  4034. this.$i18n = mergeToGlobal(vuei18n, options);
  4035. }
  4036. else {
  4037. // atttach local VueI18n instance
  4038. this.$i18n = createVueI18n({
  4039. __i18n: options.__i18n,
  4040. __injectWithOption: true,
  4041. __extender: i18n.__vueI18nExtend,
  4042. __root: composer
  4043. });
  4044. // extend VueI18n instance
  4045. const _vueI18n = this.$i18n;
  4046. if (_vueI18n.__extender) {
  4047. _vueI18n.__disposer = _vueI18n.__extender(this.$i18n);
  4048. }
  4049. }
  4050. }
  4051. else {
  4052. // attach global VueI18n instance
  4053. this.$i18n = vuei18n;
  4054. }
  4055. if (options.__i18nGlobal) {
  4056. adjustI18nResources(composer, options, options);
  4057. }
  4058. // defines vue-i18n legacy APIs
  4059. this.$t = (...args) => this.$i18n.t(...args);
  4060. this.$rt = (...args) => this.$i18n.rt(...args);
  4061. this.$tc = (...args) => this.$i18n.tc(...args);
  4062. this.$te = (key, locale) => this.$i18n.te(key, locale);
  4063. this.$d = (...args) => this.$i18n.d(...args);
  4064. this.$n = (...args) => this.$i18n.n(...args);
  4065. this.$tm = (key) => this.$i18n.tm(key);
  4066. i18n.__setInstance(instance, this.$i18n);
  4067. },
  4068. mounted() {
  4069. /* istanbul ignore if */
  4070. if (this.$el &&
  4071. this.$i18n) {
  4072. const _vueI18n = this.$i18n;
  4073. this.$el.__VUE_I18N__ = _vueI18n.__composer;
  4074. const emitter = (this.__v_emitter =
  4075. createEmitter());
  4076. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  4077. emitter.on('*', addTimelineEvent);
  4078. }
  4079. },
  4080. unmounted() {
  4081. const instance = vue.getCurrentInstance();
  4082. /* istanbul ignore if */
  4083. if (!instance) {
  4084. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  4085. }
  4086. const _vueI18n = this.$i18n;
  4087. /* istanbul ignore if */
  4088. if (this.$el &&
  4089. this.$el.__VUE_I18N__) {
  4090. if (this.__v_emitter) {
  4091. this.__v_emitter.off('*', addTimelineEvent);
  4092. delete this.__v_emitter;
  4093. }
  4094. if (this.$i18n) {
  4095. _vueI18n.__disableEmitter && _vueI18n.__disableEmitter();
  4096. delete this.$el.__VUE_I18N__;
  4097. }
  4098. }
  4099. delete this.$t;
  4100. delete this.$rt;
  4101. delete this.$tc;
  4102. delete this.$te;
  4103. delete this.$d;
  4104. delete this.$n;
  4105. delete this.$tm;
  4106. if (_vueI18n.__disposer) {
  4107. _vueI18n.__disposer();
  4108. delete _vueI18n.__disposer;
  4109. delete _vueI18n.__extender;
  4110. }
  4111. i18n.__deleteInstance(instance);
  4112. delete this.$i18n;
  4113. }
  4114. };
  4115. }
  4116. function mergeToGlobal(g, options) {
  4117. g.locale = options.locale || g.locale;
  4118. g.fallbackLocale = options.fallbackLocale || g.fallbackLocale;
  4119. g.missing = options.missing || g.missing;
  4120. g.silentTranslationWarn =
  4121. options.silentTranslationWarn || g.silentFallbackWarn;
  4122. g.silentFallbackWarn = options.silentFallbackWarn || g.silentFallbackWarn;
  4123. g.formatFallbackMessages =
  4124. options.formatFallbackMessages || g.formatFallbackMessages;
  4125. g.postTranslation = options.postTranslation || g.postTranslation;
  4126. g.warnHtmlInMessage = options.warnHtmlInMessage || g.warnHtmlInMessage;
  4127. g.escapeParameterHtml = options.escapeParameterHtml || g.escapeParameterHtml;
  4128. g.sync = options.sync || g.sync;
  4129. g.__composer[SetPluralRulesSymbol](options.pluralizationRules || g.pluralizationRules);
  4130. const messages = getLocaleMessages(g.locale, {
  4131. messages: options.messages,
  4132. __i18n: options.__i18n
  4133. });
  4134. Object.keys(messages).forEach(locale => g.mergeLocaleMessage(locale, messages[locale]));
  4135. if (options.datetimeFormats) {
  4136. Object.keys(options.datetimeFormats).forEach(locale => g.mergeDateTimeFormat(locale, options.datetimeFormats[locale]));
  4137. }
  4138. if (options.numberFormats) {
  4139. Object.keys(options.numberFormats).forEach(locale => g.mergeNumberFormat(locale, options.numberFormats[locale]));
  4140. }
  4141. return g;
  4142. }
  4143. /**
  4144. * Injection key for {@link useI18n}
  4145. *
  4146. * @remarks
  4147. * The global injection key for I18n instances with `useI18n`. this injection key is used in Web Components.
  4148. * Specify the i18n instance created by {@link createI18n} together with `provide` function.
  4149. *
  4150. * @VueI18nGeneral
  4151. */
  4152. const I18nInjectionKey =
  4153. /* #__PURE__*/ makeSymbol('global-vue-i18n');
  4154. // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
  4155. function createI18n(options = {}, VueI18nLegacy) {
  4156. // prettier-ignore
  4157. const __legacyMode = isBoolean(options.legacy)
  4158. ? options.legacy
  4159. : true;
  4160. // prettier-ignore
  4161. const __globalInjection = isBoolean(options.globalInjection)
  4162. ? options.globalInjection
  4163. : true;
  4164. // prettier-ignore
  4165. const __allowComposition = __legacyMode
  4166. ? !!options.allowComposition
  4167. : true;
  4168. const __instances = new Map();
  4169. const [globalScope, __global] = createGlobal(options, __legacyMode);
  4170. const symbol = /* #__PURE__*/ makeSymbol('vue-i18n' );
  4171. {
  4172. if (__legacyMode && __allowComposition && !false) {
  4173. warn(getWarnMessage(I18nWarnCodes.NOTICE_DROP_ALLOW_COMPOSITION));
  4174. }
  4175. }
  4176. function __getInstance(component) {
  4177. return __instances.get(component) || null;
  4178. }
  4179. function __setInstance(component, instance) {
  4180. __instances.set(component, instance);
  4181. }
  4182. function __deleteInstance(component) {
  4183. __instances.delete(component);
  4184. }
  4185. {
  4186. const i18n = {
  4187. // mode
  4188. get mode() {
  4189. return __legacyMode
  4190. ? 'legacy'
  4191. : 'composition';
  4192. },
  4193. // allowComposition
  4194. get allowComposition() {
  4195. return __allowComposition;
  4196. },
  4197. // install plugin
  4198. async install(app, ...options) {
  4199. {
  4200. app.__VUE_I18N__ = i18n;
  4201. }
  4202. // setup global provider
  4203. app.__VUE_I18N_SYMBOL__ = symbol;
  4204. app.provide(app.__VUE_I18N_SYMBOL__, i18n);
  4205. // set composer & vuei18n extend hook options from plugin options
  4206. if (isPlainObject(options[0])) {
  4207. const opts = options[0];
  4208. i18n.__composerExtend =
  4209. opts.__composerExtend;
  4210. i18n.__vueI18nExtend =
  4211. opts.__vueI18nExtend;
  4212. }
  4213. // global method and properties injection for Composition API
  4214. let globalReleaseHandler = null;
  4215. if (!__legacyMode && __globalInjection) {
  4216. globalReleaseHandler = injectGlobalFields(app, i18n.global);
  4217. }
  4218. // install built-in components and directive
  4219. {
  4220. apply(app, i18n, ...options);
  4221. }
  4222. // setup mixin for Legacy API
  4223. if (__legacyMode) {
  4224. app.mixin(defineMixin(__global, __global.__composer, i18n));
  4225. }
  4226. // release global scope
  4227. const unmountApp = app.unmount;
  4228. app.unmount = () => {
  4229. globalReleaseHandler && globalReleaseHandler();
  4230. i18n.dispose();
  4231. unmountApp();
  4232. };
  4233. // setup vue-devtools plugin
  4234. {
  4235. const ret = await enableDevTools(app, i18n);
  4236. if (!ret) {
  4237. throw createI18nError(I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN);
  4238. }
  4239. const emitter = createEmitter();
  4240. if (__legacyMode) {
  4241. const _vueI18n = __global;
  4242. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  4243. }
  4244. else {
  4245. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4246. const _composer = __global;
  4247. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  4248. }
  4249. emitter.on('*', addTimelineEvent);
  4250. }
  4251. },
  4252. // global accessor
  4253. get global() {
  4254. return __global;
  4255. },
  4256. dispose() {
  4257. globalScope.stop();
  4258. },
  4259. // @internal
  4260. __instances,
  4261. // @internal
  4262. __getInstance,
  4263. // @internal
  4264. __setInstance,
  4265. // @internal
  4266. __deleteInstance
  4267. };
  4268. return i18n;
  4269. }
  4270. }
  4271. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  4272. function useI18n(options = {}) {
  4273. const instance = vue.getCurrentInstance();
  4274. if (instance == null) {
  4275. throw createI18nError(I18nErrorCodes.MUST_BE_CALL_SETUP_TOP);
  4276. }
  4277. if (!instance.isCE &&
  4278. instance.appContext.app != null &&
  4279. !instance.appContext.app.__VUE_I18N_SYMBOL__) {
  4280. throw createI18nError(I18nErrorCodes.NOT_INSTALLED);
  4281. }
  4282. const i18n = getI18nInstance(instance);
  4283. const gl = getGlobalComposer(i18n);
  4284. const componentOptions = getComponentOptions(instance);
  4285. const scope = getScope(options, componentOptions);
  4286. {
  4287. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4288. if (i18n.mode === 'legacy' && !options.__useComponent) {
  4289. if (!i18n.allowComposition) {
  4290. throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE);
  4291. }
  4292. return useI18nForLegacy(instance, scope, gl, options);
  4293. }
  4294. }
  4295. if (scope === 'global') {
  4296. adjustI18nResources(gl, options, componentOptions);
  4297. return gl;
  4298. }
  4299. if (scope === 'parent') {
  4300. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4301. let composer = getComposer(i18n, instance, options.__useComponent);
  4302. if (composer == null) {
  4303. {
  4304. warn(getWarnMessage(I18nWarnCodes.NOT_FOUND_PARENT_SCOPE));
  4305. }
  4306. composer = gl;
  4307. }
  4308. return composer;
  4309. }
  4310. const i18nInternal = i18n;
  4311. let composer = i18nInternal.__getInstance(instance);
  4312. if (composer == null) {
  4313. const composerOptions = assign({}, options);
  4314. if ('__i18n' in componentOptions) {
  4315. composerOptions.__i18n = componentOptions.__i18n;
  4316. }
  4317. if (gl) {
  4318. composerOptions.__root = gl;
  4319. }
  4320. composer = createComposer(composerOptions);
  4321. if (i18nInternal.__composerExtend) {
  4322. composer[DisposeSymbol] =
  4323. i18nInternal.__composerExtend(composer);
  4324. }
  4325. setupLifeCycle(i18nInternal, instance, composer);
  4326. i18nInternal.__setInstance(instance, composer);
  4327. }
  4328. return composer;
  4329. }
  4330. /**
  4331. * Cast to VueI18n legacy compatible type
  4332. *
  4333. * @remarks
  4334. * This API is provided only with [vue-i18n-bridge](https://vue-i18n.intlify.dev/guide/migration/ways.html#what-is-vue-i18n-bridge).
  4335. *
  4336. * The purpose of this function is to convert an {@link I18n} instance created with {@link createI18n | createI18n(legacy: true)} into a `vue-i18n@v8.x` compatible instance of `new VueI18n` in a TypeScript environment.
  4337. *
  4338. * @param i18n - An instance of {@link I18n}
  4339. * @returns A i18n instance which is casted to {@link VueI18n} type
  4340. *
  4341. * @VueI18nTip
  4342. * :new: provided by **vue-i18n-bridge only**
  4343. *
  4344. * @VueI18nGeneral
  4345. */
  4346. /* #__NO_SIDE_EFFECTS__ */
  4347. const castToVueI18n = (i18n
  4348. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4349. ) => {
  4350. if (!(__VUE_I18N_BRIDGE__ in i18n)) {
  4351. throw createI18nError(I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N);
  4352. }
  4353. return i18n;
  4354. };
  4355. function createGlobal(options, legacyMode, VueI18nLegacy // eslint-disable-line @typescript-eslint/no-explicit-any
  4356. ) {
  4357. const scope = vue.effectScope();
  4358. {
  4359. const obj = legacyMode
  4360. ? scope.run(() => createVueI18n(options))
  4361. : scope.run(() => createComposer(options));
  4362. if (obj == null) {
  4363. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  4364. }
  4365. return [scope, obj];
  4366. }
  4367. }
  4368. function getI18nInstance(instance) {
  4369. {
  4370. const i18n = vue.inject(!instance.isCE
  4371. ? instance.appContext.app.__VUE_I18N_SYMBOL__
  4372. : I18nInjectionKey);
  4373. /* istanbul ignore if */
  4374. if (!i18n) {
  4375. throw createI18nError(!instance.isCE
  4376. ? I18nErrorCodes.UNEXPECTED_ERROR
  4377. : I18nErrorCodes.NOT_INSTALLED_WITH_PROVIDE);
  4378. }
  4379. return i18n;
  4380. }
  4381. }
  4382. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4383. function getScope(options, componentOptions) {
  4384. // prettier-ignore
  4385. return isEmptyObject(options)
  4386. ? ('__i18n' in componentOptions)
  4387. ? 'local'
  4388. : 'global'
  4389. : !options.useScope
  4390. ? 'local'
  4391. : options.useScope;
  4392. }
  4393. function getGlobalComposer(i18n) {
  4394. // prettier-ignore
  4395. return i18n.mode === 'composition'
  4396. ? i18n.global
  4397. : i18n.global.__composer
  4398. ;
  4399. }
  4400. function getComposer(i18n, target, useComponent = false) {
  4401. let composer = null;
  4402. const root = target.root;
  4403. let current = getParentComponentInstance(target, useComponent);
  4404. while (current != null) {
  4405. const i18nInternal = i18n;
  4406. if (i18n.mode === 'composition') {
  4407. composer = i18nInternal.__getInstance(current);
  4408. }
  4409. else {
  4410. {
  4411. const vueI18n = i18nInternal.__getInstance(current);
  4412. if (vueI18n != null) {
  4413. composer = vueI18n
  4414. .__composer;
  4415. if (useComponent &&
  4416. composer &&
  4417. !composer[InejctWithOptionSymbol] // eslint-disable-line @typescript-eslint/no-explicit-any
  4418. ) {
  4419. composer = null;
  4420. }
  4421. }
  4422. }
  4423. }
  4424. if (composer != null) {
  4425. break;
  4426. }
  4427. if (root === current) {
  4428. break;
  4429. }
  4430. current = current.parent;
  4431. }
  4432. return composer;
  4433. }
  4434. function getParentComponentInstance(target, useComponent = false) {
  4435. if (target == null) {
  4436. return null;
  4437. }
  4438. {
  4439. // if `useComponent: true` will be specified, we get lexical scope owner instance for use-case slots
  4440. return !useComponent
  4441. ? target.parent
  4442. : target.vnode.ctx || target.parent; // eslint-disable-line @typescript-eslint/no-explicit-any
  4443. }
  4444. }
  4445. function setupLifeCycle(i18n, target, composer) {
  4446. let emitter = null;
  4447. {
  4448. vue.onMounted(() => {
  4449. // inject composer instance to DOM for intlify-devtools
  4450. if (target.vnode.el) {
  4451. target.vnode.el.__VUE_I18N__ = composer;
  4452. emitter = createEmitter();
  4453. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4454. const _composer = composer;
  4455. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  4456. emitter.on('*', addTimelineEvent);
  4457. }
  4458. }, target);
  4459. vue.onUnmounted(() => {
  4460. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4461. const _composer = composer;
  4462. // remove composer instance from DOM for intlify-devtools
  4463. if (target.vnode.el &&
  4464. target.vnode.el.__VUE_I18N__) {
  4465. emitter && emitter.off('*', addTimelineEvent);
  4466. _composer[DisableEmitter] && _composer[DisableEmitter]();
  4467. delete target.vnode.el.__VUE_I18N__;
  4468. }
  4469. i18n.__deleteInstance(target);
  4470. // dispose extended resources
  4471. const dispose = _composer[DisposeSymbol];
  4472. if (dispose) {
  4473. dispose();
  4474. delete _composer[DisposeSymbol];
  4475. }
  4476. }, target);
  4477. }
  4478. }
  4479. function useI18nForLegacy(instance, scope, root, options = {} // eslint-disable-line @typescript-eslint/no-explicit-any
  4480. ) {
  4481. const isLocalScope = scope === 'local';
  4482. const _composer = vue.shallowRef(null);
  4483. if (isLocalScope &&
  4484. instance.proxy &&
  4485. !(instance.proxy.$options.i18n || instance.proxy.$options.__i18n)) {
  4486. throw createI18nError(I18nErrorCodes.MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION);
  4487. }
  4488. const _inheritLocale = isBoolean(options.inheritLocale)
  4489. ? options.inheritLocale
  4490. : !isString(options.locale);
  4491. const _locale = vue.ref(
  4492. // prettier-ignore
  4493. !isLocalScope || _inheritLocale
  4494. ? root.locale.value
  4495. : isString(options.locale)
  4496. ? options.locale
  4497. : DEFAULT_LOCALE);
  4498. const _fallbackLocale = vue.ref(
  4499. // prettier-ignore
  4500. !isLocalScope || _inheritLocale
  4501. ? root.fallbackLocale.value
  4502. : isString(options.fallbackLocale) ||
  4503. isArray(options.fallbackLocale) ||
  4504. isPlainObject(options.fallbackLocale) ||
  4505. options.fallbackLocale === false
  4506. ? options.fallbackLocale
  4507. : _locale.value);
  4508. const _messages = vue.ref(getLocaleMessages(_locale.value, options));
  4509. // prettier-ignore
  4510. const _datetimeFormats = vue.ref(isPlainObject(options.datetimeFormats)
  4511. ? options.datetimeFormats
  4512. : { [_locale.value]: {} });
  4513. // prettier-ignore
  4514. const _numberFormats = vue.ref(isPlainObject(options.numberFormats)
  4515. ? options.numberFormats
  4516. : { [_locale.value]: {} });
  4517. // prettier-ignore
  4518. const _missingWarn = isLocalScope
  4519. ? root.missingWarn
  4520. : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  4521. ? options.missingWarn
  4522. : true;
  4523. // prettier-ignore
  4524. const _fallbackWarn = isLocalScope
  4525. ? root.fallbackWarn
  4526. : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  4527. ? options.fallbackWarn
  4528. : true;
  4529. // prettier-ignore
  4530. const _fallbackRoot = isLocalScope
  4531. ? root.fallbackRoot
  4532. : isBoolean(options.fallbackRoot)
  4533. ? options.fallbackRoot
  4534. : true;
  4535. // configure fall back to root
  4536. const _fallbackFormat = !!options.fallbackFormat;
  4537. // runtime missing
  4538. const _missing = isFunction(options.missing) ? options.missing : null;
  4539. // postTranslation handler
  4540. const _postTranslation = isFunction(options.postTranslation)
  4541. ? options.postTranslation
  4542. : null;
  4543. // prettier-ignore
  4544. const _warnHtmlMessage = isLocalScope
  4545. ? root.warnHtmlMessage
  4546. : isBoolean(options.warnHtmlMessage)
  4547. ? options.warnHtmlMessage
  4548. : true;
  4549. const _escapeParameter = !!options.escapeParameter;
  4550. // prettier-ignore
  4551. const _modifiers = isLocalScope
  4552. ? root.modifiers
  4553. : isPlainObject(options.modifiers)
  4554. ? options.modifiers
  4555. : {};
  4556. // pluralRules
  4557. const _pluralRules = options.pluralRules || (isLocalScope && root.pluralRules);
  4558. // track reactivity
  4559. function trackReactivityValues() {
  4560. return [
  4561. _locale.value,
  4562. _fallbackLocale.value,
  4563. _messages.value,
  4564. _datetimeFormats.value,
  4565. _numberFormats.value
  4566. ];
  4567. }
  4568. // locale
  4569. const locale = vue.computed({
  4570. get: () => {
  4571. return _composer.value ? _composer.value.locale.value : _locale.value;
  4572. },
  4573. set: val => {
  4574. if (_composer.value) {
  4575. _composer.value.locale.value = val;
  4576. }
  4577. _locale.value = val;
  4578. }
  4579. });
  4580. // fallbackLocale
  4581. const fallbackLocale = vue.computed({
  4582. get: () => {
  4583. return _composer.value
  4584. ? _composer.value.fallbackLocale.value
  4585. : _fallbackLocale.value;
  4586. },
  4587. set: val => {
  4588. if (_composer.value) {
  4589. _composer.value.fallbackLocale.value = val;
  4590. }
  4591. _fallbackLocale.value = val;
  4592. }
  4593. });
  4594. // messages
  4595. const messages = vue.computed(() => {
  4596. if (_composer.value) {
  4597. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4598. return _composer.value.messages.value;
  4599. }
  4600. else {
  4601. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4602. return _messages.value;
  4603. }
  4604. });
  4605. const datetimeFormats = vue.computed(() => _datetimeFormats.value);
  4606. const numberFormats = vue.computed(() => _numberFormats.value);
  4607. function getPostTranslationHandler() {
  4608. return _composer.value
  4609. ? _composer.value.getPostTranslationHandler()
  4610. : _postTranslation;
  4611. }
  4612. function setPostTranslationHandler(handler) {
  4613. if (_composer.value) {
  4614. _composer.value.setPostTranslationHandler(handler);
  4615. }
  4616. }
  4617. function getMissingHandler() {
  4618. return _composer.value ? _composer.value.getMissingHandler() : _missing;
  4619. }
  4620. function setMissingHandler(handler) {
  4621. if (_composer.value) {
  4622. _composer.value.setMissingHandler(handler);
  4623. }
  4624. }
  4625. function warpWithDeps(fn) {
  4626. trackReactivityValues();
  4627. return fn();
  4628. }
  4629. function t(...args) {
  4630. return _composer.value
  4631. ? warpWithDeps(() => Reflect.apply(_composer.value.t, null, [...args]))
  4632. : warpWithDeps(() => '');
  4633. }
  4634. function rt(...args) {
  4635. return _composer.value
  4636. ? Reflect.apply(_composer.value.rt, null, [...args])
  4637. : '';
  4638. }
  4639. function d(...args) {
  4640. return _composer.value
  4641. ? warpWithDeps(() => Reflect.apply(_composer.value.d, null, [...args]))
  4642. : warpWithDeps(() => '');
  4643. }
  4644. function n(...args) {
  4645. return _composer.value
  4646. ? warpWithDeps(() => Reflect.apply(_composer.value.n, null, [...args]))
  4647. : warpWithDeps(() => '');
  4648. }
  4649. function tm(key) {
  4650. return _composer.value ? _composer.value.tm(key) : {};
  4651. }
  4652. function te(key, locale) {
  4653. return _composer.value ? _composer.value.te(key, locale) : false;
  4654. }
  4655. function getLocaleMessage(locale) {
  4656. return _composer.value ? _composer.value.getLocaleMessage(locale) : {};
  4657. }
  4658. function setLocaleMessage(locale, message) {
  4659. if (_composer.value) {
  4660. _composer.value.setLocaleMessage(locale, message);
  4661. _messages.value[locale] = message;
  4662. }
  4663. }
  4664. function mergeLocaleMessage(locale, message) {
  4665. if (_composer.value) {
  4666. _composer.value.mergeLocaleMessage(locale, message);
  4667. }
  4668. }
  4669. function getDateTimeFormat(locale) {
  4670. return _composer.value ? _composer.value.getDateTimeFormat(locale) : {};
  4671. }
  4672. function setDateTimeFormat(locale, format) {
  4673. if (_composer.value) {
  4674. _composer.value.setDateTimeFormat(locale, format);
  4675. _datetimeFormats.value[locale] = format;
  4676. }
  4677. }
  4678. function mergeDateTimeFormat(locale, format) {
  4679. if (_composer.value) {
  4680. _composer.value.mergeDateTimeFormat(locale, format);
  4681. }
  4682. }
  4683. function getNumberFormat(locale) {
  4684. return _composer.value ? _composer.value.getNumberFormat(locale) : {};
  4685. }
  4686. function setNumberFormat(locale, format) {
  4687. if (_composer.value) {
  4688. _composer.value.setNumberFormat(locale, format);
  4689. _numberFormats.value[locale] = format;
  4690. }
  4691. }
  4692. function mergeNumberFormat(locale, format) {
  4693. if (_composer.value) {
  4694. _composer.value.mergeNumberFormat(locale, format);
  4695. }
  4696. }
  4697. const wrapper = {
  4698. get id() {
  4699. return _composer.value ? _composer.value.id : -1;
  4700. },
  4701. locale,
  4702. fallbackLocale,
  4703. messages,
  4704. datetimeFormats,
  4705. numberFormats,
  4706. get inheritLocale() {
  4707. return _composer.value ? _composer.value.inheritLocale : _inheritLocale;
  4708. },
  4709. set inheritLocale(val) {
  4710. if (_composer.value) {
  4711. _composer.value.inheritLocale = val;
  4712. }
  4713. },
  4714. get availableLocales() {
  4715. return _composer.value
  4716. ? _composer.value.availableLocales
  4717. : Object.keys(_messages.value);
  4718. },
  4719. get modifiers() {
  4720. return (_composer.value ? _composer.value.modifiers : _modifiers);
  4721. },
  4722. get pluralRules() {
  4723. return (_composer.value ? _composer.value.pluralRules : _pluralRules);
  4724. },
  4725. get isGlobal() {
  4726. return _composer.value ? _composer.value.isGlobal : false;
  4727. },
  4728. get missingWarn() {
  4729. return _composer.value ? _composer.value.missingWarn : _missingWarn;
  4730. },
  4731. set missingWarn(val) {
  4732. if (_composer.value) {
  4733. _composer.value.missingWarn = val;
  4734. }
  4735. },
  4736. get fallbackWarn() {
  4737. return _composer.value ? _composer.value.fallbackWarn : _fallbackWarn;
  4738. },
  4739. set fallbackWarn(val) {
  4740. if (_composer.value) {
  4741. _composer.value.missingWarn = val;
  4742. }
  4743. },
  4744. get fallbackRoot() {
  4745. return _composer.value ? _composer.value.fallbackRoot : _fallbackRoot;
  4746. },
  4747. set fallbackRoot(val) {
  4748. if (_composer.value) {
  4749. _composer.value.fallbackRoot = val;
  4750. }
  4751. },
  4752. get fallbackFormat() {
  4753. return _composer.value ? _composer.value.fallbackFormat : _fallbackFormat;
  4754. },
  4755. set fallbackFormat(val) {
  4756. if (_composer.value) {
  4757. _composer.value.fallbackFormat = val;
  4758. }
  4759. },
  4760. get warnHtmlMessage() {
  4761. return _composer.value
  4762. ? _composer.value.warnHtmlMessage
  4763. : _warnHtmlMessage;
  4764. },
  4765. set warnHtmlMessage(val) {
  4766. if (_composer.value) {
  4767. _composer.value.warnHtmlMessage = val;
  4768. }
  4769. },
  4770. get escapeParameter() {
  4771. return _composer.value
  4772. ? _composer.value.escapeParameter
  4773. : _escapeParameter;
  4774. },
  4775. set escapeParameter(val) {
  4776. if (_composer.value) {
  4777. _composer.value.escapeParameter = val;
  4778. }
  4779. },
  4780. t,
  4781. getPostTranslationHandler,
  4782. setPostTranslationHandler,
  4783. getMissingHandler,
  4784. setMissingHandler,
  4785. rt,
  4786. d,
  4787. n,
  4788. tm,
  4789. te,
  4790. getLocaleMessage,
  4791. setLocaleMessage,
  4792. mergeLocaleMessage,
  4793. getDateTimeFormat,
  4794. setDateTimeFormat,
  4795. mergeDateTimeFormat,
  4796. getNumberFormat,
  4797. setNumberFormat,
  4798. mergeNumberFormat
  4799. };
  4800. function sync(composer) {
  4801. composer.locale.value = _locale.value;
  4802. composer.fallbackLocale.value = _fallbackLocale.value;
  4803. Object.keys(_messages.value).forEach(locale => {
  4804. composer.mergeLocaleMessage(locale, _messages.value[locale]);
  4805. });
  4806. Object.keys(_datetimeFormats.value).forEach(locale => {
  4807. composer.mergeDateTimeFormat(locale, _datetimeFormats.value[locale]);
  4808. });
  4809. Object.keys(_numberFormats.value).forEach(locale => {
  4810. composer.mergeNumberFormat(locale, _numberFormats.value[locale]);
  4811. });
  4812. composer.escapeParameter = _escapeParameter;
  4813. composer.fallbackFormat = _fallbackFormat;
  4814. composer.fallbackRoot = _fallbackRoot;
  4815. composer.fallbackWarn = _fallbackWarn;
  4816. composer.missingWarn = _missingWarn;
  4817. composer.warnHtmlMessage = _warnHtmlMessage;
  4818. }
  4819. vue.onBeforeMount(() => {
  4820. if (instance.proxy == null || instance.proxy.$i18n == null) {
  4821. throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_COMPOSITION_IN_LEGACY);
  4822. }
  4823. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4824. const composer = (_composer.value = instance.proxy.$i18n
  4825. .__composer);
  4826. if (scope === 'global') {
  4827. _locale.value = composer.locale.value;
  4828. _fallbackLocale.value = composer.fallbackLocale.value;
  4829. _messages.value = composer.messages.value;
  4830. _datetimeFormats.value = composer.datetimeFormats.value;
  4831. _numberFormats.value = composer.numberFormats.value;
  4832. }
  4833. else if (isLocalScope) {
  4834. sync(composer);
  4835. }
  4836. });
  4837. return wrapper;
  4838. }
  4839. const globalExportProps = [
  4840. 'locale',
  4841. 'fallbackLocale',
  4842. 'availableLocales'
  4843. ];
  4844. const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm', 'te']
  4845. ;
  4846. function injectGlobalFields(app, composer) {
  4847. const i18n = Object.create(null);
  4848. globalExportProps.forEach(prop => {
  4849. const desc = Object.getOwnPropertyDescriptor(composer, prop);
  4850. if (!desc) {
  4851. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  4852. }
  4853. const wrap = vue.isRef(desc.value) // check computed props
  4854. ? {
  4855. get() {
  4856. return desc.value.value;
  4857. },
  4858. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4859. set(val) {
  4860. desc.value.value = val;
  4861. }
  4862. }
  4863. : {
  4864. get() {
  4865. return desc.get && desc.get();
  4866. }
  4867. };
  4868. Object.defineProperty(i18n, prop, wrap);
  4869. });
  4870. app.config.globalProperties.$i18n = i18n;
  4871. globalExportMethods.forEach(method => {
  4872. const desc = Object.getOwnPropertyDescriptor(composer, method);
  4873. if (!desc || !desc.value) {
  4874. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  4875. }
  4876. Object.defineProperty(app.config.globalProperties, `$${method}`, desc);
  4877. });
  4878. const dispose = () => {
  4879. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4880. delete app.config.globalProperties.$i18n;
  4881. globalExportMethods.forEach(method => {
  4882. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4883. delete app.config.globalProperties[`$${method}`];
  4884. });
  4885. };
  4886. return dispose;
  4887. }
  4888. // register message resolver at vue-i18n
  4889. registerMessageResolver(resolveValue);
  4890. // register fallback locale at vue-i18n
  4891. registerLocaleFallbacker(fallbackWithLocaleChain);
  4892. // NOTE: experimental !!
  4893. {
  4894. const target = getGlobalThis();
  4895. target.__INTLIFY__ = true;
  4896. setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);
  4897. }
  4898. {
  4899. initDev();
  4900. }
  4901. exports.DatetimeFormat = DatetimeFormat;
  4902. exports.I18nD = I18nD;
  4903. exports.I18nInjectionKey = I18nInjectionKey;
  4904. exports.I18nN = I18nN;
  4905. exports.I18nT = I18nT;
  4906. exports.NumberFormat = NumberFormat;
  4907. exports.Translation = Translation;
  4908. exports.VERSION = VERSION;
  4909. exports.castToVueI18n = castToVueI18n;
  4910. exports.createI18n = createI18n;
  4911. exports.useI18n = useI18n;
  4912. exports.vTDirective = vTDirective;
  4913. return exports;
  4914. })({}, Vue);