vue-i18n.esm-browser.js 224 KB

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