vue-i18n.runtime.global.js 177 KB

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