vue-i18n.global.js 220 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146
  1. /*!
  2. * vue-i18n v11.1.3
  3. * (c) 2025 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$1(message, ...args) {
  36. if (args.length === 1 && isObject(args[0])) {
  37. args = args[0];
  38. }
  39. if (!args || !args.hasOwnProperty) {
  40. args = {};
  41. }
  42. return message.replace(RE_ARGS, (match, identifier) => {
  43. return args.hasOwnProperty(identifier) ? args[identifier] : '';
  44. });
  45. }
  46. const 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. const _create = Object.create;
  58. const create = (obj = null) => _create(obj);
  59. let _globalThis;
  60. const getGlobalThis = () => {
  61. // prettier-ignore
  62. return (_globalThis ||
  63. (_globalThis =
  64. typeof globalThis !== 'undefined'
  65. ? globalThis
  66. : typeof self !== 'undefined'
  67. ? self
  68. : typeof window !== 'undefined'
  69. ? window
  70. : typeof global !== 'undefined'
  71. ? global
  72. : create()));
  73. };
  74. function escapeHtml(rawText) {
  75. return rawText
  76. .replace(/</g, '&lt;')
  77. .replace(/>/g, '&gt;')
  78. .replace(/"/g, '&quot;')
  79. .replace(/'/g, '&apos;');
  80. }
  81. const hasOwnProperty = Object.prototype.hasOwnProperty;
  82. function hasOwn(obj, key) {
  83. return hasOwnProperty.call(obj, key);
  84. }
  85. /* eslint-enable */
  86. /**
  87. * Useful Utilities By Evan you
  88. * Modified by kazuya kawaguchi
  89. * MIT License
  90. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
  91. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
  92. */
  93. const isArray = Array.isArray;
  94. const isFunction = (val) => typeof val === 'function';
  95. const isString = (val) => typeof val === 'string';
  96. const isBoolean = (val) => typeof val === 'boolean';
  97. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  98. const isObject = (val) => val !== null && typeof val === 'object';
  99. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  100. const isPromise = (val) => {
  101. return isObject(val) && isFunction(val.then) && isFunction(val.catch);
  102. };
  103. const objectToString = Object.prototype.toString;
  104. const toTypeString = (value) => objectToString.call(value);
  105. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  106. // for converting list and named values to displayed strings.
  107. const toDisplayString = (val) => {
  108. return val == null
  109. ? ''
  110. : isArray(val) || (isPlainObject(val) && val.toString === objectToString)
  111. ? JSON.stringify(val, null, 2)
  112. : String(val);
  113. };
  114. function join(items, separator = '') {
  115. return items.reduce((str, item, index) => (index === 0 ? str + item : str + separator + item), '');
  116. }
  117. const RANGE = 2;
  118. function generateCodeFrame(source, start = 0, end = source.length) {
  119. const lines = source.split(/\r?\n/);
  120. let count = 0;
  121. const res = [];
  122. for (let i = 0; i < lines.length; i++) {
  123. count += lines[i].length + 1;
  124. if (count >= start) {
  125. for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
  126. if (j < 0 || j >= lines.length)
  127. continue;
  128. const line = j + 1;
  129. res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
  130. const lineLength = lines[j].length;
  131. if (j === i) {
  132. // push underline
  133. const pad = start - (count - lineLength) + 1;
  134. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  135. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  136. }
  137. else if (j > i) {
  138. if (end > count) {
  139. const length = Math.max(Math.min(end - count, lineLength), 1);
  140. res.push(` | ` + '^'.repeat(length));
  141. }
  142. count += lineLength + 1;
  143. }
  144. }
  145. break;
  146. }
  147. }
  148. return res.join('\n');
  149. }
  150. function warn(msg, err) {
  151. if (typeof console !== 'undefined') {
  152. console.warn(`[intlify] ` + msg);
  153. /* istanbul ignore if */
  154. if (err) {
  155. console.warn(err.stack);
  156. }
  157. }
  158. }
  159. const hasWarned = {};
  160. function warnOnce(msg) {
  161. if (!hasWarned[msg]) {
  162. hasWarned[msg] = true;
  163. warn(msg);
  164. }
  165. }
  166. /**
  167. * Event emitter, forked from the below:
  168. * - original repository url: https://github.com/developit/mitt
  169. * - code url: https://github.com/developit/mitt/blob/master/src/index.ts
  170. * - author: Jason Miller (https://github.com/developit)
  171. * - license: MIT
  172. */
  173. /**
  174. * Create a event emitter
  175. *
  176. * @returns An event emitter
  177. */
  178. function createEmitter() {
  179. const events = new Map();
  180. const emitter = {
  181. events,
  182. on(event, handler) {
  183. const handlers = events.get(event);
  184. const added = handlers && handlers.push(handler);
  185. if (!added) {
  186. events.set(event, [handler]);
  187. }
  188. },
  189. off(event, handler) {
  190. const handlers = events.get(event);
  191. if (handlers) {
  192. handlers.splice(handlers.indexOf(handler) >>> 0, 1);
  193. }
  194. },
  195. emit(event, payload) {
  196. (events.get(event) || [])
  197. .slice()
  198. .map(handler => handler(payload));
  199. (events.get('*') || [])
  200. .slice()
  201. .map(handler => handler(event, payload));
  202. }
  203. };
  204. return emitter;
  205. }
  206. const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val);
  207. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  208. function deepCopy(src, des) {
  209. // src and des should both be objects, and none of them can be a array
  210. if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {
  211. throw new Error('Invalid value');
  212. }
  213. const stack = [{ src, des }];
  214. while (stack.length) {
  215. const { src, des } = stack.pop();
  216. // using `Object.keys` which skips prototype properties
  217. Object.keys(src).forEach(key => {
  218. if (key === '__proto__') {
  219. return;
  220. }
  221. // if src[key] is an object/array, set des[key]
  222. // to empty object/array to prevent setting by reference
  223. if (isObject(src[key]) && !isObject(des[key])) {
  224. des[key] = Array.isArray(src[key]) ? [] : create();
  225. }
  226. if (isNotObjectOrIsArray(des[key]) || isNotObjectOrIsArray(src[key])) {
  227. // replace with src[key] when:
  228. // src[key] or des[key] is not an object, or
  229. // src[key] or des[key] is an array
  230. des[key] = src[key];
  231. }
  232. else {
  233. // src[key] and des[key] are both objects, merge them
  234. stack.push({ src: src[key], des: des[key] });
  235. }
  236. });
  237. }
  238. }
  239. function createPosition(line, column, offset) {
  240. return { line, column, offset };
  241. }
  242. function createLocation(start, end, source) {
  243. const loc = { start, end };
  244. return loc;
  245. }
  246. const CompileErrorCodes = {
  247. // tokenizer error codes
  248. EXPECTED_TOKEN: 1,
  249. INVALID_TOKEN_IN_PLACEHOLDER: 2,
  250. UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
  251. UNKNOWN_ESCAPE_SEQUENCE: 4,
  252. INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
  253. UNBALANCED_CLOSING_BRACE: 6,
  254. UNTERMINATED_CLOSING_BRACE: 7,
  255. EMPTY_PLACEHOLDER: 8,
  256. NOT_ALLOW_NEST_PLACEHOLDER: 9,
  257. INVALID_LINKED_FORMAT: 10,
  258. // parser error codes
  259. MUST_HAVE_MESSAGES_IN_PLURAL: 11,
  260. UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
  261. UNEXPECTED_EMPTY_LINKED_KEY: 13,
  262. UNEXPECTED_LEXICAL_ANALYSIS: 14,
  263. // generator error codes
  264. UNHANDLED_CODEGEN_NODE_TYPE: 15,
  265. // minifier error codes
  266. UNHANDLED_MINIFIER_NODE_TYPE: 16
  267. };
  268. // Special value for higher-order compilers to pick up the last code
  269. // to avoid collision of error codes.
  270. // This should always be kept as the last item.
  271. const COMPILE_ERROR_CODES_EXTEND_POINT = 17;
  272. /** @internal */
  273. const errorMessages$2 = {
  274. // tokenizer error messages
  275. [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
  276. [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
  277. [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
  278. [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
  279. [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
  280. [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
  281. [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
  282. [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
  283. [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
  284. [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
  285. // parser error messages
  286. [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
  287. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
  288. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
  289. [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,
  290. // generator error messages
  291. [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,
  292. // minimizer error messages
  293. [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`
  294. };
  295. function createCompileError(code, loc, options = {}) {
  296. const { domain, messages, args } = options;
  297. const msg = format$1((messages || errorMessages$2)[code] || '', ...(args || []))
  298. ;
  299. const error = new SyntaxError(String(msg));
  300. error.code = code;
  301. if (loc) {
  302. error.location = loc;
  303. }
  304. error.domain = domain;
  305. return error;
  306. }
  307. /** @internal */
  308. function defaultOnError(error) {
  309. throw error;
  310. }
  311. // eslint-disable-next-line no-useless-escape
  312. const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
  313. const detectHtmlTag = (source) => RE_HTML_TAG.test(source);
  314. const CHAR_SP = ' ';
  315. const CHAR_CR = '\r';
  316. const CHAR_LF = '\n';
  317. const CHAR_LS = String.fromCharCode(0x2028);
  318. const CHAR_PS = String.fromCharCode(0x2029);
  319. function createScanner(str) {
  320. const _buf = str;
  321. let _index = 0;
  322. let _line = 1;
  323. let _column = 1;
  324. let _peekOffset = 0;
  325. const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
  326. const isLF = (index) => _buf[index] === CHAR_LF;
  327. const isPS = (index) => _buf[index] === CHAR_PS;
  328. const isLS = (index) => _buf[index] === CHAR_LS;
  329. const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
  330. const index = () => _index;
  331. const line = () => _line;
  332. const column = () => _column;
  333. const peekOffset = () => _peekOffset;
  334. const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
  335. const currentChar = () => charAt(_index);
  336. const currentPeek = () => charAt(_index + _peekOffset);
  337. function next() {
  338. _peekOffset = 0;
  339. if (isLineEnd(_index)) {
  340. _line++;
  341. _column = 0;
  342. }
  343. if (isCRLF(_index)) {
  344. _index++;
  345. }
  346. _index++;
  347. _column++;
  348. return _buf[_index];
  349. }
  350. function peek() {
  351. if (isCRLF(_index + _peekOffset)) {
  352. _peekOffset++;
  353. }
  354. _peekOffset++;
  355. return _buf[_index + _peekOffset];
  356. }
  357. function reset() {
  358. _index = 0;
  359. _line = 1;
  360. _column = 1;
  361. _peekOffset = 0;
  362. }
  363. function resetPeek(offset = 0) {
  364. _peekOffset = offset;
  365. }
  366. function skipToPeek() {
  367. const target = _index + _peekOffset;
  368. while (target !== _index) {
  369. next();
  370. }
  371. _peekOffset = 0;
  372. }
  373. return {
  374. index,
  375. line,
  376. column,
  377. peekOffset,
  378. charAt,
  379. currentChar,
  380. currentPeek,
  381. next,
  382. peek,
  383. reset,
  384. resetPeek,
  385. skipToPeek
  386. };
  387. }
  388. const EOF = undefined;
  389. const DOT = '.';
  390. const LITERAL_DELIMITER = "'";
  391. const ERROR_DOMAIN$3 = 'tokenizer';
  392. function createTokenizer(source, options = {}) {
  393. const location = options.location !== false;
  394. const _scnr = createScanner(source);
  395. const currentOffset = () => _scnr.index();
  396. const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
  397. const _initLoc = currentPosition();
  398. const _initOffset = currentOffset();
  399. const _context = {
  400. currentType: 13 /* TokenTypes.EOF */,
  401. offset: _initOffset,
  402. startLoc: _initLoc,
  403. endLoc: _initLoc,
  404. lastType: 13 /* TokenTypes.EOF */,
  405. lastOffset: _initOffset,
  406. lastStartLoc: _initLoc,
  407. lastEndLoc: _initLoc,
  408. braceNest: 0,
  409. inLinked: false,
  410. text: ''
  411. };
  412. const context = () => _context;
  413. const { onError } = options;
  414. function emitError(code, pos, offset, ...args) {
  415. const ctx = context();
  416. pos.column += offset;
  417. pos.offset += offset;
  418. if (onError) {
  419. const loc = location ? createLocation(ctx.startLoc, pos) : null;
  420. const err = createCompileError(code, loc, {
  421. domain: ERROR_DOMAIN$3,
  422. args
  423. });
  424. onError(err);
  425. }
  426. }
  427. function getToken(context, type, value) {
  428. context.endLoc = currentPosition();
  429. context.currentType = type;
  430. const token = { type };
  431. if (location) {
  432. token.loc = createLocation(context.startLoc, context.endLoc);
  433. }
  434. if (value != null) {
  435. token.value = value;
  436. }
  437. return token;
  438. }
  439. const getEndToken = (context) => getToken(context, 13 /* TokenTypes.EOF */);
  440. function eat(scnr, ch) {
  441. if (scnr.currentChar() === ch) {
  442. scnr.next();
  443. return ch;
  444. }
  445. else {
  446. emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
  447. return '';
  448. }
  449. }
  450. function peekSpaces(scnr) {
  451. let buf = '';
  452. while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
  453. buf += scnr.currentPeek();
  454. scnr.peek();
  455. }
  456. return buf;
  457. }
  458. function skipSpaces(scnr) {
  459. const buf = peekSpaces(scnr);
  460. scnr.skipToPeek();
  461. return buf;
  462. }
  463. function isIdentifierStart(ch) {
  464. if (ch === EOF) {
  465. return false;
  466. }
  467. const cc = ch.charCodeAt(0);
  468. return ((cc >= 97 && cc <= 122) || // a-z
  469. (cc >= 65 && cc <= 90) || // A-Z
  470. cc === 95 // _
  471. );
  472. }
  473. function isNumberStart(ch) {
  474. if (ch === EOF) {
  475. return false;
  476. }
  477. const cc = ch.charCodeAt(0);
  478. return cc >= 48 && cc <= 57; // 0-9
  479. }
  480. function isNamedIdentifierStart(scnr, context) {
  481. const { currentType } = context;
  482. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  483. return false;
  484. }
  485. peekSpaces(scnr);
  486. const ret = isIdentifierStart(scnr.currentPeek());
  487. scnr.resetPeek();
  488. return ret;
  489. }
  490. function isListIdentifierStart(scnr, context) {
  491. const { currentType } = context;
  492. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  493. return false;
  494. }
  495. peekSpaces(scnr);
  496. const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
  497. const ret = isNumberStart(ch);
  498. scnr.resetPeek();
  499. return ret;
  500. }
  501. function isLiteralStart(scnr, context) {
  502. const { currentType } = context;
  503. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  504. return false;
  505. }
  506. peekSpaces(scnr);
  507. const ret = scnr.currentPeek() === LITERAL_DELIMITER;
  508. scnr.resetPeek();
  509. return ret;
  510. }
  511. function isLinkedDotStart(scnr, context) {
  512. const { currentType } = context;
  513. if (currentType !== 7 /* TokenTypes.LinkedAlias */) {
  514. return false;
  515. }
  516. peekSpaces(scnr);
  517. const ret = scnr.currentPeek() === "." /* TokenChars.LinkedDot */;
  518. scnr.resetPeek();
  519. return ret;
  520. }
  521. function isLinkedModifierStart(scnr, context) {
  522. const { currentType } = context;
  523. if (currentType !== 8 /* TokenTypes.LinkedDot */) {
  524. return false;
  525. }
  526. peekSpaces(scnr);
  527. const ret = isIdentifierStart(scnr.currentPeek());
  528. scnr.resetPeek();
  529. return ret;
  530. }
  531. function isLinkedDelimiterStart(scnr, context) {
  532. const { currentType } = context;
  533. if (!(currentType === 7 /* TokenTypes.LinkedAlias */ ||
  534. currentType === 11 /* TokenTypes.LinkedModifier */)) {
  535. return false;
  536. }
  537. peekSpaces(scnr);
  538. const ret = scnr.currentPeek() === ":" /* TokenChars.LinkedDelimiter */;
  539. scnr.resetPeek();
  540. return ret;
  541. }
  542. function isLinkedReferStart(scnr, context) {
  543. const { currentType } = context;
  544. if (currentType !== 9 /* TokenTypes.LinkedDelimiter */) {
  545. return false;
  546. }
  547. const fn = () => {
  548. const ch = scnr.currentPeek();
  549. if (ch === "{" /* TokenChars.BraceLeft */) {
  550. return isIdentifierStart(scnr.peek());
  551. }
  552. else if (ch === "@" /* TokenChars.LinkedAlias */ ||
  553. ch === "|" /* TokenChars.Pipe */ ||
  554. ch === ":" /* TokenChars.LinkedDelimiter */ ||
  555. ch === "." /* TokenChars.LinkedDot */ ||
  556. ch === CHAR_SP ||
  557. !ch) {
  558. return false;
  559. }
  560. else if (ch === CHAR_LF) {
  561. scnr.peek();
  562. return fn();
  563. }
  564. else {
  565. // other characters
  566. return isTextStart(scnr, false);
  567. }
  568. };
  569. const ret = fn();
  570. scnr.resetPeek();
  571. return ret;
  572. }
  573. function isPluralStart(scnr) {
  574. peekSpaces(scnr);
  575. const ret = scnr.currentPeek() === "|" /* TokenChars.Pipe */;
  576. scnr.resetPeek();
  577. return ret;
  578. }
  579. function isTextStart(scnr, reset = true) {
  580. const fn = (hasSpace = false, prev = '') => {
  581. const ch = scnr.currentPeek();
  582. if (ch === "{" /* TokenChars.BraceLeft */) {
  583. return hasSpace;
  584. }
  585. else if (ch === "@" /* TokenChars.LinkedAlias */ || !ch) {
  586. return hasSpace;
  587. }
  588. else if (ch === "|" /* TokenChars.Pipe */) {
  589. return !(prev === CHAR_SP || prev === CHAR_LF);
  590. }
  591. else if (ch === CHAR_SP) {
  592. scnr.peek();
  593. return fn(true, CHAR_SP);
  594. }
  595. else if (ch === CHAR_LF) {
  596. scnr.peek();
  597. return fn(true, CHAR_LF);
  598. }
  599. else {
  600. return true;
  601. }
  602. };
  603. const ret = fn();
  604. reset && scnr.resetPeek();
  605. return ret;
  606. }
  607. function takeChar(scnr, fn) {
  608. const ch = scnr.currentChar();
  609. if (ch === EOF) {
  610. return EOF;
  611. }
  612. if (fn(ch)) {
  613. scnr.next();
  614. return ch;
  615. }
  616. return null;
  617. }
  618. function isIdentifier(ch) {
  619. const cc = ch.charCodeAt(0);
  620. return ((cc >= 97 && cc <= 122) || // a-z
  621. (cc >= 65 && cc <= 90) || // A-Z
  622. (cc >= 48 && cc <= 57) || // 0-9
  623. cc === 95 || // _
  624. cc === 36 // $
  625. );
  626. }
  627. function takeIdentifierChar(scnr) {
  628. return takeChar(scnr, isIdentifier);
  629. }
  630. function isNamedIdentifier(ch) {
  631. const cc = ch.charCodeAt(0);
  632. return ((cc >= 97 && cc <= 122) || // a-z
  633. (cc >= 65 && cc <= 90) || // A-Z
  634. (cc >= 48 && cc <= 57) || // 0-9
  635. cc === 95 || // _
  636. cc === 36 || // $
  637. cc === 45 // -
  638. );
  639. }
  640. function takeNamedIdentifierChar(scnr) {
  641. return takeChar(scnr, isNamedIdentifier);
  642. }
  643. function isDigit(ch) {
  644. const cc = ch.charCodeAt(0);
  645. return cc >= 48 && cc <= 57; // 0-9
  646. }
  647. function takeDigit(scnr) {
  648. return takeChar(scnr, isDigit);
  649. }
  650. function isHexDigit(ch) {
  651. const cc = ch.charCodeAt(0);
  652. return ((cc >= 48 && cc <= 57) || // 0-9
  653. (cc >= 65 && cc <= 70) || // A-F
  654. (cc >= 97 && cc <= 102)); // a-f
  655. }
  656. function takeHexDigit(scnr) {
  657. return takeChar(scnr, isHexDigit);
  658. }
  659. function getDigits(scnr) {
  660. let ch = '';
  661. let num = '';
  662. while ((ch = takeDigit(scnr))) {
  663. num += ch;
  664. }
  665. return num;
  666. }
  667. function readText(scnr) {
  668. let buf = '';
  669. while (true) {
  670. const ch = scnr.currentChar();
  671. if (ch === "{" /* TokenChars.BraceLeft */ ||
  672. ch === "}" /* TokenChars.BraceRight */ ||
  673. ch === "@" /* TokenChars.LinkedAlias */ ||
  674. ch === "|" /* TokenChars.Pipe */ ||
  675. !ch) {
  676. break;
  677. }
  678. else if (ch === CHAR_SP || ch === CHAR_LF) {
  679. if (isTextStart(scnr)) {
  680. buf += ch;
  681. scnr.next();
  682. }
  683. else if (isPluralStart(scnr)) {
  684. break;
  685. }
  686. else {
  687. buf += ch;
  688. scnr.next();
  689. }
  690. }
  691. else {
  692. buf += ch;
  693. scnr.next();
  694. }
  695. }
  696. return buf;
  697. }
  698. function readNamedIdentifier(scnr) {
  699. skipSpaces(scnr);
  700. let ch = '';
  701. let name = '';
  702. while ((ch = takeNamedIdentifierChar(scnr))) {
  703. name += ch;
  704. }
  705. if (scnr.currentChar() === EOF) {
  706. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  707. }
  708. return name;
  709. }
  710. function readListIdentifier(scnr) {
  711. skipSpaces(scnr);
  712. let value = '';
  713. if (scnr.currentChar() === '-') {
  714. scnr.next();
  715. value += `-${getDigits(scnr)}`;
  716. }
  717. else {
  718. value += getDigits(scnr);
  719. }
  720. if (scnr.currentChar() === EOF) {
  721. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  722. }
  723. return value;
  724. }
  725. function isLiteral(ch) {
  726. return ch !== LITERAL_DELIMITER && ch !== CHAR_LF;
  727. }
  728. function readLiteral(scnr) {
  729. skipSpaces(scnr);
  730. // eslint-disable-next-line no-useless-escape
  731. eat(scnr, `\'`);
  732. let ch = '';
  733. let literal = '';
  734. while ((ch = takeChar(scnr, isLiteral))) {
  735. if (ch === '\\') {
  736. literal += readEscapeSequence(scnr);
  737. }
  738. else {
  739. literal += ch;
  740. }
  741. }
  742. const current = scnr.currentChar();
  743. if (current === CHAR_LF || current === EOF) {
  744. emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
  745. // TODO: Is it correct really?
  746. if (current === CHAR_LF) {
  747. scnr.next();
  748. // eslint-disable-next-line no-useless-escape
  749. eat(scnr, `\'`);
  750. }
  751. return literal;
  752. }
  753. // eslint-disable-next-line no-useless-escape
  754. eat(scnr, `\'`);
  755. return literal;
  756. }
  757. function readEscapeSequence(scnr) {
  758. const ch = scnr.currentChar();
  759. switch (ch) {
  760. case '\\':
  761. case `\'`: // eslint-disable-line no-useless-escape
  762. scnr.next();
  763. return `\\${ch}`;
  764. case 'u':
  765. return readUnicodeEscapeSequence(scnr, ch, 4);
  766. case 'U':
  767. return readUnicodeEscapeSequence(scnr, ch, 6);
  768. default:
  769. emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
  770. return '';
  771. }
  772. }
  773. function readUnicodeEscapeSequence(scnr, unicode, digits) {
  774. eat(scnr, unicode);
  775. let sequence = '';
  776. for (let i = 0; i < digits; i++) {
  777. const ch = takeHexDigit(scnr);
  778. if (!ch) {
  779. emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
  780. break;
  781. }
  782. sequence += ch;
  783. }
  784. return `\\${unicode}${sequence}`;
  785. }
  786. function isInvalidIdentifier(ch) {
  787. return (ch !== "{" /* TokenChars.BraceLeft */ &&
  788. ch !== "}" /* TokenChars.BraceRight */ &&
  789. ch !== CHAR_SP &&
  790. ch !== CHAR_LF);
  791. }
  792. function readInvalidIdentifier(scnr) {
  793. skipSpaces(scnr);
  794. let ch = '';
  795. let identifiers = '';
  796. while ((ch = takeChar(scnr, isInvalidIdentifier))) {
  797. identifiers += ch;
  798. }
  799. return identifiers;
  800. }
  801. function readLinkedModifier(scnr) {
  802. let ch = '';
  803. let name = '';
  804. while ((ch = takeIdentifierChar(scnr))) {
  805. name += ch;
  806. }
  807. return name;
  808. }
  809. function readLinkedRefer(scnr) {
  810. const fn = (buf) => {
  811. const ch = scnr.currentChar();
  812. if (ch === "{" /* TokenChars.BraceLeft */ ||
  813. ch === "@" /* TokenChars.LinkedAlias */ ||
  814. ch === "|" /* TokenChars.Pipe */ ||
  815. ch === "(" /* TokenChars.ParenLeft */ ||
  816. ch === ")" /* TokenChars.ParenRight */ ||
  817. !ch) {
  818. return buf;
  819. }
  820. else if (ch === CHAR_SP) {
  821. return buf;
  822. }
  823. else if (ch === CHAR_LF || ch === DOT) {
  824. buf += ch;
  825. scnr.next();
  826. return fn(buf);
  827. }
  828. else {
  829. buf += ch;
  830. scnr.next();
  831. return fn(buf);
  832. }
  833. };
  834. return fn('');
  835. }
  836. function readPlural(scnr) {
  837. skipSpaces(scnr);
  838. const plural = eat(scnr, "|" /* TokenChars.Pipe */);
  839. skipSpaces(scnr);
  840. return plural;
  841. }
  842. // TODO: We need refactoring of token parsing ...
  843. function readTokenInPlaceholder(scnr, context) {
  844. let token = null;
  845. const ch = scnr.currentChar();
  846. switch (ch) {
  847. case "{" /* TokenChars.BraceLeft */:
  848. if (context.braceNest >= 1) {
  849. emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
  850. }
  851. scnr.next();
  852. token = getToken(context, 2 /* TokenTypes.BraceLeft */, "{" /* TokenChars.BraceLeft */);
  853. skipSpaces(scnr);
  854. context.braceNest++;
  855. return token;
  856. case "}" /* TokenChars.BraceRight */:
  857. if (context.braceNest > 0 &&
  858. context.currentType === 2 /* TokenTypes.BraceLeft */) {
  859. emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
  860. }
  861. scnr.next();
  862. token = getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
  863. context.braceNest--;
  864. context.braceNest > 0 && skipSpaces(scnr);
  865. if (context.inLinked && context.braceNest === 0) {
  866. context.inLinked = false;
  867. }
  868. return token;
  869. case "@" /* TokenChars.LinkedAlias */:
  870. if (context.braceNest > 0) {
  871. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  872. }
  873. token = readTokenInLinked(scnr, context) || getEndToken(context);
  874. context.braceNest = 0;
  875. return token;
  876. default: {
  877. let validNamedIdentifier = true;
  878. let validListIdentifier = true;
  879. let validLiteral = true;
  880. if (isPluralStart(scnr)) {
  881. if (context.braceNest > 0) {
  882. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  883. }
  884. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  885. // reset
  886. context.braceNest = 0;
  887. context.inLinked = false;
  888. return token;
  889. }
  890. if (context.braceNest > 0 &&
  891. (context.currentType === 4 /* TokenTypes.Named */ ||
  892. context.currentType === 5 /* TokenTypes.List */ ||
  893. context.currentType === 6 /* TokenTypes.Literal */)) {
  894. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  895. context.braceNest = 0;
  896. return readToken(scnr, context);
  897. }
  898. if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
  899. token = getToken(context, 4 /* TokenTypes.Named */, readNamedIdentifier(scnr));
  900. skipSpaces(scnr);
  901. return token;
  902. }
  903. if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
  904. token = getToken(context, 5 /* TokenTypes.List */, readListIdentifier(scnr));
  905. skipSpaces(scnr);
  906. return token;
  907. }
  908. if ((validLiteral = isLiteralStart(scnr, context))) {
  909. token = getToken(context, 6 /* TokenTypes.Literal */, readLiteral(scnr));
  910. skipSpaces(scnr);
  911. return token;
  912. }
  913. if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
  914. // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
  915. token = getToken(context, 12 /* TokenTypes.InvalidPlace */, readInvalidIdentifier(scnr));
  916. emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
  917. skipSpaces(scnr);
  918. return token;
  919. }
  920. break;
  921. }
  922. }
  923. return token;
  924. }
  925. // TODO: We need refactoring of token parsing ...
  926. function readTokenInLinked(scnr, context) {
  927. const { currentType } = context;
  928. let token = null;
  929. const ch = scnr.currentChar();
  930. if ((currentType === 7 /* TokenTypes.LinkedAlias */ ||
  931. currentType === 8 /* TokenTypes.LinkedDot */ ||
  932. currentType === 11 /* TokenTypes.LinkedModifier */ ||
  933. currentType === 9 /* TokenTypes.LinkedDelimiter */) &&
  934. (ch === CHAR_LF || ch === CHAR_SP)) {
  935. emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
  936. }
  937. switch (ch) {
  938. case "@" /* TokenChars.LinkedAlias */:
  939. scnr.next();
  940. token = getToken(context, 7 /* TokenTypes.LinkedAlias */, "@" /* TokenChars.LinkedAlias */);
  941. context.inLinked = true;
  942. return token;
  943. case "." /* TokenChars.LinkedDot */:
  944. skipSpaces(scnr);
  945. scnr.next();
  946. return getToken(context, 8 /* TokenTypes.LinkedDot */, "." /* TokenChars.LinkedDot */);
  947. case ":" /* TokenChars.LinkedDelimiter */:
  948. skipSpaces(scnr);
  949. scnr.next();
  950. return getToken(context, 9 /* TokenTypes.LinkedDelimiter */, ":" /* TokenChars.LinkedDelimiter */);
  951. default:
  952. if (isPluralStart(scnr)) {
  953. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  954. // reset
  955. context.braceNest = 0;
  956. context.inLinked = false;
  957. return token;
  958. }
  959. if (isLinkedDotStart(scnr, context) ||
  960. isLinkedDelimiterStart(scnr, context)) {
  961. skipSpaces(scnr);
  962. return readTokenInLinked(scnr, context);
  963. }
  964. if (isLinkedModifierStart(scnr, context)) {
  965. skipSpaces(scnr);
  966. return getToken(context, 11 /* TokenTypes.LinkedModifier */, readLinkedModifier(scnr));
  967. }
  968. if (isLinkedReferStart(scnr, context)) {
  969. skipSpaces(scnr);
  970. if (ch === "{" /* TokenChars.BraceLeft */) {
  971. // scan the placeholder
  972. return readTokenInPlaceholder(scnr, context) || token;
  973. }
  974. else {
  975. return getToken(context, 10 /* TokenTypes.LinkedKey */, readLinkedRefer(scnr));
  976. }
  977. }
  978. if (currentType === 7 /* TokenTypes.LinkedAlias */) {
  979. emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
  980. }
  981. context.braceNest = 0;
  982. context.inLinked = false;
  983. return readToken(scnr, context);
  984. }
  985. }
  986. // TODO: We need refactoring of token parsing ...
  987. function readToken(scnr, context) {
  988. let token = { type: 13 /* TokenTypes.EOF */ };
  989. if (context.braceNest > 0) {
  990. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  991. }
  992. if (context.inLinked) {
  993. return readTokenInLinked(scnr, context) || getEndToken(context);
  994. }
  995. const ch = scnr.currentChar();
  996. switch (ch) {
  997. case "{" /* TokenChars.BraceLeft */:
  998. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  999. case "}" /* TokenChars.BraceRight */:
  1000. emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
  1001. scnr.next();
  1002. return getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
  1003. case "@" /* TokenChars.LinkedAlias */:
  1004. return readTokenInLinked(scnr, context) || getEndToken(context);
  1005. default: {
  1006. if (isPluralStart(scnr)) {
  1007. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  1008. // reset
  1009. context.braceNest = 0;
  1010. context.inLinked = false;
  1011. return token;
  1012. }
  1013. if (isTextStart(scnr)) {
  1014. return getToken(context, 0 /* TokenTypes.Text */, readText(scnr));
  1015. }
  1016. break;
  1017. }
  1018. }
  1019. return token;
  1020. }
  1021. function nextToken() {
  1022. const { currentType, offset, startLoc, endLoc } = _context;
  1023. _context.lastType = currentType;
  1024. _context.lastOffset = offset;
  1025. _context.lastStartLoc = startLoc;
  1026. _context.lastEndLoc = endLoc;
  1027. _context.offset = currentOffset();
  1028. _context.startLoc = currentPosition();
  1029. if (_scnr.currentChar() === EOF) {
  1030. return getToken(_context, 13 /* TokenTypes.EOF */);
  1031. }
  1032. return readToken(_scnr, _context);
  1033. }
  1034. return {
  1035. nextToken,
  1036. currentOffset,
  1037. currentPosition,
  1038. context
  1039. };
  1040. }
  1041. const ERROR_DOMAIN$2 = 'parser';
  1042. // Backslash backslash, backslash quote, uHHHH, UHHHHHH.
  1043. const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
  1044. function fromEscapeSequence(match, codePoint4, codePoint6) {
  1045. switch (match) {
  1046. case `\\\\`:
  1047. return `\\`;
  1048. // eslint-disable-next-line no-useless-escape
  1049. case `\\\'`:
  1050. // eslint-disable-next-line no-useless-escape
  1051. return `\'`;
  1052. default: {
  1053. const codePoint = parseInt(codePoint4 || codePoint6, 16);
  1054. if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
  1055. return String.fromCodePoint(codePoint);
  1056. }
  1057. // invalid ...
  1058. // Replace them with U+FFFD REPLACEMENT CHARACTER.
  1059. return '�';
  1060. }
  1061. }
  1062. }
  1063. function createParser(options = {}) {
  1064. const location = options.location !== false;
  1065. const { onError } = options;
  1066. function emitError(tokenzer, code, start, offset, ...args) {
  1067. const end = tokenzer.currentPosition();
  1068. end.offset += offset;
  1069. end.column += offset;
  1070. if (onError) {
  1071. const loc = location ? createLocation(start, end) : null;
  1072. const err = createCompileError(code, loc, {
  1073. domain: ERROR_DOMAIN$2,
  1074. args
  1075. });
  1076. onError(err);
  1077. }
  1078. }
  1079. function startNode(type, offset, loc) {
  1080. const node = { type };
  1081. if (location) {
  1082. node.start = offset;
  1083. node.end = offset;
  1084. node.loc = { start: loc, end: loc };
  1085. }
  1086. return node;
  1087. }
  1088. function endNode(node, offset, pos, type) {
  1089. if (location) {
  1090. node.end = offset;
  1091. if (node.loc) {
  1092. node.loc.end = pos;
  1093. }
  1094. }
  1095. }
  1096. function parseText(tokenizer, value) {
  1097. const context = tokenizer.context();
  1098. const node = startNode(3 /* NodeTypes.Text */, context.offset, context.startLoc);
  1099. node.value = value;
  1100. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1101. return node;
  1102. }
  1103. function parseList(tokenizer, index) {
  1104. const context = tokenizer.context();
  1105. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1106. const node = startNode(5 /* NodeTypes.List */, offset, loc);
  1107. node.index = parseInt(index, 10);
  1108. tokenizer.nextToken(); // skip brach right
  1109. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1110. return node;
  1111. }
  1112. function parseNamed(tokenizer, key) {
  1113. const context = tokenizer.context();
  1114. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1115. const node = startNode(4 /* NodeTypes.Named */, offset, loc);
  1116. node.key = key;
  1117. tokenizer.nextToken(); // skip brach right
  1118. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1119. return node;
  1120. }
  1121. function parseLiteral(tokenizer, value) {
  1122. const context = tokenizer.context();
  1123. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1124. const node = startNode(9 /* NodeTypes.Literal */, offset, loc);
  1125. node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
  1126. tokenizer.nextToken(); // skip brach right
  1127. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1128. return node;
  1129. }
  1130. function parseLinkedModifier(tokenizer) {
  1131. const token = tokenizer.nextToken();
  1132. const context = tokenizer.context();
  1133. const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
  1134. const node = startNode(8 /* NodeTypes.LinkedModifier */, offset, loc);
  1135. if (token.type !== 11 /* TokenTypes.LinkedModifier */) {
  1136. // empty modifier
  1137. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
  1138. node.value = '';
  1139. endNode(node, offset, loc);
  1140. return {
  1141. nextConsumeToken: token,
  1142. node
  1143. };
  1144. }
  1145. // check token
  1146. if (token.value == null) {
  1147. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1148. }
  1149. node.value = token.value || '';
  1150. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1151. return {
  1152. node
  1153. };
  1154. }
  1155. function parseLinkedKey(tokenizer, value) {
  1156. const context = tokenizer.context();
  1157. const node = startNode(7 /* NodeTypes.LinkedKey */, context.offset, context.startLoc);
  1158. node.value = value;
  1159. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1160. return node;
  1161. }
  1162. function parseLinked(tokenizer) {
  1163. const context = tokenizer.context();
  1164. const linkedNode = startNode(6 /* NodeTypes.Linked */, context.offset, context.startLoc);
  1165. let token = tokenizer.nextToken();
  1166. if (token.type === 8 /* TokenTypes.LinkedDot */) {
  1167. const parsed = parseLinkedModifier(tokenizer);
  1168. linkedNode.modifier = parsed.node;
  1169. token = parsed.nextConsumeToken || tokenizer.nextToken();
  1170. }
  1171. // asset check token
  1172. if (token.type !== 9 /* TokenTypes.LinkedDelimiter */) {
  1173. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1174. }
  1175. token = tokenizer.nextToken();
  1176. // skip brace left
  1177. if (token.type === 2 /* TokenTypes.BraceLeft */) {
  1178. token = tokenizer.nextToken();
  1179. }
  1180. switch (token.type) {
  1181. case 10 /* TokenTypes.LinkedKey */:
  1182. if (token.value == null) {
  1183. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1184. }
  1185. linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
  1186. break;
  1187. case 4 /* TokenTypes.Named */:
  1188. if (token.value == null) {
  1189. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1190. }
  1191. linkedNode.key = parseNamed(tokenizer, token.value || '');
  1192. break;
  1193. case 5 /* TokenTypes.List */:
  1194. if (token.value == null) {
  1195. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1196. }
  1197. linkedNode.key = parseList(tokenizer, token.value || '');
  1198. break;
  1199. case 6 /* TokenTypes.Literal */:
  1200. if (token.value == null) {
  1201. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1202. }
  1203. linkedNode.key = parseLiteral(tokenizer, token.value || '');
  1204. break;
  1205. default: {
  1206. // empty key
  1207. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
  1208. const nextContext = tokenizer.context();
  1209. const emptyLinkedKeyNode = startNode(7 /* NodeTypes.LinkedKey */, nextContext.offset, nextContext.startLoc);
  1210. emptyLinkedKeyNode.value = '';
  1211. endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
  1212. linkedNode.key = emptyLinkedKeyNode;
  1213. endNode(linkedNode, nextContext.offset, nextContext.startLoc);
  1214. return {
  1215. nextConsumeToken: token,
  1216. node: linkedNode
  1217. };
  1218. }
  1219. }
  1220. endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
  1221. return {
  1222. node: linkedNode
  1223. };
  1224. }
  1225. function parseMessage(tokenizer) {
  1226. const context = tokenizer.context();
  1227. const startOffset = context.currentType === 1 /* TokenTypes.Pipe */
  1228. ? tokenizer.currentOffset()
  1229. : context.offset;
  1230. const startLoc = context.currentType === 1 /* TokenTypes.Pipe */
  1231. ? context.endLoc
  1232. : context.startLoc;
  1233. const node = startNode(2 /* NodeTypes.Message */, startOffset, startLoc);
  1234. node.items = [];
  1235. let nextToken = null;
  1236. do {
  1237. const token = nextToken || tokenizer.nextToken();
  1238. nextToken = null;
  1239. switch (token.type) {
  1240. case 0 /* TokenTypes.Text */:
  1241. if (token.value == null) {
  1242. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1243. }
  1244. node.items.push(parseText(tokenizer, token.value || ''));
  1245. break;
  1246. case 5 /* TokenTypes.List */:
  1247. if (token.value == null) {
  1248. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1249. }
  1250. node.items.push(parseList(tokenizer, token.value || ''));
  1251. break;
  1252. case 4 /* TokenTypes.Named */:
  1253. if (token.value == null) {
  1254. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1255. }
  1256. node.items.push(parseNamed(tokenizer, token.value || ''));
  1257. break;
  1258. case 6 /* TokenTypes.Literal */:
  1259. if (token.value == null) {
  1260. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1261. }
  1262. node.items.push(parseLiteral(tokenizer, token.value || ''));
  1263. break;
  1264. case 7 /* TokenTypes.LinkedAlias */: {
  1265. const parsed = parseLinked(tokenizer);
  1266. node.items.push(parsed.node);
  1267. nextToken = parsed.nextConsumeToken || null;
  1268. break;
  1269. }
  1270. }
  1271. } while (context.currentType !== 13 /* TokenTypes.EOF */ &&
  1272. context.currentType !== 1 /* TokenTypes.Pipe */);
  1273. // adjust message node loc
  1274. const endOffset = context.currentType === 1 /* TokenTypes.Pipe */
  1275. ? context.lastOffset
  1276. : tokenizer.currentOffset();
  1277. const endLoc = context.currentType === 1 /* TokenTypes.Pipe */
  1278. ? context.lastEndLoc
  1279. : tokenizer.currentPosition();
  1280. endNode(node, endOffset, endLoc);
  1281. return node;
  1282. }
  1283. function parsePlural(tokenizer, offset, loc, msgNode) {
  1284. const context = tokenizer.context();
  1285. let hasEmptyMessage = msgNode.items.length === 0;
  1286. const node = startNode(1 /* NodeTypes.Plural */, offset, loc);
  1287. node.cases = [];
  1288. node.cases.push(msgNode);
  1289. do {
  1290. const msg = parseMessage(tokenizer);
  1291. if (!hasEmptyMessage) {
  1292. hasEmptyMessage = msg.items.length === 0;
  1293. }
  1294. node.cases.push(msg);
  1295. } while (context.currentType !== 13 /* TokenTypes.EOF */);
  1296. if (hasEmptyMessage) {
  1297. emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
  1298. }
  1299. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1300. return node;
  1301. }
  1302. function parseResource(tokenizer) {
  1303. const context = tokenizer.context();
  1304. const { offset, startLoc } = context;
  1305. const msgNode = parseMessage(tokenizer);
  1306. if (context.currentType === 13 /* TokenTypes.EOF */) {
  1307. return msgNode;
  1308. }
  1309. else {
  1310. return parsePlural(tokenizer, offset, startLoc, msgNode);
  1311. }
  1312. }
  1313. function parse(source) {
  1314. const tokenizer = createTokenizer(source, assign({}, options));
  1315. const context = tokenizer.context();
  1316. const node = startNode(0 /* NodeTypes.Resource */, context.offset, context.startLoc);
  1317. if (location && node.loc) {
  1318. node.loc.source = source;
  1319. }
  1320. node.body = parseResource(tokenizer);
  1321. if (options.onCacheKey) {
  1322. node.cacheKey = options.onCacheKey(source);
  1323. }
  1324. // assert whether achieved to EOF
  1325. if (context.currentType !== 13 /* TokenTypes.EOF */) {
  1326. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');
  1327. }
  1328. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1329. return node;
  1330. }
  1331. return { parse };
  1332. }
  1333. function getTokenCaption(token) {
  1334. if (token.type === 13 /* TokenTypes.EOF */) {
  1335. return 'EOF';
  1336. }
  1337. const name = (token.value || '').replace(/\r?\n/gu, '\\n');
  1338. return name.length > 10 ? name.slice(0, 9) + '…' : name;
  1339. }
  1340. function createTransformer(ast, options = {} // eslint-disable-line
  1341. ) {
  1342. const _context = {
  1343. ast,
  1344. helpers: new Set()
  1345. };
  1346. const context = () => _context;
  1347. const helper = (name) => {
  1348. _context.helpers.add(name);
  1349. return name;
  1350. };
  1351. return { context, helper };
  1352. }
  1353. function traverseNodes(nodes, transformer) {
  1354. for (let i = 0; i < nodes.length; i++) {
  1355. traverseNode(nodes[i], transformer);
  1356. }
  1357. }
  1358. function traverseNode(node, transformer) {
  1359. // TODO: if we need pre-hook of transform, should be implemented to here
  1360. switch (node.type) {
  1361. case 1 /* NodeTypes.Plural */:
  1362. traverseNodes(node.cases, transformer);
  1363. transformer.helper("plural" /* HelperNameMap.PLURAL */);
  1364. break;
  1365. case 2 /* NodeTypes.Message */:
  1366. traverseNodes(node.items, transformer);
  1367. break;
  1368. case 6 /* NodeTypes.Linked */: {
  1369. const linked = node;
  1370. traverseNode(linked.key, transformer);
  1371. transformer.helper("linked" /* HelperNameMap.LINKED */);
  1372. transformer.helper("type" /* HelperNameMap.TYPE */);
  1373. break;
  1374. }
  1375. case 5 /* NodeTypes.List */:
  1376. transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
  1377. transformer.helper("list" /* HelperNameMap.LIST */);
  1378. break;
  1379. case 4 /* NodeTypes.Named */:
  1380. transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
  1381. transformer.helper("named" /* HelperNameMap.NAMED */);
  1382. break;
  1383. }
  1384. // TODO: if we need post-hook of transform, should be implemented to here
  1385. }
  1386. // transform AST
  1387. function transform(ast, options = {} // eslint-disable-line
  1388. ) {
  1389. const transformer = createTransformer(ast);
  1390. transformer.helper("normalize" /* HelperNameMap.NORMALIZE */);
  1391. // traverse
  1392. ast.body && traverseNode(ast.body, transformer);
  1393. // set meta information
  1394. const context = transformer.context();
  1395. ast.helpers = Array.from(context.helpers);
  1396. }
  1397. function optimize(ast) {
  1398. const body = ast.body;
  1399. if (body.type === 2 /* NodeTypes.Message */) {
  1400. optimizeMessageNode(body);
  1401. }
  1402. else {
  1403. body.cases.forEach(c => optimizeMessageNode(c));
  1404. }
  1405. return ast;
  1406. }
  1407. function optimizeMessageNode(message) {
  1408. if (message.items.length === 1) {
  1409. const item = message.items[0];
  1410. if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
  1411. message.static = item.value;
  1412. delete item.value; // optimization for size
  1413. }
  1414. }
  1415. else {
  1416. const values = [];
  1417. for (let i = 0; i < message.items.length; i++) {
  1418. const item = message.items[i];
  1419. if (!(item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */)) {
  1420. break;
  1421. }
  1422. if (item.value == null) {
  1423. break;
  1424. }
  1425. values.push(item.value);
  1426. }
  1427. if (values.length === message.items.length) {
  1428. message.static = join(values);
  1429. for (let i = 0; i < message.items.length; i++) {
  1430. const item = message.items[i];
  1431. if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
  1432. delete item.value; // optimization for size
  1433. }
  1434. }
  1435. }
  1436. }
  1437. }
  1438. const ERROR_DOMAIN$1 = 'minifier';
  1439. /* eslint-disable @typescript-eslint/no-explicit-any */
  1440. function minify(node) {
  1441. node.t = node.type;
  1442. switch (node.type) {
  1443. case 0 /* NodeTypes.Resource */: {
  1444. const resource = node;
  1445. minify(resource.body);
  1446. resource.b = resource.body;
  1447. delete resource.body;
  1448. break;
  1449. }
  1450. case 1 /* NodeTypes.Plural */: {
  1451. const plural = node;
  1452. const cases = plural.cases;
  1453. for (let i = 0; i < cases.length; i++) {
  1454. minify(cases[i]);
  1455. }
  1456. plural.c = cases;
  1457. delete plural.cases;
  1458. break;
  1459. }
  1460. case 2 /* NodeTypes.Message */: {
  1461. const message = node;
  1462. const items = message.items;
  1463. for (let i = 0; i < items.length; i++) {
  1464. minify(items[i]);
  1465. }
  1466. message.i = items;
  1467. delete message.items;
  1468. if (message.static) {
  1469. message.s = message.static;
  1470. delete message.static;
  1471. }
  1472. break;
  1473. }
  1474. case 3 /* NodeTypes.Text */:
  1475. case 9 /* NodeTypes.Literal */:
  1476. case 8 /* NodeTypes.LinkedModifier */:
  1477. case 7 /* NodeTypes.LinkedKey */: {
  1478. const valueNode = node;
  1479. if (valueNode.value) {
  1480. valueNode.v = valueNode.value;
  1481. delete valueNode.value;
  1482. }
  1483. break;
  1484. }
  1485. case 6 /* NodeTypes.Linked */: {
  1486. const linked = node;
  1487. minify(linked.key);
  1488. linked.k = linked.key;
  1489. delete linked.key;
  1490. if (linked.modifier) {
  1491. minify(linked.modifier);
  1492. linked.m = linked.modifier;
  1493. delete linked.modifier;
  1494. }
  1495. break;
  1496. }
  1497. case 5 /* NodeTypes.List */: {
  1498. const list = node;
  1499. list.i = list.index;
  1500. delete list.index;
  1501. break;
  1502. }
  1503. case 4 /* NodeTypes.Named */: {
  1504. const named = node;
  1505. named.k = named.key;
  1506. delete named.key;
  1507. break;
  1508. }
  1509. default:
  1510. {
  1511. throw createCompileError(CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE, null, {
  1512. domain: ERROR_DOMAIN$1,
  1513. args: [node.type]
  1514. });
  1515. }
  1516. }
  1517. delete node.type;
  1518. }
  1519. /* eslint-enable @typescript-eslint/no-explicit-any */
  1520. // eslint-disable-next-line @typescript-eslint/triple-slash-reference
  1521. /// <reference types="source-map-js" />
  1522. const ERROR_DOMAIN = 'parser';
  1523. function createCodeGenerator(ast, options) {
  1524. const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
  1525. const location = options.location !== false;
  1526. const _context = {
  1527. filename,
  1528. code: '',
  1529. column: 1,
  1530. line: 1,
  1531. offset: 0,
  1532. map: undefined,
  1533. breakLineCode,
  1534. needIndent: _needIndent,
  1535. indentLevel: 0
  1536. };
  1537. if (location && ast.loc) {
  1538. _context.source = ast.loc.source;
  1539. }
  1540. const context = () => _context;
  1541. function push(code, node) {
  1542. _context.code += code;
  1543. }
  1544. function _newline(n, withBreakLine = true) {
  1545. const _breakLineCode = withBreakLine ? breakLineCode : '';
  1546. push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
  1547. }
  1548. function indent(withNewLine = true) {
  1549. const level = ++_context.indentLevel;
  1550. withNewLine && _newline(level);
  1551. }
  1552. function deindent(withNewLine = true) {
  1553. const level = --_context.indentLevel;
  1554. withNewLine && _newline(level);
  1555. }
  1556. function newline() {
  1557. _newline(_context.indentLevel);
  1558. }
  1559. const helper = (key) => `_${key}`;
  1560. const needIndent = () => _context.needIndent;
  1561. return {
  1562. context,
  1563. push,
  1564. indent,
  1565. deindent,
  1566. newline,
  1567. helper,
  1568. needIndent
  1569. };
  1570. }
  1571. function generateLinkedNode(generator, node) {
  1572. const { helper } = generator;
  1573. generator.push(`${helper("linked" /* HelperNameMap.LINKED */)}(`);
  1574. generateNode(generator, node.key);
  1575. if (node.modifier) {
  1576. generator.push(`, `);
  1577. generateNode(generator, node.modifier);
  1578. generator.push(`, _type`);
  1579. }
  1580. else {
  1581. generator.push(`, undefined, _type`);
  1582. }
  1583. generator.push(`)`);
  1584. }
  1585. function generateMessageNode(generator, node) {
  1586. const { helper, needIndent } = generator;
  1587. generator.push(`${helper("normalize" /* HelperNameMap.NORMALIZE */)}([`);
  1588. generator.indent(needIndent());
  1589. const length = node.items.length;
  1590. for (let i = 0; i < length; i++) {
  1591. generateNode(generator, node.items[i]);
  1592. if (i === length - 1) {
  1593. break;
  1594. }
  1595. generator.push(', ');
  1596. }
  1597. generator.deindent(needIndent());
  1598. generator.push('])');
  1599. }
  1600. function generatePluralNode(generator, node) {
  1601. const { helper, needIndent } = generator;
  1602. if (node.cases.length > 1) {
  1603. generator.push(`${helper("plural" /* HelperNameMap.PLURAL */)}([`);
  1604. generator.indent(needIndent());
  1605. const length = node.cases.length;
  1606. for (let i = 0; i < length; i++) {
  1607. generateNode(generator, node.cases[i]);
  1608. if (i === length - 1) {
  1609. break;
  1610. }
  1611. generator.push(', ');
  1612. }
  1613. generator.deindent(needIndent());
  1614. generator.push(`])`);
  1615. }
  1616. }
  1617. function generateResource(generator, node) {
  1618. if (node.body) {
  1619. generateNode(generator, node.body);
  1620. }
  1621. else {
  1622. generator.push('null');
  1623. }
  1624. }
  1625. function generateNode(generator, node) {
  1626. const { helper } = generator;
  1627. switch (node.type) {
  1628. case 0 /* NodeTypes.Resource */:
  1629. generateResource(generator, node);
  1630. break;
  1631. case 1 /* NodeTypes.Plural */:
  1632. generatePluralNode(generator, node);
  1633. break;
  1634. case 2 /* NodeTypes.Message */:
  1635. generateMessageNode(generator, node);
  1636. break;
  1637. case 6 /* NodeTypes.Linked */:
  1638. generateLinkedNode(generator, node);
  1639. break;
  1640. case 8 /* NodeTypes.LinkedModifier */:
  1641. generator.push(JSON.stringify(node.value), node);
  1642. break;
  1643. case 7 /* NodeTypes.LinkedKey */:
  1644. generator.push(JSON.stringify(node.value), node);
  1645. break;
  1646. case 5 /* NodeTypes.List */:
  1647. generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("list" /* HelperNameMap.LIST */)}(${node.index}))`, node);
  1648. break;
  1649. case 4 /* NodeTypes.Named */:
  1650. generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("named" /* HelperNameMap.NAMED */)}(${JSON.stringify(node.key)}))`, node);
  1651. break;
  1652. case 9 /* NodeTypes.Literal */:
  1653. generator.push(JSON.stringify(node.value), node);
  1654. break;
  1655. case 3 /* NodeTypes.Text */:
  1656. generator.push(JSON.stringify(node.value), node);
  1657. break;
  1658. default:
  1659. {
  1660. throw createCompileError(CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE, null, {
  1661. domain: ERROR_DOMAIN,
  1662. args: [node.type]
  1663. });
  1664. }
  1665. }
  1666. }
  1667. // generate code from AST
  1668. const generate = (ast, options = {}) => {
  1669. const mode = isString(options.mode) ? options.mode : 'normal';
  1670. const filename = isString(options.filename)
  1671. ? options.filename
  1672. : 'message.intl';
  1673. const sourceMap = !!options.sourceMap;
  1674. // prettier-ignore
  1675. const breakLineCode = options.breakLineCode != null
  1676. ? options.breakLineCode
  1677. : mode === 'arrow'
  1678. ? ';'
  1679. : '\n';
  1680. const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
  1681. const helpers = ast.helpers || [];
  1682. const generator = createCodeGenerator(ast, {
  1683. mode,
  1684. filename,
  1685. sourceMap,
  1686. breakLineCode,
  1687. needIndent
  1688. });
  1689. generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
  1690. generator.indent(needIndent);
  1691. if (helpers.length > 0) {
  1692. generator.push(`const { ${join(helpers.map(s => `${s}: _${s}`), ', ')} } = ctx`);
  1693. generator.newline();
  1694. }
  1695. generator.push(`return `);
  1696. generateNode(generator, ast);
  1697. generator.deindent(needIndent);
  1698. generator.push(`}`);
  1699. delete ast.helpers;
  1700. const { code, map } = generator.context();
  1701. return {
  1702. ast,
  1703. code,
  1704. map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
  1705. };
  1706. };
  1707. function baseCompile$1(source, options = {}) {
  1708. const assignedOptions = assign({}, options);
  1709. const jit = !!assignedOptions.jit;
  1710. const enalbeMinify = !!assignedOptions.minify;
  1711. const enambeOptimize = assignedOptions.optimize == null ? true : assignedOptions.optimize;
  1712. // parse source codes
  1713. const parser = createParser(assignedOptions);
  1714. const ast = parser.parse(source);
  1715. if (!jit) {
  1716. // transform ASTs
  1717. transform(ast, assignedOptions);
  1718. // generate javascript codes
  1719. return generate(ast, assignedOptions);
  1720. }
  1721. else {
  1722. // optimize ASTs
  1723. enambeOptimize && optimize(ast);
  1724. // minimize ASTs
  1725. enalbeMinify && minify(ast);
  1726. // In JIT mode, no ast transform, no code generation.
  1727. return { ast, code: '' };
  1728. }
  1729. }
  1730. function isMessageAST(val) {
  1731. return (isObject(val) &&
  1732. resolveType(val) === 0 &&
  1733. (hasOwn(val, 'b') || hasOwn(val, 'body')));
  1734. }
  1735. const PROPS_BODY = ['b', 'body'];
  1736. function resolveBody(node) {
  1737. return resolveProps(node, PROPS_BODY);
  1738. }
  1739. const PROPS_CASES = ['c', 'cases'];
  1740. function resolveCases(node) {
  1741. return resolveProps(node, PROPS_CASES, []);
  1742. }
  1743. const PROPS_STATIC = ['s', 'static'];
  1744. function resolveStatic(node) {
  1745. return resolveProps(node, PROPS_STATIC);
  1746. }
  1747. const PROPS_ITEMS = ['i', 'items'];
  1748. function resolveItems(node) {
  1749. return resolveProps(node, PROPS_ITEMS, []);
  1750. }
  1751. const PROPS_TYPE = ['t', 'type'];
  1752. function resolveType(node) {
  1753. return resolveProps(node, PROPS_TYPE);
  1754. }
  1755. const PROPS_VALUE = ['v', 'value'];
  1756. function resolveValue$1(node, type) {
  1757. const resolved = resolveProps(node, PROPS_VALUE);
  1758. if (resolved != null) {
  1759. return resolved;
  1760. }
  1761. else {
  1762. throw createUnhandleNodeError(type);
  1763. }
  1764. }
  1765. const PROPS_MODIFIER = ['m', 'modifier'];
  1766. function resolveLinkedModifier(node) {
  1767. return resolveProps(node, PROPS_MODIFIER);
  1768. }
  1769. const PROPS_KEY = ['k', 'key'];
  1770. function resolveLinkedKey(node) {
  1771. const resolved = resolveProps(node, PROPS_KEY);
  1772. if (resolved) {
  1773. return resolved;
  1774. }
  1775. else {
  1776. throw createUnhandleNodeError(6 /* NodeTypes.Linked */);
  1777. }
  1778. }
  1779. function resolveProps(node, props, defaultValue) {
  1780. for (let i = 0; i < props.length; i++) {
  1781. const prop = props[i];
  1782. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1783. if (hasOwn(node, prop) && node[prop] != null) {
  1784. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1785. return node[prop];
  1786. }
  1787. }
  1788. return defaultValue;
  1789. }
  1790. const AST_NODE_PROPS_KEYS = [
  1791. ...PROPS_BODY,
  1792. ...PROPS_CASES,
  1793. ...PROPS_STATIC,
  1794. ...PROPS_ITEMS,
  1795. ...PROPS_KEY,
  1796. ...PROPS_MODIFIER,
  1797. ...PROPS_VALUE,
  1798. ...PROPS_TYPE
  1799. ];
  1800. function createUnhandleNodeError(type) {
  1801. return new Error(`unhandled node type: ${type}`);
  1802. }
  1803. function format(ast) {
  1804. const msg = (ctx) => formatParts(ctx, ast);
  1805. return msg;
  1806. }
  1807. function formatParts(ctx, ast) {
  1808. const body = resolveBody(ast);
  1809. if (body == null) {
  1810. throw createUnhandleNodeError(0 /* NodeTypes.Resource */);
  1811. }
  1812. const type = resolveType(body);
  1813. if (type === 1 /* NodeTypes.Plural */) {
  1814. const plural = body;
  1815. const cases = resolveCases(plural);
  1816. return ctx.plural(cases.reduce((messages, c) => [
  1817. ...messages,
  1818. formatMessageParts(ctx, c)
  1819. ], []));
  1820. }
  1821. else {
  1822. return formatMessageParts(ctx, body);
  1823. }
  1824. }
  1825. function formatMessageParts(ctx, node) {
  1826. const static_ = resolveStatic(node);
  1827. if (static_ != null) {
  1828. return ctx.type === 'text'
  1829. ? static_
  1830. : ctx.normalize([static_]);
  1831. }
  1832. else {
  1833. const messages = resolveItems(node).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
  1834. return ctx.normalize(messages);
  1835. }
  1836. }
  1837. function formatMessagePart(ctx, node) {
  1838. const type = resolveType(node);
  1839. switch (type) {
  1840. case 3 /* NodeTypes.Text */: {
  1841. return resolveValue$1(node, type);
  1842. }
  1843. case 9 /* NodeTypes.Literal */: {
  1844. return resolveValue$1(node, type);
  1845. }
  1846. case 4 /* NodeTypes.Named */: {
  1847. const named = node;
  1848. if (hasOwn(named, 'k') && named.k) {
  1849. return ctx.interpolate(ctx.named(named.k));
  1850. }
  1851. if (hasOwn(named, 'key') && named.key) {
  1852. return ctx.interpolate(ctx.named(named.key));
  1853. }
  1854. throw createUnhandleNodeError(type);
  1855. }
  1856. case 5 /* NodeTypes.List */: {
  1857. const list = node;
  1858. if (hasOwn(list, 'i') && isNumber(list.i)) {
  1859. return ctx.interpolate(ctx.list(list.i));
  1860. }
  1861. if (hasOwn(list, 'index') && isNumber(list.index)) {
  1862. return ctx.interpolate(ctx.list(list.index));
  1863. }
  1864. throw createUnhandleNodeError(type);
  1865. }
  1866. case 6 /* NodeTypes.Linked */: {
  1867. const linked = node;
  1868. const modifier = resolveLinkedModifier(linked);
  1869. const key = resolveLinkedKey(linked);
  1870. return ctx.linked(formatMessagePart(ctx, key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);
  1871. }
  1872. case 7 /* NodeTypes.LinkedKey */: {
  1873. return resolveValue$1(node, type);
  1874. }
  1875. case 8 /* NodeTypes.LinkedModifier */: {
  1876. return resolveValue$1(node, type);
  1877. }
  1878. default:
  1879. throw new Error(`unhandled node on format message part: ${type}`);
  1880. }
  1881. }
  1882. const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
  1883. function checkHtmlMessage(source, warnHtmlMessage) {
  1884. if (warnHtmlMessage && detectHtmlTag(source)) {
  1885. warn(format$1(WARN_MESSAGE, { source }));
  1886. }
  1887. }
  1888. const defaultOnCacheKey = (message) => message;
  1889. let compileCache = create();
  1890. function baseCompile(message, options = {}) {
  1891. // error detecting on compile
  1892. let detectError = false;
  1893. const onError = options.onError || defaultOnError;
  1894. options.onError = (err) => {
  1895. detectError = true;
  1896. onError(err);
  1897. };
  1898. // compile with mesasge-compiler
  1899. return { ...baseCompile$1(message, options), detectError };
  1900. }
  1901. /* #__NO_SIDE_EFFECTS__ */
  1902. function compile(message, context) {
  1903. if (isString(message)) {
  1904. // check HTML message
  1905. const warnHtmlMessage = isBoolean(context.warnHtmlMessage)
  1906. ? context.warnHtmlMessage
  1907. : true;
  1908. checkHtmlMessage(message, warnHtmlMessage);
  1909. // check caches
  1910. const onCacheKey = context.onCacheKey || defaultOnCacheKey;
  1911. const cacheKey = onCacheKey(message);
  1912. const cached = compileCache[cacheKey];
  1913. if (cached) {
  1914. return cached;
  1915. }
  1916. // compile with JIT mode
  1917. const { ast, detectError } = baseCompile(message, {
  1918. ...context,
  1919. location: true,
  1920. jit: true
  1921. });
  1922. // compose message function from AST
  1923. const msg = format(ast);
  1924. // if occurred compile error, don't cache
  1925. return !detectError
  1926. ? (compileCache[cacheKey] = msg)
  1927. : msg;
  1928. }
  1929. else {
  1930. if (!isMessageAST(message)) {
  1931. warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);
  1932. return (() => message);
  1933. }
  1934. // AST case (passed from bundler)
  1935. const cacheKey = message.cacheKey;
  1936. if (cacheKey) {
  1937. const cached = compileCache[cacheKey];
  1938. if (cached) {
  1939. return cached;
  1940. }
  1941. // compose message function from message (AST)
  1942. return (compileCache[cacheKey] =
  1943. format(message));
  1944. }
  1945. else {
  1946. return format(message);
  1947. }
  1948. }
  1949. }
  1950. let devtools = null;
  1951. function setDevToolsHook(hook) {
  1952. devtools = hook;
  1953. }
  1954. function initI18nDevTools(i18n, version, meta) {
  1955. // TODO: queue if devtools is undefined
  1956. devtools &&
  1957. devtools.emit('i18n:init', {
  1958. timestamp: Date.now(),
  1959. i18n,
  1960. version,
  1961. meta
  1962. });
  1963. }
  1964. const translateDevTools =
  1965. /* #__PURE__*/ createDevToolsHook('function:translate');
  1966. function createDevToolsHook(hook) {
  1967. return (payloads) => devtools && devtools.emit(hook, payloads);
  1968. }
  1969. const CoreErrorCodes = {
  1970. INVALID_ARGUMENT: COMPILE_ERROR_CODES_EXTEND_POINT, // 17
  1971. INVALID_DATE_ARGUMENT: 18,
  1972. INVALID_ISO_DATE_ARGUMENT: 19,
  1973. NOT_SUPPORT_NON_STRING_MESSAGE: 20,
  1974. NOT_SUPPORT_LOCALE_PROMISE_VALUE: 21,
  1975. NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: 22,
  1976. NOT_SUPPORT_LOCALE_TYPE: 23
  1977. };
  1978. const CORE_ERROR_CODES_EXTEND_POINT = 24;
  1979. function createCoreError(code) {
  1980. return createCompileError(code, null, { messages: errorMessages$1 } );
  1981. }
  1982. /** @internal */
  1983. const errorMessages$1 = {
  1984. [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
  1985. [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
  1986. 'Make sure your Date represents a valid date.',
  1987. [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string',
  1988. [CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE]: 'Not support non-string message',
  1989. [CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE]: 'cannot support promise value',
  1990. [CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]: 'cannot support async function',
  1991. [CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE]: 'cannot support locale type'
  1992. };
  1993. /** @internal */
  1994. function getLocale(context, options) {
  1995. return options.locale != null
  1996. ? resolveLocale(options.locale)
  1997. : resolveLocale(context.locale);
  1998. }
  1999. let _resolveLocale;
  2000. /** @internal */
  2001. function resolveLocale(locale) {
  2002. if (isString(locale)) {
  2003. return locale;
  2004. }
  2005. else {
  2006. if (isFunction(locale)) {
  2007. if (locale.resolvedOnce && _resolveLocale != null) {
  2008. return _resolveLocale;
  2009. }
  2010. else if (locale.constructor.name === 'Function') {
  2011. const resolve = locale();
  2012. if (isPromise(resolve)) {
  2013. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);
  2014. }
  2015. return (_resolveLocale = resolve);
  2016. }
  2017. else {
  2018. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);
  2019. }
  2020. }
  2021. else {
  2022. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);
  2023. }
  2024. }
  2025. }
  2026. /**
  2027. * Fallback with simple implemenation
  2028. *
  2029. * @remarks
  2030. * A fallback locale function implemented with a simple fallback algorithm.
  2031. *
  2032. * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
  2033. *
  2034. * @param ctx - A {@link CoreContext | context}
  2035. * @param fallback - A {@link FallbackLocale | fallback locale}
  2036. * @param start - A starting {@link Locale | locale}
  2037. *
  2038. * @returns Fallback locales
  2039. *
  2040. * @VueI18nGeneral
  2041. */
  2042. function fallbackWithSimple(ctx, fallback, start) {
  2043. // prettier-ignore
  2044. return [...new Set([
  2045. start,
  2046. ...(isArray(fallback)
  2047. ? fallback
  2048. : isObject(fallback)
  2049. ? Object.keys(fallback)
  2050. : isString(fallback)
  2051. ? [fallback]
  2052. : [start])
  2053. ])];
  2054. }
  2055. /**
  2056. * Fallback with locale chain
  2057. *
  2058. * @remarks
  2059. * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
  2060. *
  2061. * @param ctx - A {@link CoreContext | context}
  2062. * @param fallback - A {@link FallbackLocale | fallback locale}
  2063. * @param start - A starting {@link Locale | locale}
  2064. *
  2065. * @returns Fallback locales
  2066. *
  2067. * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
  2068. *
  2069. * @VueI18nGeneral
  2070. */
  2071. function fallbackWithLocaleChain(ctx, fallback, start) {
  2072. const startLocale = isString(start) ? start : DEFAULT_LOCALE;
  2073. const context = ctx;
  2074. if (!context.__localeChainCache) {
  2075. context.__localeChainCache = new Map();
  2076. }
  2077. let chain = context.__localeChainCache.get(startLocale);
  2078. if (!chain) {
  2079. chain = [];
  2080. // first block defined by start
  2081. let block = [start];
  2082. // while any intervening block found
  2083. while (isArray(block)) {
  2084. block = appendBlockToChain(chain, block, fallback);
  2085. }
  2086. // prettier-ignore
  2087. // last block defined by default
  2088. const defaults = isArray(fallback) || !isPlainObject(fallback)
  2089. ? fallback
  2090. : fallback['default']
  2091. ? fallback['default']
  2092. : null;
  2093. // convert defaults to array
  2094. block = isString(defaults) ? [defaults] : defaults;
  2095. if (isArray(block)) {
  2096. appendBlockToChain(chain, block, false);
  2097. }
  2098. context.__localeChainCache.set(startLocale, chain);
  2099. }
  2100. return chain;
  2101. }
  2102. function appendBlockToChain(chain, block, blocks) {
  2103. let follow = true;
  2104. for (let i = 0; i < block.length && isBoolean(follow); i++) {
  2105. const locale = block[i];
  2106. if (isString(locale)) {
  2107. follow = appendLocaleToChain(chain, block[i], blocks);
  2108. }
  2109. }
  2110. return follow;
  2111. }
  2112. function appendLocaleToChain(chain, locale, blocks) {
  2113. let follow;
  2114. const tokens = locale.split('-');
  2115. do {
  2116. const target = tokens.join('-');
  2117. follow = appendItemToChain(chain, target, blocks);
  2118. tokens.splice(-1, 1);
  2119. } while (tokens.length && follow === true);
  2120. return follow;
  2121. }
  2122. function appendItemToChain(chain, target, blocks) {
  2123. let follow = false;
  2124. if (!chain.includes(target)) {
  2125. follow = true;
  2126. if (target) {
  2127. follow = target[target.length - 1] !== '!';
  2128. const locale = target.replace(/!/g, '');
  2129. chain.push(locale);
  2130. if ((isArray(blocks) || isPlainObject(blocks)) &&
  2131. blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
  2132. ) {
  2133. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2134. follow = blocks[locale];
  2135. }
  2136. }
  2137. }
  2138. return follow;
  2139. }
  2140. const pathStateMachine = [];
  2141. pathStateMachine[0 /* States.BEFORE_PATH */] = {
  2142. ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
  2143. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  2144. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  2145. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  2146. };
  2147. pathStateMachine[1 /* States.IN_PATH */] = {
  2148. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
  2149. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
  2150. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  2151. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  2152. };
  2153. pathStateMachine[2 /* States.BEFORE_IDENT */] = {
  2154. ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
  2155. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  2156. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
  2157. };
  2158. pathStateMachine[3 /* States.IN_IDENT */] = {
  2159. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  2160. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  2161. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
  2162. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
  2163. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
  2164. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
  2165. };
  2166. pathStateMachine[4 /* States.IN_SUB_PATH */] = {
  2167. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
  2168. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
  2169. ["[" /* PathCharTypes.LEFT_BRACKET */]: [
  2170. 4 /* States.IN_SUB_PATH */,
  2171. 2 /* Actions.INC_SUB_PATH_DEPTH */
  2172. ],
  2173. ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
  2174. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  2175. ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
  2176. };
  2177. pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
  2178. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  2179. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  2180. ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
  2181. };
  2182. pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
  2183. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  2184. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  2185. ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
  2186. };
  2187. /**
  2188. * Check if an expression is a literal value.
  2189. */
  2190. const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
  2191. function isLiteral(exp) {
  2192. return literalValueRE.test(exp);
  2193. }
  2194. /**
  2195. * Strip quotes from a string
  2196. */
  2197. function stripQuotes(str) {
  2198. const a = str.charCodeAt(0);
  2199. const b = str.charCodeAt(str.length - 1);
  2200. return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
  2201. }
  2202. /**
  2203. * Determine the type of a character in a keypath.
  2204. */
  2205. function getPathCharType(ch) {
  2206. if (ch === undefined || ch === null) {
  2207. return "o" /* PathCharTypes.END_OF_FAIL */;
  2208. }
  2209. const code = ch.charCodeAt(0);
  2210. switch (code) {
  2211. case 0x5b: // [
  2212. case 0x5d: // ]
  2213. case 0x2e: // .
  2214. case 0x22: // "
  2215. case 0x27: // '
  2216. return ch;
  2217. case 0x5f: // _
  2218. case 0x24: // $
  2219. case 0x2d: // -
  2220. return "i" /* PathCharTypes.IDENT */;
  2221. case 0x09: // Tab (HT)
  2222. case 0x0a: // Newline (LF)
  2223. case 0x0d: // Return (CR)
  2224. case 0xa0: // No-break space (NBSP)
  2225. case 0xfeff: // Byte Order Mark (BOM)
  2226. case 0x2028: // Line Separator (LS)
  2227. case 0x2029: // Paragraph Separator (PS)
  2228. return "w" /* PathCharTypes.WORKSPACE */;
  2229. }
  2230. return "i" /* PathCharTypes.IDENT */;
  2231. }
  2232. /**
  2233. * Format a subPath, return its plain form if it is
  2234. * a literal string or number. Otherwise prepend the
  2235. * dynamic indicator (*).
  2236. */
  2237. function formatSubPath(path) {
  2238. const trimmed = path.trim();
  2239. // invalid leading 0
  2240. if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
  2241. return false;
  2242. }
  2243. return isLiteral(trimmed)
  2244. ? stripQuotes(trimmed)
  2245. : "*" /* PathCharTypes.ASTARISK */ + trimmed;
  2246. }
  2247. /**
  2248. * Parse a string path into an array of segments
  2249. */
  2250. function parse(path) {
  2251. const keys = [];
  2252. let index = -1;
  2253. let mode = 0 /* States.BEFORE_PATH */;
  2254. let subPathDepth = 0;
  2255. let c;
  2256. let key; // eslint-disable-line
  2257. let newChar;
  2258. let type;
  2259. let transition;
  2260. let action;
  2261. let typeMap;
  2262. const actions = [];
  2263. actions[0 /* Actions.APPEND */] = () => {
  2264. if (key === undefined) {
  2265. key = newChar;
  2266. }
  2267. else {
  2268. key += newChar;
  2269. }
  2270. };
  2271. actions[1 /* Actions.PUSH */] = () => {
  2272. if (key !== undefined) {
  2273. keys.push(key);
  2274. key = undefined;
  2275. }
  2276. };
  2277. actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
  2278. actions[0 /* Actions.APPEND */]();
  2279. subPathDepth++;
  2280. };
  2281. actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
  2282. if (subPathDepth > 0) {
  2283. subPathDepth--;
  2284. mode = 4 /* States.IN_SUB_PATH */;
  2285. actions[0 /* Actions.APPEND */]();
  2286. }
  2287. else {
  2288. subPathDepth = 0;
  2289. if (key === undefined) {
  2290. return false;
  2291. }
  2292. key = formatSubPath(key);
  2293. if (key === false) {
  2294. return false;
  2295. }
  2296. else {
  2297. actions[1 /* Actions.PUSH */]();
  2298. }
  2299. }
  2300. };
  2301. function maybeUnescapeQuote() {
  2302. const nextChar = path[index + 1];
  2303. if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
  2304. nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
  2305. (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
  2306. nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
  2307. index++;
  2308. newChar = '\\' + nextChar;
  2309. actions[0 /* Actions.APPEND */]();
  2310. return true;
  2311. }
  2312. }
  2313. while (mode !== null) {
  2314. index++;
  2315. c = path[index];
  2316. if (c === '\\' && maybeUnescapeQuote()) {
  2317. continue;
  2318. }
  2319. type = getPathCharType(c);
  2320. typeMap = pathStateMachine[mode];
  2321. transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
  2322. // check parse error
  2323. if (transition === 8 /* States.ERROR */) {
  2324. return;
  2325. }
  2326. mode = transition[0];
  2327. if (transition[1] !== undefined) {
  2328. action = actions[transition[1]];
  2329. if (action) {
  2330. newChar = c;
  2331. if (action() === false) {
  2332. return;
  2333. }
  2334. }
  2335. }
  2336. // check parse finish
  2337. if (mode === 7 /* States.AFTER_PATH */) {
  2338. return keys;
  2339. }
  2340. }
  2341. }
  2342. // path token cache
  2343. const cache = new Map();
  2344. /**
  2345. * key-value message resolver
  2346. *
  2347. * @remarks
  2348. * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
  2349. *
  2350. * @param obj - A target object to be resolved with path
  2351. * @param path - A {@link Path | path} to resolve the value of message
  2352. *
  2353. * @returns A resolved {@link PathValue | path value}
  2354. *
  2355. * @VueI18nGeneral
  2356. */
  2357. function resolveWithKeyValue(obj, path) {
  2358. return isObject(obj) ? obj[path] : null;
  2359. }
  2360. /**
  2361. * message resolver
  2362. *
  2363. * @remarks
  2364. * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
  2365. *
  2366. * @param obj - A target object to be resolved with path
  2367. * @param path - A {@link Path | path} to resolve the value of message
  2368. *
  2369. * @returns A resolved {@link PathValue | path value}
  2370. *
  2371. * @VueI18nGeneral
  2372. */
  2373. function resolveValue(obj, path) {
  2374. // check object
  2375. if (!isObject(obj)) {
  2376. return null;
  2377. }
  2378. // parse path
  2379. let hit = cache.get(path);
  2380. if (!hit) {
  2381. hit = parse(path);
  2382. if (hit) {
  2383. cache.set(path, hit);
  2384. }
  2385. }
  2386. // check hit
  2387. if (!hit) {
  2388. return null;
  2389. }
  2390. // resolve path value
  2391. const len = hit.length;
  2392. let last = obj;
  2393. let i = 0;
  2394. while (i < len) {
  2395. const key = hit[i];
  2396. /**
  2397. * NOTE:
  2398. * if `key` is intlify message format AST node key and `last` is intlify message format AST, skip it.
  2399. * because the AST node is not a key-value structure.
  2400. */
  2401. if (AST_NODE_PROPS_KEYS.includes(key) && isMessageAST(last)) {
  2402. return null;
  2403. }
  2404. const val = last[key];
  2405. if (val === undefined) {
  2406. return null;
  2407. }
  2408. if (isFunction(last)) {
  2409. return null;
  2410. }
  2411. last = val;
  2412. i++;
  2413. }
  2414. return last;
  2415. }
  2416. const CoreWarnCodes = {
  2417. NOT_FOUND_KEY: 1,
  2418. FALLBACK_TO_TRANSLATE: 2,
  2419. CANNOT_FORMAT_NUMBER: 3,
  2420. FALLBACK_TO_NUMBER_FORMAT: 4,
  2421. CANNOT_FORMAT_DATE: 5,
  2422. FALLBACK_TO_DATE_FORMAT: 6,
  2423. EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: 7
  2424. };
  2425. const CORE_WARN_CODES_EXTEND_POINT = 8;
  2426. /** @internal */
  2427. const warnMessages$1 = {
  2428. [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
  2429. [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
  2430. [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
  2431. [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
  2432. [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
  2433. [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
  2434. [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.`
  2435. };
  2436. function getWarnMessage$1(code, ...args) {
  2437. return format$1(warnMessages$1[code], ...args);
  2438. }
  2439. /* eslint-disable @typescript-eslint/no-explicit-any */
  2440. /**
  2441. * Intlify core-base version
  2442. * @internal
  2443. */
  2444. const VERSION$1 = '11.1.3';
  2445. const NOT_REOSLVED = -1;
  2446. const DEFAULT_LOCALE = 'en-US';
  2447. const MISSING_RESOLVE_VALUE = '';
  2448. const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
  2449. function getDefaultLinkedModifiers() {
  2450. return {
  2451. upper: (val, type) => {
  2452. // prettier-ignore
  2453. return type === 'text' && isString(val)
  2454. ? val.toUpperCase()
  2455. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  2456. ? val.children.toUpperCase()
  2457. : val;
  2458. },
  2459. lower: (val, type) => {
  2460. // prettier-ignore
  2461. return type === 'text' && isString(val)
  2462. ? val.toLowerCase()
  2463. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  2464. ? val.children.toLowerCase()
  2465. : val;
  2466. },
  2467. capitalize: (val, type) => {
  2468. // prettier-ignore
  2469. return (type === 'text' && isString(val)
  2470. ? capitalize(val)
  2471. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  2472. ? capitalize(val.children)
  2473. : val);
  2474. }
  2475. };
  2476. }
  2477. let _compiler;
  2478. function registerMessageCompiler(compiler) {
  2479. _compiler = compiler;
  2480. }
  2481. let _resolver;
  2482. /**
  2483. * Register the message resolver
  2484. *
  2485. * @param resolver - A {@link MessageResolver} function
  2486. *
  2487. * @VueI18nGeneral
  2488. */
  2489. function registerMessageResolver(resolver) {
  2490. _resolver = resolver;
  2491. }
  2492. let _fallbacker;
  2493. /**
  2494. * Register the locale fallbacker
  2495. *
  2496. * @param fallbacker - A {@link LocaleFallbacker} function
  2497. *
  2498. * @VueI18nGeneral
  2499. */
  2500. function registerLocaleFallbacker(fallbacker) {
  2501. _fallbacker = fallbacker;
  2502. }
  2503. // Additional Meta for Intlify DevTools
  2504. let _additionalMeta = null;
  2505. /* #__NO_SIDE_EFFECTS__ */
  2506. const setAdditionalMeta = (meta) => {
  2507. _additionalMeta = meta;
  2508. };
  2509. /* #__NO_SIDE_EFFECTS__ */
  2510. const getAdditionalMeta = () => _additionalMeta;
  2511. let _fallbackContext = null;
  2512. const setFallbackContext = (context) => {
  2513. _fallbackContext = context;
  2514. };
  2515. const getFallbackContext = () => _fallbackContext;
  2516. // ID for CoreContext
  2517. let _cid = 0;
  2518. function createCoreContext(options = {}) {
  2519. // setup options
  2520. const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
  2521. const version = isString(options.version) ? options.version : VERSION$1;
  2522. const locale = isString(options.locale) || isFunction(options.locale)
  2523. ? options.locale
  2524. : DEFAULT_LOCALE;
  2525. const _locale = isFunction(locale) ? DEFAULT_LOCALE : locale;
  2526. const fallbackLocale = isArray(options.fallbackLocale) ||
  2527. isPlainObject(options.fallbackLocale) ||
  2528. isString(options.fallbackLocale) ||
  2529. options.fallbackLocale === false
  2530. ? options.fallbackLocale
  2531. : _locale;
  2532. const messages = isPlainObject(options.messages)
  2533. ? options.messages
  2534. : createResources(_locale);
  2535. const datetimeFormats = isPlainObject(options.datetimeFormats)
  2536. ? options.datetimeFormats
  2537. : createResources(_locale)
  2538. ;
  2539. const numberFormats = isPlainObject(options.numberFormats)
  2540. ? options.numberFormats
  2541. : createResources(_locale)
  2542. ;
  2543. const modifiers = assign(create(), options.modifiers, getDefaultLinkedModifiers());
  2544. const pluralRules = options.pluralRules || create();
  2545. const missing = isFunction(options.missing) ? options.missing : null;
  2546. const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  2547. ? options.missingWarn
  2548. : true;
  2549. const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  2550. ? options.fallbackWarn
  2551. : true;
  2552. const fallbackFormat = !!options.fallbackFormat;
  2553. const unresolving = !!options.unresolving;
  2554. const postTranslation = isFunction(options.postTranslation)
  2555. ? options.postTranslation
  2556. : null;
  2557. const processor = isPlainObject(options.processor) ? options.processor : null;
  2558. const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
  2559. ? options.warnHtmlMessage
  2560. : true;
  2561. const escapeParameter = !!options.escapeParameter;
  2562. const messageCompiler = isFunction(options.messageCompiler)
  2563. ? options.messageCompiler
  2564. : _compiler;
  2565. const messageResolver = isFunction(options.messageResolver)
  2566. ? options.messageResolver
  2567. : _resolver || resolveWithKeyValue;
  2568. const localeFallbacker = isFunction(options.localeFallbacker)
  2569. ? options.localeFallbacker
  2570. : _fallbacker || fallbackWithSimple;
  2571. const fallbackContext = isObject(options.fallbackContext)
  2572. ? options.fallbackContext
  2573. : undefined;
  2574. // setup internal options
  2575. const internalOptions = options;
  2576. const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
  2577. ? internalOptions.__datetimeFormatters
  2578. : new Map()
  2579. ;
  2580. const __numberFormatters = isObject(internalOptions.__numberFormatters)
  2581. ? internalOptions.__numberFormatters
  2582. : new Map()
  2583. ;
  2584. const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
  2585. _cid++;
  2586. const context = {
  2587. version,
  2588. cid: _cid,
  2589. locale,
  2590. fallbackLocale,
  2591. messages,
  2592. modifiers,
  2593. pluralRules,
  2594. missing,
  2595. missingWarn,
  2596. fallbackWarn,
  2597. fallbackFormat,
  2598. unresolving,
  2599. postTranslation,
  2600. processor,
  2601. warnHtmlMessage,
  2602. escapeParameter,
  2603. messageCompiler,
  2604. messageResolver,
  2605. localeFallbacker,
  2606. fallbackContext,
  2607. onWarn,
  2608. __meta
  2609. };
  2610. {
  2611. context.datetimeFormats = datetimeFormats;
  2612. context.numberFormats = numberFormats;
  2613. context.__datetimeFormatters = __datetimeFormatters;
  2614. context.__numberFormatters = __numberFormatters;
  2615. }
  2616. // for vue-devtools timeline event
  2617. {
  2618. context.__v_emitter =
  2619. internalOptions.__v_emitter != null
  2620. ? internalOptions.__v_emitter
  2621. : undefined;
  2622. }
  2623. // NOTE: experimental !!
  2624. {
  2625. initI18nDevTools(context, version, __meta);
  2626. }
  2627. return context;
  2628. }
  2629. const createResources = (locale) => ({ [locale]: create() });
  2630. /** @internal */
  2631. function isTranslateFallbackWarn(fallback, key) {
  2632. return fallback instanceof RegExp ? fallback.test(key) : fallback;
  2633. }
  2634. /** @internal */
  2635. function isTranslateMissingWarn(missing, key) {
  2636. return missing instanceof RegExp ? missing.test(key) : missing;
  2637. }
  2638. /** @internal */
  2639. function handleMissing(context, key, locale, missingWarn, type) {
  2640. const { missing, onWarn } = context;
  2641. // for vue-devtools timeline event
  2642. {
  2643. const emitter = context.__v_emitter;
  2644. if (emitter) {
  2645. emitter.emit('missing', {
  2646. locale,
  2647. key,
  2648. type,
  2649. groupId: `${type}:${key}`
  2650. });
  2651. }
  2652. }
  2653. if (missing !== null) {
  2654. const ret = missing(context, locale, key, type);
  2655. return isString(ret) ? ret : key;
  2656. }
  2657. else {
  2658. if (isTranslateMissingWarn(missingWarn, key)) {
  2659. onWarn(getWarnMessage$1(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
  2660. }
  2661. return key;
  2662. }
  2663. }
  2664. /** @internal */
  2665. function updateFallbackLocale(ctx, locale, fallback) {
  2666. const context = ctx;
  2667. context.__localeChainCache = new Map();
  2668. ctx.localeFallbacker(ctx, fallback, locale);
  2669. }
  2670. /** @internal */
  2671. function isAlmostSameLocale(locale, compareLocale) {
  2672. if (locale === compareLocale)
  2673. return false;
  2674. return locale.split('-')[0] === compareLocale.split('-')[0];
  2675. }
  2676. /** @internal */
  2677. function isImplicitFallback(targetLocale, locales) {
  2678. const index = locales.indexOf(targetLocale);
  2679. if (index === -1) {
  2680. return false;
  2681. }
  2682. for (let i = index + 1; i < locales.length; i++) {
  2683. if (isAlmostSameLocale(targetLocale, locales[i])) {
  2684. return true;
  2685. }
  2686. }
  2687. return false;
  2688. }
  2689. /* eslint-enable @typescript-eslint/no-explicit-any */
  2690. const intlDefined = typeof Intl !== 'undefined';
  2691. const Availabilities = {
  2692. dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
  2693. numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
  2694. };
  2695. // implementation of `datetime` function
  2696. function datetime(context, ...args) {
  2697. const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  2698. const { __datetimeFormatters } = context;
  2699. if (!Availabilities.dateTimeFormat) {
  2700. onWarn(getWarnMessage$1(CoreWarnCodes.CANNOT_FORMAT_DATE));
  2701. return MISSING_RESOLVE_VALUE;
  2702. }
  2703. const [key, value, options, overrides] = parseDateTimeArgs(...args);
  2704. const missingWarn = isBoolean(options.missingWarn)
  2705. ? options.missingWarn
  2706. : context.missingWarn;
  2707. const fallbackWarn = isBoolean(options.fallbackWarn)
  2708. ? options.fallbackWarn
  2709. : context.fallbackWarn;
  2710. const part = !!options.part;
  2711. const locale = getLocale(context, options);
  2712. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  2713. fallbackLocale, locale);
  2714. if (!isString(key) || key === '') {
  2715. return new Intl.DateTimeFormat(locale, overrides).format(value);
  2716. }
  2717. // resolve format
  2718. let datetimeFormat = {};
  2719. let targetLocale;
  2720. let format = null;
  2721. let from = locale;
  2722. let to = null;
  2723. const type = 'datetime format';
  2724. for (let i = 0; i < locales.length; i++) {
  2725. targetLocale = to = locales[i];
  2726. if (locale !== targetLocale &&
  2727. isTranslateFallbackWarn(fallbackWarn, key)) {
  2728. onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
  2729. key,
  2730. target: targetLocale
  2731. }));
  2732. }
  2733. // for vue-devtools timeline event
  2734. if (locale !== targetLocale) {
  2735. const emitter = context.__v_emitter;
  2736. if (emitter) {
  2737. emitter.emit('fallback', {
  2738. type,
  2739. key,
  2740. from,
  2741. to,
  2742. groupId: `${type}:${key}`
  2743. });
  2744. }
  2745. }
  2746. datetimeFormat =
  2747. datetimeFormats[targetLocale] || {};
  2748. format = datetimeFormat[key];
  2749. if (isPlainObject(format))
  2750. break;
  2751. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  2752. from = to;
  2753. }
  2754. // checking format and target locale
  2755. if (!isPlainObject(format) || !isString(targetLocale)) {
  2756. return unresolving ? NOT_REOSLVED : key;
  2757. }
  2758. let id = `${targetLocale}__${key}`;
  2759. if (!isEmptyObject(overrides)) {
  2760. id = `${id}__${JSON.stringify(overrides)}`;
  2761. }
  2762. let formatter = __datetimeFormatters.get(id);
  2763. if (!formatter) {
  2764. formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
  2765. __datetimeFormatters.set(id, formatter);
  2766. }
  2767. return !part ? formatter.format(value) : formatter.formatToParts(value);
  2768. }
  2769. /** @internal */
  2770. const DATETIME_FORMAT_OPTIONS_KEYS = [
  2771. 'localeMatcher',
  2772. 'weekday',
  2773. 'era',
  2774. 'year',
  2775. 'month',
  2776. 'day',
  2777. 'hour',
  2778. 'minute',
  2779. 'second',
  2780. 'timeZoneName',
  2781. 'formatMatcher',
  2782. 'hour12',
  2783. 'timeZone',
  2784. 'dateStyle',
  2785. 'timeStyle',
  2786. 'calendar',
  2787. 'dayPeriod',
  2788. 'numberingSystem',
  2789. 'hourCycle',
  2790. 'fractionalSecondDigits'
  2791. ];
  2792. /** @internal */
  2793. function parseDateTimeArgs(...args) {
  2794. const [arg1, arg2, arg3, arg4] = args;
  2795. const options = create();
  2796. let overrides = create();
  2797. let value;
  2798. if (isString(arg1)) {
  2799. // Only allow ISO strings - other date formats are often supported,
  2800. // but may cause different results in different browsers.
  2801. const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
  2802. if (!matches) {
  2803. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  2804. }
  2805. // Some browsers can not parse the iso datetime separated by space,
  2806. // this is a compromise solution by replace the 'T'/' ' with 'T'
  2807. const dateTime = matches[3]
  2808. ? matches[3].trim().startsWith('T')
  2809. ? `${matches[1].trim()}${matches[3].trim()}`
  2810. : `${matches[1].trim()}T${matches[3].trim()}`
  2811. : matches[1].trim();
  2812. value = new Date(dateTime);
  2813. try {
  2814. // This will fail if the date is not valid
  2815. value.toISOString();
  2816. }
  2817. catch {
  2818. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  2819. }
  2820. }
  2821. else if (isDate(arg1)) {
  2822. if (isNaN(arg1.getTime())) {
  2823. throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
  2824. }
  2825. value = arg1;
  2826. }
  2827. else if (isNumber(arg1)) {
  2828. value = arg1;
  2829. }
  2830. else {
  2831. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  2832. }
  2833. if (isString(arg2)) {
  2834. options.key = arg2;
  2835. }
  2836. else if (isPlainObject(arg2)) {
  2837. Object.keys(arg2).forEach(key => {
  2838. if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
  2839. overrides[key] = arg2[key];
  2840. }
  2841. else {
  2842. options[key] = arg2[key];
  2843. }
  2844. });
  2845. }
  2846. if (isString(arg3)) {
  2847. options.locale = arg3;
  2848. }
  2849. else if (isPlainObject(arg3)) {
  2850. overrides = arg3;
  2851. }
  2852. if (isPlainObject(arg4)) {
  2853. overrides = arg4;
  2854. }
  2855. return [options.key || '', value, options, overrides];
  2856. }
  2857. /** @internal */
  2858. function clearDateTimeFormat(ctx, locale, format) {
  2859. const context = ctx;
  2860. for (const key in format) {
  2861. const id = `${locale}__${key}`;
  2862. if (!context.__datetimeFormatters.has(id)) {
  2863. continue;
  2864. }
  2865. context.__datetimeFormatters.delete(id);
  2866. }
  2867. }
  2868. // implementation of `number` function
  2869. function number(context, ...args) {
  2870. const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  2871. const { __numberFormatters } = context;
  2872. if (!Availabilities.numberFormat) {
  2873. onWarn(getWarnMessage$1(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
  2874. return MISSING_RESOLVE_VALUE;
  2875. }
  2876. const [key, value, options, overrides] = parseNumberArgs(...args);
  2877. const missingWarn = isBoolean(options.missingWarn)
  2878. ? options.missingWarn
  2879. : context.missingWarn;
  2880. const fallbackWarn = isBoolean(options.fallbackWarn)
  2881. ? options.fallbackWarn
  2882. : context.fallbackWarn;
  2883. const part = !!options.part;
  2884. const locale = getLocale(context, options);
  2885. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  2886. fallbackLocale, locale);
  2887. if (!isString(key) || key === '') {
  2888. return new Intl.NumberFormat(locale, overrides).format(value);
  2889. }
  2890. // resolve format
  2891. let numberFormat = {};
  2892. let targetLocale;
  2893. let format = null;
  2894. let from = locale;
  2895. let to = null;
  2896. const type = 'number format';
  2897. for (let i = 0; i < locales.length; i++) {
  2898. targetLocale = to = locales[i];
  2899. if (locale !== targetLocale &&
  2900. isTranslateFallbackWarn(fallbackWarn, key)) {
  2901. onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
  2902. key,
  2903. target: targetLocale
  2904. }));
  2905. }
  2906. // for vue-devtools timeline event
  2907. if (locale !== targetLocale) {
  2908. const emitter = context.__v_emitter;
  2909. if (emitter) {
  2910. emitter.emit('fallback', {
  2911. type,
  2912. key,
  2913. from,
  2914. to,
  2915. groupId: `${type}:${key}`
  2916. });
  2917. }
  2918. }
  2919. numberFormat =
  2920. numberFormats[targetLocale] || {};
  2921. format = numberFormat[key];
  2922. if (isPlainObject(format))
  2923. break;
  2924. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  2925. from = to;
  2926. }
  2927. // checking format and target locale
  2928. if (!isPlainObject(format) || !isString(targetLocale)) {
  2929. return unresolving ? NOT_REOSLVED : key;
  2930. }
  2931. let id = `${targetLocale}__${key}`;
  2932. if (!isEmptyObject(overrides)) {
  2933. id = `${id}__${JSON.stringify(overrides)}`;
  2934. }
  2935. let formatter = __numberFormatters.get(id);
  2936. if (!formatter) {
  2937. formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
  2938. __numberFormatters.set(id, formatter);
  2939. }
  2940. return !part ? formatter.format(value) : formatter.formatToParts(value);
  2941. }
  2942. /** @internal */
  2943. const NUMBER_FORMAT_OPTIONS_KEYS = [
  2944. 'localeMatcher',
  2945. 'style',
  2946. 'currency',
  2947. 'currencyDisplay',
  2948. 'currencySign',
  2949. 'useGrouping',
  2950. 'minimumIntegerDigits',
  2951. 'minimumFractionDigits',
  2952. 'maximumFractionDigits',
  2953. 'minimumSignificantDigits',
  2954. 'maximumSignificantDigits',
  2955. 'compactDisplay',
  2956. 'notation',
  2957. 'signDisplay',
  2958. 'unit',
  2959. 'unitDisplay',
  2960. 'roundingMode',
  2961. 'roundingPriority',
  2962. 'roundingIncrement',
  2963. 'trailingZeroDisplay'
  2964. ];
  2965. /** @internal */
  2966. function parseNumberArgs(...args) {
  2967. const [arg1, arg2, arg3, arg4] = args;
  2968. const options = create();
  2969. let overrides = create();
  2970. if (!isNumber(arg1)) {
  2971. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  2972. }
  2973. const value = arg1;
  2974. if (isString(arg2)) {
  2975. options.key = arg2;
  2976. }
  2977. else if (isPlainObject(arg2)) {
  2978. Object.keys(arg2).forEach(key => {
  2979. if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
  2980. overrides[key] = arg2[key];
  2981. }
  2982. else {
  2983. options[key] = arg2[key];
  2984. }
  2985. });
  2986. }
  2987. if (isString(arg3)) {
  2988. options.locale = arg3;
  2989. }
  2990. else if (isPlainObject(arg3)) {
  2991. overrides = arg3;
  2992. }
  2993. if (isPlainObject(arg4)) {
  2994. overrides = arg4;
  2995. }
  2996. return [options.key || '', value, options, overrides];
  2997. }
  2998. /** @internal */
  2999. function clearNumberFormat(ctx, locale, format) {
  3000. const context = ctx;
  3001. for (const key in format) {
  3002. const id = `${locale}__${key}`;
  3003. if (!context.__numberFormatters.has(id)) {
  3004. continue;
  3005. }
  3006. context.__numberFormatters.delete(id);
  3007. }
  3008. }
  3009. const DEFAULT_MODIFIER = (str) => str;
  3010. const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
  3011. const DEFAULT_MESSAGE_DATA_TYPE = 'text';
  3012. const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);
  3013. const DEFAULT_INTERPOLATE = toDisplayString;
  3014. function pluralDefault(choice, choicesLength) {
  3015. choice = Math.abs(choice);
  3016. if (choicesLength === 2) {
  3017. // prettier-ignore
  3018. return choice
  3019. ? choice > 1
  3020. ? 1
  3021. : 0
  3022. : 1;
  3023. }
  3024. return choice ? Math.min(choice, 2) : 0;
  3025. }
  3026. function getPluralIndex(options) {
  3027. // prettier-ignore
  3028. const index = isNumber(options.pluralIndex)
  3029. ? options.pluralIndex
  3030. : -1;
  3031. // prettier-ignore
  3032. return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
  3033. ? isNumber(options.named.count)
  3034. ? options.named.count
  3035. : isNumber(options.named.n)
  3036. ? options.named.n
  3037. : index
  3038. : index;
  3039. }
  3040. function normalizeNamed(pluralIndex, props) {
  3041. if (!props.count) {
  3042. props.count = pluralIndex;
  3043. }
  3044. if (!props.n) {
  3045. props.n = pluralIndex;
  3046. }
  3047. }
  3048. function createMessageContext(options = {}) {
  3049. const locale = options.locale;
  3050. const pluralIndex = getPluralIndex(options);
  3051. const pluralRule = isObject(options.pluralRules) &&
  3052. isString(locale) &&
  3053. isFunction(options.pluralRules[locale])
  3054. ? options.pluralRules[locale]
  3055. : pluralDefault;
  3056. const orgPluralRule = isObject(options.pluralRules) &&
  3057. isString(locale) &&
  3058. isFunction(options.pluralRules[locale])
  3059. ? pluralDefault
  3060. : undefined;
  3061. const plural = (messages) => {
  3062. return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
  3063. };
  3064. const _list = options.list || [];
  3065. const list = (index) => _list[index];
  3066. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3067. const _named = options.named || create();
  3068. isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
  3069. const named = (key) => _named[key];
  3070. function message(key, useLinked) {
  3071. // prettier-ignore
  3072. const msg = isFunction(options.messages)
  3073. ? options.messages(key, !!useLinked)
  3074. : isObject(options.messages)
  3075. ? options.messages[key]
  3076. : false;
  3077. return !msg
  3078. ? options.parent
  3079. ? options.parent.message(key) // resolve from parent messages
  3080. : DEFAULT_MESSAGE
  3081. : msg;
  3082. }
  3083. const _modifier = (name) => options.modifiers
  3084. ? options.modifiers[name]
  3085. : DEFAULT_MODIFIER;
  3086. const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
  3087. ? options.processor.normalize
  3088. : DEFAULT_NORMALIZE;
  3089. const interpolate = isPlainObject(options.processor) &&
  3090. isFunction(options.processor.interpolate)
  3091. ? options.processor.interpolate
  3092. : DEFAULT_INTERPOLATE;
  3093. const type = isPlainObject(options.processor) && isString(options.processor.type)
  3094. ? options.processor.type
  3095. : DEFAULT_MESSAGE_DATA_TYPE;
  3096. const linked = (key, ...args) => {
  3097. const [arg1, arg2] = args;
  3098. let type = 'text';
  3099. let modifier = '';
  3100. if (args.length === 1) {
  3101. if (isObject(arg1)) {
  3102. modifier = arg1.modifier || modifier;
  3103. type = arg1.type || type;
  3104. }
  3105. else if (isString(arg1)) {
  3106. modifier = arg1 || modifier;
  3107. }
  3108. }
  3109. else if (args.length === 2) {
  3110. if (isString(arg1)) {
  3111. modifier = arg1 || modifier;
  3112. }
  3113. if (isString(arg2)) {
  3114. type = arg2 || type;
  3115. }
  3116. }
  3117. const ret = message(key, true)(ctx);
  3118. const msg =
  3119. // The message in vnode resolved with linked are returned as an array by processor.nomalize
  3120. type === 'vnode' && isArray(ret) && modifier
  3121. ? ret[0]
  3122. : ret;
  3123. return modifier ? _modifier(modifier)(msg, type) : msg;
  3124. };
  3125. const ctx = {
  3126. ["list" /* HelperNameMap.LIST */]: list,
  3127. ["named" /* HelperNameMap.NAMED */]: named,
  3128. ["plural" /* HelperNameMap.PLURAL */]: plural,
  3129. ["linked" /* HelperNameMap.LINKED */]: linked,
  3130. ["message" /* HelperNameMap.MESSAGE */]: message,
  3131. ["type" /* HelperNameMap.TYPE */]: type,
  3132. ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
  3133. ["normalize" /* HelperNameMap.NORMALIZE */]: normalize,
  3134. ["values" /* HelperNameMap.VALUES */]: assign(create(), _list, _named)
  3135. };
  3136. return ctx;
  3137. }
  3138. const NOOP_MESSAGE_FUNCTION = () => '';
  3139. const isMessageFunction = (val) => isFunction(val);
  3140. // implementation of `translate` function
  3141. function translate(context, ...args) {
  3142. const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
  3143. const [key, options] = parseTranslateArgs(...args);
  3144. const missingWarn = isBoolean(options.missingWarn)
  3145. ? options.missingWarn
  3146. : context.missingWarn;
  3147. const fallbackWarn = isBoolean(options.fallbackWarn)
  3148. ? options.fallbackWarn
  3149. : context.fallbackWarn;
  3150. const escapeParameter = isBoolean(options.escapeParameter)
  3151. ? options.escapeParameter
  3152. : context.escapeParameter;
  3153. const resolvedMessage = !!options.resolvedMessage;
  3154. // prettier-ignore
  3155. const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
  3156. ? !isBoolean(options.default)
  3157. ? options.default
  3158. : (!messageCompiler ? () => key : key)
  3159. : fallbackFormat // default by `fallbackFormat` option
  3160. ? (!messageCompiler ? () => key : key)
  3161. : null;
  3162. const enableDefaultMsg = fallbackFormat ||
  3163. (defaultMsgOrKey != null &&
  3164. (isString(defaultMsgOrKey) || isFunction(defaultMsgOrKey)));
  3165. const locale = getLocale(context, options);
  3166. // escape params
  3167. escapeParameter && escapeParams(options);
  3168. // resolve message format
  3169. // eslint-disable-next-line prefer-const
  3170. let [formatScope, targetLocale, message] = !resolvedMessage
  3171. ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
  3172. : [
  3173. key,
  3174. locale,
  3175. messages[locale] || create()
  3176. ];
  3177. // NOTE:
  3178. // Fix to work around `ssrTransfrom` bug in Vite.
  3179. // https://github.com/vitejs/vite/issues/4306
  3180. // To get around this, use temporary variables.
  3181. // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
  3182. let format = formatScope;
  3183. // if you use default message, set it as message format!
  3184. let cacheBaseKey = key;
  3185. if (!resolvedMessage &&
  3186. !(isString(format) ||
  3187. isMessageAST(format) ||
  3188. isMessageFunction(format))) {
  3189. if (enableDefaultMsg) {
  3190. format = defaultMsgOrKey;
  3191. cacheBaseKey = format;
  3192. }
  3193. }
  3194. // checking message format and target locale
  3195. if (!resolvedMessage &&
  3196. (!(isString(format) ||
  3197. isMessageAST(format) ||
  3198. isMessageFunction(format)) ||
  3199. !isString(targetLocale))) {
  3200. return unresolving ? NOT_REOSLVED : key;
  3201. }
  3202. // TODO: refactor
  3203. if (isString(format) && context.messageCompiler == null) {
  3204. warn(`The message format compilation is not supported in this build. ` +
  3205. `Because message compiler isn't included. ` +
  3206. `You need to pre-compilation all message format. ` +
  3207. `So translate function return '${key}'.`);
  3208. return key;
  3209. }
  3210. // setup compile error detecting
  3211. let occurred = false;
  3212. const onError = () => {
  3213. occurred = true;
  3214. };
  3215. // compile message format
  3216. const msg = !isMessageFunction(format)
  3217. ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
  3218. : format;
  3219. // if occurred compile error, return the message format
  3220. if (occurred) {
  3221. return format;
  3222. }
  3223. // evaluate message with context
  3224. const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
  3225. const msgContext = createMessageContext(ctxOptions);
  3226. const messaged = evaluateMessage(context, msg, msgContext);
  3227. // if use post translation option, proceed it with handler
  3228. const ret = postTranslation
  3229. ? postTranslation(messaged, key)
  3230. : messaged;
  3231. // NOTE: experimental !!
  3232. {
  3233. // prettier-ignore
  3234. const payloads = {
  3235. timestamp: Date.now(),
  3236. key: isString(key)
  3237. ? key
  3238. : isMessageFunction(format)
  3239. ? format.key
  3240. : '',
  3241. locale: targetLocale || (isMessageFunction(format)
  3242. ? format.locale
  3243. : ''),
  3244. format: isString(format)
  3245. ? format
  3246. : isMessageFunction(format)
  3247. ? format.source
  3248. : '',
  3249. message: ret
  3250. };
  3251. payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
  3252. translateDevTools(payloads);
  3253. }
  3254. return ret;
  3255. }
  3256. function escapeParams(options) {
  3257. if (isArray(options.list)) {
  3258. options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
  3259. }
  3260. else if (isObject(options.named)) {
  3261. Object.keys(options.named).forEach(key => {
  3262. if (isString(options.named[key])) {
  3263. options.named[key] = escapeHtml(options.named[key]);
  3264. }
  3265. });
  3266. }
  3267. }
  3268. function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
  3269. const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
  3270. const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
  3271. let message = create();
  3272. let targetLocale;
  3273. let format = null;
  3274. let from = locale;
  3275. let to = null;
  3276. const type = 'translate';
  3277. for (let i = 0; i < locales.length; i++) {
  3278. targetLocale = to = locales[i];
  3279. if (locale !== targetLocale &&
  3280. !isAlmostSameLocale(locale, targetLocale) &&
  3281. isTranslateFallbackWarn(fallbackWarn, key)) {
  3282. onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
  3283. key,
  3284. target: targetLocale
  3285. }));
  3286. }
  3287. // for vue-devtools timeline event
  3288. if (locale !== targetLocale) {
  3289. const emitter = context.__v_emitter;
  3290. if (emitter) {
  3291. emitter.emit('fallback', {
  3292. type,
  3293. key,
  3294. from,
  3295. to,
  3296. groupId: `${type}:${key}`
  3297. });
  3298. }
  3299. }
  3300. message =
  3301. messages[targetLocale] || create();
  3302. // for vue-devtools timeline event
  3303. let start = null;
  3304. let startTag;
  3305. let endTag;
  3306. if (inBrowser) {
  3307. start = window.performance.now();
  3308. startTag = 'intlify-message-resolve-start';
  3309. endTag = 'intlify-message-resolve-end';
  3310. mark && mark(startTag);
  3311. }
  3312. if ((format = resolveValue(message, key)) === null) {
  3313. // if null, resolve with object key path
  3314. format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
  3315. }
  3316. // for vue-devtools timeline event
  3317. if (inBrowser) {
  3318. const end = window.performance.now();
  3319. const emitter = context.__v_emitter;
  3320. if (emitter && start && format) {
  3321. emitter.emit('message-resolve', {
  3322. type: 'message-resolve',
  3323. key,
  3324. message: format,
  3325. time: end - start,
  3326. groupId: `${type}:${key}`
  3327. });
  3328. }
  3329. if (startTag && endTag && mark && measure) {
  3330. mark(endTag);
  3331. measure('intlify message resolve', startTag, endTag);
  3332. }
  3333. }
  3334. if (isString(format) || isMessageAST(format) || isMessageFunction(format)) {
  3335. break;
  3336. }
  3337. if (!isImplicitFallback(targetLocale, locales)) {
  3338. const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  3339. key, targetLocale, missingWarn, type);
  3340. if (missingRet !== key) {
  3341. format = missingRet;
  3342. }
  3343. }
  3344. from = to;
  3345. }
  3346. return [format, targetLocale, message];
  3347. }
  3348. function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
  3349. const { messageCompiler, warnHtmlMessage } = context;
  3350. if (isMessageFunction(format)) {
  3351. const msg = format;
  3352. msg.locale = msg.locale || targetLocale;
  3353. msg.key = msg.key || key;
  3354. return msg;
  3355. }
  3356. if (messageCompiler == null) {
  3357. const msg = (() => format);
  3358. msg.locale = targetLocale;
  3359. msg.key = key;
  3360. return msg;
  3361. }
  3362. // for vue-devtools timeline event
  3363. let start = null;
  3364. let startTag;
  3365. let endTag;
  3366. if (inBrowser) {
  3367. start = window.performance.now();
  3368. startTag = 'intlify-message-compilation-start';
  3369. endTag = 'intlify-message-compilation-end';
  3370. mark && mark(startTag);
  3371. }
  3372. const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
  3373. // for vue-devtools timeline event
  3374. if (inBrowser) {
  3375. const end = window.performance.now();
  3376. const emitter = context.__v_emitter;
  3377. if (emitter && start) {
  3378. emitter.emit('message-compilation', {
  3379. type: 'message-compilation',
  3380. message: format,
  3381. time: end - start,
  3382. groupId: `${'translate'}:${key}`
  3383. });
  3384. }
  3385. if (startTag && endTag && mark && measure) {
  3386. mark(endTag);
  3387. measure('intlify message compilation', startTag, endTag);
  3388. }
  3389. }
  3390. msg.locale = targetLocale;
  3391. msg.key = key;
  3392. msg.source = format;
  3393. return msg;
  3394. }
  3395. function evaluateMessage(context, msg, msgCtx) {
  3396. // for vue-devtools timeline event
  3397. let start = null;
  3398. let startTag;
  3399. let endTag;
  3400. if (inBrowser) {
  3401. start = window.performance.now();
  3402. startTag = 'intlify-message-evaluation-start';
  3403. endTag = 'intlify-message-evaluation-end';
  3404. mark && mark(startTag);
  3405. }
  3406. const messaged = msg(msgCtx);
  3407. // for vue-devtools timeline event
  3408. if (inBrowser) {
  3409. const end = window.performance.now();
  3410. const emitter = context.__v_emitter;
  3411. if (emitter && start) {
  3412. emitter.emit('message-evaluation', {
  3413. type: 'message-evaluation',
  3414. value: messaged,
  3415. time: end - start,
  3416. groupId: `${'translate'}:${msg.key}`
  3417. });
  3418. }
  3419. if (startTag && endTag && mark && measure) {
  3420. mark(endTag);
  3421. measure('intlify message evaluation', startTag, endTag);
  3422. }
  3423. }
  3424. return messaged;
  3425. }
  3426. /** @internal */
  3427. function parseTranslateArgs(...args) {
  3428. const [arg1, arg2, arg3] = args;
  3429. const options = create();
  3430. if (!isString(arg1) &&
  3431. !isNumber(arg1) &&
  3432. !isMessageFunction(arg1) &&
  3433. !isMessageAST(arg1)) {
  3434. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  3435. }
  3436. // prettier-ignore
  3437. const key = isNumber(arg1)
  3438. ? String(arg1)
  3439. : isMessageFunction(arg1)
  3440. ? arg1
  3441. : arg1;
  3442. if (isNumber(arg2)) {
  3443. options.plural = arg2;
  3444. }
  3445. else if (isString(arg2)) {
  3446. options.default = arg2;
  3447. }
  3448. else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
  3449. options.named = arg2;
  3450. }
  3451. else if (isArray(arg2)) {
  3452. options.list = arg2;
  3453. }
  3454. if (isNumber(arg3)) {
  3455. options.plural = arg3;
  3456. }
  3457. else if (isString(arg3)) {
  3458. options.default = arg3;
  3459. }
  3460. else if (isPlainObject(arg3)) {
  3461. assign(options, arg3);
  3462. }
  3463. return [key, options];
  3464. }
  3465. function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
  3466. return {
  3467. locale,
  3468. key,
  3469. warnHtmlMessage,
  3470. onError: (err) => {
  3471. onError && onError(err);
  3472. {
  3473. const _source = getSourceForCodeFrame(source);
  3474. const message = `Message compilation error: ${err.message}`;
  3475. const codeFrame = err.location &&
  3476. _source &&
  3477. generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
  3478. const emitter = context.__v_emitter;
  3479. if (emitter && _source) {
  3480. emitter.emit('compile-error', {
  3481. message: _source,
  3482. error: err.message,
  3483. start: err.location && err.location.start.offset,
  3484. end: err.location && err.location.end.offset,
  3485. groupId: `${'translate'}:${key}`
  3486. });
  3487. }
  3488. console.error(codeFrame ? `${message}\n${codeFrame}` : message);
  3489. }
  3490. },
  3491. onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
  3492. };
  3493. }
  3494. function getSourceForCodeFrame(source) {
  3495. if (isString(source)) {
  3496. return source;
  3497. }
  3498. else {
  3499. if (source.loc && source.loc.source) {
  3500. return source.loc.source;
  3501. }
  3502. }
  3503. }
  3504. function getMessageContextOptions(context, locale, message, options) {
  3505. const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
  3506. const resolveMessage = (key, useLinked) => {
  3507. let val = resolveValue(message, key);
  3508. // fallback
  3509. if (val == null && (fallbackContext || useLinked)) {
  3510. const [, , message] = resolveMessageFormat(fallbackContext || context, // NOTE: if has fallbackContext, fallback to root, else if use linked, fallback to local context
  3511. key, locale, fallbackLocale, fallbackWarn, missingWarn);
  3512. val = resolveValue(message, key);
  3513. }
  3514. if (isString(val) || isMessageAST(val)) {
  3515. let occurred = false;
  3516. const onError = () => {
  3517. occurred = true;
  3518. };
  3519. const msg = compileMessageFormat(context, key, locale, val, key, onError);
  3520. return !occurred
  3521. ? msg
  3522. : NOOP_MESSAGE_FUNCTION;
  3523. }
  3524. else if (isMessageFunction(val)) {
  3525. return val;
  3526. }
  3527. else {
  3528. // TODO: should be implemented warning message
  3529. return NOOP_MESSAGE_FUNCTION;
  3530. }
  3531. };
  3532. const ctxOptions = {
  3533. locale,
  3534. modifiers,
  3535. pluralRules,
  3536. messages: resolveMessage
  3537. };
  3538. if (context.processor) {
  3539. ctxOptions.processor = context.processor;
  3540. }
  3541. if (options.list) {
  3542. ctxOptions.list = options.list;
  3543. }
  3544. if (options.named) {
  3545. ctxOptions.named = options.named;
  3546. }
  3547. if (isNumber(options.plural)) {
  3548. ctxOptions.pluralIndex = options.plural;
  3549. }
  3550. return ctxOptions;
  3551. }
  3552. /**
  3553. * Vue I18n Version
  3554. *
  3555. * @remarks
  3556. * Semver format. Same format as the package.json `version` field.
  3557. *
  3558. * @VueI18nGeneral
  3559. */
  3560. const VERSION = '11.1.3';
  3561. /**
  3562. * This is only called development env
  3563. * istanbul-ignore-next
  3564. */
  3565. function initDev() {
  3566. {
  3567. {
  3568. console.info(`You are running a development build of vue-i18n.\n` +
  3569. `Make sure to use the production build (*.prod.js) when deploying for production.`);
  3570. }
  3571. }
  3572. }
  3573. const I18nErrorCodes = {
  3574. // composer module errors
  3575. UNEXPECTED_RETURN_TYPE: CORE_ERROR_CODES_EXTEND_POINT, // 24
  3576. // legacy module errors
  3577. INVALID_ARGUMENT: 25,
  3578. // i18n module errors
  3579. MUST_BE_CALL_SETUP_TOP: 26,
  3580. NOT_INSTALLED: 27,
  3581. // directive module errors
  3582. REQUIRED_VALUE: 28,
  3583. INVALID_VALUE: 29,
  3584. // vue-devtools errors
  3585. CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN: 30,
  3586. NOT_INSTALLED_WITH_PROVIDE: 31,
  3587. // unexpected error
  3588. UNEXPECTED_ERROR: 32,
  3589. // not compatible legacy vue-i18n constructor
  3590. NOT_COMPATIBLE_LEGACY_VUE_I18N: 33,
  3591. // Not available Compostion API in Legacy API mode. Please make sure that the legacy API mode is working properly
  3592. NOT_AVAILABLE_COMPOSITION_IN_LEGACY: 34
  3593. };
  3594. function createI18nError(code, ...args) {
  3595. return createCompileError(code, null, { messages: errorMessages, args } );
  3596. }
  3597. const errorMessages = {
  3598. [I18nErrorCodes.UNEXPECTED_RETURN_TYPE]: 'Unexpected return type in composer',
  3599. [I18nErrorCodes.INVALID_ARGUMENT]: 'Invalid argument',
  3600. [I18nErrorCodes.MUST_BE_CALL_SETUP_TOP]: 'Must be called at the top of a `setup` function',
  3601. [I18nErrorCodes.NOT_INSTALLED]: 'Need to install with `app.use` function',
  3602. [I18nErrorCodes.UNEXPECTED_ERROR]: 'Unexpected error',
  3603. [I18nErrorCodes.REQUIRED_VALUE]: `Required in value: {0}`,
  3604. [I18nErrorCodes.INVALID_VALUE]: `Invalid value`,
  3605. [I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN]: `Cannot setup vue-devtools plugin`,
  3606. [I18nErrorCodes.NOT_INSTALLED_WITH_PROVIDE]: 'Need to install with `provide` function',
  3607. [I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N]: 'Not compatible legacy VueI18n.',
  3608. [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'
  3609. };
  3610. const TranslateVNodeSymbol =
  3611. /* #__PURE__*/ makeSymbol('__translateVNode');
  3612. const DatetimePartsSymbol = /* #__PURE__*/ makeSymbol('__datetimeParts');
  3613. const NumberPartsSymbol = /* #__PURE__*/ makeSymbol('__numberParts');
  3614. const EnableEmitter = /* #__PURE__*/ makeSymbol('__enableEmitter');
  3615. const DisableEmitter = /* #__PURE__*/ makeSymbol('__disableEmitter');
  3616. const SetPluralRulesSymbol = makeSymbol('__setPluralRules');
  3617. const InejctWithOptionSymbol =
  3618. /* #__PURE__*/ makeSymbol('__injectWithOption');
  3619. const DisposeSymbol = /* #__PURE__*/ makeSymbol('__dispose');
  3620. const I18nWarnCodes = {
  3621. FALLBACK_TO_ROOT: CORE_WARN_CODES_EXTEND_POINT, // 8
  3622. NOT_FOUND_PARENT_SCOPE: 9,
  3623. IGNORE_OBJ_FLATTEN: 10,
  3624. /**
  3625. * @deprecated will be removed at vue-i18n v12
  3626. */
  3627. DEPRECATE_LEGACY_MODE: 11,
  3628. /**
  3629. * @deprecated will be removed at vue-i18n v12
  3630. */
  3631. DEPRECATE_TRANSLATE_CUSTOME_DIRECTIVE: 12
  3632. };
  3633. const warnMessages = {
  3634. [I18nWarnCodes.FALLBACK_TO_ROOT]: `Fall back to {type} '{key}' with root locale.`,
  3635. [I18nWarnCodes.NOT_FOUND_PARENT_SCOPE]: `Not found parent scope. use the global scope.`,
  3636. [I18nWarnCodes.IGNORE_OBJ_FLATTEN]: `Ignore object flatten: '{key}' key has an string value`,
  3637. /**
  3638. * @deprecated will be removed at vue-i18n v12
  3639. */
  3640. [I18nWarnCodes.DEPRECATE_LEGACY_MODE]: `Legacy API mode has been deprecated in v11. Use Composition API mode instead.\nAbout how to use the Composition API mode, see https://vue-i18n.intlify.dev/guide/advanced/composition.html`,
  3641. /**
  3642. * @deprecated will be removed at vue-i18n v12
  3643. */
  3644. [I18nWarnCodes.DEPRECATE_TRANSLATE_CUSTOME_DIRECTIVE]: `'v-t' has been deprecated in v11. Use translate APIs ('t' or '$t') instead.`
  3645. };
  3646. function getWarnMessage(code, ...args) {
  3647. return format$1(warnMessages[code], ...args);
  3648. }
  3649. /* eslint-disable @typescript-eslint/no-explicit-any */
  3650. /**
  3651. * Transform flat json in obj to normal json in obj
  3652. */
  3653. function handleFlatJson(obj) {
  3654. // check obj
  3655. if (!isObject(obj)) {
  3656. return obj;
  3657. }
  3658. if (isMessageAST(obj)) {
  3659. return obj;
  3660. }
  3661. for (const key in obj) {
  3662. // check key
  3663. if (!hasOwn(obj, key)) {
  3664. continue;
  3665. }
  3666. // handle for normal json
  3667. if (!key.includes('.')) {
  3668. // recursive process value if value is also a object
  3669. if (isObject(obj[key])) {
  3670. handleFlatJson(obj[key]);
  3671. }
  3672. }
  3673. // handle for flat json, transform to normal json
  3674. else {
  3675. // go to the last object
  3676. const subKeys = key.split('.');
  3677. const lastIndex = subKeys.length - 1;
  3678. let currentObj = obj;
  3679. let hasStringValue = false;
  3680. for (let i = 0; i < lastIndex; i++) {
  3681. if (subKeys[i] === '__proto__') {
  3682. throw new Error(`unsafe key: ${subKeys[i]}`);
  3683. }
  3684. if (!(subKeys[i] in currentObj)) {
  3685. currentObj[subKeys[i]] = create();
  3686. }
  3687. if (!isObject(currentObj[subKeys[i]])) {
  3688. warn(getWarnMessage(I18nWarnCodes.IGNORE_OBJ_FLATTEN, {
  3689. key: subKeys[i]
  3690. }));
  3691. hasStringValue = true;
  3692. break;
  3693. }
  3694. currentObj = currentObj[subKeys[i]];
  3695. }
  3696. // update last object value, delete old property
  3697. if (!hasStringValue) {
  3698. if (!isMessageAST(currentObj)) {
  3699. currentObj[subKeys[lastIndex]] = obj[key];
  3700. delete obj[key];
  3701. }
  3702. else {
  3703. /**
  3704. * NOTE:
  3705. * if the last object is a message AST and subKeys[lastIndex] has message AST prop key, ignore to copy and key deletion
  3706. */
  3707. if (!AST_NODE_PROPS_KEYS.includes(subKeys[lastIndex])) {
  3708. delete obj[key];
  3709. }
  3710. }
  3711. }
  3712. // recursive process value if value is also a object
  3713. if (!isMessageAST(currentObj)) {
  3714. const target = currentObj[subKeys[lastIndex]];
  3715. if (isObject(target)) {
  3716. handleFlatJson(target);
  3717. }
  3718. }
  3719. }
  3720. }
  3721. return obj;
  3722. }
  3723. function getLocaleMessages(locale, options) {
  3724. const { messages, __i18n, messageResolver, flatJson } = options;
  3725. // prettier-ignore
  3726. const ret = (isPlainObject(messages)
  3727. ? messages
  3728. : isArray(__i18n)
  3729. ? create()
  3730. : { [locale]: create() });
  3731. // merge locale messages of i18n custom block
  3732. if (isArray(__i18n)) {
  3733. __i18n.forEach(custom => {
  3734. if ('locale' in custom && 'resource' in custom) {
  3735. const { locale, resource } = custom;
  3736. if (locale) {
  3737. ret[locale] = ret[locale] || create();
  3738. deepCopy(resource, ret[locale]);
  3739. }
  3740. else {
  3741. deepCopy(resource, ret);
  3742. }
  3743. }
  3744. else {
  3745. isString(custom) && deepCopy(JSON.parse(custom), ret);
  3746. }
  3747. });
  3748. }
  3749. // handle messages for flat json
  3750. if (messageResolver == null && flatJson) {
  3751. for (const key in ret) {
  3752. if (hasOwn(ret, key)) {
  3753. handleFlatJson(ret[key]);
  3754. }
  3755. }
  3756. }
  3757. return ret;
  3758. }
  3759. function getComponentOptions(instance) {
  3760. return instance.type;
  3761. }
  3762. function adjustI18nResources(gl, options, componentOptions) {
  3763. // prettier-ignore
  3764. let messages = isObject(options.messages)
  3765. ? options.messages
  3766. : create();
  3767. if ('__i18nGlobal' in componentOptions) {
  3768. messages = getLocaleMessages(gl.locale.value, {
  3769. messages,
  3770. __i18n: componentOptions.__i18nGlobal
  3771. });
  3772. }
  3773. // merge locale messages
  3774. const locales = Object.keys(messages);
  3775. if (locales.length) {
  3776. locales.forEach(locale => {
  3777. gl.mergeLocaleMessage(locale, messages[locale]);
  3778. });
  3779. }
  3780. {
  3781. // merge datetime formats
  3782. if (isObject(options.datetimeFormats)) {
  3783. const locales = Object.keys(options.datetimeFormats);
  3784. if (locales.length) {
  3785. locales.forEach(locale => {
  3786. gl.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
  3787. });
  3788. }
  3789. }
  3790. // merge number formats
  3791. if (isObject(options.numberFormats)) {
  3792. const locales = Object.keys(options.numberFormats);
  3793. if (locales.length) {
  3794. locales.forEach(locale => {
  3795. gl.mergeNumberFormat(locale, options.numberFormats[locale]);
  3796. });
  3797. }
  3798. }
  3799. }
  3800. }
  3801. function createTextNode(key) {
  3802. return vue.createVNode(vue.Text, null, key, 0);
  3803. }
  3804. /* eslint-disable @typescript-eslint/no-explicit-any */
  3805. // extend VNode interface
  3806. const DEVTOOLS_META = '__INTLIFY_META__';
  3807. const NOOP_RETURN_ARRAY = () => [];
  3808. const NOOP_RETURN_FALSE = () => false;
  3809. let composerID = 0;
  3810. function defineCoreMissingHandler(missing) {
  3811. return ((ctx, locale, key, type) => {
  3812. return missing(locale, key, vue.getCurrentInstance() || undefined, type);
  3813. });
  3814. }
  3815. // for Intlify DevTools
  3816. /* #__NO_SIDE_EFFECTS__ */
  3817. const getMetaInfo = () => {
  3818. const instance = vue.getCurrentInstance();
  3819. let meta = null;
  3820. return instance && (meta = getComponentOptions(instance)[DEVTOOLS_META])
  3821. ? { [DEVTOOLS_META]: meta }
  3822. : null;
  3823. };
  3824. /**
  3825. * Create composer interface factory
  3826. *
  3827. * @internal
  3828. */
  3829. function createComposer(options = {}) {
  3830. const { __root, __injectWithOption } = options;
  3831. const _isGlobal = __root === undefined;
  3832. const flatJson = options.flatJson;
  3833. const _ref = inBrowser ? vue.ref : vue.shallowRef;
  3834. let _inheritLocale = isBoolean(options.inheritLocale)
  3835. ? options.inheritLocale
  3836. : true;
  3837. const _locale = _ref(
  3838. // prettier-ignore
  3839. __root && _inheritLocale
  3840. ? __root.locale.value
  3841. : isString(options.locale)
  3842. ? options.locale
  3843. : DEFAULT_LOCALE);
  3844. const _fallbackLocale = _ref(
  3845. // prettier-ignore
  3846. __root && _inheritLocale
  3847. ? __root.fallbackLocale.value
  3848. : isString(options.fallbackLocale) ||
  3849. isArray(options.fallbackLocale) ||
  3850. isPlainObject(options.fallbackLocale) ||
  3851. options.fallbackLocale === false
  3852. ? options.fallbackLocale
  3853. : _locale.value);
  3854. const _messages = _ref(getLocaleMessages(_locale.value, options));
  3855. // prettier-ignore
  3856. const _datetimeFormats = _ref(isPlainObject(options.datetimeFormats)
  3857. ? options.datetimeFormats
  3858. : { [_locale.value]: {} })
  3859. ;
  3860. // prettier-ignore
  3861. const _numberFormats = _ref(isPlainObject(options.numberFormats)
  3862. ? options.numberFormats
  3863. : { [_locale.value]: {} })
  3864. ;
  3865. // warning suppress options
  3866. // prettier-ignore
  3867. let _missingWarn = __root
  3868. ? __root.missingWarn
  3869. : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  3870. ? options.missingWarn
  3871. : true;
  3872. // prettier-ignore
  3873. let _fallbackWarn = __root
  3874. ? __root.fallbackWarn
  3875. : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  3876. ? options.fallbackWarn
  3877. : true;
  3878. // prettier-ignore
  3879. let _fallbackRoot = __root
  3880. ? __root.fallbackRoot
  3881. : isBoolean(options.fallbackRoot)
  3882. ? options.fallbackRoot
  3883. : true;
  3884. // configure fall back to root
  3885. let _fallbackFormat = !!options.fallbackFormat;
  3886. // runtime missing
  3887. let _missing = isFunction(options.missing) ? options.missing : null;
  3888. let _runtimeMissing = isFunction(options.missing)
  3889. ? defineCoreMissingHandler(options.missing)
  3890. : null;
  3891. // postTranslation handler
  3892. let _postTranslation = isFunction(options.postTranslation)
  3893. ? options.postTranslation
  3894. : null;
  3895. // prettier-ignore
  3896. let _warnHtmlMessage = __root
  3897. ? __root.warnHtmlMessage
  3898. : isBoolean(options.warnHtmlMessage)
  3899. ? options.warnHtmlMessage
  3900. : true;
  3901. let _escapeParameter = !!options.escapeParameter;
  3902. // custom linked modifiers
  3903. // prettier-ignore
  3904. const _modifiers = __root
  3905. ? __root.modifiers
  3906. : isPlainObject(options.modifiers)
  3907. ? options.modifiers
  3908. : {};
  3909. // pluralRules
  3910. let _pluralRules = options.pluralRules || (__root && __root.pluralRules);
  3911. // runtime context
  3912. // eslint-disable-next-line prefer-const
  3913. let _context;
  3914. const getCoreContext = () => {
  3915. _isGlobal && setFallbackContext(null);
  3916. const ctxOptions = {
  3917. version: VERSION,
  3918. locale: _locale.value,
  3919. fallbackLocale: _fallbackLocale.value,
  3920. messages: _messages.value,
  3921. modifiers: _modifiers,
  3922. pluralRules: _pluralRules,
  3923. missing: _runtimeMissing === null ? undefined : _runtimeMissing,
  3924. missingWarn: _missingWarn,
  3925. fallbackWarn: _fallbackWarn,
  3926. fallbackFormat: _fallbackFormat,
  3927. unresolving: true,
  3928. postTranslation: _postTranslation === null ? undefined : _postTranslation,
  3929. warnHtmlMessage: _warnHtmlMessage,
  3930. escapeParameter: _escapeParameter,
  3931. messageResolver: options.messageResolver,
  3932. messageCompiler: options.messageCompiler,
  3933. __meta: { framework: 'vue' }
  3934. };
  3935. {
  3936. ctxOptions.datetimeFormats = _datetimeFormats.value;
  3937. ctxOptions.numberFormats = _numberFormats.value;
  3938. ctxOptions.__datetimeFormatters = isPlainObject(_context)
  3939. ? _context.__datetimeFormatters
  3940. : undefined;
  3941. ctxOptions.__numberFormatters = isPlainObject(_context)
  3942. ? _context.__numberFormatters
  3943. : undefined;
  3944. }
  3945. {
  3946. ctxOptions.__v_emitter = isPlainObject(_context)
  3947. ? _context.__v_emitter
  3948. : undefined;
  3949. }
  3950. const ctx = createCoreContext(ctxOptions);
  3951. _isGlobal && setFallbackContext(ctx);
  3952. return ctx;
  3953. };
  3954. _context = getCoreContext();
  3955. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  3956. // track reactivity
  3957. function trackReactivityValues() {
  3958. return [
  3959. _locale.value,
  3960. _fallbackLocale.value,
  3961. _messages.value,
  3962. _datetimeFormats.value,
  3963. _numberFormats.value
  3964. ]
  3965. ;
  3966. }
  3967. // locale
  3968. const locale = vue.computed({
  3969. get: () => _locale.value,
  3970. set: val => {
  3971. _context.locale = val;
  3972. _locale.value = val;
  3973. }
  3974. });
  3975. // fallbackLocale
  3976. const fallbackLocale = vue.computed({
  3977. get: () => _fallbackLocale.value,
  3978. set: val => {
  3979. _context.fallbackLocale = val;
  3980. _fallbackLocale.value = val;
  3981. updateFallbackLocale(_context, _locale.value, val);
  3982. }
  3983. });
  3984. // messages
  3985. const messages = vue.computed(() => _messages.value);
  3986. // datetimeFormats
  3987. const datetimeFormats = /* #__PURE__*/ vue.computed(() => _datetimeFormats.value);
  3988. // numberFormats
  3989. const numberFormats = /* #__PURE__*/ vue.computed(() => _numberFormats.value);
  3990. // getPostTranslationHandler
  3991. function getPostTranslationHandler() {
  3992. return isFunction(_postTranslation) ? _postTranslation : null;
  3993. }
  3994. // setPostTranslationHandler
  3995. function setPostTranslationHandler(handler) {
  3996. _postTranslation = handler;
  3997. _context.postTranslation = handler;
  3998. }
  3999. // getMissingHandler
  4000. function getMissingHandler() {
  4001. return _missing;
  4002. }
  4003. // setMissingHandler
  4004. function setMissingHandler(handler) {
  4005. if (handler !== null) {
  4006. _runtimeMissing = defineCoreMissingHandler(handler);
  4007. }
  4008. _missing = handler;
  4009. _context.missing = _runtimeMissing;
  4010. }
  4011. function isResolvedTranslateMessage(type, arg) {
  4012. return type !== 'translate' || !arg.resolvedMessage;
  4013. }
  4014. const wrapWithDeps = (fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) => {
  4015. trackReactivityValues(); // track reactive dependency
  4016. // NOTE: experimental !!
  4017. let ret;
  4018. try {
  4019. if (true || false) {
  4020. setAdditionalMeta(getMetaInfo());
  4021. }
  4022. if (!_isGlobal) {
  4023. _context.fallbackContext = __root
  4024. ? getFallbackContext()
  4025. : undefined;
  4026. }
  4027. ret = fn(_context);
  4028. }
  4029. finally {
  4030. if (!_isGlobal) {
  4031. _context.fallbackContext = undefined;
  4032. }
  4033. }
  4034. if ((warnType !== 'translate exists' && // for not `te` (e.g `t`)
  4035. isNumber(ret) &&
  4036. ret === NOT_REOSLVED) ||
  4037. (warnType === 'translate exists' && !ret) // for `te`
  4038. ) {
  4039. const [key, arg2] = argumentParser();
  4040. if (__root &&
  4041. isString(key) &&
  4042. isResolvedTranslateMessage(warnType, arg2)) {
  4043. if (_fallbackRoot &&
  4044. (isTranslateFallbackWarn(_fallbackWarn, key) ||
  4045. isTranslateMissingWarn(_missingWarn, key))) {
  4046. warn(getWarnMessage(I18nWarnCodes.FALLBACK_TO_ROOT, {
  4047. key,
  4048. type: warnType
  4049. }));
  4050. }
  4051. // for vue-devtools timeline event
  4052. {
  4053. const { __v_emitter: emitter } = _context;
  4054. if (emitter && _fallbackRoot) {
  4055. emitter.emit('fallback', {
  4056. type: warnType,
  4057. key,
  4058. to: 'global',
  4059. groupId: `${warnType}:${key}`
  4060. });
  4061. }
  4062. }
  4063. }
  4064. return __root && _fallbackRoot
  4065. ? fallbackSuccess(__root)
  4066. : fallbackFail(key);
  4067. }
  4068. else if (successCondition(ret)) {
  4069. return ret;
  4070. }
  4071. else {
  4072. /* istanbul ignore next */
  4073. throw createI18nError(I18nErrorCodes.UNEXPECTED_RETURN_TYPE);
  4074. }
  4075. };
  4076. // t
  4077. function t(...args) {
  4078. return wrapWithDeps(context => Reflect.apply(translate, null, [context, ...args]), () => parseTranslateArgs(...args), 'translate', root => Reflect.apply(root.t, root, [...args]), key => key, val => isString(val));
  4079. }
  4080. // rt
  4081. function rt(...args) {
  4082. const [arg1, arg2, arg3] = args;
  4083. if (arg3 && !isObject(arg3)) {
  4084. throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
  4085. }
  4086. return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]);
  4087. }
  4088. // d
  4089. function d(...args) {
  4090. 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));
  4091. }
  4092. // n
  4093. function n(...args) {
  4094. 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));
  4095. }
  4096. // for custom processor
  4097. function normalize(values) {
  4098. return values.map(val => isString(val) || isNumber(val) || isBoolean(val)
  4099. ? createTextNode(String(val))
  4100. : val);
  4101. }
  4102. const interpolate = (val) => val;
  4103. const processor = {
  4104. normalize,
  4105. interpolate,
  4106. type: 'vnode'
  4107. };
  4108. // translateVNode, using for `i18n-t` component
  4109. function translateVNode(...args) {
  4110. return wrapWithDeps(context => {
  4111. let ret;
  4112. const _context = context;
  4113. try {
  4114. _context.processor = processor;
  4115. ret = Reflect.apply(translate, null, [_context, ...args]);
  4116. }
  4117. finally {
  4118. _context.processor = null;
  4119. }
  4120. return ret;
  4121. }, () => parseTranslateArgs(...args), 'translate', root => root[TranslateVNodeSymbol](...args), key => [createTextNode(key)], val => isArray(val));
  4122. }
  4123. // numberParts, using for `i18n-n` component
  4124. function numberParts(...args) {
  4125. return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format', root => root[NumberPartsSymbol](...args), NOOP_RETURN_ARRAY, val => isString(val) || isArray(val));
  4126. }
  4127. // datetimeParts, using for `i18n-d` component
  4128. function datetimeParts(...args) {
  4129. return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format', root => root[DatetimePartsSymbol](...args), NOOP_RETURN_ARRAY, val => isString(val) || isArray(val));
  4130. }
  4131. function setPluralRules(rules) {
  4132. _pluralRules = rules;
  4133. _context.pluralRules = _pluralRules;
  4134. }
  4135. // te
  4136. function te(key, locale) {
  4137. return wrapWithDeps(() => {
  4138. if (!key) {
  4139. return false;
  4140. }
  4141. const targetLocale = isString(locale) ? locale : _locale.value;
  4142. const message = getLocaleMessage(targetLocale);
  4143. const resolved = _context.messageResolver(message, key);
  4144. return (isMessageAST(resolved) ||
  4145. isMessageFunction(resolved) ||
  4146. isString(resolved));
  4147. }, () => [key], 'translate exists', root => {
  4148. return Reflect.apply(root.te, root, [key, locale]);
  4149. }, NOOP_RETURN_FALSE, val => isBoolean(val));
  4150. }
  4151. function resolveMessages(key) {
  4152. let messages = null;
  4153. const locales = fallbackWithLocaleChain(_context, _fallbackLocale.value, _locale.value);
  4154. for (let i = 0; i < locales.length; i++) {
  4155. const targetLocaleMessages = _messages.value[locales[i]] || {};
  4156. const messageValue = _context.messageResolver(targetLocaleMessages, key);
  4157. if (messageValue != null) {
  4158. messages = messageValue;
  4159. break;
  4160. }
  4161. }
  4162. return messages;
  4163. }
  4164. // tm
  4165. function tm(key) {
  4166. const messages = resolveMessages(key);
  4167. // prettier-ignore
  4168. return messages != null
  4169. ? messages
  4170. : __root
  4171. ? __root.tm(key) || {}
  4172. : {};
  4173. }
  4174. // getLocaleMessage
  4175. function getLocaleMessage(locale) {
  4176. return (_messages.value[locale] || {});
  4177. }
  4178. // setLocaleMessage
  4179. function setLocaleMessage(locale, message) {
  4180. if (flatJson) {
  4181. const _message = { [locale]: message };
  4182. for (const key in _message) {
  4183. if (hasOwn(_message, key)) {
  4184. handleFlatJson(_message[key]);
  4185. }
  4186. }
  4187. message = _message[locale];
  4188. }
  4189. _messages.value[locale] = message;
  4190. _context.messages = _messages.value;
  4191. }
  4192. // mergeLocaleMessage
  4193. function mergeLocaleMessage(locale, message) {
  4194. _messages.value[locale] = _messages.value[locale] || {};
  4195. const _message = { [locale]: message };
  4196. if (flatJson) {
  4197. for (const key in _message) {
  4198. if (hasOwn(_message, key)) {
  4199. handleFlatJson(_message[key]);
  4200. }
  4201. }
  4202. }
  4203. message = _message[locale];
  4204. deepCopy(message, _messages.value[locale]);
  4205. _context.messages = _messages.value;
  4206. }
  4207. // getDateTimeFormat
  4208. function getDateTimeFormat(locale) {
  4209. return _datetimeFormats.value[locale] || {};
  4210. }
  4211. // setDateTimeFormat
  4212. function setDateTimeFormat(locale, format) {
  4213. _datetimeFormats.value[locale] = format;
  4214. _context.datetimeFormats = _datetimeFormats.value;
  4215. clearDateTimeFormat(_context, locale, format);
  4216. }
  4217. // mergeDateTimeFormat
  4218. function mergeDateTimeFormat(locale, format) {
  4219. _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format);
  4220. _context.datetimeFormats = _datetimeFormats.value;
  4221. clearDateTimeFormat(_context, locale, format);
  4222. }
  4223. // getNumberFormat
  4224. function getNumberFormat(locale) {
  4225. return _numberFormats.value[locale] || {};
  4226. }
  4227. // setNumberFormat
  4228. function setNumberFormat(locale, format) {
  4229. _numberFormats.value[locale] = format;
  4230. _context.numberFormats = _numberFormats.value;
  4231. clearNumberFormat(_context, locale, format);
  4232. }
  4233. // mergeNumberFormat
  4234. function mergeNumberFormat(locale, format) {
  4235. _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format);
  4236. _context.numberFormats = _numberFormats.value;
  4237. clearNumberFormat(_context, locale, format);
  4238. }
  4239. // for debug
  4240. composerID++;
  4241. // watch root locale & fallbackLocale
  4242. if (__root && inBrowser) {
  4243. vue.watch(__root.locale, (val) => {
  4244. if (_inheritLocale) {
  4245. _locale.value = val;
  4246. _context.locale = val;
  4247. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  4248. }
  4249. });
  4250. vue.watch(__root.fallbackLocale, (val) => {
  4251. if (_inheritLocale) {
  4252. _fallbackLocale.value = val;
  4253. _context.fallbackLocale = val;
  4254. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  4255. }
  4256. });
  4257. }
  4258. // define basic composition API!
  4259. const composer = {
  4260. id: composerID,
  4261. locale,
  4262. fallbackLocale,
  4263. get inheritLocale() {
  4264. return _inheritLocale;
  4265. },
  4266. set inheritLocale(val) {
  4267. _inheritLocale = val;
  4268. if (val && __root) {
  4269. _locale.value = __root.locale.value;
  4270. _fallbackLocale.value = __root.fallbackLocale.value;
  4271. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  4272. }
  4273. },
  4274. get availableLocales() {
  4275. return Object.keys(_messages.value).sort();
  4276. },
  4277. messages,
  4278. get modifiers() {
  4279. return _modifiers;
  4280. },
  4281. get pluralRules() {
  4282. return _pluralRules || {};
  4283. },
  4284. get isGlobal() {
  4285. return _isGlobal;
  4286. },
  4287. get missingWarn() {
  4288. return _missingWarn;
  4289. },
  4290. set missingWarn(val) {
  4291. _missingWarn = val;
  4292. _context.missingWarn = _missingWarn;
  4293. },
  4294. get fallbackWarn() {
  4295. return _fallbackWarn;
  4296. },
  4297. set fallbackWarn(val) {
  4298. _fallbackWarn = val;
  4299. _context.fallbackWarn = _fallbackWarn;
  4300. },
  4301. get fallbackRoot() {
  4302. return _fallbackRoot;
  4303. },
  4304. set fallbackRoot(val) {
  4305. _fallbackRoot = val;
  4306. },
  4307. get fallbackFormat() {
  4308. return _fallbackFormat;
  4309. },
  4310. set fallbackFormat(val) {
  4311. _fallbackFormat = val;
  4312. _context.fallbackFormat = _fallbackFormat;
  4313. },
  4314. get warnHtmlMessage() {
  4315. return _warnHtmlMessage;
  4316. },
  4317. set warnHtmlMessage(val) {
  4318. _warnHtmlMessage = val;
  4319. _context.warnHtmlMessage = val;
  4320. },
  4321. get escapeParameter() {
  4322. return _escapeParameter;
  4323. },
  4324. set escapeParameter(val) {
  4325. _escapeParameter = val;
  4326. _context.escapeParameter = val;
  4327. },
  4328. t,
  4329. getLocaleMessage,
  4330. setLocaleMessage,
  4331. mergeLocaleMessage,
  4332. getPostTranslationHandler,
  4333. setPostTranslationHandler,
  4334. getMissingHandler,
  4335. setMissingHandler,
  4336. [SetPluralRulesSymbol]: setPluralRules
  4337. };
  4338. {
  4339. composer.datetimeFormats = datetimeFormats;
  4340. composer.numberFormats = numberFormats;
  4341. composer.rt = rt;
  4342. composer.te = te;
  4343. composer.tm = tm;
  4344. composer.d = d;
  4345. composer.n = n;
  4346. composer.getDateTimeFormat = getDateTimeFormat;
  4347. composer.setDateTimeFormat = setDateTimeFormat;
  4348. composer.mergeDateTimeFormat = mergeDateTimeFormat;
  4349. composer.getNumberFormat = getNumberFormat;
  4350. composer.setNumberFormat = setNumberFormat;
  4351. composer.mergeNumberFormat = mergeNumberFormat;
  4352. composer[InejctWithOptionSymbol] = __injectWithOption;
  4353. composer[TranslateVNodeSymbol] = translateVNode;
  4354. composer[DatetimePartsSymbol] = datetimeParts;
  4355. composer[NumberPartsSymbol] = numberParts;
  4356. }
  4357. // for vue-devtools timeline event
  4358. {
  4359. composer[EnableEmitter] = (emitter) => {
  4360. _context.__v_emitter = emitter;
  4361. };
  4362. composer[DisableEmitter] = () => {
  4363. _context.__v_emitter = undefined;
  4364. };
  4365. }
  4366. return composer;
  4367. }
  4368. /* eslint-enable @typescript-eslint/no-explicit-any */
  4369. var global$1 = (typeof global !== "undefined" ? global :
  4370. typeof self !== "undefined" ? self :
  4371. typeof window !== "undefined" ? window : {});
  4372. function getDevtoolsGlobalHook() {
  4373. return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
  4374. }
  4375. function getTarget() {
  4376. // @ts-ignore
  4377. return (typeof navigator !== 'undefined' && typeof window !== 'undefined')
  4378. ? window
  4379. : typeof global$1 !== 'undefined'
  4380. ? global$1
  4381. : {};
  4382. }
  4383. const isProxyAvailable = typeof Proxy === 'function';
  4384. const HOOK_SETUP = 'devtools-plugin:setup';
  4385. const HOOK_PLUGIN_SETTINGS_SET = 'plugin:settings:set';
  4386. let supported;
  4387. let perf;
  4388. function isPerformanceSupported() {
  4389. var _a;
  4390. if (supported !== undefined) {
  4391. return supported;
  4392. }
  4393. if (typeof window !== 'undefined' && window.performance) {
  4394. supported = true;
  4395. perf = window.performance;
  4396. }
  4397. else if (typeof global$1 !== 'undefined' && ((_a = global$1.perf_hooks) === null || _a === void 0 ? void 0 : _a.performance)) {
  4398. supported = true;
  4399. perf = global$1.perf_hooks.performance;
  4400. }
  4401. else {
  4402. supported = false;
  4403. }
  4404. return supported;
  4405. }
  4406. function now() {
  4407. return isPerformanceSupported() ? perf.now() : Date.now();
  4408. }
  4409. class ApiProxy {
  4410. constructor(plugin, hook) {
  4411. this.target = null;
  4412. this.targetQueue = [];
  4413. this.onQueue = [];
  4414. this.plugin = plugin;
  4415. this.hook = hook;
  4416. const defaultSettings = {};
  4417. if (plugin.settings) {
  4418. for (const id in plugin.settings) {
  4419. const item = plugin.settings[id];
  4420. defaultSettings[id] = item.defaultValue;
  4421. }
  4422. }
  4423. const localSettingsSaveId = `__vue-devtools-plugin-settings__${plugin.id}`;
  4424. let currentSettings = Object.assign({}, defaultSettings);
  4425. try {
  4426. const raw = localStorage.getItem(localSettingsSaveId);
  4427. const data = JSON.parse(raw);
  4428. Object.assign(currentSettings, data);
  4429. }
  4430. catch (e) {
  4431. // noop
  4432. }
  4433. this.fallbacks = {
  4434. getSettings() {
  4435. return currentSettings;
  4436. },
  4437. setSettings(value) {
  4438. try {
  4439. localStorage.setItem(localSettingsSaveId, JSON.stringify(value));
  4440. }
  4441. catch (e) {
  4442. // noop
  4443. }
  4444. currentSettings = value;
  4445. },
  4446. now() {
  4447. return now();
  4448. },
  4449. };
  4450. if (hook) {
  4451. hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => {
  4452. if (pluginId === this.plugin.id) {
  4453. this.fallbacks.setSettings(value);
  4454. }
  4455. });
  4456. }
  4457. this.proxiedOn = new Proxy({}, {
  4458. get: (_target, prop) => {
  4459. if (this.target) {
  4460. return this.target.on[prop];
  4461. }
  4462. else {
  4463. return (...args) => {
  4464. this.onQueue.push({
  4465. method: prop,
  4466. args,
  4467. });
  4468. };
  4469. }
  4470. },
  4471. });
  4472. this.proxiedTarget = new Proxy({}, {
  4473. get: (_target, prop) => {
  4474. if (this.target) {
  4475. return this.target[prop];
  4476. }
  4477. else if (prop === 'on') {
  4478. return this.proxiedOn;
  4479. }
  4480. else if (Object.keys(this.fallbacks).includes(prop)) {
  4481. return (...args) => {
  4482. this.targetQueue.push({
  4483. method: prop,
  4484. args,
  4485. resolve: () => { },
  4486. });
  4487. return this.fallbacks[prop](...args);
  4488. };
  4489. }
  4490. else {
  4491. return (...args) => {
  4492. return new Promise(resolve => {
  4493. this.targetQueue.push({
  4494. method: prop,
  4495. args,
  4496. resolve,
  4497. });
  4498. });
  4499. };
  4500. }
  4501. },
  4502. });
  4503. }
  4504. async setRealTarget(target) {
  4505. this.target = target;
  4506. for (const item of this.onQueue) {
  4507. this.target.on[item.method](...item.args);
  4508. }
  4509. for (const item of this.targetQueue) {
  4510. item.resolve(await this.target[item.method](...item.args));
  4511. }
  4512. }
  4513. }
  4514. function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
  4515. const descriptor = pluginDescriptor;
  4516. const target = getTarget();
  4517. const hook = getDevtoolsGlobalHook();
  4518. const enableProxy = isProxyAvailable && descriptor.enableEarlyProxy;
  4519. if (hook && (target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__ || !enableProxy)) {
  4520. hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
  4521. }
  4522. else {
  4523. const proxy = enableProxy ? new ApiProxy(descriptor, hook) : null;
  4524. const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
  4525. list.push({
  4526. pluginDescriptor: descriptor,
  4527. setupFn,
  4528. proxy,
  4529. });
  4530. if (proxy)
  4531. setupFn(proxy.proxiedTarget);
  4532. }
  4533. }
  4534. const VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties';
  4535. const VueDevToolsLabels = {
  4536. 'vue-devtools-plugin-vue-i18n': 'Vue I18n DevTools',
  4537. 'vue-i18n-resource-inspector': 'Vue I18n DevTools',
  4538. 'vue-i18n-timeline': 'Vue I18n'
  4539. };
  4540. const VueDevToolsPlaceholders = {
  4541. 'vue-i18n-resource-inspector': 'Search for scopes ...'
  4542. };
  4543. const VueDevToolsTimelineColors = {
  4544. 'vue-i18n-timeline': 0xffcd19
  4545. };
  4546. let devtoolsApi;
  4547. async function enableDevTools(app, i18n) {
  4548. return new Promise((resolve, reject) => {
  4549. try {
  4550. setupDevtoolsPlugin({
  4551. id: 'vue-devtools-plugin-vue-i18n',
  4552. label: VueDevToolsLabels['vue-devtools-plugin-vue-i18n'],
  4553. packageName: 'vue-i18n',
  4554. homepage: 'https://vue-i18n.intlify.dev',
  4555. logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png',
  4556. componentStateTypes: [VUE_I18N_COMPONENT_TYPES],
  4557. app: app // eslint-disable-line @typescript-eslint/no-explicit-any
  4558. }, api => {
  4559. devtoolsApi = api;
  4560. api.on.visitComponentTree(({ componentInstance, treeNode }) => {
  4561. updateComponentTreeTags(componentInstance, treeNode, i18n);
  4562. });
  4563. api.on.inspectComponent(({ componentInstance, instanceData }) => {
  4564. if (componentInstance.vnode.el &&
  4565. componentInstance.vnode.el.__VUE_I18N__ &&
  4566. instanceData) {
  4567. if (i18n.mode === 'legacy') {
  4568. // ignore global scope on legacy mode
  4569. if (componentInstance.vnode.el.__VUE_I18N__ !==
  4570. i18n.global.__composer) {
  4571. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  4572. }
  4573. }
  4574. else {
  4575. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  4576. }
  4577. }
  4578. });
  4579. api.addInspector({
  4580. id: 'vue-i18n-resource-inspector',
  4581. label: VueDevToolsLabels['vue-i18n-resource-inspector'],
  4582. icon: 'language',
  4583. treeFilterPlaceholder: VueDevToolsPlaceholders['vue-i18n-resource-inspector']
  4584. });
  4585. api.on.getInspectorTree(payload => {
  4586. if (payload.app === app &&
  4587. payload.inspectorId === 'vue-i18n-resource-inspector') {
  4588. registerScope(payload, i18n);
  4589. }
  4590. });
  4591. const roots = new Map();
  4592. api.on.getInspectorState(async (payload) => {
  4593. if (payload.app === app &&
  4594. payload.inspectorId === 'vue-i18n-resource-inspector') {
  4595. api.unhighlightElement();
  4596. inspectScope(payload, i18n);
  4597. if (payload.nodeId === 'global') {
  4598. if (!roots.has(payload.app)) {
  4599. const [root] = await api.getComponentInstances(payload.app);
  4600. roots.set(payload.app, root);
  4601. }
  4602. api.highlightElement(roots.get(payload.app));
  4603. }
  4604. else {
  4605. const instance = getComponentInstance(payload.nodeId, i18n);
  4606. instance && api.highlightElement(instance);
  4607. }
  4608. }
  4609. });
  4610. api.on.editInspectorState(payload => {
  4611. if (payload.app === app &&
  4612. payload.inspectorId === 'vue-i18n-resource-inspector') {
  4613. editScope(payload, i18n);
  4614. }
  4615. });
  4616. api.addTimelineLayer({
  4617. id: 'vue-i18n-timeline',
  4618. label: VueDevToolsLabels['vue-i18n-timeline'],
  4619. color: VueDevToolsTimelineColors['vue-i18n-timeline']
  4620. });
  4621. resolve(true);
  4622. });
  4623. }
  4624. catch (e) {
  4625. console.error(e);
  4626. // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
  4627. reject(false);
  4628. }
  4629. });
  4630. }
  4631. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4632. function getI18nScopeLable(instance) {
  4633. return (instance.type.name ||
  4634. instance.type.displayName ||
  4635. instance.type.__file ||
  4636. 'Anonymous');
  4637. }
  4638. function updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any
  4639. treeNode, i18n) {
  4640. // prettier-ignore
  4641. const global = i18n.mode === 'composition'
  4642. ? i18n.global
  4643. : i18n.global.__composer;
  4644. if (instance && instance.vnode.el && instance.vnode.el.__VUE_I18N__) {
  4645. // add custom tags local scope only
  4646. if (instance.vnode.el.__VUE_I18N__ !== global) {
  4647. const tag = {
  4648. label: `i18n (${getI18nScopeLable(instance)} Scope)`,
  4649. textColor: 0x000000,
  4650. backgroundColor: 0xffcd19
  4651. };
  4652. treeNode.tags.push(tag);
  4653. }
  4654. }
  4655. }
  4656. function inspectComposer(instanceData, composer) {
  4657. const type = VUE_I18N_COMPONENT_TYPES;
  4658. instanceData.state.push({
  4659. type,
  4660. key: 'locale',
  4661. editable: true,
  4662. value: composer.locale.value
  4663. });
  4664. instanceData.state.push({
  4665. type,
  4666. key: 'availableLocales',
  4667. editable: false,
  4668. value: composer.availableLocales
  4669. });
  4670. instanceData.state.push({
  4671. type,
  4672. key: 'fallbackLocale',
  4673. editable: true,
  4674. value: composer.fallbackLocale.value
  4675. });
  4676. instanceData.state.push({
  4677. type,
  4678. key: 'inheritLocale',
  4679. editable: true,
  4680. value: composer.inheritLocale
  4681. });
  4682. instanceData.state.push({
  4683. type,
  4684. key: 'messages',
  4685. editable: false,
  4686. value: getLocaleMessageValue(composer.messages.value)
  4687. });
  4688. {
  4689. instanceData.state.push({
  4690. type,
  4691. key: 'datetimeFormats',
  4692. editable: false,
  4693. value: composer.datetimeFormats.value
  4694. });
  4695. instanceData.state.push({
  4696. type,
  4697. key: 'numberFormats',
  4698. editable: false,
  4699. value: composer.numberFormats.value
  4700. });
  4701. }
  4702. }
  4703. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4704. function getLocaleMessageValue(messages) {
  4705. const value = {};
  4706. Object.keys(messages).forEach((key) => {
  4707. const v = messages[key];
  4708. if (isFunction(v) && 'source' in v) {
  4709. value[key] = getMessageFunctionDetails(v);
  4710. }
  4711. else if (isMessageAST(v) && v.loc && v.loc.source) {
  4712. value[key] = v.loc.source;
  4713. }
  4714. else if (isObject(v)) {
  4715. value[key] = getLocaleMessageValue(v);
  4716. }
  4717. else {
  4718. value[key] = v;
  4719. }
  4720. });
  4721. return value;
  4722. }
  4723. const ESC = {
  4724. '<': '&lt;',
  4725. '>': '&gt;',
  4726. '"': '&quot;',
  4727. '&': '&amp;'
  4728. };
  4729. function escape(s) {
  4730. return s.replace(/[<>"&]/g, escapeChar);
  4731. }
  4732. function escapeChar(a) {
  4733. return ESC[a] || a;
  4734. }
  4735. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4736. function getMessageFunctionDetails(func) {
  4737. const argString = func.source ? `("${escape(func.source)}")` : `(?)`;
  4738. return {
  4739. _custom: {
  4740. type: 'function',
  4741. display: `<span>ƒ</span> ${argString}`
  4742. }
  4743. };
  4744. }
  4745. function registerScope(payload, i18n) {
  4746. payload.rootNodes.push({
  4747. id: 'global',
  4748. label: 'Global Scope'
  4749. });
  4750. // prettier-ignore
  4751. const global = i18n.mode === 'composition'
  4752. ? i18n.global
  4753. : i18n.global.__composer;
  4754. for (const [keyInstance, instance] of i18n.__instances) {
  4755. // prettier-ignore
  4756. const composer = i18n.mode === 'composition'
  4757. ? instance
  4758. : instance.__composer;
  4759. if (global === composer) {
  4760. continue;
  4761. }
  4762. payload.rootNodes.push({
  4763. id: composer.id.toString(),
  4764. label: `${getI18nScopeLable(keyInstance)} Scope`
  4765. });
  4766. }
  4767. }
  4768. function getComponentInstance(nodeId, i18n) {
  4769. let instance = null;
  4770. if (nodeId !== 'global') {
  4771. for (const [component, composer] of i18n.__instances.entries()) {
  4772. if (composer.id.toString() === nodeId) {
  4773. instance = component;
  4774. break;
  4775. }
  4776. }
  4777. }
  4778. return instance;
  4779. }
  4780. function getComposer$2(nodeId, i18n) {
  4781. if (nodeId === 'global') {
  4782. return i18n.mode === 'composition'
  4783. ? i18n.global
  4784. : i18n.global.__composer;
  4785. }
  4786. else {
  4787. const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId);
  4788. if (instance) {
  4789. return i18n.mode === 'composition'
  4790. ? instance
  4791. : instance.__composer;
  4792. }
  4793. else {
  4794. return null;
  4795. }
  4796. }
  4797. }
  4798. function inspectScope(payload, i18n
  4799. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4800. ) {
  4801. const composer = getComposer$2(payload.nodeId, i18n);
  4802. if (composer) {
  4803. // TODO:
  4804. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4805. payload.state = makeScopeInspectState(composer);
  4806. }
  4807. return null;
  4808. }
  4809. function makeScopeInspectState(composer) {
  4810. const state = {};
  4811. const localeType = 'Locale related info';
  4812. const localeStates = [
  4813. {
  4814. type: localeType,
  4815. key: 'locale',
  4816. editable: true,
  4817. value: composer.locale.value
  4818. },
  4819. {
  4820. type: localeType,
  4821. key: 'fallbackLocale',
  4822. editable: true,
  4823. value: composer.fallbackLocale.value
  4824. },
  4825. {
  4826. type: localeType,
  4827. key: 'availableLocales',
  4828. editable: false,
  4829. value: composer.availableLocales
  4830. },
  4831. {
  4832. type: localeType,
  4833. key: 'inheritLocale',
  4834. editable: true,
  4835. value: composer.inheritLocale
  4836. }
  4837. ];
  4838. state[localeType] = localeStates;
  4839. const localeMessagesType = 'Locale messages info';
  4840. const localeMessagesStates = [
  4841. {
  4842. type: localeMessagesType,
  4843. key: 'messages',
  4844. editable: false,
  4845. value: getLocaleMessageValue(composer.messages.value)
  4846. }
  4847. ];
  4848. state[localeMessagesType] = localeMessagesStates;
  4849. {
  4850. const datetimeFormatsType = 'Datetime formats info';
  4851. const datetimeFormatsStates = [
  4852. {
  4853. type: datetimeFormatsType,
  4854. key: 'datetimeFormats',
  4855. editable: false,
  4856. value: composer.datetimeFormats.value
  4857. }
  4858. ];
  4859. state[datetimeFormatsType] = datetimeFormatsStates;
  4860. const numberFormatsType = 'Datetime formats info';
  4861. const numberFormatsStates = [
  4862. {
  4863. type: numberFormatsType,
  4864. key: 'numberFormats',
  4865. editable: false,
  4866. value: composer.numberFormats.value
  4867. }
  4868. ];
  4869. state[numberFormatsType] = numberFormatsStates;
  4870. }
  4871. return state;
  4872. }
  4873. function addTimelineEvent(event, payload) {
  4874. if (devtoolsApi) {
  4875. let groupId;
  4876. if (payload && 'groupId' in payload) {
  4877. groupId = payload.groupId;
  4878. delete payload.groupId;
  4879. }
  4880. devtoolsApi.addTimelineEvent({
  4881. layerId: 'vue-i18n-timeline',
  4882. event: {
  4883. title: event,
  4884. groupId,
  4885. time: Date.now(),
  4886. meta: {},
  4887. data: payload || {},
  4888. logType: event === 'compile-error'
  4889. ? 'error'
  4890. : event === 'fallback' || event === 'missing'
  4891. ? 'warning'
  4892. : 'default'
  4893. }
  4894. });
  4895. }
  4896. }
  4897. function editScope(payload, i18n) {
  4898. const composer = getComposer$2(payload.nodeId, i18n);
  4899. if (composer) {
  4900. const [field] = payload.path;
  4901. if (field === 'locale' && isString(payload.state.value)) {
  4902. composer.locale.value = payload.state.value;
  4903. }
  4904. else if (field === 'fallbackLocale' &&
  4905. (isString(payload.state.value) ||
  4906. isArray(payload.state.value) ||
  4907. isObject(payload.state.value))) {
  4908. composer.fallbackLocale.value = payload.state.value;
  4909. }
  4910. else if (field === 'inheritLocale' && isBoolean(payload.state.value)) {
  4911. composer.inheritLocale = payload.state.value;
  4912. }
  4913. }
  4914. }
  4915. /* eslint-disable @typescript-eslint/no-explicit-any */
  4916. /**
  4917. * Convert to I18n Composer Options from VueI18n Options
  4918. *
  4919. * @internal
  4920. */
  4921. function convertComposerOptions(options) {
  4922. const locale = isString(options.locale) ? options.locale : DEFAULT_LOCALE;
  4923. const fallbackLocale = isString(options.fallbackLocale) ||
  4924. isArray(options.fallbackLocale) ||
  4925. isPlainObject(options.fallbackLocale) ||
  4926. options.fallbackLocale === false
  4927. ? options.fallbackLocale
  4928. : locale;
  4929. const missing = isFunction(options.missing) ? options.missing : undefined;
  4930. const missingWarn = isBoolean(options.silentTranslationWarn) ||
  4931. isRegExp(options.silentTranslationWarn)
  4932. ? !options.silentTranslationWarn
  4933. : true;
  4934. const fallbackWarn = isBoolean(options.silentFallbackWarn) ||
  4935. isRegExp(options.silentFallbackWarn)
  4936. ? !options.silentFallbackWarn
  4937. : true;
  4938. const fallbackRoot = isBoolean(options.fallbackRoot)
  4939. ? options.fallbackRoot
  4940. : true;
  4941. const fallbackFormat = !!options.formatFallbackMessages;
  4942. const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};
  4943. const pluralizationRules = options.pluralizationRules;
  4944. const postTranslation = isFunction(options.postTranslation)
  4945. ? options.postTranslation
  4946. : undefined;
  4947. const warnHtmlMessage = isString(options.warnHtmlInMessage)
  4948. ? options.warnHtmlInMessage !== 'off'
  4949. : true;
  4950. const escapeParameter = !!options.escapeParameterHtml;
  4951. const inheritLocale = isBoolean(options.sync) ? options.sync : true;
  4952. let messages = options.messages;
  4953. if (isPlainObject(options.sharedMessages)) {
  4954. const sharedMessages = options.sharedMessages;
  4955. const locales = Object.keys(sharedMessages);
  4956. messages = locales.reduce((messages, locale) => {
  4957. const message = messages[locale] || (messages[locale] = {});
  4958. assign(message, sharedMessages[locale]);
  4959. return messages;
  4960. }, (messages || {}));
  4961. }
  4962. const { __i18n, __root, __injectWithOption } = options;
  4963. const datetimeFormats = options.datetimeFormats;
  4964. const numberFormats = options.numberFormats;
  4965. const flatJson = options.flatJson;
  4966. return {
  4967. locale,
  4968. fallbackLocale,
  4969. messages,
  4970. flatJson,
  4971. datetimeFormats,
  4972. numberFormats,
  4973. missing,
  4974. missingWarn,
  4975. fallbackWarn,
  4976. fallbackRoot,
  4977. fallbackFormat,
  4978. modifiers,
  4979. pluralRules: pluralizationRules,
  4980. postTranslation,
  4981. warnHtmlMessage,
  4982. escapeParameter,
  4983. messageResolver: options.messageResolver,
  4984. inheritLocale,
  4985. __i18n,
  4986. __root,
  4987. __injectWithOption
  4988. };
  4989. }
  4990. /**
  4991. * create VueI18n interface factory
  4992. *
  4993. * @internal
  4994. *
  4995. * @deprecated will be removed at vue-i18n v12
  4996. */
  4997. function createVueI18n(options = {}) {
  4998. const composer = createComposer(convertComposerOptions(options));
  4999. const { __extender } = options;
  5000. // defines VueI18n
  5001. const vueI18n = {
  5002. // id
  5003. id: composer.id,
  5004. // locale
  5005. get locale() {
  5006. return composer.locale.value;
  5007. },
  5008. set locale(val) {
  5009. composer.locale.value = val;
  5010. },
  5011. // fallbackLocale
  5012. get fallbackLocale() {
  5013. return composer.fallbackLocale.value;
  5014. },
  5015. set fallbackLocale(val) {
  5016. composer.fallbackLocale.value = val;
  5017. },
  5018. // messages
  5019. get messages() {
  5020. return composer.messages.value;
  5021. },
  5022. // datetimeFormats
  5023. get datetimeFormats() {
  5024. return composer.datetimeFormats.value;
  5025. },
  5026. // numberFormats
  5027. get numberFormats() {
  5028. return composer.numberFormats.value;
  5029. },
  5030. // availableLocales
  5031. get availableLocales() {
  5032. return composer.availableLocales;
  5033. },
  5034. // missing
  5035. get missing() {
  5036. return composer.getMissingHandler();
  5037. },
  5038. set missing(handler) {
  5039. composer.setMissingHandler(handler);
  5040. },
  5041. // silentTranslationWarn
  5042. get silentTranslationWarn() {
  5043. return isBoolean(composer.missingWarn)
  5044. ? !composer.missingWarn
  5045. : composer.missingWarn;
  5046. },
  5047. set silentTranslationWarn(val) {
  5048. composer.missingWarn = isBoolean(val) ? !val : val;
  5049. },
  5050. // silentFallbackWarn
  5051. get silentFallbackWarn() {
  5052. return isBoolean(composer.fallbackWarn)
  5053. ? !composer.fallbackWarn
  5054. : composer.fallbackWarn;
  5055. },
  5056. set silentFallbackWarn(val) {
  5057. composer.fallbackWarn = isBoolean(val) ? !val : val;
  5058. },
  5059. // modifiers
  5060. get modifiers() {
  5061. return composer.modifiers;
  5062. },
  5063. // formatFallbackMessages
  5064. get formatFallbackMessages() {
  5065. return composer.fallbackFormat;
  5066. },
  5067. set formatFallbackMessages(val) {
  5068. composer.fallbackFormat = val;
  5069. },
  5070. // postTranslation
  5071. get postTranslation() {
  5072. return composer.getPostTranslationHandler();
  5073. },
  5074. set postTranslation(handler) {
  5075. composer.setPostTranslationHandler(handler);
  5076. },
  5077. // sync
  5078. get sync() {
  5079. return composer.inheritLocale;
  5080. },
  5081. set sync(val) {
  5082. composer.inheritLocale = val;
  5083. },
  5084. // warnInHtmlMessage
  5085. get warnHtmlInMessage() {
  5086. return composer.warnHtmlMessage ? 'warn' : 'off';
  5087. },
  5088. set warnHtmlInMessage(val) {
  5089. composer.warnHtmlMessage = val !== 'off';
  5090. },
  5091. // escapeParameterHtml
  5092. get escapeParameterHtml() {
  5093. return composer.escapeParameter;
  5094. },
  5095. set escapeParameterHtml(val) {
  5096. composer.escapeParameter = val;
  5097. },
  5098. // pluralizationRules
  5099. get pluralizationRules() {
  5100. return composer.pluralRules || {};
  5101. },
  5102. // for internal
  5103. __composer: composer,
  5104. // t
  5105. t(...args) {
  5106. return Reflect.apply(composer.t, composer, [...args]);
  5107. },
  5108. // rt
  5109. rt(...args) {
  5110. return Reflect.apply(composer.rt, composer, [...args]);
  5111. },
  5112. // te
  5113. te(key, locale) {
  5114. return composer.te(key, locale);
  5115. },
  5116. // tm
  5117. tm(key) {
  5118. return composer.tm(key);
  5119. },
  5120. // getLocaleMessage
  5121. getLocaleMessage(locale) {
  5122. return composer.getLocaleMessage(locale);
  5123. },
  5124. // setLocaleMessage
  5125. setLocaleMessage(locale, message) {
  5126. composer.setLocaleMessage(locale, message);
  5127. },
  5128. // mergeLocaleMessage
  5129. mergeLocaleMessage(locale, message) {
  5130. composer.mergeLocaleMessage(locale, message);
  5131. },
  5132. // d
  5133. d(...args) {
  5134. return Reflect.apply(composer.d, composer, [...args]);
  5135. },
  5136. // getDateTimeFormat
  5137. getDateTimeFormat(locale) {
  5138. return composer.getDateTimeFormat(locale);
  5139. },
  5140. // setDateTimeFormat
  5141. setDateTimeFormat(locale, format) {
  5142. composer.setDateTimeFormat(locale, format);
  5143. },
  5144. // mergeDateTimeFormat
  5145. mergeDateTimeFormat(locale, format) {
  5146. composer.mergeDateTimeFormat(locale, format);
  5147. },
  5148. // n
  5149. n(...args) {
  5150. return Reflect.apply(composer.n, composer, [...args]);
  5151. },
  5152. // getNumberFormat
  5153. getNumberFormat(locale) {
  5154. return composer.getNumberFormat(locale);
  5155. },
  5156. // setNumberFormat
  5157. setNumberFormat(locale, format) {
  5158. composer.setNumberFormat(locale, format);
  5159. },
  5160. // mergeNumberFormat
  5161. mergeNumberFormat(locale, format) {
  5162. composer.mergeNumberFormat(locale, format);
  5163. }
  5164. };
  5165. vueI18n.__extender = __extender;
  5166. // for vue-devtools timeline event
  5167. {
  5168. vueI18n.__enableEmitter = (emitter) => {
  5169. const __composer = composer;
  5170. __composer[EnableEmitter] && __composer[EnableEmitter](emitter);
  5171. };
  5172. vueI18n.__disableEmitter = () => {
  5173. const __composer = composer;
  5174. __composer[DisableEmitter] && __composer[DisableEmitter]();
  5175. };
  5176. }
  5177. return vueI18n;
  5178. }
  5179. /* eslint-enable @typescript-eslint/no-explicit-any */
  5180. /**
  5181. * Supports compatibility for legacy vue-i18n APIs
  5182. * This mixin is used when we use vue-i18n@v9.x or later
  5183. */
  5184. function defineMixin(vuei18n, composer, i18n) {
  5185. return {
  5186. beforeCreate() {
  5187. const instance = vue.getCurrentInstance();
  5188. /* istanbul ignore if */
  5189. if (!instance) {
  5190. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  5191. }
  5192. const options = this.$options;
  5193. if (options.i18n) {
  5194. const optionsI18n = options.i18n;
  5195. if (options.__i18n) {
  5196. optionsI18n.__i18n = options.__i18n;
  5197. }
  5198. optionsI18n.__root = composer;
  5199. if (this === this.$root) {
  5200. // merge option and gttach global
  5201. this.$i18n = mergeToGlobal(vuei18n, optionsI18n);
  5202. }
  5203. else {
  5204. optionsI18n.__injectWithOption = true;
  5205. optionsI18n.__extender = i18n.__vueI18nExtend;
  5206. // atttach local VueI18n instance
  5207. this.$i18n = createVueI18n(optionsI18n);
  5208. // extend VueI18n instance
  5209. const _vueI18n = this.$i18n;
  5210. if (_vueI18n.__extender) {
  5211. _vueI18n.__disposer = _vueI18n.__extender(this.$i18n);
  5212. }
  5213. }
  5214. }
  5215. else if (options.__i18n) {
  5216. if (this === this.$root) {
  5217. // merge option and gttach global
  5218. this.$i18n = mergeToGlobal(vuei18n, options);
  5219. }
  5220. else {
  5221. // atttach local VueI18n instance
  5222. this.$i18n = createVueI18n({
  5223. __i18n: options.__i18n,
  5224. __injectWithOption: true,
  5225. __extender: i18n.__vueI18nExtend,
  5226. __root: composer
  5227. });
  5228. // extend VueI18n instance
  5229. const _vueI18n = this.$i18n;
  5230. if (_vueI18n.__extender) {
  5231. _vueI18n.__disposer = _vueI18n.__extender(this.$i18n);
  5232. }
  5233. }
  5234. }
  5235. else {
  5236. // attach global VueI18n instance
  5237. this.$i18n = vuei18n;
  5238. }
  5239. if (options.__i18nGlobal) {
  5240. adjustI18nResources(composer, options, options);
  5241. }
  5242. // defines vue-i18n legacy APIs
  5243. this.$t = (...args) => this.$i18n.t(...args);
  5244. this.$rt = (...args) => this.$i18n.rt(...args);
  5245. this.$te = (key, locale) => this.$i18n.te(key, locale);
  5246. this.$d = (...args) => this.$i18n.d(...args);
  5247. this.$n = (...args) => this.$i18n.n(...args);
  5248. this.$tm = (key) => this.$i18n.tm(key);
  5249. i18n.__setInstance(instance, this.$i18n);
  5250. },
  5251. mounted() {
  5252. /* istanbul ignore if */
  5253. if (this.$el &&
  5254. this.$i18n) {
  5255. const _vueI18n = this.$i18n;
  5256. this.$el.__VUE_I18N__ = _vueI18n.__composer;
  5257. const emitter = (this.__v_emitter =
  5258. createEmitter());
  5259. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  5260. emitter.on('*', addTimelineEvent);
  5261. }
  5262. },
  5263. unmounted() {
  5264. const instance = vue.getCurrentInstance();
  5265. /* istanbul ignore if */
  5266. if (!instance) {
  5267. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  5268. }
  5269. const _vueI18n = this.$i18n;
  5270. /* istanbul ignore if */
  5271. if (this.$el &&
  5272. this.$el.__VUE_I18N__) {
  5273. if (this.__v_emitter) {
  5274. this.__v_emitter.off('*', addTimelineEvent);
  5275. delete this.__v_emitter;
  5276. }
  5277. if (this.$i18n) {
  5278. _vueI18n.__disableEmitter && _vueI18n.__disableEmitter();
  5279. delete this.$el.__VUE_I18N__;
  5280. }
  5281. }
  5282. delete this.$t;
  5283. delete this.$rt;
  5284. delete this.$te;
  5285. delete this.$d;
  5286. delete this.$n;
  5287. delete this.$tm;
  5288. if (_vueI18n.__disposer) {
  5289. _vueI18n.__disposer();
  5290. delete _vueI18n.__disposer;
  5291. delete _vueI18n.__extender;
  5292. }
  5293. i18n.__deleteInstance(instance);
  5294. delete this.$i18n;
  5295. }
  5296. };
  5297. }
  5298. function mergeToGlobal(g, options) {
  5299. g.locale = options.locale || g.locale;
  5300. g.fallbackLocale = options.fallbackLocale || g.fallbackLocale;
  5301. g.missing = options.missing || g.missing;
  5302. g.silentTranslationWarn =
  5303. options.silentTranslationWarn || g.silentFallbackWarn;
  5304. g.silentFallbackWarn = options.silentFallbackWarn || g.silentFallbackWarn;
  5305. g.formatFallbackMessages =
  5306. options.formatFallbackMessages || g.formatFallbackMessages;
  5307. g.postTranslation = options.postTranslation || g.postTranslation;
  5308. g.warnHtmlInMessage = options.warnHtmlInMessage || g.warnHtmlInMessage;
  5309. g.escapeParameterHtml = options.escapeParameterHtml || g.escapeParameterHtml;
  5310. g.sync = options.sync || g.sync;
  5311. g.__composer[SetPluralRulesSymbol](options.pluralizationRules || g.pluralizationRules);
  5312. const messages = getLocaleMessages(g.locale, {
  5313. messages: options.messages,
  5314. __i18n: options.__i18n
  5315. });
  5316. Object.keys(messages).forEach(locale => g.mergeLocaleMessage(locale, messages[locale]));
  5317. if (options.datetimeFormats) {
  5318. Object.keys(options.datetimeFormats).forEach(locale => g.mergeDateTimeFormat(locale, options.datetimeFormats[locale]));
  5319. }
  5320. if (options.numberFormats) {
  5321. Object.keys(options.numberFormats).forEach(locale => g.mergeNumberFormat(locale, options.numberFormats[locale]));
  5322. }
  5323. return g;
  5324. }
  5325. const baseFormatProps = {
  5326. tag: {
  5327. type: [String, Object]
  5328. },
  5329. locale: {
  5330. type: String
  5331. },
  5332. scope: {
  5333. type: String,
  5334. // NOTE: avoid https://github.com/microsoft/rushstack/issues/1050
  5335. validator: (val /* ComponentI18nScope */) => val === 'parent' || val === 'global',
  5336. default: 'parent' /* ComponentI18nScope */
  5337. },
  5338. i18n: {
  5339. type: Object
  5340. }
  5341. };
  5342. function getInterpolateArg(
  5343. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5344. { slots }, // SetupContext,
  5345. keys) {
  5346. if (keys.length === 1 && keys[0] === 'default') {
  5347. // default slot with list
  5348. const ret = slots.default ? slots.default() : [];
  5349. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5350. return ret.reduce((slot, current) => {
  5351. return [
  5352. ...slot,
  5353. // prettier-ignore
  5354. ...(current.type === vue.Fragment ? current.children : [current])
  5355. ];
  5356. }, []);
  5357. }
  5358. else {
  5359. // named slots
  5360. return keys.reduce((arg, key) => {
  5361. const slot = slots[key];
  5362. if (slot) {
  5363. arg[key] = slot();
  5364. }
  5365. return arg;
  5366. }, create());
  5367. }
  5368. }
  5369. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5370. function getFragmentableTag() {
  5371. return vue.Fragment;
  5372. }
  5373. const TranslationImpl = /*#__PURE__*/ vue.defineComponent({
  5374. /* eslint-disable */
  5375. name: 'i18n-t',
  5376. props: assign({
  5377. keypath: {
  5378. type: String,
  5379. required: true
  5380. },
  5381. plural: {
  5382. type: [Number, String],
  5383. validator: (val) => isNumber(val) || !isNaN(val)
  5384. }
  5385. }, baseFormatProps),
  5386. /* eslint-enable */
  5387. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5388. setup(props, context) {
  5389. const { slots, attrs } = context;
  5390. // NOTE: avoid https://github.com/microsoft/rushstack/issues/1050
  5391. const i18n = props.i18n ||
  5392. useI18n({
  5393. useScope: props.scope,
  5394. __useComponent: true
  5395. });
  5396. return () => {
  5397. const keys = Object.keys(slots).filter(key => key !== '_');
  5398. const options = create();
  5399. if (props.locale) {
  5400. options.locale = props.locale;
  5401. }
  5402. if (props.plural !== undefined) {
  5403. options.plural = isString(props.plural) ? +props.plural : props.plural;
  5404. }
  5405. const arg = getInterpolateArg(context, keys);
  5406. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5407. const children = i18n[TranslateVNodeSymbol](props.keypath, arg, options);
  5408. const assignedAttrs = assign(create(), attrs);
  5409. const tag = isString(props.tag) || isObject(props.tag)
  5410. ? props.tag
  5411. : getFragmentableTag();
  5412. return vue.h(tag, assignedAttrs, children);
  5413. };
  5414. }
  5415. });
  5416. /**
  5417. * export the public type for h/tsx inference
  5418. * also to avoid inline import() in generated d.ts files
  5419. */
  5420. /**
  5421. * Translation Component
  5422. *
  5423. * @remarks
  5424. * See the following items for property about details
  5425. *
  5426. * @VueI18nSee [TranslationProps](component#translationprops)
  5427. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  5428. * @VueI18nSee [Component Interpolation](../guide/advanced/component)
  5429. *
  5430. * @example
  5431. * ```html
  5432. * <div id="app">
  5433. * <!-- ... -->
  5434. * <i18n keypath="term" tag="label" for="tos">
  5435. * <a :href="url" target="_blank">{{ $t('tos') }}</a>
  5436. * </i18n>
  5437. * <!-- ... -->
  5438. * </div>
  5439. * ```
  5440. * ```js
  5441. * import { createApp } from 'vue'
  5442. * import { createI18n } from 'vue-i18n'
  5443. *
  5444. * const messages = {
  5445. * en: {
  5446. * tos: 'Term of Service',
  5447. * term: 'I accept xxx {0}.'
  5448. * },
  5449. * ja: {
  5450. * tos: '利用規約',
  5451. * term: '私は xxx の{0}に同意します。'
  5452. * }
  5453. * }
  5454. *
  5455. * const i18n = createI18n({
  5456. * locale: 'en',
  5457. * messages
  5458. * })
  5459. *
  5460. * const app = createApp({
  5461. * data: {
  5462. * url: '/term'
  5463. * }
  5464. * }).use(i18n).mount('#app')
  5465. * ```
  5466. *
  5467. * @VueI18nComponent
  5468. */
  5469. const Translation = TranslationImpl;
  5470. const I18nT = Translation;
  5471. function isVNode(target) {
  5472. return isArray(target) && !isString(target[0]);
  5473. }
  5474. function renderFormatter(props, context, slotKeys, partFormatter) {
  5475. const { slots, attrs } = context;
  5476. return () => {
  5477. const options = { part: true };
  5478. let overrides = create();
  5479. if (props.locale) {
  5480. options.locale = props.locale;
  5481. }
  5482. if (isString(props.format)) {
  5483. options.key = props.format;
  5484. }
  5485. else if (isObject(props.format)) {
  5486. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5487. if (isString(props.format.key)) {
  5488. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5489. options.key = props.format.key;
  5490. }
  5491. // Filter out number format options only
  5492. overrides = Object.keys(props.format).reduce((options, prop) => {
  5493. return slotKeys.includes(prop)
  5494. ? assign(create(), options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
  5495. : options;
  5496. }, create());
  5497. }
  5498. const parts = partFormatter(...[props.value, options, overrides]);
  5499. let children = [options.key];
  5500. if (isArray(parts)) {
  5501. children = parts.map((part, index) => {
  5502. const slot = slots[part.type];
  5503. const node = slot
  5504. ? slot({ [part.type]: part.value, index, parts })
  5505. : [part.value];
  5506. if (isVNode(node)) {
  5507. node[0].key = `${part.type}-${index}`;
  5508. }
  5509. return node;
  5510. });
  5511. }
  5512. else if (isString(parts)) {
  5513. children = [parts];
  5514. }
  5515. const assignedAttrs = assign(create(), attrs);
  5516. const tag = isString(props.tag) || isObject(props.tag)
  5517. ? props.tag
  5518. : getFragmentableTag();
  5519. return vue.h(tag, assignedAttrs, children);
  5520. };
  5521. }
  5522. const NumberFormatImpl = /*#__PURE__*/ vue.defineComponent({
  5523. /* eslint-disable */
  5524. name: 'i18n-n',
  5525. props: assign({
  5526. value: {
  5527. type: Number,
  5528. required: true
  5529. },
  5530. format: {
  5531. type: [String, Object]
  5532. }
  5533. }, baseFormatProps),
  5534. /* eslint-enable */
  5535. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5536. setup(props, context) {
  5537. const i18n = props.i18n ||
  5538. useI18n({
  5539. useScope: props.scope,
  5540. __useComponent: true
  5541. });
  5542. return renderFormatter(props, context, NUMBER_FORMAT_OPTIONS_KEYS, (...args) =>
  5543. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5544. i18n[NumberPartsSymbol](...args));
  5545. }
  5546. });
  5547. /**
  5548. * export the public type for h/tsx inference
  5549. * also to avoid inline import() in generated d.ts files
  5550. */
  5551. /**
  5552. * Number Format Component
  5553. *
  5554. * @remarks
  5555. * See the following items for property about details
  5556. *
  5557. * @VueI18nSee [FormattableProps](component#formattableprops)
  5558. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  5559. * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting)
  5560. *
  5561. * @VueI18nDanger
  5562. * 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)
  5563. *
  5564. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)
  5565. *
  5566. * @VueI18nComponent
  5567. */
  5568. const NumberFormat = NumberFormatImpl;
  5569. const I18nN = NumberFormat;
  5570. function getComposer$1(i18n, instance) {
  5571. const i18nInternal = i18n;
  5572. if (i18n.mode === 'composition') {
  5573. return (i18nInternal.__getInstance(instance) || i18n.global);
  5574. }
  5575. else {
  5576. const vueI18n = i18nInternal.__getInstance(instance);
  5577. return vueI18n != null
  5578. ? vueI18n.__composer
  5579. : i18n.global.__composer;
  5580. }
  5581. }
  5582. /**
  5583. * @deprecated will be removed at vue-i18n v12
  5584. */
  5585. function vTDirective(i18n) {
  5586. const _process = (binding) => {
  5587. {
  5588. warnOnce(getWarnMessage(I18nWarnCodes.DEPRECATE_TRANSLATE_CUSTOME_DIRECTIVE));
  5589. }
  5590. const { instance, value } = binding;
  5591. /* istanbul ignore if */
  5592. if (!instance || !instance.$) {
  5593. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  5594. }
  5595. const composer = getComposer$1(i18n, instance.$);
  5596. const parsedValue = parseValue(value);
  5597. return [
  5598. Reflect.apply(composer.t, composer, [...makeParams(parsedValue)]),
  5599. composer
  5600. ];
  5601. };
  5602. const register = (el, binding) => {
  5603. const [textContent, composer] = _process(binding);
  5604. if (inBrowser && i18n.global === composer) {
  5605. // global scope only
  5606. el.__i18nWatcher = vue.watch(composer.locale, () => {
  5607. binding.instance && binding.instance.$forceUpdate();
  5608. });
  5609. }
  5610. el.__composer = composer;
  5611. el.textContent = textContent;
  5612. };
  5613. const unregister = (el) => {
  5614. if (inBrowser && el.__i18nWatcher) {
  5615. el.__i18nWatcher();
  5616. el.__i18nWatcher = undefined;
  5617. delete el.__i18nWatcher;
  5618. }
  5619. if (el.__composer) {
  5620. el.__composer = undefined;
  5621. delete el.__composer;
  5622. }
  5623. };
  5624. const update = (el, { value }) => {
  5625. if (el.__composer) {
  5626. const composer = el.__composer;
  5627. const parsedValue = parseValue(value);
  5628. el.textContent = Reflect.apply(composer.t, composer, [
  5629. ...makeParams(parsedValue)
  5630. ]);
  5631. }
  5632. };
  5633. const getSSRProps = (binding) => {
  5634. const [textContent] = _process(binding);
  5635. return { textContent };
  5636. };
  5637. return {
  5638. created: register,
  5639. unmounted: unregister,
  5640. beforeUpdate: update,
  5641. getSSRProps
  5642. };
  5643. }
  5644. function parseValue(value) {
  5645. if (isString(value)) {
  5646. return { path: value };
  5647. }
  5648. else if (isPlainObject(value)) {
  5649. if (!('path' in value)) {
  5650. throw createI18nError(I18nErrorCodes.REQUIRED_VALUE, 'path');
  5651. }
  5652. return value;
  5653. }
  5654. else {
  5655. throw createI18nError(I18nErrorCodes.INVALID_VALUE);
  5656. }
  5657. }
  5658. function makeParams(value) {
  5659. const { path, locale, args, choice, plural } = value;
  5660. const options = {};
  5661. const named = args || {};
  5662. if (isString(locale)) {
  5663. options.locale = locale;
  5664. }
  5665. if (isNumber(choice)) {
  5666. options.plural = choice;
  5667. }
  5668. if (isNumber(plural)) {
  5669. options.plural = plural;
  5670. }
  5671. return [path, named, options];
  5672. }
  5673. function apply(app, i18n, ...options) {
  5674. const pluginOptions = isPlainObject(options[0])
  5675. ? options[0]
  5676. : {};
  5677. const globalInstall = isBoolean(pluginOptions.globalInstall)
  5678. ? pluginOptions.globalInstall
  5679. : true;
  5680. if (globalInstall) {
  5681. [Translation.name, 'I18nT'].forEach(name => app.component(name, Translation));
  5682. [NumberFormat.name, 'I18nN'].forEach(name => app.component(name, NumberFormat));
  5683. [DatetimeFormat.name, 'I18nD'].forEach(name => app.component(name, DatetimeFormat));
  5684. }
  5685. // install directive
  5686. {
  5687. app.directive('t', vTDirective(i18n));
  5688. }
  5689. }
  5690. /**
  5691. * Injection key for {@link useI18n}
  5692. *
  5693. * @remarks
  5694. * The global injection key for I18n instances with `useI18n`. this injection key is used in Web Components.
  5695. * Specify the i18n instance created by {@link createI18n} together with `provide` function.
  5696. *
  5697. * @VueI18nGeneral
  5698. */
  5699. const I18nInjectionKey =
  5700. /* #__PURE__*/ makeSymbol('global-vue-i18n');
  5701. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5702. function createI18n(options = {}) {
  5703. // prettier-ignore
  5704. const __legacyMode = isBoolean(options.legacy)
  5705. ? options.legacy
  5706. : true;
  5707. if (__legacyMode) {
  5708. warnOnce(getWarnMessage(I18nWarnCodes.DEPRECATE_LEGACY_MODE));
  5709. }
  5710. // prettier-ignore
  5711. const __globalInjection = isBoolean(options.globalInjection)
  5712. ? options.globalInjection
  5713. : true;
  5714. const __instances = new Map();
  5715. const [globalScope, __global] = createGlobal(options, __legacyMode);
  5716. const symbol = /* #__PURE__*/ makeSymbol('vue-i18n' );
  5717. function __getInstance(component) {
  5718. return __instances.get(component) || null;
  5719. }
  5720. function __setInstance(component, instance) {
  5721. __instances.set(component, instance);
  5722. }
  5723. function __deleteInstance(component) {
  5724. __instances.delete(component);
  5725. }
  5726. const i18n = {
  5727. // mode
  5728. get mode() {
  5729. return __legacyMode
  5730. ? 'legacy'
  5731. : 'composition';
  5732. },
  5733. // install plugin
  5734. async install(app, ...options) {
  5735. {
  5736. app.__VUE_I18N__ = i18n;
  5737. }
  5738. // setup global provider
  5739. app.__VUE_I18N_SYMBOL__ = symbol;
  5740. app.provide(app.__VUE_I18N_SYMBOL__, i18n);
  5741. // set composer & vuei18n extend hook options from plugin options
  5742. if (isPlainObject(options[0])) {
  5743. const opts = options[0];
  5744. i18n.__composerExtend =
  5745. opts.__composerExtend;
  5746. i18n.__vueI18nExtend =
  5747. opts.__vueI18nExtend;
  5748. }
  5749. // global method and properties injection for Composition API
  5750. let globalReleaseHandler = null;
  5751. if (!__legacyMode && __globalInjection) {
  5752. globalReleaseHandler = injectGlobalFields(app, i18n.global);
  5753. }
  5754. // install built-in components and directive
  5755. {
  5756. apply(app, i18n, ...options);
  5757. }
  5758. // setup mixin for Legacy API
  5759. if (__legacyMode) {
  5760. app.mixin(defineMixin(__global, __global.__composer, i18n));
  5761. }
  5762. // release global scope
  5763. const unmountApp = app.unmount;
  5764. app.unmount = () => {
  5765. globalReleaseHandler && globalReleaseHandler();
  5766. i18n.dispose();
  5767. unmountApp();
  5768. };
  5769. // setup vue-devtools plugin
  5770. {
  5771. const ret = await enableDevTools(app, i18n);
  5772. if (!ret) {
  5773. throw createI18nError(I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN);
  5774. }
  5775. const emitter = createEmitter();
  5776. if (__legacyMode) {
  5777. const _vueI18n = __global;
  5778. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  5779. }
  5780. else {
  5781. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5782. const _composer = __global;
  5783. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  5784. }
  5785. emitter.on('*', addTimelineEvent);
  5786. }
  5787. },
  5788. // global accessor
  5789. get global() {
  5790. return __global;
  5791. },
  5792. dispose() {
  5793. globalScope.stop();
  5794. },
  5795. // @internal
  5796. __instances,
  5797. // @internal
  5798. __getInstance,
  5799. // @internal
  5800. __setInstance,
  5801. // @internal
  5802. __deleteInstance
  5803. };
  5804. return i18n;
  5805. }
  5806. function useI18n(options = {}) {
  5807. const instance = vue.getCurrentInstance();
  5808. if (instance == null) {
  5809. throw createI18nError(I18nErrorCodes.MUST_BE_CALL_SETUP_TOP);
  5810. }
  5811. if (!instance.isCE &&
  5812. instance.appContext.app != null &&
  5813. !instance.appContext.app.__VUE_I18N_SYMBOL__) {
  5814. throw createI18nError(I18nErrorCodes.NOT_INSTALLED);
  5815. }
  5816. const i18n = getI18nInstance(instance);
  5817. const gl = getGlobalComposer(i18n);
  5818. const componentOptions = getComponentOptions(instance);
  5819. const scope = getScope(options, componentOptions);
  5820. if (scope === 'global') {
  5821. adjustI18nResources(gl, options, componentOptions);
  5822. return gl;
  5823. }
  5824. if (scope === 'parent') {
  5825. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5826. let composer = getComposer(i18n, instance, options.__useComponent);
  5827. if (composer == null) {
  5828. {
  5829. warn(getWarnMessage(I18nWarnCodes.NOT_FOUND_PARENT_SCOPE));
  5830. }
  5831. composer = gl;
  5832. }
  5833. return composer;
  5834. }
  5835. const i18nInternal = i18n;
  5836. let composer = i18nInternal.__getInstance(instance);
  5837. if (composer == null) {
  5838. const composerOptions = assign({}, options);
  5839. if ('__i18n' in componentOptions) {
  5840. composerOptions.__i18n = componentOptions.__i18n;
  5841. }
  5842. if (gl) {
  5843. composerOptions.__root = gl;
  5844. }
  5845. composer = createComposer(composerOptions);
  5846. if (i18nInternal.__composerExtend) {
  5847. composer[DisposeSymbol] =
  5848. i18nInternal.__composerExtend(composer);
  5849. }
  5850. setupLifeCycle(i18nInternal, instance, composer);
  5851. i18nInternal.__setInstance(instance, composer);
  5852. }
  5853. return composer;
  5854. }
  5855. function createGlobal(options, legacyMode) {
  5856. const scope = vue.effectScope();
  5857. const obj = legacyMode
  5858. ? scope.run(() => createVueI18n(options))
  5859. : scope.run(() => createComposer(options));
  5860. if (obj == null) {
  5861. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  5862. }
  5863. return [scope, obj];
  5864. }
  5865. function getI18nInstance(instance) {
  5866. const i18n = vue.inject(!instance.isCE
  5867. ? instance.appContext.app.__VUE_I18N_SYMBOL__
  5868. : I18nInjectionKey);
  5869. /* istanbul ignore if */
  5870. if (!i18n) {
  5871. throw createI18nError(!instance.isCE
  5872. ? I18nErrorCodes.UNEXPECTED_ERROR
  5873. : I18nErrorCodes.NOT_INSTALLED_WITH_PROVIDE);
  5874. }
  5875. return i18n;
  5876. }
  5877. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5878. function getScope(options, componentOptions) {
  5879. // prettier-ignore
  5880. return isEmptyObject(options)
  5881. ? ('__i18n' in componentOptions)
  5882. ? 'local'
  5883. : 'global'
  5884. : !options.useScope
  5885. ? 'local'
  5886. : options.useScope;
  5887. }
  5888. function getGlobalComposer(i18n) {
  5889. // prettier-ignore
  5890. return i18n.mode === 'composition'
  5891. ? i18n.global
  5892. : i18n.global.__composer;
  5893. }
  5894. function getComposer(i18n, target, useComponent = false) {
  5895. let composer = null;
  5896. const root = target.root;
  5897. let current = getParentComponentInstance(target, useComponent);
  5898. while (current != null) {
  5899. const i18nInternal = i18n;
  5900. if (i18n.mode === 'composition') {
  5901. composer = i18nInternal.__getInstance(current);
  5902. }
  5903. else {
  5904. {
  5905. const vueI18n = i18nInternal.__getInstance(current);
  5906. if (vueI18n != null) {
  5907. composer = vueI18n
  5908. .__composer;
  5909. if (useComponent &&
  5910. composer &&
  5911. !composer[InejctWithOptionSymbol] // eslint-disable-line @typescript-eslint/no-explicit-any
  5912. ) {
  5913. composer = null;
  5914. }
  5915. }
  5916. }
  5917. }
  5918. if (composer != null) {
  5919. break;
  5920. }
  5921. if (root === current) {
  5922. break;
  5923. }
  5924. current = current.parent;
  5925. }
  5926. return composer;
  5927. }
  5928. function getParentComponentInstance(target, useComponent = false) {
  5929. if (target == null) {
  5930. return null;
  5931. }
  5932. // if `useComponent: true` will be specified, we get lexical scope owner instance for use-case slots
  5933. return !useComponent
  5934. ? target.parent
  5935. : target.vnode.ctx || target.parent; // eslint-disable-line @typescript-eslint/no-explicit-any
  5936. }
  5937. function setupLifeCycle(i18n, target, composer) {
  5938. let emitter = null;
  5939. vue.onMounted(() => {
  5940. // inject composer instance to DOM for intlify-devtools
  5941. if (target.vnode.el) {
  5942. target.vnode.el.__VUE_I18N__ = composer;
  5943. emitter = createEmitter();
  5944. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5945. const _composer = composer;
  5946. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  5947. emitter.on('*', addTimelineEvent);
  5948. }
  5949. }, target);
  5950. vue.onUnmounted(() => {
  5951. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5952. const _composer = composer;
  5953. // remove composer instance from DOM for intlify-devtools
  5954. if (target.vnode.el &&
  5955. target.vnode.el.__VUE_I18N__) {
  5956. emitter && emitter.off('*', addTimelineEvent);
  5957. _composer[DisableEmitter] && _composer[DisableEmitter]();
  5958. delete target.vnode.el.__VUE_I18N__;
  5959. }
  5960. i18n.__deleteInstance(target);
  5961. // dispose extended resources
  5962. const dispose = _composer[DisposeSymbol];
  5963. if (dispose) {
  5964. dispose();
  5965. delete _composer[DisposeSymbol];
  5966. }
  5967. }, target);
  5968. }
  5969. const globalExportProps = [
  5970. 'locale',
  5971. 'fallbackLocale',
  5972. 'availableLocales'
  5973. ];
  5974. const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm', 'te']
  5975. ;
  5976. function injectGlobalFields(app, composer) {
  5977. const i18n = Object.create(null);
  5978. globalExportProps.forEach(prop => {
  5979. const desc = Object.getOwnPropertyDescriptor(composer, prop);
  5980. if (!desc) {
  5981. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  5982. }
  5983. const wrap = vue.isRef(desc.value) // check computed props
  5984. ? {
  5985. get() {
  5986. return desc.value.value;
  5987. },
  5988. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5989. set(val) {
  5990. desc.value.value = val;
  5991. }
  5992. }
  5993. : {
  5994. get() {
  5995. return desc.get && desc.get();
  5996. }
  5997. };
  5998. Object.defineProperty(i18n, prop, wrap);
  5999. });
  6000. app.config.globalProperties.$i18n = i18n;
  6001. globalExportMethods.forEach(method => {
  6002. const desc = Object.getOwnPropertyDescriptor(composer, method);
  6003. if (!desc || !desc.value) {
  6004. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  6005. }
  6006. Object.defineProperty(app.config.globalProperties, `$${method}`, desc);
  6007. });
  6008. const dispose = () => {
  6009. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6010. delete app.config.globalProperties.$i18n;
  6011. globalExportMethods.forEach(method => {
  6012. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6013. delete app.config.globalProperties[`$${method}`];
  6014. });
  6015. };
  6016. return dispose;
  6017. }
  6018. const DatetimeFormatImpl = /* #__PURE__*/ vue.defineComponent({
  6019. /* eslint-disable */
  6020. name: 'i18n-d',
  6021. props: assign({
  6022. value: {
  6023. type: [Number, Date],
  6024. required: true
  6025. },
  6026. format: {
  6027. type: [String, Object]
  6028. }
  6029. }, baseFormatProps),
  6030. /* eslint-enable */
  6031. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6032. setup(props, context) {
  6033. const i18n = props.i18n ||
  6034. useI18n({
  6035. useScope: props.scope,
  6036. __useComponent: true
  6037. });
  6038. return renderFormatter(props, context, DATETIME_FORMAT_OPTIONS_KEYS, (...args) =>
  6039. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6040. i18n[DatetimePartsSymbol](...args));
  6041. }
  6042. });
  6043. /**
  6044. * Datetime Format Component
  6045. *
  6046. * @remarks
  6047. * See the following items for property about details
  6048. *
  6049. * @VueI18nSee [FormattableProps](component#formattableprops)
  6050. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  6051. * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting)
  6052. *
  6053. * @VueI18nDanger
  6054. * 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)
  6055. *
  6056. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)
  6057. *
  6058. * @VueI18nComponent
  6059. */
  6060. const DatetimeFormat = DatetimeFormatImpl;
  6061. const I18nD = DatetimeFormat;
  6062. // register message compiler at vue-i18n
  6063. registerMessageCompiler(compile);
  6064. // register message resolver at vue-i18n
  6065. registerMessageResolver(resolveValue);
  6066. // register fallback locale at vue-i18n
  6067. registerLocaleFallbacker(fallbackWithLocaleChain);
  6068. // NOTE: experimental !!
  6069. {
  6070. const target = getGlobalThis();
  6071. target.__INTLIFY__ = true;
  6072. setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);
  6073. }
  6074. {
  6075. initDev();
  6076. }
  6077. exports.DatetimeFormat = DatetimeFormat;
  6078. exports.I18nD = I18nD;
  6079. exports.I18nInjectionKey = I18nInjectionKey;
  6080. exports.I18nN = I18nN;
  6081. exports.I18nT = I18nT;
  6082. exports.NumberFormat = NumberFormat;
  6083. exports.Translation = Translation;
  6084. exports.VERSION = VERSION;
  6085. exports.createI18n = createI18n;
  6086. exports.useI18n = useI18n;
  6087. exports.vTDirective = vTDirective;
  6088. return exports;
  6089. })({}, Vue);