1fea95a400490aaf8b5cc335896b1bc11c9eac9cc2305b57e779caa294456438808911679883a9fe49c96edabcb8680bb2dbb59ba4f89b343552b3bc0a8216 251 KB

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