ts-morph.js 888 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499
  1. 'use strict';
  2. var common = require('@ts-morph/common');
  3. var CodeBlockWriter = require('code-block-writer');
  4. function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
  5. var CodeBlockWriter__default = /*#__PURE__*/_interopDefaultCompat(CodeBlockWriter);
  6. class AdvancedIterator {
  7. #iterator;
  8. #buffer = [undefined, undefined, undefined];
  9. #bufferIndex = 0;
  10. #isDone = false;
  11. #nextCount = 0;
  12. constructor(iterator) {
  13. this.#iterator = iterator;
  14. this.#advance();
  15. }
  16. get done() {
  17. return this.#isDone;
  18. }
  19. get current() {
  20. if (this.#nextCount === 0)
  21. throw new common.errors.InvalidOperationError("Cannot get the current when the iterator has not been advanced.");
  22. return this.#buffer[this.#bufferIndex];
  23. }
  24. get previous() {
  25. if (this.#nextCount <= 1)
  26. throw new common.errors.InvalidOperationError("Cannot get the previous when the iterator has not advanced enough.");
  27. return this.#buffer[(this.#bufferIndex + this.#buffer.length - 1) % this.#buffer.length];
  28. }
  29. get peek() {
  30. if (this.#isDone)
  31. throw new common.errors.InvalidOperationError("Cannot peek at the end of the iterator.");
  32. return this.#buffer[(this.#bufferIndex + 1) % this.#buffer.length];
  33. }
  34. next() {
  35. if (this.done)
  36. throw new common.errors.InvalidOperationError("Cannot get the next when at the end of the iterator.");
  37. const next = this.#buffer[this.#getNextBufferIndex()];
  38. this.#advance();
  39. this.#nextCount++;
  40. return next;
  41. }
  42. *rest() {
  43. while (!this.done)
  44. yield this.next();
  45. }
  46. #advance() {
  47. const next = this.#iterator.next();
  48. this.#bufferIndex = this.#getNextBufferIndex();
  49. if (next.done) {
  50. this.#isDone = true;
  51. return;
  52. }
  53. this.#buffer[this.#getNextBufferIndex()] = next.value;
  54. }
  55. #getNextBufferIndex() {
  56. return (this.#bufferIndex + 1) % this.#buffer.length;
  57. }
  58. }
  59. const CharCodes = {
  60. ASTERISK: "*".charCodeAt(0),
  61. NEWLINE: "\n".charCodeAt(0),
  62. CARRIAGE_RETURN: "\r".charCodeAt(0),
  63. SPACE: " ".charCodeAt(0),
  64. TAB: "\t".charCodeAt(0),
  65. CLOSE_BRACE: "}".charCodeAt(0),
  66. };
  67. function getNodeByNameOrFindFunction(items, nameOrFindFunc) {
  68. let findFunc;
  69. if (typeof nameOrFindFunc === "string")
  70. findFunc = dec => nodeHasName(dec, nameOrFindFunc);
  71. else
  72. findFunc = nameOrFindFunc;
  73. return items.find(findFunc);
  74. }
  75. function nodeHasName(node, name) {
  76. if (node.getNameNode == null)
  77. return false;
  78. const nameNode = node.getNameNode();
  79. if (nameNode == null)
  80. return false;
  81. if (Node.isArrayBindingPattern(nameNode) || Node.isObjectBindingPattern(nameNode))
  82. return nameNode.getElements().some(element => nodeHasName(element, name));
  83. const nodeName = node.getName != null ? node.getName() : nameNode.getText();
  84. return nodeName === name;
  85. }
  86. function getNotFoundErrorMessageForNameOrFindFunction(findName, nameOrFindFunction) {
  87. if (typeof nameOrFindFunction === "string")
  88. return `Expected to find ${findName} named '${nameOrFindFunction}'.`;
  89. return `Expected to find ${findName} that matched the provided condition.`;
  90. }
  91. exports.CommentNodeKind = void 0;
  92. (function (CommentNodeKind) {
  93. CommentNodeKind[CommentNodeKind["Statement"] = 0] = "Statement";
  94. CommentNodeKind[CommentNodeKind["ClassElement"] = 1] = "ClassElement";
  95. CommentNodeKind[CommentNodeKind["TypeElement"] = 2] = "TypeElement";
  96. CommentNodeKind[CommentNodeKind["ObjectLiteralElement"] = 3] = "ObjectLiteralElement";
  97. CommentNodeKind[CommentNodeKind["EnumMember"] = 4] = "EnumMember";
  98. })(exports.CommentNodeKind || (exports.CommentNodeKind = {}));
  99. class CompilerCommentNode {
  100. #fullStart;
  101. #start;
  102. #sourceFile;
  103. constructor(fullStart, pos, end, kind, sourceFile, parent) {
  104. this.#fullStart = fullStart;
  105. this.#start = pos;
  106. this.#sourceFile = sourceFile;
  107. this.pos = pos;
  108. this.end = end;
  109. this.kind = kind;
  110. this.flags = common.ts.NodeFlags.None;
  111. this.parent = parent;
  112. }
  113. pos;
  114. end;
  115. kind;
  116. flags;
  117. modifiers;
  118. parent;
  119. getSourceFile() {
  120. return this.#sourceFile;
  121. }
  122. getChildCount(sourceFile) {
  123. return 0;
  124. }
  125. getChildAt(index, sourceFile) {
  126. return undefined;
  127. }
  128. getChildren(sourceFile) {
  129. return [];
  130. }
  131. getStart(sourceFile, includeJsDocComment) {
  132. return this.#start;
  133. }
  134. getFullStart() {
  135. return this.#fullStart;
  136. }
  137. getEnd() {
  138. return this.end;
  139. }
  140. getWidth(sourceFile) {
  141. return this.end - this.#start;
  142. }
  143. getFullWidth() {
  144. return this.end - this.#fullStart;
  145. }
  146. getLeadingTriviaWidth(sourceFile) {
  147. return this.#start - this.#fullStart;
  148. }
  149. getFullText(sourceFile) {
  150. return this.#sourceFile.text.substring(this.#fullStart, this.end);
  151. }
  152. getText(sourceFile) {
  153. return this.#sourceFile.text.substring(this.#start, this.end);
  154. }
  155. getFirstToken(sourceFile) {
  156. return undefined;
  157. }
  158. getLastToken(sourceFile) {
  159. return undefined;
  160. }
  161. forEachChild(cbNode, cbNodeArray) {
  162. return undefined;
  163. }
  164. }
  165. class CompilerCommentStatement extends CompilerCommentNode {
  166. _jsdocContainerBrand;
  167. _statementBrand;
  168. _commentKind = exports.CommentNodeKind.Statement;
  169. }
  170. class CompilerCommentClassElement extends CompilerCommentNode {
  171. _classElementBrand;
  172. _declarationBrand;
  173. _commentKind = exports.CommentNodeKind.ClassElement;
  174. }
  175. class CompilerCommentTypeElement extends CompilerCommentNode {
  176. _typeElementBrand;
  177. _declarationBrand;
  178. _commentKind = exports.CommentNodeKind.TypeElement;
  179. }
  180. class CompilerCommentObjectLiteralElement extends CompilerCommentNode {
  181. _declarationBrand;
  182. _objectLiteralBrand;
  183. declarationBrand;
  184. _commentKind = exports.CommentNodeKind.ObjectLiteralElement;
  185. }
  186. class CompilerCommentEnumMember extends CompilerCommentNode {
  187. _commentKind = exports.CommentNodeKind.EnumMember;
  188. }
  189. var CommentKind;
  190. (function (CommentKind) {
  191. CommentKind[CommentKind["SingleLine"] = 0] = "SingleLine";
  192. CommentKind[CommentKind["MultiLine"] = 1] = "MultiLine";
  193. CommentKind[CommentKind["JsDoc"] = 2] = "JsDoc";
  194. })(CommentKind || (CommentKind = {}));
  195. const childrenSaver = new WeakMap();
  196. const commentNodeParserKinds = new Set([
  197. common.SyntaxKind.SourceFile,
  198. common.SyntaxKind.Block,
  199. common.SyntaxKind.ModuleBlock,
  200. common.SyntaxKind.CaseClause,
  201. common.SyntaxKind.DefaultClause,
  202. common.SyntaxKind.ClassDeclaration,
  203. common.SyntaxKind.InterfaceDeclaration,
  204. common.SyntaxKind.EnumDeclaration,
  205. common.SyntaxKind.ClassExpression,
  206. common.SyntaxKind.TypeLiteral,
  207. common.SyntaxKind.ObjectLiteralExpression,
  208. ]);
  209. class CommentNodeParser {
  210. constructor() {
  211. }
  212. static getOrParseChildren(container, sourceFile) {
  213. if (isSyntaxList(container))
  214. container = container.parent;
  215. let children = childrenSaver.get(container);
  216. if (children == null) {
  217. children = Array.from(getNodes(container, sourceFile));
  218. childrenSaver.set(container, children);
  219. }
  220. return children;
  221. }
  222. static shouldParseChildren(container) {
  223. return commentNodeParserKinds.has(container.kind)
  224. && container.pos !== container.end;
  225. }
  226. static hasParsedChildren(container) {
  227. if (isSyntaxList(container))
  228. container = container.parent;
  229. return childrenSaver.has(container);
  230. }
  231. static isCommentStatement(node) {
  232. return node._commentKind === exports.CommentNodeKind.Statement;
  233. }
  234. static isCommentClassElement(node) {
  235. return node._commentKind === exports.CommentNodeKind.ClassElement;
  236. }
  237. static isCommentTypeElement(node) {
  238. return node._commentKind === exports.CommentNodeKind.TypeElement;
  239. }
  240. static isCommentObjectLiteralElement(node) {
  241. return node._commentKind === exports.CommentNodeKind.ObjectLiteralElement;
  242. }
  243. static isCommentEnumMember(node) {
  244. return node._commentKind === exports.CommentNodeKind.EnumMember;
  245. }
  246. static getContainerBodyPos(container, sourceFile) {
  247. if (common.ts.isSourceFile(container))
  248. return 0;
  249. if (common.ts.isClassDeclaration(container)
  250. || common.ts.isEnumDeclaration(container)
  251. || common.ts.isInterfaceDeclaration(container)
  252. || common.ts.isTypeLiteralNode(container)
  253. || common.ts.isClassExpression(container)
  254. || common.ts.isBlock(container)
  255. || common.ts.isModuleBlock(container)
  256. || common.ts.isObjectLiteralExpression(container)) {
  257. return getTokenEnd(container, common.SyntaxKind.OpenBraceToken);
  258. }
  259. if (common.ts.isCaseClause(container) || common.ts.isDefaultClause(container))
  260. return getTokenEnd(container, common.SyntaxKind.ColonToken);
  261. return common.errors.throwNotImplementedForNeverValueError(container);
  262. function getTokenEnd(node, kind) {
  263. return node.getChildren(sourceFile).find(c => c.kind === kind)?.end;
  264. }
  265. }
  266. }
  267. function* getNodes(container, sourceFile) {
  268. const sourceFileText = sourceFile.text;
  269. const childNodes = getContainerChildren();
  270. const createComment = getCreationFunction();
  271. if (childNodes.length === 0) {
  272. const bodyStartPos = CommentNodeParser.getContainerBodyPos(container, sourceFile);
  273. if (bodyStartPos != null)
  274. yield* getCommentNodes(bodyStartPos, false);
  275. }
  276. else {
  277. for (const childNode of childNodes) {
  278. yield* getCommentNodes(childNode.pos, true);
  279. yield childNode;
  280. }
  281. const lastChild = childNodes[childNodes.length - 1];
  282. yield* getCommentNodes(lastChild.end, false);
  283. }
  284. function* getCommentNodes(pos, stopAtJsDoc) {
  285. const fullStart = pos;
  286. skipTrailingLine();
  287. const leadingComments = Array.from(getLeadingComments());
  288. const maxEnd = sourceFileText.length === pos || sourceFileText[pos] === "}" ? pos : common.StringUtils.getLineStartFromPos(sourceFileText, pos);
  289. for (const leadingComment of leadingComments) {
  290. if (leadingComment.end <= maxEnd)
  291. yield leadingComment;
  292. }
  293. function skipTrailingLine() {
  294. if (pos === 0)
  295. return;
  296. let lineEnd = common.StringUtils.getLineEndFromPos(sourceFileText, pos);
  297. while (pos < lineEnd) {
  298. const commentKind = getCommentKind();
  299. if (commentKind != null) {
  300. const comment = parseForComment(commentKind);
  301. if (comment.kind === common.SyntaxKind.SingleLineCommentTrivia)
  302. return;
  303. else
  304. lineEnd = common.StringUtils.getLineEndFromPos(sourceFileText, pos);
  305. }
  306. else if (!common.StringUtils.isWhitespace(sourceFileText[pos]) && sourceFileText[pos] !== ",")
  307. return;
  308. else
  309. pos++;
  310. }
  311. while (common.StringUtils.startsWithNewLine(sourceFileText[pos]))
  312. pos++;
  313. }
  314. function* getLeadingComments() {
  315. while (pos < sourceFileText.length) {
  316. const commentKind = getCommentKind();
  317. if (commentKind != null) {
  318. const isJsDoc = commentKind === CommentKind.JsDoc;
  319. if (isJsDoc && stopAtJsDoc)
  320. return;
  321. else
  322. yield parseForComment(commentKind);
  323. skipTrailingLine();
  324. }
  325. else if (!common.StringUtils.isWhitespace(sourceFileText[pos]))
  326. return;
  327. else
  328. pos++;
  329. }
  330. }
  331. function parseForComment(commentKind) {
  332. if (commentKind === CommentKind.SingleLine)
  333. return parseSingleLineComment();
  334. const isJsDoc = commentKind === CommentKind.JsDoc;
  335. return parseMultiLineComment(isJsDoc);
  336. }
  337. function getCommentKind() {
  338. const currentChar = sourceFileText[pos];
  339. if (currentChar !== "/")
  340. return undefined;
  341. const nextChar = sourceFileText[pos + 1];
  342. if (nextChar === "/")
  343. return CommentKind.SingleLine;
  344. if (nextChar !== "*")
  345. return undefined;
  346. const nextNextChar = sourceFileText[pos + 2];
  347. return nextNextChar === "*" ? CommentKind.JsDoc : CommentKind.MultiLine;
  348. }
  349. function parseSingleLineComment() {
  350. const start = pos;
  351. skipSingleLineComment();
  352. const end = pos;
  353. return createComment(fullStart, start, end, common.SyntaxKind.SingleLineCommentTrivia);
  354. }
  355. function skipSingleLineComment() {
  356. pos += 2;
  357. while (pos < sourceFileText.length && sourceFileText[pos] !== "\n" && sourceFileText[pos] !== "\r")
  358. pos++;
  359. }
  360. function parseMultiLineComment(isJsDoc) {
  361. const start = pos;
  362. skipSlashStarComment(isJsDoc);
  363. const end = pos;
  364. return createComment(fullStart, start, end, common.SyntaxKind.MultiLineCommentTrivia);
  365. }
  366. function skipSlashStarComment(isJsDoc) {
  367. pos += isJsDoc ? 3 : 2;
  368. while (pos < sourceFileText.length) {
  369. if (sourceFileText[pos] === "*" && sourceFileText[pos + 1] === "/") {
  370. pos += 2;
  371. break;
  372. }
  373. pos++;
  374. }
  375. }
  376. }
  377. function getContainerChildren() {
  378. if (common.ts.isSourceFile(container) || common.ts.isBlock(container) || common.ts.isModuleBlock(container) || common.ts.isCaseClause(container) || common.ts.isDefaultClause(container))
  379. return container.statements;
  380. if (common.ts.isClassDeclaration(container)
  381. || common.ts.isClassExpression(container)
  382. || common.ts.isEnumDeclaration(container)
  383. || common.ts.isInterfaceDeclaration(container)
  384. || common.ts.isTypeLiteralNode(container)
  385. || common.ts.isClassExpression(container)) {
  386. return container.members;
  387. }
  388. if (common.ts.isObjectLiteralExpression(container))
  389. return container.properties;
  390. return common.errors.throwNotImplementedForNeverValueError(container);
  391. }
  392. function getCreationFunction() {
  393. const ctor = getCtor();
  394. return (fullStart, pos, end, kind) => new ctor(fullStart, pos, end, kind, sourceFile, container);
  395. function getCtor() {
  396. if (isStatementContainerNode(container))
  397. return CompilerCommentStatement;
  398. if (common.ts.isClassLike(container))
  399. return CompilerCommentClassElement;
  400. if (common.ts.isInterfaceDeclaration(container) || common.ts.isTypeLiteralNode(container))
  401. return CompilerCommentTypeElement;
  402. if (common.ts.isObjectLiteralExpression(container))
  403. return CompilerCommentObjectLiteralElement;
  404. if (common.ts.isEnumDeclaration(container))
  405. return CompilerCommentEnumMember;
  406. throw new common.errors.NotImplementedError(`Not implemented comment node container type: ${common.getSyntaxKindName(container.kind)}`);
  407. }
  408. }
  409. }
  410. function isSyntaxList(node) {
  411. return node.kind === common.SyntaxKind.SyntaxList;
  412. }
  413. function isStatementContainerNode(node) {
  414. return getStatementContainerNode() != null;
  415. function getStatementContainerNode() {
  416. const container = node;
  417. if (common.ts.isSourceFile(container)
  418. || common.ts.isBlock(container)
  419. || common.ts.isModuleBlock(container)
  420. || common.ts.isCaseClause(container)
  421. || common.ts.isDefaultClause(container)) {
  422. return container;
  423. }
  424. return undefined;
  425. }
  426. }
  427. const forEachChildSaver = new WeakMap();
  428. const getChildrenSaver = new WeakMap();
  429. class ExtendedParser {
  430. static getContainerArray(container, sourceFile) {
  431. return CommentNodeParser.getOrParseChildren(container, sourceFile);
  432. }
  433. static hasParsedTokens(node) {
  434. return getChildrenSaver.has(node) || node.kind == common.SyntaxKind.SyntaxList;
  435. }
  436. static getCompilerChildrenFast(node, sourceFile) {
  437. if (ExtendedParser.hasParsedTokens(node))
  438. return ExtendedParser.getCompilerChildren(node, sourceFile);
  439. return ExtendedParser.getCompilerForEachChildren(node, sourceFile);
  440. }
  441. static getCompilerForEachChildren(node, sourceFile) {
  442. if (CommentNodeParser.shouldParseChildren(node)) {
  443. let result = forEachChildSaver.get(node);
  444. if (result == null) {
  445. result = getForEachChildren();
  446. mergeInComments(result, CommentNodeParser.getOrParseChildren(node, sourceFile));
  447. forEachChildSaver.set(node, result);
  448. }
  449. return result;
  450. }
  451. return getForEachChildren();
  452. function getForEachChildren() {
  453. const children = [];
  454. node.forEachChild(child => {
  455. children.push(child);
  456. });
  457. return children;
  458. }
  459. }
  460. static getCompilerChildren(node, sourceFile) {
  461. let result = getChildrenSaver.get(node);
  462. if (result == null) {
  463. if (isStatementMemberOrPropertyHoldingSyntaxList()) {
  464. const newArray = [...node.getChildren(sourceFile)];
  465. mergeInComments(newArray, CommentNodeParser.getOrParseChildren(node, sourceFile));
  466. result = newArray;
  467. }
  468. else {
  469. result = node.getChildren(sourceFile);
  470. }
  471. getChildrenSaver.set(node, result);
  472. }
  473. return result;
  474. function isStatementMemberOrPropertyHoldingSyntaxList() {
  475. if (node.kind !== common.ts.SyntaxKind.SyntaxList)
  476. return false;
  477. const parent = node.parent;
  478. if (!CommentNodeParser.shouldParseChildren(parent))
  479. return false;
  480. return CommentNodeParser.getContainerBodyPos(parent, sourceFile) === node.pos;
  481. }
  482. }
  483. }
  484. function mergeInComments(nodes, otherNodes) {
  485. let currentIndex = 0;
  486. for (const child of otherNodes) {
  487. if (child.kind !== common.SyntaxKind.SingleLineCommentTrivia && child.kind !== common.SyntaxKind.MultiLineCommentTrivia)
  488. continue;
  489. while (currentIndex < nodes.length && nodes[currentIndex].end < child.end)
  490. currentIndex++;
  491. nodes.splice(currentIndex, 0, child);
  492. currentIndex++;
  493. }
  494. }
  495. function isComment(node) {
  496. return node.kind === common.ts.SyntaxKind.SingleLineCommentTrivia
  497. || node.kind === common.ts.SyntaxKind.MultiLineCommentTrivia;
  498. }
  499. function getParentSyntaxList(node, sourceFile) {
  500. if (node.kind === common.SyntaxKind.EndOfFileToken)
  501. return undefined;
  502. const parent = node.parent;
  503. if (parent == null)
  504. return undefined;
  505. const { pos, end } = node;
  506. for (const child of ExtendedParser.getCompilerChildren(parent, sourceFile)) {
  507. if (child.pos > end || child === node)
  508. return undefined;
  509. if (child.kind === common.SyntaxKind.SyntaxList && child.pos <= pos && child.end >= end)
  510. return child;
  511. }
  512. return undefined;
  513. }
  514. function getSymbolByNameOrFindFunction(items, nameOrFindFunc) {
  515. let findFunc;
  516. if (typeof nameOrFindFunc === "string")
  517. findFunc = dec => dec.getName() === nameOrFindFunc;
  518. else
  519. findFunc = nameOrFindFunc;
  520. return items.find(findFunc);
  521. }
  522. function isNodeAmbientOrInAmbientContext(node) {
  523. if (checkNodeIsAmbient(node) || node._sourceFile.isDeclarationFile())
  524. return true;
  525. for (const ancestor of node._getAncestorsIterator(false)) {
  526. if (checkNodeIsAmbient(ancestor))
  527. return true;
  528. }
  529. return false;
  530. }
  531. function checkNodeIsAmbient(node) {
  532. const isThisAmbient = (node.getCombinedModifierFlags() & common.ts.ModifierFlags.Ambient) === common.ts.ModifierFlags.Ambient;
  533. return isThisAmbient || Node.isInterfaceDeclaration(node) || Node.isTypeAliasDeclaration(node);
  534. }
  535. function isStringKind(kind) {
  536. switch (kind) {
  537. case common.SyntaxKind.StringLiteral:
  538. case common.SyntaxKind.NoSubstitutionTemplateLiteral:
  539. case common.SyntaxKind.TemplateHead:
  540. case common.SyntaxKind.TemplateMiddle:
  541. case common.SyntaxKind.TemplateTail:
  542. return true;
  543. default:
  544. return false;
  545. }
  546. }
  547. class ModuleUtils {
  548. constructor() {
  549. }
  550. static isModuleSpecifierRelative(text) {
  551. return text.startsWith("./")
  552. || text.startsWith("../");
  553. }
  554. static getReferencedSourceFileFromSymbol(symbol) {
  555. const declarations = symbol.getDeclarations();
  556. if (declarations.length === 0 || declarations[0].getKind() !== common.SyntaxKind.SourceFile)
  557. return undefined;
  558. return declarations[0];
  559. }
  560. }
  561. function printNode(node, sourceFileOrOptions, secondOverloadOptions) {
  562. const isFirstOverload = sourceFileOrOptions == null || sourceFileOrOptions.kind !== common.SyntaxKind.SourceFile;
  563. const options = getOptions();
  564. const sourceFile = getSourceFile();
  565. const printer = common.ts.createPrinter({
  566. newLine: options.newLineKind ?? common.NewLineKind.LineFeed,
  567. removeComments: options.removeComments || false,
  568. });
  569. if (sourceFile == null)
  570. return printer.printFile(node);
  571. else
  572. return printer.printNode(options.emitHint ?? common.EmitHint.Unspecified, node, sourceFile);
  573. function getSourceFile() {
  574. if (isFirstOverload) {
  575. if (node.kind === common.SyntaxKind.SourceFile)
  576. return undefined;
  577. const topParent = getNodeSourceFile();
  578. if (topParent == null) {
  579. const scriptKind = getScriptKind();
  580. return common.ts.createSourceFile(`print.${getFileExt(scriptKind)}`, "", common.ScriptTarget.Latest, false, scriptKind);
  581. }
  582. return topParent;
  583. }
  584. return sourceFileOrOptions;
  585. function getScriptKind() {
  586. return options.scriptKind ?? common.ScriptKind.TSX;
  587. }
  588. function getFileExt(scriptKind) {
  589. if (scriptKind === common.ScriptKind.JSX || scriptKind === common.ScriptKind.TSX)
  590. return "tsx";
  591. return "ts";
  592. }
  593. }
  594. function getNodeSourceFile() {
  595. let topNode = node.parent;
  596. while (topNode != null && topNode.parent != null)
  597. topNode = topNode.parent;
  598. return topNode;
  599. }
  600. function getOptions() {
  601. return (isFirstOverload ? sourceFileOrOptions : secondOverloadOptions) || {};
  602. }
  603. }
  604. exports.IndentationText = void 0;
  605. (function (IndentationText) {
  606. IndentationText["TwoSpaces"] = " ";
  607. IndentationText["FourSpaces"] = " ";
  608. IndentationText["EightSpaces"] = " ";
  609. IndentationText["Tab"] = "\t";
  610. })(exports.IndentationText || (exports.IndentationText = {}));
  611. class ManipulationSettingsContainer extends common.SettingsContainer {
  612. #editorSettings;
  613. #formatCodeSettings;
  614. #userPreferences;
  615. constructor() {
  616. super({
  617. indentationText: exports.IndentationText.FourSpaces,
  618. newLineKind: common.NewLineKind.LineFeed,
  619. quoteKind: exports.QuoteKind.Double,
  620. insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true,
  621. usePrefixAndSuffixTextForRename: false,
  622. useTrailingCommas: false,
  623. });
  624. }
  625. getEditorSettings() {
  626. if (this.#editorSettings == null) {
  627. this.#editorSettings = {};
  628. fillDefaultEditorSettings(this.#editorSettings, this);
  629. }
  630. return { ...this.#editorSettings };
  631. }
  632. getFormatCodeSettings() {
  633. if (this.#formatCodeSettings == null) {
  634. this.#formatCodeSettings = {
  635. ...this.getEditorSettings(),
  636. insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: this._settings.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces,
  637. };
  638. }
  639. return { ...this.#formatCodeSettings };
  640. }
  641. getUserPreferences() {
  642. if (this.#userPreferences == null) {
  643. this.#userPreferences = {
  644. quotePreference: this.getQuoteKind() === exports.QuoteKind.Double ? "double" : "single",
  645. providePrefixAndSuffixTextForRename: this.getUsePrefixAndSuffixTextForRename(),
  646. };
  647. }
  648. return { ...this.#userPreferences };
  649. }
  650. getQuoteKind() {
  651. return this._settings.quoteKind;
  652. }
  653. getNewLineKind() {
  654. return this._settings.newLineKind;
  655. }
  656. getNewLineKindAsString() {
  657. return newLineKindToString(this.getNewLineKind());
  658. }
  659. getIndentationText() {
  660. return this._settings.indentationText;
  661. }
  662. getUsePrefixAndSuffixTextForRename() {
  663. return this._settings.usePrefixAndSuffixTextForRename;
  664. }
  665. getUseTrailingCommas() {
  666. return this._settings.useTrailingCommas;
  667. }
  668. set(settings) {
  669. super.set(settings);
  670. this.#editorSettings = undefined;
  671. this.#formatCodeSettings = undefined;
  672. this.#userPreferences = undefined;
  673. }
  674. _getIndentSizeInSpaces() {
  675. const indentationText = this.getIndentationText();
  676. switch (indentationText) {
  677. case exports.IndentationText.EightSpaces:
  678. return 8;
  679. case exports.IndentationText.FourSpaces:
  680. return 4;
  681. case exports.IndentationText.TwoSpaces:
  682. return 2;
  683. case exports.IndentationText.Tab:
  684. return 4;
  685. default:
  686. return common.errors.throwNotImplementedForNeverValueError(indentationText);
  687. }
  688. }
  689. }
  690. function setValueIfUndefined(obj, propertyName, defaultValue) {
  691. if (typeof obj[propertyName] === "undefined")
  692. obj[propertyName] = defaultValue;
  693. }
  694. function fillDefaultEditorSettings(settings, manipulationSettings) {
  695. setValueIfUndefined(settings, "convertTabsToSpaces", manipulationSettings.getIndentationText() !== exports.IndentationText.Tab);
  696. setValueIfUndefined(settings, "newLineCharacter", manipulationSettings.getNewLineKindAsString());
  697. setValueIfUndefined(settings, "indentStyle", common.ts.IndentStyle.Smart);
  698. setValueIfUndefined(settings, "indentSize", manipulationSettings.getIndentationText().length);
  699. setValueIfUndefined(settings, "tabSize", manipulationSettings.getIndentationText().length);
  700. }
  701. function fillDefaultFormatCodeSettings(settings, manipulationSettings) {
  702. fillDefaultEditorSettings(settings, manipulationSettings);
  703. setValueIfUndefined(settings, "insertSpaceAfterCommaDelimiter", true);
  704. setValueIfUndefined(settings, "insertSpaceAfterConstructor", false);
  705. setValueIfUndefined(settings, "insertSpaceAfterSemicolonInForStatements", true);
  706. setValueIfUndefined(settings, "insertSpaceAfterKeywordsInControlFlowStatements", true);
  707. setValueIfUndefined(settings, "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces", true);
  708. setValueIfUndefined(settings, "insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets", false);
  709. setValueIfUndefined(settings, "insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces", false);
  710. setValueIfUndefined(settings, "insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces", false);
  711. setValueIfUndefined(settings, "insertSpaceBeforeFunctionParenthesis", false);
  712. setValueIfUndefined(settings, "insertSpaceBeforeAndAfterBinaryOperators", true);
  713. setValueIfUndefined(settings, "placeOpenBraceOnNewLineForFunctions", false);
  714. setValueIfUndefined(settings, "placeOpenBraceOnNewLineForControlBlocks", false);
  715. setValueIfUndefined(settings, "ensureNewLineAtEndOfFile", true);
  716. }
  717. function getTextFromStringOrWriter(writer, textOrWriterFunction) {
  718. printTextFromStringOrWriter(writer, textOrWriterFunction);
  719. return writer.toString();
  720. }
  721. function printTextFromStringOrWriter(writer, textOrWriterFunction) {
  722. if (typeof textOrWriterFunction === "string")
  723. writer.write(textOrWriterFunction);
  724. else if (textOrWriterFunction instanceof Function)
  725. textOrWriterFunction(writer);
  726. else {
  727. for (let i = 0; i < textOrWriterFunction.length; i++) {
  728. if (i > 0)
  729. writer.newLineIfLastNot();
  730. printTextFromStringOrWriter(writer, textOrWriterFunction[i]);
  731. }
  732. }
  733. }
  734. class EnableableLogger {
  735. #enabled = false;
  736. setEnabled(enabled) {
  737. this.#enabled = enabled;
  738. }
  739. log(text) {
  740. if (this.#enabled)
  741. this.logInternal(text);
  742. }
  743. warn(text) {
  744. if (this.#enabled)
  745. this.warnInternal(text);
  746. }
  747. }
  748. class ConsoleLogger extends EnableableLogger {
  749. logInternal(text) {
  750. console.log(text);
  751. }
  752. warnInternal(text) {
  753. console.warn(text);
  754. }
  755. }
  756. const reg = /^[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc0-9\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19d9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]*$/;
  757. const bannedNames = new Set([
  758. "do", "if", "in", "for", "let", "new", "try", "var", "case", "else", "enum", "eval", "false", "null",
  759. "this", "true", "void", "with", "break", "catch", "class", "const", "super", "throw", "while", "yield",
  760. "delete", "export", "import", "public", "return", "static", "switch", "typeof", "default", "extends",
  761. "finally", "package", "private", "continue", "debugger", "function", "arguments", "interface", "protected",
  762. "implements", "instanceof"
  763. ]);
  764. function isValidVariableName(variableName) {
  765. if (bannedNames.has(variableName))
  766. return false;
  767. if (isAlphaNumeric(variableName))
  768. return true;
  769. return reg.test(variableName);
  770. }
  771. function isAlphaNumeric(variableName) {
  772. for (let i = 0; i < variableName.length; i++) {
  773. const ch = variableName.charCodeAt(i);
  774. if (!(ch >= 48 && ch <= 57)
  775. && !(ch >= 65 && ch <= 90)
  776. && !(ch >= 97 && ch <= 122)) {
  777. return false;
  778. }
  779. }
  780. return true;
  781. }
  782. function newLineKindToString(kind) {
  783. switch (kind) {
  784. case common.NewLineKind.CarriageReturnLineFeed:
  785. return "\r\n";
  786. case common.NewLineKind.LineFeed:
  787. return "\n";
  788. default:
  789. throw new common.errors.NotImplementedError(`Not implemented newline kind: ${kind}`);
  790. }
  791. }
  792. class LazyReferenceCoordinator {
  793. #dirtySourceFiles = new Set();
  794. constructor(factory) {
  795. const onSourceFileModified = (sourceFile) => {
  796. if (!sourceFile.wasForgotten())
  797. this.#dirtySourceFiles.add(sourceFile);
  798. };
  799. factory.onSourceFileAdded(sourceFile => {
  800. this.#dirtySourceFiles.add(sourceFile);
  801. sourceFile.onModified(onSourceFileModified);
  802. });
  803. factory.onSourceFileRemoved(sourceFile => {
  804. sourceFile._referenceContainer.clear();
  805. this.#dirtySourceFiles.delete(sourceFile);
  806. sourceFile.onModified(onSourceFileModified, false);
  807. });
  808. }
  809. refreshDirtySourceFiles() {
  810. for (const sourceFile of this.#dirtySourceFiles.values())
  811. sourceFile._referenceContainer.refresh();
  812. this.clearDirtySourceFiles();
  813. }
  814. refreshSourceFileIfDirty(sourceFile) {
  815. if (!this.#dirtySourceFiles.has(sourceFile))
  816. return;
  817. sourceFile._referenceContainer.refresh();
  818. this.clearDirtyForSourceFile(sourceFile);
  819. }
  820. addDirtySourceFile(sourceFile) {
  821. this.#dirtySourceFiles.add(sourceFile);
  822. }
  823. clearDirtySourceFiles() {
  824. this.#dirtySourceFiles.clear();
  825. }
  826. clearDirtyForSourceFile(sourceFile) {
  827. this.#dirtySourceFiles.delete(sourceFile);
  828. }
  829. }
  830. class SourceFileReferenceContainer {
  831. #sourceFile;
  832. #nodesInThis = new common.KeyValueCache();
  833. #nodesInOther = new common.KeyValueCache();
  834. #unresolvedLiterals = [];
  835. constructor(sourceFile) {
  836. this.#sourceFile = sourceFile;
  837. }
  838. getDependentSourceFiles() {
  839. this.#sourceFile._context.lazyReferenceCoordinator.refreshDirtySourceFiles();
  840. const hashSet = new Set();
  841. for (const nodeInOther of this.#nodesInOther.getKeys())
  842. hashSet.add(nodeInOther._sourceFile);
  843. return hashSet.values();
  844. }
  845. getLiteralsReferencingOtherSourceFilesEntries() {
  846. this.#sourceFile._context.lazyReferenceCoordinator.refreshSourceFileIfDirty(this.#sourceFile);
  847. return this.#nodesInThis.getEntries();
  848. }
  849. getReferencingLiteralsInOtherSourceFiles() {
  850. this.#sourceFile._context.lazyReferenceCoordinator.refreshDirtySourceFiles();
  851. return this.#nodesInOther.getKeys();
  852. }
  853. refresh() {
  854. if (this.#unresolvedLiterals.length > 0)
  855. this.#sourceFile._context.compilerFactory.onSourceFileAdded(this.#resolveUnresolved, false);
  856. this.clear();
  857. this.#populateReferences();
  858. if (this.#unresolvedLiterals.length > 0)
  859. this.#sourceFile._context.compilerFactory.onSourceFileAdded(this.#resolveUnresolved);
  860. }
  861. clear() {
  862. this.#unresolvedLiterals.length = 0;
  863. for (const [node, sourceFile] of this.#nodesInThis.getEntries()) {
  864. this.#nodesInThis.removeByKey(node);
  865. sourceFile._referenceContainer.#nodesInOther.removeByKey(node);
  866. }
  867. }
  868. #resolveUnresolved = () => {
  869. for (let i = this.#unresolvedLiterals.length - 1; i >= 0; i--) {
  870. const literal = this.#unresolvedLiterals[i];
  871. const sourceFile = this.#getSourceFileForLiteral(literal);
  872. if (sourceFile != null) {
  873. this.#unresolvedLiterals.splice(i, 1);
  874. this.#addNodeInThis(literal, sourceFile);
  875. }
  876. }
  877. if (this.#unresolvedLiterals.length === 0)
  878. this.#sourceFile._context.compilerFactory.onSourceFileAdded(this.#resolveUnresolved, false);
  879. };
  880. #populateReferences() {
  881. this.#sourceFile._context.compilerFactory.forgetNodesCreatedInBlock(remember => {
  882. for (const literal of this.#sourceFile.getImportStringLiterals()) {
  883. const sourceFile = this.#getSourceFileForLiteral(literal);
  884. remember(literal);
  885. if (sourceFile == null)
  886. this.#unresolvedLiterals.push(literal);
  887. else
  888. this.#addNodeInThis(literal, sourceFile);
  889. }
  890. });
  891. }
  892. #getSourceFileForLiteral(literal) {
  893. const parent = literal.getParentOrThrow();
  894. const grandParent = parent.getParent();
  895. if (Node.isImportDeclaration(parent) || Node.isExportDeclaration(parent))
  896. return parent.getModuleSpecifierSourceFile();
  897. else if (grandParent != null && Node.isImportEqualsDeclaration(grandParent))
  898. return grandParent.getExternalModuleReferenceSourceFile();
  899. else if (grandParent != null && Node.isImportTypeNode(grandParent)) {
  900. const importTypeSymbol = grandParent.getSymbol();
  901. if (importTypeSymbol != null)
  902. return ModuleUtils.getReferencedSourceFileFromSymbol(importTypeSymbol);
  903. }
  904. else if (Node.isCallExpression(parent)) {
  905. const literalSymbol = literal.getSymbol();
  906. if (literalSymbol != null)
  907. return ModuleUtils.getReferencedSourceFileFromSymbol(literalSymbol);
  908. }
  909. else {
  910. this.#sourceFile._context.logger.warn(`Unknown import string literal parent: ${parent.getKindName()}`);
  911. }
  912. return undefined;
  913. }
  914. #addNodeInThis(literal, sourceFile) {
  915. this.#nodesInThis.set(literal, sourceFile);
  916. sourceFile._referenceContainer.#nodesInOther.set(literal, sourceFile);
  917. }
  918. }
  919. function getCompilerOptionsFromTsConfig(filePath, options = {}) {
  920. const result = common.getCompilerOptionsFromTsConfig(filePath, options);
  921. return {
  922. options: result.options,
  923. errors: result.errors.map(error => new Diagnostic(undefined, error)),
  924. };
  925. }
  926. common.ts.version.split(".").map(v => parseInt(v, 10));
  927. class WriterUtils {
  928. constructor() {
  929. }
  930. static getLastCharactersToPos(writer, pos) {
  931. const writerLength = writer.getLength();
  932. const charCount = writerLength - pos;
  933. const chars = new Array(charCount);
  934. writer.iterateLastChars((char, i) => {
  935. const insertPos = i - pos;
  936. if (insertPos < 0)
  937. return true;
  938. chars[insertPos] = char;
  939. return undefined;
  940. });
  941. return chars.join("");
  942. }
  943. }
  944. function callBaseGetStructure(basePrototype, node, structure) {
  945. let newStructure;
  946. if (basePrototype.getStructure != null)
  947. newStructure = basePrototype.getStructure.call(node);
  948. else
  949. newStructure = {};
  950. if (structure != null)
  951. Object.assign(newStructure, structure);
  952. return newStructure;
  953. }
  954. function callBaseSet(basePrototype, node, structure) {
  955. if (basePrototype.set != null)
  956. basePrototype.set.call(node, structure);
  957. }
  958. function AmbientableNode(Base) {
  959. return class extends Base {
  960. hasDeclareKeyword() {
  961. return this.getDeclareKeyword() != null;
  962. }
  963. getDeclareKeywordOrThrow(message) {
  964. return common.errors.throwIfNullOrUndefined(this.getDeclareKeyword(), message ?? "Expected to find a declare keyword.", this);
  965. }
  966. getDeclareKeyword() {
  967. return this.getFirstModifierByKind(common.SyntaxKind.DeclareKeyword);
  968. }
  969. isAmbient() {
  970. return isNodeAmbientOrInAmbientContext(this);
  971. }
  972. setHasDeclareKeyword(value) {
  973. this.toggleModifier("declare", value);
  974. return this;
  975. }
  976. set(structure) {
  977. callBaseSet(Base.prototype, this, structure);
  978. if (structure.hasDeclareKeyword != null)
  979. this.setHasDeclareKeyword(structure.hasDeclareKeyword);
  980. return this;
  981. }
  982. getStructure() {
  983. return callBaseGetStructure(Base.prototype, this, {
  984. hasDeclareKeyword: this.hasDeclareKeyword(),
  985. });
  986. }
  987. };
  988. }
  989. var FormattingKind;
  990. (function (FormattingKind) {
  991. FormattingKind[FormattingKind["Newline"] = 0] = "Newline";
  992. FormattingKind[FormattingKind["Blankline"] = 1] = "Blankline";
  993. FormattingKind[FormattingKind["Space"] = 2] = "Space";
  994. FormattingKind[FormattingKind["None"] = 3] = "None";
  995. })(FormattingKind || (FormattingKind = {}));
  996. function getClassMemberFormatting(parent, member) {
  997. if (Node.isAmbientable(parent) && parent.isAmbient())
  998. return FormattingKind.Newline;
  999. if (hasBody$1(member))
  1000. return FormattingKind.Blankline;
  1001. return FormattingKind.Newline;
  1002. }
  1003. function hasBody$1(node) {
  1004. if (Node.isBodyable(node) && node.getBody() != null)
  1005. return true;
  1006. if (Node.isBodied(node))
  1007. return true;
  1008. return false;
  1009. }
  1010. function getFormattingKindText(formattingKind, opts) {
  1011. switch (formattingKind) {
  1012. case FormattingKind.Space:
  1013. return " ";
  1014. case FormattingKind.Newline:
  1015. return opts.newLineKind;
  1016. case FormattingKind.Blankline:
  1017. return opts.newLineKind + opts.newLineKind;
  1018. case FormattingKind.None:
  1019. return "";
  1020. default:
  1021. throw new common.errors.NotImplementedError(`Not implemented formatting kind: ${formattingKind}`);
  1022. }
  1023. }
  1024. function getInterfaceMemberFormatting(parent, member) {
  1025. return FormattingKind.Newline;
  1026. }
  1027. function hasBody(node) {
  1028. if (Node.isBodyable(node) && node.hasBody())
  1029. return true;
  1030. if (Node.isBodied(node))
  1031. return true;
  1032. return Node.isInterfaceDeclaration(node) || Node.isClassDeclaration(node) || Node.isEnumDeclaration(node);
  1033. }
  1034. function getStatementedNodeChildFormatting(parent, member) {
  1035. if (hasBody(member))
  1036. return FormattingKind.Blankline;
  1037. return FormattingKind.Newline;
  1038. }
  1039. function getClausedNodeChildFormatting(parent, member) {
  1040. return FormattingKind.Newline;
  1041. }
  1042. function getGeneralFormatting(parent, child) {
  1043. if (Node.isClassDeclaration(parent))
  1044. return getClassMemberFormatting(parent, child);
  1045. if (Node.isInterfaceDeclaration(parent))
  1046. return getInterfaceMemberFormatting();
  1047. return getStatementedNodeChildFormatting(parent, child);
  1048. }
  1049. function getTextFromTextChanges(sourceFile, textChanges) {
  1050. const text = sourceFile.getFullText();
  1051. const editResult = [];
  1052. let start = 0;
  1053. for (const { edit } of getSortedTextChanges()) {
  1054. const span = edit.getSpan();
  1055. const beforeEdit = text.slice(start, span.getStart());
  1056. start = span.getEnd();
  1057. editResult.push(beforeEdit);
  1058. editResult.push(edit.getNewText());
  1059. }
  1060. editResult.push(text.slice(start));
  1061. return editResult.join("");
  1062. function getSortedTextChanges() {
  1063. return textChanges.map((edit, index) => ({ edit: toWrappedTextChange(edit), index })).sort((a, b) => {
  1064. const aStart = a.edit.getSpan().getStart();
  1065. const bStart = b.edit.getSpan().getStart();
  1066. const difference = aStart - bStart;
  1067. if (difference === 0)
  1068. return a.index < b.index ? -1 : 1;
  1069. return difference < 0 ? -1 : 1;
  1070. });
  1071. }
  1072. function toWrappedTextChange(change) {
  1073. if (change instanceof TextChange)
  1074. return change;
  1075. else
  1076. return new TextChange(change);
  1077. }
  1078. }
  1079. function getNewInsertCode(opts) {
  1080. const { structures, newCodes, parent, getSeparator, previousFormattingKind, nextFormattingKind } = opts;
  1081. const indentationText = opts.indentationText ?? parent.getChildIndentationText();
  1082. const newLineKind = parent._context.manipulationSettings.getNewLineKindAsString();
  1083. return getFormattingKindTextWithIndent(previousFormattingKind) + getChildCode() + getFormattingKindTextWithIndent(nextFormattingKind);
  1084. function getChildCode() {
  1085. let code = newCodes[0];
  1086. for (let i = 1; i < newCodes.length; i++) {
  1087. const formattingKind = getSeparator(structures[i - 1], structures[i]);
  1088. code += getFormattingKindTextWithIndent(formattingKind);
  1089. code += newCodes[i];
  1090. }
  1091. return code;
  1092. }
  1093. function getFormattingKindTextWithIndent(formattingKind) {
  1094. let code = getFormattingKindText(formattingKind, { newLineKind });
  1095. if (formattingKind === FormattingKind.Newline || formattingKind === FormattingKind.Blankline)
  1096. code += indentationText;
  1097. return code;
  1098. }
  1099. }
  1100. const scanner = common.ts.createScanner(common.ts.ScriptTarget.Latest, true);
  1101. function appendCommaToText(text) {
  1102. const pos = getAppendCommaPos(text);
  1103. if (pos === -1)
  1104. return text;
  1105. return text.substring(0, pos) + "," + text.substring(pos);
  1106. }
  1107. function getAppendCommaPos(text) {
  1108. scanner.setText(text);
  1109. try {
  1110. if (scanner.scan() === common.ts.SyntaxKind.EndOfFileToken)
  1111. return -1;
  1112. while (scanner.scan() !== common.ts.SyntaxKind.EndOfFileToken) {
  1113. }
  1114. const pos = scanner.getStartPos();
  1115. return text[pos - 1] === "," ? -1 : pos;
  1116. }
  1117. finally {
  1118. scanner.setText(undefined);
  1119. }
  1120. }
  1121. function getEndIndexFromArray(array) {
  1122. return array?.length ?? 0;
  1123. }
  1124. function getNextMatchingPos(text, pos, condition) {
  1125. while (pos < text.length) {
  1126. const charCode = text.charCodeAt(pos);
  1127. if (!condition(charCode))
  1128. pos++;
  1129. else
  1130. break;
  1131. }
  1132. return pos;
  1133. }
  1134. function getPreviousMatchingPos(text, pos, condition) {
  1135. while (pos > 0) {
  1136. const charCode = text.charCodeAt(pos - 1);
  1137. if (!condition(charCode))
  1138. pos--;
  1139. else
  1140. break;
  1141. }
  1142. return pos;
  1143. }
  1144. function getNextNonWhitespacePos(text, pos) {
  1145. return getNextMatchingPos(text, pos, isNotWhitespace);
  1146. }
  1147. function getPreviousNonWhitespacePos(text, pos) {
  1148. return getPreviousMatchingPos(text, pos, isNotWhitespace);
  1149. }
  1150. function isNotWhitespace(charCode) {
  1151. return !common.StringUtils.isWhitespaceCharCode(charCode);
  1152. }
  1153. function getPosAtEndOfPreviousLine(fullText, pos) {
  1154. while (pos > 0) {
  1155. pos--;
  1156. if (fullText[pos] === "\n") {
  1157. if (fullText[pos - 1] === "\r")
  1158. return pos - 1;
  1159. return pos;
  1160. }
  1161. }
  1162. return pos;
  1163. }
  1164. function getPosAtNextNonBlankLine(text, pos) {
  1165. let newPos = pos;
  1166. for (let i = pos; i < text.length; i++) {
  1167. if (text[i] === " " || text[i] === "\t")
  1168. continue;
  1169. if (text[i] === "\r" && text[i + 1] === "\n" || text[i] === "\n") {
  1170. newPos = i + 1;
  1171. if (text[i] === "\r") {
  1172. i++;
  1173. newPos++;
  1174. }
  1175. continue;
  1176. }
  1177. return newPos;
  1178. }
  1179. return newPos;
  1180. }
  1181. function getPosAtStartOfLineOrNonWhitespace(fullText, pos) {
  1182. while (pos > 0) {
  1183. pos--;
  1184. const currentChar = fullText[pos];
  1185. if (currentChar === "\n")
  1186. return pos + 1;
  1187. else if (currentChar !== " " && currentChar !== "\t")
  1188. return pos + 1;
  1189. }
  1190. return pos;
  1191. }
  1192. function getInsertPosFromIndex(index, syntaxList, children) {
  1193. if (index === 0) {
  1194. const parent = syntaxList.getParentOrThrow();
  1195. if (Node.isSourceFile(parent))
  1196. return 0;
  1197. else if (Node.isCaseClause(parent) || Node.isDefaultClause(parent)) {
  1198. const colonToken = parent.getFirstChildByKindOrThrow(common.SyntaxKind.ColonToken);
  1199. return colonToken.getEnd();
  1200. }
  1201. const isInline = syntaxList !== parent.getChildSyntaxList();
  1202. if (isInline)
  1203. return syntaxList.getStart();
  1204. const parentContainer = getParentContainerOrThrow(parent);
  1205. const openBraceToken = parentContainer.getFirstChildByKindOrThrow(common.SyntaxKind.OpenBraceToken);
  1206. return openBraceToken.getEnd();
  1207. }
  1208. else {
  1209. return children[index - 1].getEnd();
  1210. }
  1211. }
  1212. function getEndPosFromIndex(index, parent, children, fullText) {
  1213. let endPos;
  1214. if (index === children.length) {
  1215. if (Node.isSourceFile(parent))
  1216. endPos = parent.getEnd();
  1217. else if (Node.isCaseClause(parent) || Node.isDefaultClause(parent))
  1218. endPos = parent.getEnd();
  1219. else {
  1220. const parentContainer = getParentContainerOrThrow(parent);
  1221. const closeBraceToken = parentContainer.getLastChildByKind(common.SyntaxKind.CloseBraceToken);
  1222. if (closeBraceToken == null)
  1223. endPos = parent.getEnd();
  1224. else
  1225. endPos = closeBraceToken.getStart();
  1226. }
  1227. }
  1228. else {
  1229. endPos = children[index].getNonWhitespaceStart();
  1230. }
  1231. return getPosAtStartOfLineOrNonWhitespace(fullText, endPos);
  1232. }
  1233. function getParentContainerOrThrow(parent) {
  1234. if (Node.isModuleDeclaration(parent)) {
  1235. const innerBody = parent._getInnerBody();
  1236. if (innerBody == null)
  1237. throw new common.errors.InvalidOperationError("This operation requires the module to have a body.");
  1238. return innerBody;
  1239. }
  1240. else if (Node.isBodied(parent))
  1241. return parent.getBody();
  1242. else if (Node.isBodyable(parent))
  1243. return parent.getBodyOrThrow();
  1244. else
  1245. return parent;
  1246. }
  1247. function fromAbstractableNode(node) {
  1248. return {
  1249. isAbstract: node.isAbstract(),
  1250. };
  1251. }
  1252. function fromAmbientableNode(node) {
  1253. return {
  1254. hasDeclareKeyword: node.hasDeclareKeyword(),
  1255. };
  1256. }
  1257. function fromExportableNode(node) {
  1258. return {
  1259. isDefaultExport: node.hasDefaultKeyword(),
  1260. isExported: node.hasExportKeyword(),
  1261. };
  1262. }
  1263. function fromStaticableNode(node) {
  1264. return {
  1265. isStatic: node.isStatic(),
  1266. };
  1267. }
  1268. function fromScopedNode(node) {
  1269. return {
  1270. scope: node.hasScopeKeyword() ? node.getScope() : undefined,
  1271. };
  1272. }
  1273. function fromOverrideableNode(node) {
  1274. return {
  1275. hasOverrideKeyword: node.hasOverrideKeyword(),
  1276. };
  1277. }
  1278. function fromQuestionTokenableNode(node) {
  1279. return {
  1280. hasQuestionToken: node.hasQuestionToken(),
  1281. };
  1282. }
  1283. function getNodesToReturn(oldChildren, newChildren, index, allowCommentNodes) {
  1284. const oldChildCount = typeof oldChildren === "number" ? oldChildren : oldChildren.length;
  1285. const newLength = newChildren.length - oldChildCount;
  1286. const result = [];
  1287. for (let i = 0; i < newLength; i++) {
  1288. const currentChild = newChildren[index + i];
  1289. if (allowCommentNodes || !Node.isCommentNode(currentChild))
  1290. result.push(currentChild);
  1291. }
  1292. return result;
  1293. }
  1294. function getRangeWithoutCommentsFromArray(array, index, length, expectedKind) {
  1295. const children = [];
  1296. while (index < array.length && children.length < length) {
  1297. const child = array[index];
  1298. const childKind = child.getKind();
  1299. if (childKind !== common.SyntaxKind.SingleLineCommentTrivia && childKind !== common.SyntaxKind.MultiLineCommentTrivia) {
  1300. if (childKind !== expectedKind) {
  1301. throw new common.errors.NotImplementedError(`Unexpected! Inserting syntax kind of ${common.getSyntaxKindName(expectedKind)}`
  1302. + `, but ${child.getKindName()} was inserted.`);
  1303. }
  1304. children.push(child);
  1305. }
  1306. index++;
  1307. }
  1308. if (children.length !== length)
  1309. throw new common.errors.NotImplementedError(`Unexpected! Inserted ${length} child/children, but ${children.length} were inserted.`);
  1310. return children;
  1311. }
  1312. function fromConstructorDeclarationOverload(node) {
  1313. const structure = {};
  1314. Object.assign(structure, fromScopedNode(node));
  1315. return structure;
  1316. }
  1317. function fromFunctionDeclarationOverload(node) {
  1318. const structure = {};
  1319. Object.assign(structure, fromAmbientableNode(node));
  1320. Object.assign(structure, fromExportableNode(node));
  1321. return structure;
  1322. }
  1323. function fromMethodDeclarationOverload(node) {
  1324. const structure = {};
  1325. Object.assign(structure, fromStaticableNode(node));
  1326. Object.assign(structure, fromAbstractableNode(node));
  1327. Object.assign(structure, fromScopedNode(node));
  1328. Object.assign(structure, fromQuestionTokenableNode(node));
  1329. Object.assign(structure, fromOverrideableNode(node));
  1330. return structure;
  1331. }
  1332. function verifyAndGetIndex(index, length) {
  1333. const newIndex = index < 0 ? length + index : index;
  1334. if (newIndex < 0)
  1335. throw new common.errors.InvalidOperationError(`Invalid index: The max negative index is ${length * -1}, but ${index} was specified.`);
  1336. if (index > length)
  1337. throw new common.errors.InvalidOperationError(`Invalid index: The max index is ${length}, but ${index} was specified.`);
  1338. return newIndex;
  1339. }
  1340. class NodeHandlerHelper {
  1341. #compilerFactory;
  1342. constructor(compilerFactory) {
  1343. this.#compilerFactory = compilerFactory;
  1344. }
  1345. handleForValues(handler, currentNode, newNode, newSourceFile) {
  1346. if (this.#compilerFactory.hasCompilerNode(currentNode))
  1347. handler.handleNode(this.#compilerFactory.getExistingNodeFromCompilerNode(currentNode), newNode, newSourceFile);
  1348. else if (currentNode.kind === common.SyntaxKind.SyntaxList) {
  1349. const sourceFile = this.#compilerFactory.getExistingNodeFromCompilerNode(currentNode.getSourceFile());
  1350. handler.handleNode(this.#compilerFactory.getNodeFromCompilerNode(currentNode, sourceFile), newNode, newSourceFile);
  1351. }
  1352. }
  1353. forgetNodeIfNecessary(currentNode) {
  1354. if (this.#compilerFactory.hasCompilerNode(currentNode))
  1355. this.#compilerFactory.getExistingNodeFromCompilerNode(currentNode).forget();
  1356. }
  1357. getCompilerChildrenAsIterators(currentNode, newNode, newSourceFile) {
  1358. const children = this.getCompilerChildren(currentNode, newNode, newSourceFile);
  1359. return [
  1360. new AdvancedIterator(common.ArrayUtils.toIterator(children[0])),
  1361. new AdvancedIterator(common.ArrayUtils.toIterator(children[1])),
  1362. ];
  1363. }
  1364. getCompilerChildren(currentNode, newNode, newSourceFile) {
  1365. const currentCompilerNode = currentNode.compilerNode;
  1366. const currentSourceFile = currentNode._sourceFile.compilerNode;
  1367. return [
  1368. ExtendedParser.getCompilerChildren(currentCompilerNode, currentSourceFile),
  1369. ExtendedParser.getCompilerChildren(newNode, newSourceFile),
  1370. ];
  1371. }
  1372. getChildrenFast(currentNode, newNode, newSourceFile) {
  1373. const currentCompilerNode = currentNode.compilerNode;
  1374. const currentSourceFile = currentNode._sourceFile.compilerNode;
  1375. if (ExtendedParser.hasParsedTokens(currentCompilerNode)) {
  1376. return [
  1377. ExtendedParser.getCompilerChildren(currentCompilerNode, currentSourceFile),
  1378. ExtendedParser.getCompilerChildren(newNode, newSourceFile),
  1379. ];
  1380. }
  1381. return [
  1382. ExtendedParser.getCompilerForEachChildren(currentCompilerNode, currentSourceFile),
  1383. ExtendedParser.getCompilerForEachChildren(newNode, newSourceFile),
  1384. ];
  1385. }
  1386. }
  1387. class StraightReplacementNodeHandler {
  1388. compilerFactory;
  1389. helper;
  1390. constructor(compilerFactory) {
  1391. this.compilerFactory = compilerFactory;
  1392. this.helper = new NodeHandlerHelper(compilerFactory);
  1393. }
  1394. handleNode(currentNode, newNode, newSourceFile) {
  1395. if (currentNode.getKind() !== newNode.kind) {
  1396. const kinds = [currentNode.getKind(), newNode.kind];
  1397. if (kinds.includes(common.ts.SyntaxKind.Identifier) && kinds.includes(common.ts.SyntaxKind.PrivateIdentifier)) {
  1398. currentNode.forget();
  1399. return;
  1400. }
  1401. throw new common.errors.InvalidOperationError(`Error replacing tree! Perhaps a syntax error was inserted `
  1402. + `(Current: ${currentNode.getKindName()} -- New: ${common.getSyntaxKindName(newNode.kind)}).`);
  1403. }
  1404. if (currentNode._hasWrappedChildren())
  1405. this.#handleChildren(currentNode, newNode, newSourceFile);
  1406. this.compilerFactory.replaceCompilerNode(currentNode, newNode);
  1407. }
  1408. #handleChildren(currentNode, newNode, newSourceFile) {
  1409. const [currentChildren, newChildren] = this.helper.getChildrenFast(currentNode, newNode, newSourceFile);
  1410. if (currentChildren.length !== newChildren.length) {
  1411. throw new Error(`Error replacing tree: The children of the old and new trees were expected to have the `
  1412. + `same count (${currentChildren.length}:${newChildren.length}).`);
  1413. }
  1414. for (let i = 0; i < currentChildren.length; i++)
  1415. this.helper.handleForValues(this, currentChildren[i], newChildren[i], newSourceFile);
  1416. }
  1417. }
  1418. class ChangeChildOrderParentHandler {
  1419. #compilerFactory;
  1420. #straightReplacementNodeHandler;
  1421. #helper;
  1422. #oldIndex;
  1423. #newIndex;
  1424. constructor(compilerFactory, opts) {
  1425. this.#straightReplacementNodeHandler = new StraightReplacementNodeHandler(compilerFactory);
  1426. this.#helper = new NodeHandlerHelper(compilerFactory);
  1427. this.#oldIndex = opts.oldIndex;
  1428. this.#newIndex = opts.newIndex;
  1429. this.#compilerFactory = compilerFactory;
  1430. }
  1431. handleNode(currentNode, newNode, newSourceFile) {
  1432. const [currentChildren, newChildren] = this.#helper.getCompilerChildren(currentNode, newNode, newSourceFile);
  1433. const currentChildrenInNewOrder = this.#getChildrenInNewOrder(currentChildren);
  1434. common.errors.throwIfNotEqual(newChildren.length, currentChildrenInNewOrder.length, "New children length should match the old children length.");
  1435. for (let i = 0; i < newChildren.length; i++)
  1436. this.#helper.handleForValues(this.#straightReplacementNodeHandler, currentChildrenInNewOrder[i], newChildren[i], newSourceFile);
  1437. this.#compilerFactory.replaceCompilerNode(currentNode, newNode);
  1438. }
  1439. #getChildrenInNewOrder(children) {
  1440. const result = [...children];
  1441. const movingNode = result.splice(this.#oldIndex, 1)[0];
  1442. result.splice(this.#newIndex, 0, movingNode);
  1443. return result;
  1444. }
  1445. }
  1446. class DefaultParentHandler {
  1447. #compilerFactory;
  1448. #straightReplacementNodeHandler;
  1449. #helper;
  1450. #childCount;
  1451. #isFirstChild;
  1452. #replacingNodes;
  1453. #customMappings;
  1454. constructor(compilerFactory, opts) {
  1455. this.#straightReplacementNodeHandler = new StraightReplacementNodeHandler(compilerFactory);
  1456. this.#helper = new NodeHandlerHelper(compilerFactory);
  1457. this.#childCount = opts.childCount;
  1458. this.#isFirstChild = opts.isFirstChild;
  1459. this.#replacingNodes = opts.replacingNodes?.map(n => n.compilerNode);
  1460. this.#customMappings = opts.customMappings;
  1461. this.#compilerFactory = compilerFactory;
  1462. }
  1463. handleNode(currentNode, newNode, newSourceFile) {
  1464. const [currentChildren, newChildren] = this.#helper.getCompilerChildrenAsIterators(currentNode, newNode, newSourceFile);
  1465. let count = this.#childCount;
  1466. this.#handleCustomMappings(newNode);
  1467. while (!currentChildren.done && !newChildren.done && !this.#isFirstChild(currentChildren.peek, newChildren.peek))
  1468. this.#helper.handleForValues(this.#straightReplacementNodeHandler, currentChildren.next(), newChildren.next(), newSourceFile);
  1469. while (!currentChildren.done && this.#tryReplaceNode(currentChildren.peek))
  1470. currentChildren.next();
  1471. if (count > 0) {
  1472. while (count > 0) {
  1473. newChildren.next();
  1474. count--;
  1475. }
  1476. }
  1477. else if (count < 0) {
  1478. while (count < 0) {
  1479. this.#helper.forgetNodeIfNecessary(currentChildren.next());
  1480. count++;
  1481. }
  1482. }
  1483. while (!currentChildren.done)
  1484. this.#helper.handleForValues(this.#straightReplacementNodeHandler, currentChildren.next(), newChildren.next(), newSourceFile);
  1485. if (!newChildren.done)
  1486. throw new Error("Error replacing tree: Should not have children left over.");
  1487. this.#compilerFactory.replaceCompilerNode(currentNode, newNode);
  1488. }
  1489. #handleCustomMappings(newParentNode) {
  1490. if (this.#customMappings == null)
  1491. return;
  1492. const customMappings = this.#customMappings(newParentNode);
  1493. for (const mapping of customMappings)
  1494. this.#compilerFactory.replaceCompilerNode(mapping.currentNode, mapping.newNode);
  1495. }
  1496. #tryReplaceNode(currentCompilerNode) {
  1497. if (this.#replacingNodes == null || this.#replacingNodes.length === 0)
  1498. return false;
  1499. const index = this.#replacingNodes.indexOf(currentCompilerNode);
  1500. if (index === -1)
  1501. return false;
  1502. this.#replacingNodes.splice(index, 1);
  1503. this.#helper.forgetNodeIfNecessary(currentCompilerNode);
  1504. return true;
  1505. }
  1506. }
  1507. class ForgetChangedNodeHandler {
  1508. #compilerFactory;
  1509. #helper;
  1510. constructor(compilerFactory) {
  1511. this.#helper = new NodeHandlerHelper(compilerFactory);
  1512. this.#compilerFactory = compilerFactory;
  1513. }
  1514. handleNode(currentNode, newNode, newSourceFile) {
  1515. if (currentNode.getKind() !== newNode.kind) {
  1516. currentNode.forget();
  1517. return;
  1518. }
  1519. if (currentNode._hasWrappedChildren())
  1520. this.#handleChildren(currentNode, newNode, newSourceFile);
  1521. this.#compilerFactory.replaceCompilerNode(currentNode, newNode);
  1522. }
  1523. #handleChildren(currentNode, newNode, newSourceFile) {
  1524. const [currentNodeChildren, newNodeChildrenArray] = this.#helper.getChildrenFast(currentNode, newNode, newSourceFile);
  1525. const newNodeChildren = common.ArrayUtils.toIterator(newNodeChildrenArray);
  1526. for (const currentNodeChild of currentNodeChildren) {
  1527. const nextNodeChildResult = newNodeChildren.next();
  1528. if (nextNodeChildResult.done) {
  1529. const existingNode = this.#compilerFactory.getExistingNodeFromCompilerNode(currentNodeChild);
  1530. if (existingNode != null)
  1531. existingNode.forget();
  1532. }
  1533. else {
  1534. this.#helper.handleForValues(this, currentNodeChild, nextNodeChildResult.value, newSourceFile);
  1535. }
  1536. }
  1537. }
  1538. }
  1539. class ParentFinderReplacementNodeHandler extends StraightReplacementNodeHandler {
  1540. #changingParent;
  1541. #parentNodeHandler;
  1542. #changingParentParent;
  1543. #foundParent = false;
  1544. #parentsAtSamePos;
  1545. constructor(compilerFactory, parentNodeHandler, changingParent) {
  1546. super(compilerFactory);
  1547. this.#changingParentParent = changingParent.getParentSyntaxList() ?? changingParent.getParent();
  1548. this.#parentsAtSamePos = this.#changingParentParent != null && this.#changingParentParent.getPos() === changingParent.getPos();
  1549. this.#parentNodeHandler = parentNodeHandler;
  1550. this.#changingParent = changingParent;
  1551. }
  1552. handleNode(currentNode, newNode, newSourceFile) {
  1553. if (!this.#foundParent && this.#isParentNode(newNode, newSourceFile)) {
  1554. this.#foundParent = true;
  1555. this.#parentNodeHandler.handleNode(currentNode, newNode, newSourceFile);
  1556. }
  1557. else {
  1558. super.handleNode(currentNode, newNode, newSourceFile);
  1559. }
  1560. }
  1561. #isParentNode(newNode, newSourceFile) {
  1562. const positionsAndKindsEqual = areNodesEqual(newNode, this.#changingParent)
  1563. && areNodesEqual(getParentSyntaxList(newNode, newSourceFile) || newNode.parent, this.#changingParentParent);
  1564. if (!positionsAndKindsEqual)
  1565. return false;
  1566. if (!this.#parentsAtSamePos)
  1567. return true;
  1568. return getAncestorLength(this.#changingParent.compilerNode) === getAncestorLength(newNode);
  1569. function getAncestorLength(nodeToCheck) {
  1570. let node = nodeToCheck;
  1571. let count = 0;
  1572. while (node.parent != null) {
  1573. count++;
  1574. node = node.parent;
  1575. }
  1576. return count;
  1577. }
  1578. }
  1579. }
  1580. function areNodesEqual(a, b) {
  1581. if (a == null && b == null)
  1582. return true;
  1583. if (a == null || b == null)
  1584. return false;
  1585. if (a.pos === b.getPos() && a.kind === b.getKind())
  1586. return true;
  1587. return false;
  1588. }
  1589. class RangeHandler {
  1590. #compilerFactory;
  1591. #straightReplacementNodeHandler;
  1592. #helper;
  1593. #start;
  1594. #end;
  1595. constructor(compilerFactory, opts) {
  1596. this.#straightReplacementNodeHandler = new StraightReplacementNodeHandler(compilerFactory);
  1597. this.#helper = new NodeHandlerHelper(compilerFactory);
  1598. this.#start = opts.start;
  1599. this.#end = opts.end;
  1600. this.#compilerFactory = compilerFactory;
  1601. }
  1602. handleNode(currentNode, newNode, newSourceFile) {
  1603. const currentSourceFile = currentNode._sourceFile.compilerNode;
  1604. const children = this.#helper.getChildrenFast(currentNode, newNode, newSourceFile);
  1605. const currentNodeChildren = new AdvancedIterator(common.ArrayUtils.toIterator(children[0]));
  1606. const newNodeChildren = new AdvancedIterator(common.ArrayUtils.toIterator(children[1]));
  1607. while (!currentNodeChildren.done && !newNodeChildren.done && newNodeChildren.peek.getEnd() <= this.#start)
  1608. this.#straightReplace(currentNodeChildren.next(), newNodeChildren.next(), newSourceFile);
  1609. while (!currentNodeChildren.done && !newNodeChildren.done
  1610. && (currentNodeChildren.peek.getStart(currentSourceFile) < this.#start
  1611. || currentNodeChildren.peek.getStart(currentSourceFile) === this.#start && newNodeChildren.peek.end > this.#end)) {
  1612. this.#rangeHandlerReplace(currentNodeChildren.next(), newNodeChildren.next(), newSourceFile);
  1613. }
  1614. while (!newNodeChildren.done && newNodeChildren.peek.getEnd() <= this.#end)
  1615. newNodeChildren.next();
  1616. while (!currentNodeChildren.done)
  1617. this.#straightReplace(currentNodeChildren.next(), newNodeChildren.next(), newSourceFile);
  1618. if (!newNodeChildren.done)
  1619. throw new Error("Error replacing tree: Should not have children left over.");
  1620. this.#compilerFactory.replaceCompilerNode(currentNode, newNode);
  1621. }
  1622. #straightReplace(currentNode, nextNode, newSourceFile) {
  1623. this.#helper.handleForValues(this.#straightReplacementNodeHandler, currentNode, nextNode, newSourceFile);
  1624. }
  1625. #rangeHandlerReplace(currentNode, nextNode, newSourceFile) {
  1626. this.#helper.handleForValues(this, currentNode, nextNode, newSourceFile);
  1627. }
  1628. }
  1629. class RangeParentHandler {
  1630. #compilerFactory;
  1631. #straightReplacementNodeHandler;
  1632. #helper;
  1633. #start;
  1634. #end;
  1635. #replacingLength;
  1636. #replacingNodes;
  1637. #customMappings;
  1638. constructor(compilerFactory, opts) {
  1639. this.#straightReplacementNodeHandler = new StraightReplacementNodeHandler(compilerFactory);
  1640. this.#helper = new NodeHandlerHelper(compilerFactory);
  1641. this.#start = opts.start;
  1642. this.#end = opts.end;
  1643. this.#replacingLength = opts.replacingLength;
  1644. this.#replacingNodes = opts.replacingNodes?.map(n => n.compilerNode);
  1645. this.#customMappings = opts.customMappings;
  1646. this.#compilerFactory = compilerFactory;
  1647. }
  1648. handleNode(currentNode, newNode, newSourceFile) {
  1649. const currentSourceFile = currentNode._sourceFile.compilerNode;
  1650. const [currentNodeChildren, newNodeChildren] = this.#helper.getCompilerChildrenAsIterators(currentNode, newNode, newSourceFile);
  1651. this.#handleCustomMappings(newNode, newSourceFile);
  1652. while (!currentNodeChildren.done && !newNodeChildren.done && newNodeChildren.peek.getStart(newSourceFile) < this.#start)
  1653. this.#straightReplace(currentNodeChildren.next(), newNodeChildren.next(), newSourceFile);
  1654. const newNodes = [];
  1655. while (!newNodeChildren.done && newNodeChildren.peek.getStart(newSourceFile) >= this.#start
  1656. && getRealEnd(newNodeChildren.peek, newSourceFile) <= this.#end) {
  1657. newNodes.push(newNodeChildren.next());
  1658. }
  1659. if (this.#replacingLength != null) {
  1660. const replacingEnd = this.#start + this.#replacingLength;
  1661. const oldNodes = [];
  1662. while (!currentNodeChildren.done
  1663. && (getRealEnd(currentNodeChildren.peek, currentSourceFile) <= replacingEnd
  1664. || currentNodeChildren.peek.getStart(currentSourceFile) < replacingEnd)) {
  1665. oldNodes.push(currentNodeChildren.next());
  1666. }
  1667. if (oldNodes.length === newNodes.length && oldNodes.every((node, i) => node.kind === newNodes[i].kind)) {
  1668. for (let i = 0; i < oldNodes.length; i++) {
  1669. const node = this.#compilerFactory.getExistingNodeFromCompilerNode(oldNodes[i]);
  1670. if (node != null) {
  1671. node.forgetDescendants();
  1672. this.#compilerFactory.replaceCompilerNode(oldNodes[i], newNodes[i]);
  1673. }
  1674. }
  1675. }
  1676. else {
  1677. oldNodes.forEach(node => this.#helper.forgetNodeIfNecessary(node));
  1678. }
  1679. }
  1680. while (!currentNodeChildren.done)
  1681. this.#straightReplace(currentNodeChildren.next(), newNodeChildren.next(), newSourceFile);
  1682. if (!newNodeChildren.done)
  1683. throw new Error("Error replacing tree: Should not have children left over.");
  1684. this.#compilerFactory.replaceCompilerNode(currentNode, newNode);
  1685. }
  1686. #handleCustomMappings(newParentNode, newSourceFile) {
  1687. if (this.#customMappings == null)
  1688. return;
  1689. const customMappings = this.#customMappings(newParentNode, newSourceFile);
  1690. for (const mapping of customMappings)
  1691. mapping.currentNode._context.compilerFactory.replaceCompilerNode(mapping.currentNode, mapping.newNode);
  1692. }
  1693. #straightReplace(currentNode, nextNode, newSourceFile) {
  1694. if (!this.#tryReplaceNode(currentNode))
  1695. this.#helper.handleForValues(this.#straightReplacementNodeHandler, currentNode, nextNode, newSourceFile);
  1696. }
  1697. #tryReplaceNode(currentCompilerNode) {
  1698. if (this.#replacingNodes == null || this.#replacingNodes.length === 0)
  1699. return false;
  1700. const index = this.#replacingNodes.indexOf(currentCompilerNode);
  1701. if (index === -1)
  1702. return false;
  1703. this.#replacingNodes.splice(index, 1);
  1704. this.#helper.forgetNodeIfNecessary(currentCompilerNode);
  1705. return true;
  1706. }
  1707. }
  1708. function getRealEnd(node, sourceFile) {
  1709. if (node.kind >= common.ts.SyntaxKind.FirstJSDocNode && node.kind <= common.ts.SyntaxKind.LastJSDocNode) {
  1710. return getPreviousMatchingPos(sourceFile.text, node.end, charCode => charCode !== CharCodes.ASTERISK && !common.StringUtils.isWhitespaceCharCode(charCode));
  1711. }
  1712. return node.end;
  1713. }
  1714. class RenameNodeHandler extends StraightReplacementNodeHandler {
  1715. handleNode(currentNode, newNode, newSourceFile) {
  1716. const currentNodeKind = currentNode.getKind();
  1717. const newNodeKind = newNode.kind;
  1718. if (currentNodeKind === common.SyntaxKind.ShorthandPropertyAssignment && newNodeKind === common.SyntaxKind.PropertyAssignment) {
  1719. const currentSourceFile = currentNode.getSourceFile();
  1720. const currentIdentifier = currentNode.getNameNode();
  1721. const newIdentifier = newNode.initializer;
  1722. this.compilerFactory.replaceCompilerNode(currentIdentifier, newIdentifier);
  1723. currentNode.forget();
  1724. this.compilerFactory.getNodeFromCompilerNode(newNode, currentSourceFile);
  1725. return;
  1726. }
  1727. else if (currentNodeKind === common.SyntaxKind.ExportSpecifier && newNodeKind === common.SyntaxKind.ExportSpecifier
  1728. && currentNode.compilerNode.propertyName == null && newNode.propertyName != null) {
  1729. handleImportOrExportSpecifier(this.compilerFactory);
  1730. return;
  1731. }
  1732. else if (currentNodeKind === common.SyntaxKind.ImportSpecifier && newNodeKind === common.SyntaxKind.ImportSpecifier
  1733. && currentNode.compilerNode.propertyName == null && newNode.propertyName != null) {
  1734. handleImportOrExportSpecifier(this.compilerFactory);
  1735. return;
  1736. }
  1737. super.handleNode(currentNode, newNode, newSourceFile);
  1738. return;
  1739. function handleImportOrExportSpecifier(compilerFactory) {
  1740. function getNameText(node) {
  1741. return node.kind === common.SyntaxKind.Identifier ? node.escapedText : node.text;
  1742. }
  1743. const currentName = currentNode.getNameNode();
  1744. const newSpecifier = newNode;
  1745. const newPropertyName = newSpecifier.propertyName;
  1746. const newName = newSpecifier.name;
  1747. const newIdentifier = getNameText(newPropertyName) === getNameText(currentName.compilerNode) ? newName : newPropertyName;
  1748. compilerFactory.replaceCompilerNode(currentName, newIdentifier);
  1749. compilerFactory.replaceCompilerNode(currentNode, newNode);
  1750. }
  1751. }
  1752. }
  1753. class TryOrForgetNodeHandler {
  1754. #handler;
  1755. constructor(handler) {
  1756. this.#handler = handler;
  1757. }
  1758. handleNode(currentNode, newNode, newSourceFile) {
  1759. if (!Node.isSourceFile(currentNode))
  1760. throw new common.errors.InvalidOperationError(`Can only use a TryOrForgetNodeHandler with a source file.`);
  1761. try {
  1762. this.#handler.handleNode(currentNode, newNode, newSourceFile);
  1763. }
  1764. catch (ex) {
  1765. currentNode._context.logger.warn("Could not replace tree, so forgetting all nodes instead. Message: " + ex);
  1766. currentNode.getChildSyntaxListOrThrow().forget();
  1767. currentNode._context.compilerFactory.replaceCompilerNode(currentNode, newNode);
  1768. }
  1769. }
  1770. }
  1771. class UnwrapParentHandler {
  1772. #childIndex;
  1773. #compilerFactory;
  1774. #straightReplacementNodeHandler;
  1775. #helper;
  1776. constructor(compilerFactory, childIndex) {
  1777. this.#straightReplacementNodeHandler = new StraightReplacementNodeHandler(compilerFactory);
  1778. this.#helper = new NodeHandlerHelper(compilerFactory);
  1779. this.#compilerFactory = compilerFactory;
  1780. this.#childIndex = childIndex;
  1781. }
  1782. handleNode(currentNode, newNode, newSourceFile) {
  1783. const [currentChildren, newChildren] = this.#helper.getCompilerChildrenAsIterators(currentNode, newNode, newSourceFile);
  1784. let index = 0;
  1785. while (!currentChildren.done && !newChildren.done && index++ < this.#childIndex)
  1786. this.#helper.handleForValues(this.#straightReplacementNodeHandler, currentChildren.next(), newChildren.next(), newSourceFile);
  1787. const currentChild = this.#compilerFactory.getExistingNodeFromCompilerNode(currentChildren.next());
  1788. const childSyntaxList = currentChild.getChildSyntaxListOrThrow();
  1789. for (const child of ExtendedParser.getCompilerChildren(childSyntaxList.compilerNode, childSyntaxList._sourceFile.compilerNode))
  1790. this.#helper.handleForValues(this.#straightReplacementNodeHandler, child, newChildren.next(), newSourceFile);
  1791. forgetNodes(currentChild);
  1792. function forgetNodes(node) {
  1793. if (node === childSyntaxList) {
  1794. node._forgetOnlyThis();
  1795. return;
  1796. }
  1797. for (const child of node._getChildrenInCacheIterator())
  1798. forgetNodes(child);
  1799. node._forgetOnlyThis();
  1800. }
  1801. while (!currentChildren.done)
  1802. this.#helper.handleForValues(this.#straightReplacementNodeHandler, currentChildren.next(), newChildren.next(), newSourceFile);
  1803. if (!newChildren.done)
  1804. throw new Error("Error replacing tree: Should not have children left over.");
  1805. this.#compilerFactory.replaceCompilerNode(currentNode, newNode);
  1806. }
  1807. }
  1808. class NodeHandlerFactory {
  1809. getDefault(opts) {
  1810. const { parent: changingParent, isFirstChild, childCount, customMappings } = opts;
  1811. const sourceFile = changingParent.getSourceFile();
  1812. const compilerFactory = sourceFile._context.compilerFactory;
  1813. const replacingNodes = opts.replacingNodes == null ? undefined : [...opts.replacingNodes];
  1814. const parentHandler = new DefaultParentHandler(compilerFactory, { childCount, isFirstChild, replacingNodes, customMappings });
  1815. if (changingParent === sourceFile)
  1816. return parentHandler;
  1817. else
  1818. return new ParentFinderReplacementNodeHandler(compilerFactory, parentHandler, changingParent);
  1819. }
  1820. getForParentRange(opts) {
  1821. const { parent: changingParent, start, end, replacingLength, replacingNodes, customMappings } = opts;
  1822. const sourceFile = changingParent.getSourceFile();
  1823. const compilerFactory = sourceFile._context.compilerFactory;
  1824. const parentHandler = new RangeParentHandler(compilerFactory, { start, end, replacingLength, replacingNodes, customMappings });
  1825. if (changingParent === sourceFile)
  1826. return parentHandler;
  1827. else
  1828. return new ParentFinderReplacementNodeHandler(compilerFactory, parentHandler, changingParent);
  1829. }
  1830. getForRange(opts) {
  1831. const { sourceFile, start, end } = opts;
  1832. const compilerFactory = sourceFile._context.compilerFactory;
  1833. return new RangeHandler(compilerFactory, { start, end });
  1834. }
  1835. getForChildIndex(opts) {
  1836. const { parent, childIndex, childCount, replacingNodes, customMappings } = opts;
  1837. const parentChildren = parent.getChildren();
  1838. common.errors.throwIfOutOfRange(childIndex, [0, parentChildren.length], "opts.childIndex");
  1839. if (childCount < 0)
  1840. common.errors.throwIfOutOfRange(childCount, [childIndex - parentChildren.length, 0], "opts.childCount");
  1841. let i = 0;
  1842. const isFirstChild = () => i++ === childIndex;
  1843. return this.getDefault({
  1844. parent,
  1845. isFirstChild,
  1846. childCount,
  1847. replacingNodes,
  1848. customMappings,
  1849. });
  1850. }
  1851. getForStraightReplacement(compilerFactory) {
  1852. return new StraightReplacementNodeHandler(compilerFactory);
  1853. }
  1854. getForForgetChanged(compilerFactory) {
  1855. return new ForgetChangedNodeHandler(compilerFactory);
  1856. }
  1857. getForRename(compilerFactory) {
  1858. return new RenameNodeHandler(compilerFactory);
  1859. }
  1860. getForTryOrForget(handler) {
  1861. return new TryOrForgetNodeHandler(handler);
  1862. }
  1863. getForChangingChildOrder(opts) {
  1864. const { parent: changingParent, oldIndex, newIndex } = opts;
  1865. const sourceFile = changingParent.getSourceFile();
  1866. const compilerFactory = sourceFile._context.compilerFactory;
  1867. const changeChildOrderParentHandler = new ChangeChildOrderParentHandler(compilerFactory, { oldIndex, newIndex });
  1868. if (changingParent === sourceFile)
  1869. return changeChildOrderParentHandler;
  1870. else
  1871. return new ParentFinderReplacementNodeHandler(compilerFactory, changeChildOrderParentHandler, changingParent);
  1872. }
  1873. getForUnwrappingNode(unwrappingNode) {
  1874. const changingParent = unwrappingNode.getParentSyntaxList() || unwrappingNode.getParentOrThrow();
  1875. const childIndex = unwrappingNode.getChildIndex();
  1876. const sourceFile = changingParent.getSourceFile();
  1877. const compilerFactory = sourceFile._context.compilerFactory;
  1878. const unwrapParentHandler = new UnwrapParentHandler(compilerFactory, childIndex);
  1879. if (changingParent === sourceFile)
  1880. return unwrapParentHandler;
  1881. else
  1882. return new ParentFinderReplacementNodeHandler(compilerFactory, unwrapParentHandler, changingParent);
  1883. }
  1884. }
  1885. function getSpacingBetweenNodes(opts) {
  1886. const { parent, previousSibling, nextSibling, newLineKind, getSiblingFormatting } = opts;
  1887. if (previousSibling == null || nextSibling == null)
  1888. return "";
  1889. const previousSiblingFormatting = getSiblingFormatting(parent, previousSibling);
  1890. const nextSiblingFormatting = getSiblingFormatting(parent, nextSibling);
  1891. if (previousSiblingFormatting === FormattingKind.Blankline || nextSiblingFormatting === FormattingKind.Blankline)
  1892. return newLineKind + newLineKind;
  1893. else if (previousSiblingFormatting === FormattingKind.Newline || nextSiblingFormatting === FormattingKind.Newline)
  1894. return newLineKind;
  1895. else if (previousSiblingFormatting === FormattingKind.Space || nextSiblingFormatting === FormattingKind.Space)
  1896. return " ";
  1897. else
  1898. return "";
  1899. }
  1900. class ChangingChildOrderTextManipulator {
  1901. #opts;
  1902. constructor(opts) {
  1903. this.#opts = opts;
  1904. }
  1905. getNewText(inputText) {
  1906. const { parent, oldIndex, newIndex, getSiblingFormatting } = this.#opts;
  1907. const children = parent.getChildren();
  1908. const newLineKind = parent._context.manipulationSettings.getNewLineKindAsString();
  1909. const movingNode = children[oldIndex];
  1910. const fullText = parent._sourceFile.getFullText();
  1911. const movingNodeStart = getPosAtNextNonBlankLine(fullText, movingNode.getPos());
  1912. const movingNodeText = fullText.substring(movingNodeStart, movingNode.getEnd());
  1913. const lowerIndex = Math.min(newIndex, oldIndex);
  1914. const upperIndex = Math.max(newIndex, oldIndex);
  1915. const childrenInNewOrder = getChildrenInNewOrder();
  1916. const isParentSourceFile = Node.isSourceFile(parent.getParentOrThrow());
  1917. let finalText = "";
  1918. fillPrefixText();
  1919. fillTextForIndex(lowerIndex);
  1920. fillMiddleText();
  1921. fillTextForIndex(upperIndex);
  1922. fillSuffixText();
  1923. return finalText;
  1924. function getChildrenInNewOrder() {
  1925. const result = [...children];
  1926. result.splice(oldIndex, 1);
  1927. result.splice(newIndex, 0, movingNode);
  1928. return result;
  1929. }
  1930. function fillPrefixText() {
  1931. finalText += fullText.substring(0, children[lowerIndex].getPos());
  1932. if (lowerIndex === 0 && !isParentSourceFile)
  1933. finalText += newLineKind;
  1934. }
  1935. function fillMiddleText() {
  1936. let startPos;
  1937. let endPos;
  1938. if (lowerIndex === oldIndex) {
  1939. startPos = getPosAtNextNonBlankLine(fullText, children[lowerIndex].getEnd());
  1940. endPos = children[upperIndex].getEnd();
  1941. }
  1942. else {
  1943. startPos = getPosAtNextNonBlankLine(fullText, children[lowerIndex].getPos());
  1944. endPos = children[upperIndex].getPos();
  1945. }
  1946. finalText += fullText.substring(startPos, endPos);
  1947. }
  1948. function fillSuffixText() {
  1949. if (children.length - 1 === upperIndex && !isParentSourceFile)
  1950. finalText += newLineKind;
  1951. finalText += fullText.substring(getPosAtNextNonBlankLine(fullText, children[upperIndex].getEnd()));
  1952. }
  1953. function fillTextForIndex(index) {
  1954. if (index === oldIndex)
  1955. fillSpacingForRemoval();
  1956. else {
  1957. fillSpacingBeforeInsertion();
  1958. finalText += movingNodeText;
  1959. fillSpacingAfterInsertion();
  1960. }
  1961. }
  1962. function fillSpacingForRemoval() {
  1963. if (oldIndex === 0 || oldIndex === children.length - 1)
  1964. return;
  1965. fillSpacingCommon({
  1966. previousSibling: childrenInNewOrder[oldIndex - 1],
  1967. nextSibling: childrenInNewOrder[oldIndex],
  1968. });
  1969. }
  1970. function fillSpacingBeforeInsertion() {
  1971. if (newIndex === 0)
  1972. return;
  1973. fillSpacingCommon({
  1974. previousSibling: childrenInNewOrder[newIndex - 1],
  1975. nextSibling: childrenInNewOrder[newIndex],
  1976. });
  1977. }
  1978. function fillSpacingAfterInsertion() {
  1979. fillSpacingCommon({
  1980. previousSibling: childrenInNewOrder[newIndex],
  1981. nextSibling: childrenInNewOrder[newIndex + 1],
  1982. });
  1983. }
  1984. function fillSpacingCommon(spacingOpts) {
  1985. const spacing = getSpacingBetweenNodes({
  1986. parent,
  1987. getSiblingFormatting,
  1988. newLineKind,
  1989. previousSibling: spacingOpts.previousSibling,
  1990. nextSibling: spacingOpts.nextSibling,
  1991. });
  1992. const twoNewLines = newLineKind + newLineKind;
  1993. if (spacing === twoNewLines) {
  1994. if (finalText.endsWith(twoNewLines))
  1995. return;
  1996. else if (finalText.endsWith(newLineKind))
  1997. finalText += newLineKind;
  1998. else
  1999. finalText += twoNewLines;
  2000. }
  2001. else if (spacing === newLineKind) {
  2002. if (finalText.endsWith(newLineKind))
  2003. return;
  2004. else
  2005. finalText += newLineKind;
  2006. }
  2007. else if (spacing === " ") {
  2008. if (finalText.endsWith(" "))
  2009. return;
  2010. else
  2011. finalText += " ";
  2012. }
  2013. else {
  2014. finalText += spacing;
  2015. }
  2016. }
  2017. }
  2018. getTextForError(newText) {
  2019. return newText;
  2020. }
  2021. }
  2022. class FullReplacementTextManipulator {
  2023. #newText;
  2024. constructor(newText) {
  2025. this.#newText = newText;
  2026. }
  2027. getNewText(inputText) {
  2028. return this.#newText;
  2029. }
  2030. getTextForError(newText) {
  2031. return newText;
  2032. }
  2033. }
  2034. function getTextForError(newText, pos, length = 0) {
  2035. const startPos = Math.max(0, newText.lastIndexOf("\n", pos) - 100);
  2036. let endPos = Math.min(newText.length, newText.indexOf("\n", pos + length));
  2037. endPos = endPos === -1 ? newText.length : Math.min(newText.length, endPos + 100);
  2038. let text = "";
  2039. text += newText.substring(startPos, endPos);
  2040. if (startPos !== 0)
  2041. text = "..." + text;
  2042. if (endPos !== newText.length)
  2043. text += "...";
  2044. return text;
  2045. }
  2046. class InsertionTextManipulator {
  2047. #opts;
  2048. constructor(opts) {
  2049. this.#opts = opts;
  2050. }
  2051. getNewText(inputText) {
  2052. const { insertPos, newText, replacingLength = 0 } = this.#opts;
  2053. return inputText.substring(0, insertPos) + newText + inputText.substring(insertPos + replacingLength);
  2054. }
  2055. getTextForError(newText) {
  2056. return getTextForError(newText, this.#opts.insertPos, this.#opts.newText.length);
  2057. }
  2058. }
  2059. class RemoveChildrenTextManipulator {
  2060. #opts;
  2061. #removalPos;
  2062. constructor(opts) {
  2063. this.#opts = opts;
  2064. }
  2065. getNewText(inputText) {
  2066. const opts = this.#opts;
  2067. const { children, removePrecedingSpaces = false, removeFollowingSpaces = false, removePrecedingNewLines = false, removeFollowingNewLines = false, replaceTrivia = "", } = opts;
  2068. const sourceFile = children[0].getSourceFile();
  2069. const fullText = sourceFile.getFullText();
  2070. const removalPos = getRemovalPos();
  2071. this.#removalPos = removalPos;
  2072. return getPrefix() + replaceTrivia + getSuffix();
  2073. function getPrefix() {
  2074. return fullText.substring(0, removalPos);
  2075. }
  2076. function getSuffix() {
  2077. return fullText.substring(getRemovalEnd());
  2078. }
  2079. function getRemovalPos() {
  2080. if (opts.customRemovalPos != null)
  2081. return opts.customRemovalPos;
  2082. const pos = children[0].getNonWhitespaceStart();
  2083. if (removePrecedingSpaces || removePrecedingNewLines)
  2084. return getPreviousMatchingPos(fullText, pos, getCharRemovalFunction(removePrecedingSpaces, removePrecedingNewLines));
  2085. return pos;
  2086. }
  2087. function getRemovalEnd() {
  2088. if (opts.customRemovalEnd != null)
  2089. return opts.customRemovalEnd;
  2090. const end = children[children.length - 1].getEnd();
  2091. if (removeFollowingSpaces || removeFollowingNewLines)
  2092. return getNextMatchingPos(fullText, end, getCharRemovalFunction(removeFollowingSpaces, removeFollowingNewLines));
  2093. return end;
  2094. }
  2095. function getCharRemovalFunction(removeSpaces, removeNewLines) {
  2096. return (char) => {
  2097. if (removeNewLines && (char === CharCodes.CARRIAGE_RETURN || char === CharCodes.NEWLINE))
  2098. return false;
  2099. if (removeSpaces && !charNotSpaceOrTab(char))
  2100. return false;
  2101. return true;
  2102. };
  2103. }
  2104. function charNotSpaceOrTab(charCode) {
  2105. return charCode !== CharCodes.SPACE && charCode !== CharCodes.TAB;
  2106. }
  2107. }
  2108. getTextForError(newText) {
  2109. return getTextForError(newText, this.#removalPos);
  2110. }
  2111. }
  2112. function isNewLineAtPos(fullText, pos) {
  2113. return fullText[pos] === "\n" || (fullText[pos] === "\r" && fullText[pos + 1] === "\n");
  2114. }
  2115. function hasNewLineInRange(fullText, range) {
  2116. for (let i = range[0]; i < range[1]; i++) {
  2117. if (fullText[i] === "\n")
  2118. return true;
  2119. }
  2120. return false;
  2121. }
  2122. class RemoveChildrenWithFormattingTextManipulator {
  2123. #opts;
  2124. #removalPos;
  2125. constructor(opts) {
  2126. this.#opts = opts;
  2127. }
  2128. getNewText(inputText) {
  2129. const { children, getSiblingFormatting } = this.#opts;
  2130. const firstChild = children[0];
  2131. const lastChild = children[children.length - 1];
  2132. const parent = firstChild.getParentOrThrow();
  2133. const sourceFile = parent.getSourceFile();
  2134. const fullText = sourceFile.getFullText();
  2135. const newLineKind = sourceFile._context.manipulationSettings.getNewLineKindAsString();
  2136. const previousSibling = firstChild.getPreviousSibling();
  2137. const nextSibling = lastChild.getNextSibling();
  2138. const removalPos = getRemovalPos();
  2139. this.#removalPos = removalPos;
  2140. return getPrefix() + getSpacing() + getSuffix();
  2141. function getPrefix() {
  2142. return fullText.substring(0, removalPos);
  2143. }
  2144. function getSpacing() {
  2145. return getSpacingBetweenNodes({
  2146. parent,
  2147. previousSibling,
  2148. nextSibling,
  2149. newLineKind,
  2150. getSiblingFormatting,
  2151. });
  2152. }
  2153. function getSuffix() {
  2154. return fullText.substring(getRemovalEnd());
  2155. }
  2156. function getRemovalPos() {
  2157. if (previousSibling != null) {
  2158. const trailingEnd = previousSibling.getTrailingTriviaEnd();
  2159. return isNewLineAtPos(fullText, trailingEnd) ? trailingEnd : previousSibling.getEnd();
  2160. }
  2161. const firstPos = getPreviousNonWhitespacePos(fullText, firstChild.getPos());
  2162. if (parent.getPos() === firstPos)
  2163. return firstChild.getNonWhitespaceStart();
  2164. return firstChild.isFirstNodeOnLine() ? firstPos : firstChild.getNonWhitespaceStart();
  2165. }
  2166. function getRemovalEnd() {
  2167. const triviaEnd = lastChild.getTrailingTriviaEnd();
  2168. if (previousSibling != null && nextSibling != null) {
  2169. const nextSiblingFormatting = getSiblingFormatting(parent, nextSibling);
  2170. if (nextSiblingFormatting === FormattingKind.Blankline || nextSiblingFormatting === FormattingKind.Newline)
  2171. return getPosAtStartOfLineOrNonWhitespace(fullText, nextSibling.getNonWhitespaceStart());
  2172. return nextSibling.getNonWhitespaceStart();
  2173. }
  2174. if (parent.getEnd() === lastChild.getEnd())
  2175. return lastChild.getEnd();
  2176. if (isNewLineAtPos(fullText, triviaEnd)) {
  2177. if (previousSibling == null && firstChild.getPos() === 0)
  2178. return getPosAtNextNonBlankLine(fullText, triviaEnd);
  2179. return getPosAtEndOfPreviousLine(fullText, getPosAtNextNonBlankLine(fullText, triviaEnd));
  2180. }
  2181. if (previousSibling == null)
  2182. return triviaEnd;
  2183. else
  2184. return lastChild.getEnd();
  2185. }
  2186. }
  2187. getTextForError(newText) {
  2188. return getTextForError(newText, this.#removalPos);
  2189. }
  2190. }
  2191. class RenameLocationTextManipulator {
  2192. #newName;
  2193. #renameLocations;
  2194. constructor(renameLocations, newName) {
  2195. this.#renameLocations = renameLocations;
  2196. this.#newName = newName;
  2197. }
  2198. getNewText(inputText) {
  2199. const renameLocations = [...this.#renameLocations].sort((a, b) => b.getTextSpan().getStart() - a.getTextSpan().getStart());
  2200. let currentPos = inputText.length;
  2201. let result = "";
  2202. for (let i = 0; i < renameLocations.length; i++) {
  2203. const renameLocation = renameLocations[i];
  2204. const textSpan = renameLocation.getTextSpan();
  2205. result = (renameLocation.getPrefixText() || "")
  2206. + this.#newName
  2207. + (renameLocation.getSuffixText() || "")
  2208. + inputText.substring(textSpan.getEnd(), currentPos)
  2209. + result;
  2210. currentPos = textSpan.getStart();
  2211. }
  2212. return inputText.substring(0, currentPos) + result;
  2213. }
  2214. getTextForError(newText) {
  2215. if (this.#renameLocations.length === 0)
  2216. return newText;
  2217. return "..." + newText.substring(this.#renameLocations[0].getTextSpan().getStart());
  2218. }
  2219. }
  2220. class UnchangedTextManipulator {
  2221. getNewText(inputText) {
  2222. return inputText;
  2223. }
  2224. getTextForError(newText) {
  2225. return newText;
  2226. }
  2227. }
  2228. class UnwrapTextManipulator extends InsertionTextManipulator {
  2229. constructor(node) {
  2230. super({
  2231. insertPos: node.getStart(true),
  2232. newText: getReplacementText(node),
  2233. replacingLength: node.getWidth(true),
  2234. });
  2235. }
  2236. }
  2237. function getReplacementText(node) {
  2238. const sourceFile = node._sourceFile;
  2239. const range = getInnerBraceRange();
  2240. const startPos = range[0];
  2241. const text = sourceFile.getFullText().substring(range[0], range[1]);
  2242. return common.StringUtils.indent(text, -1, {
  2243. indentText: sourceFile._context.manipulationSettings.getIndentationText(),
  2244. indentSizeInSpaces: sourceFile._context.manipulationSettings._getIndentSizeInSpaces(),
  2245. isInStringAtPos: pos => sourceFile.isInStringAtPos(startPos + pos),
  2246. }).trim();
  2247. function getInnerBraceRange() {
  2248. const bodyNode = getBodyNodeOrThrow();
  2249. return [bodyNode.getStart() + 1, bodyNode.getEnd() - 1];
  2250. function getBodyNodeOrThrow() {
  2251. if (Node.isModuleDeclaration(node)) {
  2252. const bodyNode = node._getInnerBody();
  2253. if (bodyNode == null)
  2254. throw new common.errors.InvalidOperationError("This operation requires the module to have a body.");
  2255. return bodyNode;
  2256. }
  2257. else if (Node.isBodied(node))
  2258. return node.getBody();
  2259. else if (Node.isBodyable(node))
  2260. return node.getBodyOrThrow();
  2261. else
  2262. common.errors.throwNotImplementedForSyntaxKindError(node.getKind(), node);
  2263. }
  2264. }
  2265. }
  2266. class ManipulationError extends common.errors.InvalidOperationError {
  2267. filePath;
  2268. oldText;
  2269. newText;
  2270. constructor(filePath, oldText, newText, errorMessage) {
  2271. super(errorMessage);
  2272. this.filePath = filePath;
  2273. this.oldText = oldText;
  2274. this.newText = newText;
  2275. }
  2276. }
  2277. function doManipulation(sourceFile, textManipulator, nodeHandler, newFilePath) {
  2278. sourceFile._firePreModified();
  2279. const oldFileText = sourceFile.getFullText();
  2280. const newFileText = textManipulator.getNewText(oldFileText);
  2281. try {
  2282. const replacementSourceFile = sourceFile._context.compilerFactory.createCompilerSourceFileFromText(newFilePath || sourceFile.getFilePath(), newFileText, sourceFile.getScriptKind());
  2283. nodeHandler.handleNode(sourceFile, replacementSourceFile, replacementSourceFile);
  2284. }
  2285. catch (err) {
  2286. const diagnostics = getSyntacticDiagnostics(sourceFile, newFileText);
  2287. const errorDetails = err.message + "\n\n"
  2288. + `-- Details --\n`
  2289. + "Path: " + sourceFile.getFilePath() + "\n"
  2290. + "Text: " + JSON.stringify(textManipulator.getTextForError(newFileText)) + "\n"
  2291. + "Stack: " + err.stack;
  2292. if (diagnostics.length > 0) {
  2293. throwError("Manipulation error: " + "A syntax error was inserted." + "\n\n"
  2294. + sourceFile._context.project.formatDiagnosticsWithColorAndContext(diagnostics, { newLineChar: "\n" })
  2295. + "\n" + errorDetails);
  2296. }
  2297. throwError("Manipulation error: " + errorDetails);
  2298. function throwError(message) {
  2299. throw new ManipulationError(sourceFile.getFilePath(), oldFileText, newFileText, message);
  2300. }
  2301. }
  2302. }
  2303. function getSyntacticDiagnostics(sourceFile, newText) {
  2304. try {
  2305. const projectOptions = { useInMemoryFileSystem: true };
  2306. const project = new sourceFile._context.project.constructor(projectOptions);
  2307. const newFile = project.createSourceFile(sourceFile.getFilePath(), newText);
  2308. return project.getProgram().getSyntacticDiagnostics(newFile);
  2309. }
  2310. catch (err) {
  2311. return [];
  2312. }
  2313. }
  2314. function insertIntoParentTextRange(opts) {
  2315. const { insertPos, newText, parent } = opts;
  2316. doManipulation(parent._sourceFile, new InsertionTextManipulator({
  2317. insertPos,
  2318. newText,
  2319. replacingLength: opts.replacing?.textLength,
  2320. }), new NodeHandlerFactory().getForParentRange({
  2321. parent,
  2322. start: insertPos,
  2323. end: insertPos + newText.length,
  2324. replacingLength: opts.replacing?.textLength,
  2325. replacingNodes: opts.replacing?.nodes,
  2326. customMappings: opts.customMappings,
  2327. }));
  2328. }
  2329. function insertIntoTextRange(opts) {
  2330. const { insertPos, newText, sourceFile } = opts;
  2331. doManipulation(sourceFile, new InsertionTextManipulator({
  2332. insertPos,
  2333. newText,
  2334. }), new NodeHandlerFactory().getForRange({
  2335. sourceFile,
  2336. start: insertPos,
  2337. end: insertPos + newText.length,
  2338. }));
  2339. }
  2340. function insertIntoCommaSeparatedNodes(opts) {
  2341. const { currentNodes, insertIndex, parent } = opts;
  2342. const previousNode = currentNodes[insertIndex - 1];
  2343. const previousNonCommentNode = getPreviousNonCommentNode();
  2344. const nextNode = currentNodes[insertIndex];
  2345. const nextNonCommentNode = getNextNonCommentNode();
  2346. const separator = opts.useNewLines ? parent._context.manipulationSettings.getNewLineKindAsString() : " ";
  2347. const parentNextSibling = parent.getNextSibling();
  2348. const isContained = parentNextSibling != null && (parentNextSibling.getKind() === common.SyntaxKind.CloseBraceToken || parentNextSibling.getKind() === common.SyntaxKind.CloseBracketToken);
  2349. let { newText } = opts;
  2350. if (previousNode != null) {
  2351. prependCommaAndSeparator();
  2352. if (nextNonCommentNode != null || opts.useTrailingCommas)
  2353. appendCommaAndSeparator();
  2354. else if (opts.useNewLines || opts.surroundWithSpaces)
  2355. appendSeparator();
  2356. else
  2357. appendIndentation();
  2358. const nextEndStart = nextNode == null ? (isContained ? parentNextSibling.getStart(true) : parent.getEnd()) : nextNode.getStart(true);
  2359. const insertPos = (previousNonCommentNode || previousNode).getEnd();
  2360. insertIntoParentTextRange({
  2361. insertPos,
  2362. newText,
  2363. parent,
  2364. replacing: { textLength: nextEndStart - insertPos },
  2365. });
  2366. }
  2367. else if (nextNode != null) {
  2368. if (opts.useNewLines || opts.surroundWithSpaces)
  2369. prependSeparator();
  2370. if (nextNonCommentNode != null || opts.useTrailingCommas)
  2371. appendCommaAndSeparator();
  2372. else
  2373. appendSeparator();
  2374. const insertPos = isContained ? parent.getPos() : parent.getStart(true);
  2375. insertIntoParentTextRange({
  2376. insertPos,
  2377. newText,
  2378. parent,
  2379. replacing: { textLength: nextNode.getStart(true) - insertPos },
  2380. });
  2381. }
  2382. else {
  2383. if (opts.useNewLines || opts.surroundWithSpaces) {
  2384. prependSeparator();
  2385. if (opts.useTrailingCommas)
  2386. appendCommaAndSeparator();
  2387. else
  2388. appendSeparator();
  2389. }
  2390. else {
  2391. appendIndentation();
  2392. }
  2393. insertIntoParentTextRange({
  2394. insertPos: parent.getPos(),
  2395. newText,
  2396. parent,
  2397. replacing: { textLength: parent.getNextSiblingOrThrow().getStart() - parent.getPos() },
  2398. });
  2399. }
  2400. function prependCommaAndSeparator() {
  2401. if (previousNonCommentNode == null) {
  2402. prependSeparator();
  2403. return;
  2404. }
  2405. const originalSourceFileText = parent.getSourceFile().getFullText();
  2406. const previousNodeNextSibling = previousNonCommentNode.getNextSibling();
  2407. let text = "";
  2408. if (previousNodeNextSibling != null && previousNodeNextSibling.getKind() === common.SyntaxKind.CommaToken) {
  2409. appendNodeTrailingCommentRanges(previousNonCommentNode);
  2410. text += ",";
  2411. if (previousNonCommentNode === previousNode)
  2412. appendNodeTrailingCommentRanges(previousNodeNextSibling);
  2413. else
  2414. appendCommentNodeTexts();
  2415. }
  2416. else {
  2417. text += ",";
  2418. if (previousNonCommentNode === previousNode)
  2419. appendNodeTrailingCommentRanges(previousNonCommentNode);
  2420. else
  2421. appendCommentNodeTexts();
  2422. }
  2423. prependSeparator();
  2424. newText = text + newText;
  2425. function appendCommentNodeTexts() {
  2426. const lastCommentRangeEnd = getLastCommentRangeEnd(previousNode) || previousNode.getEnd();
  2427. text += originalSourceFileText.substring(previousNonCommentNode.getEnd(), lastCommentRangeEnd);
  2428. }
  2429. function appendNodeTrailingCommentRanges(node) {
  2430. const lastCommentRangeEnd = getLastCommentRangeEnd(node);
  2431. if (lastCommentRangeEnd == null)
  2432. return;
  2433. text += originalSourceFileText.substring(node.getEnd(), lastCommentRangeEnd);
  2434. }
  2435. function getLastCommentRangeEnd(node) {
  2436. const commentRanges = node.getTrailingCommentRanges();
  2437. const lastCommentRange = commentRanges[commentRanges.length - 1];
  2438. return lastCommentRange?.getEnd();
  2439. }
  2440. }
  2441. function getPreviousNonCommentNode() {
  2442. for (let i = insertIndex - 1; i >= 0; i--) {
  2443. if (!Node.isCommentNode(currentNodes[i]))
  2444. return currentNodes[i];
  2445. }
  2446. return undefined;
  2447. }
  2448. function getNextNonCommentNode() {
  2449. for (let i = insertIndex; i < currentNodes.length; i++) {
  2450. if (!Node.isCommentNode(currentNodes[i]))
  2451. return currentNodes[i];
  2452. }
  2453. return undefined;
  2454. }
  2455. function prependSeparator() {
  2456. if (!common.StringUtils.startsWithNewLine(newText))
  2457. newText = separator + newText;
  2458. }
  2459. function appendCommaAndSeparator() {
  2460. newText = appendCommaToText(newText);
  2461. appendSeparator();
  2462. }
  2463. function appendSeparator() {
  2464. if (!common.StringUtils.endsWithNewLine(newText))
  2465. newText += separator;
  2466. appendIndentation();
  2467. }
  2468. function appendIndentation() {
  2469. if (opts.useNewLines || common.StringUtils.endsWithNewLine(newText)) {
  2470. if (nextNode != null)
  2471. newText += parent.getParentOrThrow().getChildIndentationText();
  2472. else
  2473. newText += parent.getParentOrThrow().getIndentationText();
  2474. }
  2475. }
  2476. }
  2477. function insertIntoBracesOrSourceFile(opts) {
  2478. const { parent, index, children } = opts;
  2479. const fullText = parent._sourceFile.getFullText();
  2480. const childSyntaxList = parent.getChildSyntaxListOrThrow();
  2481. const insertPos = getInsertPosFromIndex(index, childSyntaxList, children);
  2482. const endPos = getEndPosFromIndex(index, parent, children, fullText);
  2483. const replacingLength = endPos - insertPos;
  2484. const newText = getNewText();
  2485. doManipulation(parent._sourceFile, new InsertionTextManipulator({ insertPos, replacingLength, newText }), new NodeHandlerFactory().getForParentRange({
  2486. parent: childSyntaxList,
  2487. start: insertPos,
  2488. end: insertPos + newText.length,
  2489. replacingLength,
  2490. }));
  2491. function getNewText() {
  2492. const writer = parent._getWriterWithChildIndentation();
  2493. opts.write(writer, {
  2494. previousMember: getChild(children[index - 1]),
  2495. nextMember: getChild(children[index]),
  2496. isStartOfFile: insertPos === 0,
  2497. });
  2498. return writer.toString();
  2499. function getChild(child) {
  2500. if (child == null)
  2501. return child;
  2502. else if (Node.isOverloadable(child))
  2503. return child.getImplementation() || child;
  2504. else
  2505. return child;
  2506. }
  2507. }
  2508. }
  2509. function insertIntoBracesOrSourceFileWithGetChildren(opts) {
  2510. if (opts.structures.length === 0)
  2511. return [];
  2512. const startChildren = opts.getIndexedChildren();
  2513. const parentSyntaxList = opts.parent.getChildSyntaxListOrThrow();
  2514. const index = verifyAndGetIndex(opts.index, startChildren.length);
  2515. const previousJsDocCount = getPreviousJsDocCount();
  2516. insertIntoBracesOrSourceFile({
  2517. parent: opts.parent,
  2518. index: getChildIndex(),
  2519. children: parentSyntaxList.getChildren(),
  2520. write: opts.write,
  2521. });
  2522. return getRangeWithoutCommentsFromArray(opts.getIndexedChildren(), opts.index - previousJsDocCount, opts.structures.length, opts.expectedKind);
  2523. function getChildIndex() {
  2524. if (index === 0)
  2525. return 0;
  2526. return startChildren[index - 1].getChildIndex() + 1;
  2527. }
  2528. function getPreviousJsDocCount() {
  2529. let commentCount = 0;
  2530. let count = 0;
  2531. for (let i = index - 1; i >= 0; i--) {
  2532. const node = startChildren[i];
  2533. if (Node.isCommentNode(node)) {
  2534. commentCount++;
  2535. if (node.getText().startsWith("/**"))
  2536. count = commentCount;
  2537. }
  2538. else {
  2539. break;
  2540. }
  2541. }
  2542. return count;
  2543. }
  2544. }
  2545. function insertIntoBracesOrSourceFileWithGetChildrenWithComments(opts) {
  2546. const startChildren = opts.getIndexedChildren();
  2547. const parentSyntaxList = opts.parent.getChildSyntaxListOrThrow();
  2548. const index = verifyAndGetIndex(opts.index, startChildren.length);
  2549. insertIntoBracesOrSourceFile({
  2550. parent: opts.parent,
  2551. index: getChildIndex(),
  2552. children: parentSyntaxList.getChildren(),
  2553. write: opts.write,
  2554. });
  2555. return getNodesToReturn(startChildren, opts.getIndexedChildren(), index, true);
  2556. function getChildIndex() {
  2557. if (index === 0)
  2558. return 0;
  2559. return startChildren[index - 1].getChildIndex() + 1;
  2560. }
  2561. }
  2562. function changeChildOrder(opts) {
  2563. const { parent } = opts;
  2564. doManipulation(parent._sourceFile, new ChangingChildOrderTextManipulator(opts), new NodeHandlerFactory().getForChangingChildOrder(opts));
  2565. }
  2566. function removeChildren(opts) {
  2567. const { children } = opts;
  2568. if (children.length === 0)
  2569. return;
  2570. doManipulation(children[0].getSourceFile(), new RemoveChildrenTextManipulator(opts), new NodeHandlerFactory().getForChildIndex({
  2571. parent: children[0].getParentSyntaxList() || children[0].getParentOrThrow(),
  2572. childIndex: children[0].getChildIndex(),
  2573. childCount: -1 * children.length,
  2574. }));
  2575. }
  2576. function removeChildrenWithFormattingFromCollapsibleSyntaxList(opts) {
  2577. const { children } = opts;
  2578. if (children.length === 0)
  2579. return;
  2580. const syntaxList = children[0].getParentSyntaxListOrThrow();
  2581. if (syntaxList.getChildCount() === children.length) {
  2582. removeChildrenWithFormatting({
  2583. children: [syntaxList],
  2584. getSiblingFormatting: () => FormattingKind.None,
  2585. });
  2586. }
  2587. else {
  2588. removeChildrenWithFormatting(opts);
  2589. }
  2590. }
  2591. function removeChildrenWithFormatting(opts) {
  2592. const { children, getSiblingFormatting } = opts;
  2593. if (children.length === 0)
  2594. return;
  2595. doManipulation(children[0]._sourceFile, new RemoveChildrenWithFormattingTextManipulator({
  2596. children,
  2597. getSiblingFormatting,
  2598. }), new NodeHandlerFactory().getForChildIndex({
  2599. parent: children[0].getParentSyntaxList() || children[0].getParentOrThrow(),
  2600. childIndex: children[0].getChildIndex(),
  2601. childCount: -1 * children.length,
  2602. }));
  2603. }
  2604. function removeClassMember(classMember) {
  2605. if (Node.isOverloadable(classMember)) {
  2606. if (classMember.isImplementation())
  2607. removeClassMembers([...classMember.getOverloads(), classMember]);
  2608. else {
  2609. const parent = classMember.getParentOrThrow();
  2610. if (Node.isAmbientable(parent) && parent.isAmbient())
  2611. removeClassMembers([classMember]);
  2612. else
  2613. removeChildren({ children: [classMember], removeFollowingSpaces: true, removeFollowingNewLines: true });
  2614. }
  2615. }
  2616. else {
  2617. removeClassMembers([classMember]);
  2618. }
  2619. }
  2620. function removeClassMembers(classMembers) {
  2621. removeChildrenWithFormatting({
  2622. getSiblingFormatting: getClassMemberFormatting,
  2623. children: classMembers,
  2624. });
  2625. }
  2626. function removeInterfaceMember(interfaceMember) {
  2627. removeInterfaceMembers([interfaceMember]);
  2628. }
  2629. function removeInterfaceMembers(interfaceMembers) {
  2630. removeChildrenWithFormatting({
  2631. getSiblingFormatting: getInterfaceMemberFormatting,
  2632. children: interfaceMembers,
  2633. });
  2634. }
  2635. function removeCommaSeparatedChild(child) {
  2636. const childrenToRemove = [child];
  2637. const syntaxList = child.getParentSyntaxListOrThrow();
  2638. const isRemovingFirstChild = childrenToRemove[0] === syntaxList.getFirstChild();
  2639. addNextCommaIfAble();
  2640. addPreviousCommaIfAble();
  2641. removeChildren({
  2642. children: childrenToRemove,
  2643. removePrecedingSpaces: !isRemovingFirstChild || syntaxList.getChildren().length === childrenToRemove.length && childrenToRemove[0].isFirstNodeOnLine(),
  2644. removeFollowingSpaces: isRemovingFirstChild,
  2645. removePrecedingNewLines: !isRemovingFirstChild,
  2646. removeFollowingNewLines: isRemovingFirstChild,
  2647. });
  2648. function addNextCommaIfAble() {
  2649. const commaToken = child.getNextSiblingIfKind(common.SyntaxKind.CommaToken);
  2650. if (commaToken != null)
  2651. childrenToRemove.push(commaToken);
  2652. }
  2653. function addPreviousCommaIfAble() {
  2654. if (syntaxList.getLastChild() !== childrenToRemove[childrenToRemove.length - 1])
  2655. return;
  2656. const precedingComma = child.getPreviousSiblingIfKind(common.SyntaxKind.CommaToken);
  2657. if (precedingComma != null)
  2658. childrenToRemove.unshift(precedingComma);
  2659. }
  2660. }
  2661. function removeOverloadableStatementedNodeChild(node) {
  2662. if (node.isOverload())
  2663. removeChildren({ children: [node], removeFollowingSpaces: true, removeFollowingNewLines: true });
  2664. else
  2665. removeStatementedNodeChildren([...node.getOverloads(), node]);
  2666. }
  2667. function removeStatementedNodeChild(node) {
  2668. removeStatementedNodeChildren([node]);
  2669. }
  2670. function removeStatementedNodeChildren(nodes) {
  2671. removeChildrenWithFormatting({
  2672. getSiblingFormatting: getStatementedNodeChildFormatting,
  2673. children: nodes,
  2674. });
  2675. }
  2676. function removeClausedNodeChild(node) {
  2677. removeClausedNodeChildren([node]);
  2678. }
  2679. function removeClausedNodeChildren(nodes) {
  2680. removeChildrenWithFormatting({
  2681. getSiblingFormatting: getClausedNodeChildFormatting,
  2682. children: nodes,
  2683. });
  2684. }
  2685. function unwrapNode(node) {
  2686. doManipulation(node._sourceFile, new UnwrapTextManipulator(node), new NodeHandlerFactory().getForUnwrappingNode(node));
  2687. }
  2688. function replaceNodeText(opts) {
  2689. doManipulation(opts.sourceFile, new InsertionTextManipulator({
  2690. insertPos: opts.start,
  2691. newText: opts.newText,
  2692. replacingLength: opts.replacingLength,
  2693. }), new NodeHandlerFactory().getForForgetChanged(opts.sourceFile._context.compilerFactory));
  2694. }
  2695. function replaceSourceFileTextForFormatting(opts) {
  2696. replaceSourceFileTextStraight(opts);
  2697. }
  2698. function replaceSourceFileTextStraight(opts) {
  2699. const { sourceFile, newText } = opts;
  2700. doManipulation(sourceFile, new FullReplacementTextManipulator(newText), new NodeHandlerFactory().getForStraightReplacement(sourceFile._context.compilerFactory));
  2701. }
  2702. function replaceSourceFileTextForRename(opts) {
  2703. const { sourceFile, renameLocations, newName } = opts;
  2704. const nodeHandlerFactory = new NodeHandlerFactory();
  2705. doManipulation(sourceFile, new RenameLocationTextManipulator(renameLocations, newName), nodeHandlerFactory.getForTryOrForget(nodeHandlerFactory.getForRename(sourceFile._context.compilerFactory)));
  2706. }
  2707. function replaceTextPossiblyCreatingChildNodes(opts) {
  2708. const { replacePos, replacingLength, newText, parent } = opts;
  2709. doManipulation(parent._sourceFile, new InsertionTextManipulator({
  2710. insertPos: replacePos,
  2711. replacingLength,
  2712. newText,
  2713. }), new NodeHandlerFactory().getForParentRange({
  2714. parent,
  2715. start: replacePos,
  2716. end: replacePos + newText.length,
  2717. }));
  2718. }
  2719. function replaceSourceFileForFilePathMove(opts) {
  2720. const { sourceFile, newFilePath } = opts;
  2721. doManipulation(sourceFile, new UnchangedTextManipulator(), new NodeHandlerFactory().getForStraightReplacement(sourceFile._context.compilerFactory), newFilePath);
  2722. }
  2723. function replaceSourceFileForCacheUpdate(sourceFile) {
  2724. replaceSourceFileForFilePathMove({ sourceFile, newFilePath: sourceFile.getFilePath() });
  2725. }
  2726. function ArgumentedNode(Base) {
  2727. return class extends Base {
  2728. getArguments() {
  2729. return this.compilerNode.arguments?.map(a => this._getNodeFromCompilerNode(a)) ?? [];
  2730. }
  2731. addArgument(argumentText) {
  2732. return this.addArguments([argumentText])[0];
  2733. }
  2734. addArguments(argumentTexts) {
  2735. return this.insertArguments(this.getArguments().length, argumentTexts);
  2736. }
  2737. insertArgument(index, argumentText) {
  2738. return this.insertArguments(index, [argumentText])[0];
  2739. }
  2740. insertArguments(index, argumentTexts) {
  2741. if (argumentTexts instanceof Function)
  2742. argumentTexts = [argumentTexts];
  2743. if (common.ArrayUtils.isNullOrEmpty(argumentTexts))
  2744. return [];
  2745. this._addParensIfNecessary();
  2746. const originalArgs = this.getArguments();
  2747. index = verifyAndGetIndex(index, originalArgs.length);
  2748. const writer = this._getWriterWithQueuedChildIndentation();
  2749. for (let i = 0; i < argumentTexts.length; i++) {
  2750. writer.conditionalWrite(i > 0, ", ");
  2751. printTextFromStringOrWriter(writer, argumentTexts[i]);
  2752. }
  2753. insertIntoCommaSeparatedNodes({
  2754. parent: this.getFirstChildByKindOrThrow(common.SyntaxKind.OpenParenToken).getNextSiblingIfKindOrThrow(common.SyntaxKind.SyntaxList),
  2755. currentNodes: originalArgs,
  2756. insertIndex: index,
  2757. newText: writer.toString(),
  2758. useTrailingCommas: false,
  2759. });
  2760. return getNodesToReturn(originalArgs, this.getArguments(), index, false);
  2761. }
  2762. removeArgument(argOrIndex) {
  2763. const args = this.getArguments();
  2764. if (args.length === 0)
  2765. throw new common.errors.InvalidOperationError("Cannot remove an argument when none exist.");
  2766. const argToRemove = typeof argOrIndex === "number" ? getArgFromIndex(argOrIndex) : argOrIndex;
  2767. removeCommaSeparatedChild(argToRemove);
  2768. return this;
  2769. function getArgFromIndex(index) {
  2770. return args[verifyAndGetIndex(index, args.length - 1)];
  2771. }
  2772. }
  2773. _addParensIfNecessary() {
  2774. const fullText = this.getFullText();
  2775. if (fullText[fullText.length - 1] !== ")") {
  2776. insertIntoParentTextRange({
  2777. insertPos: this.getEnd(),
  2778. newText: "()",
  2779. parent: this,
  2780. });
  2781. }
  2782. }
  2783. };
  2784. }
  2785. function AsyncableNode(Base) {
  2786. return class extends Base {
  2787. isAsync() {
  2788. return this.hasModifier(common.SyntaxKind.AsyncKeyword);
  2789. }
  2790. getAsyncKeyword() {
  2791. return this.getFirstModifierByKind(common.SyntaxKind.AsyncKeyword);
  2792. }
  2793. getAsyncKeywordOrThrow(message) {
  2794. return common.errors.throwIfNullOrUndefined(this.getAsyncKeyword(), message ?? "Expected to find an async keyword.", this);
  2795. }
  2796. setIsAsync(value) {
  2797. this.toggleModifier("async", value);
  2798. return this;
  2799. }
  2800. set(structure) {
  2801. callBaseSet(Base.prototype, this, structure);
  2802. if (structure.isAsync != null)
  2803. this.setIsAsync(structure.isAsync);
  2804. return this;
  2805. }
  2806. getStructure() {
  2807. return callBaseGetStructure(Base.prototype, this, {
  2808. isAsync: this.isAsync(),
  2809. });
  2810. }
  2811. };
  2812. }
  2813. function AwaitableNode(Base) {
  2814. return class extends Base {
  2815. isAwaited() {
  2816. return this.compilerNode.awaitModifier != null;
  2817. }
  2818. getAwaitKeyword() {
  2819. const awaitModifier = this.compilerNode.awaitModifier;
  2820. return this._getNodeFromCompilerNodeIfExists(awaitModifier);
  2821. }
  2822. getAwaitKeywordOrThrow(message) {
  2823. return common.errors.throwIfNullOrUndefined(this.getAwaitKeyword(), message ?? "Expected to find an await token.");
  2824. }
  2825. setIsAwaited(value) {
  2826. const awaitModifier = this.getAwaitKeyword();
  2827. const isSet = awaitModifier != null;
  2828. if (isSet === value)
  2829. return this;
  2830. if (awaitModifier == null) {
  2831. insertIntoParentTextRange({
  2832. insertPos: getAwaitInsertPos(this),
  2833. parent: this,
  2834. newText: " await",
  2835. });
  2836. }
  2837. else {
  2838. removeChildren({
  2839. children: [awaitModifier],
  2840. removePrecedingSpaces: true,
  2841. });
  2842. }
  2843. return this;
  2844. }
  2845. set(structure) {
  2846. callBaseSet(Base.prototype, this, structure);
  2847. if (structure.isAwaited != null)
  2848. this.setIsAwaited(structure.isAwaited);
  2849. return this;
  2850. }
  2851. };
  2852. }
  2853. function getAwaitInsertPos(node) {
  2854. if (node.getKind() === common.SyntaxKind.ForOfStatement)
  2855. return node.getFirstChildByKindOrThrow(common.SyntaxKind.ForKeyword).getEnd();
  2856. throw new common.errors.NotImplementedError("Expected a for of statement node.");
  2857. }
  2858. function getBodyText(writer, textOrWriterFunction) {
  2859. writer.newLineIfLastNot();
  2860. if (typeof textOrWriterFunction !== "string" || textOrWriterFunction.length > 0) {
  2861. writer.indent(() => {
  2862. printTextFromStringOrWriter(writer, textOrWriterFunction);
  2863. });
  2864. }
  2865. writer.newLineIfLastNot();
  2866. writer.write("");
  2867. return writer.toString();
  2868. }
  2869. function getBodyTextWithoutLeadingIndentation(body) {
  2870. const sourceFile = body._sourceFile;
  2871. const textArea = body.getChildSyntaxList() || body;
  2872. const startPos = textArea.getNonWhitespaceStart();
  2873. const endPos = Math.max(startPos, textArea._getTrailingTriviaNonWhitespaceEnd());
  2874. const width = endPos - startPos;
  2875. if (width === 0)
  2876. return "";
  2877. const fullText = sourceFile.getFullText().substring(startPos, endPos);
  2878. return common.StringUtils.removeIndentation(fullText, {
  2879. indentSizeInSpaces: body._context.manipulationSettings._getIndentSizeInSpaces(),
  2880. isInStringAtPos: pos => sourceFile.isInStringAtPos(pos + startPos),
  2881. });
  2882. }
  2883. class TextRange {
  2884. #compilerObject;
  2885. #sourceFile;
  2886. constructor(compilerObject, sourceFile) {
  2887. this.#compilerObject = compilerObject;
  2888. this.#sourceFile = sourceFile;
  2889. }
  2890. get compilerObject() {
  2891. this.#throwIfForgotten();
  2892. return this.#compilerObject;
  2893. }
  2894. getSourceFile() {
  2895. this.#throwIfForgotten();
  2896. return this.#sourceFile;
  2897. }
  2898. getPos() {
  2899. return this.compilerObject.pos;
  2900. }
  2901. getEnd() {
  2902. return this.compilerObject.end;
  2903. }
  2904. getWidth() {
  2905. return this.getEnd() - this.getPos();
  2906. }
  2907. getText() {
  2908. const fullText = this.getSourceFile().getFullText();
  2909. return fullText.substring(this.compilerObject.pos, this.compilerObject.end);
  2910. }
  2911. _forget() {
  2912. this.#compilerObject = undefined;
  2913. this.#sourceFile = undefined;
  2914. }
  2915. wasForgotten() {
  2916. return this.#compilerObject == null;
  2917. }
  2918. #throwIfForgotten() {
  2919. if (this.#compilerObject != null)
  2920. return;
  2921. const message = "Attempted to get a text range that was forgotten. "
  2922. + "Text ranges are forgotten after a manipulation has occurred. "
  2923. + "Please re-request the text range after manipulations.";
  2924. throw new common.errors.InvalidOperationError(message);
  2925. }
  2926. }
  2927. class CommentRange extends TextRange {
  2928. constructor(compilerObject, sourceFile) {
  2929. super(compilerObject, sourceFile);
  2930. }
  2931. getKind() {
  2932. return this.compilerObject.kind;
  2933. }
  2934. }
  2935. class Node {
  2936. #compilerNode;
  2937. #forgottenText;
  2938. #childStringRanges;
  2939. #leadingCommentRanges;
  2940. #trailingCommentRanges;
  2941. _wrappedChildCount = 0;
  2942. _context;
  2943. __sourceFile;
  2944. get _sourceFile() {
  2945. if (this.__sourceFile == null)
  2946. throw new common.errors.InvalidOperationError("Operation cannot be performed on a node that has no source file.");
  2947. return this.__sourceFile;
  2948. }
  2949. get compilerNode() {
  2950. if (this.#compilerNode == null) {
  2951. let message = "Attempted to get information from a node that was removed or forgotten.";
  2952. if (this.#forgottenText != null)
  2953. message += `\n\nNode text: ${this.#forgottenText}`;
  2954. throw new common.errors.InvalidOperationError(message);
  2955. }
  2956. return this.#compilerNode;
  2957. }
  2958. constructor(context, node, sourceFile) {
  2959. if (context == null || context.compilerFactory == null) {
  2960. throw new common.errors.InvalidOperationError("Constructing a node is not supported. Please create a source file from the default export "
  2961. + "of the package and manipulate the source file from there.");
  2962. }
  2963. this._context = context;
  2964. this.#compilerNode = node;
  2965. this.__sourceFile = sourceFile;
  2966. }
  2967. forget() {
  2968. if (this.wasForgotten())
  2969. return;
  2970. this.forgetDescendants();
  2971. this._forgetOnlyThis();
  2972. }
  2973. forgetDescendants() {
  2974. for (const child of this._getChildrenInCacheIterator())
  2975. child.forget();
  2976. }
  2977. _forgetOnlyThis() {
  2978. if (this.wasForgotten())
  2979. return;
  2980. const parent = this.getParent();
  2981. if (parent != null)
  2982. parent._wrappedChildCount--;
  2983. this.#storeTextForForgetting();
  2984. this._context.compilerFactory.removeNodeFromCache(this);
  2985. this._clearInternals();
  2986. }
  2987. wasForgotten() {
  2988. return this.#compilerNode == null;
  2989. }
  2990. _hasWrappedChildren() {
  2991. return this._wrappedChildCount > 0 || this.#compilerNode?.kind === common.SyntaxKind.SyntaxList;
  2992. }
  2993. _replaceCompilerNodeFromFactory(compilerNode) {
  2994. if (compilerNode == null)
  2995. this.#storeTextForForgetting();
  2996. this._clearInternals();
  2997. this.#compilerNode = compilerNode;
  2998. }
  2999. #storeTextForForgetting() {
  3000. const sourceFileCompilerNode = this._sourceFile && this._sourceFile.compilerNode;
  3001. const compilerNode = this.#compilerNode;
  3002. if (sourceFileCompilerNode == null || compilerNode == null)
  3003. return;
  3004. this.#forgottenText = getText();
  3005. function getText() {
  3006. const start = compilerNode.getStart(sourceFileCompilerNode);
  3007. const length = compilerNode.end - start;
  3008. const trimmedLength = Math.min(length, 100);
  3009. const text = sourceFileCompilerNode.text.substr(start, trimmedLength);
  3010. return trimmedLength !== length ? text + "..." : text;
  3011. }
  3012. }
  3013. _clearInternals() {
  3014. this.#compilerNode = undefined;
  3015. this.#childStringRanges = undefined;
  3016. clearTextRanges(this.#leadingCommentRanges);
  3017. clearTextRanges(this.#trailingCommentRanges);
  3018. this.#leadingCommentRanges = undefined;
  3019. this.#trailingCommentRanges = undefined;
  3020. function clearTextRanges(textRanges) {
  3021. if (textRanges == null)
  3022. return;
  3023. textRanges.forEach(r => r._forget());
  3024. }
  3025. }
  3026. getKind() {
  3027. return this.compilerNode.kind;
  3028. }
  3029. getKindName() {
  3030. return common.getSyntaxKindName(this.compilerNode.kind);
  3031. }
  3032. getFlags() {
  3033. return this.compilerNode.flags;
  3034. }
  3035. print(options = {}) {
  3036. if (options.newLineKind == null)
  3037. options.newLineKind = this._context.manipulationSettings.getNewLineKind();
  3038. if (this.getKind() === common.SyntaxKind.SourceFile)
  3039. return printNode(this.compilerNode, options);
  3040. else
  3041. return printNode(this.compilerNode, this._sourceFile.compilerNode, options);
  3042. }
  3043. getSymbolOrThrow(message) {
  3044. return common.errors.throwIfNullOrUndefined(this.getSymbol(), message ?? "Could not find the node's symbol.", this);
  3045. }
  3046. getSymbol() {
  3047. const boundSymbol = this.compilerNode.symbol;
  3048. if (boundSymbol != null)
  3049. return this._context.compilerFactory.getSymbol(boundSymbol);
  3050. const typeChecker = this._context.typeChecker;
  3051. const typeCheckerSymbol = typeChecker.getSymbolAtLocation(this);
  3052. if (typeCheckerSymbol != null)
  3053. return typeCheckerSymbol;
  3054. const nameNode = this.compilerNode.name;
  3055. if (nameNode != null)
  3056. return this._getNodeFromCompilerNode(nameNode).getSymbol();
  3057. return undefined;
  3058. }
  3059. getSymbolsInScope(meaning) {
  3060. return this._context.typeChecker.getSymbolsInScope(this, meaning);
  3061. }
  3062. getLocalOrThrow(name, message) {
  3063. return common.errors.throwIfNullOrUndefined(this.getLocal(name), message ?? (() => `Expected to find local symbol with name: ${name}`), this);
  3064. }
  3065. getLocal(name) {
  3066. const locals = this.#getCompilerLocals();
  3067. if (locals == null)
  3068. return undefined;
  3069. const tsSymbol = locals.get(common.ts.escapeLeadingUnderscores(name));
  3070. return tsSymbol == null ? undefined : this._context.compilerFactory.getSymbol(tsSymbol);
  3071. }
  3072. getLocals() {
  3073. const locals = this.#getCompilerLocals();
  3074. if (locals == null)
  3075. return [];
  3076. return Array.from(locals.values()).map(symbol => this._context.compilerFactory.getSymbol(symbol));
  3077. }
  3078. #getCompilerLocals() {
  3079. this._ensureBound();
  3080. return this.compilerNode.locals;
  3081. }
  3082. getType() {
  3083. return this._context.typeChecker.getTypeAtLocation(this);
  3084. }
  3085. containsRange(pos, end) {
  3086. return this.getPos() <= pos && end <= this.getEnd();
  3087. }
  3088. isInStringAtPos(pos) {
  3089. common.errors.throwIfOutOfRange(pos, [this.getPos(), this.getEnd()], "pos");
  3090. if (this.#childStringRanges == null) {
  3091. this.#childStringRanges = [];
  3092. for (const descendant of this._getCompilerDescendantsIterator()) {
  3093. if (isStringKind(descendant.kind))
  3094. this.#childStringRanges.push([descendant.getStart(this._sourceFile.compilerNode), descendant.getEnd()]);
  3095. }
  3096. }
  3097. class InStringRangeComparer {
  3098. compareTo(value) {
  3099. if (pos <= value[0])
  3100. return -1;
  3101. if (pos >= value[1] - 1)
  3102. return 1;
  3103. return 0;
  3104. }
  3105. }
  3106. return common.ArrayUtils.binarySearch(this.#childStringRanges, new InStringRangeComparer()) !== -1;
  3107. }
  3108. asKindOrThrow(kind, message) {
  3109. return common.errors.throwIfNullOrUndefined(this.asKind(kind), message ?? (() => `Expected the node to be of kind ${common.getSyntaxKindName(kind)}, but it was ${common.getSyntaxKindName(this.getKind())}.`), this);
  3110. }
  3111. isKind(kind) {
  3112. return this.getKind() === kind;
  3113. }
  3114. asKind(kind) {
  3115. if (this.isKind(kind))
  3116. return this;
  3117. else
  3118. return undefined;
  3119. }
  3120. getFirstChildOrThrow(condition, message) {
  3121. return common.errors.throwIfNullOrUndefined(this.getFirstChild(condition), message ?? "Could not find a child that matched the specified condition.", this);
  3122. }
  3123. getFirstChild(condition) {
  3124. const firstChild = this._getCompilerFirstChild(getWrappedCondition(this, condition));
  3125. return this._getNodeFromCompilerNodeIfExists(firstChild);
  3126. }
  3127. getLastChildOrThrow(condition, message) {
  3128. return common.errors.throwIfNullOrUndefined(this.getLastChild(condition), message ?? "Could not find a child that matched the specified condition.", this);
  3129. }
  3130. getLastChild(condition) {
  3131. const lastChild = this._getCompilerLastChild(getWrappedCondition(this, condition));
  3132. return this._getNodeFromCompilerNodeIfExists(lastChild);
  3133. }
  3134. getFirstDescendantOrThrow(condition, message) {
  3135. return common.errors.throwIfNullOrUndefined(this.getFirstDescendant(condition), message ?? "Could not find a descendant that matched the specified condition.", this);
  3136. }
  3137. getFirstDescendant(condition) {
  3138. for (const descendant of this._getDescendantsIterator()) {
  3139. if (condition == null || condition(descendant))
  3140. return descendant;
  3141. }
  3142. return undefined;
  3143. }
  3144. getPreviousSiblingOrThrow(condition, message) {
  3145. return common.errors.throwIfNullOrUndefined(this.getPreviousSibling(condition), message ?? "Could not find the previous sibling.", this);
  3146. }
  3147. getPreviousSibling(condition) {
  3148. const previousSibling = this._getCompilerPreviousSibling(getWrappedCondition(this, condition));
  3149. return this._getNodeFromCompilerNodeIfExists(previousSibling);
  3150. }
  3151. getNextSiblingOrThrow(condition, message) {
  3152. return common.errors.throwIfNullOrUndefined(this.getNextSibling(condition), message ?? "Could not find the next sibling.", this);
  3153. }
  3154. getNextSibling(condition) {
  3155. const nextSibling = this._getCompilerNextSibling(getWrappedCondition(this, condition));
  3156. return this._getNodeFromCompilerNodeIfExists(nextSibling);
  3157. }
  3158. getPreviousSiblings() {
  3159. return this._getCompilerPreviousSiblings().map(n => this._getNodeFromCompilerNode(n));
  3160. }
  3161. getNextSiblings() {
  3162. return this._getCompilerNextSiblings().map(n => this._getNodeFromCompilerNode(n));
  3163. }
  3164. getChildren() {
  3165. return this._getCompilerChildren().map(n => this._getNodeFromCompilerNode(n));
  3166. }
  3167. getChildAtIndex(index) {
  3168. return this._getNodeFromCompilerNode(this._getCompilerChildAtIndex(index));
  3169. }
  3170. *_getChildrenIterator() {
  3171. for (const compilerChild of this._getCompilerChildren())
  3172. yield this._getNodeFromCompilerNode(compilerChild);
  3173. }
  3174. *_getChildrenInCacheIterator() {
  3175. const children = this._getCompilerChildrenFast();
  3176. for (const child of children) {
  3177. if (this._context.compilerFactory.hasCompilerNode(child))
  3178. yield this._context.compilerFactory.getExistingNodeFromCompilerNode(child);
  3179. else if (child.kind === common.SyntaxKind.SyntaxList) {
  3180. yield this._getNodeFromCompilerNode(child);
  3181. }
  3182. }
  3183. }
  3184. getChildSyntaxListOrThrow(message) {
  3185. return common.errors.throwIfNullOrUndefined(this.getChildSyntaxList(), message ?? "A child syntax list was expected.", this);
  3186. }
  3187. getChildSyntaxList() {
  3188. let node = this;
  3189. if (Node.isBodyable(node) || Node.isBodied(node)) {
  3190. do {
  3191. const bodyNode = Node.isBodyable(node) ? node.getBody() : node.getBody();
  3192. if (bodyNode == null)
  3193. return undefined;
  3194. node = bodyNode;
  3195. } while ((Node.isBodyable(node) || Node.isBodied(node)) && node.compilerNode.statements == null);
  3196. }
  3197. if (Node.isSourceFile(node)
  3198. || Node.isBodyable(this)
  3199. || Node.isBodied(this)
  3200. || Node.isCaseBlock(this)
  3201. || Node.isCaseClause(this)
  3202. || Node.isDefaultClause(this)
  3203. || Node.isJsxElement(this)) {
  3204. return node.getFirstChildByKind(common.SyntaxKind.SyntaxList);
  3205. }
  3206. let passedBrace = false;
  3207. for (const child of node._getCompilerChildren()) {
  3208. if (!passedBrace)
  3209. passedBrace = child.kind === common.SyntaxKind.OpenBraceToken;
  3210. else if (child.kind === common.SyntaxKind.SyntaxList)
  3211. return this._getNodeFromCompilerNode(child);
  3212. }
  3213. return undefined;
  3214. }
  3215. forEachChild(cbNode, cbNodeArray) {
  3216. const snapshots = [];
  3217. this.compilerNode.forEachChild(node => {
  3218. snapshots.push(this._getNodeFromCompilerNode(node));
  3219. }, cbNodeArray == null ? undefined : nodes => {
  3220. snapshots.push(nodes.map(n => this._getNodeFromCompilerNode(n)));
  3221. });
  3222. for (const snapshot of snapshots) {
  3223. if (snapshot instanceof Array) {
  3224. const filteredNodes = snapshot.filter(n => !n.wasForgotten());
  3225. if (filteredNodes.length > 0) {
  3226. const returnValue = cbNodeArray(filteredNodes);
  3227. if (returnValue)
  3228. return returnValue;
  3229. }
  3230. }
  3231. else if (!snapshot.wasForgotten()) {
  3232. const returnValue = cbNode(snapshot);
  3233. if (returnValue)
  3234. return returnValue;
  3235. }
  3236. }
  3237. return undefined;
  3238. }
  3239. forEachDescendant(cbNode, cbNodeArray) {
  3240. const stopReturnValue = {};
  3241. const upReturnValue = {};
  3242. let stop = false;
  3243. let up = false;
  3244. const traversal = {
  3245. stop: () => stop = true,
  3246. up: () => up = true,
  3247. };
  3248. const nodeCallback = (node) => {
  3249. if (stop)
  3250. return stopReturnValue;
  3251. let skip = false;
  3252. const returnValue = cbNode(node, {
  3253. ...traversal,
  3254. skip: () => skip = true,
  3255. });
  3256. if (returnValue)
  3257. return returnValue;
  3258. if (stop)
  3259. return stopReturnValue;
  3260. if (skip || up)
  3261. return undefined;
  3262. if (!node.wasForgotten())
  3263. return forEachChildForNode(node);
  3264. return undefined;
  3265. };
  3266. const arrayCallback = cbNodeArray == null ? undefined : (nodes) => {
  3267. if (stop)
  3268. return stopReturnValue;
  3269. let skip = false;
  3270. const returnValue = cbNodeArray(nodes, {
  3271. ...traversal,
  3272. skip: () => skip = true,
  3273. });
  3274. if (returnValue)
  3275. return returnValue;
  3276. if (skip)
  3277. return undefined;
  3278. for (const node of nodes) {
  3279. if (stop)
  3280. return stopReturnValue;
  3281. if (up)
  3282. return undefined;
  3283. const innerReturnValue = forEachChildForNode(node);
  3284. if (innerReturnValue)
  3285. return innerReturnValue;
  3286. }
  3287. return undefined;
  3288. };
  3289. const finalResult = forEachChildForNode(this);
  3290. return finalResult === stopReturnValue ? undefined : finalResult;
  3291. function forEachChildForNode(node) {
  3292. const result = node.forEachChild(innerNode => {
  3293. const returnValue = nodeCallback(innerNode);
  3294. if (up) {
  3295. up = false;
  3296. return returnValue || upReturnValue;
  3297. }
  3298. return returnValue;
  3299. }, arrayCallback == null ? undefined : nodes => {
  3300. const returnValue = arrayCallback(nodes);
  3301. if (up) {
  3302. up = false;
  3303. return returnValue || upReturnValue;
  3304. }
  3305. return returnValue;
  3306. });
  3307. return result === upReturnValue ? undefined : result;
  3308. }
  3309. }
  3310. forEachChildAsArray() {
  3311. const children = [];
  3312. this.compilerNode.forEachChild(child => {
  3313. children.push(this._getNodeFromCompilerNode(child));
  3314. });
  3315. return children;
  3316. }
  3317. forEachDescendantAsArray() {
  3318. const descendants = [];
  3319. this.forEachDescendant(descendant => {
  3320. descendants.push(descendant);
  3321. });
  3322. return descendants;
  3323. }
  3324. getDescendants() {
  3325. return Array.from(this._getDescendantsIterator());
  3326. }
  3327. *_getDescendantsIterator() {
  3328. for (const descendant of this._getCompilerDescendantsIterator())
  3329. yield this._getNodeFromCompilerNode(descendant);
  3330. }
  3331. getDescendantStatements() {
  3332. const statements = [];
  3333. handleNode(this, this.compilerNode);
  3334. return statements;
  3335. function handleNode(thisNode, node) {
  3336. if (handleStatements(thisNode, node))
  3337. return;
  3338. else if (node.kind === common.SyntaxKind.ArrowFunction) {
  3339. const arrowFunction = node;
  3340. if (arrowFunction.body.kind !== common.SyntaxKind.Block)
  3341. statements.push(thisNode._getNodeFromCompilerNode(arrowFunction.body));
  3342. else
  3343. handleNode(thisNode, arrowFunction.body);
  3344. }
  3345. else {
  3346. handleChildren(thisNode, node);
  3347. }
  3348. }
  3349. function handleStatements(thisNode, node) {
  3350. if (node.statements == null)
  3351. return false;
  3352. const statementedNode = thisNode._getNodeFromCompilerNode(node);
  3353. for (const statement of statementedNode.getStatements()) {
  3354. statements.push(statement);
  3355. handleChildren(thisNode, statement.compilerNode);
  3356. }
  3357. return true;
  3358. }
  3359. function handleChildren(thisNode, node) {
  3360. common.ts.forEachChild(node, childNode => handleNode(thisNode, childNode));
  3361. }
  3362. }
  3363. getChildCount() {
  3364. return this._getCompilerChildren().length;
  3365. }
  3366. getChildAtPos(pos) {
  3367. if (pos < this.getPos() || pos >= this.getEnd())
  3368. return undefined;
  3369. for (const child of this._getCompilerChildren()) {
  3370. if (pos >= child.pos && pos < child.end)
  3371. return this._getNodeFromCompilerNode(child);
  3372. }
  3373. return undefined;
  3374. }
  3375. getDescendantAtPos(pos) {
  3376. let node;
  3377. while (true) {
  3378. const nextNode = (node || this).getChildAtPos(pos);
  3379. if (nextNode == null)
  3380. return node;
  3381. else
  3382. node = nextNode;
  3383. }
  3384. }
  3385. getDescendantAtStartWithWidth(start, width) {
  3386. let foundNode;
  3387. this._context.compilerFactory.forgetNodesCreatedInBlock(remember => {
  3388. let nextNode = this.getSourceFile();
  3389. do {
  3390. nextNode = nextNode.getChildAtPos(start);
  3391. if (nextNode != null) {
  3392. if (nextNode.getStart() === start && nextNode.getWidth() === width)
  3393. foundNode = nextNode;
  3394. else if (foundNode != null)
  3395. break;
  3396. }
  3397. } while (nextNode != null);
  3398. if (foundNode != null)
  3399. remember(foundNode);
  3400. });
  3401. return foundNode;
  3402. }
  3403. getPos() {
  3404. return this.compilerNode.pos;
  3405. }
  3406. getEnd() {
  3407. return this.compilerNode.end;
  3408. }
  3409. getStart(includeJsDocComments) {
  3410. return this.compilerNode.getStart(this._sourceFile.compilerNode, includeJsDocComments);
  3411. }
  3412. getFullStart() {
  3413. return this.compilerNode.getFullStart();
  3414. }
  3415. getNonWhitespaceStart() {
  3416. return this._context.compilerFactory.forgetNodesCreatedInBlock(() => {
  3417. const parent = this.getParent();
  3418. const pos = this.getPos();
  3419. const parentTakesPrecedence = parent != null
  3420. && !Node.isSourceFile(parent)
  3421. && parent.getPos() === pos;
  3422. if (parentTakesPrecedence)
  3423. return this.getStart(true);
  3424. let startSearchPos;
  3425. const sourceFileFullText = this._sourceFile.getFullText();
  3426. const previousSibling = this.getPreviousSibling();
  3427. if (previousSibling != null && Node.isCommentNode(previousSibling))
  3428. startSearchPos = previousSibling.getEnd();
  3429. else if (previousSibling != null) {
  3430. if (hasNewLineInRange(sourceFileFullText, [pos, this.getStart(true)]))
  3431. startSearchPos = previousSibling.getTrailingTriviaEnd();
  3432. else
  3433. startSearchPos = pos;
  3434. }
  3435. else {
  3436. startSearchPos = this.getPos();
  3437. }
  3438. return getNextNonWhitespacePos(sourceFileFullText, startSearchPos);
  3439. });
  3440. }
  3441. _getTrailingTriviaNonWhitespaceEnd() {
  3442. return getPreviousNonWhitespacePos(this._sourceFile.getFullText(), this.getTrailingTriviaEnd());
  3443. }
  3444. getWidth(includeJsDocComments) {
  3445. return this.getEnd() - this.getStart(includeJsDocComments);
  3446. }
  3447. getFullWidth() {
  3448. return this.compilerNode.getFullWidth();
  3449. }
  3450. getLeadingTriviaWidth() {
  3451. return this.compilerNode.getLeadingTriviaWidth(this._sourceFile.compilerNode);
  3452. }
  3453. getTrailingTriviaWidth() {
  3454. return this.getTrailingTriviaEnd() - this.getEnd();
  3455. }
  3456. getTrailingTriviaEnd() {
  3457. const parent = this.getParent();
  3458. const end = this.getEnd();
  3459. if (parent == null)
  3460. return end;
  3461. const parentEnd = parent.getEnd();
  3462. if (parentEnd === end)
  3463. return end;
  3464. const trailingComments = this.getTrailingCommentRanges();
  3465. const searchStart = getSearchStart();
  3466. return getNextMatchingPos(this._sourceFile.getFullText(), searchStart, char => char !== CharCodes.SPACE && char !== CharCodes.TAB);
  3467. function getSearchStart() {
  3468. return trailingComments.length > 0 ? trailingComments[trailingComments.length - 1].getEnd() : end;
  3469. }
  3470. }
  3471. getText(includeJsDocCommentOrOptions) {
  3472. const options = typeof includeJsDocCommentOrOptions === "object" ? includeJsDocCommentOrOptions : undefined;
  3473. const includeJsDocComments = includeJsDocCommentOrOptions === true || (options != null && options.includeJsDocComments);
  3474. const trimLeadingIndentation = options != null && options.trimLeadingIndentation;
  3475. const startPos = this.getStart(includeJsDocComments);
  3476. const text = this._sourceFile.getFullText().substring(startPos, this.getEnd());
  3477. if (trimLeadingIndentation) {
  3478. return common.StringUtils.removeIndentation(text, {
  3479. isInStringAtPos: pos => this._sourceFile.isInStringAtPos(pos + startPos),
  3480. indentSizeInSpaces: this._context.manipulationSettings._getIndentSizeInSpaces(),
  3481. });
  3482. }
  3483. else {
  3484. return text;
  3485. }
  3486. }
  3487. getFullText() {
  3488. return this.compilerNode.getFullText(this._sourceFile.compilerNode);
  3489. }
  3490. getCombinedModifierFlags() {
  3491. return common.ts.getCombinedModifierFlags(this.compilerNode);
  3492. }
  3493. getSourceFile() {
  3494. return this._sourceFile;
  3495. }
  3496. getProject() {
  3497. return this._context.project;
  3498. }
  3499. getNodeProperty(propertyName) {
  3500. const property = this.compilerNode[propertyName];
  3501. if (property == null)
  3502. return undefined;
  3503. else if (property instanceof Array)
  3504. return property.map(p => isNode(p) ? this._getNodeFromCompilerNode(p) : p);
  3505. else if (isNode(property))
  3506. return this._getNodeFromCompilerNode(property);
  3507. else
  3508. return property;
  3509. function isNode(value) {
  3510. return typeof value.kind === "number" && typeof value.pos === "number" && typeof value.end === "number";
  3511. }
  3512. }
  3513. getAncestors(includeSyntaxLists = false) {
  3514. return Array.from(this._getAncestorsIterator(includeSyntaxLists));
  3515. }
  3516. *_getAncestorsIterator(includeSyntaxLists) {
  3517. let parent = getParent(this);
  3518. while (parent != null) {
  3519. yield parent;
  3520. parent = getParent(parent);
  3521. }
  3522. function getParent(node) {
  3523. return includeSyntaxLists ? node.getParentSyntaxList() || node.getParent() : node.getParent();
  3524. }
  3525. }
  3526. getParent() {
  3527. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.parent);
  3528. }
  3529. getParentOrThrow(message) {
  3530. return common.errors.throwIfNullOrUndefined(this.getParent(), message ?? "Expected to find a parent.", this);
  3531. }
  3532. getParentWhileOrThrow(condition, message) {
  3533. return common.errors.throwIfNullOrUndefined(this.getParentWhile(condition), message ?? "The initial parent did not match the provided condition.", this);
  3534. }
  3535. getParentWhile(condition) {
  3536. let node = undefined;
  3537. let parent = this.getParent();
  3538. while (parent && condition(parent, node || this)) {
  3539. node = parent;
  3540. parent = node.getParent();
  3541. }
  3542. return node;
  3543. }
  3544. getParentWhileKindOrThrow(kind, message) {
  3545. return common.errors.throwIfNullOrUndefined(this.getParentWhileKind(kind), message ?? (() => `The initial parent was not a syntax kind of ${common.getSyntaxKindName(kind)}.`), this);
  3546. }
  3547. getParentWhileKind(kind) {
  3548. return this.getParentWhile(n => n.getKind() === kind);
  3549. }
  3550. getLastToken() {
  3551. const lastToken = this.compilerNode.getLastToken(this._sourceFile.compilerNode);
  3552. if (lastToken == null)
  3553. throw new common.errors.NotImplementedError("Not implemented scenario where the last token does not exist.");
  3554. return this._getNodeFromCompilerNode(lastToken);
  3555. }
  3556. isInSyntaxList() {
  3557. return this.getParentSyntaxList() != null;
  3558. }
  3559. getParentSyntaxListOrThrow(message) {
  3560. return common.errors.throwIfNullOrUndefined(this.getParentSyntaxList(), message ?? "Expected the parent to be a syntax list.", this);
  3561. }
  3562. getParentSyntaxList() {
  3563. const kind = this.getKind();
  3564. if (kind === common.SyntaxKind.SingleLineCommentTrivia || kind === common.SyntaxKind.MultiLineCommentTrivia)
  3565. return this.getParentOrThrow().getChildSyntaxList();
  3566. const syntaxList = getParentSyntaxList(this.compilerNode, this._sourceFile.compilerNode);
  3567. return this._getNodeFromCompilerNodeIfExists(syntaxList);
  3568. }
  3569. _getParentSyntaxListIfWrapped() {
  3570. const parent = this.getParent();
  3571. if (parent == null || !ExtendedParser.hasParsedTokens(parent.compilerNode))
  3572. return undefined;
  3573. return this.getParentSyntaxList();
  3574. }
  3575. getChildIndex() {
  3576. const parent = this.getParentSyntaxList() || this.getParentOrThrow();
  3577. const index = parent._getCompilerChildren().indexOf(this.compilerNode);
  3578. if (index === -1)
  3579. throw new common.errors.NotImplementedError("For some reason the child's parent did not contain the child.");
  3580. return index;
  3581. }
  3582. getIndentationLevel() {
  3583. const indentationText = this._context.manipulationSettings.getIndentationText();
  3584. return this._context.languageService.getIdentationAtPosition(this._sourceFile, this.getStart()) / indentationText.length;
  3585. }
  3586. getChildIndentationLevel() {
  3587. if (Node.isSourceFile(this))
  3588. return 0;
  3589. return this.getIndentationLevel() + 1;
  3590. }
  3591. getIndentationText(offset = 0) {
  3592. return this.#getIndentationTextForLevel(this.getIndentationLevel() + offset);
  3593. }
  3594. getChildIndentationText(offset = 0) {
  3595. return this.#getIndentationTextForLevel(this.getChildIndentationLevel() + offset);
  3596. }
  3597. #getIndentationTextForLevel(level) {
  3598. return this._context.manipulationSettings.getIndentationText().repeat(level);
  3599. }
  3600. getStartLinePos(includeJsDocComments) {
  3601. const sourceFileText = this._sourceFile.getFullText();
  3602. return getPreviousMatchingPos(sourceFileText, this.getStart(includeJsDocComments), char => char === CharCodes.NEWLINE || char === CharCodes.CARRIAGE_RETURN);
  3603. }
  3604. getStartLineNumber(includeJsDocComments) {
  3605. return common.StringUtils.getLineNumberAtPos(this._sourceFile.getFullText(), this.getStartLinePos(includeJsDocComments));
  3606. }
  3607. getEndLineNumber() {
  3608. const sourceFileText = this._sourceFile.getFullText();
  3609. const endLinePos = getPreviousMatchingPos(sourceFileText, this.getEnd(), char => char === CharCodes.NEWLINE || char === CharCodes.CARRIAGE_RETURN);
  3610. return common.StringUtils.getLineNumberAtPos(this._sourceFile.getFullText(), endLinePos);
  3611. }
  3612. isFirstNodeOnLine() {
  3613. const sourceFileText = this._sourceFile.getFullText();
  3614. const startPos = this.getNonWhitespaceStart();
  3615. for (let i = startPos - 1; i >= 0; i--) {
  3616. const currentChar = sourceFileText[i];
  3617. if (currentChar === " " || currentChar === "\t")
  3618. continue;
  3619. if (currentChar === "\n")
  3620. return true;
  3621. return false;
  3622. }
  3623. return true;
  3624. }
  3625. replaceWithText(textOrWriterFunction, writer) {
  3626. const newText = getTextFromStringOrWriter(writer || this._getWriterWithQueuedIndentation(), textOrWriterFunction);
  3627. if (Node.isSourceFile(this)) {
  3628. this.replaceText([this.getPos(), this.getEnd()], newText);
  3629. return this;
  3630. }
  3631. const parent = this.getParentSyntaxList() || this.getParentOrThrow();
  3632. const childIndex = this.getChildIndex();
  3633. const start = this.getStart(true);
  3634. insertIntoParentTextRange({
  3635. parent,
  3636. insertPos: start,
  3637. newText,
  3638. replacing: {
  3639. textLength: this.getEnd() - start,
  3640. },
  3641. });
  3642. return parent.getChildren()[childIndex];
  3643. }
  3644. prependWhitespace(textOrWriterFunction) {
  3645. insertWhiteSpaceTextAtPos(this, this.getStart(true), textOrWriterFunction, common.nameof(this, "prependWhitespace"));
  3646. }
  3647. appendWhitespace(textOrWriterFunction) {
  3648. insertWhiteSpaceTextAtPos(this, this.getEnd(), textOrWriterFunction, common.nameof(this, "appendWhitespace"));
  3649. }
  3650. formatText(settings = {}) {
  3651. const formattingEdits = this._context.languageService.getFormattingEditsForRange(this._sourceFile.getFilePath(), [this.getStart(true), this.getEnd()], settings);
  3652. replaceSourceFileTextForFormatting({
  3653. sourceFile: this._sourceFile,
  3654. newText: getTextFromTextChanges(this._sourceFile, formattingEdits),
  3655. });
  3656. }
  3657. transform(visitNode) {
  3658. const compilerFactory = this._context.compilerFactory;
  3659. const printer = common.ts.createPrinter({
  3660. newLine: this._context.manipulationSettings.getNewLineKind(),
  3661. removeComments: false,
  3662. });
  3663. const transformations = [];
  3664. const compilerSourceFile = this._sourceFile.compilerNode;
  3665. const compilerNode = this.compilerNode;
  3666. const transformerFactory = context => {
  3667. return rootNode => innerVisit(rootNode, context);
  3668. };
  3669. if (this.getKind() === common.ts.SyntaxKind.SourceFile) {
  3670. common.ts.transform(compilerNode, [transformerFactory], this._context.compilerOptions.get());
  3671. replaceSourceFileTextStraight({
  3672. sourceFile: this._sourceFile,
  3673. newText: getTransformedText([0, this.getEnd()]),
  3674. });
  3675. return this;
  3676. }
  3677. else {
  3678. const parent = this.getParentSyntaxList() || this.getParentOrThrow();
  3679. const childIndex = this.getChildIndex();
  3680. const start = this.getStart(true);
  3681. const end = this.getEnd();
  3682. common.ts.transform(compilerNode, [transformerFactory], this._context.compilerOptions.get());
  3683. insertIntoParentTextRange({
  3684. parent,
  3685. insertPos: start,
  3686. newText: getTransformedText([start, end]),
  3687. replacing: {
  3688. textLength: end - start,
  3689. },
  3690. });
  3691. return parent.getChildren()[childIndex];
  3692. }
  3693. function innerVisit(node, context) {
  3694. const traversal = {
  3695. factory: context.factory,
  3696. visitChildren() {
  3697. node = common.ts.visitEachChild(node, child => innerVisit(child, context), context);
  3698. return node;
  3699. },
  3700. currentNode: node,
  3701. };
  3702. const resultNode = visitNode(traversal);
  3703. handleTransformation(node, resultNode);
  3704. return resultNode;
  3705. }
  3706. function handleTransformation(oldNode, newNode) {
  3707. if (oldNode === newNode && newNode.emitNode == null)
  3708. return;
  3709. const start = oldNode.getStart(compilerSourceFile, true);
  3710. const end = oldNode.end;
  3711. let lastTransformation;
  3712. while ((lastTransformation = transformations[transformations.length - 1]) && lastTransformation.start > start)
  3713. transformations.pop();
  3714. const wrappedNode = compilerFactory.getExistingNodeFromCompilerNode(oldNode);
  3715. transformations.push({
  3716. start,
  3717. end,
  3718. compilerNode: newNode,
  3719. });
  3720. if (wrappedNode != null) {
  3721. if (oldNode.kind !== newNode.kind)
  3722. wrappedNode.forget();
  3723. else
  3724. wrappedNode.forgetDescendants();
  3725. }
  3726. }
  3727. function getTransformedText(replaceRange) {
  3728. const fileText = compilerSourceFile.getFullText();
  3729. let finalText = "";
  3730. let lastPos = replaceRange[0];
  3731. for (const transform of transformations) {
  3732. finalText += fileText.substring(lastPos, transform.start);
  3733. finalText += printer.printNode(common.ts.EmitHint.Unspecified, transform.compilerNode, transform.compilerNode.getSourceFile() ?? compilerSourceFile);
  3734. lastPos = transform.end;
  3735. }
  3736. finalText += fileText.substring(lastPos, replaceRange[1]);
  3737. return finalText;
  3738. }
  3739. }
  3740. getLeadingCommentRanges() {
  3741. return this.#leadingCommentRanges || (this.#leadingCommentRanges = this.#getCommentsAtPos(this.getFullStart(), (text, pos) => {
  3742. const comments = common.ts.getLeadingCommentRanges(text, pos) || [];
  3743. if (this.getKind() === common.SyntaxKind.SingleLineCommentTrivia || this.getKind() === common.SyntaxKind.MultiLineCommentTrivia) {
  3744. const thisPos = this.getPos();
  3745. return comments.filter(r => r.pos < thisPos);
  3746. }
  3747. else {
  3748. return comments;
  3749. }
  3750. }));
  3751. }
  3752. getTrailingCommentRanges() {
  3753. return this.#trailingCommentRanges ?? (this.#trailingCommentRanges = this.#getCommentsAtPos(this.getEnd(), common.ts.getTrailingCommentRanges));
  3754. }
  3755. #getCommentsAtPos(pos, getComments) {
  3756. if (this.getKind() === common.SyntaxKind.SourceFile)
  3757. return [];
  3758. return (getComments(this._sourceFile.getFullText(), pos) ?? []).map(r => new CommentRange(r, this._sourceFile));
  3759. }
  3760. getChildrenOfKind(kind) {
  3761. return this._getCompilerChildrenOfKind(kind).map(c => this._getNodeFromCompilerNode(c));
  3762. }
  3763. getFirstChildByKindOrThrow(kind, message) {
  3764. return common.errors.throwIfNullOrUndefined(this.getFirstChildByKind(kind), message ?? (() => `A child of the kind ${common.getSyntaxKindName(kind)} was expected.`), this);
  3765. }
  3766. getFirstChildByKind(kind) {
  3767. const child = this._getCompilerChildrenOfKind(kind)[0];
  3768. return child == null ? undefined : this._getNodeFromCompilerNode(child);
  3769. }
  3770. getFirstChildIfKindOrThrow(kind, message) {
  3771. return common.errors.throwIfNullOrUndefined(this.getFirstChildIfKind(kind), message ?? (() => `A first child of the kind ${common.getSyntaxKindName(kind)} was expected.`), this);
  3772. }
  3773. getFirstChildIfKind(kind) {
  3774. const firstChild = this._getCompilerFirstChild();
  3775. return firstChild != null && firstChild.kind === kind ? this._getNodeFromCompilerNode(firstChild) : undefined;
  3776. }
  3777. getLastChildByKindOrThrow(kind, message) {
  3778. return common.errors.throwIfNullOrUndefined(this.getLastChildByKind(kind), message ?? (() => `A child of the kind ${common.getSyntaxKindName(kind)} was expected.`), this);
  3779. }
  3780. getLastChildByKind(kind) {
  3781. const children = this._getCompilerChildrenOfKind(kind);
  3782. const lastChild = children[children.length - 1];
  3783. return this._getNodeFromCompilerNodeIfExists(lastChild);
  3784. }
  3785. getLastChildIfKindOrThrow(kind, message) {
  3786. return common.errors.throwIfNullOrUndefined(this.getLastChildIfKind(kind), message ?? (() => `A last child of the kind ${common.getSyntaxKindName(kind)} was expected.`), this);
  3787. }
  3788. getLastChildIfKind(kind) {
  3789. const lastChild = this._getCompilerLastChild();
  3790. return lastChild != null && lastChild.kind === kind ? this._getNodeFromCompilerNode(lastChild) : undefined;
  3791. }
  3792. getChildAtIndexIfKindOrThrow(index, kind, message) {
  3793. return common.errors.throwIfNullOrUndefined(this.getChildAtIndexIfKind(index, kind), message ?? (() => `Child at index ${index} was expected to be ${common.getSyntaxKindName(kind)}`), this);
  3794. }
  3795. getChildAtIndexIfKind(index, kind) {
  3796. const node = this._getCompilerChildAtIndex(index);
  3797. return node.kind === kind ? this._getNodeFromCompilerNode(node) : undefined;
  3798. }
  3799. getPreviousSiblingIfKindOrThrow(kind, message) {
  3800. return common.errors.throwIfNullOrUndefined(this.getPreviousSiblingIfKind(kind), message ?? (() => `A previous sibling of kind ${common.getSyntaxKindName(kind)} was expected.`), this);
  3801. }
  3802. getNextSiblingIfKindOrThrow(kind, message) {
  3803. return common.errors.throwIfNullOrUndefined(this.getNextSiblingIfKind(kind), message ?? (() => `A next sibling of kind ${common.getSyntaxKindName(kind)} was expected.`), this);
  3804. }
  3805. getPreviousSiblingIfKind(kind) {
  3806. const previousSibling = this._getCompilerPreviousSibling();
  3807. return previousSibling != null && previousSibling.kind === kind
  3808. ? this._getNodeFromCompilerNode(previousSibling)
  3809. : undefined;
  3810. }
  3811. getNextSiblingIfKind(kind) {
  3812. const nextSibling = this._getCompilerNextSibling();
  3813. return nextSibling != null && nextSibling.kind === kind ? this._getNodeFromCompilerNode(nextSibling) : undefined;
  3814. }
  3815. getParentIfOrThrow(condition, message) {
  3816. return common.errors.throwIfNullOrUndefined(this.getParentIf(condition), message ?? "The parent did not match the provided condition.", this);
  3817. }
  3818. getParentIf(condition) {
  3819. return condition(this.getParent(), this) ? this.getParent() : undefined;
  3820. }
  3821. getParentIfKindOrThrow(kind, message) {
  3822. return common.errors.throwIfNullOrUndefined(this.getParentIfKind(kind), message ?? (() => `The parent was not a syntax kind of ${common.getSyntaxKindName(kind)}.`), this);
  3823. }
  3824. getParentIfKind(kind) {
  3825. return this.getParentIf(n => n !== undefined && n.getKind() === kind);
  3826. }
  3827. getFirstAncestorByKindOrThrow(kind, message) {
  3828. return common.errors.throwIfNullOrUndefined(this.getFirstAncestorByKind(kind), message ?? (() => `Expected an ancestor with a syntax kind of ${common.getSyntaxKindName(kind)}.`), this);
  3829. }
  3830. getFirstAncestorByKind(kind) {
  3831. for (const parent of this._getAncestorsIterator(kind === common.SyntaxKind.SyntaxList)) {
  3832. if (parent.getKind() === kind)
  3833. return parent;
  3834. }
  3835. return undefined;
  3836. }
  3837. getFirstAncestorOrThrow(condition, message) {
  3838. return common.errors.throwIfNullOrUndefined(this.getFirstAncestor(condition), message ?? `Expected to find an ancestor that matched the provided condition.`, this);
  3839. }
  3840. getFirstAncestor(condition) {
  3841. for (const ancestor of this._getAncestorsIterator(false)) {
  3842. if (condition == null || condition(ancestor))
  3843. return ancestor;
  3844. }
  3845. return undefined;
  3846. }
  3847. getDescendantsOfKind(kind) {
  3848. const descendants = [];
  3849. for (const descendant of this._getCompilerDescendantsOfKindIterator(kind))
  3850. descendants.push(this._getNodeFromCompilerNode(descendant));
  3851. return descendants;
  3852. }
  3853. getFirstDescendantByKindOrThrow(kind, message) {
  3854. return common.errors.throwIfNullOrUndefined(this.getFirstDescendantByKind(kind), message ?? (() => `A descendant of kind ${common.getSyntaxKindName(kind)} was expected to be found.`), this);
  3855. }
  3856. getFirstDescendantByKind(kind) {
  3857. for (const descendant of this._getCompilerDescendantsOfKindIterator(kind))
  3858. return this._getNodeFromCompilerNode(descendant);
  3859. return undefined;
  3860. }
  3861. _getCompilerChildren() {
  3862. return ExtendedParser.getCompilerChildren(this.compilerNode, this._sourceFile.compilerNode);
  3863. }
  3864. _getCompilerForEachChildren() {
  3865. return ExtendedParser.getCompilerForEachChildren(this.compilerNode, this._sourceFile.compilerNode);
  3866. }
  3867. _getCompilerChildrenFast() {
  3868. return ExtendedParser.hasParsedTokens(this.compilerNode) ? this._getCompilerChildren() : this._getCompilerForEachChildren();
  3869. }
  3870. _getCompilerChildrenOfKind(kind) {
  3871. const children = useParseTreeSearchForKind(this, kind) ? this._getCompilerForEachChildren() : this._getCompilerChildren();
  3872. return children.filter(c => c.kind === kind);
  3873. }
  3874. *_getCompilerDescendantsOfKindIterator(kind) {
  3875. const children = useParseTreeSearchForKind(this, kind) ? this._getCompilerForEachChildren() : this._getCompilerChildren();
  3876. for (const child of children) {
  3877. if (child.kind === kind)
  3878. yield child;
  3879. const descendants = useParseTreeSearchForKind(child.kind, kind)
  3880. ? getCompilerForEachDescendantsIterator(child)
  3881. : getCompilerDescendantsIterator(child, this._sourceFile.compilerNode);
  3882. for (const descendant of descendants) {
  3883. if (descendant.kind === kind)
  3884. yield descendant;
  3885. }
  3886. }
  3887. }
  3888. _getCompilerDescendantsIterator() {
  3889. return getCompilerDescendantsIterator(this.compilerNode, this._sourceFile.compilerNode);
  3890. }
  3891. _getCompilerForEachDescendantsIterator() {
  3892. return getCompilerForEachDescendantsIterator(this.compilerNode);
  3893. }
  3894. _getCompilerFirstChild(condition) {
  3895. for (const child of this._getCompilerChildren()) {
  3896. if (condition == null || condition(child))
  3897. return child;
  3898. }
  3899. return undefined;
  3900. }
  3901. _getCompilerLastChild(condition) {
  3902. const children = this._getCompilerChildren();
  3903. for (let i = children.length - 1; i >= 0; i--) {
  3904. const child = children[i];
  3905. if (condition == null || condition(child))
  3906. return child;
  3907. }
  3908. return undefined;
  3909. }
  3910. _getCompilerPreviousSiblings() {
  3911. const parent = this.getParentSyntaxList() || this.getParentOrThrow();
  3912. const previousSiblings = [];
  3913. for (const child of parent._getCompilerChildren()) {
  3914. if (child === this.compilerNode)
  3915. break;
  3916. previousSiblings.unshift(child);
  3917. }
  3918. return previousSiblings;
  3919. }
  3920. _getCompilerNextSiblings() {
  3921. let foundChild = false;
  3922. const parent = this.getParentSyntaxList() || this.getParentOrThrow();
  3923. const nextSiblings = [];
  3924. for (const child of parent._getCompilerChildren()) {
  3925. if (!foundChild) {
  3926. foundChild = child === this.compilerNode;
  3927. continue;
  3928. }
  3929. nextSiblings.push(child);
  3930. }
  3931. return nextSiblings;
  3932. }
  3933. _getCompilerPreviousSibling(condition) {
  3934. for (const sibling of this._getCompilerPreviousSiblings()) {
  3935. if (condition == null || condition(sibling))
  3936. return sibling;
  3937. }
  3938. return undefined;
  3939. }
  3940. _getCompilerNextSibling(condition) {
  3941. for (const sibling of this._getCompilerNextSiblings()) {
  3942. if (condition == null || condition(sibling))
  3943. return sibling;
  3944. }
  3945. return undefined;
  3946. }
  3947. _getCompilerChildAtIndex(index) {
  3948. const children = this._getCompilerChildren();
  3949. common.errors.throwIfOutOfRange(index, [0, children.length - 1], "index");
  3950. return children[index];
  3951. }
  3952. _getWriterWithIndentation() {
  3953. const writer = this._getWriter();
  3954. writer.setIndentationLevel(this.getIndentationLevel());
  3955. return writer;
  3956. }
  3957. _getWriterWithQueuedIndentation() {
  3958. const writer = this._getWriter();
  3959. writer.queueIndentationLevel(this.getIndentationLevel());
  3960. return writer;
  3961. }
  3962. _getWriterWithChildIndentation() {
  3963. const writer = this._getWriter();
  3964. writer.setIndentationLevel(this.getChildIndentationLevel());
  3965. return writer;
  3966. }
  3967. _getWriterWithQueuedChildIndentation() {
  3968. const writer = this._getWriter();
  3969. writer.queueIndentationLevel(this.getChildIndentationLevel());
  3970. return writer;
  3971. }
  3972. _getTextWithQueuedChildIndentation(textOrWriterFunc) {
  3973. const writer = this._getWriterWithQueuedChildIndentation();
  3974. if (typeof textOrWriterFunc === "string")
  3975. writer.write(textOrWriterFunc);
  3976. else
  3977. textOrWriterFunc(writer);
  3978. return writer.toString();
  3979. }
  3980. _getWriter() {
  3981. return this._context.createWriter();
  3982. }
  3983. _getNodeFromCompilerNode(compilerNode) {
  3984. return this._context.compilerFactory.getNodeFromCompilerNode(compilerNode, this._sourceFile);
  3985. }
  3986. _getNodeFromCompilerNodeIfExists(compilerNode) {
  3987. return compilerNode == null ? undefined : this._getNodeFromCompilerNode(compilerNode);
  3988. }
  3989. _ensureBound() {
  3990. if (this.compilerNode.symbol != null)
  3991. return;
  3992. this.getSymbol();
  3993. }
  3994. static hasExpression(node) {
  3995. return node.getExpression?.() != null;
  3996. }
  3997. static hasName(node) {
  3998. return typeof node.getName?.() === "string";
  3999. }
  4000. static hasBody(node) {
  4001. return node.getBody?.() != null;
  4002. }
  4003. static hasStructure(node) {
  4004. return typeof node.getStructure === "function";
  4005. }
  4006. static is(kind) {
  4007. return (node) => {
  4008. return node?.getKind() == kind;
  4009. };
  4010. }
  4011. static isNode(value) {
  4012. return value != null && value.compilerNode != null;
  4013. }
  4014. static isCommentNode(node) {
  4015. const kind = node?.getKind();
  4016. return kind === common.SyntaxKind.SingleLineCommentTrivia || kind === common.SyntaxKind.MultiLineCommentTrivia;
  4017. }
  4018. static isCommentStatement(node) {
  4019. return node?.compilerNode?._commentKind === exports.CommentNodeKind.Statement;
  4020. }
  4021. static isCommentClassElement(node) {
  4022. return node?.compilerNode?._commentKind === exports.CommentNodeKind.ClassElement;
  4023. }
  4024. static isCommentTypeElement(node) {
  4025. return node?.compilerNode?._commentKind === exports.CommentNodeKind.TypeElement;
  4026. }
  4027. static isCommentObjectLiteralElement(node) {
  4028. return node?.compilerNode?._commentKind === exports.CommentNodeKind.ObjectLiteralElement;
  4029. }
  4030. static isCommentEnumMember(node) {
  4031. return node?.compilerNode?._commentKind == exports.CommentNodeKind.EnumMember;
  4032. }
  4033. static isAbstractable(node) {
  4034. switch (node?.getKind()) {
  4035. case common.SyntaxKind.ClassDeclaration:
  4036. case common.SyntaxKind.ClassExpression:
  4037. case common.SyntaxKind.ConstructorType:
  4038. case common.SyntaxKind.GetAccessor:
  4039. case common.SyntaxKind.MethodDeclaration:
  4040. case common.SyntaxKind.PropertyDeclaration:
  4041. case common.SyntaxKind.SetAccessor:
  4042. return true;
  4043. default:
  4044. return false;
  4045. }
  4046. }
  4047. static isAmbientable(node) {
  4048. switch (node?.getKind()) {
  4049. case common.SyntaxKind.ClassDeclaration:
  4050. case common.SyntaxKind.EnumDeclaration:
  4051. case common.SyntaxKind.FunctionDeclaration:
  4052. case common.SyntaxKind.InterfaceDeclaration:
  4053. case common.SyntaxKind.ModuleDeclaration:
  4054. case common.SyntaxKind.PropertyDeclaration:
  4055. case common.SyntaxKind.TypeAliasDeclaration:
  4056. case common.SyntaxKind.VariableStatement:
  4057. return true;
  4058. default:
  4059. return false;
  4060. }
  4061. }
  4062. static isAnyKeyword = Node.is(common.SyntaxKind.AnyKeyword);
  4063. static isArgumented(node) {
  4064. switch (node?.getKind()) {
  4065. case common.SyntaxKind.CallExpression:
  4066. case common.SyntaxKind.NewExpression:
  4067. return true;
  4068. default:
  4069. return false;
  4070. }
  4071. }
  4072. static isArrayBindingPattern = Node.is(common.SyntaxKind.ArrayBindingPattern);
  4073. static isArrayLiteralExpression = Node.is(common.SyntaxKind.ArrayLiteralExpression);
  4074. static isArrayTypeNode(node) {
  4075. return node?.getKind() === common.SyntaxKind.ArrayType;
  4076. }
  4077. static isArrowFunction = Node.is(common.SyntaxKind.ArrowFunction);
  4078. static isAsExpression = Node.is(common.SyntaxKind.AsExpression);
  4079. static isAsyncable(node) {
  4080. switch (node?.getKind()) {
  4081. case common.SyntaxKind.ArrowFunction:
  4082. case common.SyntaxKind.FunctionDeclaration:
  4083. case common.SyntaxKind.FunctionExpression:
  4084. case common.SyntaxKind.MethodDeclaration:
  4085. return true;
  4086. default:
  4087. return false;
  4088. }
  4089. }
  4090. static isAwaitable(node) {
  4091. return node?.getKind() === common.SyntaxKind.ForOfStatement;
  4092. }
  4093. static isAwaitExpression = Node.is(common.SyntaxKind.AwaitExpression);
  4094. static isBigIntLiteral = Node.is(common.SyntaxKind.BigIntLiteral);
  4095. static isBinaryExpression = Node.is(common.SyntaxKind.BinaryExpression);
  4096. static isBindingElement = Node.is(common.SyntaxKind.BindingElement);
  4097. static isBindingNamed(node) {
  4098. switch (node?.getKind()) {
  4099. case common.SyntaxKind.BindingElement:
  4100. case common.SyntaxKind.Parameter:
  4101. case common.SyntaxKind.VariableDeclaration:
  4102. return true;
  4103. default:
  4104. return false;
  4105. }
  4106. }
  4107. static isBlock = Node.is(common.SyntaxKind.Block);
  4108. static isBodied(node) {
  4109. switch (node?.getKind()) {
  4110. case common.SyntaxKind.ArrowFunction:
  4111. case common.SyntaxKind.ClassStaticBlockDeclaration:
  4112. case common.SyntaxKind.FunctionExpression:
  4113. return true;
  4114. default:
  4115. return false;
  4116. }
  4117. }
  4118. static isBodyable(node) {
  4119. switch (node?.getKind()) {
  4120. case common.SyntaxKind.Constructor:
  4121. case common.SyntaxKind.FunctionDeclaration:
  4122. case common.SyntaxKind.GetAccessor:
  4123. case common.SyntaxKind.MethodDeclaration:
  4124. case common.SyntaxKind.ModuleDeclaration:
  4125. case common.SyntaxKind.SetAccessor:
  4126. return true;
  4127. default:
  4128. return false;
  4129. }
  4130. }
  4131. static isBooleanKeyword = Node.is(common.SyntaxKind.BooleanKeyword);
  4132. static isBreakStatement = Node.is(common.SyntaxKind.BreakStatement);
  4133. static isCallExpression = Node.is(common.SyntaxKind.CallExpression);
  4134. static isCallSignatureDeclaration(node) {
  4135. return node?.getKind() === common.SyntaxKind.CallSignature;
  4136. }
  4137. static isCaseBlock = Node.is(common.SyntaxKind.CaseBlock);
  4138. static isCaseClause = Node.is(common.SyntaxKind.CaseClause);
  4139. static isCatchClause = Node.is(common.SyntaxKind.CatchClause);
  4140. static isChildOrderable(node) {
  4141. switch (node?.getKind()) {
  4142. case common.SyntaxKind.Block:
  4143. case common.SyntaxKind.BreakStatement:
  4144. case common.SyntaxKind.CallSignature:
  4145. case common.SyntaxKind.ClassDeclaration:
  4146. case common.SyntaxKind.ClassStaticBlockDeclaration:
  4147. case common.SyntaxKind.Constructor:
  4148. case common.SyntaxKind.ConstructSignature:
  4149. case common.SyntaxKind.ContinueStatement:
  4150. case common.SyntaxKind.DebuggerStatement:
  4151. case common.SyntaxKind.DoStatement:
  4152. case common.SyntaxKind.EmptyStatement:
  4153. case common.SyntaxKind.EnumDeclaration:
  4154. case common.SyntaxKind.ExportAssignment:
  4155. case common.SyntaxKind.ExportDeclaration:
  4156. case common.SyntaxKind.ExpressionStatement:
  4157. case common.SyntaxKind.ForInStatement:
  4158. case common.SyntaxKind.ForOfStatement:
  4159. case common.SyntaxKind.ForStatement:
  4160. case common.SyntaxKind.FunctionDeclaration:
  4161. case common.SyntaxKind.GetAccessor:
  4162. case common.SyntaxKind.IfStatement:
  4163. case common.SyntaxKind.ImportDeclaration:
  4164. case common.SyntaxKind.ImportEqualsDeclaration:
  4165. case common.SyntaxKind.IndexSignature:
  4166. case common.SyntaxKind.InterfaceDeclaration:
  4167. case common.SyntaxKind.LabeledStatement:
  4168. case common.SyntaxKind.MethodDeclaration:
  4169. case common.SyntaxKind.MethodSignature:
  4170. case common.SyntaxKind.ModuleBlock:
  4171. case common.SyntaxKind.ModuleDeclaration:
  4172. case common.SyntaxKind.NotEmittedStatement:
  4173. case common.SyntaxKind.PropertyDeclaration:
  4174. case common.SyntaxKind.PropertySignature:
  4175. case common.SyntaxKind.ReturnStatement:
  4176. case common.SyntaxKind.SetAccessor:
  4177. case common.SyntaxKind.SwitchStatement:
  4178. case common.SyntaxKind.ThrowStatement:
  4179. case common.SyntaxKind.TryStatement:
  4180. case common.SyntaxKind.TypeAliasDeclaration:
  4181. case common.SyntaxKind.VariableStatement:
  4182. case common.SyntaxKind.WhileStatement:
  4183. case common.SyntaxKind.WithStatement:
  4184. return true;
  4185. default:
  4186. return false;
  4187. }
  4188. }
  4189. static isClassDeclaration = Node.is(common.SyntaxKind.ClassDeclaration);
  4190. static isClassExpression = Node.is(common.SyntaxKind.ClassExpression);
  4191. static isClassLikeDeclarationBase(node) {
  4192. switch (node?.getKind()) {
  4193. case common.SyntaxKind.ClassDeclaration:
  4194. case common.SyntaxKind.ClassExpression:
  4195. return true;
  4196. default:
  4197. return false;
  4198. }
  4199. }
  4200. static isClassStaticBlockDeclaration = Node.is(common.SyntaxKind.ClassStaticBlockDeclaration);
  4201. static isCommaListExpression = Node.is(common.SyntaxKind.CommaListExpression);
  4202. static isComputedPropertyName = Node.is(common.SyntaxKind.ComputedPropertyName);
  4203. static isConditionalExpression = Node.is(common.SyntaxKind.ConditionalExpression);
  4204. static isConditionalTypeNode(node) {
  4205. return node?.getKind() === common.SyntaxKind.ConditionalType;
  4206. }
  4207. static isConstructorDeclaration(node) {
  4208. return node?.getKind() === common.SyntaxKind.Constructor;
  4209. }
  4210. static isConstructorTypeNode(node) {
  4211. return node?.getKind() === common.SyntaxKind.ConstructorType;
  4212. }
  4213. static isConstructSignatureDeclaration(node) {
  4214. return node?.getKind() === common.SyntaxKind.ConstructSignature;
  4215. }
  4216. static isContinueStatement = Node.is(common.SyntaxKind.ContinueStatement);
  4217. static isDebuggerStatement = Node.is(common.SyntaxKind.DebuggerStatement);
  4218. static isDecoratable(node) {
  4219. switch (node?.getKind()) {
  4220. case common.SyntaxKind.ClassDeclaration:
  4221. case common.SyntaxKind.ClassExpression:
  4222. case common.SyntaxKind.GetAccessor:
  4223. case common.SyntaxKind.MethodDeclaration:
  4224. case common.SyntaxKind.Parameter:
  4225. case common.SyntaxKind.PropertyDeclaration:
  4226. case common.SyntaxKind.SetAccessor:
  4227. return true;
  4228. default:
  4229. return false;
  4230. }
  4231. }
  4232. static isDecorator = Node.is(common.SyntaxKind.Decorator);
  4233. static isDefaultClause = Node.is(common.SyntaxKind.DefaultClause);
  4234. static isDeleteExpression = Node.is(common.SyntaxKind.DeleteExpression);
  4235. static isDoStatement = Node.is(common.SyntaxKind.DoStatement);
  4236. static isDotDotDotTokenable(node) {
  4237. switch (node?.getKind()) {
  4238. case common.SyntaxKind.BindingElement:
  4239. case common.SyntaxKind.JsxExpression:
  4240. case common.SyntaxKind.NamedTupleMember:
  4241. case common.SyntaxKind.Parameter:
  4242. return true;
  4243. default:
  4244. return false;
  4245. }
  4246. }
  4247. static isElementAccessExpression = Node.is(common.SyntaxKind.ElementAccessExpression);
  4248. static isEmptyStatement = Node.is(common.SyntaxKind.EmptyStatement);
  4249. static isEnumDeclaration = Node.is(common.SyntaxKind.EnumDeclaration);
  4250. static isEnumMember = Node.is(common.SyntaxKind.EnumMember);
  4251. static isExclamationTokenable(node) {
  4252. switch (node?.getKind()) {
  4253. case common.SyntaxKind.PropertyDeclaration:
  4254. case common.SyntaxKind.VariableDeclaration:
  4255. return true;
  4256. default:
  4257. return false;
  4258. }
  4259. }
  4260. static isExportable(node) {
  4261. switch (node?.getKind()) {
  4262. case common.SyntaxKind.ClassDeclaration:
  4263. case common.SyntaxKind.EnumDeclaration:
  4264. case common.SyntaxKind.FunctionDeclaration:
  4265. case common.SyntaxKind.ImportEqualsDeclaration:
  4266. case common.SyntaxKind.InterfaceDeclaration:
  4267. case common.SyntaxKind.ModuleDeclaration:
  4268. case common.SyntaxKind.TypeAliasDeclaration:
  4269. case common.SyntaxKind.VariableStatement:
  4270. return true;
  4271. default:
  4272. return false;
  4273. }
  4274. }
  4275. static isExportAssignment = Node.is(common.SyntaxKind.ExportAssignment);
  4276. static isExportDeclaration = Node.is(common.SyntaxKind.ExportDeclaration);
  4277. static isExportGetable(node) {
  4278. switch (node?.getKind()) {
  4279. case common.SyntaxKind.ClassDeclaration:
  4280. case common.SyntaxKind.EnumDeclaration:
  4281. case common.SyntaxKind.FunctionDeclaration:
  4282. case common.SyntaxKind.ImportEqualsDeclaration:
  4283. case common.SyntaxKind.InterfaceDeclaration:
  4284. case common.SyntaxKind.ModuleDeclaration:
  4285. case common.SyntaxKind.TypeAliasDeclaration:
  4286. case common.SyntaxKind.VariableDeclaration:
  4287. case common.SyntaxKind.VariableStatement:
  4288. return true;
  4289. default:
  4290. return false;
  4291. }
  4292. }
  4293. static isExportSpecifier = Node.is(common.SyntaxKind.ExportSpecifier);
  4294. static isExpression(node) {
  4295. switch (node?.getKind()) {
  4296. case common.SyntaxKind.AnyKeyword:
  4297. case common.SyntaxKind.BooleanKeyword:
  4298. case common.SyntaxKind.NumberKeyword:
  4299. case common.SyntaxKind.ObjectKeyword:
  4300. case common.SyntaxKind.StringKeyword:
  4301. case common.SyntaxKind.SymbolKeyword:
  4302. case common.SyntaxKind.UndefinedKeyword:
  4303. case common.SyntaxKind.ArrayLiteralExpression:
  4304. case common.SyntaxKind.ArrowFunction:
  4305. case common.SyntaxKind.AsExpression:
  4306. case common.SyntaxKind.AwaitExpression:
  4307. case common.SyntaxKind.BigIntLiteral:
  4308. case common.SyntaxKind.BinaryExpression:
  4309. case common.SyntaxKind.CallExpression:
  4310. case common.SyntaxKind.ClassExpression:
  4311. case common.SyntaxKind.CommaListExpression:
  4312. case common.SyntaxKind.ConditionalExpression:
  4313. case common.SyntaxKind.DeleteExpression:
  4314. case common.SyntaxKind.ElementAccessExpression:
  4315. case common.SyntaxKind.FalseKeyword:
  4316. case common.SyntaxKind.FunctionExpression:
  4317. case common.SyntaxKind.Identifier:
  4318. case common.SyntaxKind.ImportKeyword:
  4319. case common.SyntaxKind.JsxClosingFragment:
  4320. case common.SyntaxKind.JsxElement:
  4321. case common.SyntaxKind.JsxExpression:
  4322. case common.SyntaxKind.JsxFragment:
  4323. case common.SyntaxKind.JsxOpeningElement:
  4324. case common.SyntaxKind.JsxOpeningFragment:
  4325. case common.SyntaxKind.JsxSelfClosingElement:
  4326. case common.SyntaxKind.MetaProperty:
  4327. case common.SyntaxKind.NewExpression:
  4328. case common.SyntaxKind.NonNullExpression:
  4329. case common.SyntaxKind.NoSubstitutionTemplateLiteral:
  4330. case common.SyntaxKind.NullKeyword:
  4331. case common.SyntaxKind.NumericLiteral:
  4332. case common.SyntaxKind.ObjectLiteralExpression:
  4333. case common.SyntaxKind.OmittedExpression:
  4334. case common.SyntaxKind.ParenthesizedExpression:
  4335. case common.SyntaxKind.PartiallyEmittedExpression:
  4336. case common.SyntaxKind.PostfixUnaryExpression:
  4337. case common.SyntaxKind.PrefixUnaryExpression:
  4338. case common.SyntaxKind.PropertyAccessExpression:
  4339. case common.SyntaxKind.RegularExpressionLiteral:
  4340. case common.SyntaxKind.SatisfiesExpression:
  4341. case common.SyntaxKind.SpreadElement:
  4342. case common.SyntaxKind.StringLiteral:
  4343. case common.SyntaxKind.SuperKeyword:
  4344. case common.SyntaxKind.TaggedTemplateExpression:
  4345. case common.SyntaxKind.TemplateExpression:
  4346. case common.SyntaxKind.ThisKeyword:
  4347. case common.SyntaxKind.TrueKeyword:
  4348. case common.SyntaxKind.TypeAssertionExpression:
  4349. case common.SyntaxKind.TypeOfExpression:
  4350. case common.SyntaxKind.VoidExpression:
  4351. case common.SyntaxKind.YieldExpression:
  4352. return true;
  4353. default:
  4354. return false;
  4355. }
  4356. }
  4357. static isExpressionable(node) {
  4358. switch (node?.getKind()) {
  4359. case common.SyntaxKind.ExternalModuleReference:
  4360. case common.SyntaxKind.JsxExpression:
  4361. case common.SyntaxKind.ReturnStatement:
  4362. case common.SyntaxKind.YieldExpression:
  4363. return true;
  4364. default:
  4365. return false;
  4366. }
  4367. }
  4368. static isExpressioned(node) {
  4369. switch (node?.getKind()) {
  4370. case common.SyntaxKind.AsExpression:
  4371. case common.SyntaxKind.CaseClause:
  4372. case common.SyntaxKind.ComputedPropertyName:
  4373. case common.SyntaxKind.DoStatement:
  4374. case common.SyntaxKind.ExportAssignment:
  4375. case common.SyntaxKind.ExpressionStatement:
  4376. case common.SyntaxKind.ForInStatement:
  4377. case common.SyntaxKind.ForOfStatement:
  4378. case common.SyntaxKind.IfStatement:
  4379. case common.SyntaxKind.JsxSpreadAttribute:
  4380. case common.SyntaxKind.NonNullExpression:
  4381. case common.SyntaxKind.ParenthesizedExpression:
  4382. case common.SyntaxKind.PartiallyEmittedExpression:
  4383. case common.SyntaxKind.SatisfiesExpression:
  4384. case common.SyntaxKind.SpreadAssignment:
  4385. case common.SyntaxKind.SpreadElement:
  4386. case common.SyntaxKind.SwitchStatement:
  4387. case common.SyntaxKind.TemplateSpan:
  4388. case common.SyntaxKind.ThrowStatement:
  4389. case common.SyntaxKind.WhileStatement:
  4390. case common.SyntaxKind.WithStatement:
  4391. return true;
  4392. default:
  4393. return false;
  4394. }
  4395. }
  4396. static isExpressionStatement = Node.is(common.SyntaxKind.ExpressionStatement);
  4397. static isExpressionWithTypeArguments = Node.is(common.SyntaxKind.ExpressionWithTypeArguments);
  4398. static isExtendsClauseable(node) {
  4399. return node?.getKind() === common.SyntaxKind.InterfaceDeclaration;
  4400. }
  4401. static isExternalModuleReference = Node.is(common.SyntaxKind.ExternalModuleReference);
  4402. static isFalseLiteral(node) {
  4403. return node?.getKind() === common.SyntaxKind.FalseKeyword;
  4404. }
  4405. static isForInStatement = Node.is(common.SyntaxKind.ForInStatement);
  4406. static isForOfStatement = Node.is(common.SyntaxKind.ForOfStatement);
  4407. static isForStatement = Node.is(common.SyntaxKind.ForStatement);
  4408. static isFunctionDeclaration = Node.is(common.SyntaxKind.FunctionDeclaration);
  4409. static isFunctionExpression = Node.is(common.SyntaxKind.FunctionExpression);
  4410. static isFunctionLikeDeclaration(node) {
  4411. switch (node?.getKind()) {
  4412. case common.SyntaxKind.ArrowFunction:
  4413. case common.SyntaxKind.Constructor:
  4414. case common.SyntaxKind.FunctionDeclaration:
  4415. case common.SyntaxKind.GetAccessor:
  4416. case common.SyntaxKind.MethodDeclaration:
  4417. case common.SyntaxKind.SetAccessor:
  4418. return true;
  4419. default:
  4420. return false;
  4421. }
  4422. }
  4423. static isFunctionTypeNode(node) {
  4424. return node?.getKind() === common.SyntaxKind.FunctionType;
  4425. }
  4426. static isGeneratorable(node) {
  4427. switch (node?.getKind()) {
  4428. case common.SyntaxKind.FunctionDeclaration:
  4429. case common.SyntaxKind.FunctionExpression:
  4430. case common.SyntaxKind.MethodDeclaration:
  4431. case common.SyntaxKind.YieldExpression:
  4432. return true;
  4433. default:
  4434. return false;
  4435. }
  4436. }
  4437. static isGetAccessorDeclaration(node) {
  4438. return node?.getKind() === common.SyntaxKind.GetAccessor;
  4439. }
  4440. static isHeritageClause = Node.is(common.SyntaxKind.HeritageClause);
  4441. static isHeritageClauseable(node) {
  4442. switch (node?.getKind()) {
  4443. case common.SyntaxKind.ClassDeclaration:
  4444. case common.SyntaxKind.ClassExpression:
  4445. case common.SyntaxKind.InterfaceDeclaration:
  4446. return true;
  4447. default:
  4448. return false;
  4449. }
  4450. }
  4451. static isIdentifier = Node.is(common.SyntaxKind.Identifier);
  4452. static isIfStatement = Node.is(common.SyntaxKind.IfStatement);
  4453. static isImplementsClauseable(node) {
  4454. switch (node?.getKind()) {
  4455. case common.SyntaxKind.ClassDeclaration:
  4456. case common.SyntaxKind.ClassExpression:
  4457. return true;
  4458. default:
  4459. return false;
  4460. }
  4461. }
  4462. static isImportAttribute = Node.is(common.SyntaxKind.ImportAttribute);
  4463. static isImportAttributeNamed(node) {
  4464. return node?.getKind() === common.SyntaxKind.ImportAttribute;
  4465. }
  4466. static isImportAttributes = Node.is(common.SyntaxKind.ImportAttributes);
  4467. static isImportClause = Node.is(common.SyntaxKind.ImportClause);
  4468. static isImportDeclaration = Node.is(common.SyntaxKind.ImportDeclaration);
  4469. static isImportEqualsDeclaration = Node.is(common.SyntaxKind.ImportEqualsDeclaration);
  4470. static isImportExpression(node) {
  4471. return node?.getKind() === common.SyntaxKind.ImportKeyword;
  4472. }
  4473. static isImportSpecifier = Node.is(common.SyntaxKind.ImportSpecifier);
  4474. static isImportTypeNode(node) {
  4475. return node?.getKind() === common.SyntaxKind.ImportType;
  4476. }
  4477. static isIndexedAccessTypeNode(node) {
  4478. return node?.getKind() === common.SyntaxKind.IndexedAccessType;
  4479. }
  4480. static isIndexSignatureDeclaration(node) {
  4481. return node?.getKind() === common.SyntaxKind.IndexSignature;
  4482. }
  4483. static isInferKeyword = Node.is(common.SyntaxKind.InferKeyword);
  4484. static isInferTypeNode(node) {
  4485. return node?.getKind() === common.SyntaxKind.InferType;
  4486. }
  4487. static isInitializerExpressionable(node) {
  4488. switch (node?.getKind()) {
  4489. case common.SyntaxKind.BindingElement:
  4490. case common.SyntaxKind.EnumMember:
  4491. case common.SyntaxKind.Parameter:
  4492. case common.SyntaxKind.PropertyDeclaration:
  4493. case common.SyntaxKind.PropertySignature:
  4494. case common.SyntaxKind.VariableDeclaration:
  4495. return true;
  4496. default:
  4497. return false;
  4498. }
  4499. }
  4500. static isInitializerExpressionGetable(node) {
  4501. switch (node?.getKind()) {
  4502. case common.SyntaxKind.BindingElement:
  4503. case common.SyntaxKind.EnumMember:
  4504. case common.SyntaxKind.Parameter:
  4505. case common.SyntaxKind.PropertyAssignment:
  4506. case common.SyntaxKind.PropertyDeclaration:
  4507. case common.SyntaxKind.PropertySignature:
  4508. case common.SyntaxKind.ShorthandPropertyAssignment:
  4509. case common.SyntaxKind.VariableDeclaration:
  4510. return true;
  4511. default:
  4512. return false;
  4513. }
  4514. }
  4515. static isInterfaceDeclaration = Node.is(common.SyntaxKind.InterfaceDeclaration);
  4516. static isIntersectionTypeNode(node) {
  4517. return node?.getKind() === common.SyntaxKind.IntersectionType;
  4518. }
  4519. static isIterationStatement(node) {
  4520. switch (node?.getKind()) {
  4521. case common.SyntaxKind.DoStatement:
  4522. case common.SyntaxKind.ForInStatement:
  4523. case common.SyntaxKind.ForOfStatement:
  4524. case common.SyntaxKind.ForStatement:
  4525. case common.SyntaxKind.WhileStatement:
  4526. return true;
  4527. default:
  4528. return false;
  4529. }
  4530. }
  4531. static isJSDoc = Node.is(common.SyntaxKind.JSDoc);
  4532. static isJSDocable(node) {
  4533. switch (node?.getKind()) {
  4534. case common.SyntaxKind.ArrowFunction:
  4535. case common.SyntaxKind.CallSignature:
  4536. case common.SyntaxKind.CaseClause:
  4537. case common.SyntaxKind.ClassDeclaration:
  4538. case common.SyntaxKind.ClassExpression:
  4539. case common.SyntaxKind.ClassStaticBlockDeclaration:
  4540. case common.SyntaxKind.Constructor:
  4541. case common.SyntaxKind.ConstructSignature:
  4542. case common.SyntaxKind.EnumDeclaration:
  4543. case common.SyntaxKind.EnumMember:
  4544. case common.SyntaxKind.ExportAssignment:
  4545. case common.SyntaxKind.ExpressionStatement:
  4546. case common.SyntaxKind.FunctionDeclaration:
  4547. case common.SyntaxKind.FunctionExpression:
  4548. case common.SyntaxKind.GetAccessor:
  4549. case common.SyntaxKind.ImportEqualsDeclaration:
  4550. case common.SyntaxKind.IndexSignature:
  4551. case common.SyntaxKind.InterfaceDeclaration:
  4552. case common.SyntaxKind.LabeledStatement:
  4553. case common.SyntaxKind.MethodDeclaration:
  4554. case common.SyntaxKind.MethodSignature:
  4555. case common.SyntaxKind.ModuleDeclaration:
  4556. case common.SyntaxKind.NamedTupleMember:
  4557. case common.SyntaxKind.PropertyDeclaration:
  4558. case common.SyntaxKind.PropertySignature:
  4559. case common.SyntaxKind.SetAccessor:
  4560. case common.SyntaxKind.TypeAliasDeclaration:
  4561. case common.SyntaxKind.VariableStatement:
  4562. return true;
  4563. default:
  4564. return false;
  4565. }
  4566. }
  4567. static isJSDocAllType = Node.is(common.SyntaxKind.JSDocAllType);
  4568. static isJSDocAugmentsTag = Node.is(common.SyntaxKind.JSDocAugmentsTag);
  4569. static isJSDocAuthorTag = Node.is(common.SyntaxKind.JSDocAuthorTag);
  4570. static isJSDocCallbackTag = Node.is(common.SyntaxKind.JSDocCallbackTag);
  4571. static isJSDocClassTag = Node.is(common.SyntaxKind.JSDocClassTag);
  4572. static isJSDocDeprecatedTag = Node.is(common.SyntaxKind.JSDocDeprecatedTag);
  4573. static isJSDocEnumTag = Node.is(common.SyntaxKind.JSDocEnumTag);
  4574. static isJSDocFunctionType = Node.is(common.SyntaxKind.JSDocFunctionType);
  4575. static isJSDocImplementsTag = Node.is(common.SyntaxKind.JSDocImplementsTag);
  4576. static isJSDocLink = Node.is(common.SyntaxKind.JSDocLink);
  4577. static isJSDocLinkCode = Node.is(common.SyntaxKind.JSDocLinkCode);
  4578. static isJSDocLinkPlain = Node.is(common.SyntaxKind.JSDocLinkPlain);
  4579. static isJSDocMemberName = Node.is(common.SyntaxKind.JSDocMemberName);
  4580. static isJSDocNamepathType = Node.is(common.SyntaxKind.JSDocNamepathType);
  4581. static isJSDocNameReference = Node.is(common.SyntaxKind.JSDocNameReference);
  4582. static isJSDocNonNullableType = Node.is(common.SyntaxKind.JSDocNonNullableType);
  4583. static isJSDocNullableType = Node.is(common.SyntaxKind.JSDocNullableType);
  4584. static isJSDocOptionalType = Node.is(common.SyntaxKind.JSDocOptionalType);
  4585. static isJSDocOverloadTag = Node.is(common.SyntaxKind.JSDocOverloadTag);
  4586. static isJSDocOverrideTag = Node.is(common.SyntaxKind.JSDocOverrideTag);
  4587. static isJSDocParameterTag = Node.is(common.SyntaxKind.JSDocParameterTag);
  4588. static isJSDocPrivateTag = Node.is(common.SyntaxKind.JSDocPrivateTag);
  4589. static isJSDocPropertyLikeTag(node) {
  4590. switch (node?.getKind()) {
  4591. case common.SyntaxKind.JSDocParameterTag:
  4592. case common.SyntaxKind.JSDocPropertyTag:
  4593. return true;
  4594. default:
  4595. return false;
  4596. }
  4597. }
  4598. static isJSDocPropertyTag = Node.is(common.SyntaxKind.JSDocPropertyTag);
  4599. static isJSDocProtectedTag = Node.is(common.SyntaxKind.JSDocProtectedTag);
  4600. static isJSDocPublicTag = Node.is(common.SyntaxKind.JSDocPublicTag);
  4601. static isJSDocReadonlyTag = Node.is(common.SyntaxKind.JSDocReadonlyTag);
  4602. static isJSDocReturnTag = Node.is(common.SyntaxKind.JSDocReturnTag);
  4603. static isJSDocSatisfiesTag = Node.is(common.SyntaxKind.JSDocSatisfiesTag);
  4604. static isJSDocSeeTag = Node.is(common.SyntaxKind.JSDocSeeTag);
  4605. static isJSDocSignature = Node.is(common.SyntaxKind.JSDocSignature);
  4606. static isJSDocTag(node) {
  4607. switch (node?.getKind()) {
  4608. case common.SyntaxKind.JSDocAugmentsTag:
  4609. case common.SyntaxKind.JSDocAuthorTag:
  4610. case common.SyntaxKind.JSDocCallbackTag:
  4611. case common.SyntaxKind.JSDocClassTag:
  4612. case common.SyntaxKind.JSDocDeprecatedTag:
  4613. case common.SyntaxKind.JSDocEnumTag:
  4614. case common.SyntaxKind.JSDocImplementsTag:
  4615. case common.SyntaxKind.JSDocOverloadTag:
  4616. case common.SyntaxKind.JSDocOverrideTag:
  4617. case common.SyntaxKind.JSDocParameterTag:
  4618. case common.SyntaxKind.JSDocPrivateTag:
  4619. case common.SyntaxKind.JSDocPropertyTag:
  4620. case common.SyntaxKind.JSDocProtectedTag:
  4621. case common.SyntaxKind.JSDocPublicTag:
  4622. case common.SyntaxKind.JSDocReadonlyTag:
  4623. case common.SyntaxKind.JSDocReturnTag:
  4624. case common.SyntaxKind.JSDocSatisfiesTag:
  4625. case common.SyntaxKind.JSDocSeeTag:
  4626. case common.SyntaxKind.JSDocTemplateTag:
  4627. case common.SyntaxKind.JSDocThisTag:
  4628. case common.SyntaxKind.JSDocThrowsTag:
  4629. case common.SyntaxKind.JSDocTypedefTag:
  4630. case common.SyntaxKind.JSDocTypeTag:
  4631. case common.SyntaxKind.JSDocTag:
  4632. return true;
  4633. default:
  4634. return false;
  4635. }
  4636. }
  4637. static isJSDocTemplateTag = Node.is(common.SyntaxKind.JSDocTemplateTag);
  4638. static isJSDocText = Node.is(common.SyntaxKind.JSDocText);
  4639. static isJSDocThisTag = Node.is(common.SyntaxKind.JSDocThisTag);
  4640. static isJSDocThrowsTag = Node.is(common.SyntaxKind.JSDocThrowsTag);
  4641. static isJSDocType(node) {
  4642. switch (node?.getKind()) {
  4643. case common.SyntaxKind.JSDocAllType:
  4644. case common.SyntaxKind.JSDocFunctionType:
  4645. case common.SyntaxKind.JSDocNamepathType:
  4646. case common.SyntaxKind.JSDocNonNullableType:
  4647. case common.SyntaxKind.JSDocNullableType:
  4648. case common.SyntaxKind.JSDocOptionalType:
  4649. case common.SyntaxKind.JSDocSignature:
  4650. case common.SyntaxKind.JSDocTypeLiteral:
  4651. case common.SyntaxKind.JSDocUnknownType:
  4652. case common.SyntaxKind.JSDocVariadicType:
  4653. return true;
  4654. default:
  4655. return false;
  4656. }
  4657. }
  4658. static isJSDocTypedefTag = Node.is(common.SyntaxKind.JSDocTypedefTag);
  4659. static isJSDocTypeExpression = Node.is(common.SyntaxKind.JSDocTypeExpression);
  4660. static isJSDocTypeExpressionableTag(node) {
  4661. switch (node?.getKind()) {
  4662. case common.SyntaxKind.JSDocOverloadTag:
  4663. case common.SyntaxKind.JSDocReturnTag:
  4664. case common.SyntaxKind.JSDocSatisfiesTag:
  4665. case common.SyntaxKind.JSDocSeeTag:
  4666. case common.SyntaxKind.JSDocThisTag:
  4667. case common.SyntaxKind.JSDocThrowsTag:
  4668. return true;
  4669. default:
  4670. return false;
  4671. }
  4672. }
  4673. static isJSDocTypeLiteral = Node.is(common.SyntaxKind.JSDocTypeLiteral);
  4674. static isJSDocTypeParameteredTag(node) {
  4675. return node?.getKind() === common.SyntaxKind.JSDocTemplateTag;
  4676. }
  4677. static isJSDocTypeTag = Node.is(common.SyntaxKind.JSDocTypeTag);
  4678. static isJSDocUnknownTag(node) {
  4679. return node?.getKind() === common.SyntaxKind.JSDocTag;
  4680. }
  4681. static isJSDocUnknownType = Node.is(common.SyntaxKind.JSDocUnknownType);
  4682. static isJSDocVariadicType = Node.is(common.SyntaxKind.JSDocVariadicType);
  4683. static isJsxAttribute = Node.is(common.SyntaxKind.JsxAttribute);
  4684. static isJsxAttributed(node) {
  4685. switch (node?.getKind()) {
  4686. case common.SyntaxKind.JsxOpeningElement:
  4687. case common.SyntaxKind.JsxSelfClosingElement:
  4688. return true;
  4689. default:
  4690. return false;
  4691. }
  4692. }
  4693. static isJsxClosingElement = Node.is(common.SyntaxKind.JsxClosingElement);
  4694. static isJsxClosingFragment = Node.is(common.SyntaxKind.JsxClosingFragment);
  4695. static isJsxElement = Node.is(common.SyntaxKind.JsxElement);
  4696. static isJsxExpression = Node.is(common.SyntaxKind.JsxExpression);
  4697. static isJsxFragment = Node.is(common.SyntaxKind.JsxFragment);
  4698. static isJsxNamespacedName = Node.is(common.SyntaxKind.JsxNamespacedName);
  4699. static isJsxOpeningElement = Node.is(common.SyntaxKind.JsxOpeningElement);
  4700. static isJsxOpeningFragment = Node.is(common.SyntaxKind.JsxOpeningFragment);
  4701. static isJsxSelfClosingElement = Node.is(common.SyntaxKind.JsxSelfClosingElement);
  4702. static isJsxSpreadAttribute = Node.is(common.SyntaxKind.JsxSpreadAttribute);
  4703. static isJsxTagNamed(node) {
  4704. switch (node?.getKind()) {
  4705. case common.SyntaxKind.JsxClosingElement:
  4706. case common.SyntaxKind.JsxOpeningElement:
  4707. case common.SyntaxKind.JsxSelfClosingElement:
  4708. return true;
  4709. default:
  4710. return false;
  4711. }
  4712. }
  4713. static isJsxText = Node.is(common.SyntaxKind.JsxText);
  4714. static isLabeledStatement = Node.is(common.SyntaxKind.LabeledStatement);
  4715. static isLeftHandSideExpression(node) {
  4716. switch (node?.getKind()) {
  4717. case common.SyntaxKind.ArrayLiteralExpression:
  4718. case common.SyntaxKind.BigIntLiteral:
  4719. case common.SyntaxKind.CallExpression:
  4720. case common.SyntaxKind.ClassExpression:
  4721. case common.SyntaxKind.ElementAccessExpression:
  4722. case common.SyntaxKind.FalseKeyword:
  4723. case common.SyntaxKind.FunctionExpression:
  4724. case common.SyntaxKind.Identifier:
  4725. case common.SyntaxKind.ImportKeyword:
  4726. case common.SyntaxKind.JsxElement:
  4727. case common.SyntaxKind.JsxFragment:
  4728. case common.SyntaxKind.JsxSelfClosingElement:
  4729. case common.SyntaxKind.MetaProperty:
  4730. case common.SyntaxKind.NewExpression:
  4731. case common.SyntaxKind.NonNullExpression:
  4732. case common.SyntaxKind.NoSubstitutionTemplateLiteral:
  4733. case common.SyntaxKind.NullKeyword:
  4734. case common.SyntaxKind.NumericLiteral:
  4735. case common.SyntaxKind.ObjectLiteralExpression:
  4736. case common.SyntaxKind.PropertyAccessExpression:
  4737. case common.SyntaxKind.RegularExpressionLiteral:
  4738. case common.SyntaxKind.StringLiteral:
  4739. case common.SyntaxKind.SuperKeyword:
  4740. case common.SyntaxKind.TaggedTemplateExpression:
  4741. case common.SyntaxKind.TemplateExpression:
  4742. case common.SyntaxKind.ThisKeyword:
  4743. case common.SyntaxKind.TrueKeyword:
  4744. return true;
  4745. default:
  4746. return false;
  4747. }
  4748. }
  4749. static isLeftHandSideExpressioned(node) {
  4750. switch (node?.getKind()) {
  4751. case common.SyntaxKind.CallExpression:
  4752. case common.SyntaxKind.Decorator:
  4753. case common.SyntaxKind.ElementAccessExpression:
  4754. case common.SyntaxKind.ExpressionWithTypeArguments:
  4755. case common.SyntaxKind.NewExpression:
  4756. case common.SyntaxKind.PropertyAccessExpression:
  4757. return true;
  4758. default:
  4759. return false;
  4760. }
  4761. }
  4762. static isLiteralExpression(node) {
  4763. switch (node?.getKind()) {
  4764. case common.SyntaxKind.BigIntLiteral:
  4765. case common.SyntaxKind.NoSubstitutionTemplateLiteral:
  4766. case common.SyntaxKind.NumericLiteral:
  4767. case common.SyntaxKind.RegularExpressionLiteral:
  4768. case common.SyntaxKind.StringLiteral:
  4769. return true;
  4770. default:
  4771. return false;
  4772. }
  4773. }
  4774. static isLiteralLike(node) {
  4775. switch (node?.getKind()) {
  4776. case common.SyntaxKind.BigIntLiteral:
  4777. case common.SyntaxKind.JsxText:
  4778. case common.SyntaxKind.NoSubstitutionTemplateLiteral:
  4779. case common.SyntaxKind.NumericLiteral:
  4780. case common.SyntaxKind.RegularExpressionLiteral:
  4781. case common.SyntaxKind.StringLiteral:
  4782. case common.SyntaxKind.TemplateHead:
  4783. case common.SyntaxKind.TemplateMiddle:
  4784. case common.SyntaxKind.TemplateTail:
  4785. return true;
  4786. default:
  4787. return false;
  4788. }
  4789. }
  4790. static isLiteralTypeNode(node) {
  4791. return node?.getKind() === common.SyntaxKind.LiteralType;
  4792. }
  4793. static isMappedTypeNode(node) {
  4794. return node?.getKind() === common.SyntaxKind.MappedType;
  4795. }
  4796. static isMemberExpression(node) {
  4797. switch (node?.getKind()) {
  4798. case common.SyntaxKind.ArrayLiteralExpression:
  4799. case common.SyntaxKind.BigIntLiteral:
  4800. case common.SyntaxKind.ClassExpression:
  4801. case common.SyntaxKind.ElementAccessExpression:
  4802. case common.SyntaxKind.FalseKeyword:
  4803. case common.SyntaxKind.FunctionExpression:
  4804. case common.SyntaxKind.Identifier:
  4805. case common.SyntaxKind.ImportKeyword:
  4806. case common.SyntaxKind.JsxElement:
  4807. case common.SyntaxKind.JsxFragment:
  4808. case common.SyntaxKind.JsxSelfClosingElement:
  4809. case common.SyntaxKind.MetaProperty:
  4810. case common.SyntaxKind.NewExpression:
  4811. case common.SyntaxKind.NoSubstitutionTemplateLiteral:
  4812. case common.SyntaxKind.NullKeyword:
  4813. case common.SyntaxKind.NumericLiteral:
  4814. case common.SyntaxKind.ObjectLiteralExpression:
  4815. case common.SyntaxKind.PropertyAccessExpression:
  4816. case common.SyntaxKind.RegularExpressionLiteral:
  4817. case common.SyntaxKind.StringLiteral:
  4818. case common.SyntaxKind.SuperKeyword:
  4819. case common.SyntaxKind.TaggedTemplateExpression:
  4820. case common.SyntaxKind.TemplateExpression:
  4821. case common.SyntaxKind.ThisKeyword:
  4822. case common.SyntaxKind.TrueKeyword:
  4823. return true;
  4824. default:
  4825. return false;
  4826. }
  4827. }
  4828. static isMetaProperty = Node.is(common.SyntaxKind.MetaProperty);
  4829. static isMethodDeclaration = Node.is(common.SyntaxKind.MethodDeclaration);
  4830. static isMethodSignature = Node.is(common.SyntaxKind.MethodSignature);
  4831. static isModifierable(node) {
  4832. switch (node?.getKind()) {
  4833. case common.SyntaxKind.ArrowFunction:
  4834. case common.SyntaxKind.ClassDeclaration:
  4835. case common.SyntaxKind.ClassExpression:
  4836. case common.SyntaxKind.Constructor:
  4837. case common.SyntaxKind.ConstructorType:
  4838. case common.SyntaxKind.EnumDeclaration:
  4839. case common.SyntaxKind.FunctionDeclaration:
  4840. case common.SyntaxKind.FunctionExpression:
  4841. case common.SyntaxKind.GetAccessor:
  4842. case common.SyntaxKind.ImportEqualsDeclaration:
  4843. case common.SyntaxKind.IndexSignature:
  4844. case common.SyntaxKind.InterfaceDeclaration:
  4845. case common.SyntaxKind.MethodDeclaration:
  4846. case common.SyntaxKind.ModuleDeclaration:
  4847. case common.SyntaxKind.Parameter:
  4848. case common.SyntaxKind.PropertyDeclaration:
  4849. case common.SyntaxKind.PropertySignature:
  4850. case common.SyntaxKind.SetAccessor:
  4851. case common.SyntaxKind.TypeAliasDeclaration:
  4852. case common.SyntaxKind.TypeParameter:
  4853. case common.SyntaxKind.VariableDeclarationList:
  4854. case common.SyntaxKind.VariableStatement:
  4855. return true;
  4856. default:
  4857. return false;
  4858. }
  4859. }
  4860. static isModuleBlock = Node.is(common.SyntaxKind.ModuleBlock);
  4861. static isModuleChildable(node) {
  4862. switch (node?.getKind()) {
  4863. case common.SyntaxKind.ClassDeclaration:
  4864. case common.SyntaxKind.EnumDeclaration:
  4865. case common.SyntaxKind.FunctionDeclaration:
  4866. case common.SyntaxKind.InterfaceDeclaration:
  4867. case common.SyntaxKind.ModuleDeclaration:
  4868. case common.SyntaxKind.VariableStatement:
  4869. return true;
  4870. default:
  4871. return false;
  4872. }
  4873. }
  4874. static isModuleDeclaration = Node.is(common.SyntaxKind.ModuleDeclaration);
  4875. static isModuled(node) {
  4876. switch (node?.getKind()) {
  4877. case common.SyntaxKind.ModuleDeclaration:
  4878. case common.SyntaxKind.SourceFile:
  4879. return true;
  4880. default:
  4881. return false;
  4882. }
  4883. }
  4884. static isModuleNamed(node) {
  4885. return node?.getKind() === common.SyntaxKind.ModuleDeclaration;
  4886. }
  4887. static isNameable(node) {
  4888. switch (node?.getKind()) {
  4889. case common.SyntaxKind.ClassDeclaration:
  4890. case common.SyntaxKind.ClassExpression:
  4891. case common.SyntaxKind.FunctionDeclaration:
  4892. case common.SyntaxKind.FunctionExpression:
  4893. return true;
  4894. default:
  4895. return false;
  4896. }
  4897. }
  4898. static isNamedExports = Node.is(common.SyntaxKind.NamedExports);
  4899. static isNamedImports = Node.is(common.SyntaxKind.NamedImports);
  4900. static isNamed(node) {
  4901. switch (node?.getKind()) {
  4902. case common.SyntaxKind.EnumDeclaration:
  4903. case common.SyntaxKind.ImportEqualsDeclaration:
  4904. case common.SyntaxKind.InterfaceDeclaration:
  4905. case common.SyntaxKind.MetaProperty:
  4906. case common.SyntaxKind.NamedTupleMember:
  4907. case common.SyntaxKind.PropertyAccessExpression:
  4908. case common.SyntaxKind.ShorthandPropertyAssignment:
  4909. case common.SyntaxKind.TypeAliasDeclaration:
  4910. case common.SyntaxKind.TypeParameter:
  4911. return true;
  4912. default:
  4913. return false;
  4914. }
  4915. }
  4916. static isNamedTupleMember = Node.is(common.SyntaxKind.NamedTupleMember);
  4917. static isNamespaceExport = Node.is(common.SyntaxKind.NamespaceExport);
  4918. static isNamespaceImport = Node.is(common.SyntaxKind.NamespaceImport);
  4919. static isNeverKeyword = Node.is(common.SyntaxKind.NeverKeyword);
  4920. static isNewExpression = Node.is(common.SyntaxKind.NewExpression);
  4921. static isNodeWithTypeArguments(node) {
  4922. switch (node?.getKind()) {
  4923. case common.SyntaxKind.ExpressionWithTypeArguments:
  4924. case common.SyntaxKind.ImportType:
  4925. case common.SyntaxKind.TypeQuery:
  4926. case common.SyntaxKind.TypeReference:
  4927. return true;
  4928. default:
  4929. return false;
  4930. }
  4931. }
  4932. static isNonNullExpression = Node.is(common.SyntaxKind.NonNullExpression);
  4933. static isNoSubstitutionTemplateLiteral = Node.is(common.SyntaxKind.NoSubstitutionTemplateLiteral);
  4934. static isNotEmittedStatement = Node.is(common.SyntaxKind.NotEmittedStatement);
  4935. static isNullLiteral(node) {
  4936. return node?.getKind() === common.SyntaxKind.NullKeyword;
  4937. }
  4938. static isNumberKeyword = Node.is(common.SyntaxKind.NumberKeyword);
  4939. static isNumericLiteral = Node.is(common.SyntaxKind.NumericLiteral);
  4940. static isObjectBindingPattern = Node.is(common.SyntaxKind.ObjectBindingPattern);
  4941. static isObjectKeyword = Node.is(common.SyntaxKind.ObjectKeyword);
  4942. static isObjectLiteralExpression = Node.is(common.SyntaxKind.ObjectLiteralExpression);
  4943. static isOmittedExpression = Node.is(common.SyntaxKind.OmittedExpression);
  4944. static isOverloadable(node) {
  4945. switch (node?.getKind()) {
  4946. case common.SyntaxKind.Constructor:
  4947. case common.SyntaxKind.FunctionDeclaration:
  4948. case common.SyntaxKind.MethodDeclaration:
  4949. return true;
  4950. default:
  4951. return false;
  4952. }
  4953. }
  4954. static isOverrideable(node) {
  4955. switch (node?.getKind()) {
  4956. case common.SyntaxKind.MethodDeclaration:
  4957. case common.SyntaxKind.Parameter:
  4958. case common.SyntaxKind.PropertyDeclaration:
  4959. return true;
  4960. default:
  4961. return false;
  4962. }
  4963. }
  4964. static isParameterDeclaration(node) {
  4965. return node?.getKind() === common.SyntaxKind.Parameter;
  4966. }
  4967. static isParametered(node) {
  4968. switch (node?.getKind()) {
  4969. case common.SyntaxKind.ArrowFunction:
  4970. case common.SyntaxKind.CallSignature:
  4971. case common.SyntaxKind.Constructor:
  4972. case common.SyntaxKind.ConstructorType:
  4973. case common.SyntaxKind.ConstructSignature:
  4974. case common.SyntaxKind.FunctionDeclaration:
  4975. case common.SyntaxKind.FunctionExpression:
  4976. case common.SyntaxKind.FunctionType:
  4977. case common.SyntaxKind.GetAccessor:
  4978. case common.SyntaxKind.JSDocFunctionType:
  4979. case common.SyntaxKind.MethodDeclaration:
  4980. case common.SyntaxKind.MethodSignature:
  4981. case common.SyntaxKind.SetAccessor:
  4982. return true;
  4983. default:
  4984. return false;
  4985. }
  4986. }
  4987. static isParenthesizedExpression = Node.is(common.SyntaxKind.ParenthesizedExpression);
  4988. static isParenthesizedTypeNode(node) {
  4989. return node?.getKind() === common.SyntaxKind.ParenthesizedType;
  4990. }
  4991. static isPartiallyEmittedExpression = Node.is(common.SyntaxKind.PartiallyEmittedExpression);
  4992. static isPostfixUnaryExpression = Node.is(common.SyntaxKind.PostfixUnaryExpression);
  4993. static isPrefixUnaryExpression = Node.is(common.SyntaxKind.PrefixUnaryExpression);
  4994. static isPrimaryExpression(node) {
  4995. switch (node?.getKind()) {
  4996. case common.SyntaxKind.ArrayLiteralExpression:
  4997. case common.SyntaxKind.BigIntLiteral:
  4998. case common.SyntaxKind.ClassExpression:
  4999. case common.SyntaxKind.FalseKeyword:
  5000. case common.SyntaxKind.FunctionExpression:
  5001. case common.SyntaxKind.Identifier:
  5002. case common.SyntaxKind.ImportKeyword:
  5003. case common.SyntaxKind.JsxElement:
  5004. case common.SyntaxKind.JsxFragment:
  5005. case common.SyntaxKind.JsxSelfClosingElement:
  5006. case common.SyntaxKind.MetaProperty:
  5007. case common.SyntaxKind.NewExpression:
  5008. case common.SyntaxKind.NoSubstitutionTemplateLiteral:
  5009. case common.SyntaxKind.NullKeyword:
  5010. case common.SyntaxKind.NumericLiteral:
  5011. case common.SyntaxKind.ObjectLiteralExpression:
  5012. case common.SyntaxKind.RegularExpressionLiteral:
  5013. case common.SyntaxKind.StringLiteral:
  5014. case common.SyntaxKind.SuperKeyword:
  5015. case common.SyntaxKind.TemplateExpression:
  5016. case common.SyntaxKind.ThisKeyword:
  5017. case common.SyntaxKind.TrueKeyword:
  5018. return true;
  5019. default:
  5020. return false;
  5021. }
  5022. }
  5023. static isPrivateIdentifier = Node.is(common.SyntaxKind.PrivateIdentifier);
  5024. static isPropertyAccessExpression = Node.is(common.SyntaxKind.PropertyAccessExpression);
  5025. static isPropertyAssignment = Node.is(common.SyntaxKind.PropertyAssignment);
  5026. static isPropertyDeclaration = Node.is(common.SyntaxKind.PropertyDeclaration);
  5027. static isPropertyNamed(node) {
  5028. switch (node?.getKind()) {
  5029. case common.SyntaxKind.EnumMember:
  5030. case common.SyntaxKind.GetAccessor:
  5031. case common.SyntaxKind.MethodDeclaration:
  5032. case common.SyntaxKind.MethodSignature:
  5033. case common.SyntaxKind.PropertyAssignment:
  5034. case common.SyntaxKind.PropertyDeclaration:
  5035. case common.SyntaxKind.PropertySignature:
  5036. case common.SyntaxKind.SetAccessor:
  5037. return true;
  5038. default:
  5039. return false;
  5040. }
  5041. }
  5042. static isPropertySignature = Node.is(common.SyntaxKind.PropertySignature);
  5043. static isQualifiedName = Node.is(common.SyntaxKind.QualifiedName);
  5044. static isQuestionDotTokenable(node) {
  5045. switch (node?.getKind()) {
  5046. case common.SyntaxKind.CallExpression:
  5047. case common.SyntaxKind.ElementAccessExpression:
  5048. case common.SyntaxKind.PropertyAccessExpression:
  5049. return true;
  5050. default:
  5051. return false;
  5052. }
  5053. }
  5054. static isQuestionTokenable(node) {
  5055. switch (node?.getKind()) {
  5056. case common.SyntaxKind.MethodDeclaration:
  5057. case common.SyntaxKind.MethodSignature:
  5058. case common.SyntaxKind.NamedTupleMember:
  5059. case common.SyntaxKind.Parameter:
  5060. case common.SyntaxKind.PropertyAssignment:
  5061. case common.SyntaxKind.PropertyDeclaration:
  5062. case common.SyntaxKind.PropertySignature:
  5063. case common.SyntaxKind.ShorthandPropertyAssignment:
  5064. return true;
  5065. default:
  5066. return false;
  5067. }
  5068. }
  5069. static isReadonlyable(node) {
  5070. switch (node?.getKind()) {
  5071. case common.SyntaxKind.IndexSignature:
  5072. case common.SyntaxKind.Parameter:
  5073. case common.SyntaxKind.PropertyDeclaration:
  5074. case common.SyntaxKind.PropertySignature:
  5075. return true;
  5076. default:
  5077. return false;
  5078. }
  5079. }
  5080. static isReferenceFindable(node) {
  5081. switch (node?.getKind()) {
  5082. case common.SyntaxKind.BindingElement:
  5083. case common.SyntaxKind.ClassDeclaration:
  5084. case common.SyntaxKind.ClassExpression:
  5085. case common.SyntaxKind.Constructor:
  5086. case common.SyntaxKind.EnumDeclaration:
  5087. case common.SyntaxKind.EnumMember:
  5088. case common.SyntaxKind.FunctionDeclaration:
  5089. case common.SyntaxKind.FunctionExpression:
  5090. case common.SyntaxKind.GetAccessor:
  5091. case common.SyntaxKind.Identifier:
  5092. case common.SyntaxKind.ImportAttribute:
  5093. case common.SyntaxKind.ImportEqualsDeclaration:
  5094. case common.SyntaxKind.InterfaceDeclaration:
  5095. case common.SyntaxKind.MetaProperty:
  5096. case common.SyntaxKind.MethodDeclaration:
  5097. case common.SyntaxKind.MethodSignature:
  5098. case common.SyntaxKind.ModuleDeclaration:
  5099. case common.SyntaxKind.NamedTupleMember:
  5100. case common.SyntaxKind.Parameter:
  5101. case common.SyntaxKind.PrivateIdentifier:
  5102. case common.SyntaxKind.PropertyAccessExpression:
  5103. case common.SyntaxKind.PropertyAssignment:
  5104. case common.SyntaxKind.PropertyDeclaration:
  5105. case common.SyntaxKind.PropertySignature:
  5106. case common.SyntaxKind.SetAccessor:
  5107. case common.SyntaxKind.ShorthandPropertyAssignment:
  5108. case common.SyntaxKind.TypeAliasDeclaration:
  5109. case common.SyntaxKind.TypeParameter:
  5110. case common.SyntaxKind.VariableDeclaration:
  5111. return true;
  5112. default:
  5113. return false;
  5114. }
  5115. }
  5116. static isRegularExpressionLiteral = Node.is(common.SyntaxKind.RegularExpressionLiteral);
  5117. static isRenameable(node) {
  5118. switch (node?.getKind()) {
  5119. case common.SyntaxKind.BindingElement:
  5120. case common.SyntaxKind.ClassDeclaration:
  5121. case common.SyntaxKind.ClassExpression:
  5122. case common.SyntaxKind.EnumDeclaration:
  5123. case common.SyntaxKind.EnumMember:
  5124. case common.SyntaxKind.FunctionDeclaration:
  5125. case common.SyntaxKind.FunctionExpression:
  5126. case common.SyntaxKind.GetAccessor:
  5127. case common.SyntaxKind.Identifier:
  5128. case common.SyntaxKind.ImportAttribute:
  5129. case common.SyntaxKind.ImportEqualsDeclaration:
  5130. case common.SyntaxKind.InterfaceDeclaration:
  5131. case common.SyntaxKind.MetaProperty:
  5132. case common.SyntaxKind.MethodDeclaration:
  5133. case common.SyntaxKind.MethodSignature:
  5134. case common.SyntaxKind.ModuleDeclaration:
  5135. case common.SyntaxKind.NamedTupleMember:
  5136. case common.SyntaxKind.NamespaceExport:
  5137. case common.SyntaxKind.NamespaceImport:
  5138. case common.SyntaxKind.Parameter:
  5139. case common.SyntaxKind.PrivateIdentifier:
  5140. case common.SyntaxKind.PropertyAccessExpression:
  5141. case common.SyntaxKind.PropertyAssignment:
  5142. case common.SyntaxKind.PropertyDeclaration:
  5143. case common.SyntaxKind.PropertySignature:
  5144. case common.SyntaxKind.SetAccessor:
  5145. case common.SyntaxKind.ShorthandPropertyAssignment:
  5146. case common.SyntaxKind.TypeAliasDeclaration:
  5147. case common.SyntaxKind.TypeParameter:
  5148. case common.SyntaxKind.VariableDeclaration:
  5149. return true;
  5150. default:
  5151. return false;
  5152. }
  5153. }
  5154. static isRestTypeNode(node) {
  5155. return node?.getKind() === common.SyntaxKind.RestType;
  5156. }
  5157. static isReturnStatement = Node.is(common.SyntaxKind.ReturnStatement);
  5158. static isReturnTyped(node) {
  5159. switch (node?.getKind()) {
  5160. case common.SyntaxKind.ArrowFunction:
  5161. case common.SyntaxKind.CallSignature:
  5162. case common.SyntaxKind.Constructor:
  5163. case common.SyntaxKind.ConstructorType:
  5164. case common.SyntaxKind.ConstructSignature:
  5165. case common.SyntaxKind.FunctionDeclaration:
  5166. case common.SyntaxKind.FunctionExpression:
  5167. case common.SyntaxKind.FunctionType:
  5168. case common.SyntaxKind.GetAccessor:
  5169. case common.SyntaxKind.IndexSignature:
  5170. case common.SyntaxKind.JSDocFunctionType:
  5171. case common.SyntaxKind.MethodDeclaration:
  5172. case common.SyntaxKind.MethodSignature:
  5173. case common.SyntaxKind.SetAccessor:
  5174. return true;
  5175. default:
  5176. return false;
  5177. }
  5178. }
  5179. static isSatisfiesExpression = Node.is(common.SyntaxKind.SatisfiesExpression);
  5180. static isScopeable(node) {
  5181. return node?.getKind() === common.SyntaxKind.Parameter;
  5182. }
  5183. static isScoped(node) {
  5184. switch (node?.getKind()) {
  5185. case common.SyntaxKind.Constructor:
  5186. case common.SyntaxKind.GetAccessor:
  5187. case common.SyntaxKind.MethodDeclaration:
  5188. case common.SyntaxKind.PropertyDeclaration:
  5189. case common.SyntaxKind.SetAccessor:
  5190. return true;
  5191. default:
  5192. return false;
  5193. }
  5194. }
  5195. static isSemicolonToken = Node.is(common.SyntaxKind.SemicolonToken);
  5196. static isSetAccessorDeclaration(node) {
  5197. return node?.getKind() === common.SyntaxKind.SetAccessor;
  5198. }
  5199. static isShorthandPropertyAssignment = Node.is(common.SyntaxKind.ShorthandPropertyAssignment);
  5200. static isSignaturedDeclaration(node) {
  5201. switch (node?.getKind()) {
  5202. case common.SyntaxKind.ArrowFunction:
  5203. case common.SyntaxKind.CallSignature:
  5204. case common.SyntaxKind.Constructor:
  5205. case common.SyntaxKind.ConstructorType:
  5206. case common.SyntaxKind.ConstructSignature:
  5207. case common.SyntaxKind.FunctionDeclaration:
  5208. case common.SyntaxKind.FunctionExpression:
  5209. case common.SyntaxKind.FunctionType:
  5210. case common.SyntaxKind.GetAccessor:
  5211. case common.SyntaxKind.JSDocFunctionType:
  5212. case common.SyntaxKind.MethodDeclaration:
  5213. case common.SyntaxKind.MethodSignature:
  5214. case common.SyntaxKind.SetAccessor:
  5215. return true;
  5216. default:
  5217. return false;
  5218. }
  5219. }
  5220. static isSourceFile = Node.is(common.SyntaxKind.SourceFile);
  5221. static isSpreadAssignment = Node.is(common.SyntaxKind.SpreadAssignment);
  5222. static isSpreadElement = Node.is(common.SyntaxKind.SpreadElement);
  5223. static isStatement(node) {
  5224. switch (node?.getKind()) {
  5225. case common.SyntaxKind.Block:
  5226. case common.SyntaxKind.BreakStatement:
  5227. case common.SyntaxKind.ClassDeclaration:
  5228. case common.SyntaxKind.ContinueStatement:
  5229. case common.SyntaxKind.DebuggerStatement:
  5230. case common.SyntaxKind.DoStatement:
  5231. case common.SyntaxKind.EmptyStatement:
  5232. case common.SyntaxKind.EnumDeclaration:
  5233. case common.SyntaxKind.ExportAssignment:
  5234. case common.SyntaxKind.ExportDeclaration:
  5235. case common.SyntaxKind.ExpressionStatement:
  5236. case common.SyntaxKind.ForInStatement:
  5237. case common.SyntaxKind.ForOfStatement:
  5238. case common.SyntaxKind.ForStatement:
  5239. case common.SyntaxKind.FunctionDeclaration:
  5240. case common.SyntaxKind.IfStatement:
  5241. case common.SyntaxKind.ImportDeclaration:
  5242. case common.SyntaxKind.ImportEqualsDeclaration:
  5243. case common.SyntaxKind.InterfaceDeclaration:
  5244. case common.SyntaxKind.LabeledStatement:
  5245. case common.SyntaxKind.ModuleBlock:
  5246. case common.SyntaxKind.ModuleDeclaration:
  5247. case common.SyntaxKind.NotEmittedStatement:
  5248. case common.SyntaxKind.ReturnStatement:
  5249. case common.SyntaxKind.SwitchStatement:
  5250. case common.SyntaxKind.ThrowStatement:
  5251. case common.SyntaxKind.TryStatement:
  5252. case common.SyntaxKind.TypeAliasDeclaration:
  5253. case common.SyntaxKind.VariableStatement:
  5254. case common.SyntaxKind.WhileStatement:
  5255. case common.SyntaxKind.WithStatement:
  5256. return true;
  5257. default:
  5258. return false;
  5259. }
  5260. }
  5261. static isStatemented(node) {
  5262. switch (node?.getKind()) {
  5263. case common.SyntaxKind.ArrowFunction:
  5264. case common.SyntaxKind.Block:
  5265. case common.SyntaxKind.CaseClause:
  5266. case common.SyntaxKind.ClassStaticBlockDeclaration:
  5267. case common.SyntaxKind.Constructor:
  5268. case common.SyntaxKind.DefaultClause:
  5269. case common.SyntaxKind.FunctionDeclaration:
  5270. case common.SyntaxKind.FunctionExpression:
  5271. case common.SyntaxKind.GetAccessor:
  5272. case common.SyntaxKind.MethodDeclaration:
  5273. case common.SyntaxKind.ModuleBlock:
  5274. case common.SyntaxKind.ModuleDeclaration:
  5275. case common.SyntaxKind.SetAccessor:
  5276. case common.SyntaxKind.SourceFile:
  5277. return true;
  5278. default:
  5279. return false;
  5280. }
  5281. }
  5282. static isStaticable(node) {
  5283. switch (node?.getKind()) {
  5284. case common.SyntaxKind.GetAccessor:
  5285. case common.SyntaxKind.MethodDeclaration:
  5286. case common.SyntaxKind.PropertyDeclaration:
  5287. case common.SyntaxKind.SetAccessor:
  5288. return true;
  5289. default:
  5290. return false;
  5291. }
  5292. }
  5293. static isStringKeyword = Node.is(common.SyntaxKind.StringKeyword);
  5294. static isStringLiteral = Node.is(common.SyntaxKind.StringLiteral);
  5295. static isSuperExpression(node) {
  5296. return node?.getKind() === common.SyntaxKind.SuperKeyword;
  5297. }
  5298. static isSwitchStatement = Node.is(common.SyntaxKind.SwitchStatement);
  5299. static isSymbolKeyword = Node.is(common.SyntaxKind.SymbolKeyword);
  5300. static isSyntaxList = Node.is(common.SyntaxKind.SyntaxList);
  5301. static isTaggedTemplateExpression = Node.is(common.SyntaxKind.TaggedTemplateExpression);
  5302. static isTemplateExpression = Node.is(common.SyntaxKind.TemplateExpression);
  5303. static isTemplateHead = Node.is(common.SyntaxKind.TemplateHead);
  5304. static isTemplateLiteralTypeNode(node) {
  5305. return node?.getKind() === common.SyntaxKind.TemplateLiteralType;
  5306. }
  5307. static isTemplateMiddle = Node.is(common.SyntaxKind.TemplateMiddle);
  5308. static isTemplateSpan = Node.is(common.SyntaxKind.TemplateSpan);
  5309. static isTemplateTail = Node.is(common.SyntaxKind.TemplateTail);
  5310. static isTextInsertable(node) {
  5311. switch (node?.getKind()) {
  5312. case common.SyntaxKind.ArrowFunction:
  5313. case common.SyntaxKind.Block:
  5314. case common.SyntaxKind.CaseBlock:
  5315. case common.SyntaxKind.CaseClause:
  5316. case common.SyntaxKind.ClassDeclaration:
  5317. case common.SyntaxKind.ClassExpression:
  5318. case common.SyntaxKind.ClassStaticBlockDeclaration:
  5319. case common.SyntaxKind.Constructor:
  5320. case common.SyntaxKind.DefaultClause:
  5321. case common.SyntaxKind.EnumDeclaration:
  5322. case common.SyntaxKind.FunctionDeclaration:
  5323. case common.SyntaxKind.FunctionExpression:
  5324. case common.SyntaxKind.GetAccessor:
  5325. case common.SyntaxKind.InterfaceDeclaration:
  5326. case common.SyntaxKind.MethodDeclaration:
  5327. case common.SyntaxKind.ModuleDeclaration:
  5328. case common.SyntaxKind.SetAccessor:
  5329. case common.SyntaxKind.SourceFile:
  5330. return true;
  5331. default:
  5332. return false;
  5333. }
  5334. }
  5335. static isThisExpression(node) {
  5336. return node?.getKind() === common.SyntaxKind.ThisKeyword;
  5337. }
  5338. static isThisTypeNode(node) {
  5339. return node?.getKind() === common.SyntaxKind.ThisType;
  5340. }
  5341. static isThrowStatement = Node.is(common.SyntaxKind.ThrowStatement);
  5342. static isTrueLiteral(node) {
  5343. return node?.getKind() === common.SyntaxKind.TrueKeyword;
  5344. }
  5345. static isTryStatement = Node.is(common.SyntaxKind.TryStatement);
  5346. static isTupleTypeNode(node) {
  5347. return node?.getKind() === common.SyntaxKind.TupleType;
  5348. }
  5349. static isTypeAliasDeclaration = Node.is(common.SyntaxKind.TypeAliasDeclaration);
  5350. static isTypeArgumented(node) {
  5351. switch (node?.getKind()) {
  5352. case common.SyntaxKind.CallExpression:
  5353. case common.SyntaxKind.ExpressionWithTypeArguments:
  5354. case common.SyntaxKind.ImportType:
  5355. case common.SyntaxKind.NewExpression:
  5356. case common.SyntaxKind.TypeQuery:
  5357. case common.SyntaxKind.TypeReference:
  5358. return true;
  5359. default:
  5360. return false;
  5361. }
  5362. }
  5363. static isTypeAssertion(node) {
  5364. return node?.getKind() === common.SyntaxKind.TypeAssertionExpression;
  5365. }
  5366. static isTyped(node) {
  5367. switch (node?.getKind()) {
  5368. case common.SyntaxKind.AsExpression:
  5369. case common.SyntaxKind.NamedTupleMember:
  5370. case common.SyntaxKind.Parameter:
  5371. case common.SyntaxKind.PropertyDeclaration:
  5372. case common.SyntaxKind.PropertySignature:
  5373. case common.SyntaxKind.SatisfiesExpression:
  5374. case common.SyntaxKind.TypeAliasDeclaration:
  5375. case common.SyntaxKind.TypeAssertionExpression:
  5376. case common.SyntaxKind.VariableDeclaration:
  5377. return true;
  5378. default:
  5379. return false;
  5380. }
  5381. }
  5382. static isTypeElement(node) {
  5383. switch (node?.getKind()) {
  5384. case common.SyntaxKind.CallSignature:
  5385. case common.SyntaxKind.ConstructSignature:
  5386. case common.SyntaxKind.IndexSignature:
  5387. case common.SyntaxKind.MethodSignature:
  5388. case common.SyntaxKind.PropertySignature:
  5389. return true;
  5390. default:
  5391. return false;
  5392. }
  5393. }
  5394. static isTypeElementMembered(node) {
  5395. switch (node?.getKind()) {
  5396. case common.SyntaxKind.InterfaceDeclaration:
  5397. case common.SyntaxKind.TypeLiteral:
  5398. return true;
  5399. default:
  5400. return false;
  5401. }
  5402. }
  5403. static isTypeLiteral(node) {
  5404. return node?.getKind() === common.SyntaxKind.TypeLiteral;
  5405. }
  5406. static isTypeNode(node) {
  5407. switch (node?.getKind()) {
  5408. case common.SyntaxKind.ArrayType:
  5409. case common.SyntaxKind.ConditionalType:
  5410. case common.SyntaxKind.ConstructorType:
  5411. case common.SyntaxKind.ExpressionWithTypeArguments:
  5412. case common.SyntaxKind.FunctionType:
  5413. case common.SyntaxKind.ImportType:
  5414. case common.SyntaxKind.IndexedAccessType:
  5415. case common.SyntaxKind.InferType:
  5416. case common.SyntaxKind.IntersectionType:
  5417. case common.SyntaxKind.JSDocAllType:
  5418. case common.SyntaxKind.JSDocFunctionType:
  5419. case common.SyntaxKind.JSDocNamepathType:
  5420. case common.SyntaxKind.JSDocNonNullableType:
  5421. case common.SyntaxKind.JSDocNullableType:
  5422. case common.SyntaxKind.JSDocOptionalType:
  5423. case common.SyntaxKind.JSDocSignature:
  5424. case common.SyntaxKind.JSDocTypeExpression:
  5425. case common.SyntaxKind.JSDocTypeLiteral:
  5426. case common.SyntaxKind.JSDocUnknownType:
  5427. case common.SyntaxKind.JSDocVariadicType:
  5428. case common.SyntaxKind.LiteralType:
  5429. case common.SyntaxKind.MappedType:
  5430. case common.SyntaxKind.NamedTupleMember:
  5431. case common.SyntaxKind.ParenthesizedType:
  5432. case common.SyntaxKind.RestType:
  5433. case common.SyntaxKind.TemplateLiteralType:
  5434. case common.SyntaxKind.ThisType:
  5435. case common.SyntaxKind.TupleType:
  5436. case common.SyntaxKind.TypeLiteral:
  5437. case common.SyntaxKind.TypeOperator:
  5438. case common.SyntaxKind.TypePredicate:
  5439. case common.SyntaxKind.TypeQuery:
  5440. case common.SyntaxKind.TypeReference:
  5441. case common.SyntaxKind.UnionType:
  5442. return true;
  5443. default:
  5444. return false;
  5445. }
  5446. }
  5447. static isTypeOfExpression = Node.is(common.SyntaxKind.TypeOfExpression);
  5448. static isTypeOperatorTypeNode(node) {
  5449. return node?.getKind() === common.SyntaxKind.TypeOperator;
  5450. }
  5451. static isTypeParameterDeclaration(node) {
  5452. return node?.getKind() === common.SyntaxKind.TypeParameter;
  5453. }
  5454. static isTypeParametered(node) {
  5455. switch (node?.getKind()) {
  5456. case common.SyntaxKind.ArrowFunction:
  5457. case common.SyntaxKind.CallSignature:
  5458. case common.SyntaxKind.ClassDeclaration:
  5459. case common.SyntaxKind.ClassExpression:
  5460. case common.SyntaxKind.Constructor:
  5461. case common.SyntaxKind.ConstructSignature:
  5462. case common.SyntaxKind.FunctionDeclaration:
  5463. case common.SyntaxKind.FunctionExpression:
  5464. case common.SyntaxKind.FunctionType:
  5465. case common.SyntaxKind.GetAccessor:
  5466. case common.SyntaxKind.InterfaceDeclaration:
  5467. case common.SyntaxKind.MethodDeclaration:
  5468. case common.SyntaxKind.MethodSignature:
  5469. case common.SyntaxKind.SetAccessor:
  5470. case common.SyntaxKind.TypeAliasDeclaration:
  5471. return true;
  5472. default:
  5473. return false;
  5474. }
  5475. }
  5476. static isTypePredicate(node) {
  5477. return node?.getKind() === common.SyntaxKind.TypePredicate;
  5478. }
  5479. static isTypeQuery(node) {
  5480. return node?.getKind() === common.SyntaxKind.TypeQuery;
  5481. }
  5482. static isTypeReference(node) {
  5483. return node?.getKind() === common.SyntaxKind.TypeReference;
  5484. }
  5485. static isUnaryExpression(node) {
  5486. switch (node?.getKind()) {
  5487. case common.SyntaxKind.ArrayLiteralExpression:
  5488. case common.SyntaxKind.AwaitExpression:
  5489. case common.SyntaxKind.BigIntLiteral:
  5490. case common.SyntaxKind.CallExpression:
  5491. case common.SyntaxKind.ClassExpression:
  5492. case common.SyntaxKind.DeleteExpression:
  5493. case common.SyntaxKind.ElementAccessExpression:
  5494. case common.SyntaxKind.FalseKeyword:
  5495. case common.SyntaxKind.FunctionExpression:
  5496. case common.SyntaxKind.Identifier:
  5497. case common.SyntaxKind.ImportKeyword:
  5498. case common.SyntaxKind.JsxElement:
  5499. case common.SyntaxKind.JsxFragment:
  5500. case common.SyntaxKind.JsxSelfClosingElement:
  5501. case common.SyntaxKind.MetaProperty:
  5502. case common.SyntaxKind.NewExpression:
  5503. case common.SyntaxKind.NonNullExpression:
  5504. case common.SyntaxKind.NoSubstitutionTemplateLiteral:
  5505. case common.SyntaxKind.NullKeyword:
  5506. case common.SyntaxKind.NumericLiteral:
  5507. case common.SyntaxKind.ObjectLiteralExpression:
  5508. case common.SyntaxKind.PostfixUnaryExpression:
  5509. case common.SyntaxKind.PrefixUnaryExpression:
  5510. case common.SyntaxKind.PropertyAccessExpression:
  5511. case common.SyntaxKind.RegularExpressionLiteral:
  5512. case common.SyntaxKind.StringLiteral:
  5513. case common.SyntaxKind.SuperKeyword:
  5514. case common.SyntaxKind.TaggedTemplateExpression:
  5515. case common.SyntaxKind.TemplateExpression:
  5516. case common.SyntaxKind.ThisKeyword:
  5517. case common.SyntaxKind.TrueKeyword:
  5518. case common.SyntaxKind.TypeAssertionExpression:
  5519. case common.SyntaxKind.TypeOfExpression:
  5520. case common.SyntaxKind.VoidExpression:
  5521. return true;
  5522. default:
  5523. return false;
  5524. }
  5525. }
  5526. static isUnaryExpressioned(node) {
  5527. switch (node?.getKind()) {
  5528. case common.SyntaxKind.AwaitExpression:
  5529. case common.SyntaxKind.DeleteExpression:
  5530. case common.SyntaxKind.TypeAssertionExpression:
  5531. case common.SyntaxKind.TypeOfExpression:
  5532. case common.SyntaxKind.VoidExpression:
  5533. return true;
  5534. default:
  5535. return false;
  5536. }
  5537. }
  5538. static isUndefinedKeyword = Node.is(common.SyntaxKind.UndefinedKeyword);
  5539. static isUnionTypeNode(node) {
  5540. return node?.getKind() === common.SyntaxKind.UnionType;
  5541. }
  5542. static isUnwrappable(node) {
  5543. switch (node?.getKind()) {
  5544. case common.SyntaxKind.FunctionDeclaration:
  5545. case common.SyntaxKind.ModuleDeclaration:
  5546. return true;
  5547. default:
  5548. return false;
  5549. }
  5550. }
  5551. static isUpdateExpression(node) {
  5552. switch (node?.getKind()) {
  5553. case common.SyntaxKind.ArrayLiteralExpression:
  5554. case common.SyntaxKind.BigIntLiteral:
  5555. case common.SyntaxKind.CallExpression:
  5556. case common.SyntaxKind.ClassExpression:
  5557. case common.SyntaxKind.ElementAccessExpression:
  5558. case common.SyntaxKind.FalseKeyword:
  5559. case common.SyntaxKind.FunctionExpression:
  5560. case common.SyntaxKind.Identifier:
  5561. case common.SyntaxKind.ImportKeyword:
  5562. case common.SyntaxKind.JsxElement:
  5563. case common.SyntaxKind.JsxFragment:
  5564. case common.SyntaxKind.JsxSelfClosingElement:
  5565. case common.SyntaxKind.MetaProperty:
  5566. case common.SyntaxKind.NewExpression:
  5567. case common.SyntaxKind.NonNullExpression:
  5568. case common.SyntaxKind.NoSubstitutionTemplateLiteral:
  5569. case common.SyntaxKind.NullKeyword:
  5570. case common.SyntaxKind.NumericLiteral:
  5571. case common.SyntaxKind.ObjectLiteralExpression:
  5572. case common.SyntaxKind.PropertyAccessExpression:
  5573. case common.SyntaxKind.RegularExpressionLiteral:
  5574. case common.SyntaxKind.StringLiteral:
  5575. case common.SyntaxKind.SuperKeyword:
  5576. case common.SyntaxKind.TaggedTemplateExpression:
  5577. case common.SyntaxKind.TemplateExpression:
  5578. case common.SyntaxKind.ThisKeyword:
  5579. case common.SyntaxKind.TrueKeyword:
  5580. return true;
  5581. default:
  5582. return false;
  5583. }
  5584. }
  5585. static isVariableDeclaration = Node.is(common.SyntaxKind.VariableDeclaration);
  5586. static isVariableDeclarationList = Node.is(common.SyntaxKind.VariableDeclarationList);
  5587. static isVariableStatement = Node.is(common.SyntaxKind.VariableStatement);
  5588. static isVoidExpression = Node.is(common.SyntaxKind.VoidExpression);
  5589. static isWhileStatement = Node.is(common.SyntaxKind.WhileStatement);
  5590. static isWithStatement = Node.is(common.SyntaxKind.WithStatement);
  5591. static isYieldExpression = Node.is(common.SyntaxKind.YieldExpression);
  5592. static _hasStructure(node) {
  5593. switch (node?.getKind()) {
  5594. case common.SyntaxKind.CallSignature:
  5595. case common.SyntaxKind.ClassDeclaration:
  5596. case common.SyntaxKind.ClassStaticBlockDeclaration:
  5597. case common.SyntaxKind.Constructor:
  5598. case common.SyntaxKind.ConstructSignature:
  5599. case common.SyntaxKind.Decorator:
  5600. case common.SyntaxKind.EnumDeclaration:
  5601. case common.SyntaxKind.EnumMember:
  5602. case common.SyntaxKind.ExportAssignment:
  5603. case common.SyntaxKind.ExportDeclaration:
  5604. case common.SyntaxKind.ExportSpecifier:
  5605. case common.SyntaxKind.FunctionDeclaration:
  5606. case common.SyntaxKind.GetAccessor:
  5607. case common.SyntaxKind.ImportAttribute:
  5608. case common.SyntaxKind.ImportDeclaration:
  5609. case common.SyntaxKind.ImportSpecifier:
  5610. case common.SyntaxKind.IndexSignature:
  5611. case common.SyntaxKind.InterfaceDeclaration:
  5612. case common.SyntaxKind.JSDoc:
  5613. case common.SyntaxKind.JsxAttribute:
  5614. case common.SyntaxKind.JsxElement:
  5615. case common.SyntaxKind.JsxNamespacedName:
  5616. case common.SyntaxKind.JsxSelfClosingElement:
  5617. case common.SyntaxKind.JsxSpreadAttribute:
  5618. case common.SyntaxKind.MethodDeclaration:
  5619. case common.SyntaxKind.MethodSignature:
  5620. case common.SyntaxKind.ModuleDeclaration:
  5621. case common.SyntaxKind.Parameter:
  5622. case common.SyntaxKind.PropertyAssignment:
  5623. case common.SyntaxKind.PropertyDeclaration:
  5624. case common.SyntaxKind.PropertySignature:
  5625. case common.SyntaxKind.SetAccessor:
  5626. case common.SyntaxKind.ShorthandPropertyAssignment:
  5627. case common.SyntaxKind.SourceFile:
  5628. case common.SyntaxKind.SpreadAssignment:
  5629. case common.SyntaxKind.TypeAliasDeclaration:
  5630. case common.SyntaxKind.TypeParameter:
  5631. case common.SyntaxKind.VariableDeclaration:
  5632. case common.SyntaxKind.VariableStatement:
  5633. return true;
  5634. default:
  5635. return false;
  5636. }
  5637. }
  5638. }
  5639. function getWrappedCondition(thisNode, condition) {
  5640. return condition == null ? undefined : ((c) => condition(thisNode._getNodeFromCompilerNode(c)));
  5641. }
  5642. function insertWhiteSpaceTextAtPos(node, insertPos, textOrWriterFunction, methodName) {
  5643. const parent = Node.isSourceFile(node) ? node.getChildSyntaxListOrThrow() : node.getParentSyntaxList() || node.getParentOrThrow();
  5644. const newText = getTextFromStringOrWriter(node._getWriterWithQueuedIndentation(), textOrWriterFunction);
  5645. if (!/^[\s\r\n]*$/.test(newText))
  5646. throw new common.errors.InvalidOperationError(`Cannot insert non-whitespace into ${methodName}.`);
  5647. insertIntoParentTextRange({
  5648. parent,
  5649. insertPos,
  5650. newText,
  5651. });
  5652. }
  5653. function* getCompilerForEachDescendantsIterator(node) {
  5654. for (const child of getForEachChildren()) {
  5655. yield child;
  5656. yield* getCompilerForEachDescendantsIterator(child);
  5657. }
  5658. function getForEachChildren() {
  5659. const children = [];
  5660. node.forEachChild(child => {
  5661. children.push(child);
  5662. });
  5663. return children;
  5664. }
  5665. }
  5666. function* getCompilerDescendantsIterator(node, sourceFile) {
  5667. for (const child of ExtendedParser.getCompilerChildren(node, sourceFile)) {
  5668. yield child;
  5669. yield* getCompilerDescendantsIterator(child, sourceFile);
  5670. }
  5671. }
  5672. function useParseTreeSearchForKind(thisNodeOrSyntaxKind, searchingKind) {
  5673. return searchingKind >= common.SyntaxKind.FirstNode && searchingKind < common.SyntaxKind.FirstJSDocNode
  5674. && getThisKind() !== common.SyntaxKind.SyntaxList;
  5675. function getThisKind() {
  5676. if (typeof thisNodeOrSyntaxKind === "number")
  5677. return thisNodeOrSyntaxKind;
  5678. return thisNodeOrSyntaxKind.compilerNode.kind;
  5679. }
  5680. }
  5681. exports.Scope = void 0;
  5682. (function (Scope) {
  5683. Scope["Public"] = "public";
  5684. Scope["Protected"] = "protected";
  5685. Scope["Private"] = "private";
  5686. })(exports.Scope || (exports.Scope = {}));
  5687. class SyntaxList extends Node {
  5688. addChildText(textOrWriterFunction) {
  5689. return this.insertChildText(this.getChildCount(), textOrWriterFunction);
  5690. }
  5691. insertChildText(index, textOrWriterFunction) {
  5692. const initialChildCount = this.getChildCount();
  5693. const newLineKind = this._context.manipulationSettings.getNewLineKindAsString();
  5694. const parent = this.getParentOrThrow();
  5695. index = verifyAndGetIndex(index, initialChildCount);
  5696. const isInline = this !== parent.getChildSyntaxList();
  5697. let insertText = getTextFromStringOrWriter(isInline ? parent._getWriterWithQueuedChildIndentation() : parent._getWriterWithChildIndentation(), textOrWriterFunction);
  5698. if (insertText.length === 0)
  5699. return [];
  5700. if (isInline) {
  5701. if (index === 0)
  5702. insertText += " ";
  5703. else
  5704. insertText = " " + insertText;
  5705. }
  5706. else {
  5707. if (index === 0 && Node.isSourceFile(parent)) {
  5708. if (!insertText.endsWith("\n"))
  5709. insertText += newLineKind;
  5710. }
  5711. else {
  5712. insertText = newLineKind + insertText;
  5713. if (!Node.isSourceFile(parent) && index === initialChildCount && insertText.endsWith("\n"))
  5714. insertText = insertText.replace(/\r?\n$/, "");
  5715. }
  5716. }
  5717. const insertPos = getInsertPosFromIndex(index, this, this.getChildren());
  5718. insertIntoParentTextRange({
  5719. insertPos,
  5720. newText: insertText,
  5721. parent: this,
  5722. });
  5723. const finalChildren = this.getChildren();
  5724. return getNodesToReturn(initialChildCount, finalChildren, index, true);
  5725. }
  5726. }
  5727. function renameNode(node, newName, options) {
  5728. common.errors.throwIfWhitespaceOrNotString(newName, "newName");
  5729. if (node.getText() === newName)
  5730. return;
  5731. const renameLocations = node._context.languageService.findRenameLocations(node, options);
  5732. const renameLocationsBySourceFile = new common.KeyValueCache();
  5733. for (const renameLocation of renameLocations) {
  5734. const locations = renameLocationsBySourceFile.getOrCreate(renameLocation.getSourceFile(), () => []);
  5735. locations.push(renameLocation);
  5736. }
  5737. for (const [sourceFile, locations] of renameLocationsBySourceFile.getEntries()) {
  5738. replaceSourceFileTextForRename({
  5739. sourceFile,
  5740. renameLocations: locations,
  5741. newName,
  5742. });
  5743. }
  5744. }
  5745. function setBodyTextForNode(body, textOrWriterFunction) {
  5746. const newText = getBodyText(body._getWriterWithIndentation(), textOrWriterFunction);
  5747. const openBrace = body.getFirstChildByKindOrThrow(common.SyntaxKind.OpenBraceToken);
  5748. const closeBrace = body.getFirstChildByKindOrThrow(common.SyntaxKind.CloseBraceToken);
  5749. insertIntoParentTextRange({
  5750. insertPos: openBrace.getEnd(),
  5751. newText,
  5752. parent: body,
  5753. replacing: {
  5754. textLength: closeBrace.getStart() - openBrace.getEnd(),
  5755. },
  5756. });
  5757. }
  5758. function BodiedNode(Base) {
  5759. return class extends Base {
  5760. getBody() {
  5761. const body = this.compilerNode.body;
  5762. if (body == null)
  5763. throw new common.errors.InvalidOperationError("Bodied node should have a body.");
  5764. return this._getNodeFromCompilerNode(body);
  5765. }
  5766. setBodyText(textOrWriterFunction) {
  5767. const body = this.getBody();
  5768. setBodyTextForNode(body, textOrWriterFunction);
  5769. return this;
  5770. }
  5771. getBodyText() {
  5772. return getBodyTextWithoutLeadingIndentation(this.getBody());
  5773. }
  5774. };
  5775. }
  5776. function BodyableNode(Base) {
  5777. return class extends Base {
  5778. getBodyOrThrow(message) {
  5779. return common.errors.throwIfNullOrUndefined(this.getBody(), message ?? "Expected to find the node's body.", this);
  5780. }
  5781. getBody() {
  5782. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.body);
  5783. }
  5784. getBodyText() {
  5785. const body = this.getBody();
  5786. return body == null ? undefined : getBodyTextWithoutLeadingIndentation(body);
  5787. }
  5788. setBodyText(textOrWriterFunction) {
  5789. this.addBody();
  5790. setBodyTextForNode(this.getBodyOrThrow(), textOrWriterFunction);
  5791. return this;
  5792. }
  5793. hasBody() {
  5794. return this.compilerNode.body != null;
  5795. }
  5796. addBody() {
  5797. if (this.hasBody())
  5798. return this;
  5799. const semiColon = this.getLastChildByKind(common.SyntaxKind.SemicolonToken);
  5800. insertIntoParentTextRange({
  5801. parent: this,
  5802. insertPos: semiColon == null ? this.getEnd() : semiColon.getStart(),
  5803. newText: this._getWriterWithQueuedIndentation().space().block().toString(),
  5804. replacing: {
  5805. textLength: semiColon?.getFullWidth() ?? 0,
  5806. },
  5807. });
  5808. return this;
  5809. }
  5810. removeBody() {
  5811. const body = this.getBody();
  5812. if (body == null)
  5813. return this;
  5814. insertIntoParentTextRange({
  5815. parent: this,
  5816. insertPos: body.getPos(),
  5817. newText: ";",
  5818. replacing: {
  5819. textLength: body.getFullWidth(),
  5820. },
  5821. });
  5822. return this;
  5823. }
  5824. };
  5825. }
  5826. function ChildOrderableNode(Base) {
  5827. return class extends Base {
  5828. setOrder(order) {
  5829. const childIndex = this.getChildIndex();
  5830. const parent = this.getParentSyntaxList() || this.getParentSyntaxListOrThrow();
  5831. common.errors.throwIfOutOfRange(order, [0, parent.getChildCount() - 1], "order");
  5832. if (childIndex === order)
  5833. return this;
  5834. changeChildOrder({
  5835. parent,
  5836. getSiblingFormatting: getGeneralFormatting,
  5837. oldIndex: childIndex,
  5838. newIndex: order,
  5839. });
  5840. return this;
  5841. }
  5842. };
  5843. }
  5844. function DecoratableNode(Base) {
  5845. return class extends Base {
  5846. getDecorator(nameOrFindFunction) {
  5847. return getNodeByNameOrFindFunction(this.getDecorators(), nameOrFindFunction);
  5848. }
  5849. getDecoratorOrThrow(nameOrFindFunction, message) {
  5850. return common.errors.throwIfNullOrUndefined(this.getDecorator(nameOrFindFunction), message ?? (() => getNotFoundErrorMessageForNameOrFindFunction("decorator", nameOrFindFunction)), this);
  5851. }
  5852. getDecorators() {
  5853. return getCompilerNodeDecorators(this.compilerNode).map(d => this._getNodeFromCompilerNode(d));
  5854. }
  5855. addDecorator(structure) {
  5856. return this.insertDecorator(getEndIndexFromArray(getCompilerNodeDecorators(this.compilerNode)), structure);
  5857. }
  5858. addDecorators(structures) {
  5859. return this.insertDecorators(getEndIndexFromArray(getCompilerNodeDecorators(this.compilerNode)), structures);
  5860. }
  5861. insertDecorator(index, structure) {
  5862. return this.insertDecorators(index, [structure])[0];
  5863. }
  5864. insertDecorators(index, structures) {
  5865. if (common.ArrayUtils.isNullOrEmpty(structures))
  5866. return [];
  5867. const decoratorLines = getDecoratorLines(this, structures);
  5868. const decorators = this.getDecorators();
  5869. index = verifyAndGetIndex(index, decorators.length);
  5870. const formattingKind = getDecoratorFormattingKind(this, decorators);
  5871. const previousDecorator = decorators[index - 1];
  5872. const decoratorCode = getNewInsertCode({
  5873. structures,
  5874. newCodes: decoratorLines,
  5875. parent: this,
  5876. indentationText: this.getIndentationText(),
  5877. getSeparator: () => formattingKind,
  5878. previousFormattingKind: previousDecorator == null ? FormattingKind.None : formattingKind,
  5879. nextFormattingKind: previousDecorator == null ? formattingKind : FormattingKind.None,
  5880. });
  5881. insertIntoParentTextRange({
  5882. parent: decorators[0]?.getParentSyntaxListOrThrow() ?? this.getModifiers()[0]?.getParentSyntaxListOrThrow() ?? this,
  5883. insertPos: index === 0 ? (decorators[0] ?? this).getStart() : decorators[index - 1].getEnd(),
  5884. newText: decoratorCode,
  5885. });
  5886. return getNodesToReturn(decorators, this.getDecorators(), index, false);
  5887. }
  5888. set(structure) {
  5889. callBaseSet(Base.prototype, this, structure);
  5890. if (structure.decorators != null) {
  5891. this.getDecorators().forEach(d => d.remove());
  5892. this.addDecorators(structure.decorators);
  5893. }
  5894. return this;
  5895. }
  5896. getStructure() {
  5897. return callBaseGetStructure(Base.prototype, this, {
  5898. decorators: this.getDecorators().map(d => d.getStructure()),
  5899. });
  5900. }
  5901. };
  5902. }
  5903. function getCompilerNodeDecorators(node) {
  5904. return common.ts.canHaveDecorators(node) ? common.ts.getDecorators(node) ?? [] : [];
  5905. }
  5906. function getDecoratorLines(node, structures) {
  5907. const lines = [];
  5908. for (const structure of structures) {
  5909. const writer = node._getWriter();
  5910. const structurePrinter = node._context.structurePrinterFactory.forDecorator();
  5911. structurePrinter.printText(writer, structure);
  5912. lines.push(writer.toString());
  5913. }
  5914. return lines;
  5915. }
  5916. function getDecoratorFormattingKind(parent, currentDecorators) {
  5917. const sameLine = areDecoratorsOnSameLine(parent, currentDecorators);
  5918. return sameLine ? FormattingKind.Space : FormattingKind.Newline;
  5919. }
  5920. function areDecoratorsOnSameLine(parent, currentDecorators) {
  5921. if (currentDecorators.length === 1) {
  5922. const previousNode = currentDecorators[0].getPreviousSibling();
  5923. if (previousNode != null && previousNode.getStartLinePos() === currentDecorators[0].getStartLinePos())
  5924. return true;
  5925. }
  5926. if (currentDecorators.length <= 1)
  5927. return parent.getKind() === common.SyntaxKind.Parameter;
  5928. const startLinePos = currentDecorators[0].getStartLinePos();
  5929. for (let i = 1; i < currentDecorators.length; i++) {
  5930. if (currentDecorators[i].getStartLinePos() !== startLinePos)
  5931. return false;
  5932. }
  5933. return true;
  5934. }
  5935. function DotDotDotTokenableNode(Base) {
  5936. return class extends Base {
  5937. getDotDotDotTokenOrThrow(message) {
  5938. return common.errors.throwIfNullOrUndefined(this.getDotDotDotToken(), message ?? "Expected to find a dot dot dot token (...).", this);
  5939. }
  5940. getDotDotDotToken() {
  5941. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.dotDotDotToken);
  5942. }
  5943. };
  5944. }
  5945. function ExclamationTokenableNode(Base) {
  5946. return class extends Base {
  5947. hasExclamationToken() {
  5948. return this.compilerNode.exclamationToken != null;
  5949. }
  5950. getExclamationTokenNode() {
  5951. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.exclamationToken);
  5952. }
  5953. getExclamationTokenNodeOrThrow(message) {
  5954. return common.errors.throwIfNullOrUndefined(this.getExclamationTokenNode(), message ?? "Expected to find an exclamation token.", this);
  5955. }
  5956. setHasExclamationToken(value) {
  5957. const exclamationTokenNode = this.getExclamationTokenNode();
  5958. const hasExclamationToken = exclamationTokenNode != null;
  5959. if (value === hasExclamationToken)
  5960. return this;
  5961. if (value) {
  5962. if (Node.isQuestionTokenable(this))
  5963. this.setHasQuestionToken(false);
  5964. const colonNode = this.getFirstChildByKind(common.SyntaxKind.ColonToken);
  5965. if (colonNode == null)
  5966. throw new common.errors.InvalidOperationError("Cannot add an exclamation token to a node that does not have a type.");
  5967. insertIntoParentTextRange({
  5968. insertPos: colonNode.getStart(),
  5969. parent: this,
  5970. newText: "!",
  5971. });
  5972. }
  5973. else {
  5974. removeChildren({ children: [exclamationTokenNode] });
  5975. }
  5976. return this;
  5977. }
  5978. set(structure) {
  5979. callBaseSet(Base.prototype, this, structure);
  5980. if (structure.hasExclamationToken != null)
  5981. this.setHasExclamationToken(structure.hasExclamationToken);
  5982. return this;
  5983. }
  5984. getStructure() {
  5985. return callBaseGetStructure(Base.prototype, this, {
  5986. hasExclamationToken: this.hasExclamationToken(),
  5987. });
  5988. }
  5989. };
  5990. }
  5991. function ExportGetableNode(Base) {
  5992. return class extends Base {
  5993. hasExportKeyword() {
  5994. return this.getExportKeyword() != null;
  5995. }
  5996. getExportKeyword() {
  5997. if (Node.isVariableDeclaration(this)) {
  5998. const variableStatement = this.getVariableStatement();
  5999. return variableStatement?.getExportKeyword();
  6000. }
  6001. if (!Node.isModifierable(this))
  6002. return throwForNotModifierableNode();
  6003. return this.getFirstModifierByKind(common.SyntaxKind.ExportKeyword);
  6004. }
  6005. getExportKeywordOrThrow(message) {
  6006. return common.errors.throwIfNullOrUndefined(this.getExportKeyword(), message ?? "Expected to find an export keyword.", this);
  6007. }
  6008. hasDefaultKeyword() {
  6009. return this.getDefaultKeyword() != null;
  6010. }
  6011. getDefaultKeyword() {
  6012. if (Node.isVariableDeclaration(this)) {
  6013. const variableStatement = this.getVariableStatement();
  6014. return variableStatement?.getDefaultKeyword();
  6015. }
  6016. if (!Node.isModifierable(this))
  6017. return throwForNotModifierableNode();
  6018. return this.getFirstModifierByKind(common.SyntaxKind.DefaultKeyword);
  6019. }
  6020. getDefaultKeywordOrThrow(message) {
  6021. return common.errors.throwIfNullOrUndefined(this.getDefaultKeyword(), message ?? "Expected to find a default keyword.", this);
  6022. }
  6023. isExported() {
  6024. if (this.hasExportKeyword())
  6025. return true;
  6026. const thisSymbol = this.getSymbol();
  6027. const sourceFileSymbol = this.getSourceFile().getSymbol();
  6028. if (thisSymbol == null || sourceFileSymbol == null)
  6029. return false;
  6030. return sourceFileSymbol.getExports().some(e => e === thisSymbol || e.getAliasedSymbol() === thisSymbol);
  6031. }
  6032. isDefaultExport() {
  6033. if (this.hasDefaultKeyword())
  6034. return true;
  6035. const thisSymbol = this.getSymbol();
  6036. if (thisSymbol == null)
  6037. return false;
  6038. const defaultExportSymbol = this.getSourceFile().getDefaultExportSymbol();
  6039. if (defaultExportSymbol == null)
  6040. return false;
  6041. if (thisSymbol === defaultExportSymbol)
  6042. return true;
  6043. const aliasedSymbol = defaultExportSymbol.getAliasedSymbol();
  6044. return thisSymbol === aliasedSymbol;
  6045. }
  6046. isNamedExport() {
  6047. const thisSymbol = this.getSymbol();
  6048. const sourceFileSymbol = this.getSourceFile().getSymbol();
  6049. if (thisSymbol == null || sourceFileSymbol == null)
  6050. return false;
  6051. return !isDefaultExport() && sourceFileSymbol.getExports().some(e => e === thisSymbol || e.getAliasedSymbol() === thisSymbol);
  6052. function isDefaultExport() {
  6053. const defaultExportSymbol = sourceFileSymbol.getExport("default");
  6054. if (defaultExportSymbol == null)
  6055. return false;
  6056. return thisSymbol === defaultExportSymbol || thisSymbol === defaultExportSymbol.getAliasedSymbol();
  6057. }
  6058. }
  6059. };
  6060. }
  6061. function throwForNotModifierableNode() {
  6062. throw new common.errors.NotImplementedError(`Not implemented situation where node was not a ModifierableNode.`);
  6063. }
  6064. function ExportableNode(Base) {
  6065. return apply$1(ExportGetableNode(Base));
  6066. }
  6067. function apply$1(Base) {
  6068. return class extends Base {
  6069. setIsDefaultExport(value) {
  6070. if (value === this.isDefaultExport())
  6071. return this;
  6072. if (value && !Node.isSourceFile(this.getParentOrThrow()))
  6073. throw new common.errors.InvalidOperationError("The parent must be a source file in order to set this node as a default export.");
  6074. const sourceFile = this.getSourceFile();
  6075. const fileDefaultExportSymbol = sourceFile.getDefaultExportSymbol();
  6076. if (fileDefaultExportSymbol != null)
  6077. sourceFile.removeDefaultExport(fileDefaultExportSymbol);
  6078. if (!value)
  6079. return this;
  6080. if (Node.hasName(this) && shouldWriteAsSeparateStatement.call(this)) {
  6081. const parentSyntaxList = this.getFirstAncestorByKindOrThrow(common.SyntaxKind.SyntaxList);
  6082. const name = this.getName();
  6083. parentSyntaxList.insertChildText(this.getChildIndex() + 1, writer => {
  6084. writer.newLine().write(`export default ${name};`);
  6085. });
  6086. }
  6087. else {
  6088. this.addModifier("export");
  6089. this.addModifier("default");
  6090. }
  6091. return this;
  6092. function shouldWriteAsSeparateStatement() {
  6093. if (Node.isEnumDeclaration(this) || Node.isModuleDeclaration(this) || Node.isTypeAliasDeclaration(this))
  6094. return true;
  6095. if (Node.isAmbientable(this) && this.isAmbient())
  6096. return true;
  6097. return false;
  6098. }
  6099. }
  6100. setIsExported(value) {
  6101. if (Node.isSourceFile(this.getParentOrThrow()))
  6102. this.toggleModifier("default", false);
  6103. this.toggleModifier("export", value);
  6104. return this;
  6105. }
  6106. set(structure) {
  6107. callBaseSet(Base.prototype, this, structure);
  6108. if (structure.isExported != null)
  6109. this.setIsExported(structure.isExported);
  6110. if (structure.isDefaultExport != null)
  6111. this.setIsDefaultExport(structure.isDefaultExport);
  6112. return this;
  6113. }
  6114. getStructure() {
  6115. return callBaseGetStructure(Base.prototype, this, {
  6116. isExported: this.hasExportKeyword(),
  6117. isDefaultExport: this.hasDefaultKeyword(),
  6118. });
  6119. }
  6120. };
  6121. }
  6122. class Printer {
  6123. printTextOrWriterFunc(writer, textOrWriterFunc) {
  6124. if (typeof textOrWriterFunc === "string")
  6125. writer.write(textOrWriterFunc);
  6126. else if (textOrWriterFunc != null)
  6127. textOrWriterFunc(writer);
  6128. }
  6129. getNewWriter(writer) {
  6130. return new CodeBlockWriter__default.default(writer.getOptions());
  6131. }
  6132. getNewWriterWithQueuedChildIndentation(writer) {
  6133. const newWriter = new CodeBlockWriter__default.default(writer.getOptions());
  6134. newWriter.queueIndentationLevel(1);
  6135. return newWriter;
  6136. }
  6137. getText(writer, textOrWriterFunc) {
  6138. const newWriter = this.getNewWriter(writer);
  6139. this.printTextOrWriterFunc(newWriter, textOrWriterFunc);
  6140. return newWriter.toString();
  6141. }
  6142. getTextWithQueuedChildIndentation(writer, textOrWriterFunc) {
  6143. const queuedChildIndentationWriter = this.getNewWriterWithQueuedChildIndentation(writer);
  6144. this.printTextOrWriterFunc(queuedChildIndentationWriter, textOrWriterFunc);
  6145. return queuedChildIndentationWriter.toString();
  6146. }
  6147. }
  6148. class InitializerExpressionableNodeStructurePrinter extends Printer {
  6149. printText(writer, structure) {
  6150. const { initializer } = structure;
  6151. if (initializer == null)
  6152. return;
  6153. const initializerText = this.getText(writer, initializer);
  6154. if (!common.StringUtils.isNullOrWhitespace(initializerText)) {
  6155. writer.hangingIndent(() => {
  6156. writer.spaceIfLastNot();
  6157. writer.write(`= ${initializerText}`);
  6158. });
  6159. }
  6160. }
  6161. }
  6162. class ModifierableNodeStructurePrinter extends Printer {
  6163. printText(writer, structure) {
  6164. const scope = structure.scope;
  6165. if (structure.isDefaultExport)
  6166. writer.write("export default ");
  6167. else if (structure.isExported)
  6168. writer.write("export ");
  6169. if (structure.hasDeclareKeyword)
  6170. writer.write("declare ");
  6171. if (scope != null)
  6172. writer.write(`${scope} `);
  6173. if (structure.isStatic)
  6174. writer.write("static ");
  6175. if (structure.hasOverrideKeyword)
  6176. writer.write("override ");
  6177. if (structure.isAbstract)
  6178. writer.write("abstract ");
  6179. if (structure.isAsync)
  6180. writer.write("async ");
  6181. if (structure.isReadonly)
  6182. writer.write("readonly ");
  6183. if (structure.hasAccessorKeyword)
  6184. writer.write("accessor ");
  6185. }
  6186. }
  6187. class ReturnTypedNodeStructurePrinter extends Printer {
  6188. #alwaysWrite;
  6189. constructor(alwaysWrite = false) {
  6190. super();
  6191. this.#alwaysWrite = alwaysWrite;
  6192. }
  6193. printText(writer, structure) {
  6194. let { returnType } = structure;
  6195. if (returnType == null && this.#alwaysWrite === false)
  6196. return;
  6197. returnType = returnType ?? "void";
  6198. const returnTypeText = this.getText(writer, returnType);
  6199. if (!common.StringUtils.isNullOrWhitespace(returnTypeText)) {
  6200. writer.hangingIndent(() => {
  6201. writer.write(`: ${returnTypeText}`);
  6202. });
  6203. }
  6204. }
  6205. }
  6206. class TypedNodeStructurePrinter extends Printer {
  6207. #separator;
  6208. #alwaysWrite;
  6209. constructor(separator, alwaysWrite = false) {
  6210. super();
  6211. this.#alwaysWrite = alwaysWrite;
  6212. this.#separator = separator;
  6213. }
  6214. printText(writer, structure) {
  6215. let { type } = structure;
  6216. if (type == null && this.#alwaysWrite === false)
  6217. return;
  6218. type = type ?? "any";
  6219. const typeText = this.getText(writer, type);
  6220. if (!common.StringUtils.isNullOrWhitespace(typeText)) {
  6221. writer.hangingIndent(() => {
  6222. writer.write(`${this.#separator} ${typeText}`);
  6223. });
  6224. }
  6225. }
  6226. }
  6227. class BlankLineFormattingStructuresPrinter extends Printer {
  6228. #printer;
  6229. constructor(printer) {
  6230. super();
  6231. this.#printer = printer;
  6232. }
  6233. printText(writer, structures) {
  6234. if (structures == null)
  6235. return;
  6236. for (let i = 0; i < structures.length; i++) {
  6237. writer.conditionalBlankLine(i > 0);
  6238. this.#printer.printText(writer, structures[i]);
  6239. }
  6240. }
  6241. }
  6242. class CommaSeparatedStructuresPrinter extends Printer {
  6243. #printer;
  6244. constructor(printer) {
  6245. super();
  6246. this.#printer = printer;
  6247. }
  6248. printText(writer, structures) {
  6249. printTextWithSeparator(this.#printer, writer, structures, () => writer.spaceIfLastNot());
  6250. }
  6251. }
  6252. function printTextWithSeparator(printer, writer, structures, separator) {
  6253. if (structures == null)
  6254. return;
  6255. if (structures instanceof Function || typeof structures === "string")
  6256. printer.printText(writer, structures);
  6257. else {
  6258. const commaAppendPositions = new Array(structures.length);
  6259. for (let i = 0; i < structures.length; i++) {
  6260. if (i > 0)
  6261. separator();
  6262. const structure = structures[i];
  6263. const startPos = writer.getLength();
  6264. printer.printText(writer, structure);
  6265. const pos = getAppendCommaPos(WriterUtils.getLastCharactersToPos(writer, startPos));
  6266. commaAppendPositions[i] = pos === -1 ? false : pos + startPos;
  6267. }
  6268. let foundFirst = false;
  6269. for (let i = commaAppendPositions.length - 1; i >= 0; i--) {
  6270. const pos = commaAppendPositions[i];
  6271. if (pos === false)
  6272. continue;
  6273. else if (!foundFirst)
  6274. foundFirst = true;
  6275. else
  6276. writer.unsafeInsert(pos, ",");
  6277. }
  6278. }
  6279. }
  6280. class CommaNewLineSeparatedStructuresPrinter extends Printer {
  6281. #printer;
  6282. constructor(printer) {
  6283. super();
  6284. this.#printer = printer;
  6285. }
  6286. printText(writer, structures) {
  6287. printTextWithSeparator(this.#printer, writer, structures, () => writer.newLineIfLastNot());
  6288. }
  6289. }
  6290. class NewLineFormattingStructuresPrinter extends Printer {
  6291. #printer;
  6292. constructor(printer) {
  6293. super();
  6294. this.#printer = printer;
  6295. }
  6296. printText(writer, structures) {
  6297. if (structures == null)
  6298. return;
  6299. for (let i = 0; i < structures.length; i++) {
  6300. writer.conditionalNewLine(i > 0);
  6301. this.#printer.printText(writer, structures[i]);
  6302. }
  6303. }
  6304. }
  6305. class SpaceFormattingStructuresPrinter extends Printer {
  6306. #printer;
  6307. constructor(printer) {
  6308. super();
  6309. this.#printer = printer;
  6310. }
  6311. printText(writer, structures) {
  6312. if (structures == null)
  6313. return;
  6314. for (let i = 0; i < structures.length; i++) {
  6315. writer.conditionalWrite(i > 0, " ");
  6316. this.#printer.printText(writer, structures[i]);
  6317. }
  6318. }
  6319. }
  6320. class NodePrinter extends Printer {
  6321. factory;
  6322. constructor(factory) {
  6323. super();
  6324. this.factory = factory;
  6325. }
  6326. printTextWithoutTrivia(writer, structure) {
  6327. this.printTextInternal(writer, structure);
  6328. }
  6329. printText(writer, structure) {
  6330. this.printLeadingTrivia(writer, structure);
  6331. writer.closeComment();
  6332. this.printTextInternal(writer, structure);
  6333. this.printTrailingTrivia(writer, structure);
  6334. }
  6335. printLeadingTrivia(writer, structure) {
  6336. const leadingTrivia = structure?.leadingTrivia;
  6337. if (leadingTrivia) {
  6338. this.#printTrivia(writer, leadingTrivia);
  6339. if (writer.isInComment())
  6340. writer.closeComment();
  6341. }
  6342. }
  6343. printTrailingTrivia(writer, structure) {
  6344. const trailingTrivia = structure?.trailingTrivia;
  6345. if (trailingTrivia != null)
  6346. this.#printTrivia(writer, trailingTrivia);
  6347. }
  6348. #printTrivia(writer, trivia) {
  6349. if (trivia instanceof Array) {
  6350. for (let i = 0; i < trivia.length; i++) {
  6351. this.printTextOrWriterFunc(writer, trivia[i]);
  6352. if (i !== trivia.length - 1)
  6353. writer.newLineIfLastNot();
  6354. }
  6355. }
  6356. else {
  6357. this.printTextOrWriterFunc(writer, trivia);
  6358. }
  6359. }
  6360. }
  6361. class GetAndSetAccessorStructurePrinter {
  6362. #getAccessorPrinter;
  6363. #setAccessorPrinter;
  6364. constructor(getAccessorPrinter, setAccessorPrinter) {
  6365. this.#getAccessorPrinter = getAccessorPrinter;
  6366. this.#setAccessorPrinter = setAccessorPrinter;
  6367. }
  6368. printGetAndSet(writer, getAccessors, setAccessors, isAmbient) {
  6369. getAccessors = [...getAccessors ?? []];
  6370. setAccessors = [...setAccessors ?? []];
  6371. for (const getAccessor of getAccessors) {
  6372. this.#conditionalSeparator(writer, isAmbient);
  6373. this.#getAccessorPrinter.printText(writer, getAccessor);
  6374. const setAccessorIndex = setAccessors.findIndex(item => item.name === getAccessor.name);
  6375. if (setAccessorIndex >= 0) {
  6376. this.#conditionalSeparator(writer, isAmbient);
  6377. this.#setAccessorPrinter.printText(writer, setAccessors[setAccessorIndex]);
  6378. setAccessors.splice(setAccessorIndex, 1);
  6379. }
  6380. }
  6381. for (const setAccessor of setAccessors) {
  6382. this.#conditionalSeparator(writer, isAmbient);
  6383. this.#setAccessorPrinter.printText(writer, setAccessor);
  6384. }
  6385. }
  6386. #conditionalSeparator(writer, isAmbient) {
  6387. if (writer.isAtStartOfFirstLineOfBlock())
  6388. return;
  6389. if (isAmbient)
  6390. writer.newLine();
  6391. else
  6392. writer.blankLine();
  6393. }
  6394. }
  6395. class ClassDeclarationStructurePrinter extends NodePrinter {
  6396. #options;
  6397. #multipleWriter = new BlankLineFormattingStructuresPrinter(this);
  6398. constructor(factory, options) {
  6399. super(factory);
  6400. this.#options = options;
  6401. }
  6402. printTexts(writer, structures) {
  6403. this.#multipleWriter.printText(writer, structures);
  6404. }
  6405. printTextInternal(writer, structure) {
  6406. const isAmbient = structure.hasDeclareKeyword || this.#options.isAmbient;
  6407. this.factory.forJSDoc().printDocs(writer, structure.docs);
  6408. this.factory.forDecorator().printTexts(writer, structure.decorators);
  6409. this.#printHeader(writer, structure);
  6410. writer.inlineBlock(() => {
  6411. this.factory.forPropertyDeclaration().printTexts(writer, structure.properties);
  6412. this.#printStaticBlocks(writer, structure);
  6413. this.#printCtors(writer, structure, isAmbient);
  6414. this.#printGetAndSet(writer, structure, isAmbient);
  6415. if (!common.ArrayUtils.isNullOrEmpty(structure.methods)) {
  6416. this.#conditionalSeparator(writer, isAmbient);
  6417. this.factory.forMethodDeclaration({ isAmbient }).printTexts(writer, structure.methods);
  6418. }
  6419. });
  6420. }
  6421. #printHeader(writer, structure) {
  6422. this.factory.forModifierableNode().printText(writer, structure);
  6423. writer.write(`class`);
  6424. if (!common.StringUtils.isNullOrWhitespace(structure.name))
  6425. writer.space().write(structure.name);
  6426. this.factory.forTypeParameterDeclaration().printTextsWithBrackets(writer, structure.typeParameters);
  6427. writer.space();
  6428. writer.hangingIndent(() => {
  6429. if (structure.extends != null) {
  6430. const extendsText = this.getText(writer, structure.extends);
  6431. if (!common.StringUtils.isNullOrWhitespace(extendsText))
  6432. writer.write(`extends ${extendsText} `);
  6433. }
  6434. if (structure.implements != null) {
  6435. const implementsText = structure.implements instanceof Array
  6436. ? structure.implements.map(i => this.getText(writer, i)).join(", ")
  6437. : this.getText(writer, structure.implements);
  6438. if (!common.StringUtils.isNullOrWhitespace(implementsText))
  6439. writer.write(`implements ${implementsText} `);
  6440. }
  6441. });
  6442. }
  6443. #printCtors(writer, structure, isAmbient) {
  6444. if (common.ArrayUtils.isNullOrEmpty(structure.ctors))
  6445. return;
  6446. for (const ctor of structure.ctors) {
  6447. this.#conditionalSeparator(writer, isAmbient);
  6448. this.factory.forConstructorDeclaration({ isAmbient }).printText(writer, ctor);
  6449. }
  6450. }
  6451. #printStaticBlocks(writer, structure) {
  6452. if (common.ArrayUtils.isNullOrEmpty(structure.staticBlocks))
  6453. return;
  6454. for (const block of structure.staticBlocks) {
  6455. this.#conditionalSeparator(writer, false);
  6456. this.factory.forClassStaticBlockDeclaration().printText(writer, block);
  6457. }
  6458. }
  6459. #printGetAndSet(writer, structure, isAmbient) {
  6460. if (structure.getAccessors == null && structure.setAccessors == null)
  6461. return;
  6462. const getAccessorWriter = this.factory.forGetAccessorDeclaration({ isAmbient });
  6463. const setAccessorWriter = this.factory.forSetAccessorDeclaration({ isAmbient });
  6464. const combinedPrinter = new GetAndSetAccessorStructurePrinter(getAccessorWriter, setAccessorWriter);
  6465. combinedPrinter.printGetAndSet(writer, structure.getAccessors, structure.setAccessors, isAmbient);
  6466. }
  6467. #conditionalSeparator(writer, isAmbient) {
  6468. if (writer.isAtStartOfFirstLineOfBlock())
  6469. return;
  6470. if (isAmbient)
  6471. writer.newLine();
  6472. else
  6473. writer.blankLine();
  6474. }
  6475. }
  6476. exports.StructureKind = void 0;
  6477. (function (StructureKind) {
  6478. StructureKind[StructureKind["ImportAttribute"] = 0] = "ImportAttribute";
  6479. StructureKind[StructureKind["CallSignature"] = 1] = "CallSignature";
  6480. StructureKind[StructureKind["Class"] = 2] = "Class";
  6481. StructureKind[StructureKind["ClassStaticBlock"] = 3] = "ClassStaticBlock";
  6482. StructureKind[StructureKind["ConstructSignature"] = 4] = "ConstructSignature";
  6483. StructureKind[StructureKind["Constructor"] = 5] = "Constructor";
  6484. StructureKind[StructureKind["ConstructorOverload"] = 6] = "ConstructorOverload";
  6485. StructureKind[StructureKind["Decorator"] = 7] = "Decorator";
  6486. StructureKind[StructureKind["Enum"] = 8] = "Enum";
  6487. StructureKind[StructureKind["EnumMember"] = 9] = "EnumMember";
  6488. StructureKind[StructureKind["ExportAssignment"] = 10] = "ExportAssignment";
  6489. StructureKind[StructureKind["ExportDeclaration"] = 11] = "ExportDeclaration";
  6490. StructureKind[StructureKind["ExportSpecifier"] = 12] = "ExportSpecifier";
  6491. StructureKind[StructureKind["Function"] = 13] = "Function";
  6492. StructureKind[StructureKind["FunctionOverload"] = 14] = "FunctionOverload";
  6493. StructureKind[StructureKind["GetAccessor"] = 15] = "GetAccessor";
  6494. StructureKind[StructureKind["ImportDeclaration"] = 16] = "ImportDeclaration";
  6495. StructureKind[StructureKind["ImportSpecifier"] = 17] = "ImportSpecifier";
  6496. StructureKind[StructureKind["IndexSignature"] = 18] = "IndexSignature";
  6497. StructureKind[StructureKind["Interface"] = 19] = "Interface";
  6498. StructureKind[StructureKind["JsxAttribute"] = 20] = "JsxAttribute";
  6499. StructureKind[StructureKind["JsxSpreadAttribute"] = 21] = "JsxSpreadAttribute";
  6500. StructureKind[StructureKind["JsxElement"] = 22] = "JsxElement";
  6501. StructureKind[StructureKind["JsxSelfClosingElement"] = 23] = "JsxSelfClosingElement";
  6502. StructureKind[StructureKind["JSDoc"] = 24] = "JSDoc";
  6503. StructureKind[StructureKind["JSDocTag"] = 25] = "JSDocTag";
  6504. StructureKind[StructureKind["Method"] = 26] = "Method";
  6505. StructureKind[StructureKind["MethodOverload"] = 27] = "MethodOverload";
  6506. StructureKind[StructureKind["MethodSignature"] = 28] = "MethodSignature";
  6507. StructureKind[StructureKind["Module"] = 29] = "Module";
  6508. StructureKind[StructureKind["Parameter"] = 30] = "Parameter";
  6509. StructureKind[StructureKind["Property"] = 31] = "Property";
  6510. StructureKind[StructureKind["PropertyAssignment"] = 32] = "PropertyAssignment";
  6511. StructureKind[StructureKind["PropertySignature"] = 33] = "PropertySignature";
  6512. StructureKind[StructureKind["SetAccessor"] = 34] = "SetAccessor";
  6513. StructureKind[StructureKind["ShorthandPropertyAssignment"] = 35] = "ShorthandPropertyAssignment";
  6514. StructureKind[StructureKind["SourceFile"] = 36] = "SourceFile";
  6515. StructureKind[StructureKind["SpreadAssignment"] = 37] = "SpreadAssignment";
  6516. StructureKind[StructureKind["TypeAlias"] = 38] = "TypeAlias";
  6517. StructureKind[StructureKind["TypeParameter"] = 39] = "TypeParameter";
  6518. StructureKind[StructureKind["VariableDeclaration"] = 40] = "VariableDeclaration";
  6519. StructureKind[StructureKind["VariableStatement"] = 41] = "VariableStatement";
  6520. })(exports.StructureKind || (exports.StructureKind = {}));
  6521. const Structure = {
  6522. hasName(structure) {
  6523. return typeof structure.name === "string";
  6524. },
  6525. isCallSignature(structure) {
  6526. return structure?.kind === exports.StructureKind.CallSignature;
  6527. },
  6528. isJSDocable(structure) {
  6529. switch (structure?.kind) {
  6530. case exports.StructureKind.CallSignature:
  6531. case exports.StructureKind.Class:
  6532. case exports.StructureKind.ClassStaticBlock:
  6533. case exports.StructureKind.ConstructorOverload:
  6534. case exports.StructureKind.Constructor:
  6535. case exports.StructureKind.ConstructSignature:
  6536. case exports.StructureKind.Enum:
  6537. case exports.StructureKind.EnumMember:
  6538. case exports.StructureKind.ExportAssignment:
  6539. case exports.StructureKind.FunctionOverload:
  6540. case exports.StructureKind.Function:
  6541. case exports.StructureKind.GetAccessor:
  6542. case exports.StructureKind.IndexSignature:
  6543. case exports.StructureKind.Interface:
  6544. case exports.StructureKind.MethodOverload:
  6545. case exports.StructureKind.Method:
  6546. case exports.StructureKind.MethodSignature:
  6547. case exports.StructureKind.Module:
  6548. case exports.StructureKind.Property:
  6549. case exports.StructureKind.PropertySignature:
  6550. case exports.StructureKind.SetAccessor:
  6551. case exports.StructureKind.TypeAlias:
  6552. case exports.StructureKind.VariableStatement:
  6553. return true;
  6554. default:
  6555. return false;
  6556. }
  6557. },
  6558. isSignatured(structure) {
  6559. switch (structure?.kind) {
  6560. case exports.StructureKind.CallSignature:
  6561. case exports.StructureKind.ConstructorOverload:
  6562. case exports.StructureKind.Constructor:
  6563. case exports.StructureKind.ConstructSignature:
  6564. case exports.StructureKind.FunctionOverload:
  6565. case exports.StructureKind.Function:
  6566. case exports.StructureKind.GetAccessor:
  6567. case exports.StructureKind.MethodOverload:
  6568. case exports.StructureKind.Method:
  6569. case exports.StructureKind.MethodSignature:
  6570. case exports.StructureKind.SetAccessor:
  6571. return true;
  6572. default:
  6573. return false;
  6574. }
  6575. },
  6576. isParametered(structure) {
  6577. switch (structure?.kind) {
  6578. case exports.StructureKind.CallSignature:
  6579. case exports.StructureKind.ConstructorOverload:
  6580. case exports.StructureKind.Constructor:
  6581. case exports.StructureKind.ConstructSignature:
  6582. case exports.StructureKind.FunctionOverload:
  6583. case exports.StructureKind.Function:
  6584. case exports.StructureKind.GetAccessor:
  6585. case exports.StructureKind.MethodOverload:
  6586. case exports.StructureKind.Method:
  6587. case exports.StructureKind.MethodSignature:
  6588. case exports.StructureKind.SetAccessor:
  6589. return true;
  6590. default:
  6591. return false;
  6592. }
  6593. },
  6594. isReturnTyped(structure) {
  6595. switch (structure?.kind) {
  6596. case exports.StructureKind.CallSignature:
  6597. case exports.StructureKind.ConstructorOverload:
  6598. case exports.StructureKind.Constructor:
  6599. case exports.StructureKind.ConstructSignature:
  6600. case exports.StructureKind.FunctionOverload:
  6601. case exports.StructureKind.Function:
  6602. case exports.StructureKind.GetAccessor:
  6603. case exports.StructureKind.IndexSignature:
  6604. case exports.StructureKind.MethodOverload:
  6605. case exports.StructureKind.Method:
  6606. case exports.StructureKind.MethodSignature:
  6607. case exports.StructureKind.SetAccessor:
  6608. return true;
  6609. default:
  6610. return false;
  6611. }
  6612. },
  6613. isTypeParametered(structure) {
  6614. switch (structure?.kind) {
  6615. case exports.StructureKind.CallSignature:
  6616. case exports.StructureKind.Class:
  6617. case exports.StructureKind.ConstructorOverload:
  6618. case exports.StructureKind.Constructor:
  6619. case exports.StructureKind.ConstructSignature:
  6620. case exports.StructureKind.FunctionOverload:
  6621. case exports.StructureKind.Function:
  6622. case exports.StructureKind.GetAccessor:
  6623. case exports.StructureKind.Interface:
  6624. case exports.StructureKind.MethodOverload:
  6625. case exports.StructureKind.Method:
  6626. case exports.StructureKind.MethodSignature:
  6627. case exports.StructureKind.SetAccessor:
  6628. case exports.StructureKind.TypeAlias:
  6629. return true;
  6630. default:
  6631. return false;
  6632. }
  6633. },
  6634. isClass(structure) {
  6635. return structure?.kind === exports.StructureKind.Class;
  6636. },
  6637. isClassLikeDeclarationBase(structure) {
  6638. return structure?.kind === exports.StructureKind.Class;
  6639. },
  6640. isNameable(structure) {
  6641. switch (structure?.kind) {
  6642. case exports.StructureKind.Class:
  6643. case exports.StructureKind.Function:
  6644. return true;
  6645. default:
  6646. return false;
  6647. }
  6648. },
  6649. isImplementsClauseable(structure) {
  6650. return structure?.kind === exports.StructureKind.Class;
  6651. },
  6652. isDecoratable(structure) {
  6653. switch (structure?.kind) {
  6654. case exports.StructureKind.Class:
  6655. case exports.StructureKind.GetAccessor:
  6656. case exports.StructureKind.Method:
  6657. case exports.StructureKind.Parameter:
  6658. case exports.StructureKind.Property:
  6659. case exports.StructureKind.SetAccessor:
  6660. return true;
  6661. default:
  6662. return false;
  6663. }
  6664. },
  6665. isAbstractable(structure) {
  6666. switch (structure?.kind) {
  6667. case exports.StructureKind.Class:
  6668. case exports.StructureKind.GetAccessor:
  6669. case exports.StructureKind.MethodOverload:
  6670. case exports.StructureKind.Method:
  6671. case exports.StructureKind.Property:
  6672. case exports.StructureKind.SetAccessor:
  6673. return true;
  6674. default:
  6675. return false;
  6676. }
  6677. },
  6678. isAmbientable(structure) {
  6679. switch (structure?.kind) {
  6680. case exports.StructureKind.Class:
  6681. case exports.StructureKind.Enum:
  6682. case exports.StructureKind.FunctionOverload:
  6683. case exports.StructureKind.Function:
  6684. case exports.StructureKind.Interface:
  6685. case exports.StructureKind.Module:
  6686. case exports.StructureKind.Property:
  6687. case exports.StructureKind.TypeAlias:
  6688. case exports.StructureKind.VariableStatement:
  6689. return true;
  6690. default:
  6691. return false;
  6692. }
  6693. },
  6694. isExportable(structure) {
  6695. switch (structure?.kind) {
  6696. case exports.StructureKind.Class:
  6697. case exports.StructureKind.Enum:
  6698. case exports.StructureKind.FunctionOverload:
  6699. case exports.StructureKind.Function:
  6700. case exports.StructureKind.Interface:
  6701. case exports.StructureKind.Module:
  6702. case exports.StructureKind.TypeAlias:
  6703. case exports.StructureKind.VariableStatement:
  6704. return true;
  6705. default:
  6706. return false;
  6707. }
  6708. },
  6709. isClassStaticBlock(structure) {
  6710. return structure?.kind === exports.StructureKind.ClassStaticBlock;
  6711. },
  6712. isStatemented(structure) {
  6713. switch (structure?.kind) {
  6714. case exports.StructureKind.ClassStaticBlock:
  6715. case exports.StructureKind.Constructor:
  6716. case exports.StructureKind.Function:
  6717. case exports.StructureKind.GetAccessor:
  6718. case exports.StructureKind.Method:
  6719. case exports.StructureKind.Module:
  6720. case exports.StructureKind.SetAccessor:
  6721. case exports.StructureKind.SourceFile:
  6722. return true;
  6723. default:
  6724. return false;
  6725. }
  6726. },
  6727. isConstructorDeclarationOverload(structure) {
  6728. return structure?.kind === exports.StructureKind.ConstructorOverload;
  6729. },
  6730. isScoped(structure) {
  6731. switch (structure?.kind) {
  6732. case exports.StructureKind.ConstructorOverload:
  6733. case exports.StructureKind.Constructor:
  6734. case exports.StructureKind.GetAccessor:
  6735. case exports.StructureKind.MethodOverload:
  6736. case exports.StructureKind.Method:
  6737. case exports.StructureKind.Property:
  6738. case exports.StructureKind.SetAccessor:
  6739. return true;
  6740. default:
  6741. return false;
  6742. }
  6743. },
  6744. isConstructor(structure) {
  6745. return structure?.kind === exports.StructureKind.Constructor;
  6746. },
  6747. isFunctionLike(structure) {
  6748. switch (structure?.kind) {
  6749. case exports.StructureKind.Constructor:
  6750. case exports.StructureKind.Function:
  6751. case exports.StructureKind.GetAccessor:
  6752. case exports.StructureKind.Method:
  6753. case exports.StructureKind.SetAccessor:
  6754. return true;
  6755. default:
  6756. return false;
  6757. }
  6758. },
  6759. isConstructSignature(structure) {
  6760. return structure?.kind === exports.StructureKind.ConstructSignature;
  6761. },
  6762. isDecorator(structure) {
  6763. return structure?.kind === exports.StructureKind.Decorator;
  6764. },
  6765. isEnum(structure) {
  6766. return structure?.kind === exports.StructureKind.Enum;
  6767. },
  6768. isNamed(structure) {
  6769. switch (structure?.kind) {
  6770. case exports.StructureKind.Enum:
  6771. case exports.StructureKind.Interface:
  6772. case exports.StructureKind.ShorthandPropertyAssignment:
  6773. case exports.StructureKind.TypeAlias:
  6774. case exports.StructureKind.TypeParameter:
  6775. return true;
  6776. default:
  6777. return false;
  6778. }
  6779. },
  6780. isEnumMember(structure) {
  6781. return structure?.kind === exports.StructureKind.EnumMember;
  6782. },
  6783. isPropertyNamed(structure) {
  6784. switch (structure?.kind) {
  6785. case exports.StructureKind.EnumMember:
  6786. case exports.StructureKind.GetAccessor:
  6787. case exports.StructureKind.Method:
  6788. case exports.StructureKind.MethodSignature:
  6789. case exports.StructureKind.PropertyAssignment:
  6790. case exports.StructureKind.Property:
  6791. case exports.StructureKind.PropertySignature:
  6792. case exports.StructureKind.SetAccessor:
  6793. return true;
  6794. default:
  6795. return false;
  6796. }
  6797. },
  6798. isInitializerExpressionable(structure) {
  6799. switch (structure?.kind) {
  6800. case exports.StructureKind.EnumMember:
  6801. case exports.StructureKind.Parameter:
  6802. case exports.StructureKind.Property:
  6803. case exports.StructureKind.PropertySignature:
  6804. case exports.StructureKind.VariableDeclaration:
  6805. return true;
  6806. default:
  6807. return false;
  6808. }
  6809. },
  6810. isExportAssignment(structure) {
  6811. return structure?.kind === exports.StructureKind.ExportAssignment;
  6812. },
  6813. isExportDeclaration(structure) {
  6814. return structure?.kind === exports.StructureKind.ExportDeclaration;
  6815. },
  6816. isExportSpecifier(structure) {
  6817. return structure?.kind === exports.StructureKind.ExportSpecifier;
  6818. },
  6819. isFunctionDeclarationOverload(structure) {
  6820. return structure?.kind === exports.StructureKind.FunctionOverload;
  6821. },
  6822. isAsyncable(structure) {
  6823. switch (structure?.kind) {
  6824. case exports.StructureKind.FunctionOverload:
  6825. case exports.StructureKind.Function:
  6826. case exports.StructureKind.MethodOverload:
  6827. case exports.StructureKind.Method:
  6828. return true;
  6829. default:
  6830. return false;
  6831. }
  6832. },
  6833. isGeneratorable(structure) {
  6834. switch (structure?.kind) {
  6835. case exports.StructureKind.FunctionOverload:
  6836. case exports.StructureKind.Function:
  6837. case exports.StructureKind.MethodOverload:
  6838. case exports.StructureKind.Method:
  6839. return true;
  6840. default:
  6841. return false;
  6842. }
  6843. },
  6844. isFunction(structure) {
  6845. return structure?.kind === exports.StructureKind.Function;
  6846. },
  6847. isGetAccessor(structure) {
  6848. return structure?.kind === exports.StructureKind.GetAccessor;
  6849. },
  6850. isStaticable(structure) {
  6851. switch (structure?.kind) {
  6852. case exports.StructureKind.GetAccessor:
  6853. case exports.StructureKind.MethodOverload:
  6854. case exports.StructureKind.Method:
  6855. case exports.StructureKind.Property:
  6856. case exports.StructureKind.SetAccessor:
  6857. return true;
  6858. default:
  6859. return false;
  6860. }
  6861. },
  6862. isImportAttribute(structure) {
  6863. return structure?.kind === exports.StructureKind.ImportAttribute;
  6864. },
  6865. isImportAttributeNamed(structure) {
  6866. return structure?.kind === exports.StructureKind.ImportAttribute;
  6867. },
  6868. isImportDeclaration(structure) {
  6869. return structure?.kind === exports.StructureKind.ImportDeclaration;
  6870. },
  6871. isImportSpecifier(structure) {
  6872. return structure?.kind === exports.StructureKind.ImportSpecifier;
  6873. },
  6874. isIndexSignature(structure) {
  6875. return structure?.kind === exports.StructureKind.IndexSignature;
  6876. },
  6877. isReadonlyable(structure) {
  6878. switch (structure?.kind) {
  6879. case exports.StructureKind.IndexSignature:
  6880. case exports.StructureKind.Parameter:
  6881. case exports.StructureKind.Property:
  6882. case exports.StructureKind.PropertySignature:
  6883. return true;
  6884. default:
  6885. return false;
  6886. }
  6887. },
  6888. isInterface(structure) {
  6889. return structure?.kind === exports.StructureKind.Interface;
  6890. },
  6891. isExtendsClauseable(structure) {
  6892. return structure?.kind === exports.StructureKind.Interface;
  6893. },
  6894. isTypeElementMembered(structure) {
  6895. return structure?.kind === exports.StructureKind.Interface;
  6896. },
  6897. isJSDoc(structure) {
  6898. return structure?.kind === exports.StructureKind.JSDoc;
  6899. },
  6900. isJSDocTag(structure) {
  6901. return structure?.kind === exports.StructureKind.JSDocTag;
  6902. },
  6903. isJsxAttribute(structure) {
  6904. return structure?.kind === exports.StructureKind.JsxAttribute;
  6905. },
  6906. isJsxElement(structure) {
  6907. return structure?.kind === exports.StructureKind.JsxElement;
  6908. },
  6909. isJsxSelfClosingElement(structure) {
  6910. return structure?.kind === exports.StructureKind.JsxSelfClosingElement;
  6911. },
  6912. isJsxTagNamed(structure) {
  6913. return structure?.kind === exports.StructureKind.JsxSelfClosingElement;
  6914. },
  6915. isJsxAttributed(structure) {
  6916. return structure?.kind === exports.StructureKind.JsxSelfClosingElement;
  6917. },
  6918. isJsxSpreadAttribute(structure) {
  6919. return structure?.kind === exports.StructureKind.JsxSpreadAttribute;
  6920. },
  6921. isMethodDeclarationOverload(structure) {
  6922. return structure?.kind === exports.StructureKind.MethodOverload;
  6923. },
  6924. isQuestionTokenable(structure) {
  6925. switch (structure?.kind) {
  6926. case exports.StructureKind.MethodOverload:
  6927. case exports.StructureKind.Method:
  6928. case exports.StructureKind.MethodSignature:
  6929. case exports.StructureKind.Parameter:
  6930. case exports.StructureKind.Property:
  6931. case exports.StructureKind.PropertySignature:
  6932. return true;
  6933. default:
  6934. return false;
  6935. }
  6936. },
  6937. isOverrideable(structure) {
  6938. switch (structure?.kind) {
  6939. case exports.StructureKind.MethodOverload:
  6940. case exports.StructureKind.Method:
  6941. case exports.StructureKind.Parameter:
  6942. case exports.StructureKind.Property:
  6943. return true;
  6944. default:
  6945. return false;
  6946. }
  6947. },
  6948. isMethod(structure) {
  6949. return structure?.kind === exports.StructureKind.Method;
  6950. },
  6951. isMethodSignature(structure) {
  6952. return structure?.kind === exports.StructureKind.MethodSignature;
  6953. },
  6954. isModule(structure) {
  6955. return structure?.kind === exports.StructureKind.Module;
  6956. },
  6957. isModuleNamed(structure) {
  6958. return structure?.kind === exports.StructureKind.Module;
  6959. },
  6960. isParameter(structure) {
  6961. return structure?.kind === exports.StructureKind.Parameter;
  6962. },
  6963. isBindingNamed(structure) {
  6964. switch (structure?.kind) {
  6965. case exports.StructureKind.Parameter:
  6966. case exports.StructureKind.VariableDeclaration:
  6967. return true;
  6968. default:
  6969. return false;
  6970. }
  6971. },
  6972. isTyped(structure) {
  6973. switch (structure?.kind) {
  6974. case exports.StructureKind.Parameter:
  6975. case exports.StructureKind.Property:
  6976. case exports.StructureKind.PropertySignature:
  6977. case exports.StructureKind.TypeAlias:
  6978. case exports.StructureKind.VariableDeclaration:
  6979. return true;
  6980. default:
  6981. return false;
  6982. }
  6983. },
  6984. isScopeable(structure) {
  6985. return structure?.kind === exports.StructureKind.Parameter;
  6986. },
  6987. isPropertyAssignment(structure) {
  6988. return structure?.kind === exports.StructureKind.PropertyAssignment;
  6989. },
  6990. isProperty(structure) {
  6991. return structure?.kind === exports.StructureKind.Property;
  6992. },
  6993. isExclamationTokenable(structure) {
  6994. switch (structure?.kind) {
  6995. case exports.StructureKind.Property:
  6996. case exports.StructureKind.VariableDeclaration:
  6997. return true;
  6998. default:
  6999. return false;
  7000. }
  7001. },
  7002. isPropertySignature(structure) {
  7003. return structure?.kind === exports.StructureKind.PropertySignature;
  7004. },
  7005. isSetAccessor(structure) {
  7006. return structure?.kind === exports.StructureKind.SetAccessor;
  7007. },
  7008. isShorthandPropertyAssignment(structure) {
  7009. return structure?.kind === exports.StructureKind.ShorthandPropertyAssignment;
  7010. },
  7011. isSourceFile(structure) {
  7012. return structure?.kind === exports.StructureKind.SourceFile;
  7013. },
  7014. isSpreadAssignment(structure) {
  7015. return structure?.kind === exports.StructureKind.SpreadAssignment;
  7016. },
  7017. isExpressioned(structure) {
  7018. return structure?.kind === exports.StructureKind.SpreadAssignment;
  7019. },
  7020. isTypeAlias(structure) {
  7021. return structure?.kind === exports.StructureKind.TypeAlias;
  7022. },
  7023. isTypeParameter(structure) {
  7024. return structure?.kind === exports.StructureKind.TypeParameter;
  7025. },
  7026. isVariableDeclaration(structure) {
  7027. return structure?.kind === exports.StructureKind.VariableDeclaration;
  7028. },
  7029. isVariableStatement(structure) {
  7030. return structure?.kind === exports.StructureKind.VariableStatement;
  7031. }
  7032. };
  7033. function forEachStructureChild(structure, callback) {
  7034. if (common.ArrayUtils.isReadonlyArray(structure)) {
  7035. for (const item of structure) {
  7036. const result = callback(item);
  7037. if (result)
  7038. return result;
  7039. }
  7040. return undefined;
  7041. }
  7042. switch (structure.kind) {
  7043. case exports.StructureKind.CallSignature:
  7044. return forCallSignatureDeclaration(structure, callback);
  7045. case exports.StructureKind.Class:
  7046. return forClassDeclaration(structure, callback);
  7047. case exports.StructureKind.ClassStaticBlock:
  7048. return forClassStaticBlockDeclaration(structure, callback);
  7049. case exports.StructureKind.ConstructorOverload:
  7050. return forConstructorDeclarationOverload(structure, callback);
  7051. case exports.StructureKind.Constructor:
  7052. return forConstructorDeclaration(structure, callback);
  7053. case exports.StructureKind.ConstructSignature:
  7054. return forConstructSignatureDeclaration(structure, callback);
  7055. case exports.StructureKind.Enum:
  7056. return forEnumDeclaration(structure, callback);
  7057. case exports.StructureKind.EnumMember:
  7058. return forEnumMember(structure, callback);
  7059. case exports.StructureKind.ExportAssignment:
  7060. return forExportAssignment(structure, callback);
  7061. case exports.StructureKind.ExportDeclaration:
  7062. return forExportDeclaration(structure, callback);
  7063. case exports.StructureKind.FunctionOverload:
  7064. return forFunctionDeclarationOverload(structure, callback);
  7065. case exports.StructureKind.Function:
  7066. return forFunctionDeclaration(structure, callback);
  7067. case exports.StructureKind.GetAccessor:
  7068. return forGetAccessorDeclaration(structure, callback);
  7069. case exports.StructureKind.ImportDeclaration:
  7070. return forImportDeclaration(structure, callback);
  7071. case exports.StructureKind.IndexSignature:
  7072. return forIndexSignatureDeclaration(structure, callback);
  7073. case exports.StructureKind.Interface:
  7074. return forInterfaceDeclaration(structure, callback);
  7075. case exports.StructureKind.JSDoc:
  7076. return forJSDoc(structure, callback);
  7077. case exports.StructureKind.JsxElement:
  7078. return forJsxElement(structure, callback);
  7079. case exports.StructureKind.JsxSelfClosingElement:
  7080. return forJsxSelfClosingElement(structure, callback);
  7081. case exports.StructureKind.MethodOverload:
  7082. return forMethodDeclarationOverload(structure, callback);
  7083. case exports.StructureKind.Method:
  7084. return forMethodDeclaration(structure, callback);
  7085. case exports.StructureKind.MethodSignature:
  7086. return forMethodSignature(structure, callback);
  7087. case exports.StructureKind.Module:
  7088. return forModuleDeclaration(structure, callback);
  7089. case exports.StructureKind.Parameter:
  7090. return forParameterDeclaration(structure, callback);
  7091. case exports.StructureKind.Property:
  7092. return forPropertyDeclaration(structure, callback);
  7093. case exports.StructureKind.PropertySignature:
  7094. return forPropertySignature(structure, callback);
  7095. case exports.StructureKind.SetAccessor:
  7096. return forSetAccessorDeclaration(structure, callback);
  7097. case exports.StructureKind.SourceFile:
  7098. return forSourceFile(structure, callback);
  7099. case exports.StructureKind.TypeAlias:
  7100. return forTypeAliasDeclaration(structure, callback);
  7101. case exports.StructureKind.VariableStatement:
  7102. return forVariableStatement(structure, callback);
  7103. default:
  7104. return undefined;
  7105. }
  7106. }
  7107. function forCallSignatureDeclaration(structure, callback) {
  7108. return forJSDocableNode(structure, callback)
  7109. || forSignaturedDeclaration(structure, callback)
  7110. || forTypeParameteredNode(structure, callback);
  7111. }
  7112. function forJSDocableNode(structure, callback) {
  7113. return forAllIfStructure(structure.docs, callback, exports.StructureKind.JSDoc);
  7114. }
  7115. function forSignaturedDeclaration(structure, callback) {
  7116. return forParameteredNode(structure, callback);
  7117. }
  7118. function forParameteredNode(structure, callback) {
  7119. return forAll(structure.parameters, callback, exports.StructureKind.Parameter);
  7120. }
  7121. function forTypeParameteredNode(structure, callback) {
  7122. return forAllIfStructure(structure.typeParameters, callback, exports.StructureKind.TypeParameter);
  7123. }
  7124. function forClassDeclaration(structure, callback) {
  7125. return forClassLikeDeclarationBase(structure, callback);
  7126. }
  7127. function forClassLikeDeclarationBase(structure, callback) {
  7128. return forDecoratableNode(structure, callback)
  7129. || forTypeParameteredNode(structure, callback)
  7130. || forJSDocableNode(structure, callback)
  7131. || forAll(structure.ctors, callback, exports.StructureKind.Constructor)
  7132. || forAll(structure.staticBlocks, callback, exports.StructureKind.ClassStaticBlock)
  7133. || forAll(structure.properties, callback, exports.StructureKind.Property)
  7134. || forAll(structure.getAccessors, callback, exports.StructureKind.GetAccessor)
  7135. || forAll(structure.setAccessors, callback, exports.StructureKind.SetAccessor)
  7136. || forAll(structure.methods, callback, exports.StructureKind.Method);
  7137. }
  7138. function forDecoratableNode(structure, callback) {
  7139. return forAll(structure.decorators, callback, exports.StructureKind.Decorator);
  7140. }
  7141. function forClassStaticBlockDeclaration(structure, callback) {
  7142. return forJSDocableNode(structure, callback)
  7143. || forStatementedNode(structure, callback);
  7144. }
  7145. function forStatementedNode(structure, callback) {
  7146. return forAllUnknownKindIfStructure(structure.statements, callback);
  7147. }
  7148. function forConstructorDeclarationOverload(structure, callback) {
  7149. return forSignaturedDeclaration(structure, callback)
  7150. || forTypeParameteredNode(structure, callback)
  7151. || forJSDocableNode(structure, callback);
  7152. }
  7153. function forConstructorDeclaration(structure, callback) {
  7154. return forFunctionLikeDeclaration(structure, callback)
  7155. || forAll(structure.overloads, callback, exports.StructureKind.ConstructorOverload);
  7156. }
  7157. function forFunctionLikeDeclaration(structure, callback) {
  7158. return forSignaturedDeclaration(structure, callback)
  7159. || forTypeParameteredNode(structure, callback)
  7160. || forJSDocableNode(structure, callback)
  7161. || forStatementedNode(structure, callback);
  7162. }
  7163. function forConstructSignatureDeclaration(structure, callback) {
  7164. return forJSDocableNode(structure, callback)
  7165. || forSignaturedDeclaration(structure, callback)
  7166. || forTypeParameteredNode(structure, callback);
  7167. }
  7168. function forEnumDeclaration(structure, callback) {
  7169. return forJSDocableNode(structure, callback)
  7170. || forAll(structure.members, callback, exports.StructureKind.EnumMember);
  7171. }
  7172. function forEnumMember(structure, callback) {
  7173. return forJSDocableNode(structure, callback);
  7174. }
  7175. function forExportAssignment(structure, callback) {
  7176. return forJSDocableNode(structure, callback);
  7177. }
  7178. function forExportDeclaration(structure, callback) {
  7179. return forAllIfStructure(structure.namedExports, callback, exports.StructureKind.ExportSpecifier)
  7180. || forAll(structure.attributes, callback, exports.StructureKind.ImportAttribute);
  7181. }
  7182. function forFunctionDeclarationOverload(structure, callback) {
  7183. return forSignaturedDeclaration(structure, callback)
  7184. || forTypeParameteredNode(structure, callback)
  7185. || forJSDocableNode(structure, callback);
  7186. }
  7187. function forFunctionDeclaration(structure, callback) {
  7188. return forFunctionLikeDeclaration(structure, callback)
  7189. || forAll(structure.overloads, callback, exports.StructureKind.FunctionOverload);
  7190. }
  7191. function forGetAccessorDeclaration(structure, callback) {
  7192. return forDecoratableNode(structure, callback)
  7193. || forFunctionLikeDeclaration(structure, callback);
  7194. }
  7195. function forImportDeclaration(structure, callback) {
  7196. return forAllIfStructure(structure.namedImports, callback, exports.StructureKind.ImportSpecifier)
  7197. || forAll(structure.attributes, callback, exports.StructureKind.ImportAttribute);
  7198. }
  7199. function forIndexSignatureDeclaration(structure, callback) {
  7200. return forJSDocableNode(structure, callback);
  7201. }
  7202. function forInterfaceDeclaration(structure, callback) {
  7203. return forTypeParameteredNode(structure, callback)
  7204. || forJSDocableNode(structure, callback)
  7205. || forTypeElementMemberedNode(structure, callback);
  7206. }
  7207. function forTypeElementMemberedNode(structure, callback) {
  7208. return forAll(structure.callSignatures, callback, exports.StructureKind.CallSignature)
  7209. || forAll(structure.constructSignatures, callback, exports.StructureKind.ConstructSignature)
  7210. || forAll(structure.getAccessors, callback, exports.StructureKind.GetAccessor)
  7211. || forAll(structure.indexSignatures, callback, exports.StructureKind.IndexSignature)
  7212. || forAll(structure.methods, callback, exports.StructureKind.MethodSignature)
  7213. || forAll(structure.properties, callback, exports.StructureKind.PropertySignature)
  7214. || forAll(structure.setAccessors, callback, exports.StructureKind.SetAccessor);
  7215. }
  7216. function forJSDoc(structure, callback) {
  7217. return forAll(structure.tags, callback, exports.StructureKind.JSDocTag);
  7218. }
  7219. function forJsxElement(structure, callback) {
  7220. return forAllUnknownKindIfStructure(structure.attributes, callback)
  7221. || forAllUnknownKindIfStructure(structure.children, callback);
  7222. }
  7223. function forJsxSelfClosingElement(structure, callback) {
  7224. return forJsxAttributedNode(structure, callback);
  7225. }
  7226. function forJsxAttributedNode(structure, callback) {
  7227. return forAllUnknownKindIfStructure(structure.attributes, callback);
  7228. }
  7229. function forMethodDeclarationOverload(structure, callback) {
  7230. return forSignaturedDeclaration(structure, callback)
  7231. || forTypeParameteredNode(structure, callback)
  7232. || forJSDocableNode(structure, callback);
  7233. }
  7234. function forMethodDeclaration(structure, callback) {
  7235. return forDecoratableNode(structure, callback)
  7236. || forFunctionLikeDeclaration(structure, callback)
  7237. || forAll(structure.overloads, callback, exports.StructureKind.MethodOverload);
  7238. }
  7239. function forMethodSignature(structure, callback) {
  7240. return forJSDocableNode(structure, callback)
  7241. || forSignaturedDeclaration(structure, callback)
  7242. || forTypeParameteredNode(structure, callback);
  7243. }
  7244. function forModuleDeclaration(structure, callback) {
  7245. return forJSDocableNode(structure, callback)
  7246. || forStatementedNode(structure, callback);
  7247. }
  7248. function forParameterDeclaration(structure, callback) {
  7249. return forDecoratableNode(structure, callback);
  7250. }
  7251. function forPropertyDeclaration(structure, callback) {
  7252. return forJSDocableNode(structure, callback)
  7253. || forDecoratableNode(structure, callback);
  7254. }
  7255. function forPropertySignature(structure, callback) {
  7256. return forJSDocableNode(structure, callback);
  7257. }
  7258. function forSetAccessorDeclaration(structure, callback) {
  7259. return forDecoratableNode(structure, callback)
  7260. || forFunctionLikeDeclaration(structure, callback);
  7261. }
  7262. function forSourceFile(structure, callback) {
  7263. return forStatementedNode(structure, callback);
  7264. }
  7265. function forTypeAliasDeclaration(structure, callback) {
  7266. return forTypeParameteredNode(structure, callback)
  7267. || forJSDocableNode(structure, callback);
  7268. }
  7269. function forVariableStatement(structure, callback) {
  7270. return forJSDocableNode(structure, callback)
  7271. || forAll(structure.declarations, callback, exports.StructureKind.VariableDeclaration);
  7272. }
  7273. function forAll(structures, callback, kind) {
  7274. if (structures == null)
  7275. return;
  7276. for (const structure of structures) {
  7277. const result = callback(ensureKind(structure, kind));
  7278. if (result)
  7279. return result;
  7280. }
  7281. return undefined;
  7282. }
  7283. function forAllIfStructure(values, callback, kind) {
  7284. if (values == null || !(values instanceof Array))
  7285. return;
  7286. for (const value of values) {
  7287. if (isStructure(value)) {
  7288. const result = callback(ensureKind(value, kind));
  7289. if (result)
  7290. return result;
  7291. }
  7292. }
  7293. return undefined;
  7294. }
  7295. function forAllUnknownKindIfStructure(values, callback) {
  7296. if (values == null || !(values instanceof Array))
  7297. return;
  7298. for (const value of values) {
  7299. if (isStructure(value)) {
  7300. const result = callback(value);
  7301. if (result)
  7302. return result;
  7303. }
  7304. }
  7305. return undefined;
  7306. }
  7307. function ensureKind(structure, kind) {
  7308. if (structure.kind == null)
  7309. structure.kind = kind;
  7310. return structure;
  7311. }
  7312. function isStructure(value) {
  7313. return value != null && typeof value.kind === "number";
  7314. }
  7315. function isLastNonWhitespaceCharCloseBrace(writer) {
  7316. return writer.iterateLastCharCodes(charCode => {
  7317. if (charCode === CharCodes.CLOSE_BRACE)
  7318. return true;
  7319. else if (common.StringUtils.isWhitespaceCharCode(charCode))
  7320. return undefined;
  7321. else
  7322. return false;
  7323. }) || false;
  7324. }
  7325. class ClassMemberStructurePrinter extends Printer {
  7326. #options;
  7327. #factory;
  7328. constructor(factory, options) {
  7329. super();
  7330. this.#factory = factory;
  7331. this.#options = options;
  7332. }
  7333. printTexts(writer, members) {
  7334. if (members == null)
  7335. return;
  7336. if (typeof members === "string" || members instanceof Function)
  7337. this.printText(writer, members);
  7338. else {
  7339. for (const member of members) {
  7340. if (isLastNonWhitespaceCharCloseBrace(writer))
  7341. writer.blankLineIfLastNot();
  7342. else if (!writer.isAtStartOfFirstLineOfBlock())
  7343. writer.newLineIfLastNot();
  7344. this.printText(writer, member);
  7345. }
  7346. }
  7347. }
  7348. printText(writer, member) {
  7349. if (typeof member === "string" || member instanceof Function || member == null) {
  7350. this.printTextOrWriterFunc(writer, member);
  7351. return;
  7352. }
  7353. switch (member.kind) {
  7354. case exports.StructureKind.Method:
  7355. if (!this.#options.isAmbient)
  7356. ensureBlankLine();
  7357. this.#factory.forMethodDeclaration(this.#options).printText(writer, member);
  7358. break;
  7359. case exports.StructureKind.Property:
  7360. this.#factory.forPropertyDeclaration().printText(writer, member);
  7361. break;
  7362. case exports.StructureKind.GetAccessor:
  7363. if (!this.#options.isAmbient)
  7364. ensureBlankLine();
  7365. this.#factory.forGetAccessorDeclaration(this.#options).printText(writer, member);
  7366. break;
  7367. case exports.StructureKind.SetAccessor:
  7368. if (!this.#options.isAmbient)
  7369. ensureBlankLine();
  7370. this.#factory.forSetAccessorDeclaration(this.#options).printText(writer, member);
  7371. break;
  7372. case exports.StructureKind.Constructor:
  7373. if (!this.#options.isAmbient)
  7374. ensureBlankLine();
  7375. this.#factory.forConstructorDeclaration(this.#options).printText(writer, member);
  7376. break;
  7377. case exports.StructureKind.ClassStaticBlock:
  7378. ensureBlankLine();
  7379. this.#factory.forClassStaticBlockDeclaration().printText(writer, member);
  7380. break;
  7381. default:
  7382. common.errors.throwNotImplementedForNeverValueError(member);
  7383. }
  7384. function ensureBlankLine() {
  7385. if (!writer.isAtStartOfFirstLineOfBlock())
  7386. writer.blankLineIfLastNot();
  7387. }
  7388. }
  7389. }
  7390. class ClassStaticBlockDeclarationStructurePrinter extends NodePrinter {
  7391. constructor(factory) {
  7392. super(factory);
  7393. }
  7394. printTexts(writer, structures) {
  7395. if (structures == null)
  7396. return;
  7397. for (let i = 0; i < structures.length; i++) {
  7398. if (i > 0)
  7399. writer.blankLine();
  7400. this.printText(writer, structures[i]);
  7401. }
  7402. }
  7403. printTextInternal(writer, structure) {
  7404. writer.write("static");
  7405. writer.space().inlineBlock(() => {
  7406. this.factory.forStatementedNode({ isAmbient: false }).printText(writer, structure);
  7407. });
  7408. }
  7409. }
  7410. class ConstructorDeclarationStructurePrinter extends NodePrinter {
  7411. #options;
  7412. constructor(factory, options) {
  7413. super(factory);
  7414. this.#options = options;
  7415. }
  7416. printTexts(writer, structures) {
  7417. if (structures == null)
  7418. return;
  7419. for (let i = 0; i < structures.length; i++) {
  7420. if (i > 0) {
  7421. if (this.#options.isAmbient)
  7422. writer.newLine();
  7423. else
  7424. writer.blankLine();
  7425. }
  7426. this.printText(writer, structures[i]);
  7427. }
  7428. }
  7429. printTextInternal(writer, structure) {
  7430. this.#printOverloads(writer, getOverloadStructures());
  7431. this.#printHeader(writer, structure);
  7432. if (this.#options.isAmbient)
  7433. writer.write(";");
  7434. else {
  7435. writer.space().inlineBlock(() => {
  7436. this.factory.forStatementedNode(this.#options).printText(writer, structure);
  7437. });
  7438. }
  7439. function getOverloadStructures() {
  7440. const overloads = common.ObjectUtils.clone(structure.overloads);
  7441. if (overloads == null || overloads.length === 0)
  7442. return;
  7443. for (const overload of overloads)
  7444. setValueIfUndefined(overload, "scope", structure.scope);
  7445. return overloads;
  7446. }
  7447. }
  7448. #printOverloads(writer, structures) {
  7449. if (structures == null || structures.length === 0)
  7450. return;
  7451. for (const structure of structures) {
  7452. this.printOverload(writer, structure);
  7453. writer.newLine();
  7454. }
  7455. }
  7456. printOverload(writer, structure) {
  7457. this.printLeadingTrivia(writer, structure);
  7458. this.#printHeader(writer, structure);
  7459. writer.write(";");
  7460. this.printTrailingTrivia(writer, structure);
  7461. }
  7462. #printHeader(writer, structure) {
  7463. this.factory.forJSDoc().printDocs(writer, structure.docs);
  7464. this.factory.forModifierableNode().printText(writer, structure);
  7465. writer.write("constructor");
  7466. this.factory.forTypeParameterDeclaration().printTextsWithBrackets(writer, structure.typeParameters);
  7467. this.factory.forParameterDeclaration().printTextsWithParenthesis(writer, structure.parameters);
  7468. }
  7469. }
  7470. class GetAccessorDeclarationStructurePrinter extends NodePrinter {
  7471. #options;
  7472. #multipleWriter;
  7473. constructor(factory, options) {
  7474. super(factory);
  7475. this.#options = options;
  7476. this.#multipleWriter = this.#options.isAmbient ? new NewLineFormattingStructuresPrinter(this) : new BlankLineFormattingStructuresPrinter(this);
  7477. }
  7478. printTexts(writer, structures) {
  7479. if (structures != null)
  7480. this.#multipleWriter.printText(writer, structures);
  7481. }
  7482. printTextInternal(writer, structure) {
  7483. this.factory.forJSDoc().printDocs(writer, structure.docs);
  7484. this.factory.forDecorator().printTexts(writer, structure.decorators);
  7485. this.factory.forModifierableNode().printText(writer, structure);
  7486. writer.write(`get ${structure.name}`);
  7487. this.factory.forTypeParameterDeclaration().printTextsWithBrackets(writer, structure.typeParameters);
  7488. this.factory.forParameterDeclaration().printTextsWithParenthesis(writer, structure.parameters);
  7489. this.factory.forReturnTypedNode().printText(writer, structure);
  7490. if (this.#options.isAmbient || structure.isAbstract)
  7491. writer.write(";");
  7492. else {
  7493. writer.spaceIfLastNot().inlineBlock(() => {
  7494. this.factory.forStatementedNode(this.#options).printText(writer, structure);
  7495. });
  7496. }
  7497. }
  7498. }
  7499. class MethodDeclarationStructurePrinter extends NodePrinter {
  7500. #options;
  7501. constructor(factory, options) {
  7502. super(factory);
  7503. this.#options = options;
  7504. }
  7505. printTexts(writer, structures) {
  7506. if (structures == null)
  7507. return;
  7508. for (let i = 0; i < structures.length; i++) {
  7509. if (i > 0) {
  7510. if (this.#options.isAmbient)
  7511. writer.newLine();
  7512. else
  7513. writer.blankLine();
  7514. }
  7515. this.printText(writer, structures[i]);
  7516. }
  7517. }
  7518. printTextInternal(writer, structure) {
  7519. this.#printOverloads(writer, structure.name, getOverloadStructures());
  7520. this.#printHeader(writer, structure.name, structure);
  7521. if (this.#options.isAmbient || structure.isAbstract)
  7522. writer.write(";");
  7523. else {
  7524. writer.spaceIfLastNot().inlineBlock(() => {
  7525. this.factory.forStatementedNode(this.#options).printText(writer, structure);
  7526. });
  7527. }
  7528. function getOverloadStructures() {
  7529. const overloads = common.ObjectUtils.clone(structure.overloads);
  7530. if (overloads == null || overloads.length === 0)
  7531. return;
  7532. for (const overload of overloads) {
  7533. setValueIfUndefined(overload, "scope", structure.scope);
  7534. setValueIfUndefined(overload, "isStatic", structure.isStatic);
  7535. setValueIfUndefined(overload, "isAbstract", structure.isAbstract);
  7536. setValueIfUndefined(overload, "hasQuestionToken", structure.hasQuestionToken);
  7537. }
  7538. return overloads;
  7539. }
  7540. }
  7541. #printOverloads(writer, name, structures) {
  7542. if (structures == null || structures.length === 0)
  7543. return;
  7544. for (const structure of structures) {
  7545. this.printOverload(writer, name, structure);
  7546. writer.newLine();
  7547. }
  7548. }
  7549. printOverload(writer, name, structure) {
  7550. this.printLeadingTrivia(writer, structure);
  7551. this.#printHeader(writer, name, structure);
  7552. writer.write(";");
  7553. this.printTrailingTrivia(writer, structure);
  7554. }
  7555. #printHeader(writer, name, structure) {
  7556. this.factory.forJSDoc().printDocs(writer, structure.docs);
  7557. if (structure.decorators != null)
  7558. this.factory.forDecorator().printTexts(writer, structure.decorators);
  7559. this.factory.forModifierableNode().printText(writer, structure);
  7560. writer.conditionalWrite(structure.isGenerator, "*");
  7561. writer.write(name);
  7562. writer.conditionalWrite(structure.hasQuestionToken, "?");
  7563. this.factory.forTypeParameterDeclaration().printTextsWithBrackets(writer, structure.typeParameters);
  7564. this.factory.forParameterDeclaration().printTextsWithParenthesis(writer, structure.parameters);
  7565. this.factory.forReturnTypedNode().printText(writer, structure);
  7566. }
  7567. }
  7568. class PropertyDeclarationStructurePrinter extends NodePrinter {
  7569. #multipleWriter = new NewLineFormattingStructuresPrinter(this);
  7570. printTexts(writer, structures) {
  7571. this.#multipleWriter.printText(writer, structures);
  7572. }
  7573. printTextInternal(writer, structure) {
  7574. this.factory.forJSDoc().printDocs(writer, structure.docs);
  7575. this.factory.forDecorator().printTexts(writer, structure.decorators);
  7576. this.factory.forModifierableNode().printText(writer, structure);
  7577. writer.write(structure.name);
  7578. writer.conditionalWrite(structure.hasQuestionToken, "?");
  7579. writer.conditionalWrite(structure.hasExclamationToken && !structure.hasQuestionToken, "!");
  7580. this.factory.forTypedNode(":").printText(writer, structure);
  7581. this.factory.forInitializerExpressionableNode().printText(writer, structure);
  7582. writer.write(";");
  7583. }
  7584. }
  7585. class SetAccessorDeclarationStructurePrinter extends NodePrinter {
  7586. #options;
  7587. #multipleWriter;
  7588. constructor(factory, options) {
  7589. super(factory);
  7590. this.#options = options;
  7591. this.#multipleWriter = this.#options.isAmbient ? new NewLineFormattingStructuresPrinter(this) : new BlankLineFormattingStructuresPrinter(this);
  7592. }
  7593. printTexts(writer, structures) {
  7594. if (structures != null)
  7595. this.#multipleWriter.printText(writer, structures);
  7596. }
  7597. printTextInternal(writer, structure) {
  7598. this.factory.forJSDoc().printDocs(writer, structure.docs);
  7599. this.factory.forDecorator().printTexts(writer, structure.decorators);
  7600. this.factory.forModifierableNode().printText(writer, structure);
  7601. writer.write(`set ${structure.name}`);
  7602. this.factory.forTypeParameterDeclaration().printTextsWithBrackets(writer, structure.typeParameters);
  7603. this.factory.forParameterDeclaration().printTextsWithParenthesis(writer, structure.parameters);
  7604. this.factory.forReturnTypedNode().printText(writer, structure);
  7605. if (this.#options.isAmbient || structure.isAbstract)
  7606. writer.write(";");
  7607. else {
  7608. writer.spaceIfLastNot().inlineBlock(() => {
  7609. this.factory.forStatementedNode(this.#options).printText(writer, structure);
  7610. });
  7611. }
  7612. }
  7613. }
  7614. class StringStructurePrinter extends Printer {
  7615. printText(writer, textOrWriterFunc) {
  7616. if (typeof textOrWriterFunc === "string")
  7617. writer.write(textOrWriterFunc);
  7618. else
  7619. textOrWriterFunc(writer);
  7620. }
  7621. }
  7622. class DecoratorStructurePrinter extends NodePrinter {
  7623. printTexts(writer, structures) {
  7624. this.#printMultiple(writer, structures, () => writer.newLine());
  7625. }
  7626. printTextsInline(writer, structures) {
  7627. this.#printMultiple(writer, structures, () => writer.space());
  7628. }
  7629. printTextInternal(writer, structure) {
  7630. writer.write(`@${structure.name}`);
  7631. this.#printTypeArguments(writer, structure);
  7632. this.#printArguments(writer, structure);
  7633. }
  7634. #printTypeArguments(writer, structure) {
  7635. if (structure.typeArguments == null || structure.typeArguments.length === 0)
  7636. return;
  7637. writer.write("<");
  7638. for (let i = 0; i < structure.typeArguments.length; i++) {
  7639. writer.conditionalWrite(i > 0, ", ");
  7640. writer.write(this.getTextWithQueuedChildIndentation(writer, structure.typeArguments[i]));
  7641. }
  7642. writer.write(">");
  7643. }
  7644. #printArguments(writer, structure) {
  7645. if (structure.arguments == null)
  7646. return;
  7647. writer.write("(");
  7648. const args = structure.arguments instanceof Array ? structure.arguments : [structure.arguments];
  7649. for (let i = 0; i < args.length; i++) {
  7650. writer.conditionalWrite(i > 0, ", ");
  7651. writer.write(this.getTextWithQueuedChildIndentation(writer, args[i]));
  7652. }
  7653. writer.write(")");
  7654. }
  7655. #printMultiple(writer, structures, separator) {
  7656. if (structures == null || structures.length === 0)
  7657. return;
  7658. for (const structure of structures) {
  7659. this.printText(writer, structure);
  7660. separator();
  7661. }
  7662. }
  7663. }
  7664. class JSDocStructurePrinter extends NodePrinter {
  7665. printDocs(writer, structures) {
  7666. if (structures == null)
  7667. return;
  7668. for (const structure of structures) {
  7669. this.printText(writer, structure);
  7670. writer.newLine();
  7671. }
  7672. }
  7673. printTextInternal(writer, structure) {
  7674. const text = getText(this);
  7675. const lines = text.split(/\r?\n/);
  7676. const startsWithNewLine = lines[0].length === 0;
  7677. const isSingleLine = lines.length <= 1;
  7678. const startIndex = startsWithNewLine ? 1 : 0;
  7679. writer.write("/**");
  7680. if (isSingleLine)
  7681. writer.space();
  7682. else
  7683. writer.newLine();
  7684. if (isSingleLine)
  7685. writer.write(lines[startIndex]);
  7686. else {
  7687. for (let i = startIndex; i < lines.length; i++) {
  7688. writer.write(` *`);
  7689. if (lines[i].length > 0)
  7690. writer.write(` ${lines[i]}`);
  7691. writer.newLine();
  7692. }
  7693. }
  7694. writer.spaceIfLastNot();
  7695. writer.write("*/");
  7696. function getText(jsdocPrinter) {
  7697. if (typeof structure === "string")
  7698. return structure;
  7699. const tempWriter = jsdocPrinter.getNewWriter(writer);
  7700. if (typeof structure === "function")
  7701. structure(tempWriter);
  7702. else {
  7703. if (structure.description)
  7704. printTextFromStringOrWriter(tempWriter, structure.description);
  7705. if (structure.tags && structure.tags.length > 0) {
  7706. if (tempWriter.getLength() > 0)
  7707. tempWriter.newLine();
  7708. jsdocPrinter.factory.forJSDocTag({ printStarsOnNewLine: false }).printTexts(tempWriter, structure.tags);
  7709. }
  7710. }
  7711. return tempWriter.toString();
  7712. }
  7713. }
  7714. }
  7715. class JSDocTagStructurePrinter extends NodePrinter {
  7716. #options;
  7717. constructor(factory, options) {
  7718. super(factory);
  7719. this.#options = options;
  7720. }
  7721. printTexts(writer, structures) {
  7722. if (structures == null)
  7723. return;
  7724. for (let i = 0; i < structures.length; i++) {
  7725. if (i > 0) {
  7726. writer.newLine();
  7727. writer.conditionalWrite(this.#options.printStarsOnNewLine, " * ");
  7728. }
  7729. this.printText(writer, structures[i]);
  7730. }
  7731. }
  7732. printTextInternal(writer, structure) {
  7733. const text = getText(this);
  7734. const lines = text.split(/\r?\n/);
  7735. for (let i = 0; i < lines.length; i++) {
  7736. if (i > 0) {
  7737. writer.newLine();
  7738. if (this.#options.printStarsOnNewLine)
  7739. writer.write(` *`);
  7740. }
  7741. if (lines[i].length > 0) {
  7742. if (this.#options.printStarsOnNewLine && i > 0)
  7743. writer.space();
  7744. writer.write(lines[i]);
  7745. }
  7746. }
  7747. function getText(tagPrinter) {
  7748. if (typeof structure === "string")
  7749. return structure;
  7750. const tempWriter = tagPrinter.getNewWriter(writer);
  7751. if (typeof structure === "function")
  7752. structure(tempWriter);
  7753. else {
  7754. if (structure.text)
  7755. printTextFromStringOrWriter(tempWriter, structure.text);
  7756. const currentText = tempWriter.toString();
  7757. tempWriter.unsafeInsert(0, `@${structure.tagName}` + (currentText.length > 0 && !common.StringUtils.startsWithNewLine(currentText) ? " " : ""));
  7758. }
  7759. return tempWriter.toString();
  7760. }
  7761. }
  7762. }
  7763. class EnumDeclarationStructurePrinter extends NodePrinter {
  7764. #multipleWriter = new BlankLineFormattingStructuresPrinter(this);
  7765. printTexts(writer, structures) {
  7766. this.#multipleWriter.printText(writer, structures);
  7767. }
  7768. printTextInternal(writer, structure) {
  7769. this.factory.forJSDoc().printDocs(writer, structure.docs);
  7770. this.factory.forModifierableNode().printText(writer, structure);
  7771. writer.conditionalWrite(structure.isConst, "const ");
  7772. writer.write(`enum ${structure.name} `).inlineBlock(() => {
  7773. this.factory.forEnumMember().printTexts(writer, structure.members);
  7774. });
  7775. }
  7776. }
  7777. class EnumMemberStructurePrinter extends NodePrinter {
  7778. #multipleWriter = new CommaNewLineSeparatedStructuresPrinter(this);
  7779. printTexts(writer, structures) {
  7780. this.#multipleWriter.printText(writer, structures);
  7781. }
  7782. printTextInternal(writer, structure) {
  7783. if (structure instanceof Function) {
  7784. structure(writer);
  7785. return;
  7786. }
  7787. else if (typeof structure === "string") {
  7788. writer.write(structure);
  7789. return;
  7790. }
  7791. this.factory.forJSDoc().printDocs(writer, structure.docs);
  7792. if (isValidVariableName(structure.name) || common.StringUtils.isQuoted(structure.name))
  7793. writer.write(structure.name);
  7794. else
  7795. writer.quote(structure.name);
  7796. if (typeof structure.value === "string") {
  7797. const { value } = structure;
  7798. writer.hangingIndent(() => writer.write(` = `).quote(value));
  7799. }
  7800. else if (typeof structure.value === "number")
  7801. writer.write(` = ${structure.value}`);
  7802. else
  7803. this.factory.forInitializerExpressionableNode().printText(writer, structure);
  7804. }
  7805. }
  7806. class ObjectLiteralExpressionPropertyStructurePrinter extends Printer {
  7807. #factory;
  7808. #multipleWriter = new CommaNewLineSeparatedStructuresPrinter(this);
  7809. #options = { isAmbient: false };
  7810. constructor(factory) {
  7811. super();
  7812. this.#factory = factory;
  7813. }
  7814. printTexts(writer, members) {
  7815. this.#multipleWriter.printText(writer, members);
  7816. }
  7817. printText(writer, member) {
  7818. if (typeof member === "string" || member instanceof Function || member == null) {
  7819. this.printTextOrWriterFunc(writer, member);
  7820. return;
  7821. }
  7822. switch (member.kind) {
  7823. case exports.StructureKind.PropertyAssignment:
  7824. this.#factory.forPropertyAssignment().printText(writer, member);
  7825. break;
  7826. case exports.StructureKind.ShorthandPropertyAssignment:
  7827. this.#factory.forShorthandPropertyAssignment().printText(writer, member);
  7828. break;
  7829. case exports.StructureKind.SpreadAssignment:
  7830. this.#factory.forSpreadAssignment().printText(writer, member);
  7831. break;
  7832. case exports.StructureKind.Method:
  7833. this.#factory.forMethodDeclaration(this.#options).printText(writer, member);
  7834. break;
  7835. case exports.StructureKind.GetAccessor:
  7836. this.#factory.forGetAccessorDeclaration(this.#options).printText(writer, member);
  7837. break;
  7838. case exports.StructureKind.SetAccessor:
  7839. this.#factory.forSetAccessorDeclaration(this.#options).printText(writer, member);
  7840. break;
  7841. default:
  7842. common.errors.throwNotImplementedForNeverValueError(member);
  7843. }
  7844. }
  7845. }
  7846. class PropertyAssignmentStructurePrinter extends NodePrinter {
  7847. printTextInternal(writer, structure) {
  7848. writer.hangingIndent(() => {
  7849. writer.write(`${structure.name}: `);
  7850. printTextFromStringOrWriter(writer, structure.initializer);
  7851. });
  7852. }
  7853. }
  7854. class ShorthandPropertyAssignmentStructurePrinter extends NodePrinter {
  7855. printTextInternal(writer, structure) {
  7856. writer.write(`${structure.name}`);
  7857. }
  7858. }
  7859. class SpreadAssignmentStructurePrinter extends NodePrinter {
  7860. printTextInternal(writer, structure) {
  7861. writer.hangingIndent(() => {
  7862. writer.write("...");
  7863. printTextFromStringOrWriter(writer, structure.expression);
  7864. });
  7865. }
  7866. }
  7867. class FunctionDeclarationStructurePrinter extends NodePrinter {
  7868. #options;
  7869. constructor(factory, options) {
  7870. super(factory);
  7871. this.#options = options;
  7872. }
  7873. printTexts(writer, structures) {
  7874. if (structures == null)
  7875. return;
  7876. for (let i = 0; i < structures.length; i++) {
  7877. const currentStructure = structures[i];
  7878. if (i > 0) {
  7879. const previousStructure = structures[i - 1];
  7880. if (this.#options.isAmbient || previousStructure.hasDeclareKeyword && currentStructure.hasDeclareKeyword)
  7881. writer.newLine();
  7882. else
  7883. writer.blankLine();
  7884. }
  7885. this.printText(writer, currentStructure);
  7886. }
  7887. }
  7888. printTextInternal(writer, structure) {
  7889. this.#printOverloads(writer, structure.name, getOverloadStructures());
  7890. this.#printHeader(writer, structure.name, structure);
  7891. if (this.#options.isAmbient || structure.hasDeclareKeyword)
  7892. writer.write(";");
  7893. else {
  7894. writer.space().inlineBlock(() => {
  7895. this.factory.forStatementedNode({ isAmbient: false }).printText(writer, structure);
  7896. });
  7897. }
  7898. function getOverloadStructures() {
  7899. const overloads = common.ObjectUtils.clone(structure.overloads);
  7900. if (overloads == null || overloads.length === 0)
  7901. return;
  7902. for (const overload of overloads) {
  7903. setValueIfUndefined(overload, "hasDeclareKeyword", structure.hasDeclareKeyword);
  7904. setValueIfUndefined(overload, "isExported", structure.isExported);
  7905. setValueIfUndefined(overload, "isDefaultExport", structure.isDefaultExport);
  7906. }
  7907. return overloads;
  7908. }
  7909. }
  7910. #printOverloads(writer, name, structures) {
  7911. if (structures == null || structures.length === 0)
  7912. return;
  7913. for (const structure of structures) {
  7914. this.printOverload(writer, name, structure);
  7915. writer.newLine();
  7916. }
  7917. }
  7918. printOverload(writer, name, structure) {
  7919. this.printLeadingTrivia(writer, structure);
  7920. this.#printHeader(writer, name, structure);
  7921. writer.write(";");
  7922. this.printTrailingTrivia(writer, structure);
  7923. }
  7924. #printHeader(writer, name, structure) {
  7925. this.factory.forJSDoc().printDocs(writer, structure.docs);
  7926. this.factory.forModifierableNode().printText(writer, structure);
  7927. writer.write(`function`);
  7928. writer.conditionalWrite(structure.isGenerator, "*");
  7929. if (!common.StringUtils.isNullOrWhitespace(name))
  7930. writer.write(` ${name}`);
  7931. this.factory.forTypeParameterDeclaration().printTextsWithBrackets(writer, structure.typeParameters);
  7932. this.factory.forParameterDeclaration().printTextsWithParenthesis(writer, structure.parameters);
  7933. this.factory.forReturnTypedNode().printText(writer, structure);
  7934. }
  7935. }
  7936. class ParameterDeclarationStructurePrinter extends NodePrinter {
  7937. #multipleWriter = new CommaSeparatedStructuresPrinter(this);
  7938. printTextsWithParenthesis(writer, structures) {
  7939. writer.write("(");
  7940. if (structures != null)
  7941. this.factory.forParameterDeclaration().printTexts(writer, structures);
  7942. writer.write(`)`);
  7943. }
  7944. printTexts(writer, structures) {
  7945. if (structures == null || structures.length === 0)
  7946. return;
  7947. writer.hangingIndent(() => {
  7948. this.#multipleWriter.printText(writer, structures);
  7949. });
  7950. }
  7951. printTextInternal(writer, structure) {
  7952. if (structure.name == null) {
  7953. throw new common.errors
  7954. .NotImplementedError("Not implemented scenario where parameter declaration structure doesn't have a name. Please open an issue if you need this.");
  7955. }
  7956. this.factory.forDecorator().printTextsInline(writer, structure.decorators);
  7957. this.factory.forModifierableNode().printText(writer, structure);
  7958. writer.conditionalWrite(structure.isRestParameter, "...");
  7959. writer.write(structure.name);
  7960. writer.conditionalWrite(structure.hasQuestionToken, "?");
  7961. this.factory.forTypedNode(":", structure.hasQuestionToken).printText(writer, structure);
  7962. this.factory.forInitializerExpressionableNode().printText(writer, structure);
  7963. }
  7964. }
  7965. class CallSignatureDeclarationStructurePrinter extends NodePrinter {
  7966. #multipleWriter = new NewLineFormattingStructuresPrinter(this);
  7967. printTexts(writer, structures) {
  7968. this.#multipleWriter.printText(writer, structures);
  7969. }
  7970. printTextInternal(writer, structure) {
  7971. this.factory.forJSDoc().printDocs(writer, structure.docs);
  7972. this.factory.forTypeParameterDeclaration().printTextsWithBrackets(writer, structure.typeParameters);
  7973. this.factory.forParameterDeclaration().printTextsWithParenthesis(writer, structure.parameters);
  7974. this.factory.forReturnTypedNode(true).printText(writer, structure);
  7975. writer.write(";");
  7976. }
  7977. }
  7978. class ConstructSignatureDeclarationStructurePrinter extends NodePrinter {
  7979. #multipleWriter = new NewLineFormattingStructuresPrinter(this);
  7980. printTexts(writer, structures) {
  7981. this.#multipleWriter.printText(writer, structures);
  7982. }
  7983. printTextInternal(writer, structure) {
  7984. this.factory.forJSDoc().printDocs(writer, structure.docs);
  7985. writer.write("new");
  7986. this.factory.forTypeParameterDeclaration().printTextsWithBrackets(writer, structure.typeParameters);
  7987. this.factory.forParameterDeclaration().printTextsWithParenthesis(writer, structure.parameters);
  7988. this.factory.forReturnTypedNode().printText(writer, structure);
  7989. writer.write(";");
  7990. }
  7991. }
  7992. class IndexSignatureDeclarationStructurePrinter extends NodePrinter {
  7993. #multipleWriter = new NewLineFormattingStructuresPrinter(this);
  7994. printTexts(writer, structures) {
  7995. this.#multipleWriter.printText(writer, structures);
  7996. }
  7997. printTextInternal(writer, structure) {
  7998. this.factory.forJSDoc().printDocs(writer, structure.docs);
  7999. this.factory.forModifierableNode().printText(writer, structure);
  8000. writer.write(`[${structure.keyName || "key"}: ${structure.keyType || "string"}]`);
  8001. this.factory.forReturnTypedNode().printText(writer, structure);
  8002. writer.write(";");
  8003. }
  8004. }
  8005. class InterfaceDeclarationStructurePrinter extends NodePrinter {
  8006. #multipleWriter = new BlankLineFormattingStructuresPrinter(this);
  8007. printTexts(writer, structures) {
  8008. this.#multipleWriter.printText(writer, structures);
  8009. }
  8010. printTextInternal(writer, structure) {
  8011. this.factory.forJSDoc().printDocs(writer, structure.docs);
  8012. this.factory.forModifierableNode().printText(writer, structure);
  8013. writer.write(`interface ${structure.name}`);
  8014. this.factory.forTypeParameterDeclaration().printTextsWithBrackets(writer, structure.typeParameters);
  8015. writer.space();
  8016. if (structure.extends != null) {
  8017. const extendsText = structure.extends instanceof Array
  8018. ? structure.extends.map(i => this.getText(writer, i)).join(", ")
  8019. : this.getText(writer, structure.extends);
  8020. if (!common.StringUtils.isNullOrWhitespace(extendsText))
  8021. writer.hangingIndent(() => writer.write(`extends ${extendsText} `));
  8022. }
  8023. writer.inlineBlock(() => {
  8024. this.factory.forTypeElementMemberedNode().printText(writer, structure);
  8025. });
  8026. }
  8027. }
  8028. class MethodSignatureStructurePrinter extends NodePrinter {
  8029. #multipleWriter = new NewLineFormattingStructuresPrinter(this);
  8030. printTexts(writer, structures) {
  8031. this.#multipleWriter.printText(writer, structures);
  8032. }
  8033. printTextInternal(writer, structure) {
  8034. this.factory.forJSDoc().printDocs(writer, structure.docs);
  8035. writer.write(structure.name);
  8036. writer.conditionalWrite(structure.hasQuestionToken, "?");
  8037. this.factory.forTypeParameterDeclaration().printTextsWithBrackets(writer, structure.typeParameters);
  8038. this.factory.forParameterDeclaration().printTextsWithParenthesis(writer, structure.parameters);
  8039. this.factory.forReturnTypedNode().printText(writer, structure);
  8040. writer.write(";");
  8041. }
  8042. }
  8043. class PropertySignatureStructurePrinter extends NodePrinter {
  8044. #multipleWriter = new NewLineFormattingStructuresPrinter(this);
  8045. printTexts(writer, structures) {
  8046. this.#multipleWriter.printText(writer, structures);
  8047. }
  8048. printTextInternal(writer, structure) {
  8049. this.factory.forJSDoc().printDocs(writer, structure.docs);
  8050. this.factory.forModifierableNode().printText(writer, structure);
  8051. writer.write(structure.name);
  8052. writer.conditionalWrite(structure.hasQuestionToken, "?");
  8053. this.factory.forTypedNode(":").printText(writer, structure);
  8054. this.factory.forInitializerExpressionableNode().printText(writer, structure);
  8055. writer.write(";");
  8056. }
  8057. }
  8058. class TypeElementMemberedNodeStructurePrinter extends Printer {
  8059. #factory;
  8060. constructor(factory) {
  8061. super();
  8062. this.#factory = factory;
  8063. }
  8064. printText(writer, structure) {
  8065. this.#factory.forCallSignatureDeclaration().printTexts(writer, structure.callSignatures);
  8066. this.#conditionalSeparator(writer, structure.constructSignatures);
  8067. this.#factory.forConstructSignatureDeclaration().printTexts(writer, structure.constructSignatures);
  8068. this.#conditionalSeparator(writer, structure.indexSignatures);
  8069. this.#factory.forIndexSignatureDeclaration().printTexts(writer, structure.indexSignatures);
  8070. this.#printGetAndSet(writer, structure);
  8071. this.#conditionalSeparator(writer, structure.properties);
  8072. this.#factory.forPropertySignature().printTexts(writer, structure.properties);
  8073. this.#conditionalSeparator(writer, structure.methods);
  8074. this.#factory.forMethodSignature().printTexts(writer, structure.methods);
  8075. }
  8076. #printGetAndSet(writer, structure) {
  8077. if (structure.getAccessors == null && structure.setAccessors == null)
  8078. return;
  8079. const getAccessorWriter = this.#factory.forGetAccessorDeclaration({ isAmbient: true });
  8080. const setAccessorWriter = this.#factory.forSetAccessorDeclaration({ isAmbient: true });
  8081. const combinedPrinter = new GetAndSetAccessorStructurePrinter(getAccessorWriter, setAccessorWriter);
  8082. combinedPrinter.printGetAndSet(writer, structure.getAccessors, structure.setAccessors, true);
  8083. }
  8084. #conditionalSeparator(writer, structures) {
  8085. if (!common.ArrayUtils.isNullOrEmpty(structures) && !writer.isAtStartOfFirstLineOfBlock())
  8086. writer.newLine();
  8087. }
  8088. }
  8089. class TypeElementMemberStructurePrinter extends Printer {
  8090. #factory;
  8091. constructor(factory) {
  8092. super();
  8093. this.#factory = factory;
  8094. }
  8095. printTexts(writer, members) {
  8096. if (members == null)
  8097. return;
  8098. if (typeof members === "string" || members instanceof Function)
  8099. this.printText(writer, members);
  8100. else {
  8101. for (const member of members) {
  8102. if (isLastNonWhitespaceCharCloseBrace(writer))
  8103. writer.blankLineIfLastNot();
  8104. else if (!writer.isAtStartOfFirstLineOfBlock())
  8105. writer.newLineIfLastNot();
  8106. this.printText(writer, member);
  8107. }
  8108. }
  8109. }
  8110. printText(writer, members) {
  8111. if (typeof members === "string" || members instanceof Function || members == null) {
  8112. this.printTextOrWriterFunc(writer, members);
  8113. return;
  8114. }
  8115. switch (members.kind) {
  8116. case exports.StructureKind.PropertySignature:
  8117. this.#factory.forPropertySignature().printText(writer, members);
  8118. break;
  8119. case exports.StructureKind.MethodSignature:
  8120. this.#factory.forMethodSignature().printText(writer, members);
  8121. break;
  8122. case exports.StructureKind.CallSignature:
  8123. this.#factory.forCallSignatureDeclaration().printText(writer, members);
  8124. break;
  8125. case exports.StructureKind.IndexSignature:
  8126. this.#factory.forIndexSignatureDeclaration().printText(writer, members);
  8127. break;
  8128. case exports.StructureKind.ConstructSignature:
  8129. this.#factory.forConstructSignatureDeclaration().printText(writer, members);
  8130. break;
  8131. default:
  8132. common.errors.throwNotImplementedForNeverValueError(members);
  8133. }
  8134. }
  8135. }
  8136. class JsxAttributeDeciderStructurePrinter extends NodePrinter {
  8137. printTextInternal(writer, structure) {
  8138. if (isJsxAttribute())
  8139. this.factory.forJsxAttribute().printTextWithoutTrivia(writer, structure);
  8140. else if (structure.kind === exports.StructureKind.JsxSpreadAttribute)
  8141. this.factory.forJsxSpreadAttribute().printTextWithoutTrivia(writer, structure);
  8142. else
  8143. throw common.errors.throwNotImplementedForNeverValueError(structure);
  8144. function isJsxAttribute(struct) {
  8145. return structure.kind == null || structure.kind === exports.StructureKind.JsxAttribute;
  8146. }
  8147. }
  8148. }
  8149. class JsxAttributeStructurePrinter extends NodePrinter {
  8150. printTextInternal(writer, structure) {
  8151. if (typeof structure.name === "object")
  8152. this.factory.forJsxNamespacedName().printText(writer, structure.name);
  8153. else
  8154. writer.write(structure.name);
  8155. if (structure.initializer != null)
  8156. writer.write("=").write(structure.initializer);
  8157. }
  8158. }
  8159. class JsxChildDeciderStructurePrinter extends NodePrinter {
  8160. printTextInternal(writer, structure) {
  8161. if (isJsxElement(structure))
  8162. this.factory.forJsxElement().printText(writer, structure);
  8163. else if (structure.kind === exports.StructureKind.JsxSelfClosingElement)
  8164. this.factory.forJsxSelfClosingElement().printText(writer, structure);
  8165. else
  8166. common.errors.throwNotImplementedForNeverValueError(structure);
  8167. function isJsxElement(struct) {
  8168. return struct.kind == null || struct.kind === exports.StructureKind.JsxElement;
  8169. }
  8170. }
  8171. }
  8172. class JsxElementStructurePrinter extends NodePrinter {
  8173. printTextInternal(writer, structure) {
  8174. writer.hangingIndent(() => {
  8175. writer.write(`<${structure.name}`);
  8176. if (structure.attributes)
  8177. this.#printAttributes(writer, structure.attributes);
  8178. writer.write(">");
  8179. });
  8180. this.#printChildren(writer, structure.children);
  8181. writer.write(`</${structure.name}>`);
  8182. }
  8183. #printAttributes(writer, attributes) {
  8184. const attributePrinter = this.factory.forJsxAttributeDecider();
  8185. for (const attrib of attributes) {
  8186. writer.space();
  8187. attributePrinter.printText(writer, attrib);
  8188. }
  8189. }
  8190. #printChildren(writer, children) {
  8191. if (children == null)
  8192. return;
  8193. writer.newLine();
  8194. writer.indent(() => {
  8195. for (const child of children) {
  8196. this.factory.forJsxChildDecider().printText(writer, child);
  8197. writer.newLine();
  8198. }
  8199. });
  8200. }
  8201. }
  8202. class JsxNamespacedNameStructurePrinter extends NodePrinter {
  8203. printTextInternal(writer, structure) {
  8204. writer.write(structure.namespace).write(":").write(structure.name);
  8205. }
  8206. }
  8207. class JsxSelfClosingElementStructurePrinter extends NodePrinter {
  8208. printTextInternal(writer, structure) {
  8209. writer.hangingIndent(() => {
  8210. writer.write(`<${structure.name}`);
  8211. if (structure.attributes)
  8212. this.#printAttributes(writer, structure.attributes);
  8213. writer.write(" />");
  8214. });
  8215. }
  8216. #printAttributes(writer, attributes) {
  8217. const attributePrinter = this.factory.forJsxAttributeDecider();
  8218. for (const attrib of attributes) {
  8219. writer.space();
  8220. attributePrinter.printText(writer, attrib);
  8221. }
  8222. }
  8223. }
  8224. class JsxSpreadAttributeStructurePrinter extends NodePrinter {
  8225. printTextInternal(writer, structure) {
  8226. writer.hangingIndent(() => {
  8227. writer.write("{");
  8228. writer.write("...");
  8229. writer.write(structure.expression);
  8230. writer.write("}");
  8231. });
  8232. }
  8233. }
  8234. class ExportAssignmentStructurePrinter extends NodePrinter {
  8235. #multipleWriter = new NewLineFormattingStructuresPrinter(this);
  8236. printTexts(writer, structures) {
  8237. this.#multipleWriter.printText(writer, structures);
  8238. }
  8239. printTextInternal(writer, structure) {
  8240. this.factory.forJSDoc().printDocs(writer, structure.docs);
  8241. writer.write("export");
  8242. if (structure.isExportEquals !== false)
  8243. writer.write(" = ");
  8244. else
  8245. writer.write(" default ");
  8246. writer.write(this.getTextWithQueuedChildIndentation(writer, structure.expression)).write(";");
  8247. }
  8248. }
  8249. class ExportDeclarationStructurePrinter extends NodePrinter {
  8250. #multipleWriter = new NewLineFormattingStructuresPrinter(this);
  8251. printTexts(writer, structures) {
  8252. this.#multipleWriter.printText(writer, structures);
  8253. }
  8254. printTextInternal(writer, structure) {
  8255. const hasModuleSpecifier = structure.moduleSpecifier != null && structure.moduleSpecifier.length > 0;
  8256. const hasNamedImport = structure.namedExports != null && structure.namedExports.length > 0;
  8257. if (hasNamedImport && structure.namespaceExport != null)
  8258. throw new common.errors.InvalidOperationError("An export declaration cannot have both a namespace export and a named export.");
  8259. writer.write("export");
  8260. if (structure.isTypeOnly)
  8261. writer.write(" type");
  8262. if (structure.namedExports != null && structure.namedExports.length > 0) {
  8263. writer.space();
  8264. this.factory.forNamedImportExportSpecifier().printTextsWithBraces(writer, structure.namedExports);
  8265. }
  8266. else if (structure.namespaceExport != null) {
  8267. writer.write(" *");
  8268. if (!common.StringUtils.isNullOrWhitespace(structure.namespaceExport))
  8269. writer.write(` as ${structure.namespaceExport}`);
  8270. }
  8271. else if (!hasModuleSpecifier) {
  8272. writer.write(" {")
  8273. .conditionalWrite(this.factory.getFormatCodeSettings().insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces, " ")
  8274. .write("}");
  8275. }
  8276. else {
  8277. writer.write(` *`);
  8278. }
  8279. if (hasModuleSpecifier) {
  8280. writer.write(" from ");
  8281. writer.quote(structure.moduleSpecifier);
  8282. }
  8283. if (structure.attributes) {
  8284. writer.space();
  8285. this.factory.forImportAttribute().printAttributes(writer, structure.attributes);
  8286. }
  8287. writer.write(";");
  8288. }
  8289. }
  8290. class ImportAttributeStructurePrinter extends NodePrinter {
  8291. #multipleWriter = new CommaNewLineSeparatedStructuresPrinter(this);
  8292. printTexts(writer, structures) {
  8293. this.#multipleWriter.printText(writer, structures);
  8294. }
  8295. printAttributes(writer, structures) {
  8296. if (!structures)
  8297. return;
  8298. writer.write("with ");
  8299. writer.inlineBlock(() => {
  8300. this.printTexts(writer, structures);
  8301. });
  8302. }
  8303. printTextInternal(writer, structure) {
  8304. writer.write(structure.name);
  8305. writer.write(": ");
  8306. writer.quote(structure.value);
  8307. }
  8308. }
  8309. class ImportDeclarationStructurePrinter extends NodePrinter {
  8310. #multipleWriter = new NewLineFormattingStructuresPrinter(this);
  8311. printTexts(writer, structures) {
  8312. this.#multipleWriter.printText(writer, structures);
  8313. }
  8314. printTextInternal(writer, structure) {
  8315. const hasNamedImport = structure.namedImports != null && structure.namedImports.length > 0;
  8316. if (hasNamedImport && structure.namespaceImport != null)
  8317. throw new common.errors.InvalidOperationError("An import declaration cannot have both a namespace import and a named import.");
  8318. writer.write("import");
  8319. if (structure.isTypeOnly)
  8320. writer.write(" type");
  8321. if (structure.defaultImport != null) {
  8322. writer.write(` ${structure.defaultImport}`);
  8323. writer.conditionalWrite(hasNamedImport || structure.namespaceImport != null, ",");
  8324. }
  8325. if (structure.namespaceImport != null)
  8326. writer.write(` * as ${structure.namespaceImport}`);
  8327. if (structure.namedImports != null && structure.namedImports.length > 0) {
  8328. writer.space();
  8329. this.factory.forNamedImportExportSpecifier().printTextsWithBraces(writer, structure.namedImports);
  8330. }
  8331. writer.conditionalWrite(structure.defaultImport != null || hasNamedImport || structure.namespaceImport != null, " from");
  8332. writer.write(" ");
  8333. writer.quote(structure.moduleSpecifier);
  8334. if (structure.attributes) {
  8335. writer.space();
  8336. this.factory.forImportAttribute().printAttributes(writer, structure.attributes);
  8337. }
  8338. writer.write(";");
  8339. }
  8340. }
  8341. class ModuleDeclarationStructurePrinter extends NodePrinter {
  8342. #options;
  8343. #blankLineFormattingWriter = new BlankLineFormattingStructuresPrinter(this);
  8344. constructor(factory, options) {
  8345. super(factory);
  8346. this.#options = options;
  8347. }
  8348. printTexts(writer, structures) {
  8349. this.#blankLineFormattingWriter.printText(writer, structures);
  8350. }
  8351. printTextInternal(writer, structure) {
  8352. structure = this.#validateAndGetStructure(structure);
  8353. this.factory.forJSDoc().printDocs(writer, structure.docs);
  8354. this.factory.forModifierableNode().printText(writer, structure);
  8355. if (structure.declarationKind == null || structure.declarationKind !== exports.ModuleDeclarationKind.Global)
  8356. writer.write(`${structure.declarationKind || "namespace"} ${structure.name}`);
  8357. else
  8358. writer.write("global");
  8359. if (structure.hasDeclareKeyword && common.StringUtils.isQuoted(structure.name.trim())
  8360. && structure.hasOwnProperty(common.nameof(structure, "statements")) && structure.statements == null) {
  8361. writer.write(";");
  8362. }
  8363. else {
  8364. writer.write(" ");
  8365. writer.inlineBlock(() => {
  8366. this.factory.forStatementedNode({
  8367. isAmbient: structure.hasDeclareKeyword || this.#options.isAmbient,
  8368. }).printText(writer, structure);
  8369. });
  8370. }
  8371. }
  8372. #validateAndGetStructure(structure) {
  8373. if (common.StringUtils.isQuoted(structure.name.trim())) {
  8374. if (structure.declarationKind === exports.ModuleDeclarationKind.Namespace) {
  8375. throw new common.errors.InvalidOperationError(`Cannot print a namespace with quotes for namespace with name ${structure.name}. `
  8376. + `Use ModuleDeclarationKind.Module instead.`);
  8377. }
  8378. structure = common.ObjectUtils.clone(structure);
  8379. setValueIfUndefined(structure, "hasDeclareKeyword", true);
  8380. setValueIfUndefined(structure, "declarationKind", exports.ModuleDeclarationKind.Module);
  8381. }
  8382. return structure;
  8383. }
  8384. }
  8385. class NamedImportExportSpecifierStructurePrinter extends NodePrinter {
  8386. #multipleWriter = new CommaSeparatedStructuresPrinter(this);
  8387. printTextsWithBraces(writer, structures) {
  8388. const formatSettings = this.factory.getFormatCodeSettings();
  8389. writer.write("{");
  8390. const specifierWriter = this.getNewWriter(writer);
  8391. this.printTexts(specifierWriter, structures);
  8392. const specifierText = specifierWriter.toString();
  8393. if (formatSettings.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces && !common.StringUtils.startsWithNewLine(specifierText))
  8394. writer.space();
  8395. writer.write(specifierText);
  8396. if (formatSettings.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces && !common.StringUtils.endsWithNewLine(specifierText))
  8397. writer.space();
  8398. writer.write("}");
  8399. }
  8400. printTexts(writer, structures) {
  8401. if (structures instanceof Function)
  8402. this.printText(writer, structures);
  8403. else
  8404. this.#multipleWriter.printText(writer, structures);
  8405. }
  8406. printTextInternal(writer, structure) {
  8407. const specifierWriter = this.getNewWriterWithQueuedChildIndentation(writer);
  8408. if (typeof structure === "string")
  8409. specifierWriter.write(structure);
  8410. else if (structure instanceof Function)
  8411. structure(specifierWriter);
  8412. else {
  8413. if (structure.isTypeOnly)
  8414. writer.write("type ");
  8415. specifierWriter.write(structure.name);
  8416. if (!common.StringUtils.isNullOrWhitespace(structure.alias)) {
  8417. if (!specifierWriter.isLastNewLine())
  8418. specifierWriter.space();
  8419. specifierWriter.write(`as ${structure.alias}`);
  8420. }
  8421. }
  8422. writer.write(specifierWriter.toString());
  8423. }
  8424. }
  8425. class SourceFileStructurePrinter extends NodePrinter {
  8426. #options;
  8427. constructor(factory, options) {
  8428. super(factory);
  8429. this.#options = options;
  8430. }
  8431. printTextInternal(writer, structure) {
  8432. this.factory.forStatementedNode(this.#options).printText(writer, structure);
  8433. writer.conditionalNewLine(!writer.isAtStartOfFirstLineOfBlock() && !writer.isLastNewLine());
  8434. }
  8435. }
  8436. class StatementedNodeStructurePrinter extends Printer {
  8437. #options;
  8438. #factory;
  8439. constructor(factory, options) {
  8440. super();
  8441. this.#factory = factory;
  8442. this.#options = options;
  8443. }
  8444. printText(writer, structure) {
  8445. this.#factory.forStatement(this.#options).printTexts(writer, structure.statements);
  8446. }
  8447. }
  8448. class StatementStructurePrinter extends Printer {
  8449. #options;
  8450. #factory;
  8451. constructor(factory, options) {
  8452. super();
  8453. this.#factory = factory;
  8454. this.#options = options;
  8455. }
  8456. printTexts(writer, statements) {
  8457. if (statements == null)
  8458. return;
  8459. if (typeof statements === "string" || statements instanceof Function)
  8460. this.printText(writer, statements);
  8461. else {
  8462. for (const statement of statements) {
  8463. if (isLastNonWhitespaceCharCloseBrace(writer))
  8464. writer.blankLineIfLastNot();
  8465. else if (!writer.isAtStartOfFirstLineOfBlock())
  8466. writer.newLineIfLastNot();
  8467. this.printText(writer, statement);
  8468. }
  8469. }
  8470. }
  8471. printText(writer, statement) {
  8472. if (typeof statement === "string" || statement instanceof Function || statement == null) {
  8473. this.printTextOrWriterFunc(writer, statement);
  8474. return;
  8475. }
  8476. switch (statement.kind) {
  8477. case exports.StructureKind.Function:
  8478. if (!this.#options.isAmbient)
  8479. ensureBlankLine();
  8480. this.#factory.forFunctionDeclaration(this.#options).printText(writer, statement);
  8481. break;
  8482. case exports.StructureKind.Class:
  8483. ensureBlankLine();
  8484. this.#factory.forClassDeclaration(this.#options).printText(writer, statement);
  8485. break;
  8486. case exports.StructureKind.Interface:
  8487. ensureBlankLine();
  8488. this.#factory.forInterfaceDeclaration().printText(writer, statement);
  8489. break;
  8490. case exports.StructureKind.TypeAlias:
  8491. this.#factory.forTypeAliasDeclaration().printText(writer, statement);
  8492. break;
  8493. case exports.StructureKind.VariableStatement:
  8494. this.#factory.forVariableStatement().printText(writer, statement);
  8495. break;
  8496. case exports.StructureKind.ImportDeclaration:
  8497. this.#factory.forImportDeclaration().printText(writer, statement);
  8498. break;
  8499. case exports.StructureKind.Module:
  8500. ensureBlankLine();
  8501. this.#factory.forModuleDeclaration(this.#options).printText(writer, statement);
  8502. break;
  8503. case exports.StructureKind.Enum:
  8504. ensureBlankLine();
  8505. this.#factory.forEnumDeclaration().printText(writer, statement);
  8506. break;
  8507. case exports.StructureKind.ExportDeclaration:
  8508. this.#factory.forExportDeclaration().printText(writer, statement);
  8509. break;
  8510. case exports.StructureKind.ExportAssignment:
  8511. this.#factory.forExportAssignment().printText(writer, statement);
  8512. break;
  8513. default:
  8514. common.errors.throwNotImplementedForNeverValueError(statement);
  8515. }
  8516. function ensureBlankLine() {
  8517. if (!writer.isAtStartOfFirstLineOfBlock())
  8518. writer.blankLineIfLastNot();
  8519. }
  8520. }
  8521. }
  8522. exports.VariableDeclarationKind = void 0;
  8523. (function (VariableDeclarationKind) {
  8524. VariableDeclarationKind["Var"] = "var";
  8525. VariableDeclarationKind["Let"] = "let";
  8526. VariableDeclarationKind["Const"] = "const";
  8527. VariableDeclarationKind["AwaitUsing"] = "await using";
  8528. VariableDeclarationKind["Using"] = "using";
  8529. })(exports.VariableDeclarationKind || (exports.VariableDeclarationKind = {}));
  8530. class VariableStatementStructurePrinter extends NodePrinter {
  8531. #multipleWriter = new NewLineFormattingStructuresPrinter(this);
  8532. printTexts(writer, structures) {
  8533. this.#multipleWriter.printText(writer, structures);
  8534. }
  8535. printTextInternal(writer, structure) {
  8536. this.factory.forJSDoc().printDocs(writer, structure.docs);
  8537. writer.hangingIndent(() => {
  8538. this.factory.forModifierableNode().printText(writer, structure);
  8539. writer.write(`${structure.declarationKind || exports.VariableDeclarationKind.Let} `);
  8540. this.factory.forVariableDeclaration().printTexts(writer, structure.declarations);
  8541. writer.write(";");
  8542. });
  8543. }
  8544. }
  8545. class TypeAliasDeclarationStructurePrinter extends NodePrinter {
  8546. #multipleWriter = new NewLineFormattingStructuresPrinter(this);
  8547. printTexts(writer, structures) {
  8548. this.#multipleWriter.printText(writer, structures);
  8549. }
  8550. printTextInternal(writer, structure) {
  8551. this.factory.forJSDoc().printDocs(writer, structure.docs);
  8552. this.factory.forModifierableNode().printText(writer, structure);
  8553. writer.write(`type ${structure.name}`);
  8554. this.factory.forTypeParameterDeclaration().printTextsWithBrackets(writer, structure.typeParameters);
  8555. this.factory.forTypedNode(" =").printText(writer, structure);
  8556. writer.write(";");
  8557. }
  8558. }
  8559. class TypeParameterDeclarationStructurePrinter extends NodePrinter {
  8560. #multipleWriter = new CommaSeparatedStructuresPrinter(this);
  8561. printTextsWithBrackets(writer, structures) {
  8562. if (structures == null || structures.length === 0)
  8563. return;
  8564. writer.write("<");
  8565. this.printTexts(writer, structures);
  8566. writer.write(">");
  8567. }
  8568. printTexts(writer, structures) {
  8569. this.#multipleWriter.printText(writer, structures);
  8570. }
  8571. printTextInternal(writer, structure) {
  8572. if (typeof structure === "string") {
  8573. writer.write(structure);
  8574. return;
  8575. }
  8576. writer.hangingIndent(() => {
  8577. if (structure.isConst)
  8578. writer.write("const ");
  8579. if (structure.variance != null) {
  8580. if ((structure.variance & exports.TypeParameterVariance.In) !== 0)
  8581. writer.write("in ");
  8582. if ((structure.variance & exports.TypeParameterVariance.Out) !== 0)
  8583. writer.write("out ");
  8584. }
  8585. writer.write(structure.name);
  8586. if (structure.constraint != null) {
  8587. const constraintText = this.getText(writer, structure.constraint);
  8588. if (!common.StringUtils.isNullOrWhitespace(constraintText))
  8589. writer.write(` extends ${constraintText}`);
  8590. }
  8591. if (structure.default != null) {
  8592. const defaultText = this.getText(writer, structure.default);
  8593. if (!common.StringUtils.isNullOrWhitespace(defaultText))
  8594. writer.write(` = ${defaultText}`);
  8595. }
  8596. });
  8597. }
  8598. }
  8599. class VariableDeclarationStructurePrinter extends NodePrinter {
  8600. #multipleWriter = new CommaSeparatedStructuresPrinter(this);
  8601. printTexts(writer, structures) {
  8602. this.#multipleWriter.printText(writer, structures);
  8603. }
  8604. printTextInternal(writer, structure) {
  8605. writer.write(structure.name);
  8606. writer.conditionalWrite(structure.hasExclamationToken, "!");
  8607. this.factory.forTypedNode(":").printText(writer, structure);
  8608. this.factory.forInitializerExpressionableNode().printText(writer, structure);
  8609. }
  8610. }
  8611. function ExtendsClauseableNode(Base) {
  8612. return class extends Base {
  8613. getExtends() {
  8614. const extendsClause = this.getHeritageClauseByKind(common.SyntaxKind.ExtendsKeyword);
  8615. return extendsClause?.getTypeNodes() ?? [];
  8616. }
  8617. addExtends(text) {
  8618. return this.insertExtends(this.getExtends().length, text);
  8619. }
  8620. insertExtends(index, texts) {
  8621. const originalExtends = this.getExtends();
  8622. const wasStringInput = typeof texts === "string";
  8623. if (typeof texts === "string") {
  8624. common.errors.throwIfWhitespaceOrNotString(texts, "texts");
  8625. texts = [texts];
  8626. }
  8627. else if (texts.length === 0) {
  8628. return [];
  8629. }
  8630. const writer = this._getWriterWithQueuedChildIndentation();
  8631. const structurePrinter = new CommaSeparatedStructuresPrinter(new StringStructurePrinter());
  8632. structurePrinter.printText(writer, texts);
  8633. index = verifyAndGetIndex(index, originalExtends.length);
  8634. if (originalExtends.length > 0) {
  8635. const extendsClause = this.getHeritageClauseByKindOrThrow(common.SyntaxKind.ExtendsKeyword);
  8636. insertIntoCommaSeparatedNodes({
  8637. parent: extendsClause.getFirstChildByKindOrThrow(common.SyntaxKind.SyntaxList),
  8638. currentNodes: originalExtends,
  8639. insertIndex: index,
  8640. newText: writer.toString(),
  8641. useTrailingCommas: false,
  8642. });
  8643. }
  8644. else {
  8645. const openBraceToken = this.getFirstChildByKindOrThrow(common.SyntaxKind.OpenBraceToken);
  8646. const openBraceStart = openBraceToken.getStart();
  8647. const isLastSpace = /\s/.test(this.getSourceFile().getFullText()[openBraceStart - 1]);
  8648. let insertText = `extends ${writer.toString()} `;
  8649. if (!isLastSpace)
  8650. insertText = " " + insertText;
  8651. insertIntoParentTextRange({
  8652. parent: this,
  8653. insertPos: openBraceStart,
  8654. newText: insertText,
  8655. });
  8656. }
  8657. const newExtends = this.getExtends();
  8658. return wasStringInput ? newExtends[index] : getNodesToReturn(originalExtends, newExtends, index, false);
  8659. }
  8660. removeExtends(implementsNodeOrIndex) {
  8661. const extendsClause = this.getHeritageClauseByKind(common.SyntaxKind.ExtendsKeyword);
  8662. if (extendsClause == null)
  8663. throw new common.errors.InvalidOperationError("Cannot remove an extends when none exist.");
  8664. extendsClause.removeExpression(implementsNodeOrIndex);
  8665. return this;
  8666. }
  8667. set(structure) {
  8668. callBaseSet(Base.prototype, this, structure);
  8669. if (structure.extends != null) {
  8670. this.getExtends().forEach(e => this.removeExtends(e));
  8671. this.addExtends(structure.extends);
  8672. }
  8673. return this;
  8674. }
  8675. getStructure() {
  8676. return callBaseGetStructure(Base.prototype, this, {
  8677. extends: this.getExtends().map(e => e.getText()),
  8678. });
  8679. }
  8680. };
  8681. }
  8682. function GeneratorableNode(Base) {
  8683. return class extends Base {
  8684. isGenerator() {
  8685. return this.compilerNode.asteriskToken != null;
  8686. }
  8687. getAsteriskToken() {
  8688. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.asteriskToken);
  8689. }
  8690. getAsteriskTokenOrThrow(message) {
  8691. return common.errors.throwIfNullOrUndefined(this.getAsteriskToken(), message ?? "Expected to find an asterisk token.", this);
  8692. }
  8693. setIsGenerator(value) {
  8694. const asteriskToken = this.getAsteriskToken();
  8695. const isSet = asteriskToken != null;
  8696. if (isSet === value)
  8697. return this;
  8698. if (asteriskToken == null) {
  8699. insertIntoParentTextRange({
  8700. insertPos: getAsteriskInsertPos(this),
  8701. parent: this,
  8702. newText: "*",
  8703. });
  8704. }
  8705. else {
  8706. removeChildrenWithFormatting({
  8707. children: [asteriskToken],
  8708. getSiblingFormatting: () => FormattingKind.Space,
  8709. });
  8710. }
  8711. return this;
  8712. }
  8713. set(structure) {
  8714. callBaseSet(Base.prototype, this, structure);
  8715. if (structure.isGenerator != null)
  8716. this.setIsGenerator(structure.isGenerator);
  8717. return this;
  8718. }
  8719. getStructure() {
  8720. return callBaseGetStructure(Base.prototype, this, {
  8721. isGenerator: this.isGenerator(),
  8722. });
  8723. }
  8724. };
  8725. }
  8726. function getAsteriskInsertPos(node) {
  8727. if (node.getKind() === common.SyntaxKind.FunctionDeclaration)
  8728. return node.getFirstChildByKindOrThrow(common.SyntaxKind.FunctionKeyword).getEnd();
  8729. const namedNode = node;
  8730. if (namedNode.getName == null)
  8731. throw new common.errors.NotImplementedError("Expected a name node for a non-function declaration.");
  8732. return namedNode.getNameNode().getStart();
  8733. }
  8734. function HeritageClauseableNode(Base) {
  8735. return class extends Base {
  8736. getHeritageClauses() {
  8737. const heritageClauses = this.compilerNode.heritageClauses;
  8738. return heritageClauses?.map(c => this._getNodeFromCompilerNode(c)) ?? [];
  8739. }
  8740. getHeritageClauseByKindOrThrow(kind, message) {
  8741. return common.errors.throwIfNullOrUndefined(this.getHeritageClauseByKind(kind), message ?? (() => `Expected to have heritage clause of kind ${common.getSyntaxKindName(kind)}.`), this);
  8742. }
  8743. getHeritageClauseByKind(kind) {
  8744. return this.getHeritageClauses().find(c => c.compilerNode.token === kind);
  8745. }
  8746. };
  8747. }
  8748. function ImplementsClauseableNode(Base) {
  8749. return class extends Base {
  8750. getImplements() {
  8751. const implementsClause = this.getHeritageClauseByKind(common.SyntaxKind.ImplementsKeyword);
  8752. return implementsClause?.getTypeNodes() ?? [];
  8753. }
  8754. addImplements(text) {
  8755. return this.insertImplements(this.getImplements().length, text);
  8756. }
  8757. insertImplements(index, texts) {
  8758. const originalImplements = this.getImplements();
  8759. const wasStringInput = typeof texts === "string";
  8760. if (typeof texts === "string") {
  8761. common.errors.throwIfWhitespaceOrNotString(texts, "texts");
  8762. texts = [texts];
  8763. }
  8764. else if (texts.length === 0) {
  8765. return [];
  8766. }
  8767. const writer = this._getWriterWithQueuedChildIndentation();
  8768. const structurePrinter = new CommaSeparatedStructuresPrinter(new StringStructurePrinter());
  8769. structurePrinter.printText(writer, texts);
  8770. const heritageClauses = this.getHeritageClauses();
  8771. index = verifyAndGetIndex(index, originalImplements.length);
  8772. if (originalImplements.length > 0) {
  8773. const implementsClause = this.getHeritageClauseByKindOrThrow(common.SyntaxKind.ImplementsKeyword);
  8774. insertIntoCommaSeparatedNodes({
  8775. parent: implementsClause.getFirstChildByKindOrThrow(common.SyntaxKind.SyntaxList),
  8776. currentNodes: originalImplements,
  8777. insertIndex: index,
  8778. newText: writer.toString(),
  8779. useTrailingCommas: false,
  8780. });
  8781. }
  8782. else {
  8783. const openBraceToken = this.getFirstChildByKindOrThrow(common.SyntaxKind.OpenBraceToken);
  8784. const openBraceStart = openBraceToken.getStart();
  8785. const isLastSpace = /\s/.test(this.getSourceFile().getFullText()[openBraceStart - 1]);
  8786. let insertText = `implements ${writer.toString()} `;
  8787. if (!isLastSpace)
  8788. insertText = " " + insertText;
  8789. insertIntoParentTextRange({
  8790. parent: heritageClauses.length === 0 ? this : heritageClauses[0].getParentSyntaxListOrThrow(),
  8791. insertPos: openBraceStart,
  8792. newText: insertText,
  8793. });
  8794. }
  8795. const newImplements = this.getImplements();
  8796. return wasStringInput ? newImplements[0] : getNodesToReturn(originalImplements, newImplements, index, false);
  8797. }
  8798. removeImplements(implementsNodeOrIndex) {
  8799. const implementsClause = this.getHeritageClauseByKind(common.SyntaxKind.ImplementsKeyword);
  8800. if (implementsClause == null)
  8801. throw new common.errors.InvalidOperationError("Cannot remove an implements when none exist.");
  8802. implementsClause.removeExpression(implementsNodeOrIndex);
  8803. return this;
  8804. }
  8805. set(structure) {
  8806. callBaseSet(Base.prototype, this, structure);
  8807. if (structure.implements != null) {
  8808. this.getImplements().forEach(expr => this.removeImplements(expr));
  8809. this.addImplements(structure.implements);
  8810. }
  8811. return this;
  8812. }
  8813. getStructure() {
  8814. return callBaseGetStructure(Base.prototype, this, {
  8815. implements: this.getImplements().map(node => node.getText()),
  8816. });
  8817. }
  8818. };
  8819. }
  8820. function InitializerExpressionGetableNode(Base) {
  8821. return class extends Base {
  8822. hasInitializer() {
  8823. return this.compilerNode.initializer != null;
  8824. }
  8825. getInitializerIfKindOrThrow(kind, message) {
  8826. return common.errors.throwIfNullOrUndefined(this.getInitializerIfKind(kind), message ?? `Expected to find an initializer of kind '${common.getSyntaxKindName(kind)}'.`, this);
  8827. }
  8828. getInitializerIfKind(kind) {
  8829. const initializer = this.getInitializer();
  8830. if (initializer != null && initializer.getKind() !== kind)
  8831. return undefined;
  8832. return initializer;
  8833. }
  8834. getInitializerOrThrow(message) {
  8835. return common.errors.throwIfNullOrUndefined(this.getInitializer(), message ?? "Expected to find an initializer.", this);
  8836. }
  8837. getInitializer() {
  8838. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.initializer);
  8839. }
  8840. };
  8841. }
  8842. function InitializerExpressionableNode(Base) {
  8843. return apply(InitializerExpressionGetableNode(Base));
  8844. }
  8845. function apply(Base) {
  8846. return class extends Base {
  8847. removeInitializer() {
  8848. const initializer = this.getInitializer();
  8849. if (initializer == null)
  8850. return this;
  8851. const previousSibling = initializer.getPreviousSiblingIfKindOrThrow(common.SyntaxKind.EqualsToken);
  8852. removeChildren({
  8853. children: [previousSibling, initializer],
  8854. removePrecedingSpaces: true,
  8855. });
  8856. return this;
  8857. }
  8858. setInitializer(textOrWriterFunction) {
  8859. const text = getTextFromStringOrWriter(this._getWriterWithQueuedChildIndentation(), textOrWriterFunction);
  8860. common.errors.throwIfWhitespaceOrNotString(text, "textOrWriterFunction");
  8861. if (this.hasInitializer())
  8862. this.removeInitializer();
  8863. const semiColonToken = this.getLastChildIfKind(common.SyntaxKind.SemicolonToken);
  8864. insertIntoParentTextRange({
  8865. insertPos: semiColonToken != null ? semiColonToken.getPos() : this.getEnd(),
  8866. parent: this,
  8867. newText: ` = ${text}`,
  8868. });
  8869. return this;
  8870. }
  8871. set(structure) {
  8872. callBaseSet(Base.prototype, this, structure);
  8873. if (structure.initializer != null)
  8874. this.setInitializer(structure.initializer);
  8875. else if (structure.hasOwnProperty(common.nameof(structure, "initializer")))
  8876. this.removeInitializer();
  8877. return this;
  8878. }
  8879. getStructure() {
  8880. const initializer = this.getInitializer();
  8881. return callBaseGetStructure(Base.prototype, this, {
  8882. initializer: initializer ? initializer.getText() : undefined,
  8883. });
  8884. }
  8885. };
  8886. }
  8887. function JSDocableNode(Base) {
  8888. return class extends Base {
  8889. getJsDocs() {
  8890. const nodes = this.compilerNode.jsDoc;
  8891. return nodes?.map(n => this._getNodeFromCompilerNode(n)) ?? [];
  8892. }
  8893. addJsDoc(structure) {
  8894. return this.addJsDocs([structure])[0];
  8895. }
  8896. addJsDocs(structures) {
  8897. return this.insertJsDocs(getEndIndexFromArray(this.compilerNode.jsDoc), structures);
  8898. }
  8899. insertJsDoc(index, structure) {
  8900. return this.insertJsDocs(index, [structure])[0];
  8901. }
  8902. insertJsDocs(index, structures) {
  8903. if (common.ArrayUtils.isNullOrEmpty(structures))
  8904. return [];
  8905. const writer = this._getWriterWithQueuedIndentation();
  8906. const structurePrinter = this._context.structurePrinterFactory.forJSDoc();
  8907. structurePrinter.printDocs(writer, structures);
  8908. writer.write("");
  8909. const code = writer.toString();
  8910. const nodes = this.getJsDocs();
  8911. index = verifyAndGetIndex(index, nodes.length);
  8912. const insertPos = index === nodes.length ? this.getStart() : nodes[index].getStart();
  8913. insertIntoParentTextRange({
  8914. insertPos,
  8915. parent: this,
  8916. newText: code,
  8917. });
  8918. return getNodesToReturn(nodes, this.getJsDocs(), index, false);
  8919. }
  8920. set(structure) {
  8921. callBaseSet(Base.prototype, this, structure);
  8922. if (structure.docs != null) {
  8923. this.getJsDocs().forEach(doc => doc.remove());
  8924. this.addJsDocs(structure.docs);
  8925. }
  8926. return this;
  8927. }
  8928. getStructure() {
  8929. return callBaseGetStructure(Base.prototype, this, {
  8930. docs: this.getJsDocs().map(jsdoc => jsdoc.getStructure()),
  8931. });
  8932. }
  8933. };
  8934. }
  8935. function LiteralLikeNode(Base) {
  8936. return class extends Base {
  8937. getLiteralText() {
  8938. return this.compilerNode.text;
  8939. }
  8940. isTerminated() {
  8941. return !(this.compilerNode.isUnterminated || false);
  8942. }
  8943. hasExtendedUnicodeEscape() {
  8944. return this.compilerNode.hasExtendedUnicodeEscape || false;
  8945. }
  8946. };
  8947. }
  8948. function ModifierableNode(Base) {
  8949. return class extends Base {
  8950. getModifiers() {
  8951. return this.getCompilerModifiers().map(m => this._getNodeFromCompilerNode(m));
  8952. }
  8953. getFirstModifierByKindOrThrow(kind, message) {
  8954. return common.errors.throwIfNullOrUndefined(this.getFirstModifierByKind(kind), message ?? (() => `Expected a modifier of syntax kind: ${common.getSyntaxKindName(kind)}`), this);
  8955. }
  8956. getFirstModifierByKind(kind) {
  8957. for (const modifier of this.getCompilerModifiers()) {
  8958. if (modifier.kind === kind)
  8959. return this._getNodeFromCompilerNode(modifier);
  8960. }
  8961. return undefined;
  8962. }
  8963. hasModifier(textOrKind) {
  8964. if (typeof textOrKind === "string")
  8965. return this.getModifiers().some(m => m.getText() === textOrKind);
  8966. else
  8967. return this.getCompilerModifiers().some(m => m.kind === textOrKind);
  8968. }
  8969. toggleModifier(text, value) {
  8970. if (value == null)
  8971. value = !this.hasModifier(text);
  8972. if (value)
  8973. this.addModifier(text);
  8974. else
  8975. this.removeModifier(text);
  8976. return this;
  8977. }
  8978. addModifier(text) {
  8979. const rawModifiers = this.getModifiers();
  8980. const modifiers = this.getModifiers().filter(m => m.getKind() !== common.SyntaxKind.Decorator);
  8981. const existingModifier = modifiers.find(m => m.getText() === text);
  8982. if (existingModifier != null)
  8983. return existingModifier;
  8984. const insertPos = getInsertPos(this);
  8985. let startPos;
  8986. let newText;
  8987. const isFirstModifier = modifiers.length === 0 || insertPos === modifiers[0].getStart();
  8988. if (isFirstModifier) {
  8989. newText = text + " ";
  8990. startPos = insertPos;
  8991. }
  8992. else {
  8993. newText = " " + text;
  8994. startPos = insertPos + 1;
  8995. }
  8996. insertIntoParentTextRange({
  8997. parent: rawModifiers.length === 0 ? this : rawModifiers[0].getParentSyntaxListOrThrow(),
  8998. insertPos,
  8999. newText,
  9000. });
  9001. return this.getModifiers().find(m => m.getStart() === startPos);
  9002. function getInsertPos(node) {
  9003. let pos = getInitialInsertPos();
  9004. for (const addAfterText of getAddAfterModifierTexts(text)) {
  9005. for (let i = 0; i < modifiers.length; i++) {
  9006. const modifier = modifiers[i];
  9007. if (modifier.getText() === addAfterText) {
  9008. if (pos < modifier.getEnd())
  9009. pos = modifier.getEnd();
  9010. break;
  9011. }
  9012. }
  9013. }
  9014. return pos;
  9015. function getInitialInsertPos() {
  9016. if (modifiers.length > 0)
  9017. return modifiers[0].getStart();
  9018. for (const child of node._getChildrenIterator()) {
  9019. if (child.getKind() === common.SyntaxKind.SyntaxList || common.ts.isJSDocCommentContainingNode(child.compilerNode))
  9020. continue;
  9021. return child.getStart();
  9022. }
  9023. return node.getStart();
  9024. }
  9025. }
  9026. }
  9027. removeModifier(text) {
  9028. const modifiers = this.getModifiers();
  9029. const modifier = modifiers.find(m => m.getText() === text);
  9030. if (modifier == null)
  9031. return false;
  9032. removeChildren({
  9033. children: [modifiers.length === 1 ? modifier.getParentSyntaxListOrThrow() : modifier],
  9034. removeFollowingSpaces: true,
  9035. });
  9036. return true;
  9037. }
  9038. getCompilerModifiers() {
  9039. return this.compilerNode.modifiers ?? [];
  9040. }
  9041. };
  9042. }
  9043. function getAddAfterModifierTexts(text) {
  9044. switch (text) {
  9045. case "export":
  9046. return [];
  9047. case "public":
  9048. case "protected":
  9049. case "private":
  9050. return [];
  9051. case "default":
  9052. return ["export"];
  9053. case "const":
  9054. return ["export"];
  9055. case "declare":
  9056. return ["export", "default"];
  9057. case "static":
  9058. return ["public", "protected", "private"];
  9059. case "override":
  9060. return ["public", "private", "protected", "static"];
  9061. case "abstract":
  9062. return ["export", "default", "declare", "public", "private", "protected", "static", "override"];
  9063. case "async":
  9064. return ["export", "default", "declare", "public", "private", "protected", "static", "override", "abstract"];
  9065. case "readonly":
  9066. return ["export", "default", "declare", "public", "private", "protected", "static", "override", "abstract"];
  9067. case "out":
  9068. return ["const", "in"];
  9069. case "in":
  9070. return ["const"];
  9071. case "accessor":
  9072. return ["public", "private", "protected", "declare", "override", "static", "abstract", "readonly"];
  9073. default:
  9074. common.errors.throwNotImplementedForNeverValueError(text);
  9075. }
  9076. }
  9077. function ModuledNode(Base) {
  9078. return class extends Base {
  9079. addImportDeclaration(structure) {
  9080. return this.addImportDeclarations([structure])[0];
  9081. }
  9082. addImportDeclarations(structures) {
  9083. const compilerChildren = this._getCompilerStatementsWithComments();
  9084. return this.insertImportDeclarations(getInsertIndex(), structures);
  9085. function getInsertIndex() {
  9086. let insertIndex = 0;
  9087. let wasLastComment = true;
  9088. for (let i = 0; i < compilerChildren.length; i++) {
  9089. const child = compilerChildren[i];
  9090. if (wasLastComment && child.kind === common.SyntaxKind.MultiLineCommentTrivia)
  9091. insertIndex = i + 1;
  9092. else {
  9093. wasLastComment = false;
  9094. if (child.kind === common.SyntaxKind.ImportDeclaration)
  9095. insertIndex = i + 1;
  9096. }
  9097. }
  9098. return insertIndex;
  9099. }
  9100. }
  9101. insertImportDeclaration(index, structure) {
  9102. return this.insertImportDeclarations(index, [structure])[0];
  9103. }
  9104. insertImportDeclarations(index, structures) {
  9105. return this._insertChildren({
  9106. expectedKind: common.SyntaxKind.ImportDeclaration,
  9107. index,
  9108. structures,
  9109. write: (writer, info) => {
  9110. this._standardWrite(writer, info, () => {
  9111. this._context.structurePrinterFactory.forImportDeclaration().printTexts(writer, structures);
  9112. }, {
  9113. previousNewLine: previousMember => Node.isImportDeclaration(previousMember) || isComment(previousMember.compilerNode),
  9114. nextNewLine: nextMember => Node.isImportDeclaration(nextMember),
  9115. });
  9116. },
  9117. });
  9118. }
  9119. getImportDeclaration(conditionOrModuleSpecifier) {
  9120. return this.getImportDeclarations().find(getCondition());
  9121. function getCondition() {
  9122. if (typeof conditionOrModuleSpecifier === "string")
  9123. return (dec) => dec.getModuleSpecifierValue() === conditionOrModuleSpecifier;
  9124. else
  9125. return conditionOrModuleSpecifier;
  9126. }
  9127. }
  9128. getImportDeclarationOrThrow(conditionOrModuleSpecifier, message) {
  9129. return common.errors.throwIfNullOrUndefined(this.getImportDeclaration(conditionOrModuleSpecifier), message ?? "Expected to find an import with the provided condition.", this);
  9130. }
  9131. getImportDeclarations() {
  9132. return this.getStatements().filter(Node.isImportDeclaration);
  9133. }
  9134. addExportDeclaration(structure) {
  9135. return this.addExportDeclarations([structure])[0];
  9136. }
  9137. addExportDeclarations(structures) {
  9138. return this.insertExportDeclarations(this.getChildSyntaxListOrThrow().getChildCount(), structures);
  9139. }
  9140. insertExportDeclaration(index, structure) {
  9141. return this.insertExportDeclarations(index, [structure])[0];
  9142. }
  9143. insertExportDeclarations(index, structures) {
  9144. return this._insertChildren({
  9145. expectedKind: common.SyntaxKind.ExportDeclaration,
  9146. index,
  9147. structures,
  9148. write: (writer, info) => {
  9149. this._standardWrite(writer, info, () => {
  9150. this._context.structurePrinterFactory.forExportDeclaration().printTexts(writer, structures);
  9151. }, {
  9152. previousNewLine: previousMember => Node.isExportDeclaration(previousMember) || isComment(previousMember.compilerNode),
  9153. nextNewLine: nextMember => Node.isExportDeclaration(nextMember),
  9154. });
  9155. },
  9156. });
  9157. }
  9158. getExportDeclaration(conditionOrModuleSpecifier) {
  9159. return this.getExportDeclarations().find(getCondition());
  9160. function getCondition() {
  9161. if (typeof conditionOrModuleSpecifier === "string")
  9162. return (dec) => dec.getModuleSpecifierValue() === conditionOrModuleSpecifier;
  9163. else
  9164. return conditionOrModuleSpecifier;
  9165. }
  9166. }
  9167. getExportDeclarationOrThrow(conditionOrModuleSpecifier, message) {
  9168. return common.errors.throwIfNullOrUndefined(this.getExportDeclaration(conditionOrModuleSpecifier), message ?? "Expected to find an export declaration with the provided condition.", this);
  9169. }
  9170. getExportDeclarations() {
  9171. return this.getStatements().filter(Node.isExportDeclaration);
  9172. }
  9173. addExportAssignment(structure) {
  9174. return this.addExportAssignments([structure])[0];
  9175. }
  9176. addExportAssignments(structures) {
  9177. return this.insertExportAssignments(this.getChildSyntaxListOrThrow().getChildCount(), structures);
  9178. }
  9179. insertExportAssignment(index, structure) {
  9180. return this.insertExportAssignments(index, [structure])[0];
  9181. }
  9182. insertExportAssignments(index, structures) {
  9183. return this._insertChildren({
  9184. expectedKind: common.SyntaxKind.ExportAssignment,
  9185. index,
  9186. structures,
  9187. write: (writer, info) => {
  9188. this._standardWrite(writer, info, () => {
  9189. this._context.structurePrinterFactory.forExportAssignment().printTexts(writer, structures);
  9190. }, {
  9191. previousNewLine: previousMember => Node.isExportAssignment(previousMember) || isComment(previousMember.compilerNode),
  9192. nextNewLine: nextMember => Node.isExportAssignment(nextMember),
  9193. });
  9194. },
  9195. });
  9196. }
  9197. getExportAssignment(condition) {
  9198. return this.getExportAssignments().find(condition);
  9199. }
  9200. getExportAssignmentOrThrow(condition, message) {
  9201. return common.errors.throwIfNullOrUndefined(this.getExportAssignment(condition), message ?? "Expected to find an export assignment with the provided condition.", this);
  9202. }
  9203. getExportAssignments() {
  9204. return this.getStatements().filter(Node.isExportAssignment);
  9205. }
  9206. getDefaultExportSymbol() {
  9207. const sourceFileSymbol = this.getSymbol();
  9208. if (sourceFileSymbol == null)
  9209. return undefined;
  9210. return sourceFileSymbol.getExport("default");
  9211. }
  9212. getDefaultExportSymbolOrThrow(message) {
  9213. return common.errors.throwIfNullOrUndefined(this.getDefaultExportSymbol(), message ?? "Expected to find a default export symbol");
  9214. }
  9215. getExportSymbols() {
  9216. const symbol = this.getSymbol();
  9217. return symbol == null ? [] : this._context.typeChecker.getExportsOfModule(symbol);
  9218. }
  9219. getExportedDeclarations() {
  9220. const result = new Map();
  9221. const exportSymbols = this.getExportSymbols();
  9222. for (const symbol of exportSymbols) {
  9223. for (const declaration of symbol.getDeclarations()) {
  9224. const declarations = Array.from(getDeclarationHandlingImportsAndExports(declaration));
  9225. const name = symbol.getName();
  9226. const existingArray = result.get(name);
  9227. if (existingArray != null)
  9228. existingArray.push(...declarations);
  9229. else
  9230. result.set(symbol.getName(), declarations);
  9231. }
  9232. }
  9233. return result;
  9234. function* getDeclarationHandlingImportsAndExports(declaration) {
  9235. if (Node.isExportSpecifier(declaration)) {
  9236. for (const d of declaration.getLocalTargetDeclarations())
  9237. yield* getDeclarationHandlingImportsAndExports(d);
  9238. }
  9239. else if (Node.isExportAssignment(declaration)) {
  9240. const expression = declaration.getExpression();
  9241. if (expression == null || expression.getKind() !== common.SyntaxKind.Identifier) {
  9242. yield expression;
  9243. return;
  9244. }
  9245. yield* getDeclarationsForSymbol(expression.getSymbol());
  9246. }
  9247. else if (Node.isImportSpecifier(declaration)) {
  9248. const identifier = declaration.getNameNode();
  9249. const symbol = identifier.getSymbol();
  9250. if (symbol == null)
  9251. return;
  9252. yield* getDeclarationsForSymbol(symbol.getAliasedSymbol() || symbol);
  9253. }
  9254. else if (Node.isImportClause(declaration)) {
  9255. const identifier = declaration.getDefaultImport();
  9256. if (identifier == null)
  9257. return;
  9258. const symbol = identifier.getSymbol();
  9259. if (symbol == null)
  9260. return;
  9261. yield* getDeclarationsForSymbol(symbol.getAliasedSymbol() || symbol);
  9262. }
  9263. else if (Node.isNamespaceImport(declaration) || Node.isNamespaceExport(declaration)) {
  9264. const symbol = declaration.getNameNode().getSymbol();
  9265. if (symbol == null)
  9266. return;
  9267. yield* getDeclarationsForSymbol(symbol.getAliasedSymbol() || symbol);
  9268. }
  9269. else {
  9270. yield declaration;
  9271. }
  9272. function* getDeclarationsForSymbol(symbol) {
  9273. if (symbol == null)
  9274. return;
  9275. for (const d of symbol.getDeclarations())
  9276. yield* getDeclarationHandlingImportsAndExports(d);
  9277. }
  9278. }
  9279. }
  9280. removeDefaultExport(defaultExportSymbol) {
  9281. defaultExportSymbol = defaultExportSymbol || this.getDefaultExportSymbol();
  9282. if (defaultExportSymbol == null)
  9283. return this;
  9284. const declaration = defaultExportSymbol.getDeclarations()[0];
  9285. if (declaration.compilerNode.kind === common.SyntaxKind.ExportAssignment)
  9286. removeChildrenWithFormatting({ children: [declaration], getSiblingFormatting: () => FormattingKind.Newline });
  9287. else if (Node.isModifierable(declaration)) {
  9288. declaration.toggleModifier("default", false);
  9289. declaration.toggleModifier("export", false);
  9290. }
  9291. return this;
  9292. }
  9293. };
  9294. }
  9295. function NamedNodeBase(Base) {
  9296. return class extends Base {
  9297. getNameNode() {
  9298. return this._getNodeFromCompilerNode(this.compilerNode.name);
  9299. }
  9300. getName() {
  9301. return this.getNameNode().getText();
  9302. }
  9303. set(structure) {
  9304. callBaseSet(Base.prototype, this, structure);
  9305. if (structure.name != null)
  9306. this.getNameNode().replaceWithText(structure.name);
  9307. return this;
  9308. }
  9309. getStructure() {
  9310. return callBaseGetStructure(Base.prototype, this, {
  9311. name: this.getName(),
  9312. });
  9313. }
  9314. };
  9315. }
  9316. function ReferenceFindableNode(Base) {
  9317. return class extends Base {
  9318. findReferences() {
  9319. return this._context.languageService.findReferences(getNodeForReferences(this));
  9320. }
  9321. findReferencesAsNodes() {
  9322. return this._context.languageService.findReferencesAsNodes(getNodeForReferences(this));
  9323. }
  9324. };
  9325. }
  9326. function getNodeForReferences(node) {
  9327. if (Node.isIdentifier(node) || Node.isStringLiteral(node))
  9328. return node;
  9329. const nameNode = node.getNodeProperty("name");
  9330. if (nameNode != null)
  9331. return nameNode;
  9332. if (Node.isExportable(node))
  9333. return node.getDefaultKeyword() || node;
  9334. return node;
  9335. }
  9336. function RenameableNode(Base) {
  9337. return class extends Base {
  9338. rename(newName, options) {
  9339. renameNode(getNodeToRename(this), newName, options);
  9340. return this;
  9341. function getNodeToRename(thisNode) {
  9342. if (Node.isIdentifier(thisNode) || Node.isPrivateIdentifier(thisNode) || Node.isStringLiteral(thisNode))
  9343. return thisNode;
  9344. else if (thisNode.getNameNode != null) {
  9345. const node = thisNode.getNameNode();
  9346. common.errors.throwIfNullOrUndefined(node, "Expected to find a name node when renaming.");
  9347. if (Node.isArrayBindingPattern(node) || Node.isObjectBindingPattern(node))
  9348. throw new common.errors.NotImplementedError(`Not implemented renameable scenario for ${node.getKindName()}.`);
  9349. return node;
  9350. }
  9351. else {
  9352. throw new common.errors.NotImplementedError(`Not implemented renameable scenario for ${thisNode.getKindName()}`);
  9353. }
  9354. }
  9355. }
  9356. };
  9357. }
  9358. function BindingNamedNode(Base) {
  9359. const base = ReferenceFindableNode(RenameableNode(Base));
  9360. return NamedNodeBase(base);
  9361. }
  9362. function ImportAttributeNamedNode(Base) {
  9363. const base = ReferenceFindableNode(RenameableNode(Base));
  9364. return NamedNodeBase(base);
  9365. }
  9366. function ModuleNamedNode(Base) {
  9367. const base = ReferenceFindableNode(RenameableNode(Base));
  9368. return NamedNodeBase(base);
  9369. }
  9370. function NameableNode(Base) {
  9371. return NameableNodeInternal(ReferenceFindableNode(RenameableNode(Base)));
  9372. }
  9373. function NameableNodeInternal(Base) {
  9374. return class extends Base {
  9375. getNameNode() {
  9376. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.name);
  9377. }
  9378. getNameNodeOrThrow(message) {
  9379. return common.errors.throwIfNullOrUndefined(this.getNameNode(), message ?? "Expected to have a name node.", this);
  9380. }
  9381. getName() {
  9382. return this.getNameNode()?.getText() ?? undefined;
  9383. }
  9384. getNameOrThrow(message) {
  9385. return common.errors.throwIfNullOrUndefined(this.getName(), message ?? "Expected to have a name.", this);
  9386. }
  9387. rename(newName) {
  9388. if (newName === this.getName())
  9389. return this;
  9390. if (common.StringUtils.isNullOrWhitespace(newName)) {
  9391. this.removeName();
  9392. return this;
  9393. }
  9394. const nameNode = this.getNameNode();
  9395. if (nameNode == null)
  9396. addNameNode(this, newName);
  9397. else
  9398. Base.prototype.rename.call(this, newName);
  9399. return this;
  9400. }
  9401. removeName() {
  9402. const nameNode = this.getNameNode();
  9403. if (nameNode == null)
  9404. return this;
  9405. removeChildren({ children: [nameNode], removePrecedingSpaces: true });
  9406. return this;
  9407. }
  9408. set(structure) {
  9409. callBaseSet(Base.prototype, this, structure);
  9410. if (structure.name != null) {
  9411. common.errors.throwIfWhitespaceOrNotString(structure.name, "structure.name");
  9412. const nameNode = this.getNameNode();
  9413. if (nameNode == null)
  9414. addNameNode(this, structure.name);
  9415. else
  9416. nameNode.replaceWithText(structure.name);
  9417. }
  9418. else if (structure.hasOwnProperty(common.nameof(structure, "name"))) {
  9419. this.removeName();
  9420. }
  9421. return this;
  9422. }
  9423. getStructure() {
  9424. return callBaseGetStructure(Base.prototype, this, {
  9425. name: this.getName(),
  9426. });
  9427. }
  9428. };
  9429. }
  9430. function addNameNode(node, newName) {
  9431. if (Node.isClassDeclaration(node) || Node.isClassExpression(node)) {
  9432. const classKeyword = node.getFirstChildByKindOrThrow(common.SyntaxKind.ClassKeyword);
  9433. insertIntoParentTextRange({
  9434. insertPos: classKeyword.getEnd(),
  9435. newText: " " + newName,
  9436. parent: node,
  9437. });
  9438. }
  9439. else {
  9440. const openParenToken = node.getFirstChildByKindOrThrow(common.SyntaxKind.OpenParenToken);
  9441. insertIntoParentTextRange({
  9442. insertPos: openParenToken.getStart(),
  9443. newText: " " + newName,
  9444. parent: node,
  9445. });
  9446. }
  9447. }
  9448. function NamedNode(Base) {
  9449. const base = RenameableNode(ReferenceFindableNode(Base));
  9450. return NamedNodeBase(base);
  9451. }
  9452. function PropertyNamedNode(Base) {
  9453. const base = ReferenceFindableNode(RenameableNode(Base));
  9454. return NamedNodeBase(base);
  9455. }
  9456. function OverrideableNode(Base) {
  9457. return class extends Base {
  9458. hasOverrideKeyword() {
  9459. return this.hasModifier(common.SyntaxKind.OverrideKeyword);
  9460. }
  9461. getOverrideKeyword() {
  9462. return this.getFirstModifierByKind(common.SyntaxKind.OverrideKeyword);
  9463. }
  9464. getOverrideKeywordOrThrow(message) {
  9465. return common.errors.throwIfNullOrUndefined(this.getOverrideKeyword(), message ?? "Expected to find an override keyword.", this);
  9466. }
  9467. setHasOverrideKeyword(value) {
  9468. this.toggleModifier("override", value);
  9469. return this;
  9470. }
  9471. set(structure) {
  9472. callBaseSet(Base.prototype, this, structure);
  9473. if (structure.hasOverrideKeyword != null)
  9474. this.setHasOverrideKeyword(structure.hasOverrideKeyword);
  9475. return this;
  9476. }
  9477. getStructure() {
  9478. return callBaseGetStructure(Base.prototype, this, {
  9479. hasOverrideKeyword: this.hasOverrideKeyword(),
  9480. });
  9481. }
  9482. };
  9483. }
  9484. function ParameteredNode(Base) {
  9485. return class extends Base {
  9486. getParameter(nameOrFindFunction) {
  9487. return getNodeByNameOrFindFunction(this.getParameters(), nameOrFindFunction);
  9488. }
  9489. getParameterOrThrow(nameOrFindFunction) {
  9490. return common.errors.throwIfNullOrUndefined(this.getParameter(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("parameter", nameOrFindFunction));
  9491. }
  9492. getParameters() {
  9493. return this.compilerNode.parameters.map(p => this._getNodeFromCompilerNode(p));
  9494. }
  9495. addParameter(structure) {
  9496. return this.addParameters([structure])[0];
  9497. }
  9498. addParameters(structures) {
  9499. return this.insertParameters(getEndIndexFromArray(this.compilerNode.parameters), structures);
  9500. }
  9501. insertParameter(index, structure) {
  9502. return this.insertParameters(index, [structure])[0];
  9503. }
  9504. insertParameters(index, structures) {
  9505. if (common.ArrayUtils.isNullOrEmpty(structures))
  9506. return [];
  9507. const parameters = this.getParameters();
  9508. const syntaxList = this.getFirstChildByKindOrThrow(common.SyntaxKind.OpenParenToken).getNextSiblingIfKindOrThrow(common.SyntaxKind.SyntaxList);
  9509. index = verifyAndGetIndex(index, parameters.length);
  9510. const writer = this._getWriterWithQueuedChildIndentation();
  9511. const structurePrinter = this._context.structurePrinterFactory.forParameterDeclaration();
  9512. structurePrinter.printTexts(writer, structures);
  9513. insertIntoCommaSeparatedNodes({
  9514. parent: syntaxList,
  9515. currentNodes: parameters,
  9516. insertIndex: index,
  9517. newText: writer.toString(),
  9518. useTrailingCommas: false,
  9519. });
  9520. return getNodesToReturn(parameters, this.getParameters(), index, false);
  9521. }
  9522. set(structure) {
  9523. callBaseSet(Base.prototype, this, structure);
  9524. if (structure.parameters != null) {
  9525. this.getParameters().forEach(p => p.remove());
  9526. this.addParameters(structure.parameters);
  9527. }
  9528. return this;
  9529. }
  9530. getStructure() {
  9531. return callBaseGetStructure(Base.prototype, this, {
  9532. parameters: this.getParameters().map(p => p.getStructure()),
  9533. });
  9534. }
  9535. };
  9536. }
  9537. function QuestionDotTokenableNode(Base) {
  9538. return class extends Base {
  9539. hasQuestionDotToken() {
  9540. return this.compilerNode.questionDotToken != null;
  9541. }
  9542. getQuestionDotTokenNode() {
  9543. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.questionDotToken);
  9544. }
  9545. getQuestionDotTokenNodeOrThrow(message) {
  9546. return common.errors.throwIfNullOrUndefined(this.getQuestionDotTokenNode(), message ?? "Expected to find a question dot token.", this);
  9547. }
  9548. setHasQuestionDotToken(value) {
  9549. const questionDotTokenNode = this.getQuestionDotTokenNode();
  9550. const hasQuestionDotToken = questionDotTokenNode != null;
  9551. if (value === hasQuestionDotToken)
  9552. return this;
  9553. if (value) {
  9554. if (Node.isPropertyAccessExpression(this))
  9555. this.getFirstChildByKindOrThrow(common.SyntaxKind.DotToken).replaceWithText("?.");
  9556. else {
  9557. insertIntoParentTextRange({
  9558. insertPos: getInsertPos.call(this),
  9559. parent: this,
  9560. newText: "?.",
  9561. });
  9562. }
  9563. }
  9564. else {
  9565. if (Node.isPropertyAccessExpression(this))
  9566. questionDotTokenNode.replaceWithText(".");
  9567. else
  9568. removeChildren({ children: [questionDotTokenNode] });
  9569. }
  9570. return this;
  9571. function getInsertPos() {
  9572. if (Node.isCallExpression(this))
  9573. return this.getFirstChildByKindOrThrow(common.SyntaxKind.OpenParenToken).getStart();
  9574. if (Node.isElementAccessExpression(this))
  9575. return this.getFirstChildByKindOrThrow(common.SyntaxKind.OpenBracketToken).getStart();
  9576. common.errors.throwNotImplementedForSyntaxKindError(this.compilerNode.kind);
  9577. }
  9578. }
  9579. set(structure) {
  9580. callBaseSet(Base.prototype, this, structure);
  9581. if (structure.hasQuestionDotToken != null)
  9582. this.setHasQuestionDotToken(structure.hasQuestionDotToken);
  9583. return this;
  9584. }
  9585. getStructure() {
  9586. return callBaseGetStructure(Base.prototype, this, {
  9587. hasQuestionDotToken: this.hasQuestionDotToken(),
  9588. });
  9589. }
  9590. };
  9591. }
  9592. function QuestionTokenableNode(Base) {
  9593. return class extends Base {
  9594. hasQuestionToken() {
  9595. return this.compilerNode.questionToken != null;
  9596. }
  9597. getQuestionTokenNode() {
  9598. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.questionToken);
  9599. }
  9600. getQuestionTokenNodeOrThrow(message) {
  9601. return common.errors.throwIfNullOrUndefined(this.getQuestionTokenNode(), message ?? "Expected to find a question token.", this);
  9602. }
  9603. setHasQuestionToken(value) {
  9604. const questionTokenNode = this.getQuestionTokenNode();
  9605. const hasQuestionToken = questionTokenNode != null;
  9606. if (value === hasQuestionToken)
  9607. return this;
  9608. if (value) {
  9609. if (Node.isExclamationTokenable(this))
  9610. this.setHasExclamationToken(false);
  9611. insertIntoParentTextRange({
  9612. insertPos: getInsertPos.call(this),
  9613. parent: this,
  9614. newText: "?",
  9615. });
  9616. }
  9617. else {
  9618. removeChildren({ children: [questionTokenNode] });
  9619. }
  9620. return this;
  9621. function getInsertPos() {
  9622. if (Node.hasName(this))
  9623. return this.getNameNode().getEnd();
  9624. const colonNode = this.getFirstChildByKind(common.SyntaxKind.ColonToken);
  9625. if (colonNode != null)
  9626. return colonNode.getStart();
  9627. const semicolonToken = this.getLastChildByKind(common.SyntaxKind.SemicolonToken);
  9628. if (semicolonToken != null)
  9629. return semicolonToken.getStart();
  9630. return this.getEnd();
  9631. }
  9632. }
  9633. set(structure) {
  9634. callBaseSet(Base.prototype, this, structure);
  9635. if (structure.hasQuestionToken != null)
  9636. this.setHasQuestionToken(structure.hasQuestionToken);
  9637. return this;
  9638. }
  9639. getStructure() {
  9640. return callBaseGetStructure(Base.prototype, this, {
  9641. hasQuestionToken: this.hasQuestionToken(),
  9642. });
  9643. }
  9644. };
  9645. }
  9646. function ReadonlyableNode(Base) {
  9647. return class extends Base {
  9648. isReadonly() {
  9649. return this.getReadonlyKeyword() != null;
  9650. }
  9651. getReadonlyKeyword() {
  9652. return this.getFirstModifierByKind(common.SyntaxKind.ReadonlyKeyword);
  9653. }
  9654. getReadonlyKeywordOrThrow(message) {
  9655. return common.errors.throwIfNullOrUndefined(this.getReadonlyKeyword(), message ?? "Expected to find a readonly keyword.", this);
  9656. }
  9657. setIsReadonly(value) {
  9658. this.toggleModifier("readonly", value);
  9659. return this;
  9660. }
  9661. set(structure) {
  9662. callBaseSet(Base.prototype, this, structure);
  9663. if (structure.isReadonly != null)
  9664. this.setIsReadonly(structure.isReadonly);
  9665. return this;
  9666. }
  9667. getStructure() {
  9668. return callBaseGetStructure(Base.prototype, this, {
  9669. isReadonly: this.isReadonly(),
  9670. });
  9671. }
  9672. };
  9673. }
  9674. function ReturnTypedNode(Base) {
  9675. return class extends Base {
  9676. getReturnType() {
  9677. return this.getSignature().getReturnType();
  9678. }
  9679. getReturnTypeNode() {
  9680. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.type);
  9681. }
  9682. getReturnTypeNodeOrThrow(message) {
  9683. return common.errors.throwIfNullOrUndefined(this.getReturnTypeNode(), message ?? "Expected to find a return type node.", this);
  9684. }
  9685. setReturnType(textOrWriterFunction) {
  9686. const text = getTextFromStringOrWriter(this._getWriterWithQueuedChildIndentation(), textOrWriterFunction);
  9687. if (common.StringUtils.isNullOrWhitespace(text))
  9688. return this.removeReturnType();
  9689. const returnTypeNode = this.getReturnTypeNode();
  9690. if (returnTypeNode != null) {
  9691. if (returnTypeNode.getText() !== text)
  9692. returnTypeNode.replaceWithText(text);
  9693. return this;
  9694. }
  9695. insertIntoParentTextRange({
  9696. parent: this,
  9697. insertPos: getEndNode(this).getEnd(),
  9698. newText: `: ${text}`,
  9699. });
  9700. return this;
  9701. function getEndNode(thisNode) {
  9702. if (thisNode.getKind() === common.SyntaxKind.IndexSignature)
  9703. return thisNode.getFirstChildByKindOrThrow(common.SyntaxKind.CloseBracketToken);
  9704. return thisNode.getFirstChildByKindOrThrow(common.SyntaxKind.CloseParenToken);
  9705. }
  9706. }
  9707. removeReturnType() {
  9708. const returnTypeNode = this.getReturnTypeNode();
  9709. if (returnTypeNode == null)
  9710. return this;
  9711. const colonToken = returnTypeNode.getPreviousSiblingIfKindOrThrow(common.SyntaxKind.ColonToken);
  9712. removeChildren({ children: [colonToken, returnTypeNode], removePrecedingSpaces: true });
  9713. return this;
  9714. }
  9715. getSignature() {
  9716. const signature = this._context.typeChecker.getSignatureFromNode(this);
  9717. if (signature == null)
  9718. throw new common.errors.NotImplementedError("Expected the node to have a signature.");
  9719. return signature;
  9720. }
  9721. set(structure) {
  9722. callBaseSet(Base.prototype, this, structure);
  9723. if (structure.returnType != null)
  9724. this.setReturnType(structure.returnType);
  9725. else if (structure.hasOwnProperty(common.nameof(structure, "returnType")))
  9726. this.removeReturnType();
  9727. return this;
  9728. }
  9729. getStructure() {
  9730. const returnTypeNode = this.getReturnTypeNode();
  9731. return callBaseGetStructure(Base.prototype, this, {
  9732. returnType: returnTypeNode ? returnTypeNode.getText({ trimLeadingIndentation: true }) : undefined,
  9733. });
  9734. }
  9735. };
  9736. }
  9737. function ScopeableNode(Base) {
  9738. return class extends Base {
  9739. getScope() {
  9740. const scope = getScopeForNode(this);
  9741. if (scope != null)
  9742. return scope;
  9743. if (Node.isParameterDeclaration(this) && this.isReadonly())
  9744. return exports.Scope.Public;
  9745. return undefined;
  9746. }
  9747. setScope(scope) {
  9748. setScopeForNode(this, scope);
  9749. return this;
  9750. }
  9751. getScopeKeyword() {
  9752. return this.getModifiers().find(m => {
  9753. const text = m.getText();
  9754. return text === "public" || text === "protected" || text === "private";
  9755. });
  9756. }
  9757. hasScopeKeyword() {
  9758. return this.getScopeKeyword() != null;
  9759. }
  9760. set(structure) {
  9761. callBaseSet(Base.prototype, this, structure);
  9762. if (structure.hasOwnProperty(common.nameof(structure, "scope")))
  9763. this.setScope(structure.scope);
  9764. return this;
  9765. }
  9766. getStructure() {
  9767. return callBaseGetStructure(Base.prototype, this, {
  9768. scope: this.getScope(),
  9769. });
  9770. }
  9771. };
  9772. }
  9773. function getScopeForNode(node) {
  9774. const modifierFlags = node.getCombinedModifierFlags();
  9775. if ((modifierFlags & common.ts.ModifierFlags.Private) !== 0)
  9776. return exports.Scope.Private;
  9777. else if ((modifierFlags & common.ts.ModifierFlags.Protected) !== 0)
  9778. return exports.Scope.Protected;
  9779. else if ((modifierFlags & common.ts.ModifierFlags.Public) !== 0)
  9780. return exports.Scope.Public;
  9781. else
  9782. return undefined;
  9783. }
  9784. function setScopeForNode(node, scope) {
  9785. node.toggleModifier("public", scope === exports.Scope.Public);
  9786. node.toggleModifier("protected", scope === exports.Scope.Protected);
  9787. node.toggleModifier("private", scope === exports.Scope.Private);
  9788. }
  9789. function ScopedNode(Base) {
  9790. return class extends Base {
  9791. getScope() {
  9792. return getScopeForNode(this) || exports.Scope.Public;
  9793. }
  9794. setScope(scope) {
  9795. setScopeForNode(this, scope);
  9796. return this;
  9797. }
  9798. hasScopeKeyword() {
  9799. return getScopeForNode(this) != null;
  9800. }
  9801. set(structure) {
  9802. callBaseSet(Base.prototype, this, structure);
  9803. if (structure.hasOwnProperty(common.nameof(structure, "scope")))
  9804. this.setScope(structure.scope);
  9805. return this;
  9806. }
  9807. getStructure() {
  9808. return callBaseGetStructure(Base.prototype, this, {
  9809. scope: this.hasScopeKeyword() ? this.getScope() : undefined,
  9810. });
  9811. }
  9812. };
  9813. }
  9814. function SignaturedDeclaration(Base) {
  9815. return ReturnTypedNode(ParameteredNode(Base));
  9816. }
  9817. function StaticableNode(Base) {
  9818. return class extends Base {
  9819. isStatic() {
  9820. return this.hasModifier(common.SyntaxKind.StaticKeyword);
  9821. }
  9822. getStaticKeyword() {
  9823. return this.getFirstModifierByKind(common.SyntaxKind.StaticKeyword);
  9824. }
  9825. getStaticKeywordOrThrow(message) {
  9826. return common.errors.throwIfNullOrUndefined(this.getStaticKeyword(), message ?? "Expected to find a static keyword.", this);
  9827. }
  9828. setIsStatic(value) {
  9829. this.toggleModifier("static", value);
  9830. return this;
  9831. }
  9832. set(structure) {
  9833. callBaseSet(Base.prototype, this, structure);
  9834. if (structure.isStatic != null)
  9835. this.setIsStatic(structure.isStatic);
  9836. return this;
  9837. }
  9838. getStructure() {
  9839. return callBaseGetStructure(Base.prototype, this, {
  9840. isStatic: this.isStatic(),
  9841. });
  9842. }
  9843. };
  9844. }
  9845. function TextInsertableNode(Base) {
  9846. return class extends Base {
  9847. insertText(pos, textOrWriterFunction) {
  9848. this.replaceText([pos, pos], textOrWriterFunction);
  9849. return this;
  9850. }
  9851. removeText(pos, end) {
  9852. if (pos == null)
  9853. this.replaceText(getValidRange(this), "");
  9854. else
  9855. this.replaceText([pos, end], "");
  9856. return this;
  9857. }
  9858. replaceText(range, textOrWriterFunction) {
  9859. const childSyntaxList = this.getChildSyntaxListOrThrow();
  9860. const validRange = getValidRange(this);
  9861. const pos = range[0];
  9862. const end = range[1];
  9863. verifyArguments();
  9864. insertIntoParentTextRange({
  9865. insertPos: pos,
  9866. newText: getTextFromStringOrWriter(this._getWriter(), textOrWriterFunction),
  9867. parent: childSyntaxList.getParentOrThrow(),
  9868. replacing: {
  9869. textLength: end - pos,
  9870. nodes: [childSyntaxList],
  9871. },
  9872. });
  9873. return this;
  9874. function verifyArguments() {
  9875. verifyInRange(pos);
  9876. verifyInRange(end);
  9877. if (pos > end)
  9878. throw new common.errors.ArgumentError("range", "Cannot specify a start position greater than the end position.");
  9879. }
  9880. function verifyInRange(i) {
  9881. if (i >= validRange[0] && i <= validRange[1])
  9882. return;
  9883. throw new common.errors.InvalidOperationError(`Cannot insert or replace text outside the bounds of the node. `
  9884. + `Expected a position between [${validRange[0]}, ${validRange[1]}], but received ${i}.`);
  9885. }
  9886. }
  9887. };
  9888. }
  9889. function getValidRange(thisNode) {
  9890. const rangeNode = getRangeNode();
  9891. const openBrace = Node.isSourceFile(rangeNode) ? undefined : rangeNode.getPreviousSiblingIfKind(common.SyntaxKind.OpenBraceToken);
  9892. const closeBrace = openBrace == null ? undefined : rangeNode.getNextSiblingIfKind(common.SyntaxKind.CloseBraceToken);
  9893. if (openBrace != null && closeBrace != null)
  9894. return [openBrace.getEnd(), closeBrace.getStart()];
  9895. else
  9896. return [rangeNode.getPos(), rangeNode.getEnd()];
  9897. function getRangeNode() {
  9898. if (Node.isSourceFile(thisNode))
  9899. return thisNode;
  9900. return thisNode.getChildSyntaxListOrThrow();
  9901. }
  9902. }
  9903. function TypeArgumentedNode(Base) {
  9904. return class extends Base {
  9905. getTypeArguments() {
  9906. if (this.compilerNode.typeArguments == null)
  9907. return [];
  9908. return this.compilerNode.typeArguments.map(a => this._getNodeFromCompilerNode(a));
  9909. }
  9910. addTypeArgument(argumentText) {
  9911. return this.addTypeArguments([argumentText])[0];
  9912. }
  9913. addTypeArguments(argumentTexts) {
  9914. return this.insertTypeArguments(this.getTypeArguments().length, argumentTexts);
  9915. }
  9916. insertTypeArgument(index, argumentText) {
  9917. return this.insertTypeArguments(index, [argumentText])[0];
  9918. }
  9919. insertTypeArguments(index, argumentTexts) {
  9920. if (common.ArrayUtils.isNullOrEmpty(argumentTexts))
  9921. return [];
  9922. const typeArguments = this.getTypeArguments();
  9923. index = verifyAndGetIndex(index, typeArguments.length);
  9924. if (typeArguments.length === 0) {
  9925. const identifier = this.getFirstChildByKindOrThrow(common.SyntaxKind.Identifier);
  9926. insertIntoParentTextRange({
  9927. insertPos: identifier.getEnd(),
  9928. parent: this,
  9929. newText: `<${argumentTexts.join(", ")}>`,
  9930. });
  9931. }
  9932. else {
  9933. insertIntoCommaSeparatedNodes({
  9934. parent: this.getFirstChildByKindOrThrow(common.SyntaxKind.LessThanToken).getNextSiblingIfKindOrThrow(common.SyntaxKind.SyntaxList),
  9935. currentNodes: typeArguments,
  9936. insertIndex: index,
  9937. newText: argumentTexts.join(", "),
  9938. useTrailingCommas: false,
  9939. });
  9940. }
  9941. return getNodesToReturn(typeArguments, this.getTypeArguments(), index, false);
  9942. }
  9943. removeTypeArgument(typeArgOrIndex) {
  9944. const typeArguments = this.getTypeArguments();
  9945. if (typeArguments.length === 0)
  9946. throw new common.errors.InvalidOperationError("Cannot remove a type argument when none exist.");
  9947. const typeArgToRemove = typeof typeArgOrIndex === "number" ? getTypeArgFromIndex(typeArgOrIndex) : typeArgOrIndex;
  9948. if (typeArguments.length === 1) {
  9949. const childSyntaxList = typeArguments[0].getParentSyntaxListOrThrow();
  9950. removeChildren({
  9951. children: [
  9952. childSyntaxList.getPreviousSiblingIfKindOrThrow(common.SyntaxKind.LessThanToken),
  9953. childSyntaxList,
  9954. childSyntaxList.getNextSiblingIfKindOrThrow(common.SyntaxKind.GreaterThanToken),
  9955. ],
  9956. });
  9957. }
  9958. else {
  9959. removeCommaSeparatedChild(typeArgToRemove);
  9960. }
  9961. return this;
  9962. function getTypeArgFromIndex(index) {
  9963. return typeArguments[verifyAndGetIndex(index, typeArguments.length - 1)];
  9964. }
  9965. }
  9966. };
  9967. }
  9968. function TypedNode(Base) {
  9969. return class extends Base {
  9970. getTypeNode() {
  9971. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.type);
  9972. }
  9973. getTypeNodeOrThrow(message) {
  9974. return common.errors.throwIfNullOrUndefined(this.getTypeNode(), message ?? "Expected to find a type node.", this);
  9975. }
  9976. setType(textOrWriterFunction) {
  9977. const text = getTextFromStringOrWriter(this._getWriterWithQueuedChildIndentation(), textOrWriterFunction);
  9978. if (common.StringUtils.isNullOrWhitespace(text))
  9979. return this.removeType();
  9980. const typeNode = this.getTypeNode();
  9981. if (typeNode != null && typeNode.getText() === text)
  9982. return this;
  9983. const separatorSyntaxKind = getSeparatorSyntaxKindForNode(this);
  9984. const separatorNode = this.getFirstChildByKind(separatorSyntaxKind);
  9985. let insertPos;
  9986. let newText;
  9987. if (separatorNode == null) {
  9988. insertPos = getInsertPosWhenNoType(this);
  9989. newText = (separatorSyntaxKind === common.SyntaxKind.EqualsToken ? " = " : ": ") + text;
  9990. }
  9991. else {
  9992. insertPos = typeNode.getStart();
  9993. newText = text;
  9994. }
  9995. insertIntoParentTextRange({
  9996. parent: this,
  9997. insertPos,
  9998. newText,
  9999. replacing: {
  10000. textLength: typeNode == null ? 0 : typeNode.getWidth(),
  10001. },
  10002. });
  10003. return this;
  10004. function getInsertPosWhenNoType(node) {
  10005. let identifier = node.getFirstChildByKind(common.SyntaxKind.Identifier) ?? node.getFirstChildByKind(common.SyntaxKind.ArrayBindingPattern) ?? node.getFirstChildIfKindOrThrow(common.SyntaxKind.ObjectBindingPattern, "A first child of the kind Identifier, ArrayBindingPattern, or ObjectBindingPattern was expected.");
  10006. const nextSibling = identifier.getNextSibling();
  10007. const insertAfterNode = isQuestionOrExclamation(nextSibling) ? nextSibling : identifier;
  10008. return insertAfterNode.getEnd();
  10009. }
  10010. function isQuestionOrExclamation(node) {
  10011. if (node == null)
  10012. return false;
  10013. const kind = node.getKind();
  10014. return kind === common.SyntaxKind.QuestionToken || kind === common.SyntaxKind.ExclamationToken;
  10015. }
  10016. }
  10017. set(structure) {
  10018. callBaseSet(Base.prototype, this, structure);
  10019. if (structure.type != null)
  10020. this.setType(structure.type);
  10021. else if (structure.hasOwnProperty(common.nameof(structure, "type")))
  10022. this.removeType();
  10023. return this;
  10024. }
  10025. removeType() {
  10026. if (this.getKind() === common.SyntaxKind.TypeAliasDeclaration)
  10027. throw new common.errors.NotSupportedError(`Cannot remove the type of a type alias. Use ${common.nameof("setType")} instead.`);
  10028. const typeNode = this.getTypeNode();
  10029. if (typeNode == null)
  10030. return this;
  10031. const separatorToken = typeNode.getPreviousSiblingIfKindOrThrow(getSeparatorSyntaxKindForNode(this));
  10032. removeChildren({ children: [separatorToken, typeNode], removePrecedingSpaces: true });
  10033. return this;
  10034. }
  10035. getStructure() {
  10036. const typeNode = this.getTypeNode();
  10037. return callBaseGetStructure(Base.prototype, this, {
  10038. type: typeNode ? typeNode.getText({ trimLeadingIndentation: true }) : undefined,
  10039. });
  10040. }
  10041. };
  10042. }
  10043. function getSeparatorSyntaxKindForNode(node) {
  10044. switch (node.getKind()) {
  10045. case common.SyntaxKind.TypeAliasDeclaration:
  10046. return common.SyntaxKind.EqualsToken;
  10047. default:
  10048. return common.SyntaxKind.ColonToken;
  10049. }
  10050. }
  10051. function TypeElementMemberedNode(Base) {
  10052. return class extends Base {
  10053. addMember(member) {
  10054. return this.addMembers([member])[0];
  10055. }
  10056. addMembers(members) {
  10057. return this.insertMembers(getEndIndexFromArray(this.getMembersWithComments()), members);
  10058. }
  10059. insertMember(index, member) {
  10060. return this.insertMembers(index, [member])[0];
  10061. }
  10062. insertMembers(index, members) {
  10063. return insertIntoBracesOrSourceFileWithGetChildrenWithComments({
  10064. getIndexedChildren: () => this.getMembersWithComments(),
  10065. index,
  10066. parent: this,
  10067. write: writer => {
  10068. writer.newLineIfLastNot();
  10069. const memberWriter = this._getWriter();
  10070. const memberPrinter = this._context.structurePrinterFactory.forTypeElementMember();
  10071. memberPrinter.printTexts(memberWriter, members);
  10072. writer.write(memberWriter.toString());
  10073. writer.newLineIfLastNot();
  10074. },
  10075. });
  10076. }
  10077. addConstructSignature(structure) {
  10078. return this.addConstructSignatures([structure])[0];
  10079. }
  10080. addConstructSignatures(structures) {
  10081. return this.insertConstructSignatures(getEndIndexFromArray(this.getMembersWithComments()), structures);
  10082. }
  10083. insertConstructSignature(index, structure) {
  10084. return this.insertConstructSignatures(index, [structure])[0];
  10085. }
  10086. insertConstructSignatures(index, structures) {
  10087. return insertChildren$1({
  10088. thisNode: this,
  10089. index,
  10090. structures,
  10091. expectedKind: common.SyntaxKind.ConstructSignature,
  10092. createStructurePrinter: () => this._context.structurePrinterFactory.forConstructSignatureDeclaration(),
  10093. });
  10094. }
  10095. getConstructSignature(findFunction) {
  10096. return this.getConstructSignatures().find(findFunction);
  10097. }
  10098. getConstructSignatureOrThrow(findFunction, message) {
  10099. return common.errors.throwIfNullOrUndefined(this.getConstructSignature(findFunction), message ?? "Expected to find a construct signature with the provided condition.", this);
  10100. }
  10101. getConstructSignatures() {
  10102. return this.compilerNode.members.filter(m => m.kind === common.SyntaxKind.ConstructSignature)
  10103. .map(m => this._getNodeFromCompilerNode(m));
  10104. }
  10105. addCallSignature(structure) {
  10106. return this.addCallSignatures([structure])[0];
  10107. }
  10108. addCallSignatures(structures) {
  10109. return this.insertCallSignatures(getEndIndexFromArray(this.getMembersWithComments()), structures);
  10110. }
  10111. insertCallSignature(index, structure) {
  10112. return this.insertCallSignatures(index, [structure])[0];
  10113. }
  10114. insertCallSignatures(index, structures) {
  10115. return insertChildren$1({
  10116. thisNode: this,
  10117. index,
  10118. structures,
  10119. expectedKind: common.SyntaxKind.CallSignature,
  10120. createStructurePrinter: () => this._context.structurePrinterFactory.forCallSignatureDeclaration(),
  10121. });
  10122. }
  10123. getCallSignature(findFunction) {
  10124. return this.getCallSignatures().find(findFunction);
  10125. }
  10126. getCallSignatureOrThrow(findFunction, message) {
  10127. return common.errors.throwIfNullOrUndefined(this.getCallSignature(findFunction), message ?? "Expected to find a call signature with the provided condition.", this);
  10128. }
  10129. getCallSignatures() {
  10130. return this.compilerNode.members.filter(m => m.kind === common.SyntaxKind.CallSignature)
  10131. .map(m => this._getNodeFromCompilerNode(m));
  10132. }
  10133. addIndexSignature(structure) {
  10134. return this.addIndexSignatures([structure])[0];
  10135. }
  10136. addIndexSignatures(structures) {
  10137. return this.insertIndexSignatures(getEndIndexFromArray(this.getMembersWithComments()), structures);
  10138. }
  10139. insertIndexSignature(index, structure) {
  10140. return this.insertIndexSignatures(index, [structure])[0];
  10141. }
  10142. insertIndexSignatures(index, structures) {
  10143. return insertChildren$1({
  10144. thisNode: this,
  10145. index,
  10146. structures,
  10147. expectedKind: common.SyntaxKind.IndexSignature,
  10148. createStructurePrinter: () => this._context.structurePrinterFactory.forIndexSignatureDeclaration(),
  10149. });
  10150. }
  10151. getIndexSignature(findFunction) {
  10152. return this.getIndexSignatures().find(findFunction);
  10153. }
  10154. getIndexSignatureOrThrow(findFunction, message) {
  10155. return common.errors.throwIfNullOrUndefined(this.getIndexSignature(findFunction), message ?? "Expected to find a index signature with the provided condition.", this);
  10156. }
  10157. getIndexSignatures() {
  10158. return this.compilerNode.members.filter(m => m.kind === common.SyntaxKind.IndexSignature)
  10159. .map(m => this._getNodeFromCompilerNode(m));
  10160. }
  10161. addMethod(structure) {
  10162. return this.addMethods([structure])[0];
  10163. }
  10164. addMethods(structures) {
  10165. return this.insertMethods(getEndIndexFromArray(this.getMembersWithComments()), structures);
  10166. }
  10167. insertMethod(index, structure) {
  10168. return this.insertMethods(index, [structure])[0];
  10169. }
  10170. insertMethods(index, structures) {
  10171. return insertChildren$1({
  10172. thisNode: this,
  10173. index,
  10174. structures,
  10175. expectedKind: common.SyntaxKind.MethodSignature,
  10176. createStructurePrinter: () => this._context.structurePrinterFactory.forMethodSignature(),
  10177. });
  10178. }
  10179. getMethod(nameOrFindFunction) {
  10180. return getNodeByNameOrFindFunction(this.getMethods(), nameOrFindFunction);
  10181. }
  10182. getMethodOrThrow(nameOrFindFunction) {
  10183. return common.errors.throwIfNullOrUndefined(this.getMethod(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("interface method signature", nameOrFindFunction));
  10184. }
  10185. getMethods() {
  10186. return this.compilerNode.members.filter(m => m.kind === common.SyntaxKind.MethodSignature)
  10187. .map(m => this._getNodeFromCompilerNode(m));
  10188. }
  10189. addProperty(structure) {
  10190. return this.addProperties([structure])[0];
  10191. }
  10192. addProperties(structures) {
  10193. return this.insertProperties(getEndIndexFromArray(this.getMembersWithComments()), structures);
  10194. }
  10195. insertProperty(index, structure) {
  10196. return this.insertProperties(index, [structure])[0];
  10197. }
  10198. insertProperties(index, structures) {
  10199. return insertChildren$1({
  10200. thisNode: this,
  10201. index,
  10202. structures,
  10203. expectedKind: common.SyntaxKind.PropertySignature,
  10204. createStructurePrinter: () => this._context.structurePrinterFactory.forPropertySignature(),
  10205. });
  10206. }
  10207. getProperty(nameOrFindFunction) {
  10208. return getNodeByNameOrFindFunction(this.getProperties(), nameOrFindFunction);
  10209. }
  10210. getPropertyOrThrow(nameOrFindFunction) {
  10211. return common.errors.throwIfNullOrUndefined(this.getProperty(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("interface property signature", nameOrFindFunction));
  10212. }
  10213. getProperties() {
  10214. return this.compilerNode.members.filter(m => m.kind === common.SyntaxKind.PropertySignature)
  10215. .map(m => this._getNodeFromCompilerNode(m));
  10216. }
  10217. addGetAccessor(structure) {
  10218. return this.addGetAccessors([structure])[0];
  10219. }
  10220. addGetAccessors(structures) {
  10221. const result = [];
  10222. for (const structure of structures) {
  10223. const setAccessor = this.getSetAccessor(structure.name);
  10224. const index = setAccessor == null ? getEndIndexFromArray(this.getMembersWithComments()) : setAccessor.getChildIndex();
  10225. result.push(this.insertGetAccessor(index, structure));
  10226. }
  10227. return result;
  10228. }
  10229. insertGetAccessor(index, structure) {
  10230. return this.insertGetAccessors(index, [structure])[0];
  10231. }
  10232. insertGetAccessors(index, structures) {
  10233. return insertChildren$1({
  10234. thisNode: this,
  10235. index,
  10236. structures,
  10237. expectedKind: common.SyntaxKind.GetAccessor,
  10238. createStructurePrinter: () => this._context.structurePrinterFactory.forGetAccessorDeclaration({
  10239. isAmbient: true,
  10240. }),
  10241. });
  10242. }
  10243. getGetAccessor(nameOrFindFunction) {
  10244. return getNodeByNameOrFindFunction(this.getGetAccessors(), nameOrFindFunction);
  10245. }
  10246. getGetAccessorOrThrow(nameOrFindFunction) {
  10247. return common.errors.throwIfNullOrUndefined(this.getGetAccessor(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("interface get accessor", nameOrFindFunction));
  10248. }
  10249. getGetAccessors() {
  10250. return this.compilerNode.members.filter(m => m.kind === common.SyntaxKind.GetAccessor)
  10251. .map(m => this._getNodeFromCompilerNode(m));
  10252. }
  10253. addSetAccessor(structure) {
  10254. return this.addSetAccessors([structure])[0];
  10255. }
  10256. addSetAccessors(structures) {
  10257. const result = [];
  10258. for (const structure of structures) {
  10259. const getAccessor = this.getGetAccessor(structure.name);
  10260. const index = getAccessor == null ? getEndIndexFromArray(this.getMembersWithComments()) : getAccessor.getChildIndex() + 1;
  10261. result.push(this.insertSetAccessor(index, structure));
  10262. }
  10263. return result;
  10264. }
  10265. insertSetAccessor(index, structure) {
  10266. return this.insertSetAccessors(index, [structure])[0];
  10267. }
  10268. insertSetAccessors(index, structures) {
  10269. return insertChildren$1({
  10270. thisNode: this,
  10271. index,
  10272. structures,
  10273. expectedKind: common.SyntaxKind.SetAccessor,
  10274. createStructurePrinter: () => this._context.structurePrinterFactory.forSetAccessorDeclaration({
  10275. isAmbient: true,
  10276. }),
  10277. });
  10278. }
  10279. getSetAccessor(nameOrFindFunction) {
  10280. return getNodeByNameOrFindFunction(this.getSetAccessors(), nameOrFindFunction);
  10281. }
  10282. getSetAccessorOrThrow(nameOrFindFunction) {
  10283. return common.errors.throwIfNullOrUndefined(this.getSetAccessor(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("interface set accessor", nameOrFindFunction));
  10284. }
  10285. getSetAccessors() {
  10286. return this.compilerNode.members.filter(m => m.kind === common.SyntaxKind.SetAccessor)
  10287. .map(m => this._getNodeFromCompilerNode(m));
  10288. }
  10289. getMembers() {
  10290. return this.compilerNode.members.map(m => this._getNodeFromCompilerNode(m));
  10291. }
  10292. getMembersWithComments() {
  10293. const compilerNode = this.compilerNode;
  10294. return ExtendedParser.getContainerArray(compilerNode, this._sourceFile.compilerNode)
  10295. .map(m => this._getNodeFromCompilerNode(m));
  10296. }
  10297. set(structure) {
  10298. callBaseSet(Base.prototype, this, structure);
  10299. if (structure.callSignatures != null) {
  10300. this.getCallSignatures().forEach(c => c.remove());
  10301. this.addCallSignatures(structure.callSignatures);
  10302. }
  10303. if (structure.constructSignatures != null) {
  10304. this.getConstructSignatures().forEach(c => c.remove());
  10305. this.addConstructSignatures(structure.constructSignatures);
  10306. }
  10307. if (structure.indexSignatures != null) {
  10308. this.getIndexSignatures().forEach(c => c.remove());
  10309. this.addIndexSignatures(structure.indexSignatures);
  10310. }
  10311. if (structure.properties != null) {
  10312. this.getProperties().forEach(c => c.remove());
  10313. this.addProperties(structure.properties);
  10314. }
  10315. if (structure.getAccessors != null) {
  10316. this.getGetAccessors().forEach(c => c.remove());
  10317. this.addGetAccessors(structure.getAccessors);
  10318. }
  10319. if (structure.setAccessors != null) {
  10320. this.getSetAccessors().forEach(c => c.remove());
  10321. this.addSetAccessors(structure.setAccessors);
  10322. }
  10323. if (structure.methods != null) {
  10324. this.getMethods().forEach(c => c.remove());
  10325. this.addMethods(structure.methods);
  10326. }
  10327. return this;
  10328. }
  10329. getStructure() {
  10330. return callBaseGetStructure(Base.prototype, this, {
  10331. callSignatures: this.getCallSignatures().map(node => node.getStructure()),
  10332. constructSignatures: this.getConstructSignatures().map(node => node.getStructure()),
  10333. getAccessors: this.getGetAccessors().map(node => node.getStructure()),
  10334. indexSignatures: this.getIndexSignatures().map(node => node.getStructure()),
  10335. methods: this.getMethods().map(node => node.getStructure()),
  10336. properties: this.getProperties().map(node => node.getStructure()),
  10337. setAccessors: this.getSetAccessors().map(node => node.getStructure()),
  10338. });
  10339. }
  10340. };
  10341. }
  10342. function insertChildren$1(opts) {
  10343. return insertIntoBracesOrSourceFileWithGetChildren({
  10344. getIndexedChildren: () => opts.thisNode.getMembersWithComments(),
  10345. parent: opts.thisNode,
  10346. index: opts.index,
  10347. structures: opts.structures,
  10348. expectedKind: opts.expectedKind,
  10349. write: (writer, info) => {
  10350. writer.newLineIfLastNot();
  10351. opts.createStructurePrinter().printTexts(writer, opts.structures);
  10352. writer.newLineIfLastNot();
  10353. },
  10354. });
  10355. }
  10356. function TypeParameteredNode(Base) {
  10357. return class extends Base {
  10358. getTypeParameter(nameOrFindFunction) {
  10359. return getNodeByNameOrFindFunction(this.getTypeParameters(), nameOrFindFunction);
  10360. }
  10361. getTypeParameterOrThrow(nameOrFindFunction) {
  10362. return common.errors.throwIfNullOrUndefined(this.getTypeParameter(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("type parameter", nameOrFindFunction));
  10363. }
  10364. getTypeParameters() {
  10365. const typeParameters = this.compilerNode.typeParameters;
  10366. if (typeParameters == null)
  10367. return [];
  10368. return typeParameters.map(t => this._getNodeFromCompilerNode(t));
  10369. }
  10370. addTypeParameter(structure) {
  10371. return this.addTypeParameters([structure])[0];
  10372. }
  10373. addTypeParameters(structures) {
  10374. return this.insertTypeParameters(getEndIndexFromArray(this.compilerNode.typeParameters), structures);
  10375. }
  10376. insertTypeParameter(index, structure) {
  10377. return this.insertTypeParameters(index, [structure])[0];
  10378. }
  10379. insertTypeParameters(index, structures) {
  10380. if (common.ArrayUtils.isNullOrEmpty(structures))
  10381. return [];
  10382. const typeParameters = this.getTypeParameters();
  10383. const writer = this._getWriterWithQueuedChildIndentation();
  10384. const structurePrinter = this._context.structurePrinterFactory.forTypeParameterDeclaration();
  10385. index = verifyAndGetIndex(index, typeParameters.length);
  10386. structurePrinter.printTexts(writer, structures);
  10387. if (typeParameters.length === 0) {
  10388. insertIntoParentTextRange({
  10389. insertPos: getInsertPos(this),
  10390. parent: this,
  10391. newText: `<${writer.toString()}>`,
  10392. });
  10393. }
  10394. else {
  10395. insertIntoCommaSeparatedNodes({
  10396. parent: this.getFirstChildByKindOrThrow(common.SyntaxKind.LessThanToken).getNextSiblingIfKindOrThrow(common.SyntaxKind.SyntaxList),
  10397. currentNodes: typeParameters,
  10398. insertIndex: index,
  10399. newText: writer.toString(),
  10400. useTrailingCommas: false,
  10401. });
  10402. }
  10403. return getNodesToReturn(typeParameters, this.getTypeParameters(), index, false);
  10404. }
  10405. set(structure) {
  10406. callBaseSet(Base.prototype, this, structure);
  10407. if (structure.typeParameters != null) {
  10408. this.getTypeParameters().forEach(t => t.remove());
  10409. this.addTypeParameters(structure.typeParameters);
  10410. }
  10411. return this;
  10412. }
  10413. getStructure() {
  10414. return callBaseGetStructure(Base.prototype, this, {
  10415. typeParameters: this.getTypeParameters().map(p => p.getStructure()),
  10416. });
  10417. }
  10418. };
  10419. }
  10420. function getInsertPos(node) {
  10421. const namedNode = node;
  10422. if (namedNode.getNameNode != null)
  10423. return namedNode.getNameNode().getEnd();
  10424. else if (Node.isCallSignatureDeclaration(node) || Node.isFunctionTypeNode(node))
  10425. return node.getFirstChildByKindOrThrow(common.SyntaxKind.OpenParenToken).getStart();
  10426. else
  10427. throw new common.errors.NotImplementedError(`Not implemented scenario inserting type parameters for node with kind ${node.getKindName()}.`);
  10428. }
  10429. function UnwrappableNode(Base) {
  10430. return class extends Base {
  10431. unwrap() {
  10432. unwrapNode(this);
  10433. }
  10434. };
  10435. }
  10436. class ArrayBindingPattern extends Node {
  10437. getElements() {
  10438. return this.compilerNode.elements.map(e => this._getNodeFromCompilerNode(e));
  10439. }
  10440. }
  10441. const createBase$F = (ctor) => DotDotDotTokenableNode(InitializerExpressionableNode(BindingNamedNode(ctor)));
  10442. const BindingElementBase = createBase$F(Node);
  10443. class BindingElement extends BindingElementBase {
  10444. getPropertyNameNodeOrThrow(message) {
  10445. return common.errors.throwIfNullOrUndefined(this.getPropertyNameNode(), message ?? "Expected to find a property name node.", this);
  10446. }
  10447. getPropertyNameNode() {
  10448. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.propertyName);
  10449. }
  10450. }
  10451. class ObjectBindingPattern extends Node {
  10452. getElements() {
  10453. return this.compilerNode.elements.map(e => this._getNodeFromCompilerNode(e));
  10454. }
  10455. }
  10456. function AbstractableNode(Base) {
  10457. return class extends Base {
  10458. isAbstract() {
  10459. return this.getAbstractKeyword() != null;
  10460. }
  10461. getAbstractKeyword() {
  10462. return this.getFirstModifierByKind(common.SyntaxKind.AbstractKeyword);
  10463. }
  10464. getAbstractKeywordOrThrow(message) {
  10465. return common.errors.throwIfNullOrUndefined(this.getAbstractKeyword(), message ?? "Expected to find an abstract keyword.", this);
  10466. }
  10467. setIsAbstract(isAbstract) {
  10468. this.toggleModifier("abstract", isAbstract);
  10469. return this;
  10470. }
  10471. set(structure) {
  10472. callBaseSet(Base.prototype, this, structure);
  10473. if (structure.isAbstract != null)
  10474. this.setIsAbstract(structure.isAbstract);
  10475. return this;
  10476. }
  10477. getStructure() {
  10478. return callBaseGetStructure(Base.prototype, this, {
  10479. isAbstract: this.isAbstract(),
  10480. });
  10481. }
  10482. };
  10483. }
  10484. class Expression extends Node {
  10485. getContextualType() {
  10486. return this._context.typeChecker.getContextualType(this);
  10487. }
  10488. }
  10489. const BinaryExpressionBase = Expression;
  10490. class BinaryExpression extends BinaryExpressionBase {
  10491. getLeft() {
  10492. return this._getNodeFromCompilerNode(this.compilerNode.left);
  10493. }
  10494. getOperatorToken() {
  10495. return this._getNodeFromCompilerNode(this.compilerNode.operatorToken);
  10496. }
  10497. getRight() {
  10498. return this._getNodeFromCompilerNode(this.compilerNode.right);
  10499. }
  10500. }
  10501. const AssignmentExpressionBase = BinaryExpression;
  10502. class AssignmentExpression extends AssignmentExpressionBase {
  10503. getOperatorToken() {
  10504. return this._getNodeFromCompilerNode(this.compilerNode.operatorToken);
  10505. }
  10506. }
  10507. const ArrayDestructuringAssignmentBase = AssignmentExpression;
  10508. class ArrayDestructuringAssignment extends ArrayDestructuringAssignmentBase {
  10509. getLeft() {
  10510. return this._getNodeFromCompilerNode(this.compilerNode.left);
  10511. }
  10512. }
  10513. class UnaryExpression extends Expression {
  10514. }
  10515. class UpdateExpression extends UnaryExpression {
  10516. }
  10517. class LeftHandSideExpression extends UpdateExpression {
  10518. }
  10519. class MemberExpression extends LeftHandSideExpression {
  10520. }
  10521. class PrimaryExpression extends MemberExpression {
  10522. }
  10523. class ArrayLiteralExpression extends PrimaryExpression {
  10524. getElements() {
  10525. return this.compilerNode.elements.map(e => this._getNodeFromCompilerNode(e));
  10526. }
  10527. addElement(textOrWriterFunction, options) {
  10528. return this.addElements([textOrWriterFunction], options)[0];
  10529. }
  10530. addElements(textsOrWriterFunction, options) {
  10531. return this.insertElements(this.compilerNode.elements.length, textsOrWriterFunction, options);
  10532. }
  10533. insertElement(index, textOrWriterFunction, options) {
  10534. return this.insertElements(index, [textOrWriterFunction], options)[0];
  10535. }
  10536. insertElements(index, textsOrWriterFunction, options = {}) {
  10537. const elements = this.getElements();
  10538. index = verifyAndGetIndex(index, elements.length);
  10539. const useNewLines = getUseNewLines(this);
  10540. const writer = useNewLines ? this._getWriterWithChildIndentation() : this._getWriterWithQueuedChildIndentation();
  10541. const stringStructurePrinter = new StringStructurePrinter();
  10542. const structurePrinter = useNewLines
  10543. ? new CommaNewLineSeparatedStructuresPrinter(stringStructurePrinter)
  10544. : new CommaSeparatedStructuresPrinter(stringStructurePrinter);
  10545. structurePrinter.printText(writer, textsOrWriterFunction);
  10546. return insertTexts(this);
  10547. function insertTexts(node) {
  10548. insertIntoCommaSeparatedNodes({
  10549. parent: node.getFirstChildByKindOrThrow(common.SyntaxKind.SyntaxList),
  10550. currentNodes: elements,
  10551. insertIndex: index,
  10552. newText: writer.toString(),
  10553. useNewLines,
  10554. useTrailingCommas: useNewLines && node._context.manipulationSettings.getUseTrailingCommas(),
  10555. });
  10556. const newElements = node.getElements();
  10557. return getNodesToReturn(elements, newElements, index, false);
  10558. }
  10559. function getUseNewLines(node) {
  10560. if (options.useNewLines != null)
  10561. return options.useNewLines;
  10562. if (elements.length > 1)
  10563. return allElementsOnDifferentLines();
  10564. return node.getStartLineNumber() !== node.getEndLineNumber();
  10565. function allElementsOnDifferentLines() {
  10566. let previousLine = elements[0].getStartLineNumber();
  10567. for (let i = 1; i < elements.length; i++) {
  10568. const currentLine = elements[i].getStartLineNumber();
  10569. if (previousLine === currentLine)
  10570. return false;
  10571. previousLine = currentLine;
  10572. }
  10573. return true;
  10574. }
  10575. }
  10576. }
  10577. removeElement(elementOrIndex) {
  10578. const elements = this.getElements();
  10579. if (elements.length === 0)
  10580. throw new common.errors.InvalidOperationError("Cannot remove an element when none exist.");
  10581. const elementToRemove = typeof elementOrIndex === "number" ? getElementFromIndex(elementOrIndex) : elementOrIndex;
  10582. removeCommaSeparatedChild(elementToRemove);
  10583. function getElementFromIndex(index) {
  10584. return elements[verifyAndGetIndex(index, elements.length - 1)];
  10585. }
  10586. }
  10587. }
  10588. function ExpressionableNode(Base) {
  10589. return class extends Base {
  10590. getExpression() {
  10591. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.expression);
  10592. }
  10593. getExpressionOrThrow(message) {
  10594. return common.errors.throwIfNullOrUndefined(this.getExpression(), message ?? "Expected to find an expression.", this);
  10595. }
  10596. getExpressionIfKind(kind) {
  10597. const expression = this.getExpression();
  10598. return expression?.getKind() === kind ? expression : undefined;
  10599. }
  10600. getExpressionIfKindOrThrow(kind, message) {
  10601. return common.errors.throwIfNullOrUndefined(this.getExpressionIfKind(kind), message ?? `An expression with the kind kind ${common.getSyntaxKindName(kind)} was expected.`, this);
  10602. }
  10603. };
  10604. }
  10605. function BaseExpressionedNode(Base) {
  10606. return class extends Base {
  10607. getExpression() {
  10608. return this._getNodeFromCompilerNode(this.compilerNode.expression);
  10609. }
  10610. getExpressionIfKind(kind) {
  10611. const { expression } = this.compilerNode;
  10612. return expression.kind === kind ? this._getNodeFromCompilerNode(expression) : undefined;
  10613. }
  10614. getExpressionIfKindOrThrow(kind, message) {
  10615. return common.errors.throwIfNullOrUndefined(this.getExpressionIfKind(kind), message ?? `An expression of the kind ${common.getSyntaxKindName(kind)} was expected.`, this);
  10616. }
  10617. setExpression(textOrWriterFunction) {
  10618. this.getExpression().replaceWithText(textOrWriterFunction, this._getWriterWithQueuedChildIndentation());
  10619. return this;
  10620. }
  10621. set(structure) {
  10622. callBaseSet(Base.prototype, this, structure);
  10623. if (structure.expression != null)
  10624. this.setExpression(structure.expression);
  10625. return this;
  10626. }
  10627. };
  10628. }
  10629. function ExpressionedNode(Base) {
  10630. return BaseExpressionedNode(Base);
  10631. }
  10632. function ImportExpressionedNode(Base) {
  10633. return BaseExpressionedNode(Base);
  10634. }
  10635. function LeftHandSideExpressionedNode(Base) {
  10636. return BaseExpressionedNode(Base);
  10637. }
  10638. function SuperExpressionedNode(Base) {
  10639. return BaseExpressionedNode(Base);
  10640. }
  10641. function UnaryExpressionedNode(Base) {
  10642. return BaseExpressionedNode(Base);
  10643. }
  10644. const createBase$E = (ctor) => TypedNode(ExpressionedNode(ctor));
  10645. const AsExpressionBase = createBase$E(Expression);
  10646. class AsExpression extends AsExpressionBase {
  10647. }
  10648. const AwaitExpressionBase = UnaryExpressionedNode(UnaryExpression);
  10649. class AwaitExpression extends AwaitExpressionBase {
  10650. }
  10651. const createBase$D = (ctor) => TypeArgumentedNode(ArgumentedNode(QuestionDotTokenableNode(LeftHandSideExpressionedNode(ctor))));
  10652. const CallExpressionBase = createBase$D(LeftHandSideExpression);
  10653. class CallExpression extends CallExpressionBase {
  10654. getReturnType() {
  10655. return this._context.typeChecker.getTypeAtLocation(this);
  10656. }
  10657. }
  10658. const CommaListExpressionBase = Expression;
  10659. class CommaListExpression extends CommaListExpressionBase {
  10660. getElements() {
  10661. return this.compilerNode.elements.map(e => this._getNodeFromCompilerNode(e));
  10662. }
  10663. }
  10664. const ConditionalExpressionBase = Expression;
  10665. class ConditionalExpression extends ConditionalExpressionBase {
  10666. getCondition() {
  10667. return this._getNodeFromCompilerNode(this.compilerNode.condition);
  10668. }
  10669. getQuestionToken() {
  10670. return this._getNodeFromCompilerNode(this.compilerNode.questionToken);
  10671. }
  10672. getWhenTrue() {
  10673. return this._getNodeFromCompilerNode(this.compilerNode.whenTrue);
  10674. }
  10675. getColonToken() {
  10676. return this._getNodeFromCompilerNode(this.compilerNode.colonToken);
  10677. }
  10678. getWhenFalse() {
  10679. return this._getNodeFromCompilerNode(this.compilerNode.whenFalse);
  10680. }
  10681. }
  10682. const DeleteExpressionBase = UnaryExpressionedNode(UnaryExpression);
  10683. class DeleteExpression extends DeleteExpressionBase {
  10684. }
  10685. const createBase$C = (ctor) => QuestionDotTokenableNode(LeftHandSideExpressionedNode(ctor));
  10686. const ElementAccessExpressionBase = createBase$C(MemberExpression);
  10687. class ElementAccessExpression extends ElementAccessExpressionBase {
  10688. getArgumentExpression() {
  10689. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.argumentExpression);
  10690. }
  10691. getArgumentExpressionOrThrow(message) {
  10692. return common.errors.throwIfNullOrUndefined(this.getArgumentExpression(), message ?? "Expected to find an argument expression.", this);
  10693. }
  10694. }
  10695. const ImportExpressionBase = PrimaryExpression;
  10696. class ImportExpression extends ImportExpressionBase {
  10697. }
  10698. const LiteralExpressionBase = LiteralLikeNode(PrimaryExpression);
  10699. class LiteralExpression extends LiteralExpressionBase {
  10700. }
  10701. const MetaPropertyBase = NamedNode(PrimaryExpression);
  10702. class MetaProperty extends MetaPropertyBase {
  10703. getKeywordToken() {
  10704. return this.compilerNode.keywordToken;
  10705. }
  10706. }
  10707. const createBase$B = (ctor) => TypeArgumentedNode(ArgumentedNode(LeftHandSideExpressionedNode(ctor)));
  10708. const NewExpressionBase = createBase$B(PrimaryExpression);
  10709. class NewExpression extends NewExpressionBase {
  10710. }
  10711. const NonNullExpressionBase = ExpressionedNode(LeftHandSideExpression);
  10712. class NonNullExpression extends NonNullExpressionBase {
  10713. }
  10714. class ObjectLiteralElement extends Node {
  10715. remove() {
  10716. removeCommaSeparatedChild(this);
  10717. }
  10718. }
  10719. class CommentObjectLiteralElement extends ObjectLiteralElement {
  10720. }
  10721. const ObjectDestructuringAssignmentBase = AssignmentExpression;
  10722. class ObjectDestructuringAssignment extends ObjectDestructuringAssignmentBase {
  10723. getLeft() {
  10724. return this._getNodeFromCompilerNode(this.compilerNode.left);
  10725. }
  10726. }
  10727. const ObjectLiteralExpressionBase = PrimaryExpression;
  10728. class ObjectLiteralExpression extends ObjectLiteralExpressionBase {
  10729. getPropertyOrThrow(nameOrFindFunction) {
  10730. return common.errors.throwIfNullOrUndefined(this.getProperty(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("property", nameOrFindFunction));
  10731. }
  10732. getProperty(nameOrFindFunction) {
  10733. let findFunc;
  10734. if (typeof nameOrFindFunction === "string") {
  10735. findFunc = prop => {
  10736. if (prop[common.nameof("getName")] == null)
  10737. return false;
  10738. return prop.getName() === nameOrFindFunction;
  10739. };
  10740. }
  10741. else {
  10742. findFunc = nameOrFindFunction;
  10743. }
  10744. return this.getProperties().find(findFunc);
  10745. }
  10746. getProperties() {
  10747. return this.compilerNode.properties.map(p => this._getNodeFromCompilerNode(p));
  10748. }
  10749. getPropertiesWithComments() {
  10750. const members = ExtendedParser.getContainerArray(this.compilerNode, this.getSourceFile().compilerNode);
  10751. return members.map(p => this._getNodeFromCompilerNode(p));
  10752. }
  10753. #getAddIndex() {
  10754. const members = ExtendedParser.getContainerArray(this.compilerNode, this.getSourceFile().compilerNode);
  10755. return members.length;
  10756. }
  10757. addProperty(structure) {
  10758. return this.insertProperties(this.#getAddIndex(), [structure])[0];
  10759. }
  10760. addProperties(structures) {
  10761. return this.insertProperties(this.#getAddIndex(), structures);
  10762. }
  10763. insertProperty(index, structure) {
  10764. return this.insertProperties(index, [structure])[0];
  10765. }
  10766. insertProperties(index, structures) {
  10767. const properties = this.getPropertiesWithComments();
  10768. index = verifyAndGetIndex(index, properties.length);
  10769. const writer = this._getWriterWithChildIndentation();
  10770. const structurePrinter = this._context.structurePrinterFactory.forObjectLiteralExpressionProperty();
  10771. structurePrinter.printTexts(writer, structures);
  10772. insertIntoCommaSeparatedNodes({
  10773. parent: this.getChildSyntaxListOrThrow(),
  10774. currentNodes: properties,
  10775. insertIndex: index,
  10776. newText: writer.toString(),
  10777. useNewLines: true,
  10778. useTrailingCommas: this._context.manipulationSettings.getUseTrailingCommas(),
  10779. });
  10780. return getNodesToReturn(properties, this.getPropertiesWithComments(), index, true);
  10781. }
  10782. addPropertyAssignment(structure) {
  10783. return this.addPropertyAssignments([structure])[0];
  10784. }
  10785. addPropertyAssignments(structures) {
  10786. return this.insertPropertyAssignments(this.#getAddIndex(), structures);
  10787. }
  10788. insertPropertyAssignment(index, structure) {
  10789. return this.insertPropertyAssignments(index, [structure])[0];
  10790. }
  10791. insertPropertyAssignments(index, structures) {
  10792. return this.#insertProperty(index, structures, () => this._context.structurePrinterFactory.forPropertyAssignment());
  10793. }
  10794. addShorthandPropertyAssignment(structure) {
  10795. return this.addShorthandPropertyAssignments([structure])[0];
  10796. }
  10797. addShorthandPropertyAssignments(structures) {
  10798. return this.insertShorthandPropertyAssignments(this.#getAddIndex(), structures);
  10799. }
  10800. insertShorthandPropertyAssignment(index, structure) {
  10801. return this.insertShorthandPropertyAssignments(index, [structure])[0];
  10802. }
  10803. insertShorthandPropertyAssignments(index, structures) {
  10804. return this.#insertProperty(index, structures, () => this._context.structurePrinterFactory.forShorthandPropertyAssignment());
  10805. }
  10806. addSpreadAssignment(structure) {
  10807. return this.addSpreadAssignments([structure])[0];
  10808. }
  10809. addSpreadAssignments(structures) {
  10810. return this.insertSpreadAssignments(this.#getAddIndex(), structures);
  10811. }
  10812. insertSpreadAssignment(index, structure) {
  10813. return this.insertSpreadAssignments(index, [structure])[0];
  10814. }
  10815. insertSpreadAssignments(index, structures) {
  10816. return this.#insertProperty(index, structures, () => this._context.structurePrinterFactory.forSpreadAssignment());
  10817. }
  10818. addMethod(structure) {
  10819. return this.addMethods([structure])[0];
  10820. }
  10821. addMethods(structures) {
  10822. return this.insertMethods(this.#getAddIndex(), structures);
  10823. }
  10824. insertMethod(index, structure) {
  10825. return this.insertMethods(index, [structure])[0];
  10826. }
  10827. insertMethods(index, structures) {
  10828. return this.#insertProperty(index, structures, () => this._context.structurePrinterFactory.forMethodDeclaration({ isAmbient: false }));
  10829. }
  10830. addGetAccessor(structure) {
  10831. return this.addGetAccessors([structure])[0];
  10832. }
  10833. addGetAccessors(structures) {
  10834. return this.insertGetAccessors(this.#getAddIndex(), structures);
  10835. }
  10836. insertGetAccessor(index, structure) {
  10837. return this.insertGetAccessors(index, [structure])[0];
  10838. }
  10839. insertGetAccessors(index, structures) {
  10840. return this.#insertProperty(index, structures, () => this._context.structurePrinterFactory.forGetAccessorDeclaration({ isAmbient: false }));
  10841. }
  10842. addSetAccessor(structure) {
  10843. return this.addSetAccessors([structure])[0];
  10844. }
  10845. addSetAccessors(structures) {
  10846. return this.insertSetAccessors(this.#getAddIndex(), structures);
  10847. }
  10848. insertSetAccessor(index, structure) {
  10849. return this.insertSetAccessors(index, [structure])[0];
  10850. }
  10851. insertSetAccessors(index, structures) {
  10852. return this.#insertProperty(index, structures, () => this._context.structurePrinterFactory.forSetAccessorDeclaration({ isAmbient: false }));
  10853. }
  10854. #insertProperty(index, structures, createStructurePrinter) {
  10855. index = verifyAndGetIndex(index, this.#getAddIndex());
  10856. const writer = this._getWriterWithChildIndentation();
  10857. const structurePrinter = new CommaNewLineSeparatedStructuresPrinter(createStructurePrinter());
  10858. const oldProperties = this.getPropertiesWithComments();
  10859. structurePrinter.printText(writer, structures);
  10860. insertIntoCommaSeparatedNodes({
  10861. parent: this.getFirstChildByKindOrThrow(common.SyntaxKind.SyntaxList),
  10862. currentNodes: oldProperties,
  10863. insertIndex: index,
  10864. newText: writer.toString(),
  10865. useNewLines: true,
  10866. useTrailingCommas: this._context.manipulationSettings.getUseTrailingCommas(),
  10867. });
  10868. return getNodesToReturn(oldProperties, this.getPropertiesWithComments(), index, false);
  10869. }
  10870. }
  10871. const createBase$A = (ctor) => InitializerExpressionGetableNode(QuestionTokenableNode(PropertyNamedNode(ctor)));
  10872. const PropertyAssignmentBase = createBase$A(ObjectLiteralElement);
  10873. class PropertyAssignment extends PropertyAssignmentBase {
  10874. removeInitializer() {
  10875. const initializer = this.getInitializerOrThrow();
  10876. const colonToken = initializer.getPreviousSiblingIfKindOrThrow(common.SyntaxKind.ColonToken);
  10877. const childIndex = this.getChildIndex();
  10878. const sourceFileText = this._sourceFile.getFullText();
  10879. const insertPos = this.getStart();
  10880. const newText = sourceFileText.substring(insertPos, colonToken.getPos()) + sourceFileText.substring(initializer.getEnd(), this.getEnd());
  10881. const parent = this.getParentSyntaxList() || this.getParentOrThrow();
  10882. insertIntoParentTextRange({
  10883. insertPos,
  10884. newText,
  10885. parent,
  10886. replacing: {
  10887. textLength: this.getWidth(),
  10888. },
  10889. });
  10890. return parent.getChildAtIndexIfKindOrThrow(childIndex, common.SyntaxKind.ShorthandPropertyAssignment);
  10891. }
  10892. setInitializer(textOrWriterFunction) {
  10893. const initializer = this.getInitializerOrThrow();
  10894. insertIntoParentTextRange({
  10895. insertPos: initializer.getStart(),
  10896. newText: getTextFromStringOrWriter(this._getWriterWithQueuedChildIndentation(), textOrWriterFunction),
  10897. parent: this,
  10898. replacing: {
  10899. textLength: initializer.getWidth(),
  10900. },
  10901. });
  10902. return this;
  10903. }
  10904. set(structure) {
  10905. callBaseSet(PropertyAssignmentBase.prototype, this, structure);
  10906. if (structure.initializer != null)
  10907. this.setInitializer(structure.initializer);
  10908. else if (structure.hasOwnProperty(common.nameof(structure, "initializer")))
  10909. return this.removeInitializer();
  10910. return this;
  10911. }
  10912. getStructure() {
  10913. const initializer = this.getInitializerOrThrow();
  10914. const structure = callBaseGetStructure(PropertyAssignmentBase.prototype, this, {
  10915. kind: exports.StructureKind.PropertyAssignment,
  10916. initializer: initializer.getText(),
  10917. });
  10918. delete structure.hasQuestionToken;
  10919. return structure;
  10920. }
  10921. }
  10922. const createBase$z = (ctor) => InitializerExpressionGetableNode(QuestionTokenableNode(NamedNode(ctor)));
  10923. const ShorthandPropertyAssignmentBase = createBase$z(ObjectLiteralElement);
  10924. class ShorthandPropertyAssignment extends ShorthandPropertyAssignmentBase {
  10925. hasObjectAssignmentInitializer() {
  10926. return this.compilerNode.objectAssignmentInitializer != null;
  10927. }
  10928. getObjectAssignmentInitializerOrThrow(message) {
  10929. return common.errors.throwIfNullOrUndefined(this.getObjectAssignmentInitializer(), message ?? "Expected to find an object assignment initializer.", this);
  10930. }
  10931. getObjectAssignmentInitializer() {
  10932. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.objectAssignmentInitializer);
  10933. }
  10934. getEqualsTokenOrThrow(message) {
  10935. return common.errors.throwIfNullOrUndefined(this.getEqualsToken(), message ?? "Expected to find an equals token.", this);
  10936. }
  10937. getEqualsToken() {
  10938. const equalsToken = this.compilerNode.equalsToken;
  10939. if (equalsToken == null)
  10940. return undefined;
  10941. return this._getNodeFromCompilerNode(equalsToken);
  10942. }
  10943. removeObjectAssignmentInitializer() {
  10944. if (!this.hasObjectAssignmentInitializer())
  10945. return this;
  10946. removeChildren({
  10947. children: [this.getEqualsTokenOrThrow(), this.getObjectAssignmentInitializerOrThrow()],
  10948. removePrecedingSpaces: true,
  10949. });
  10950. return this;
  10951. }
  10952. setInitializer(text) {
  10953. const parent = this.getParentSyntaxList() || this.getParentOrThrow();
  10954. const childIndex = this.getChildIndex();
  10955. insertIntoParentTextRange({
  10956. insertPos: this.getStart(),
  10957. newText: this.getText() + `: ${text}`,
  10958. parent,
  10959. replacing: {
  10960. textLength: this.getWidth(),
  10961. },
  10962. });
  10963. return parent.getChildAtIndexIfKindOrThrow(childIndex, common.SyntaxKind.PropertyAssignment);
  10964. }
  10965. set(structure) {
  10966. callBaseSet(ShorthandPropertyAssignmentBase.prototype, this, structure);
  10967. return this;
  10968. }
  10969. getStructure() {
  10970. const structure = callBaseGetStructure(ShorthandPropertyAssignmentBase.prototype, this, {
  10971. kind: exports.StructureKind.ShorthandPropertyAssignment,
  10972. });
  10973. delete structure.hasQuestionToken;
  10974. return structure;
  10975. }
  10976. getValueSymbol() {
  10977. return this._context.typeChecker.getShorthandAssignmentValueSymbol(this);
  10978. }
  10979. getValueSymbolOrThrow(message) {
  10980. return common.errors.throwIfNullOrUndefined(this.getValueSymbol(), message ?? "Expected to find a value symbol.", this);
  10981. }
  10982. }
  10983. const SpreadAssignmentBase = ExpressionedNode(ObjectLiteralElement);
  10984. class SpreadAssignment extends SpreadAssignmentBase {
  10985. set(structure) {
  10986. callBaseSet(SpreadAssignmentBase.prototype, this, structure);
  10987. return this;
  10988. }
  10989. getStructure() {
  10990. return callBaseGetStructure(SpreadAssignmentBase.prototype, this, {
  10991. kind: exports.StructureKind.SpreadAssignment,
  10992. expression: this.getExpression().getText(),
  10993. });
  10994. }
  10995. }
  10996. const OmittedExpressionBase = Expression;
  10997. class OmittedExpression extends OmittedExpressionBase {
  10998. }
  10999. const ParenthesizedExpressionBase = ExpressionedNode(Expression);
  11000. class ParenthesizedExpression extends ParenthesizedExpressionBase {
  11001. }
  11002. const PartiallyEmittedExpressionBase = ExpressionedNode(Expression);
  11003. class PartiallyEmittedExpression extends PartiallyEmittedExpressionBase {
  11004. }
  11005. const PostfixUnaryExpressionBase = UnaryExpression;
  11006. class PostfixUnaryExpression extends PostfixUnaryExpressionBase {
  11007. getOperatorToken() {
  11008. return this.compilerNode.operator;
  11009. }
  11010. getOperand() {
  11011. return this._getNodeFromCompilerNode(this.compilerNode.operand);
  11012. }
  11013. }
  11014. const PrefixUnaryExpressionBase = UnaryExpression;
  11015. class PrefixUnaryExpression extends PrefixUnaryExpressionBase {
  11016. getOperatorToken() {
  11017. return this.compilerNode.operator;
  11018. }
  11019. getOperand() {
  11020. return this._getNodeFromCompilerNode(this.compilerNode.operand);
  11021. }
  11022. }
  11023. const createBase$y = (ctor) => NamedNode(QuestionDotTokenableNode(LeftHandSideExpressionedNode(ctor)));
  11024. const PropertyAccessExpressionBase = createBase$y(MemberExpression);
  11025. class PropertyAccessExpression extends PropertyAccessExpressionBase {
  11026. }
  11027. const createBase$x = (ctor) => TypedNode(ExpressionedNode(ctor));
  11028. const SatisfiesExpressionBase = createBase$x(Expression);
  11029. class SatisfiesExpression extends SatisfiesExpressionBase {
  11030. }
  11031. const SpreadElementBase = ExpressionedNode(Expression);
  11032. class SpreadElement extends SpreadElementBase {
  11033. }
  11034. const SuperElementAccessExpressionBase = SuperExpressionedNode(ElementAccessExpression);
  11035. class SuperElementAccessExpression extends SuperElementAccessExpressionBase {
  11036. }
  11037. const SuperExpressionBase = PrimaryExpression;
  11038. class SuperExpression extends SuperExpressionBase {
  11039. }
  11040. const SuperPropertyAccessExpressionBase = SuperExpressionedNode(PropertyAccessExpression);
  11041. class SuperPropertyAccessExpression extends SuperPropertyAccessExpressionBase {
  11042. }
  11043. const ThisExpressionBase = PrimaryExpression;
  11044. class ThisExpression extends ThisExpressionBase {
  11045. }
  11046. const createBase$w = (ctor) => TypedNode(UnaryExpressionedNode(ctor));
  11047. const TypeAssertionBase = createBase$w(UnaryExpression);
  11048. class TypeAssertion extends TypeAssertionBase {
  11049. }
  11050. const TypeOfExpressionBase = UnaryExpressionedNode(UnaryExpression);
  11051. class TypeOfExpression extends TypeOfExpressionBase {
  11052. }
  11053. const VoidExpressionBase = UnaryExpressionedNode(UnaryExpression);
  11054. class VoidExpression extends VoidExpressionBase {
  11055. }
  11056. const YieldExpressionBase = ExpressionableNode(GeneratorableNode(Expression));
  11057. class YieldExpression extends YieldExpressionBase {
  11058. }
  11059. const StatementBase = ChildOrderableNode(Node);
  11060. class Statement extends StatementBase {
  11061. remove() {
  11062. removeStatementedNodeChild(this);
  11063. }
  11064. }
  11065. function StatementedNode(Base) {
  11066. return class extends Base {
  11067. getStatements() {
  11068. const statementsContainer = this._getCompilerStatementsContainer();
  11069. const statements = statementsContainer?.statements ?? [];
  11070. return statements.map(s => this._getNodeFromCompilerNode(s));
  11071. }
  11072. getStatementsWithComments() {
  11073. return this._getCompilerStatementsWithComments().map(s => this._getNodeFromCompilerNode(s));
  11074. }
  11075. getStatement(findFunction) {
  11076. return this.getStatements().find(findFunction);
  11077. }
  11078. getStatementOrThrow(findFunction, message) {
  11079. return common.errors.throwIfNullOrUndefined(this.getStatement(findFunction), message ?? "Expected to find a statement matching the provided condition.", this);
  11080. }
  11081. getStatementByKind(kind) {
  11082. const statement = this._getCompilerStatementsWithComments().find(s => s.kind === kind);
  11083. return this._getNodeFromCompilerNodeIfExists(statement);
  11084. }
  11085. getStatementByKindOrThrow(kind, message) {
  11086. return common.errors.throwIfNullOrUndefined(this.getStatementByKind(kind), message ?? `Expected to find a statement with syntax kind ${common.getSyntaxKindName(kind)}.`, this);
  11087. }
  11088. addStatements(textOrWriterFunction) {
  11089. return this.insertStatements(this._getCompilerStatementsWithComments().length, textOrWriterFunction);
  11090. }
  11091. insertStatements(index, statements) {
  11092. addBodyIfNotExists(this);
  11093. const writerFunction = (writer) => {
  11094. const statementsPrinter = this._context.structurePrinterFactory.forStatement({ isAmbient: isNodeAmbientOrInAmbientContext(this) });
  11095. statementsPrinter.printTexts(writer, statements);
  11096. };
  11097. return getChildSyntaxList.call(this).insertChildText(index, writerFunction);
  11098. function getChildSyntaxList() {
  11099. const childSyntaxList = this.getChildSyntaxListOrThrow();
  11100. if (Node.isCaseClause(this) || Node.isDefaultClause(this)) {
  11101. const block = childSyntaxList.getFirstChildIfKind(common.SyntaxKind.Block);
  11102. if (block != null)
  11103. return block.getChildSyntaxListOrThrow();
  11104. }
  11105. return childSyntaxList;
  11106. }
  11107. }
  11108. removeStatement(index) {
  11109. index = verifyAndGetIndex(index, this._getCompilerStatementsWithComments().length - 1);
  11110. return this.removeStatements([index, index]);
  11111. }
  11112. removeStatements(indexRange) {
  11113. const statements = this.getStatementsWithComments();
  11114. common.errors.throwIfRangeOutOfRange(indexRange, [0, statements.length], "indexRange");
  11115. removeStatementedNodeChildren(statements.slice(indexRange[0], indexRange[1] + 1));
  11116. return this;
  11117. }
  11118. addClass(structure) {
  11119. return this.addClasses([structure])[0];
  11120. }
  11121. addClasses(structures) {
  11122. return this.insertClasses(this._getCompilerStatementsWithComments().length, structures);
  11123. }
  11124. insertClass(index, structure) {
  11125. return this.insertClasses(index, [structure])[0];
  11126. }
  11127. insertClasses(index, structures) {
  11128. return this._insertChildren({
  11129. expectedKind: common.SyntaxKind.ClassDeclaration,
  11130. index,
  11131. structures,
  11132. write: (writer, info) => {
  11133. this._standardWrite(writer, info, () => {
  11134. this._context.structurePrinterFactory.forClassDeclaration({ isAmbient: isNodeAmbientOrInAmbientContext(this) })
  11135. .printTexts(writer, structures);
  11136. });
  11137. },
  11138. });
  11139. }
  11140. getClasses() {
  11141. return this.getStatements().filter(Node.isClassDeclaration);
  11142. }
  11143. getClass(nameOrFindFunction) {
  11144. return getNodeByNameOrFindFunction(this.getClasses(), nameOrFindFunction);
  11145. }
  11146. getClassOrThrow(nameOrFindFunction) {
  11147. return common.errors.throwIfNullOrUndefined(this.getClass(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("class", nameOrFindFunction));
  11148. }
  11149. addEnum(structure) {
  11150. return this.addEnums([structure])[0];
  11151. }
  11152. addEnums(structures) {
  11153. return this.insertEnums(this._getCompilerStatementsWithComments().length, structures);
  11154. }
  11155. insertEnum(index, structure) {
  11156. return this.insertEnums(index, [structure])[0];
  11157. }
  11158. insertEnums(index, structures) {
  11159. return this._insertChildren({
  11160. expectedKind: common.SyntaxKind.EnumDeclaration,
  11161. index,
  11162. structures,
  11163. write: (writer, info) => {
  11164. this._standardWrite(writer, info, () => {
  11165. this._context.structurePrinterFactory.forEnumDeclaration().printTexts(writer, structures);
  11166. });
  11167. },
  11168. });
  11169. }
  11170. getEnums() {
  11171. return this.getStatements().filter(Node.isEnumDeclaration);
  11172. }
  11173. getEnum(nameOrFindFunction) {
  11174. return getNodeByNameOrFindFunction(this.getEnums(), nameOrFindFunction);
  11175. }
  11176. getEnumOrThrow(nameOrFindFunction) {
  11177. return common.errors.throwIfNullOrUndefined(this.getEnum(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("enum", nameOrFindFunction));
  11178. }
  11179. addFunction(structure) {
  11180. return this.addFunctions([structure])[0];
  11181. }
  11182. addFunctions(structures) {
  11183. return this.insertFunctions(this._getCompilerStatementsWithComments().length, structures);
  11184. }
  11185. insertFunction(index, structure) {
  11186. return this.insertFunctions(index, [structure])[0];
  11187. }
  11188. insertFunctions(index, structures) {
  11189. return this._insertChildren({
  11190. expectedKind: common.SyntaxKind.FunctionDeclaration,
  11191. index,
  11192. structures,
  11193. write: (writer, info) => {
  11194. this._standardWrite(writer, info, () => {
  11195. this._context.structurePrinterFactory.forFunctionDeclaration({
  11196. isAmbient: isNodeAmbientOrInAmbientContext(this),
  11197. }).printTexts(writer, structures);
  11198. }, {
  11199. previousNewLine: previousMember => structures[0].hasDeclareKeyword === true
  11200. && Node.isFunctionDeclaration(previousMember)
  11201. && previousMember.getBody() == null,
  11202. nextNewLine: nextMember => structures[structures.length - 1].hasDeclareKeyword === true
  11203. && Node.isFunctionDeclaration(nextMember)
  11204. && nextMember.getBody() == null,
  11205. });
  11206. },
  11207. });
  11208. }
  11209. getFunctions() {
  11210. return this.getStatements().filter(Node.isFunctionDeclaration).filter(f => f.isAmbient() || f.isImplementation());
  11211. }
  11212. getFunction(nameOrFindFunction) {
  11213. return getNodeByNameOrFindFunction(this.getFunctions(), nameOrFindFunction);
  11214. }
  11215. getFunctionOrThrow(nameOrFindFunction) {
  11216. return common.errors.throwIfNullOrUndefined(this.getFunction(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("function", nameOrFindFunction));
  11217. }
  11218. addInterface(structure) {
  11219. return this.addInterfaces([structure])[0];
  11220. }
  11221. addInterfaces(structures) {
  11222. return this.insertInterfaces(this._getCompilerStatementsWithComments().length, structures);
  11223. }
  11224. insertInterface(index, structure) {
  11225. return this.insertInterfaces(index, [structure])[0];
  11226. }
  11227. insertInterfaces(index, structures) {
  11228. return this._insertChildren({
  11229. expectedKind: common.SyntaxKind.InterfaceDeclaration,
  11230. index,
  11231. structures,
  11232. write: (writer, info) => {
  11233. this._standardWrite(writer, info, () => {
  11234. this._context.structurePrinterFactory.forInterfaceDeclaration().printTexts(writer, structures);
  11235. });
  11236. },
  11237. });
  11238. }
  11239. getInterfaces() {
  11240. return this.getStatements().filter(Node.isInterfaceDeclaration);
  11241. }
  11242. getInterface(nameOrFindFunction) {
  11243. return getNodeByNameOrFindFunction(this.getInterfaces(), nameOrFindFunction);
  11244. }
  11245. getInterfaceOrThrow(nameOrFindFunction) {
  11246. return common.errors.throwIfNullOrUndefined(this.getInterface(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("interface", nameOrFindFunction));
  11247. }
  11248. addModule(structure) {
  11249. return this.addModules([structure])[0];
  11250. }
  11251. addModules(structures) {
  11252. return this.insertModules(this._getCompilerStatementsWithComments().length, structures);
  11253. }
  11254. insertModule(index, structure) {
  11255. return this.insertModules(index, [structure])[0];
  11256. }
  11257. insertModules(index, structures) {
  11258. return this._insertChildren({
  11259. expectedKind: common.SyntaxKind.ModuleDeclaration,
  11260. index,
  11261. structures,
  11262. write: (writer, info) => {
  11263. this._standardWrite(writer, info, () => {
  11264. this._context.structurePrinterFactory.forModuleDeclaration({ isAmbient: isNodeAmbientOrInAmbientContext(this) })
  11265. .printTexts(writer, structures);
  11266. });
  11267. },
  11268. });
  11269. }
  11270. getModules() {
  11271. return this.getStatements().filter(Node.isModuleDeclaration);
  11272. }
  11273. getModule(nameOrFindFunction) {
  11274. return getNodeByNameOrFindFunction(this.getModules(), nameOrFindFunction);
  11275. }
  11276. getModuleOrThrow(nameOrFindFunction) {
  11277. return common.errors.throwIfNullOrUndefined(this.getModule(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("module", nameOrFindFunction));
  11278. }
  11279. addTypeAlias(structure) {
  11280. return this.addTypeAliases([structure])[0];
  11281. }
  11282. addTypeAliases(structures) {
  11283. return this.insertTypeAliases(this._getCompilerStatementsWithComments().length, structures);
  11284. }
  11285. insertTypeAlias(index, structure) {
  11286. return this.insertTypeAliases(index, [structure])[0];
  11287. }
  11288. insertTypeAliases(index, structures) {
  11289. return this._insertChildren({
  11290. expectedKind: common.SyntaxKind.TypeAliasDeclaration,
  11291. index,
  11292. structures,
  11293. write: (writer, info) => {
  11294. this._standardWrite(writer, info, () => {
  11295. this._context.structurePrinterFactory.forTypeAliasDeclaration().printTexts(writer, structures);
  11296. }, {
  11297. previousNewLine: previousMember => Node.isTypeAliasDeclaration(previousMember),
  11298. nextNewLine: nextMember => Node.isTypeAliasDeclaration(nextMember),
  11299. });
  11300. },
  11301. });
  11302. }
  11303. getTypeAliases() {
  11304. return this.getStatements().filter(Node.isTypeAliasDeclaration);
  11305. }
  11306. getTypeAlias(nameOrFindFunction) {
  11307. return getNodeByNameOrFindFunction(this.getTypeAliases(), nameOrFindFunction);
  11308. }
  11309. getTypeAliasOrThrow(nameOrFindFunction) {
  11310. return common.errors.throwIfNullOrUndefined(this.getTypeAlias(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("type alias", nameOrFindFunction));
  11311. }
  11312. getVariableStatements() {
  11313. return this.getStatements().filter(Node.isVariableStatement);
  11314. }
  11315. getVariableStatement(nameOrFindFunction) {
  11316. return this.getVariableStatements().find(getFindFunction());
  11317. function getFindFunction() {
  11318. if (typeof nameOrFindFunction === "string")
  11319. return (statement) => statement.getDeclarations().some(d => nodeHasName(d, nameOrFindFunction));
  11320. return nameOrFindFunction;
  11321. }
  11322. }
  11323. getVariableStatementOrThrow(nameOrFindFunction, message) {
  11324. return common.errors.throwIfNullOrUndefined(this.getVariableStatement(nameOrFindFunction), message ?? "Expected to find a variable statement that matched the provided condition.", this);
  11325. }
  11326. addVariableStatement(structure) {
  11327. return this.addVariableStatements([structure])[0];
  11328. }
  11329. addVariableStatements(structures) {
  11330. return this.insertVariableStatements(this._getCompilerStatementsWithComments().length, structures);
  11331. }
  11332. insertVariableStatement(index, structure) {
  11333. return this.insertVariableStatements(index, [structure])[0];
  11334. }
  11335. insertVariableStatements(index, structures) {
  11336. return this._insertChildren({
  11337. expectedKind: common.SyntaxKind.VariableStatement,
  11338. index,
  11339. structures,
  11340. write: (writer, info) => {
  11341. this._standardWrite(writer, info, () => {
  11342. this._context.structurePrinterFactory.forVariableStatement().printTexts(writer, structures);
  11343. }, {
  11344. previousNewLine: previousMember => Node.isVariableStatement(previousMember),
  11345. nextNewLine: nextMember => Node.isVariableStatement(nextMember),
  11346. });
  11347. },
  11348. });
  11349. }
  11350. getVariableDeclarations() {
  11351. const variables = [];
  11352. for (const list of this.getVariableStatements())
  11353. variables.push(...list.getDeclarations());
  11354. return variables;
  11355. }
  11356. getVariableDeclaration(nameOrFindFunction) {
  11357. return getNodeByNameOrFindFunction(this.getVariableDeclarations(), nameOrFindFunction);
  11358. }
  11359. getVariableDeclarationOrThrow(nameOrFindFunction) {
  11360. return common.errors.throwIfNullOrUndefined(this.getVariableDeclaration(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("variable declaration", nameOrFindFunction));
  11361. }
  11362. getStructure() {
  11363. const structure = {};
  11364. if (Node.isBodyable(this) && !this.hasBody())
  11365. structure.statements = undefined;
  11366. else {
  11367. structure.statements = this.getStatements().map(s => {
  11368. if (Node._hasStructure(s))
  11369. return s.getStructure();
  11370. return s.getText({ trimLeadingIndentation: true });
  11371. });
  11372. }
  11373. return callBaseGetStructure(Base.prototype, this, structure);
  11374. }
  11375. set(structure) {
  11376. if (Node.isBodyable(this) && structure.statements == null && structure.hasOwnProperty(common.nameof(structure, "statements")))
  11377. this.removeBody();
  11378. else if (structure.statements != null) {
  11379. const statementCount = this._getCompilerStatementsWithComments().length;
  11380. if (statementCount > 0)
  11381. this.removeStatements([0, statementCount - 1]);
  11382. }
  11383. callBaseSet(Base.prototype, this, structure);
  11384. if (structure.statements != null)
  11385. this.addStatements(structure.statements);
  11386. return this;
  11387. }
  11388. _getCompilerStatementsWithComments() {
  11389. const statementsContainer = this._getCompilerStatementsContainer();
  11390. if (statementsContainer == null)
  11391. return [];
  11392. else {
  11393. return ExtendedParser.getContainerArray(statementsContainer, this._sourceFile.compilerNode);
  11394. }
  11395. }
  11396. _getCompilerStatementsContainer() {
  11397. if (Node.isSourceFile(this) || Node.isCaseClause(this) || Node.isDefaultClause(this))
  11398. return this.compilerNode;
  11399. else if (Node.isModuleDeclaration(this)) {
  11400. const body = this._getInnerBody();
  11401. if (body == null)
  11402. return undefined;
  11403. else
  11404. return body.compilerNode;
  11405. }
  11406. else if (Node.isBodyable(this) || Node.isBodied(this))
  11407. return this.getBody()?.compilerNode;
  11408. else if (Node.isBlock(this) || Node.isModuleBlock(this))
  11409. return this.compilerNode;
  11410. else
  11411. throw new common.errors.NotImplementedError(`Could not find the statements for node kind: ${this.getKindName()}, text: ${this.getText()}`);
  11412. }
  11413. _insertChildren(opts) {
  11414. addBodyIfNotExists(this);
  11415. return insertIntoBracesOrSourceFileWithGetChildren({
  11416. expectedKind: opts.expectedKind,
  11417. getIndexedChildren: () => this.getStatementsWithComments(),
  11418. index: opts.index,
  11419. parent: this,
  11420. structures: opts.structures,
  11421. write: (writer, info) => opts.write(writer, info),
  11422. });
  11423. }
  11424. _standardWrite(writer, info, writeStructures, opts = {}) {
  11425. if (info.previousMember != null && (opts.previousNewLine == null || !opts.previousNewLine(info.previousMember))
  11426. && !Node.isCommentNode(info.previousMember)) {
  11427. writer.blankLine();
  11428. }
  11429. else if (!info.isStartOfFile) {
  11430. writer.newLineIfLastNot();
  11431. }
  11432. writeStructures();
  11433. if (info.nextMember != null && (opts.nextNewLine == null || !opts.nextNewLine(info.nextMember)))
  11434. writer.blankLine();
  11435. else
  11436. writer.newLineIfLastNot();
  11437. }
  11438. };
  11439. }
  11440. function addBodyIfNotExists(node) {
  11441. if (Node.isBodyable(node) && !node.hasBody())
  11442. node.addBody();
  11443. }
  11444. const createBase$v = (ctor) => TextInsertableNode(StatementedNode(ctor));
  11445. const BlockBase = createBase$v(Statement);
  11446. class Block extends BlockBase {
  11447. }
  11448. class BreakStatement extends Statement {
  11449. getLabel() {
  11450. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.label);
  11451. }
  11452. getLabelOrThrow(message) {
  11453. return common.errors.throwIfNullOrUndefined(this.getLabel(), message ?? "Expected to find a label.", this);
  11454. }
  11455. }
  11456. const CaseBlockBase = TextInsertableNode(Node);
  11457. class CaseBlock extends CaseBlockBase {
  11458. getClauses() {
  11459. const clauses = this.compilerNode.clauses || [];
  11460. return clauses.map(s => this._getNodeFromCompilerNode(s));
  11461. }
  11462. removeClause(index) {
  11463. index = verifyAndGetIndex(index, this.getClauses().length - 1);
  11464. return this.removeClauses([index, index]);
  11465. }
  11466. removeClauses(indexRange) {
  11467. const clauses = this.getClauses();
  11468. common.errors.throwIfRangeOutOfRange(indexRange, [0, clauses.length], "indexRange");
  11469. removeClausedNodeChildren(clauses.slice(indexRange[0], indexRange[1] + 1));
  11470. return this;
  11471. }
  11472. }
  11473. const createBase$u = (ctor) => JSDocableNode(ExpressionedNode(TextInsertableNode(StatementedNode(ctor))));
  11474. const CaseClauseBase = createBase$u(Node);
  11475. class CaseClause extends CaseClauseBase {
  11476. remove() {
  11477. removeClausedNodeChild(this);
  11478. }
  11479. }
  11480. const CatchClauseBase = Node;
  11481. class CatchClause extends CatchClauseBase {
  11482. getBlock() {
  11483. return this._getNodeFromCompilerNode(this.compilerNode.block);
  11484. }
  11485. getVariableDeclaration() {
  11486. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.variableDeclaration);
  11487. }
  11488. getVariableDeclarationOrThrow(message) {
  11489. return common.errors.throwIfNullOrUndefined(this.getVariableDeclaration(), message ?? "Expected to find a variable declaration.", this);
  11490. }
  11491. }
  11492. class CommentStatement extends Statement {
  11493. }
  11494. class ContinueStatement extends Statement {
  11495. getLabel() {
  11496. return this.compilerNode.label == null
  11497. ? undefined
  11498. : this._getNodeFromCompilerNode(this.compilerNode.label);
  11499. }
  11500. getLabelOrThrow(message) {
  11501. return common.errors.throwIfNullOrUndefined(this.getLabel(), message ?? "Expected to find a label.", this);
  11502. }
  11503. }
  11504. const DebuggerStatementBase = Statement;
  11505. class DebuggerStatement extends DebuggerStatementBase {
  11506. }
  11507. const createBase$t = (ctor) => TextInsertableNode(StatementedNode(ctor));
  11508. const DefaultClauseBase = createBase$t(Node);
  11509. class DefaultClause extends DefaultClauseBase {
  11510. remove() {
  11511. removeClausedNodeChild(this);
  11512. }
  11513. }
  11514. class IterationStatement extends Statement {
  11515. getStatement() {
  11516. return this._getNodeFromCompilerNode(this.compilerNode.statement);
  11517. }
  11518. }
  11519. const DoStatementBase = ExpressionedNode(IterationStatement);
  11520. class DoStatement extends DoStatementBase {
  11521. }
  11522. const EmptyStatementBase = Statement;
  11523. class EmptyStatement extends EmptyStatementBase {
  11524. }
  11525. const ExpressionStatementBase = ExpressionedNode(JSDocableNode(Statement));
  11526. class ExpressionStatement extends ExpressionStatementBase {
  11527. }
  11528. const ForInStatementBase = ExpressionedNode(IterationStatement);
  11529. class ForInStatement extends ForInStatementBase {
  11530. getInitializer() {
  11531. return this._getNodeFromCompilerNode(this.compilerNode.initializer);
  11532. }
  11533. }
  11534. const ForOfStatementBase = ExpressionedNode(AwaitableNode(IterationStatement));
  11535. class ForOfStatement extends ForOfStatementBase {
  11536. getInitializer() {
  11537. return this._getNodeFromCompilerNode(this.compilerNode.initializer);
  11538. }
  11539. }
  11540. const ForStatementBase = IterationStatement;
  11541. class ForStatement extends ForStatementBase {
  11542. getInitializer() {
  11543. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.initializer);
  11544. }
  11545. getInitializerOrThrow(message) {
  11546. return common.errors.throwIfNullOrUndefined(this.getInitializer(), message ?? "Expected to find an initializer.", this);
  11547. }
  11548. getCondition() {
  11549. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.condition);
  11550. }
  11551. getConditionOrThrow(message) {
  11552. return common.errors.throwIfNullOrUndefined(this.getCondition(), message ?? "Expected to find a condition.", this);
  11553. }
  11554. getIncrementor() {
  11555. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.incrementor);
  11556. }
  11557. getIncrementorOrThrow(message) {
  11558. return common.errors.throwIfNullOrUndefined(this.getIncrementor(), message ?? "Expected to find an incrementor.", this);
  11559. }
  11560. }
  11561. const IfStatementBase = ExpressionedNode(Statement);
  11562. class IfStatement extends IfStatementBase {
  11563. getThenStatement() {
  11564. return this._getNodeFromCompilerNode(this.compilerNode.thenStatement);
  11565. }
  11566. getElseStatement() {
  11567. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.elseStatement);
  11568. }
  11569. remove() {
  11570. const nodes = [];
  11571. if (Node.isIfStatement(this.getParentOrThrow()))
  11572. nodes.push(this.getPreviousSiblingIfKindOrThrow(common.SyntaxKind.ElseKeyword));
  11573. nodes.push(this);
  11574. removeStatementedNodeChildren(nodes);
  11575. }
  11576. }
  11577. const LabeledStatementBase = JSDocableNode(Statement);
  11578. class LabeledStatement extends LabeledStatementBase {
  11579. getLabel() {
  11580. return this._getNodeFromCompilerNode(this.compilerNode.label);
  11581. }
  11582. getStatement() {
  11583. return this._getNodeFromCompilerNode(this.compilerNode.statement);
  11584. }
  11585. }
  11586. const NotEmittedStatementBase = Statement;
  11587. class NotEmittedStatement extends NotEmittedStatementBase {
  11588. }
  11589. const ReturnStatementBase = ExpressionableNode(Statement);
  11590. class ReturnStatement extends ReturnStatementBase {
  11591. }
  11592. const SwitchStatementBase = ExpressionedNode(Statement);
  11593. class SwitchStatement extends SwitchStatementBase {
  11594. getCaseBlock() {
  11595. return this._getNodeFromCompilerNode(this.compilerNode.caseBlock);
  11596. }
  11597. getClauses() {
  11598. return this.getCaseBlock().getClauses();
  11599. }
  11600. removeClause(index) {
  11601. return this.getCaseBlock().removeClause(index);
  11602. }
  11603. removeClauses(indexRange) {
  11604. return this.getCaseBlock().removeClauses(indexRange);
  11605. }
  11606. }
  11607. const ThrowStatementBase = ExpressionedNode(Statement);
  11608. class ThrowStatement extends ThrowStatementBase {
  11609. }
  11610. const TryStatementBase = Statement;
  11611. class TryStatement extends TryStatementBase {
  11612. getTryBlock() {
  11613. return this._getNodeFromCompilerNode(this.compilerNode.tryBlock);
  11614. }
  11615. getCatchClause() {
  11616. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.catchClause);
  11617. }
  11618. getCatchClauseOrThrow(message) {
  11619. return common.errors.throwIfNullOrUndefined(this.getCatchClause(), message ?? "Expected to find a catch clause.", this);
  11620. }
  11621. getFinallyBlock() {
  11622. if (this.compilerNode.finallyBlock == null || this.compilerNode.finallyBlock.getFullWidth() === 0)
  11623. return undefined;
  11624. return this._getNodeFromCompilerNode(this.compilerNode.finallyBlock);
  11625. }
  11626. getFinallyBlockOrThrow(message) {
  11627. return common.errors.throwIfNullOrUndefined(this.getFinallyBlock(), message ?? "Expected to find a finally block.", this);
  11628. }
  11629. }
  11630. const ExportAssignmentBase = ExpressionedNode(JSDocableNode(Statement));
  11631. class ExportAssignment extends ExportAssignmentBase {
  11632. isExportEquals() {
  11633. return this.compilerNode.isExportEquals || false;
  11634. }
  11635. setIsExportEquals(value) {
  11636. if (this.isExportEquals() === value)
  11637. return this;
  11638. if (value)
  11639. this.getFirstChildByKindOrThrow(common.SyntaxKind.DefaultKeyword).replaceWithText("=");
  11640. else
  11641. this.getFirstChildByKindOrThrow(common.SyntaxKind.EqualsToken).replaceWithText("default");
  11642. return this;
  11643. }
  11644. set(structure) {
  11645. callBaseSet(ExportAssignmentBase.prototype, this, structure);
  11646. if (structure.expression != null)
  11647. this.setExpression(structure.expression);
  11648. if (structure.isExportEquals != null)
  11649. this.setIsExportEquals(structure.isExportEquals);
  11650. return this;
  11651. }
  11652. getStructure() {
  11653. return callBaseGetStructure(Statement.prototype, this, {
  11654. kind: exports.StructureKind.ExportAssignment,
  11655. expression: this.getExpression().getText(),
  11656. isExportEquals: this.isExportEquals(),
  11657. });
  11658. }
  11659. }
  11660. const ExportDeclarationBase = Statement;
  11661. class ExportDeclaration extends ExportDeclarationBase {
  11662. isTypeOnly() {
  11663. return this.compilerNode.isTypeOnly;
  11664. }
  11665. setIsTypeOnly(value) {
  11666. if (this.isTypeOnly() === value)
  11667. return this;
  11668. if (value) {
  11669. insertIntoParentTextRange({
  11670. parent: this,
  11671. insertPos: (this.getNodeProperty("exportClause") ?? this.getFirstChildByKindOrThrow(common.SyntaxKind.AsteriskToken)).getStart(),
  11672. newText: "type ",
  11673. });
  11674. }
  11675. else {
  11676. const typeKeyword = this.getFirstChildByKindOrThrow(common.ts.SyntaxKind.TypeKeyword);
  11677. removeChildren({
  11678. children: [typeKeyword],
  11679. removeFollowingSpaces: true,
  11680. });
  11681. }
  11682. return this;
  11683. }
  11684. getNamespaceExport() {
  11685. const exportClause = this.getNodeProperty("exportClause");
  11686. return exportClause != null && Node.isNamespaceExport(exportClause) ? exportClause : undefined;
  11687. }
  11688. getNamespaceExportOrThrow(message) {
  11689. return common.errors.throwIfNullOrUndefined(this.getNamespaceExport(), message ?? "Expected to find a namespace export.", this);
  11690. }
  11691. setNamespaceExport(name) {
  11692. const exportClause = this.getNodeProperty("exportClause");
  11693. const newText = common.StringUtils.isNullOrWhitespace(name) ? "*" : `* as ${name}`;
  11694. if (exportClause == null) {
  11695. const asteriskToken = this.getFirstChildByKindOrThrow(common.SyntaxKind.AsteriskToken);
  11696. insertIntoParentTextRange({
  11697. insertPos: asteriskToken.getStart(),
  11698. parent: this,
  11699. newText,
  11700. replacing: {
  11701. textLength: 1,
  11702. },
  11703. });
  11704. }
  11705. else if (Node.isNamespaceExport(exportClause))
  11706. exportClause.getNameNode().replaceWithText(name);
  11707. else {
  11708. insertIntoParentTextRange({
  11709. insertPos: exportClause.getStart(),
  11710. parent: this,
  11711. newText,
  11712. replacing: {
  11713. textLength: exportClause.getWidth(),
  11714. },
  11715. });
  11716. }
  11717. return this;
  11718. }
  11719. setModuleSpecifier(textOrSourceFile) {
  11720. const text = typeof textOrSourceFile === "string" ? textOrSourceFile : this._sourceFile.getRelativePathAsModuleSpecifierTo(textOrSourceFile);
  11721. if (common.StringUtils.isNullOrEmpty(text)) {
  11722. this.removeModuleSpecifier();
  11723. return this;
  11724. }
  11725. const stringLiteral = this.getModuleSpecifier();
  11726. if (stringLiteral == null) {
  11727. const semiColonToken = this.getLastChildIfKind(common.SyntaxKind.SemicolonToken);
  11728. const quoteKind = this._context.manipulationSettings.getQuoteKind();
  11729. insertIntoParentTextRange({
  11730. insertPos: semiColonToken != null ? semiColonToken.getPos() : this.getEnd(),
  11731. parent: this,
  11732. newText: ` from ${quoteKind}${text}${quoteKind}`,
  11733. });
  11734. }
  11735. else {
  11736. stringLiteral.setLiteralValue(text);
  11737. }
  11738. return this;
  11739. }
  11740. getModuleSpecifier() {
  11741. const moduleSpecifier = this._getNodeFromCompilerNodeIfExists(this.compilerNode.moduleSpecifier);
  11742. if (moduleSpecifier == null)
  11743. return undefined;
  11744. if (!Node.isStringLiteral(moduleSpecifier))
  11745. throw new common.errors.InvalidOperationError("Expected the module specifier to be a string literal.");
  11746. return moduleSpecifier;
  11747. }
  11748. getModuleSpecifierValue() {
  11749. const moduleSpecifier = this.getModuleSpecifier();
  11750. return moduleSpecifier?.getLiteralValue();
  11751. }
  11752. getModuleSpecifierSourceFileOrThrow(message) {
  11753. return common.errors.throwIfNullOrUndefined(this.getModuleSpecifierSourceFile(), message ?? `A module specifier source file was expected.`, this);
  11754. }
  11755. getModuleSpecifierSourceFile() {
  11756. const stringLiteral = this.getLastChildByKind(common.SyntaxKind.StringLiteral);
  11757. if (stringLiteral == null)
  11758. return undefined;
  11759. const symbol = stringLiteral.getSymbol();
  11760. if (symbol == null)
  11761. return undefined;
  11762. const declaration = symbol.getDeclarations()[0];
  11763. return declaration != null && Node.isSourceFile(declaration) ? declaration : undefined;
  11764. }
  11765. isModuleSpecifierRelative() {
  11766. const moduleSpecifierValue = this.getModuleSpecifierValue();
  11767. if (moduleSpecifierValue == null)
  11768. return false;
  11769. return ModuleUtils.isModuleSpecifierRelative(moduleSpecifierValue);
  11770. }
  11771. removeModuleSpecifier() {
  11772. const moduleSpecifier = this.getModuleSpecifier();
  11773. if (moduleSpecifier == null)
  11774. return this;
  11775. if (!this.hasNamedExports())
  11776. throw new common.errors.InvalidOperationError(`Cannot remove the module specifier from an export declaration that has no named exports.`);
  11777. removeChildren({
  11778. children: [this.getFirstChildByKindOrThrow(common.SyntaxKind.FromKeyword), moduleSpecifier],
  11779. removePrecedingNewLines: true,
  11780. removePrecedingSpaces: true,
  11781. });
  11782. return this;
  11783. }
  11784. hasModuleSpecifier() {
  11785. return this.getLastChildByKind(common.SyntaxKind.StringLiteral) != null;
  11786. }
  11787. isNamespaceExport() {
  11788. return !this.hasNamedExports();
  11789. }
  11790. hasNamedExports() {
  11791. return this.compilerNode.exportClause?.kind === common.SyntaxKind.NamedExports;
  11792. }
  11793. addNamedExport(namedExport) {
  11794. return this.addNamedExports([namedExport])[0];
  11795. }
  11796. addNamedExports(namedExports) {
  11797. return this.insertNamedExports(this.getNamedExports().length, namedExports);
  11798. }
  11799. insertNamedExport(index, namedExport) {
  11800. return this.insertNamedExports(index, [namedExport])[0];
  11801. }
  11802. insertNamedExports(index, namedExports) {
  11803. if (!(namedExports instanceof Function) && common.ArrayUtils.isNullOrEmpty(namedExports))
  11804. return [];
  11805. const originalNamedExports = this.getNamedExports();
  11806. const writer = this._getWriterWithIndentation();
  11807. const namedExportStructurePrinter = this._context.structurePrinterFactory.forNamedImportExportSpecifier();
  11808. index = verifyAndGetIndex(index, originalNamedExports.length);
  11809. const exportClause = this.getNodeProperty("exportClause");
  11810. if (exportClause == null) {
  11811. namedExportStructurePrinter.printTextsWithBraces(writer, namedExports);
  11812. const asteriskToken = this.getFirstChildByKindOrThrow(common.SyntaxKind.AsteriskToken);
  11813. insertIntoParentTextRange({
  11814. insertPos: asteriskToken.getStart(),
  11815. parent: this,
  11816. newText: writer.toString(),
  11817. replacing: {
  11818. textLength: 1,
  11819. },
  11820. });
  11821. }
  11822. else if (exportClause.getKind() === common.SyntaxKind.NamespaceExport) {
  11823. namedExportStructurePrinter.printTextsWithBraces(writer, namedExports);
  11824. insertIntoParentTextRange({
  11825. insertPos: exportClause.getStart(),
  11826. parent: this,
  11827. newText: writer.toString(),
  11828. replacing: {
  11829. textLength: exportClause.getWidth(),
  11830. },
  11831. });
  11832. }
  11833. else {
  11834. namedExportStructurePrinter.printTexts(writer, namedExports);
  11835. insertIntoCommaSeparatedNodes({
  11836. parent: this.getFirstChildByKindOrThrow(common.SyntaxKind.NamedExports).getFirstChildByKindOrThrow(common.SyntaxKind.SyntaxList),
  11837. currentNodes: originalNamedExports,
  11838. insertIndex: index,
  11839. newText: writer.toString(),
  11840. surroundWithSpaces: this._context.getFormatCodeSettings().insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces,
  11841. useTrailingCommas: false,
  11842. });
  11843. }
  11844. const newNamedExports = this.getNamedExports();
  11845. return getNodesToReturn(originalNamedExports, newNamedExports, index, false);
  11846. }
  11847. getNamedExports() {
  11848. const namedExports = this.compilerNode.exportClause;
  11849. if (namedExports == null || common.ts.isNamespaceExport(namedExports))
  11850. return [];
  11851. return namedExports.elements.map(e => this._getNodeFromCompilerNode(e));
  11852. }
  11853. toNamespaceExport() {
  11854. if (!this.hasModuleSpecifier())
  11855. throw new common.errors.InvalidOperationError("Cannot change to a namespace export when no module specifier exists.");
  11856. const namedExportsNode = this.getNodeProperty("exportClause");
  11857. if (namedExportsNode == null)
  11858. return this;
  11859. insertIntoParentTextRange({
  11860. parent: this,
  11861. newText: "*",
  11862. insertPos: namedExportsNode.getStart(),
  11863. replacing: {
  11864. textLength: namedExportsNode.getWidth(),
  11865. },
  11866. });
  11867. return this;
  11868. }
  11869. setAttributes(elements) {
  11870. let attributes = this.getAttributes();
  11871. if (attributes) {
  11872. if (elements)
  11873. attributes.setElements(elements);
  11874. else
  11875. attributes.remove();
  11876. }
  11877. else if (elements) {
  11878. const printer = this._context.structurePrinterFactory.forImportAttribute();
  11879. const writer = this._context.createWriter();
  11880. writer.space();
  11881. printer.printAttributes(writer, elements);
  11882. insertIntoParentTextRange({
  11883. parent: this,
  11884. newText: writer.toString(),
  11885. insertPos: this.getSourceFile().getFullText()[this.getEnd() - 1] === ";" ? this.getEnd() - 1 : this.getEnd(),
  11886. });
  11887. }
  11888. return this;
  11889. }
  11890. getAttributes() {
  11891. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.attributes);
  11892. }
  11893. set(structure) {
  11894. callBaseSet(ExportDeclarationBase.prototype, this, structure);
  11895. if (structure.namedExports != null) {
  11896. setEmptyNamedExport(this);
  11897. this.addNamedExports(structure.namedExports);
  11898. }
  11899. else if (structure.hasOwnProperty(common.nameof(structure, "namedExports")) && structure.moduleSpecifier == null) {
  11900. this.toNamespaceExport();
  11901. }
  11902. if (structure.moduleSpecifier != null)
  11903. this.setModuleSpecifier(structure.moduleSpecifier);
  11904. else if (structure.hasOwnProperty(common.nameof(structure, "moduleSpecifier")))
  11905. this.removeModuleSpecifier();
  11906. if (structure.namedExports == null && structure.hasOwnProperty(common.nameof(structure, "namedExports")))
  11907. this.toNamespaceExport();
  11908. if (structure.namespaceExport != null)
  11909. this.setNamespaceExport(structure.namespaceExport);
  11910. if (structure.isTypeOnly != null)
  11911. this.setIsTypeOnly(structure.isTypeOnly);
  11912. if (structure.hasOwnProperty(common.nameof(structure, "attributes")))
  11913. this.setAttributes(structure.attributes);
  11914. return this;
  11915. }
  11916. getStructure() {
  11917. const moduleSpecifier = this.getModuleSpecifier();
  11918. const attributes = this.getAttributes();
  11919. return callBaseGetStructure(ExportDeclarationBase.prototype, this, {
  11920. kind: exports.StructureKind.ExportDeclaration,
  11921. isTypeOnly: this.isTypeOnly(),
  11922. moduleSpecifier: moduleSpecifier?.getLiteralText(),
  11923. namedExports: this.getNamedExports().map(node => node.getStructure()),
  11924. namespaceExport: this.getNamespaceExport()?.getName(),
  11925. attributes: attributes ? attributes.getElements().map(e => e.getStructure()) : undefined,
  11926. });
  11927. }
  11928. }
  11929. function setEmptyNamedExport(node) {
  11930. const namedExportsNode = node.getNodeProperty("exportClause");
  11931. let replaceNode;
  11932. if (namedExportsNode != null) {
  11933. if (node.getNamedExports().length === 0)
  11934. return;
  11935. replaceNode = namedExportsNode;
  11936. }
  11937. else {
  11938. replaceNode = node.getFirstChildByKindOrThrow(common.SyntaxKind.AsteriskToken);
  11939. }
  11940. insertIntoParentTextRange({
  11941. parent: node,
  11942. newText: "{ }",
  11943. insertPos: replaceNode.getStart(),
  11944. replacing: {
  11945. textLength: replaceNode.getWidth(),
  11946. },
  11947. });
  11948. }
  11949. const ExportSpecifierBase = Node;
  11950. class ExportSpecifier extends ExportSpecifierBase {
  11951. setName(name) {
  11952. const nameNode = this.getNameNode();
  11953. if (this.getName() === name)
  11954. return this;
  11955. if (isValidVariableName(name))
  11956. nameNode.replaceWithText(name);
  11957. else
  11958. nameNode.replaceWithText(`"${name.replaceAll("\"", "\\\"")}"`);
  11959. return this;
  11960. }
  11961. getName() {
  11962. const nameNode = this.getNameNode();
  11963. if (nameNode.getKind() === common.ts.SyntaxKind.StringLiteral)
  11964. return nameNode.getLiteralText();
  11965. else
  11966. return nameNode.getText();
  11967. }
  11968. getNameNode() {
  11969. return this._getNodeFromCompilerNode(this.compilerNode.propertyName || this.compilerNode.name);
  11970. }
  11971. renameAlias(alias) {
  11972. if (common.StringUtils.isNullOrWhitespace(alias)) {
  11973. this.removeAliasWithRename();
  11974. return this;
  11975. }
  11976. let aliasNode = this.getAliasNode();
  11977. if (aliasNode == null) {
  11978. this.setAlias(this.getName());
  11979. aliasNode = this.getAliasNode();
  11980. }
  11981. if (aliasNode.getKind() === common.SyntaxKind.Identifier)
  11982. aliasNode.rename(alias);
  11983. return this;
  11984. }
  11985. setAlias(alias) {
  11986. if (common.StringUtils.isNullOrWhitespace(alias)) {
  11987. this.removeAlias();
  11988. return this;
  11989. }
  11990. const aliasNode = this.getAliasNode();
  11991. if (aliasNode == null) {
  11992. insertIntoParentTextRange({
  11993. insertPos: this.getNameNode().getEnd(),
  11994. parent: this,
  11995. newText: ` as ${alias}`,
  11996. });
  11997. }
  11998. else if (isValidVariableName(alias))
  11999. aliasNode.replaceWithText(alias);
  12000. else
  12001. aliasNode.replaceWithText(`"${alias.replaceAll("\"", "\\\"")}"`);
  12002. return this;
  12003. }
  12004. removeAlias() {
  12005. const aliasNode = this.getAliasNode();
  12006. if (aliasNode == null)
  12007. return this;
  12008. removeChildren({
  12009. children: [this.getFirstChildByKindOrThrow(common.SyntaxKind.AsKeyword), aliasNode],
  12010. removePrecedingSpaces: true,
  12011. removePrecedingNewLines: true,
  12012. });
  12013. return this;
  12014. }
  12015. removeAliasWithRename() {
  12016. const aliasNode = this.getAliasNode();
  12017. if (aliasNode == null)
  12018. return this;
  12019. if (aliasNode.getKind() === common.SyntaxKind.Identifier)
  12020. aliasNode.rename(this.getName());
  12021. this.removeAlias();
  12022. return this;
  12023. }
  12024. getAliasNode() {
  12025. if (this.compilerNode.propertyName == null)
  12026. return undefined;
  12027. return this._getNodeFromCompilerNode(this.compilerNode.name);
  12028. }
  12029. isTypeOnly() {
  12030. return this.compilerNode.isTypeOnly;
  12031. }
  12032. setIsTypeOnly(value) {
  12033. if (this.isTypeOnly() === value)
  12034. return this;
  12035. if (value) {
  12036. insertIntoParentTextRange({
  12037. insertPos: this.getStart(),
  12038. parent: this,
  12039. newText: `type `,
  12040. });
  12041. }
  12042. else {
  12043. removeChildren({
  12044. children: [this.getFirstChildByKindOrThrow(common.ts.SyntaxKind.TypeKeyword)],
  12045. removeFollowingSpaces: true,
  12046. });
  12047. }
  12048. return this;
  12049. }
  12050. getExportDeclaration() {
  12051. return this.getFirstAncestorByKindOrThrow(common.SyntaxKind.ExportDeclaration);
  12052. }
  12053. getLocalTargetSymbolOrThrow(message) {
  12054. return common.errors.throwIfNullOrUndefined(this.getLocalTargetSymbol(), message ?? `The export specifier's local target symbol was expected.`, this);
  12055. }
  12056. getLocalTargetSymbol() {
  12057. return this._context.typeChecker.getExportSpecifierLocalTargetSymbol(this);
  12058. }
  12059. getLocalTargetDeclarations() {
  12060. return this.getLocalTargetSymbol()?.getDeclarations() ?? [];
  12061. }
  12062. remove() {
  12063. const exportDeclaration = this.getExportDeclaration();
  12064. const exports = exportDeclaration.getNamedExports();
  12065. if (exports.length > 1)
  12066. removeCommaSeparatedChild(this);
  12067. else if (exportDeclaration.hasModuleSpecifier())
  12068. exportDeclaration.toNamespaceExport();
  12069. else
  12070. exportDeclaration.remove();
  12071. }
  12072. set(structure) {
  12073. callBaseSet(ExportSpecifierBase.prototype, this, structure);
  12074. if (structure.isTypeOnly != null)
  12075. this.setIsTypeOnly(structure.isTypeOnly);
  12076. if (structure.name != null)
  12077. this.setName(structure.name);
  12078. if (structure.alias != null)
  12079. this.setAlias(structure.alias);
  12080. else if (structure.hasOwnProperty(common.nameof(structure, "alias")))
  12081. this.removeAlias();
  12082. return this;
  12083. }
  12084. getStructure() {
  12085. const alias = this.getAliasNode();
  12086. return callBaseGetStructure(Node.prototype, this, {
  12087. kind: exports.StructureKind.ExportSpecifier,
  12088. alias: alias ? alias.getText() : undefined,
  12089. name: this.getNameNode().getText(),
  12090. isTypeOnly: this.isTypeOnly(),
  12091. });
  12092. }
  12093. }
  12094. const ExternalModuleReferenceBase = ExpressionableNode(Node);
  12095. class ExternalModuleReference extends ExternalModuleReferenceBase {
  12096. getReferencedSourceFileOrThrow(message) {
  12097. return common.errors.throwIfNullOrUndefined(this.getReferencedSourceFile(), message ?? "Expected to find the referenced source file.", this);
  12098. }
  12099. isRelative() {
  12100. const expression = this.getExpression();
  12101. if (expression == null || !Node.isStringLiteral(expression))
  12102. return false;
  12103. return ModuleUtils.isModuleSpecifierRelative(expression.getLiteralText());
  12104. }
  12105. getReferencedSourceFile() {
  12106. const expression = this.getExpression();
  12107. if (expression == null)
  12108. return undefined;
  12109. const symbol = expression.getSymbol();
  12110. if (symbol == null)
  12111. return undefined;
  12112. return ModuleUtils.getReferencedSourceFileFromSymbol(symbol);
  12113. }
  12114. }
  12115. const ImportAttributeBase = ImportAttributeNamedNode(Node);
  12116. class ImportAttribute extends ImportAttributeBase {
  12117. getValue() {
  12118. return this._getNodeFromCompilerNode(this.compilerNode.value);
  12119. }
  12120. set(structure) {
  12121. callBaseSet(ImportAttributeBase.prototype, this, structure);
  12122. if (structure.value)
  12123. this.getValue().replaceWithText(structure.value);
  12124. return this;
  12125. }
  12126. getStructure() {
  12127. return callBaseGetStructure(ImportAttributeBase.prototype, this, {
  12128. kind: exports.StructureKind.ImportAttribute,
  12129. value: this.getValue().getText(),
  12130. });
  12131. }
  12132. }
  12133. const ImportAttributesBase = Node;
  12134. class ImportAttributes extends ImportAttributesBase {
  12135. setElements(elements) {
  12136. this.replaceWithText(writer => {
  12137. const structurePrinter = this._context.structurePrinterFactory.forImportAttribute();
  12138. structurePrinter.printAttributes(writer, elements);
  12139. });
  12140. return this;
  12141. }
  12142. getElements() {
  12143. return this.compilerNode.elements.map(e => this._getNodeFromCompilerNode(e));
  12144. }
  12145. remove() {
  12146. removeChildren({
  12147. children: [this],
  12148. removePrecedingNewLines: true,
  12149. removePrecedingSpaces: true,
  12150. });
  12151. }
  12152. }
  12153. const ImportClauseBase = Node;
  12154. class ImportClause extends ImportClauseBase {
  12155. isTypeOnly() {
  12156. return this.compilerNode.isTypeOnly;
  12157. }
  12158. setIsTypeOnly(value) {
  12159. if (this.isTypeOnly() === value)
  12160. return this;
  12161. if (value) {
  12162. insertIntoParentTextRange({
  12163. parent: this,
  12164. insertPos: this.getStart(),
  12165. newText: "type ",
  12166. });
  12167. }
  12168. else {
  12169. const typeKeyword = this.getFirstChildByKindOrThrow(common.ts.SyntaxKind.TypeKeyword);
  12170. removeChildren({
  12171. children: [typeKeyword],
  12172. removeFollowingSpaces: true,
  12173. });
  12174. }
  12175. return this;
  12176. }
  12177. getDefaultImportOrThrow(message) {
  12178. return common.errors.throwIfNullOrUndefined(this.getDefaultImport(), message ?? "Expected to find a default import.", this);
  12179. }
  12180. getDefaultImport() {
  12181. return this.getNodeProperty("name");
  12182. }
  12183. getNamedBindingsOrThrow(message) {
  12184. return common.errors.throwIfNullOrUndefined(this.getNamedBindings(), message ?? "Expected to find an import declaration's named bindings.", this);
  12185. }
  12186. getNamedBindings() {
  12187. return this.getNodeProperty("namedBindings");
  12188. }
  12189. getNamespaceImportOrThrow(message) {
  12190. return common.errors.throwIfNullOrUndefined(this.getNamespaceImport(), message ?? "Expected to find a namespace import.", this);
  12191. }
  12192. getNamespaceImport() {
  12193. const namedBindings = this.getNamedBindings();
  12194. if (namedBindings == null || !Node.isNamespaceImport(namedBindings))
  12195. return undefined;
  12196. return namedBindings.getNameNode();
  12197. }
  12198. getNamedImports() {
  12199. const namedBindings = this.getNamedBindings();
  12200. if (namedBindings == null || !Node.isNamedImports(namedBindings))
  12201. return [];
  12202. return namedBindings.getElements();
  12203. }
  12204. }
  12205. const ImportDeclarationBase = Statement;
  12206. class ImportDeclaration extends ImportDeclarationBase {
  12207. isTypeOnly() {
  12208. return this.getImportClause()?.isTypeOnly() ?? false;
  12209. }
  12210. setIsTypeOnly(value) {
  12211. const importClause = this.getImportClause();
  12212. if (importClause == null) {
  12213. if (!value)
  12214. return this;
  12215. else
  12216. throw new common.errors.InvalidOperationError("Cannot set an import as type only when there is no import clause.");
  12217. }
  12218. importClause.setIsTypeOnly(value);
  12219. return this;
  12220. }
  12221. setModuleSpecifier(textOrSourceFile) {
  12222. const text = typeof textOrSourceFile === "string" ? textOrSourceFile : this._sourceFile.getRelativePathAsModuleSpecifierTo(textOrSourceFile);
  12223. this.getModuleSpecifier().setLiteralValue(text);
  12224. return this;
  12225. }
  12226. getModuleSpecifier() {
  12227. const moduleSpecifier = this._getNodeFromCompilerNode(this.compilerNode.moduleSpecifier);
  12228. if (!Node.isStringLiteral(moduleSpecifier))
  12229. throw new common.errors.InvalidOperationError("Expected the module specifier to be a string literal.");
  12230. return moduleSpecifier;
  12231. }
  12232. getModuleSpecifierValue() {
  12233. return this.getModuleSpecifier().getLiteralValue();
  12234. }
  12235. getModuleSpecifierSourceFileOrThrow(message) {
  12236. return common.errors.throwIfNullOrUndefined(this.getModuleSpecifierSourceFile(), message ?? `A module specifier source file was expected.`, this);
  12237. }
  12238. getModuleSpecifierSourceFile() {
  12239. const symbol = this.getModuleSpecifier().getSymbol();
  12240. if (symbol == null)
  12241. return undefined;
  12242. return ModuleUtils.getReferencedSourceFileFromSymbol(symbol);
  12243. }
  12244. isModuleSpecifierRelative() {
  12245. return ModuleUtils.isModuleSpecifierRelative(this.getModuleSpecifierValue());
  12246. }
  12247. setDefaultImport(text) {
  12248. if (common.StringUtils.isNullOrWhitespace(text))
  12249. return this.removeDefaultImport();
  12250. const defaultImport = this.getDefaultImport();
  12251. if (defaultImport != null) {
  12252. defaultImport.replaceWithText(text);
  12253. return this;
  12254. }
  12255. const importKeyword = this.getFirstChildByKindOrThrow(common.SyntaxKind.ImportKeyword);
  12256. const importClause = this.getImportClause();
  12257. if (importClause == null) {
  12258. insertIntoParentTextRange({
  12259. insertPos: importKeyword.getEnd(),
  12260. parent: this,
  12261. newText: ` ${text} from`,
  12262. });
  12263. return this;
  12264. }
  12265. insertIntoParentTextRange({
  12266. insertPos: importKeyword.getEnd(),
  12267. parent: importClause,
  12268. newText: ` ${text},`,
  12269. });
  12270. return this;
  12271. }
  12272. renameDefaultImport(text) {
  12273. if (common.StringUtils.isNullOrWhitespace(text))
  12274. return this.removeDefaultImport();
  12275. const defaultImport = this.getDefaultImport();
  12276. if (defaultImport != null) {
  12277. defaultImport.rename(text);
  12278. return this;
  12279. }
  12280. this.setDefaultImport(text);
  12281. return this;
  12282. }
  12283. getDefaultImportOrThrow(message) {
  12284. return common.errors.throwIfNullOrUndefined(this.getDefaultImport(), message ?? "Expected to find a default import.", this);
  12285. }
  12286. getDefaultImport() {
  12287. return this.getImportClause()?.getDefaultImport() ?? undefined;
  12288. }
  12289. setNamespaceImport(text) {
  12290. if (common.StringUtils.isNullOrWhitespace(text))
  12291. return this.removeNamespaceImport();
  12292. const namespaceImport = this.getNamespaceImport();
  12293. if (namespaceImport != null) {
  12294. namespaceImport.rename(text);
  12295. return this;
  12296. }
  12297. if (this.getNamedImports().length > 0)
  12298. throw new common.errors.InvalidOperationError("Cannot add a namespace import to an import declaration that has named imports.");
  12299. const defaultImport = this.getDefaultImport();
  12300. if (defaultImport != null) {
  12301. insertIntoParentTextRange({
  12302. insertPos: defaultImport.getEnd(),
  12303. parent: this.getImportClause(),
  12304. newText: `, * as ${text}`,
  12305. });
  12306. return this;
  12307. }
  12308. insertIntoParentTextRange({
  12309. insertPos: this.getFirstChildByKindOrThrow(common.SyntaxKind.ImportKeyword).getEnd(),
  12310. parent: this,
  12311. newText: ` * as ${text} from`,
  12312. });
  12313. return this;
  12314. }
  12315. removeNamespaceImport() {
  12316. const namespaceImport = this.getNamespaceImport();
  12317. if (namespaceImport == null)
  12318. return this;
  12319. removeChildren({
  12320. children: getChildrenToRemove.call(this),
  12321. removePrecedingSpaces: true,
  12322. removePrecedingNewLines: true,
  12323. });
  12324. return this;
  12325. function getChildrenToRemove() {
  12326. const defaultImport = this.getDefaultImport();
  12327. if (defaultImport == null)
  12328. return [this.getImportClauseOrThrow(), this.getLastChildByKindOrThrow(common.SyntaxKind.FromKeyword)];
  12329. else
  12330. return [defaultImport.getNextSiblingIfKindOrThrow(common.SyntaxKind.CommaToken), namespaceImport];
  12331. }
  12332. }
  12333. removeDefaultImport() {
  12334. const importClause = this.getImportClause();
  12335. if (importClause == null)
  12336. return this;
  12337. const defaultImport = importClause.getDefaultImport();
  12338. if (defaultImport == null)
  12339. return this;
  12340. const hasOnlyDefaultImport = importClause.getNamedBindings() == null;
  12341. if (hasOnlyDefaultImport) {
  12342. if (importClause.isTypeOnly()) {
  12343. insertIntoParentTextRange({
  12344. parent: importClause,
  12345. newText: "{}",
  12346. insertPos: defaultImport.getStart(),
  12347. replacing: {
  12348. textLength: defaultImport.getWidth(),
  12349. },
  12350. });
  12351. }
  12352. else {
  12353. removeChildren({
  12354. children: [importClause, importClause.getNextSiblingIfKindOrThrow(common.SyntaxKind.FromKeyword)],
  12355. removePrecedingSpaces: true,
  12356. removePrecedingNewLines: true,
  12357. });
  12358. }
  12359. }
  12360. else {
  12361. removeChildren({
  12362. children: [defaultImport, defaultImport.getNextSiblingIfKindOrThrow(common.SyntaxKind.CommaToken)],
  12363. removePrecedingSpaces: true,
  12364. removePrecedingNewLines: true,
  12365. });
  12366. }
  12367. return this;
  12368. }
  12369. getNamespaceImportOrThrow(message) {
  12370. return common.errors.throwIfNullOrUndefined(this.getNamespaceImport(), message ?? "Expected to find a namespace import.", this);
  12371. }
  12372. getNamespaceImport() {
  12373. return this.getImportClause()?.getNamespaceImport() ?? undefined;
  12374. }
  12375. addNamedImport(namedImport) {
  12376. return this.addNamedImports([namedImport])[0];
  12377. }
  12378. addNamedImports(namedImports) {
  12379. return this.insertNamedImports(this.getNamedImports().length, namedImports);
  12380. }
  12381. insertNamedImport(index, namedImport) {
  12382. return this.insertNamedImports(index, [namedImport])[0];
  12383. }
  12384. insertNamedImports(index, namedImports) {
  12385. if (!(namedImports instanceof Function) && common.ArrayUtils.isNullOrEmpty(namedImports))
  12386. return [];
  12387. const originalNamedImports = this.getNamedImports();
  12388. const writer = this._getWriterWithQueuedIndentation();
  12389. const namedImportStructurePrinter = this._context.structurePrinterFactory.forNamedImportExportSpecifier();
  12390. const importClause = this.getImportClause();
  12391. index = verifyAndGetIndex(index, originalNamedImports.length);
  12392. if (originalNamedImports.length === 0) {
  12393. namedImportStructurePrinter.printTextsWithBraces(writer, namedImports);
  12394. if (importClause == null) {
  12395. insertIntoParentTextRange({
  12396. insertPos: this.getFirstChildByKindOrThrow(common.SyntaxKind.ImportKeyword).getEnd(),
  12397. parent: this,
  12398. newText: ` ${writer.toString()} from`,
  12399. });
  12400. }
  12401. else if (this.getNamespaceImport() != null)
  12402. throw getErrorWhenNamespaceImportsExist();
  12403. else if (importClause.getNamedBindings() != null) {
  12404. const namedBindings = importClause.getNamedBindingsOrThrow();
  12405. insertIntoParentTextRange({
  12406. insertPos: namedBindings.getStart(),
  12407. replacing: {
  12408. textLength: namedBindings.getWidth(),
  12409. },
  12410. parent: importClause,
  12411. newText: writer.toString(),
  12412. });
  12413. }
  12414. else {
  12415. insertIntoParentTextRange({
  12416. insertPos: this.getDefaultImport().getEnd(),
  12417. parent: importClause,
  12418. newText: `, ${writer.toString()}`,
  12419. });
  12420. }
  12421. }
  12422. else {
  12423. if (importClause == null)
  12424. throw new common.errors.NotImplementedError("Expected to have an import clause.");
  12425. namedImportStructurePrinter.printTexts(writer, namedImports);
  12426. insertIntoCommaSeparatedNodes({
  12427. parent: importClause.getFirstChildByKindOrThrow(common.SyntaxKind.NamedImports).getFirstChildByKindOrThrow(common.SyntaxKind.SyntaxList),
  12428. currentNodes: originalNamedImports,
  12429. insertIndex: index,
  12430. newText: writer.toString(),
  12431. surroundWithSpaces: this._context.getFormatCodeSettings().insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces,
  12432. useTrailingCommas: false,
  12433. });
  12434. }
  12435. const newNamedImports = this.getNamedImports();
  12436. return getNodesToReturn(originalNamedImports, newNamedImports, index, false);
  12437. }
  12438. getNamedImports() {
  12439. return this.getImportClause()?.getNamedImports() ?? [];
  12440. }
  12441. removeNamedImports() {
  12442. const importClause = this.getImportClause();
  12443. if (importClause == null)
  12444. return this;
  12445. const namedImportsNode = importClause.getNamedBindings();
  12446. if (namedImportsNode == null || namedImportsNode.getKind() !== common.SyntaxKind.NamedImports)
  12447. return this;
  12448. const defaultImport = this.getDefaultImport();
  12449. if (defaultImport != null) {
  12450. const commaToken = defaultImport.getNextSiblingIfKindOrThrow(common.SyntaxKind.CommaToken);
  12451. removeChildren({ children: [commaToken, namedImportsNode] });
  12452. return this;
  12453. }
  12454. const fromKeyword = importClause.getNextSiblingIfKindOrThrow(common.SyntaxKind.FromKeyword);
  12455. removeChildren({ children: [importClause, fromKeyword], removePrecedingSpaces: true });
  12456. return this;
  12457. }
  12458. getImportClauseOrThrow(message) {
  12459. return common.errors.throwIfNullOrUndefined(this.getImportClause(), message ?? "Expected to find an import clause.", this);
  12460. }
  12461. getImportClause() {
  12462. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.importClause);
  12463. }
  12464. setAttributes(elements) {
  12465. let attributes = this.getAttributes();
  12466. if (attributes) {
  12467. if (elements)
  12468. attributes.setElements(elements);
  12469. else
  12470. attributes.remove();
  12471. }
  12472. else if (elements) {
  12473. const printer = this._context.structurePrinterFactory.forImportAttribute();
  12474. const writer = this._context.createWriter();
  12475. writer.space();
  12476. printer.printAttributes(writer, elements);
  12477. insertIntoParentTextRange({
  12478. parent: this,
  12479. newText: writer.toString(),
  12480. insertPos: this.getSourceFile().getFullText()[this.getEnd() - 1] === ";" ? this.getEnd() - 1 : this.getEnd(),
  12481. });
  12482. }
  12483. return this;
  12484. }
  12485. getAttributes() {
  12486. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.attributes);
  12487. }
  12488. set(structure) {
  12489. callBaseSet(ImportDeclarationBase.prototype, this, structure);
  12490. if (structure.defaultImport != null)
  12491. this.setDefaultImport(structure.defaultImport);
  12492. else if (structure.hasOwnProperty(common.nameof(structure, "defaultImport")))
  12493. this.removeDefaultImport();
  12494. if (structure.hasOwnProperty(common.nameof(structure, "namedImports")))
  12495. this.removeNamedImports();
  12496. if (structure.namespaceImport != null)
  12497. this.setNamespaceImport(structure.namespaceImport);
  12498. else if (structure.hasOwnProperty(common.nameof(structure, "namespaceImport")))
  12499. this.removeNamespaceImport();
  12500. if (structure.namedImports != null) {
  12501. setEmptyNamedImport(this);
  12502. this.addNamedImports(structure.namedImports);
  12503. }
  12504. if (structure.moduleSpecifier != null)
  12505. this.setModuleSpecifier(structure.moduleSpecifier);
  12506. if (structure.isTypeOnly != null)
  12507. this.setIsTypeOnly(structure.isTypeOnly);
  12508. if (structure.hasOwnProperty(common.nameof(structure, "attributes")))
  12509. this.setAttributes(structure.attributes);
  12510. return this;
  12511. }
  12512. getStructure() {
  12513. const namespaceImport = this.getNamespaceImport();
  12514. const defaultImport = this.getDefaultImport();
  12515. const attributes = this.getAttributes();
  12516. return callBaseGetStructure(ImportDeclarationBase.prototype, this, {
  12517. kind: exports.StructureKind.ImportDeclaration,
  12518. isTypeOnly: this.isTypeOnly(),
  12519. defaultImport: defaultImport ? defaultImport.getText() : undefined,
  12520. moduleSpecifier: this.getModuleSpecifier().getLiteralText(),
  12521. namedImports: this.getNamedImports().map(node => node.getStructure()),
  12522. namespaceImport: namespaceImport ? namespaceImport.getText() : undefined,
  12523. attributes: attributes ? attributes.getElements().map(e => e.getStructure()) : undefined,
  12524. });
  12525. }
  12526. }
  12527. function setEmptyNamedImport(node) {
  12528. const importClause = node.getNodeProperty("importClause");
  12529. const writer = node._getWriterWithQueuedChildIndentation();
  12530. const namedImportStructurePrinter = node._context.structurePrinterFactory.forNamedImportExportSpecifier();
  12531. namedImportStructurePrinter.printTextsWithBraces(writer, []);
  12532. const emptyBracesText = writer.toString();
  12533. if (node.getNamespaceImport() != null)
  12534. throw getErrorWhenNamespaceImportsExist();
  12535. if (importClause == null) {
  12536. insertIntoParentTextRange({
  12537. insertPos: node.getFirstChildByKindOrThrow(common.SyntaxKind.ImportKeyword).getEnd(),
  12538. parent: node,
  12539. newText: ` ${emptyBracesText} from`,
  12540. });
  12541. return;
  12542. }
  12543. const replaceNode = importClause.getNamedBindings();
  12544. if (replaceNode != null) {
  12545. insertIntoParentTextRange({
  12546. parent: importClause,
  12547. newText: emptyBracesText,
  12548. insertPos: replaceNode.getStart(),
  12549. replacing: {
  12550. textLength: replaceNode.getWidth(),
  12551. },
  12552. });
  12553. return;
  12554. }
  12555. const defaultImport = importClause.getDefaultImport();
  12556. if (defaultImport != null) {
  12557. insertIntoParentTextRange({
  12558. insertPos: defaultImport.getEnd(),
  12559. parent: importClause,
  12560. newText: `, ${emptyBracesText}`,
  12561. });
  12562. return;
  12563. }
  12564. }
  12565. function getErrorWhenNamespaceImportsExist() {
  12566. return new common.errors.InvalidOperationError("Cannot add a named import to an import declaration that has a namespace import.");
  12567. }
  12568. const createBase$s = (ctor) => ExportableNode(ModifierableNode(JSDocableNode(NamedNode(ctor))));
  12569. const ImportEqualsDeclarationBase = createBase$s(Statement);
  12570. class ImportEqualsDeclaration extends ImportEqualsDeclarationBase {
  12571. isTypeOnly() {
  12572. return this.compilerNode.isTypeOnly ?? false;
  12573. }
  12574. setIsTypeOnly(value) {
  12575. if (this.isTypeOnly() === value)
  12576. return this;
  12577. if (value) {
  12578. insertIntoParentTextRange({
  12579. parent: this,
  12580. insertPos: this.getNameNode().getStart(),
  12581. newText: "type ",
  12582. });
  12583. }
  12584. else {
  12585. const typeKeyword = this.getFirstChildByKindOrThrow(common.ts.SyntaxKind.TypeKeyword);
  12586. removeChildren({
  12587. children: [typeKeyword],
  12588. removeFollowingSpaces: true,
  12589. });
  12590. }
  12591. return this;
  12592. }
  12593. getModuleReference() {
  12594. return this._getNodeFromCompilerNode(this.compilerNode.moduleReference);
  12595. }
  12596. isExternalModuleReferenceRelative() {
  12597. const moduleReference = this.getModuleReference();
  12598. if (!Node.isExternalModuleReference(moduleReference))
  12599. return false;
  12600. return moduleReference.isRelative();
  12601. }
  12602. setExternalModuleReference(textOrSourceFile) {
  12603. const text = typeof textOrSourceFile === "string" ? textOrSourceFile : this._sourceFile.getRelativePathAsModuleSpecifierTo(textOrSourceFile);
  12604. const moduleReference = this.getModuleReference();
  12605. if (Node.isExternalModuleReference(moduleReference) && moduleReference.getExpression() != null)
  12606. moduleReference.getExpressionOrThrow().replaceWithText(writer => writer.quote(text));
  12607. else
  12608. moduleReference.replaceWithText(writer => writer.write("require(").quote(text).write(")"));
  12609. return this;
  12610. }
  12611. getExternalModuleReferenceSourceFileOrThrow(message) {
  12612. return common.errors.throwIfNullOrUndefined(this.getExternalModuleReferenceSourceFile(), message ?? "Expected to find an external module reference's referenced source file.", this);
  12613. }
  12614. getExternalModuleReferenceSourceFile() {
  12615. const moduleReference = this.getModuleReference();
  12616. if (!Node.isExternalModuleReference(moduleReference))
  12617. return undefined;
  12618. return moduleReference.getReferencedSourceFile();
  12619. }
  12620. }
  12621. const ImportSpecifierBase = Node;
  12622. class ImportSpecifier extends ImportSpecifierBase {
  12623. setName(name) {
  12624. const nameNode = this.getNameNode();
  12625. if (this.getName() === name)
  12626. return this;
  12627. if (isValidVariableName(name))
  12628. nameNode.replaceWithText(name);
  12629. else
  12630. nameNode.replaceWithText(`"${name.replaceAll("\"", "\\\"")}"`);
  12631. return this;
  12632. }
  12633. getName() {
  12634. const nameNode = this.getNameNode();
  12635. if (nameNode.getKind() === common.ts.SyntaxKind.StringLiteral)
  12636. return nameNode.getLiteralText();
  12637. else
  12638. return nameNode.getText();
  12639. }
  12640. getNameNode() {
  12641. return this._getNodeFromCompilerNode(this.compilerNode.propertyName ?? this.compilerNode.name);
  12642. }
  12643. renameAlias(alias) {
  12644. if (common.StringUtils.isNullOrWhitespace(alias)) {
  12645. this.removeAliasWithRename();
  12646. return this;
  12647. }
  12648. let aliasIdentifier = this.getAliasNode();
  12649. if (aliasIdentifier == null) {
  12650. this.setAlias(this.getName());
  12651. aliasIdentifier = this.getAliasNode();
  12652. }
  12653. aliasIdentifier.rename(alias);
  12654. return this;
  12655. }
  12656. setAlias(alias) {
  12657. if (common.StringUtils.isNullOrWhitespace(alias)) {
  12658. this.removeAlias();
  12659. return this;
  12660. }
  12661. const aliasIdentifier = this.getAliasNode();
  12662. if (aliasIdentifier == null) {
  12663. insertIntoParentTextRange({
  12664. insertPos: this.getNameNode().getEnd(),
  12665. parent: this,
  12666. newText: ` as ${alias}`,
  12667. });
  12668. }
  12669. else {
  12670. aliasIdentifier.replaceWithText(alias);
  12671. }
  12672. return this;
  12673. }
  12674. removeAlias() {
  12675. const aliasIdentifier = this.getAliasNode();
  12676. if (aliasIdentifier == null)
  12677. return this;
  12678. removeChildren({
  12679. children: [this.getFirstChildByKindOrThrow(common.SyntaxKind.AsKeyword), aliasIdentifier],
  12680. removePrecedingSpaces: true,
  12681. removePrecedingNewLines: true,
  12682. });
  12683. return this;
  12684. }
  12685. removeAliasWithRename() {
  12686. const aliasIdentifier = this.getAliasNode();
  12687. if (aliasIdentifier == null)
  12688. return this;
  12689. aliasIdentifier.rename(this.getName());
  12690. this.removeAlias();
  12691. return this;
  12692. }
  12693. getAliasNode() {
  12694. if (this.compilerNode.propertyName == null)
  12695. return undefined;
  12696. return this._getNodeFromCompilerNode(this.compilerNode.name);
  12697. }
  12698. isTypeOnly() {
  12699. return this.compilerNode.isTypeOnly;
  12700. }
  12701. setIsTypeOnly(value) {
  12702. if (this.isTypeOnly() === value)
  12703. return this;
  12704. if (value) {
  12705. insertIntoParentTextRange({
  12706. insertPos: this.getStart(),
  12707. parent: this,
  12708. newText: `type `,
  12709. });
  12710. }
  12711. else {
  12712. removeChildren({
  12713. children: [this.getFirstChildByKindOrThrow(common.ts.SyntaxKind.TypeKeyword)],
  12714. removeFollowingSpaces: true,
  12715. });
  12716. }
  12717. return this;
  12718. }
  12719. getImportDeclaration() {
  12720. return this.getFirstAncestorByKindOrThrow(common.SyntaxKind.ImportDeclaration);
  12721. }
  12722. remove() {
  12723. const importDeclaration = this.getImportDeclaration();
  12724. const namedImports = importDeclaration.getNamedImports();
  12725. if (namedImports.length > 1)
  12726. removeCommaSeparatedChild(this);
  12727. else
  12728. importDeclaration.removeNamedImports();
  12729. }
  12730. set(structure) {
  12731. callBaseSet(ImportSpecifierBase.prototype, this, structure);
  12732. if (structure.isTypeOnly != null)
  12733. this.setIsTypeOnly(structure.isTypeOnly);
  12734. if (structure.name != null)
  12735. this.setName(structure.name);
  12736. if (structure.alias != null)
  12737. this.setAlias(structure.alias);
  12738. else if (structure.hasOwnProperty(common.nameof(structure, "alias")))
  12739. this.removeAlias();
  12740. return this;
  12741. }
  12742. getStructure() {
  12743. const alias = this.getAliasNode();
  12744. return callBaseGetStructure(ImportSpecifierBase.prototype, this, {
  12745. kind: exports.StructureKind.ImportSpecifier,
  12746. name: this.getName(),
  12747. alias: alias ? alias.getText() : undefined,
  12748. isTypeOnly: this.isTypeOnly(),
  12749. });
  12750. }
  12751. }
  12752. const ModuleBlockBase = StatementedNode(Statement);
  12753. class ModuleBlock extends ModuleBlockBase {
  12754. }
  12755. function ModuleChildableNode(Base) {
  12756. return class extends Base {
  12757. getParentModuleOrThrow(message) {
  12758. return common.errors.throwIfNullOrUndefined(this.getParentModule(), message ?? "Expected to find the parent module declaration.", this);
  12759. }
  12760. getParentModule() {
  12761. let parent = this.getParentOrThrow();
  12762. if (!Node.isModuleBlock(parent))
  12763. return undefined;
  12764. while (parent.getParentOrThrow().getKind() === common.SyntaxKind.ModuleDeclaration)
  12765. parent = parent.getParentOrThrow();
  12766. return parent;
  12767. }
  12768. };
  12769. }
  12770. exports.ModuleDeclarationKind = void 0;
  12771. (function (ModuleDeclarationKind) {
  12772. ModuleDeclarationKind["Namespace"] = "namespace";
  12773. ModuleDeclarationKind["Module"] = "module";
  12774. ModuleDeclarationKind["Global"] = "global";
  12775. })(exports.ModuleDeclarationKind || (exports.ModuleDeclarationKind = {}));
  12776. const createBase$r = (ctor) => ModuledNode(UnwrappableNode(TextInsertableNode(BodyableNode(ModuleChildableNode(StatementedNode(JSDocableNode(AmbientableNode(ExportableNode(ModifierableNode(ModuleNamedNode(ctor)))))))))));
  12777. const ModuleDeclarationBase = createBase$r(Statement);
  12778. class ModuleDeclaration extends ModuleDeclarationBase {
  12779. getName() {
  12780. const nameNodesOrStringLit = this.getNameNodes();
  12781. if (nameNodesOrStringLit instanceof Array)
  12782. return nameNodesOrStringLit.map(n => n.getText()).join(".");
  12783. return nameNodesOrStringLit.getText();
  12784. }
  12785. setName(newName) {
  12786. const openIssueText = `Please open an issue if you really need this and I'll up the priority.`;
  12787. if (newName.indexOf(".") >= 0)
  12788. throw new common.errors.NotImplementedError(`Not implemented to set a namespace name to a name containing a period. ${openIssueText}`);
  12789. const moduleName = this.getNameNodes();
  12790. if (moduleName instanceof Array) {
  12791. if (moduleName.length > 1)
  12792. throw new common.errors.NotImplementedError(`Not implemented to set a namespace name that uses dot notation. ${openIssueText}`);
  12793. if (newName !== "global")
  12794. addNamespaceKeywordIfNecessary(this);
  12795. if (common.StringUtils.isQuoted(newName))
  12796. changeToAmbientModuleIfNecessary(this);
  12797. moduleName[0].replaceWithText(newName);
  12798. }
  12799. else {
  12800. moduleName.replaceWithText(newName);
  12801. }
  12802. return this;
  12803. }
  12804. rename(newName, options) {
  12805. if (newName.indexOf(".") >= 0)
  12806. throw new common.errors.NotSupportedError(`Cannot rename a namespace name to a name containing a period.`);
  12807. const nameNodes = this.getNameNodes();
  12808. if (nameNodes instanceof Array) {
  12809. if (nameNodes.length > 1) {
  12810. throw new common.errors.NotSupportedError(`Cannot rename a namespace name that uses dot notation. Rename the individual nodes via .${common.nameof(this, "getNameNodes")}()`);
  12811. }
  12812. if (newName !== "global")
  12813. addNamespaceKeywordIfNecessary(this);
  12814. nameNodes[0].rename(newName, options);
  12815. }
  12816. else {
  12817. renameNode(nameNodes, common.StringUtils.stripQuotes(newName), options);
  12818. }
  12819. return this;
  12820. }
  12821. getNameNodes() {
  12822. const name = this.getNameNode();
  12823. if (Node.isStringLiteral(name))
  12824. return name;
  12825. else {
  12826. const nodes = [];
  12827. let current = this;
  12828. do {
  12829. nodes.push(this._getNodeFromCompilerNode(current.compilerNode.name));
  12830. current = current.getFirstChildByKind(common.SyntaxKind.ModuleDeclaration);
  12831. } while (current != null);
  12832. return nodes;
  12833. }
  12834. }
  12835. hasNamespaceKeyword() {
  12836. return this.getDeclarationKind() === exports.ModuleDeclarationKind.Namespace;
  12837. }
  12838. hasModuleKeyword() {
  12839. return this.getDeclarationKind() === exports.ModuleDeclarationKind.Module;
  12840. }
  12841. setDeclarationKind(kind) {
  12842. if (this.getDeclarationKind() === kind)
  12843. return this;
  12844. if (kind === exports.ModuleDeclarationKind.Global) {
  12845. const declarationKindKeyword = this.getDeclarationKindKeyword();
  12846. this.getNameNode().replaceWithText("global");
  12847. if (declarationKindKeyword != null) {
  12848. removeChildren({
  12849. children: [declarationKindKeyword],
  12850. removeFollowingNewLines: true,
  12851. removeFollowingSpaces: true,
  12852. });
  12853. }
  12854. }
  12855. else {
  12856. const declarationKindKeyword = this.getDeclarationKindKeyword();
  12857. if (declarationKindKeyword != null)
  12858. declarationKindKeyword.replaceWithText(kind);
  12859. else {
  12860. insertIntoParentTextRange({
  12861. parent: this,
  12862. insertPos: this.getNameNode().getStart(),
  12863. newText: kind + " ",
  12864. });
  12865. }
  12866. }
  12867. return this;
  12868. }
  12869. getDeclarationKind() {
  12870. const nodeFlags = this.getFlags();
  12871. if ((nodeFlags & common.ts.NodeFlags.GlobalAugmentation) !== 0)
  12872. return exports.ModuleDeclarationKind.Global;
  12873. if ((nodeFlags & common.ts.NodeFlags.Namespace) !== 0)
  12874. return exports.ModuleDeclarationKind.Namespace;
  12875. return exports.ModuleDeclarationKind.Module;
  12876. }
  12877. getDeclarationKindKeyword() {
  12878. return this.getFirstChild(child => child.getKind() === common.SyntaxKind.NamespaceKeyword
  12879. || child.getKind() === common.SyntaxKind.ModuleKeyword);
  12880. }
  12881. set(structure) {
  12882. if (structure.name != null && structure.name !== "global")
  12883. addNamespaceKeywordIfNecessary(this);
  12884. callBaseSet(ModuleDeclarationBase.prototype, this, structure);
  12885. if (structure.declarationKind != null)
  12886. this.setDeclarationKind(structure.declarationKind);
  12887. return this;
  12888. }
  12889. getStructure() {
  12890. return callBaseGetStructure(ModuleDeclarationBase.prototype, this, {
  12891. kind: exports.StructureKind.Module,
  12892. declarationKind: this.getDeclarationKind(),
  12893. });
  12894. }
  12895. _getInnerBody() {
  12896. let node = this.getBody();
  12897. while (node != null && Node.isBodyable(node) && node.compilerNode.statements == null)
  12898. node = node.getBody();
  12899. return node;
  12900. }
  12901. }
  12902. function addNamespaceKeywordIfNecessary(namespaceDec) {
  12903. if (namespaceDec.getDeclarationKind() === exports.ModuleDeclarationKind.Global)
  12904. namespaceDec.setDeclarationKind(exports.ModuleDeclarationKind.Namespace);
  12905. }
  12906. function changeToAmbientModuleIfNecessary(namespaceDec) {
  12907. if (namespaceDec.hasNamespaceKeyword())
  12908. namespaceDec.setDeclarationKind(exports.ModuleDeclarationKind.Module);
  12909. if (!namespaceDec.hasDeclareKeyword())
  12910. namespaceDec.setHasDeclareKeyword(true);
  12911. }
  12912. const NamedExportsBase = Node;
  12913. class NamedExports extends NamedExportsBase {
  12914. getElements() {
  12915. return this.compilerNode.elements.map(e => this._getNodeFromCompilerNode(e));
  12916. }
  12917. }
  12918. const NamedImportsBase = Node;
  12919. class NamedImports extends NamedImportsBase {
  12920. getElements() {
  12921. return this.compilerNode.elements.map(e => this._getNodeFromCompilerNode(e));
  12922. }
  12923. }
  12924. const NamespaceExportBase = RenameableNode(Node);
  12925. class NamespaceExport extends NamespaceExportBase {
  12926. setName(name) {
  12927. const nameNode = this.getNameNode();
  12928. if (this.getName() === name)
  12929. return this;
  12930. if (isValidVariableName(name))
  12931. nameNode.replaceWithText(name);
  12932. else
  12933. nameNode.replaceWithText(`"${name.replaceAll("\"", "\\\"")}"`);
  12934. return this;
  12935. }
  12936. getName() {
  12937. const nameNode = this.getNameNode();
  12938. if (nameNode.getKind() === common.ts.SyntaxKind.StringLiteral)
  12939. return nameNode.getLiteralText();
  12940. else
  12941. return nameNode.getText();
  12942. }
  12943. getNameNode() {
  12944. return this._getNodeFromCompilerNode(this.compilerNode.name);
  12945. }
  12946. }
  12947. const NamespaceImportBase = RenameableNode(Node);
  12948. class NamespaceImport extends NamespaceImportBase {
  12949. setName(name) {
  12950. const nameNode = this.getNameNode();
  12951. if (nameNode.getText() === name)
  12952. return this;
  12953. nameNode.replaceWithText(name);
  12954. return this;
  12955. }
  12956. getName() {
  12957. return this.getNameNode().getText();
  12958. }
  12959. getNameNode() {
  12960. return this._getNodeFromCompilerNode(this.compilerNode.name);
  12961. }
  12962. }
  12963. class FileReference extends TextRange {
  12964. constructor(compilerObject, sourceFile) {
  12965. super(compilerObject, sourceFile);
  12966. }
  12967. getFileName() {
  12968. return this.compilerObject.fileName;
  12969. }
  12970. }
  12971. exports.FileSystemRefreshResult = void 0;
  12972. (function (FileSystemRefreshResult) {
  12973. FileSystemRefreshResult[FileSystemRefreshResult["NoChange"] = 0] = "NoChange";
  12974. FileSystemRefreshResult[FileSystemRefreshResult["Updated"] = 1] = "Updated";
  12975. FileSystemRefreshResult[FileSystemRefreshResult["Deleted"] = 2] = "Deleted";
  12976. })(exports.FileSystemRefreshResult || (exports.FileSystemRefreshResult = {}));
  12977. /******************************************************************************
  12978. Copyright (c) Microsoft Corporation.
  12979. Permission to use, copy, modify, and/or distribute this software for any
  12980. purpose with or without fee is hereby granted.
  12981. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  12982. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  12983. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  12984. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  12985. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  12986. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  12987. PERFORMANCE OF THIS SOFTWARE.
  12988. ***************************************************************************** */
  12989. /* global Reflect, Promise, SuppressedError, Symbol */
  12990. function __decorate(decorators, target, key, desc) {
  12991. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  12992. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  12993. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  12994. return c > 3 && r && Object.defineProperty(target, key, r), r;
  12995. }
  12996. typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
  12997. var e = new Error(message);
  12998. return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
  12999. };
  13000. const SourceFileBase = ModuledNode(TextInsertableNode(StatementedNode(Node)));
  13001. class SourceFile extends SourceFileBase {
  13002. #isSaved = false;
  13003. #modifiedEventContainer = new common.EventContainer();
  13004. #preModifiedEventContainer = new common.EventContainer();
  13005. _referenceContainer = new SourceFileReferenceContainer(this);
  13006. #referencedFiles;
  13007. #libReferenceDirectives;
  13008. #typeReferenceDirectives;
  13009. _hasBom;
  13010. constructor(context, node) {
  13011. super(context, node, undefined);
  13012. this.__sourceFile = this;
  13013. const onPreModified = () => {
  13014. this.isFromExternalLibrary();
  13015. this.#preModifiedEventContainer.unsubscribe(onPreModified);
  13016. };
  13017. this.#preModifiedEventContainer.subscribe(onPreModified);
  13018. }
  13019. _replaceCompilerNodeFromFactory(compilerNode) {
  13020. super._replaceCompilerNodeFromFactory(compilerNode);
  13021. this._context.resetProgram();
  13022. this.#isSaved = false;
  13023. this.#modifiedEventContainer.fire(this);
  13024. }
  13025. _clearInternals() {
  13026. super._clearInternals();
  13027. clearTextRanges(this.#referencedFiles);
  13028. clearTextRanges(this.#typeReferenceDirectives);
  13029. clearTextRanges(this.#libReferenceDirectives);
  13030. this.#referencedFiles = undefined;
  13031. this.#typeReferenceDirectives = undefined;
  13032. this.#libReferenceDirectives = undefined;
  13033. function clearTextRanges(textRanges) {
  13034. textRanges?.forEach(r => r._forget());
  13035. }
  13036. }
  13037. getFilePath() {
  13038. return this.compilerNode.fileName;
  13039. }
  13040. getBaseName() {
  13041. return common.FileUtils.getBaseName(this.getFilePath());
  13042. }
  13043. getBaseNameWithoutExtension() {
  13044. const baseName = this.getBaseName();
  13045. const extension = this.getExtension();
  13046. return baseName.substring(0, baseName.length - extension.length);
  13047. }
  13048. getExtension() {
  13049. return common.FileUtils.getExtension(this.getFilePath());
  13050. }
  13051. getDirectory() {
  13052. return this._context.compilerFactory.getDirectoryFromCache(this.getDirectoryPath());
  13053. }
  13054. getDirectoryPath() {
  13055. return this._context.fileSystemWrapper.getStandardizedAbsolutePath(common.FileUtils.getDirPath(this.compilerNode.fileName));
  13056. }
  13057. getFullText() {
  13058. return this.compilerNode.text;
  13059. }
  13060. getLineAndColumnAtPos(pos) {
  13061. const fullText = this.getFullText();
  13062. return {
  13063. line: common.StringUtils.getLineNumberAtPos(fullText, pos),
  13064. column: common.StringUtils.getLengthFromLineStartAtPos(fullText, pos) + 1,
  13065. };
  13066. }
  13067. getLengthFromLineStartAtPos(pos) {
  13068. return common.StringUtils.getLengthFromLineStartAtPos(this.getFullText(), pos);
  13069. }
  13070. copyToDirectory(dirPathOrDirectory, options) {
  13071. const dirPath = typeof dirPathOrDirectory === "string" ? dirPathOrDirectory : dirPathOrDirectory.getPath();
  13072. return this.copy(common.FileUtils.pathJoin(dirPath, this.getBaseName()), options);
  13073. }
  13074. copy(filePath, options = {}) {
  13075. this._throwIfIsInMemoryLibFile();
  13076. const result = this._copyInternal(filePath, options);
  13077. if (result === false)
  13078. return this;
  13079. const copiedSourceFile = result;
  13080. if (copiedSourceFile.getDirectoryPath() !== this.getDirectoryPath())
  13081. copiedSourceFile._updateReferencesForCopyInternal(this._getReferencesForCopyInternal());
  13082. return copiedSourceFile;
  13083. }
  13084. _copyInternal(fileAbsoluteOrRelativePath, options = {}) {
  13085. const { overwrite = false } = options;
  13086. const { compilerFactory, fileSystemWrapper } = this._context;
  13087. const standardizedFilePath = fileSystemWrapper.getStandardizedAbsolutePath(fileAbsoluteOrRelativePath, this.getDirectoryPath());
  13088. if (standardizedFilePath === this.getFilePath())
  13089. return false;
  13090. return getCopiedSourceFile(this);
  13091. function getCopiedSourceFile(currentFile) {
  13092. try {
  13093. return compilerFactory.createSourceFileFromText(standardizedFilePath, currentFile.getFullText(), { overwrite, markInProject: getShouldBeInProject() });
  13094. }
  13095. catch (err) {
  13096. if (err instanceof common.errors.InvalidOperationError)
  13097. throw new common.errors.InvalidOperationError(`Did you mean to provide the overwrite option? ` + err.message);
  13098. else
  13099. throw err;
  13100. }
  13101. function getShouldBeInProject() {
  13102. if (currentFile._isInProject())
  13103. return true;
  13104. const destinationFile = compilerFactory.getSourceFileFromCacheFromFilePath(standardizedFilePath);
  13105. return destinationFile != null && destinationFile._isInProject();
  13106. }
  13107. }
  13108. }
  13109. _getReferencesForCopyInternal() {
  13110. return Array.from(this._referenceContainer.getLiteralsReferencingOtherSourceFilesEntries());
  13111. }
  13112. _updateReferencesForCopyInternal(literalReferences) {
  13113. for (const reference of literalReferences)
  13114. reference[0] = this.getChildSyntaxListOrThrow().getDescendantAtStartWithWidth(reference[0].getStart(), reference[0].getWidth());
  13115. updateStringLiteralReferences(literalReferences);
  13116. }
  13117. async copyImmediately(filePath, options) {
  13118. const newSourceFile = this.copy(filePath, options);
  13119. await newSourceFile.save();
  13120. return newSourceFile;
  13121. }
  13122. copyImmediatelySync(filePath, options) {
  13123. const newSourceFile = this.copy(filePath, options);
  13124. newSourceFile.saveSync();
  13125. return newSourceFile;
  13126. }
  13127. moveToDirectory(dirPathOrDirectory, options) {
  13128. const dirPath = typeof dirPathOrDirectory === "string" ? dirPathOrDirectory : dirPathOrDirectory.getPath();
  13129. return this.move(common.FileUtils.pathJoin(dirPath, this.getBaseName()), options);
  13130. }
  13131. move(filePath, options = {}) {
  13132. this._throwIfIsInMemoryLibFile();
  13133. const oldDirPath = this.getDirectoryPath();
  13134. const sourceFileReferences = this._getReferencesForMoveInternal();
  13135. const oldFilePath = this.getFilePath();
  13136. if (!this._moveInternal(filePath, options))
  13137. return this;
  13138. this._context.fileSystemWrapper.queueFileDelete(oldFilePath);
  13139. this._updateReferencesForMoveInternal(sourceFileReferences, oldDirPath);
  13140. this._context.lazyReferenceCoordinator.clearDirtySourceFiles();
  13141. this._context.lazyReferenceCoordinator.addDirtySourceFile(this);
  13142. return this;
  13143. }
  13144. _moveInternal(fileRelativeOrAbsolutePath, options = {}) {
  13145. const { overwrite = false } = options;
  13146. const filePath = this._context.fileSystemWrapper.getStandardizedAbsolutePath(fileRelativeOrAbsolutePath, this.getDirectoryPath());
  13147. if (filePath === this.getFilePath())
  13148. return false;
  13149. let markAsInProject = false;
  13150. if (overwrite) {
  13151. const existingSourceFile = this._context.compilerFactory.getSourceFileFromCacheFromFilePath(filePath);
  13152. if (existingSourceFile != null) {
  13153. markAsInProject = existingSourceFile._isInProject();
  13154. existingSourceFile.forget();
  13155. }
  13156. }
  13157. else {
  13158. this._context.compilerFactory.throwIfFileExists(filePath, "Did you mean to provide the overwrite option?");
  13159. }
  13160. replaceSourceFileForFilePathMove({
  13161. newFilePath: filePath,
  13162. sourceFile: this,
  13163. });
  13164. if (markAsInProject)
  13165. this._markAsInProject();
  13166. if (this._isInProject())
  13167. this.getDirectory()._markAsInProject();
  13168. return true;
  13169. }
  13170. _getReferencesForMoveInternal() {
  13171. return {
  13172. literalReferences: Array.from(this._referenceContainer.getLiteralsReferencingOtherSourceFilesEntries()),
  13173. referencingLiterals: Array.from(this._referenceContainer.getReferencingLiteralsInOtherSourceFiles()),
  13174. };
  13175. }
  13176. _updateReferencesForMoveInternal(sourceFileReferences, oldDirPath) {
  13177. const { literalReferences, referencingLiterals } = sourceFileReferences;
  13178. if (oldDirPath !== this.getDirectoryPath())
  13179. updateStringLiteralReferences(literalReferences);
  13180. updateStringLiteralReferences(referencingLiterals.map(node => [node, this]));
  13181. }
  13182. async moveImmediately(filePath, options) {
  13183. const oldFilePath = this.getFilePath();
  13184. const newFilePath = this._context.fileSystemWrapper.getStandardizedAbsolutePath(filePath, this.getDirectoryPath());
  13185. this.move(filePath, options);
  13186. if (oldFilePath !== newFilePath) {
  13187. await this._context.fileSystemWrapper.moveFileImmediately(oldFilePath, newFilePath, this.getFullText());
  13188. this.#isSaved = true;
  13189. }
  13190. else {
  13191. await this.save();
  13192. }
  13193. return this;
  13194. }
  13195. moveImmediatelySync(filePath, options) {
  13196. const oldFilePath = this.getFilePath();
  13197. const newFilePath = this._context.fileSystemWrapper.getStandardizedAbsolutePath(filePath, this.getDirectoryPath());
  13198. this.move(filePath, options);
  13199. if (oldFilePath !== newFilePath) {
  13200. this._context.fileSystemWrapper.moveFileImmediatelySync(oldFilePath, newFilePath, this.getFullText());
  13201. this.#isSaved = true;
  13202. }
  13203. else {
  13204. this.saveSync();
  13205. }
  13206. return this;
  13207. }
  13208. delete() {
  13209. this._throwIfIsInMemoryLibFile();
  13210. const filePath = this.getFilePath();
  13211. this.forget();
  13212. this._context.fileSystemWrapper.queueFileDelete(filePath);
  13213. }
  13214. async deleteImmediately() {
  13215. this._throwIfIsInMemoryLibFile();
  13216. const filePath = this.getFilePath();
  13217. this.forget();
  13218. await this._context.fileSystemWrapper.deleteFileImmediately(filePath);
  13219. }
  13220. deleteImmediatelySync() {
  13221. this._throwIfIsInMemoryLibFile();
  13222. const filePath = this.getFilePath();
  13223. this.forget();
  13224. this._context.fileSystemWrapper.deleteFileImmediatelySync(filePath);
  13225. }
  13226. async save() {
  13227. if (this._isLibFileInMemory())
  13228. return;
  13229. await this._context.fileSystemWrapper.writeFile(this.getFilePath(), this.#getTextForSave());
  13230. this.#isSaved = true;
  13231. }
  13232. saveSync() {
  13233. if (this._isLibFileInMemory())
  13234. return;
  13235. this._context.fileSystemWrapper.writeFileSync(this.getFilePath(), this.#getTextForSave());
  13236. this.#isSaved = true;
  13237. }
  13238. #getTextForSave() {
  13239. const text = this.getFullText();
  13240. return this._hasBom ? "\uFEFF" + text : text;
  13241. }
  13242. getPathReferenceDirectives() {
  13243. if (this.#referencedFiles == null) {
  13244. this.#referencedFiles = (this.compilerNode.referencedFiles || [])
  13245. .map(f => new FileReference(f, this));
  13246. }
  13247. return this.#referencedFiles;
  13248. }
  13249. getTypeReferenceDirectives() {
  13250. if (this.#typeReferenceDirectives == null) {
  13251. this.#typeReferenceDirectives = (this.compilerNode.typeReferenceDirectives || [])
  13252. .map(f => new FileReference(f, this));
  13253. }
  13254. return this.#typeReferenceDirectives;
  13255. }
  13256. getLibReferenceDirectives() {
  13257. if (this.#libReferenceDirectives == null) {
  13258. this.#libReferenceDirectives = (this.compilerNode.libReferenceDirectives || [])
  13259. .map(f => new FileReference(f, this));
  13260. }
  13261. return this.#libReferenceDirectives;
  13262. }
  13263. getReferencingSourceFiles() {
  13264. return Array.from(this._referenceContainer.getDependentSourceFiles());
  13265. }
  13266. getReferencingNodesInOtherSourceFiles() {
  13267. const literals = this.getReferencingLiteralsInOtherSourceFiles();
  13268. return Array.from(getNodes());
  13269. function* getNodes() {
  13270. for (const literal of literals)
  13271. yield getReferencingNodeFromStringLiteral(literal);
  13272. }
  13273. }
  13274. getReferencingLiteralsInOtherSourceFiles() {
  13275. return Array.from(this._referenceContainer.getReferencingLiteralsInOtherSourceFiles());
  13276. }
  13277. getReferencedSourceFiles() {
  13278. const entries = this._referenceContainer.getLiteralsReferencingOtherSourceFilesEntries();
  13279. return Array.from(new Set(getSourceFilesFromEntries()).values());
  13280. function* getSourceFilesFromEntries() {
  13281. for (const [, sourceFile] of entries)
  13282. yield sourceFile;
  13283. }
  13284. }
  13285. getNodesReferencingOtherSourceFiles() {
  13286. const entries = this._referenceContainer.getLiteralsReferencingOtherSourceFilesEntries();
  13287. return Array.from(getNodes());
  13288. function* getNodes() {
  13289. for (const [literal] of entries)
  13290. yield getReferencingNodeFromStringLiteral(literal);
  13291. }
  13292. }
  13293. getLiteralsReferencingOtherSourceFiles() {
  13294. const entries = this._referenceContainer.getLiteralsReferencingOtherSourceFilesEntries();
  13295. return Array.from(getLiteralsFromEntries());
  13296. function* getLiteralsFromEntries() {
  13297. for (const [literal] of entries)
  13298. yield literal;
  13299. }
  13300. }
  13301. getImportStringLiterals() {
  13302. this._ensureBound();
  13303. const literals = (this.compilerNode.imports || []);
  13304. return literals.filter(l => l.pos !== -1).map(l => this._getNodeFromCompilerNode(l));
  13305. }
  13306. getLanguageVersion() {
  13307. return this.compilerNode.languageVersion;
  13308. }
  13309. getLanguageVariant() {
  13310. return this.compilerNode.languageVariant;
  13311. }
  13312. getScriptKind() {
  13313. return this.compilerNode.scriptKind;
  13314. }
  13315. isDeclarationFile() {
  13316. return this.compilerNode.isDeclarationFile;
  13317. }
  13318. isFromExternalLibrary() {
  13319. if (!this._context.program._isCompilerProgramCreated())
  13320. return false;
  13321. const compilerProgram = this._context.program.compilerObject;
  13322. return compilerProgram.isSourceFileFromExternalLibrary(this.compilerNode);
  13323. }
  13324. isInNodeModules() {
  13325. return this.getFilePath().indexOf("/node_modules/") >= 0;
  13326. }
  13327. isSaved() {
  13328. return this.#isSaved && !this._isLibFileInMemory();
  13329. }
  13330. _setIsSaved(value) {
  13331. this.#isSaved = value;
  13332. }
  13333. getPreEmitDiagnostics() {
  13334. return this._context.getPreEmitDiagnostics(this);
  13335. }
  13336. unindent(positionRangeOrPos, times = 1) {
  13337. return this.indent(positionRangeOrPos, times * -1);
  13338. }
  13339. indent(positionRangeOrPos, times = 1) {
  13340. if (times === 0)
  13341. return this;
  13342. const sourceFileText = this.getFullText();
  13343. const positionRange = typeof positionRangeOrPos === "number" ? [positionRangeOrPos, positionRangeOrPos] : positionRangeOrPos;
  13344. common.errors.throwIfRangeOutOfRange(positionRange, [0, sourceFileText.length], "positionRange");
  13345. const startLinePos = getPreviousMatchingPos(sourceFileText, positionRange[0], char => char === CharCodes.NEWLINE);
  13346. const endLinePos = getNextMatchingPos(sourceFileText, positionRange[1], char => char === CharCodes.CARRIAGE_RETURN || char === CharCodes.NEWLINE);
  13347. const correctedText = common.StringUtils.indent(sourceFileText.substring(startLinePos, endLinePos), times, {
  13348. indentText: this._context.manipulationSettings.getIndentationText(),
  13349. indentSizeInSpaces: this._context.manipulationSettings._getIndentSizeInSpaces(),
  13350. isInStringAtPos: pos => this.isInStringAtPos(pos + startLinePos),
  13351. });
  13352. replaceSourceFileTextForFormatting({
  13353. sourceFile: this,
  13354. newText: sourceFileText.substring(0, startLinePos) + correctedText + sourceFileText.substring(endLinePos),
  13355. });
  13356. return this;
  13357. }
  13358. emit(options) {
  13359. return this._context.program.emit({ targetSourceFile: this, ...options });
  13360. }
  13361. emitSync(options) {
  13362. return this._context.program.emitSync({ targetSourceFile: this, ...options });
  13363. }
  13364. getEmitOutput(options = {}) {
  13365. return this._context.languageService.getEmitOutput(this, options.emitOnlyDtsFiles || false);
  13366. }
  13367. formatText(settings = {}) {
  13368. replaceSourceFileTextForFormatting({
  13369. sourceFile: this,
  13370. newText: this._context.languageService.getFormattedDocumentText(this.getFilePath(), settings),
  13371. });
  13372. }
  13373. async refreshFromFileSystem() {
  13374. const fileReadResult = await this._context.fileSystemWrapper.readFileOrNotExists(this.getFilePath(), this._context.getEncoding());
  13375. return this.#refreshFromFileSystemInternal(fileReadResult);
  13376. }
  13377. refreshFromFileSystemSync() {
  13378. const fileReadResult = this._context.fileSystemWrapper.readFileOrNotExistsSync(this.getFilePath(), this._context.getEncoding());
  13379. return this.#refreshFromFileSystemInternal(fileReadResult);
  13380. }
  13381. getRelativePathTo(sourceFileDirOrPath) {
  13382. return this.getDirectory().getRelativePathTo(sourceFileDirOrPath);
  13383. }
  13384. getRelativePathAsModuleSpecifierTo(sourceFileDirOrFilePath) {
  13385. return this.getDirectory().getRelativePathAsModuleSpecifierTo(sourceFileDirOrFilePath);
  13386. }
  13387. onModified(subscription, subscribe = true) {
  13388. if (subscribe)
  13389. this.#modifiedEventContainer.subscribe(subscription);
  13390. else
  13391. this.#modifiedEventContainer.unsubscribe(subscription);
  13392. return this;
  13393. }
  13394. _doActionPreNextModification(action) {
  13395. const wrappedSubscription = () => {
  13396. action();
  13397. this.#preModifiedEventContainer.unsubscribe(wrappedSubscription);
  13398. };
  13399. this.#preModifiedEventContainer.subscribe(wrappedSubscription);
  13400. return this;
  13401. }
  13402. _firePreModified() {
  13403. this.#preModifiedEventContainer.fire(this);
  13404. }
  13405. organizeImports(formatSettings = {}, userPreferences = {}) {
  13406. this._context.languageService.organizeImports(this, formatSettings, userPreferences).forEach(fileTextChanges => fileTextChanges.applyChanges());
  13407. return this;
  13408. }
  13409. fixUnusedIdentifiers(formatSettings = {}, userPreferences = {}) {
  13410. this._context.languageService.getCombinedCodeFix(this, "unusedIdentifier_delete", formatSettings, userPreferences).applyChanges();
  13411. this._context.languageService.getCombinedCodeFix(this, "unusedIdentifier_deleteImports", formatSettings, userPreferences).applyChanges();
  13412. return this;
  13413. }
  13414. fixMissingImports(formatSettings = {}, userPreferences = {}) {
  13415. const combinedCodeFix = this._context.languageService.getCombinedCodeFix(this, "fixMissingImport", formatSettings, userPreferences);
  13416. const sourceFile = this;
  13417. for (const fileTextChanges of combinedCodeFix.getChanges()) {
  13418. const changes = fileTextChanges.getTextChanges();
  13419. removeUnnecessaryDoubleBlankLines(changes);
  13420. applyTextChanges(changes);
  13421. }
  13422. return this;
  13423. function removeUnnecessaryDoubleBlankLines(changes) {
  13424. changes.sort((a, b) => a.getSpan().getStart() - b.getSpan().getStart());
  13425. for (let i = 0; i < changes.length - 1; i++) {
  13426. const { compilerObject } = changes[i];
  13427. compilerObject.newText = compilerObject.newText.replace(/(\r?)\n\r?\n$/, "$1\n");
  13428. }
  13429. }
  13430. function applyTextChanges(changes) {
  13431. const groups = common.ArrayUtils.groupBy(changes, change => change.getSpan().getStart());
  13432. let addedLength = 0;
  13433. for (const group of groups) {
  13434. const insertPos = group[0].getSpan().getStart() + addedLength;
  13435. const newText = group.map(item => item.getNewText()).join("");
  13436. insertIntoTextRange({
  13437. sourceFile,
  13438. insertPos,
  13439. newText,
  13440. });
  13441. addedLength += newText.length;
  13442. }
  13443. }
  13444. }
  13445. applyTextChanges(textChanges) {
  13446. if (textChanges.length === 0)
  13447. return this;
  13448. this.forgetDescendants();
  13449. replaceNodeText({
  13450. sourceFile: this._sourceFile,
  13451. start: 0,
  13452. replacingLength: this.getFullWidth(),
  13453. newText: getTextFromTextChanges(this, textChanges),
  13454. });
  13455. return this;
  13456. }
  13457. set(structure) {
  13458. callBaseSet(SourceFileBase.prototype, this, structure);
  13459. return this;
  13460. }
  13461. getStructure() {
  13462. return callBaseGetStructure(SourceFileBase.prototype, this, {
  13463. kind: exports.StructureKind.SourceFile,
  13464. });
  13465. }
  13466. #refreshFromFileSystemInternal(fileReadResult) {
  13467. if (fileReadResult === false) {
  13468. this.forget();
  13469. return exports.FileSystemRefreshResult.Deleted;
  13470. }
  13471. const fileText = fileReadResult;
  13472. if (fileText === this.getFullText())
  13473. return exports.FileSystemRefreshResult.NoChange;
  13474. this.replaceText([0, this.getEnd()], fileText);
  13475. this._setIsSaved(true);
  13476. return exports.FileSystemRefreshResult.Updated;
  13477. }
  13478. _isLibFileInMemory() {
  13479. return this.compilerNode.fileName.startsWith(common.libFolderInMemoryPath);
  13480. }
  13481. _throwIfIsInMemoryLibFile() {
  13482. if (this._isLibFileInMemory())
  13483. throw new common.errors.InvalidOperationError(`This operation is not permitted on an in memory lib folder file.`);
  13484. }
  13485. _isInProject() {
  13486. return this._context.inProjectCoordinator.isSourceFileInProject(this);
  13487. }
  13488. _markAsInProject() {
  13489. this._context.inProjectCoordinator.markSourceFileAsInProject(this);
  13490. }
  13491. }
  13492. __decorate([
  13493. common.Memoize
  13494. ], SourceFile.prototype, "isFromExternalLibrary", null);
  13495. function updateStringLiteralReferences(nodeReferences) {
  13496. for (const [stringLiteral, sourceFile] of nodeReferences) {
  13497. if (ModuleUtils.isModuleSpecifierRelative(stringLiteral.getLiteralText()))
  13498. stringLiteral.setLiteralValue(stringLiteral._sourceFile.getRelativePathAsModuleSpecifierTo(sourceFile));
  13499. }
  13500. }
  13501. function getReferencingNodeFromStringLiteral(literal) {
  13502. const parent = literal.getParentOrThrow();
  13503. const grandParent = parent.getParent();
  13504. if (grandParent != null && Node.isImportEqualsDeclaration(grandParent))
  13505. return grandParent;
  13506. else
  13507. return parent;
  13508. }
  13509. const createBase$q = (ctor) => ModuleChildableNode(JSDocableNode(AmbientableNode(ExportableNode(ModifierableNode(ctor)))));
  13510. const VariableStatementBase = createBase$q(Statement);
  13511. class VariableStatement extends VariableStatementBase {
  13512. getDeclarationList() {
  13513. return this._getNodeFromCompilerNode(this.compilerNode.declarationList);
  13514. }
  13515. getDeclarations() {
  13516. return this.getDeclarationList().getDeclarations();
  13517. }
  13518. getDeclarationKind() {
  13519. return this.getDeclarationList().getDeclarationKind();
  13520. }
  13521. getDeclarationKindKeywords() {
  13522. return this.getDeclarationList().getDeclarationKindKeywords();
  13523. }
  13524. setDeclarationKind(type) {
  13525. return this.getDeclarationList().setDeclarationKind(type);
  13526. }
  13527. addDeclaration(structure) {
  13528. return this.getDeclarationList().addDeclaration(structure);
  13529. }
  13530. addDeclarations(structures) {
  13531. return this.getDeclarationList().addDeclarations(structures);
  13532. }
  13533. insertDeclaration(index, structure) {
  13534. return this.getDeclarationList().insertDeclaration(index, structure);
  13535. }
  13536. insertDeclarations(index, structures) {
  13537. return this.getDeclarationList().insertDeclarations(index, structures);
  13538. }
  13539. set(structure) {
  13540. callBaseSet(VariableStatementBase.prototype, this, structure);
  13541. if (structure.declarationKind != null)
  13542. this.setDeclarationKind(structure.declarationKind);
  13543. if (structure.declarations != null) {
  13544. const existingDeclarations = this.getDeclarations();
  13545. this.addDeclarations(structure.declarations);
  13546. existingDeclarations.forEach(d => d.remove());
  13547. }
  13548. return this;
  13549. }
  13550. getStructure() {
  13551. return callBaseGetStructure(VariableStatementBase.prototype, this, {
  13552. kind: exports.StructureKind.VariableStatement,
  13553. declarationKind: this.getDeclarationKind(),
  13554. declarations: this.getDeclarations().map(declaration => declaration.getStructure()),
  13555. });
  13556. }
  13557. }
  13558. const WhileStatementBase = ExpressionedNode(IterationStatement);
  13559. class WhileStatement extends WhileStatementBase {
  13560. }
  13561. const WithStatementBase = ExpressionedNode(Statement);
  13562. class WithStatement extends WithStatementBase {
  13563. getStatement() {
  13564. return this._getNodeFromCompilerNode(this.compilerNode.statement);
  13565. }
  13566. }
  13567. function FunctionLikeDeclaration(Base) {
  13568. return JSDocableNode(TypeParameteredNode(SignaturedDeclaration(StatementedNode(ModifierableNode(Base)))));
  13569. }
  13570. const createBase$p = (ctor) => TextInsertableNode(BodiedNode(AsyncableNode(FunctionLikeDeclaration(ctor))));
  13571. const ArrowFunctionBase = createBase$p(Expression);
  13572. class ArrowFunction extends ArrowFunctionBase {
  13573. getEqualsGreaterThan() {
  13574. return this._getNodeFromCompilerNode(this.compilerNode.equalsGreaterThanToken);
  13575. }
  13576. }
  13577. function OverloadableNode(Base) {
  13578. return class extends Base {
  13579. getOverloads() {
  13580. return getOverloadsAndImplementation(this).filter(n => n.isOverload());
  13581. }
  13582. getImplementation() {
  13583. if (this.isImplementation())
  13584. return this;
  13585. return getOverloadsAndImplementation(this).find(n => n.isImplementation());
  13586. }
  13587. getImplementationOrThrow(message) {
  13588. return common.errors.throwIfNullOrUndefined(this.getImplementation(), message ?? "Expected to find a corresponding implementation for the overload.", this);
  13589. }
  13590. isOverload() {
  13591. return !this.isImplementation();
  13592. }
  13593. isImplementation() {
  13594. return this.getBody() != null;
  13595. }
  13596. };
  13597. }
  13598. function getOverloadsAndImplementation(node) {
  13599. const parent = node.getParentOrThrow();
  13600. const name = getNameIfNamedNode(node);
  13601. const isStatic = getStaticIfStaticable(node);
  13602. const kind = node.getKind();
  13603. return parent.forEachChildAsArray().filter(n => {
  13604. return getNameIfNamedNode(n) === name
  13605. && n.getKind() === kind
  13606. && getStaticIfStaticable(n) === isStatic;
  13607. });
  13608. }
  13609. function getNameIfNamedNode(node) {
  13610. const nodeAsNamedNode = node;
  13611. if (nodeAsNamedNode.getName instanceof Function)
  13612. return nodeAsNamedNode.getName();
  13613. return undefined;
  13614. }
  13615. function getStaticIfStaticable(node) {
  13616. const nodeAsStaticableNode = node;
  13617. if (nodeAsStaticableNode.isStatic instanceof Function)
  13618. return nodeAsStaticableNode.isStatic();
  13619. return false;
  13620. }
  13621. function insertOverloads(opts) {
  13622. if (opts.structures.length === 0)
  13623. return [];
  13624. const parentSyntaxList = opts.node.getParentSyntaxListOrThrow();
  13625. const implementationNode = opts.node.getImplementation() || opts.node;
  13626. const overloads = opts.node.getOverloads();
  13627. const overloadsCount = overloads.length;
  13628. const firstIndex = overloads.length > 0 ? overloads[0].getChildIndex() : implementationNode.getChildIndex();
  13629. const index = verifyAndGetIndex(opts.index, overloadsCount);
  13630. const mainIndex = firstIndex + index;
  13631. const thisStructure = opts.getThisStructure(implementationNode);
  13632. const structures = opts.structures.map(structure => Object.assign(Object.assign({}, thisStructure), structure));
  13633. const writer = implementationNode._getWriterWithQueuedIndentation();
  13634. for (const structure of structures) {
  13635. if (writer.getLength() > 0)
  13636. writer.newLine();
  13637. opts.printStructure(writer, structure);
  13638. }
  13639. writer.newLine();
  13640. writer.write("");
  13641. insertIntoParentTextRange({
  13642. parent: parentSyntaxList,
  13643. insertPos: (overloads[index] || implementationNode).getNonWhitespaceStart(),
  13644. newText: writer.toString(),
  13645. });
  13646. return getRangeWithoutCommentsFromArray(parentSyntaxList.getChildren(), mainIndex, structures.length, opts.expectedSyntaxKind);
  13647. }
  13648. const createBase$o = (ctor) => UnwrappableNode(TextInsertableNode(OverloadableNode(BodyableNode(AsyncableNode(GeneratorableNode(AmbientableNode(ExportableNode(FunctionLikeDeclaration(ModuleChildableNode(NameableNode(ctor)))))))))));
  13649. const FunctionDeclarationBase = createBase$o(Statement);
  13650. const createOverloadBase$2 = (ctor) => UnwrappableNode(TextInsertableNode(AsyncableNode(GeneratorableNode(SignaturedDeclaration(AmbientableNode(ModuleChildableNode(JSDocableNode(TypeParameteredNode(ExportableNode(ModifierableNode(ctor)))))))))));
  13651. const FunctionDeclarationOverloadBase = createOverloadBase$2(Statement);
  13652. class FunctionDeclaration extends FunctionDeclarationBase {
  13653. addOverload(structure) {
  13654. return this.addOverloads([structure])[0];
  13655. }
  13656. addOverloads(structures) {
  13657. return this.insertOverloads(this.getOverloads().length, structures);
  13658. }
  13659. insertOverload(index, structure) {
  13660. return this.insertOverloads(index, [structure])[0];
  13661. }
  13662. insertOverloads(index, structures) {
  13663. const thisName = this.getName();
  13664. const printer = this._context.structurePrinterFactory.forFunctionDeclaration({
  13665. isAmbient: this.isAmbient(),
  13666. });
  13667. return insertOverloads({
  13668. node: this,
  13669. index,
  13670. structures,
  13671. printStructure: (writer, structure) => {
  13672. printer.printOverload(writer, thisName, structure);
  13673. },
  13674. getThisStructure: fromFunctionDeclarationOverload,
  13675. expectedSyntaxKind: common.SyntaxKind.FunctionDeclaration,
  13676. });
  13677. }
  13678. remove() {
  13679. removeOverloadableStatementedNodeChild(this);
  13680. }
  13681. set(structure) {
  13682. callBaseSet(FunctionDeclarationBase.prototype, this, structure);
  13683. if (structure.overloads != null) {
  13684. this.getOverloads().forEach(o => o.remove());
  13685. this.addOverloads(structure.overloads);
  13686. }
  13687. return this;
  13688. }
  13689. getStructure() {
  13690. const isOverload = this.isOverload();
  13691. const hasImplementation = this.getImplementation();
  13692. const basePrototype = isOverload && hasImplementation ? FunctionDeclarationOverloadBase.prototype : FunctionDeclarationBase.prototype;
  13693. return callBaseGetStructure(basePrototype, this, getStructure(this));
  13694. function getStructure(thisNode) {
  13695. if (hasImplementation && isOverload)
  13696. return getOverloadSpecificStructure();
  13697. return getSpecificStructure();
  13698. function getOverloadSpecificStructure() {
  13699. return { kind: exports.StructureKind.FunctionOverload };
  13700. }
  13701. function getSpecificStructure() {
  13702. if (!hasImplementation)
  13703. return { kind: exports.StructureKind.Function };
  13704. else {
  13705. return {
  13706. kind: exports.StructureKind.Function,
  13707. overloads: thisNode.getOverloads().map(o => o.getStructure()),
  13708. };
  13709. }
  13710. }
  13711. }
  13712. }
  13713. }
  13714. const createBase$n = (ctor) => JSDocableNode(TextInsertableNode(BodiedNode(AsyncableNode(GeneratorableNode(StatementedNode(TypeParameteredNode(SignaturedDeclaration(ModifierableNode(NameableNode(ctor))))))))));
  13715. const FunctionExpressionBase = createBase$n(PrimaryExpression);
  13716. class FunctionExpression extends FunctionExpressionBase {
  13717. }
  13718. const createBase$m = (ctor) => OverrideableNode(QuestionTokenableNode(DecoratableNode(ScopeableNode(ReadonlyableNode(ModifierableNode(DotDotDotTokenableNode(TypedNode(InitializerExpressionableNode(BindingNamedNode(ctor))))))))));
  13719. const ParameterDeclarationBase = createBase$m(Node);
  13720. class ParameterDeclaration extends ParameterDeclarationBase {
  13721. isRestParameter() {
  13722. return this.compilerNode.dotDotDotToken != null;
  13723. }
  13724. isParameterProperty() {
  13725. return this.getScope() != null || this.isReadonly() || this.hasOverrideKeyword();
  13726. }
  13727. setIsRestParameter(value) {
  13728. if (this.isRestParameter() === value)
  13729. return this;
  13730. if (value) {
  13731. addParensIfNecessary(this);
  13732. insertIntoParentTextRange({
  13733. insertPos: this.getNameNode().getStart(),
  13734. parent: this,
  13735. newText: "...",
  13736. });
  13737. }
  13738. else {
  13739. removeChildren({ children: [this.getDotDotDotTokenOrThrow()] });
  13740. }
  13741. return this;
  13742. }
  13743. isOptional() {
  13744. return this.compilerNode.questionToken != null || this.isRestParameter() || this.hasInitializer();
  13745. }
  13746. remove() {
  13747. removeCommaSeparatedChild(this);
  13748. }
  13749. set(structure) {
  13750. callBaseSet(ParameterDeclarationBase.prototype, this, structure);
  13751. if (structure.isRestParameter != null)
  13752. this.setIsRestParameter(structure.isRestParameter);
  13753. return this;
  13754. }
  13755. getStructure() {
  13756. return callBaseGetStructure(ParameterDeclarationBase.prototype, this, {
  13757. kind: exports.StructureKind.Parameter,
  13758. isRestParameter: this.isRestParameter(),
  13759. });
  13760. }
  13761. setHasQuestionToken(value) {
  13762. if (value)
  13763. addParensIfNecessary(this);
  13764. super.setHasQuestionToken(value);
  13765. return this;
  13766. }
  13767. setInitializer(textOrWriterFunction) {
  13768. addParensIfNecessary(this);
  13769. super.setInitializer(textOrWriterFunction);
  13770. return this;
  13771. }
  13772. setType(textOrWriterFunction) {
  13773. addParensIfNecessary(this);
  13774. super.setType.call(this, textOrWriterFunction);
  13775. return this;
  13776. }
  13777. }
  13778. function addParensIfNecessary(parameter) {
  13779. const parent = parameter.getParentOrThrow();
  13780. if (isParameterWithoutParens())
  13781. addParens();
  13782. function isParameterWithoutParens() {
  13783. return Node.isArrowFunction(parent)
  13784. && parent.compilerNode.parameters.length === 1
  13785. && parameter.getParentSyntaxListOrThrow().getPreviousSiblingIfKind(common.SyntaxKind.OpenParenToken) == null;
  13786. }
  13787. function addParens() {
  13788. const paramText = parameter.getText();
  13789. insertIntoParentTextRange({
  13790. parent,
  13791. insertPos: parameter.getStart(),
  13792. newText: `(${paramText})`,
  13793. replacing: {
  13794. textLength: paramText.length,
  13795. },
  13796. customMappings: newParent => {
  13797. return [{ currentNode: parameter, newNode: newParent.parameters[0] }];
  13798. },
  13799. });
  13800. }
  13801. }
  13802. class ClassElement extends Node {
  13803. remove() {
  13804. const parent = this.getParentOrThrow();
  13805. if (Node.isClassDeclaration(parent) || Node.isClassExpression(parent))
  13806. removeClassMember(this);
  13807. else if (Node.isObjectLiteralExpression(parent))
  13808. removeCommaSeparatedChild(this);
  13809. else if (Node.isInterfaceDeclaration(parent))
  13810. removeInterfaceMember(this);
  13811. else
  13812. common.errors.throwNotImplementedForSyntaxKindError(parent.getKind());
  13813. }
  13814. }
  13815. const createBase$l = (ctor) => ChildOrderableNode(TextInsertableNode(OverrideableNode(OverloadableNode(BodyableNode(DecoratableNode(AbstractableNode(ScopedNode(QuestionTokenableNode(StaticableNode(AsyncableNode(GeneratorableNode(FunctionLikeDeclaration(PropertyNamedNode(ctor))))))))))))));
  13816. const MethodDeclarationBase = createBase$l(ClassElement);
  13817. const createOverloadBase$1 = (ctor) => JSDocableNode(ChildOrderableNode(TextInsertableNode(OverrideableNode(ScopedNode(TypeParameteredNode(AbstractableNode(QuestionTokenableNode(StaticableNode(AsyncableNode(ModifierableNode(GeneratorableNode(SignaturedDeclaration(ctor)))))))))))));
  13818. const MethodDeclarationOverloadBase = createOverloadBase$1(ClassElement);
  13819. class MethodDeclaration extends MethodDeclarationBase {
  13820. set(structure) {
  13821. callBaseSet(MethodDeclarationBase.prototype, this, structure);
  13822. if (structure.overloads != null) {
  13823. this.getOverloads().forEach(o => o.remove());
  13824. this.addOverloads(structure.overloads);
  13825. }
  13826. return this;
  13827. }
  13828. addOverload(structure) {
  13829. return this.addOverloads([structure])[0];
  13830. }
  13831. addOverloads(structures) {
  13832. return this.insertOverloads(this.getOverloads().length, structures);
  13833. }
  13834. insertOverload(index, structure) {
  13835. return this.insertOverloads(index, [structure])[0];
  13836. }
  13837. insertOverloads(index, structures) {
  13838. const thisName = this.getName();
  13839. const printer = this._context.structurePrinterFactory.forMethodDeclaration({
  13840. isAmbient: isNodeAmbientOrInAmbientContext(this),
  13841. });
  13842. return insertOverloads({
  13843. node: this,
  13844. index,
  13845. structures,
  13846. printStructure: (writer, structure) => {
  13847. printer.printOverload(writer, thisName, structure);
  13848. },
  13849. getThisStructure: fromMethodDeclarationOverload,
  13850. expectedSyntaxKind: common.SyntaxKind.MethodDeclaration,
  13851. });
  13852. }
  13853. getStructure() {
  13854. const hasImplementation = this.getImplementation() != null;
  13855. const isOverload = this.isOverload();
  13856. const basePrototype = isOverload && hasImplementation ? MethodDeclarationOverloadBase.prototype : MethodDeclarationBase.prototype;
  13857. return callBaseGetStructure(basePrototype, this, getStructure(this));
  13858. function getStructure(thisNode) {
  13859. if (hasImplementation && isOverload)
  13860. return getOverloadSpecificStructure();
  13861. return getSpecificStructure();
  13862. function getOverloadSpecificStructure() {
  13863. return { kind: exports.StructureKind.MethodOverload };
  13864. }
  13865. function getSpecificStructure() {
  13866. if (!hasImplementation)
  13867. return { kind: exports.StructureKind.Method };
  13868. else {
  13869. return {
  13870. kind: exports.StructureKind.Method,
  13871. overloads: thisNode.getOverloads().map(o => o.getStructure()),
  13872. };
  13873. }
  13874. }
  13875. }
  13876. }
  13877. }
  13878. function ClassLikeDeclarationBase(Base) {
  13879. return ClassLikeDeclarationBaseSpecific(NameableNode(TextInsertableNode(ImplementsClauseableNode(HeritageClauseableNode(AbstractableNode(JSDocableNode(TypeParameteredNode(DecoratableNode(ModifierableNode(Base))))))))));
  13880. }
  13881. function ClassLikeDeclarationBaseSpecific(Base) {
  13882. return class extends Base {
  13883. setExtends(text) {
  13884. text = this._getTextWithQueuedChildIndentation(text);
  13885. if (common.StringUtils.isNullOrWhitespace(text))
  13886. return this.removeExtends();
  13887. const extendsClause = this.getHeritageClauseByKind(common.SyntaxKind.ExtendsKeyword);
  13888. if (extendsClause != null) {
  13889. const childSyntaxList = extendsClause.getFirstChildByKindOrThrow(common.SyntaxKind.SyntaxList);
  13890. const childSyntaxListStart = childSyntaxList.getStart();
  13891. insertIntoParentTextRange({
  13892. parent: extendsClause,
  13893. newText: text,
  13894. insertPos: childSyntaxListStart,
  13895. replacing: {
  13896. textLength: childSyntaxList.getEnd() - childSyntaxListStart,
  13897. },
  13898. });
  13899. }
  13900. else {
  13901. const implementsClause = this.getHeritageClauseByKind(common.SyntaxKind.ImplementsKeyword);
  13902. let insertPos;
  13903. if (implementsClause != null)
  13904. insertPos = implementsClause.getStart();
  13905. else
  13906. insertPos = this.getFirstChildByKindOrThrow(common.SyntaxKind.OpenBraceToken).getStart();
  13907. const isLastSpace = /\s/.test(this.getSourceFile().getFullText()[insertPos - 1]);
  13908. let newText = `extends ${text} `;
  13909. if (!isLastSpace)
  13910. newText = " " + newText;
  13911. insertIntoParentTextRange({
  13912. parent: implementsClause == null ? this : implementsClause.getParentSyntaxListOrThrow(),
  13913. insertPos,
  13914. newText,
  13915. });
  13916. }
  13917. return this;
  13918. }
  13919. removeExtends() {
  13920. const extendsClause = this.getHeritageClauseByKind(common.SyntaxKind.ExtendsKeyword);
  13921. if (extendsClause == null)
  13922. return this;
  13923. extendsClause.removeExpression(0);
  13924. return this;
  13925. }
  13926. getExtendsOrThrow(message) {
  13927. return common.errors.throwIfNullOrUndefined(this.getExtends(), message ?? `Expected to find the extends expression for the class ${this.getName()}.`, this);
  13928. }
  13929. getExtends() {
  13930. const extendsClause = this.getHeritageClauseByKind(common.SyntaxKind.ExtendsKeyword);
  13931. if (extendsClause == null)
  13932. return undefined;
  13933. const types = extendsClause.getTypeNodes();
  13934. return types.length === 0 ? undefined : types[0];
  13935. }
  13936. addMembers(members) {
  13937. return this.insertMembers(getEndIndexFromArray(this.getMembersWithComments()), members);
  13938. }
  13939. addMember(member) {
  13940. return this.insertMember(getEndIndexFromArray(this.getMembersWithComments()), member);
  13941. }
  13942. insertMember(index, member) {
  13943. return this.insertMembers(index, [member])[0];
  13944. }
  13945. insertMembers(index, members) {
  13946. const isAmbient = isNodeAmbientOrInAmbientContext(this);
  13947. return insertIntoBracesOrSourceFileWithGetChildrenWithComments({
  13948. getIndexedChildren: () => this.getMembersWithComments(),
  13949. index,
  13950. parent: this,
  13951. write: (writer, info) => {
  13952. const previousMemberHasBody = !isAmbient && info.previousMember != null && Node.isBodyable(info.previousMember)
  13953. && info.previousMember.hasBody();
  13954. const firstStructureHasBody = !isAmbient && members instanceof Array && structureHasBody(members[0]);
  13955. if (previousMemberHasBody || info.previousMember != null && firstStructureHasBody)
  13956. writer.blankLineIfLastNot();
  13957. else
  13958. writer.newLineIfLastNot();
  13959. const memberWriter = this._getWriter();
  13960. const memberPrinter = this._context.structurePrinterFactory.forClassMember({ isAmbient });
  13961. memberPrinter.printTexts(memberWriter, members);
  13962. writer.write(memberWriter.toString());
  13963. const lastStructureHasBody = !isAmbient && members instanceof Array && structureHasBody(members[members.length - 1]);
  13964. const nextMemberHasBody = !isAmbient && info.nextMember != null && Node.isBodyable(info.nextMember) && info.nextMember.hasBody();
  13965. if (info.nextMember != null && lastStructureHasBody || nextMemberHasBody)
  13966. writer.blankLineIfLastNot();
  13967. else
  13968. writer.newLineIfLastNot();
  13969. },
  13970. });
  13971. function structureHasBody(value) {
  13972. if (isAmbient || value == null || typeof value.kind !== "number")
  13973. return false;
  13974. const structure = value;
  13975. return Structure.isMethod(structure)
  13976. || Structure.isGetAccessor(structure)
  13977. || Structure.isSetAccessor(structure)
  13978. || Structure.isConstructor(structure);
  13979. }
  13980. }
  13981. addConstructor(structure = {}) {
  13982. return this.insertConstructor(getEndIndexFromArray(this.getMembersWithComments()), structure);
  13983. }
  13984. addConstructors(structures) {
  13985. return this.insertConstructors(getEndIndexFromArray(this.getMembersWithComments()), structures);
  13986. }
  13987. insertConstructor(index, structure = {}) {
  13988. return this.insertConstructors(index, [structure])[0];
  13989. }
  13990. insertConstructors(index, structures) {
  13991. const isAmbient = isNodeAmbientOrInAmbientContext(this);
  13992. return insertChildren(this, {
  13993. index,
  13994. structures,
  13995. expectedKind: common.SyntaxKind.Constructor,
  13996. write: (writer, info) => {
  13997. if (!isAmbient && info.previousMember != null && !Node.isCommentNode(info.previousMember))
  13998. writer.blankLineIfLastNot();
  13999. else
  14000. writer.newLineIfLastNot();
  14001. this._context.structurePrinterFactory.forConstructorDeclaration({ isAmbient }).printTexts(writer, structures);
  14002. if (!isAmbient && info.nextMember != null)
  14003. writer.blankLineIfLastNot();
  14004. else
  14005. writer.newLineIfLastNot();
  14006. },
  14007. });
  14008. }
  14009. getConstructors() {
  14010. return this.getMembers().filter(m => Node.isConstructorDeclaration(m));
  14011. }
  14012. addStaticBlock(structure = {}) {
  14013. return this.insertStaticBlock(getEndIndexFromArray(this.getMembersWithComments()), structure);
  14014. }
  14015. addStaticBlocks(structures) {
  14016. return this.insertStaticBlocks(getEndIndexFromArray(this.getMembersWithComments()), structures);
  14017. }
  14018. insertStaticBlock(index, structure = {}) {
  14019. return this.insertStaticBlocks(index, [structure])[0];
  14020. }
  14021. insertStaticBlocks(index, structures) {
  14022. const isAmbient = isNodeAmbientOrInAmbientContext(this);
  14023. return insertChildren(this, {
  14024. index,
  14025. structures,
  14026. expectedKind: common.SyntaxKind.ClassStaticBlockDeclaration,
  14027. write: (writer, info) => {
  14028. if (!isAmbient && info.previousMember != null && !Node.isCommentNode(info.previousMember))
  14029. writer.blankLineIfLastNot();
  14030. else
  14031. writer.newLineIfLastNot();
  14032. this._context.structurePrinterFactory.forClassStaticBlockDeclaration().printTexts(writer, structures);
  14033. if (!isAmbient && info.nextMember != null)
  14034. writer.blankLineIfLastNot();
  14035. else
  14036. writer.newLineIfLastNot();
  14037. },
  14038. });
  14039. }
  14040. getStaticBlocks() {
  14041. return this.getMembers().filter(m => Node.isClassStaticBlockDeclaration(m));
  14042. }
  14043. addGetAccessor(structure) {
  14044. return this.addGetAccessors([structure])[0];
  14045. }
  14046. addGetAccessors(structures) {
  14047. return this.insertGetAccessors(getEndIndexFromArray(this.getMembersWithComments()), structures);
  14048. }
  14049. insertGetAccessor(index, structure) {
  14050. return this.insertGetAccessors(index, [structure])[0];
  14051. }
  14052. insertGetAccessors(index, structures) {
  14053. return insertChildren(this, {
  14054. index,
  14055. structures,
  14056. expectedKind: common.SyntaxKind.GetAccessor,
  14057. write: (writer, info) => {
  14058. if (info.previousMember != null && !Node.isCommentNode(info.previousMember))
  14059. writer.blankLineIfLastNot();
  14060. else
  14061. writer.newLineIfLastNot();
  14062. this._context.structurePrinterFactory.forGetAccessorDeclaration({
  14063. isAmbient: isNodeAmbientOrInAmbientContext(this),
  14064. }).printTexts(writer, structures);
  14065. if (info.nextMember != null)
  14066. writer.blankLineIfLastNot();
  14067. else
  14068. writer.newLineIfLastNot();
  14069. },
  14070. });
  14071. }
  14072. addSetAccessor(structure) {
  14073. return this.addSetAccessors([structure])[0];
  14074. }
  14075. addSetAccessors(structures) {
  14076. return this.insertSetAccessors(getEndIndexFromArray(this.getMembersWithComments()), structures);
  14077. }
  14078. insertSetAccessor(index, structure) {
  14079. return this.insertSetAccessors(index, [structure])[0];
  14080. }
  14081. insertSetAccessors(index, structures) {
  14082. return insertChildren(this, {
  14083. index,
  14084. structures,
  14085. expectedKind: common.SyntaxKind.SetAccessor,
  14086. write: (writer, info) => {
  14087. if (info.previousMember != null && !Node.isCommentNode(info.previousMember))
  14088. writer.blankLineIfLastNot();
  14089. else
  14090. writer.newLineIfLastNot();
  14091. this._context.structurePrinterFactory.forSetAccessorDeclaration({
  14092. isAmbient: isNodeAmbientOrInAmbientContext(this),
  14093. }).printTexts(writer, structures);
  14094. if (info.nextMember != null)
  14095. writer.blankLineIfLastNot();
  14096. else
  14097. writer.newLineIfLastNot();
  14098. },
  14099. });
  14100. }
  14101. addProperty(structure) {
  14102. return this.addProperties([structure])[0];
  14103. }
  14104. addProperties(structures) {
  14105. return this.insertProperties(getEndIndexFromArray(this.getMembersWithComments()), structures);
  14106. }
  14107. insertProperty(index, structure) {
  14108. return this.insertProperties(index, [structure])[0];
  14109. }
  14110. insertProperties(index, structures) {
  14111. return insertChildren(this, {
  14112. index,
  14113. structures,
  14114. expectedKind: common.SyntaxKind.PropertyDeclaration,
  14115. write: (writer, info) => {
  14116. if (info.previousMember != null && Node.hasBody(info.previousMember))
  14117. writer.blankLineIfLastNot();
  14118. else
  14119. writer.newLineIfLastNot();
  14120. this._context.structurePrinterFactory.forPropertyDeclaration().printTexts(writer, structures);
  14121. if (info.nextMember != null && Node.hasBody(info.nextMember))
  14122. writer.blankLineIfLastNot();
  14123. else
  14124. writer.newLineIfLastNot();
  14125. },
  14126. });
  14127. }
  14128. addMethod(structure) {
  14129. return this.addMethods([structure])[0];
  14130. }
  14131. addMethods(structures) {
  14132. return this.insertMethods(getEndIndexFromArray(this.getMembersWithComments()), structures);
  14133. }
  14134. insertMethod(index, structure) {
  14135. return this.insertMethods(index, [structure])[0];
  14136. }
  14137. insertMethods(index, structures) {
  14138. const isAmbient = isNodeAmbientOrInAmbientContext(this);
  14139. structures = structures.map(s => ({ ...s }));
  14140. return insertChildren(this, {
  14141. index,
  14142. write: (writer, info) => {
  14143. if (!isAmbient && info.previousMember != null && !Node.isCommentNode(info.previousMember))
  14144. writer.blankLineIfLastNot();
  14145. else
  14146. writer.newLineIfLastNot();
  14147. this._context.structurePrinterFactory.forMethodDeclaration({ isAmbient }).printTexts(writer, structures);
  14148. if (!isAmbient && info.nextMember != null)
  14149. writer.blankLineIfLastNot();
  14150. else
  14151. writer.newLineIfLastNot();
  14152. },
  14153. structures,
  14154. expectedKind: common.SyntaxKind.MethodDeclaration,
  14155. });
  14156. }
  14157. getInstanceProperty(nameOrFindFunction) {
  14158. return getNodeByNameOrFindFunction(this.getInstanceProperties(), nameOrFindFunction);
  14159. }
  14160. getInstancePropertyOrThrow(nameOrFindFunction) {
  14161. return common.errors.throwIfNullOrUndefined(this.getInstanceProperty(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("class instance property", nameOrFindFunction));
  14162. }
  14163. getInstanceProperties() {
  14164. return this.getInstanceMembers()
  14165. .filter(m => isClassPropertyType(m));
  14166. }
  14167. getStaticProperty(nameOrFindFunction) {
  14168. return getNodeByNameOrFindFunction(this.getStaticProperties(), nameOrFindFunction);
  14169. }
  14170. getStaticPropertyOrThrow(nameOrFindFunction) {
  14171. return common.errors.throwIfNullOrUndefined(this.getStaticProperty(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("class static property", nameOrFindFunction));
  14172. }
  14173. getStaticProperties() {
  14174. return this.getStaticMembers()
  14175. .filter(m => isClassPropertyType(m));
  14176. }
  14177. getProperty(nameOrFindFunction) {
  14178. return getNodeByNameOrFindFunction(this.getProperties(), nameOrFindFunction);
  14179. }
  14180. getPropertyOrThrow(nameOrFindFunction) {
  14181. return common.errors.throwIfNullOrUndefined(this.getProperty(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("class property declaration", nameOrFindFunction));
  14182. }
  14183. getProperties() {
  14184. return this.getMembers()
  14185. .filter(m => Node.isPropertyDeclaration(m));
  14186. }
  14187. getGetAccessor(nameOrFindFunction) {
  14188. return getNodeByNameOrFindFunction(this.getGetAccessors(), nameOrFindFunction);
  14189. }
  14190. getGetAccessorOrThrow(nameOrFindFunction) {
  14191. return common.errors.throwIfNullOrUndefined(this.getGetAccessor(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("class getAccessor declaration", nameOrFindFunction));
  14192. }
  14193. getGetAccessors() {
  14194. return this.getMembers()
  14195. .filter(m => Node.isGetAccessorDeclaration(m));
  14196. }
  14197. getSetAccessor(nameOrFindFunction) {
  14198. return getNodeByNameOrFindFunction(this.getSetAccessors(), nameOrFindFunction);
  14199. }
  14200. getSetAccessorOrThrow(nameOrFindFunction) {
  14201. return common.errors.throwIfNullOrUndefined(this.getSetAccessor(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("class setAccessor declaration", nameOrFindFunction));
  14202. }
  14203. getSetAccessors() {
  14204. return this.getMembers()
  14205. .filter(m => Node.isSetAccessorDeclaration(m));
  14206. }
  14207. getMethod(nameOrFindFunction) {
  14208. return getNodeByNameOrFindFunction(this.getMethods(), nameOrFindFunction);
  14209. }
  14210. getMethodOrThrow(nameOrFindFunction) {
  14211. return common.errors.throwIfNullOrUndefined(this.getMethod(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("class method declaration", nameOrFindFunction));
  14212. }
  14213. getMethods() {
  14214. return this.getMembers()
  14215. .filter(m => Node.isMethodDeclaration(m));
  14216. }
  14217. getInstanceMethod(nameOrFindFunction) {
  14218. return getNodeByNameOrFindFunction(this.getInstanceMethods(), nameOrFindFunction);
  14219. }
  14220. getInstanceMethodOrThrow(nameOrFindFunction) {
  14221. return common.errors.throwIfNullOrUndefined(this.getInstanceMethod(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("class instance method", nameOrFindFunction));
  14222. }
  14223. getInstanceMethods() {
  14224. return this.getInstanceMembers().filter(m => m instanceof MethodDeclaration);
  14225. }
  14226. getStaticMethod(nameOrFindFunction) {
  14227. return getNodeByNameOrFindFunction(this.getStaticMethods(), nameOrFindFunction);
  14228. }
  14229. getStaticMethodOrThrow(nameOrFindFunction) {
  14230. return common.errors.throwIfNullOrUndefined(this.getStaticMethod(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("class static method", nameOrFindFunction));
  14231. }
  14232. getStaticMethods() {
  14233. return this.getStaticMembers().filter(m => m instanceof MethodDeclaration);
  14234. }
  14235. getInstanceMember(nameOrFindFunction) {
  14236. return getNodeByNameOrFindFunction(this.getInstanceMembers(), nameOrFindFunction);
  14237. }
  14238. getInstanceMemberOrThrow(nameOrFindFunction) {
  14239. return common.errors.throwIfNullOrUndefined(this.getInstanceMember(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("class instance member", nameOrFindFunction));
  14240. }
  14241. getInstanceMembers() {
  14242. return this.getMembersWithParameterProperties().filter(m => {
  14243. if (Node.isConstructorDeclaration(m))
  14244. return false;
  14245. return Node.isParameterDeclaration(m) || !m.isStatic();
  14246. });
  14247. }
  14248. getStaticMember(nameOrFindFunction) {
  14249. return getNodeByNameOrFindFunction(this.getStaticMembers(), nameOrFindFunction);
  14250. }
  14251. getStaticMemberOrThrow(nameOrFindFunction) {
  14252. return common.errors.throwIfNullOrUndefined(this.getStaticMember(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("class static member", nameOrFindFunction));
  14253. }
  14254. getStaticMembers() {
  14255. return this.getMembers().filter(m => {
  14256. if (Node.isConstructorDeclaration(m))
  14257. return false;
  14258. return !Node.isParameterDeclaration(m) && m.isStatic();
  14259. });
  14260. }
  14261. getMembersWithParameterProperties() {
  14262. const members = this.getMembers();
  14263. const implementationCtors = members.filter(c => Node.isConstructorDeclaration(c) && c.isImplementation());
  14264. for (const ctor of implementationCtors) {
  14265. let insertIndex = members.indexOf(ctor) + 1;
  14266. for (const param of ctor.getParameters()) {
  14267. if (param.isParameterProperty()) {
  14268. members.splice(insertIndex, 0, param);
  14269. insertIndex++;
  14270. }
  14271. }
  14272. }
  14273. return members;
  14274. }
  14275. getMembers() {
  14276. return getAllMembers(this, this.compilerNode.members).filter(m => isSupportedClassMember(m));
  14277. }
  14278. getMembersWithComments() {
  14279. const compilerNode = this.compilerNode;
  14280. const members = ExtendedParser.getContainerArray(compilerNode, this.getSourceFile().compilerNode);
  14281. return getAllMembers(this, members)
  14282. .filter(m => isSupportedClassMember(m) || Node.isCommentClassElement(m));
  14283. }
  14284. getMember(nameOrFindFunction) {
  14285. return getNodeByNameOrFindFunction(this.getMembers(), nameOrFindFunction);
  14286. }
  14287. getMemberOrThrow(nameOrFindFunction) {
  14288. return common.errors.throwIfNullOrUndefined(this.getMember(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("class member", nameOrFindFunction));
  14289. }
  14290. getBaseTypes() {
  14291. return this.getType().getBaseTypes();
  14292. }
  14293. getBaseClassOrThrow(message) {
  14294. return common.errors.throwIfNullOrUndefined(this.getBaseClass(), message ?? `Expected to find the base class of ${this.getName()}.`, this);
  14295. }
  14296. getBaseClass() {
  14297. const baseTypes = this.getBaseTypes().map(t => t.isIntersection() ? t.getIntersectionTypes() : [t]).flat();
  14298. const declarations = baseTypes
  14299. .map(t => t.getSymbol())
  14300. .filter(s => s != null)
  14301. .map(s => s.getDeclarations())
  14302. .reduce((a, b) => a.concat(b), [])
  14303. .filter(d => d.getKind() === common.SyntaxKind.ClassDeclaration);
  14304. if (declarations.length !== 1)
  14305. return undefined;
  14306. return declarations[0];
  14307. }
  14308. getDerivedClasses() {
  14309. const classes = getImmediateDerivedClasses(this);
  14310. for (let i = 0; i < classes.length; i++) {
  14311. const derivedClasses = getImmediateDerivedClasses(classes[i]);
  14312. for (const derivedClass of derivedClasses) {
  14313. if (derivedClass !== this && classes.indexOf(derivedClass) === -1)
  14314. classes.push(derivedClass);
  14315. }
  14316. }
  14317. return classes;
  14318. }
  14319. };
  14320. }
  14321. function getAllMembers(classDec, compilerMembers) {
  14322. const isAmbient = isNodeAmbientOrInAmbientContext(classDec);
  14323. const members = compilerMembers.map(m => classDec._getNodeFromCompilerNode(m));
  14324. return isAmbient ? members : members.filter(m => {
  14325. if (!(Node.isConstructorDeclaration(m) || Node.isMethodDeclaration(m)))
  14326. return true;
  14327. if (Node.isMethodDeclaration(m) && m.isAbstract())
  14328. return true;
  14329. return m.isImplementation();
  14330. });
  14331. }
  14332. function getImmediateDerivedClasses(classDec) {
  14333. const classes = [];
  14334. const nameNode = classDec.getNameNode();
  14335. if (nameNode == null)
  14336. return classes;
  14337. for (let node of nameNode.findReferencesAsNodes()) {
  14338. node = node.getParentWhileKind(common.SyntaxKind.PropertyAccessExpression) ?? node;
  14339. const nodeParent = node.getParentIfKind(common.SyntaxKind.ExpressionWithTypeArguments);
  14340. if (nodeParent == null)
  14341. continue;
  14342. const heritageClause = nodeParent.getParentIfKind(common.SyntaxKind.HeritageClause);
  14343. if (heritageClause == null || heritageClause.getToken() !== common.SyntaxKind.ExtendsKeyword)
  14344. continue;
  14345. const derivedClass = heritageClause.getParentIfKind(common.SyntaxKind.ClassDeclaration);
  14346. if (derivedClass == null)
  14347. continue;
  14348. classes.push(derivedClass);
  14349. }
  14350. return classes;
  14351. }
  14352. function isClassPropertyType(m) {
  14353. return Node.isPropertyDeclaration(m)
  14354. || Node.isSetAccessorDeclaration(m)
  14355. || Node.isGetAccessorDeclaration(m)
  14356. || Node.isParameterDeclaration(m);
  14357. }
  14358. function isSupportedClassMember(m) {
  14359. return Node.isMethodDeclaration(m)
  14360. || Node.isPropertyDeclaration(m)
  14361. || Node.isGetAccessorDeclaration(m)
  14362. || Node.isSetAccessorDeclaration(m)
  14363. || Node.isConstructorDeclaration(m)
  14364. || Node.isClassStaticBlockDeclaration(m);
  14365. }
  14366. function insertChildren(classDeclaration, opts) {
  14367. return insertIntoBracesOrSourceFileWithGetChildren({
  14368. getIndexedChildren: () => classDeclaration.getMembersWithComments(),
  14369. parent: classDeclaration,
  14370. ...opts,
  14371. });
  14372. }
  14373. const createBase$k = (ctor) => ModuleChildableNode(AmbientableNode(ExportableNode(ClassLikeDeclarationBase(ctor))));
  14374. const ClassDeclarationBase = createBase$k(Statement);
  14375. class ClassDeclaration extends ClassDeclarationBase {
  14376. set(structure) {
  14377. callBaseSet(ClassDeclarationBase.prototype, this, structure);
  14378. if (structure.extends != null)
  14379. this.setExtends(structure.extends);
  14380. else if (structure.hasOwnProperty(common.nameof(structure, "extends")))
  14381. this.removeExtends();
  14382. if (structure.ctors != null) {
  14383. this.getConstructors().forEach(c => c.remove());
  14384. this.addConstructors(structure.ctors);
  14385. }
  14386. if (structure.staticBlocks != null) {
  14387. this.getStaticBlocks().forEach(c => c.remove());
  14388. this.addStaticBlocks(structure.staticBlocks);
  14389. }
  14390. if (structure.properties != null) {
  14391. this.getProperties().forEach(p => p.remove());
  14392. this.addProperties(structure.properties);
  14393. }
  14394. if (structure.getAccessors != null) {
  14395. this.getGetAccessors().forEach(a => a.remove());
  14396. this.addGetAccessors(structure.getAccessors);
  14397. }
  14398. if (structure.setAccessors != null) {
  14399. this.getSetAccessors().forEach(a => a.remove());
  14400. this.addSetAccessors(structure.setAccessors);
  14401. }
  14402. if (structure.methods != null) {
  14403. this.getMethods().forEach(m => m.remove());
  14404. this.addMethods(structure.methods);
  14405. }
  14406. return this;
  14407. }
  14408. getStructure() {
  14409. const getExtends = this.getExtends();
  14410. const isAmbient = this.isAmbient();
  14411. return callBaseGetStructure(ClassDeclarationBase.prototype, this, {
  14412. kind: exports.StructureKind.Class,
  14413. ctors: this.getConstructors().filter(ctor => isAmbient || !ctor.isOverload()).map(ctor => ctor.getStructure()),
  14414. staticBlocks: this.getStaticBlocks().map(ctor => ctor.getStructure()),
  14415. methods: this.getMethods().filter(method => isAmbient || !method.isOverload()).map(method => method.getStructure()),
  14416. properties: this.getProperties().map(property => property.getStructure()),
  14417. extends: getExtends ? getExtends.getText() : undefined,
  14418. getAccessors: this.getGetAccessors().map(getAccessor => getAccessor.getStructure()),
  14419. setAccessors: this.getSetAccessors().map(accessor => accessor.getStructure()),
  14420. });
  14421. }
  14422. extractInterface(name) {
  14423. const { constructors, properties, methods, accessors } = getExtractedClassDetails(this, false);
  14424. const parameterProperties = constructors.map(c => c.getParameters().filter(p => p.isParameterProperty()))
  14425. .flat()
  14426. .filter(p => p.getName() != null && p.getScope() === exports.Scope.Public);
  14427. return {
  14428. kind: exports.StructureKind.Interface,
  14429. name: getDefaultExtractedName(name, this),
  14430. docs: this.getJsDocs().map(d => d.getStructure()),
  14431. typeParameters: this.getTypeParameters().map(p => p.getStructure()),
  14432. properties: [
  14433. ...parameterProperties.map(p => {
  14434. const jsDocComment = p.getParentOrThrow().getJsDocs().map(j => j.getTags())
  14435. .flat()
  14436. .filter(Node.isJSDocParameterTag)
  14437. .filter(t => t.getTagName() === "param" && t.getName() === p.getName() && t.getComment() != null)
  14438. .map(t => t.getCommentText().trim())[0];
  14439. return {
  14440. kind: exports.StructureKind.PropertySignature,
  14441. docs: jsDocComment == null ? [] : [{ kind: exports.StructureKind.JSDoc, description: jsDocComment }],
  14442. name: p.getName(),
  14443. type: p.getType().getText(p),
  14444. hasQuestionToken: p.hasQuestionToken(),
  14445. isReadonly: p.isReadonly(),
  14446. };
  14447. }),
  14448. ...properties.map(getExtractedInterfacePropertyStructure),
  14449. ...accessors.map(getExtractedInterfaceAccessorStructure),
  14450. ],
  14451. methods: methods.map(getExtractedInterfaceMethodStructure),
  14452. };
  14453. }
  14454. extractStaticInterface(name) {
  14455. const { constructors, properties, methods, accessors } = getExtractedClassDetails(this, true);
  14456. const instanceName = getDefaultExtractedName(undefined, this);
  14457. return {
  14458. kind: exports.StructureKind.Interface,
  14459. name,
  14460. properties: [
  14461. ...properties.map(getExtractedInterfacePropertyStructure),
  14462. ...accessors.map(getExtractedInterfaceAccessorStructure),
  14463. ],
  14464. methods: methods.map(getExtractedInterfaceMethodStructure),
  14465. constructSignatures: constructors.map(c => ({
  14466. kind: exports.StructureKind.ConstructSignature,
  14467. docs: c.getJsDocs().map(d => d.getStructure()),
  14468. parameters: c.getParameters().map(p => ({
  14469. ...getExtractedInterfaceParameterStructure(p),
  14470. scope: undefined,
  14471. isReadonly: false,
  14472. })),
  14473. returnType: instanceName,
  14474. })),
  14475. };
  14476. }
  14477. }
  14478. function getExtractedClassDetails(classDec, isStatic) {
  14479. const constructors = classDec.getConstructors().map(c => c.getOverloads().length > 0 ? c.getOverloads() : [c]).flat();
  14480. const properties = classDec.getProperties().filter(p => p.isStatic() === isStatic && p.getScope() === exports.Scope.Public);
  14481. const methods = classDec.getMethods()
  14482. .filter(p => p.isStatic() === isStatic && p.getScope() === exports.Scope.Public)
  14483. .map(m => m.getOverloads().length > 0 ? m.getOverloads() : [m]).flat();
  14484. return { constructors, properties, methods, accessors: getAccessors() };
  14485. function getAccessors() {
  14486. const result = new common.KeyValueCache();
  14487. for (const accessor of [...classDec.getGetAccessors(), ...classDec.getSetAccessors()]) {
  14488. if (accessor.isStatic() === isStatic && accessor.getScope() === exports.Scope.Public)
  14489. result.getOrCreate(accessor.getName(), () => []).push(accessor);
  14490. }
  14491. return result.getValuesAsArray();
  14492. }
  14493. }
  14494. function getDefaultExtractedName(name, classDec) {
  14495. name = common.StringUtils.isNullOrWhitespace(name) ? undefined : name;
  14496. return name || classDec.getName() || classDec.getSourceFile().getBaseNameWithoutExtension().replace(/[^a-zA-Z0-9_$]/g, "");
  14497. }
  14498. function getExtractedInterfacePropertyStructure(prop) {
  14499. return {
  14500. kind: exports.StructureKind.PropertySignature,
  14501. docs: prop.getJsDocs().map(d => d.getStructure()),
  14502. name: prop.getName(),
  14503. type: prop.getType().getText(prop),
  14504. hasQuestionToken: prop.hasQuestionToken(),
  14505. isReadonly: prop.isReadonly(),
  14506. };
  14507. }
  14508. function getExtractedInterfaceAccessorStructure(getAndSet) {
  14509. return {
  14510. kind: exports.StructureKind.PropertySignature,
  14511. docs: getAndSet[0].getJsDocs().map(d => d.getStructure()),
  14512. name: getAndSet[0].getName(),
  14513. type: getAndSet[0].getType().getText(getAndSet[0]),
  14514. hasQuestionToken: false,
  14515. isReadonly: getAndSet.every(Node.isGetAccessorDeclaration),
  14516. };
  14517. }
  14518. function getExtractedInterfaceMethodStructure(method) {
  14519. return {
  14520. kind: exports.StructureKind.MethodSignature,
  14521. docs: method.getJsDocs().map(d => d.getStructure()),
  14522. name: method.getName(),
  14523. hasQuestionToken: method.hasQuestionToken(),
  14524. returnType: method.getReturnType().getText(method),
  14525. parameters: method.getParameters().map(getExtractedInterfaceParameterStructure),
  14526. typeParameters: method.getTypeParameters().map(p => p.getStructure()),
  14527. };
  14528. }
  14529. function getExtractedInterfaceParameterStructure(param) {
  14530. return {
  14531. ...param.getStructure(),
  14532. decorators: [],
  14533. };
  14534. }
  14535. const ClassExpressionBase = ClassLikeDeclarationBase(PrimaryExpression);
  14536. class ClassExpression extends ClassExpressionBase {
  14537. }
  14538. const createBase$j = (ctor) => ChildOrderableNode(TextInsertableNode(StatementedNode(JSDocableNode(BodiedNode(ctor)))));
  14539. const ClassStaticBlockDeclarationBase = createBase$j(ClassElement);
  14540. class ClassStaticBlockDeclaration extends ClassStaticBlockDeclarationBase {
  14541. getName() {
  14542. return "static";
  14543. }
  14544. isStatic() {
  14545. return true;
  14546. }
  14547. set(structure) {
  14548. callBaseSet(ClassStaticBlockDeclarationBase.prototype, this, structure);
  14549. return this;
  14550. }
  14551. getStructure() {
  14552. return callBaseGetStructure(ClassStaticBlockDeclarationBase.prototype, this, {
  14553. kind: exports.StructureKind.ClassStaticBlock,
  14554. });
  14555. }
  14556. }
  14557. class CommentClassElement extends ClassElement {
  14558. }
  14559. const createBase$i = (ctor) => ReferenceFindableNode(ChildOrderableNode(TextInsertableNode(OverloadableNode(ScopedNode(FunctionLikeDeclaration(BodyableNode(ctor)))))));
  14560. const ConstructorDeclarationBase = createBase$i(ClassElement);
  14561. const createOverloadBase = (ctor) => TypeParameteredNode(JSDocableNode(ChildOrderableNode(TextInsertableNode(ScopedNode(ModifierableNode(SignaturedDeclaration(ctor)))))));
  14562. const ConstructorDeclarationOverloadBase = createOverloadBase(ClassElement);
  14563. class ConstructorDeclaration extends ConstructorDeclarationBase {
  14564. set(structure) {
  14565. callBaseSet(ConstructorDeclarationBase.prototype, this, structure);
  14566. if (structure.overloads != null) {
  14567. this.getOverloads().forEach(o => o.remove());
  14568. this.addOverloads(structure.overloads);
  14569. }
  14570. return this;
  14571. }
  14572. addOverload(structure) {
  14573. return this.addOverloads([structure])[0];
  14574. }
  14575. addOverloads(structures) {
  14576. return this.insertOverloads(this.getOverloads().length, structures);
  14577. }
  14578. insertOverload(index, structure) {
  14579. return this.insertOverloads(index, [structure])[0];
  14580. }
  14581. insertOverloads(index, structures) {
  14582. const printer = this._context.structurePrinterFactory.forConstructorDeclaration({
  14583. isAmbient: isNodeAmbientOrInAmbientContext(this),
  14584. });
  14585. return insertOverloads({
  14586. node: this,
  14587. index,
  14588. structures,
  14589. printStructure: (writer, structure) => {
  14590. printer.printOverload(writer, structure);
  14591. },
  14592. getThisStructure: fromConstructorDeclarationOverload,
  14593. expectedSyntaxKind: common.SyntaxKind.Constructor,
  14594. });
  14595. }
  14596. getStructure() {
  14597. const hasImplementation = this.getImplementation() != null;
  14598. const isOverload = this.isOverload();
  14599. const basePrototype = isOverload && hasImplementation ? ConstructorDeclarationOverloadBase.prototype : ConstructorDeclarationBase.prototype;
  14600. return callBaseGetStructure(basePrototype, this, getStructure(this));
  14601. function getStructure(thisNode) {
  14602. if (hasImplementation && isOverload)
  14603. return getSpecificOverloadStructure();
  14604. return getSpecificStructure();
  14605. function getSpecificOverloadStructure() {
  14606. return { kind: exports.StructureKind.ConstructorOverload };
  14607. }
  14608. function getSpecificStructure() {
  14609. if (!hasImplementation)
  14610. return { kind: exports.StructureKind.Constructor };
  14611. else {
  14612. return {
  14613. kind: exports.StructureKind.Constructor,
  14614. overloads: thisNode.getOverloads().map(o => o.getStructure()),
  14615. };
  14616. }
  14617. }
  14618. }
  14619. }
  14620. }
  14621. const createBase$h = (ctor) => ChildOrderableNode(TextInsertableNode(DecoratableNode(AbstractableNode(ScopedNode(StaticableNode(FunctionLikeDeclaration(BodyableNode(PropertyNamedNode(ctor)))))))));
  14622. const GetAccessorDeclarationBase = createBase$h(ClassElement);
  14623. class GetAccessorDeclaration extends GetAccessorDeclarationBase {
  14624. set(structure) {
  14625. callBaseSet(GetAccessorDeclarationBase.prototype, this, structure);
  14626. return this;
  14627. }
  14628. getSetAccessor() {
  14629. const thisName = this.getName();
  14630. const isStatic = this.isStatic();
  14631. return this.getParentOrThrow().forEachChild(sibling => {
  14632. if (Node.isSetAccessorDeclaration(sibling) && sibling.getName() === thisName && sibling.isStatic() === isStatic)
  14633. return sibling;
  14634. return undefined;
  14635. });
  14636. }
  14637. getSetAccessorOrThrow(message) {
  14638. return common.errors.throwIfNullOrUndefined(this.getSetAccessor(), message ?? (() => `Expected to find a corresponding set accessor for ${this.getName()}.`), this);
  14639. }
  14640. getStructure() {
  14641. return callBaseGetStructure(GetAccessorDeclarationBase.prototype, this, {
  14642. kind: exports.StructureKind.GetAccessor,
  14643. });
  14644. }
  14645. }
  14646. const createBase$g = (ctor) => ChildOrderableNode(OverrideableNode(AmbientableNode(DecoratableNode(AbstractableNode(ScopedNode(StaticableNode(JSDocableNode(ReadonlyableNode(ExclamationTokenableNode(QuestionTokenableNode(InitializerExpressionableNode(TypedNode(PropertyNamedNode(ModifierableNode(ctor)))))))))))))));
  14647. const PropertyDeclarationBase = createBase$g(ClassElement);
  14648. class PropertyDeclaration extends PropertyDeclarationBase {
  14649. hasAccessorKeyword() {
  14650. return this.hasModifier(common.SyntaxKind.AccessorKeyword);
  14651. }
  14652. setHasAccessorKeyword(value) {
  14653. return this.toggleModifier("accessor", value);
  14654. }
  14655. set(structure) {
  14656. callBaseSet(PropertyDeclarationBase.prototype, this, structure);
  14657. if (structure.hasAccessorKeyword != null)
  14658. this.setHasAccessorKeyword(structure.hasAccessorKeyword);
  14659. return this;
  14660. }
  14661. remove() {
  14662. const parent = this.getParentOrThrow();
  14663. switch (parent.getKind()) {
  14664. case common.SyntaxKind.ClassDeclaration:
  14665. super.remove();
  14666. break;
  14667. default:
  14668. throw new common.errors.NotImplementedError(`Not implemented parent syntax kind: ${parent.getKindName()}`);
  14669. }
  14670. }
  14671. getStructure() {
  14672. return callBaseGetStructure(PropertyDeclarationBase.prototype, this, {
  14673. kind: exports.StructureKind.Property,
  14674. hasAccessorKeyword: this.hasAccessorKeyword(),
  14675. });
  14676. }
  14677. }
  14678. const createBase$f = (ctor) => ChildOrderableNode(TextInsertableNode(DecoratableNode(AbstractableNode(ScopedNode(StaticableNode(FunctionLikeDeclaration(BodyableNode(PropertyNamedNode(ctor)))))))));
  14679. const SetAccessorDeclarationBase = createBase$f(ClassElement);
  14680. class SetAccessorDeclaration extends SetAccessorDeclarationBase {
  14681. set(structure) {
  14682. callBaseSet(SetAccessorDeclarationBase.prototype, this, structure);
  14683. return this;
  14684. }
  14685. getGetAccessor() {
  14686. const thisName = this.getName();
  14687. const isStatic = this.isStatic();
  14688. return this.getParentOrThrow().forEachChild(sibling => {
  14689. if (Node.isGetAccessorDeclaration(sibling) && sibling.getName() === thisName && sibling.isStatic() === isStatic)
  14690. return sibling;
  14691. return undefined;
  14692. });
  14693. }
  14694. getGetAccessorOrThrow(message) {
  14695. return common.errors.throwIfNullOrUndefined(this.getGetAccessor(), message ?? (() => `Expected to find a corresponding get accessor for ${this.getName()}.`), this);
  14696. }
  14697. getStructure() {
  14698. return callBaseGetStructure(SetAccessorDeclarationBase.prototype, this, {
  14699. kind: exports.StructureKind.SetAccessor,
  14700. });
  14701. }
  14702. }
  14703. const DecoratorBase = LeftHandSideExpressionedNode(Node);
  14704. class Decorator extends DecoratorBase {
  14705. getName() {
  14706. return this.getNameNode().getText();
  14707. }
  14708. getNameNode() {
  14709. const callExpression = this.getCallExpression();
  14710. if (callExpression)
  14711. return getIdentifierFromName(callExpression.getExpression());
  14712. else
  14713. return getIdentifierFromName(this._getInnerExpression());
  14714. function getIdentifierFromName(expression) {
  14715. const identifier = getNameFromExpression(expression);
  14716. if (!Node.isIdentifier(identifier)) {
  14717. throw new common.errors.NotImplementedError(`Expected the decorator expression '${identifier.getText()}' to be an identifier. `
  14718. + `Please deal directly with 'getExpression()' on the decorator to handle more complex scenarios.`);
  14719. }
  14720. return identifier;
  14721. }
  14722. function getNameFromExpression(expression) {
  14723. if (Node.isPropertyAccessExpression(expression))
  14724. return expression.getNameNode();
  14725. return expression;
  14726. }
  14727. }
  14728. getFullName() {
  14729. const sourceFile = this.getSourceFile();
  14730. if (this.isDecoratorFactory())
  14731. return this.getCallExpression().getExpression().getText();
  14732. return this.compilerNode.expression.getText(sourceFile.compilerNode);
  14733. }
  14734. isDecoratorFactory() {
  14735. return Node.isCallExpression(this._getInnerExpression());
  14736. }
  14737. setIsDecoratorFactory(isDecoratorFactory) {
  14738. if (this.isDecoratorFactory() === isDecoratorFactory)
  14739. return this;
  14740. if (isDecoratorFactory) {
  14741. const expression = this._getInnerExpression();
  14742. const expressionText = expression.getText();
  14743. insertIntoParentTextRange({
  14744. parent: this,
  14745. insertPos: expression.getStart(),
  14746. newText: `${expressionText}()`,
  14747. replacing: {
  14748. textLength: expressionText.length,
  14749. },
  14750. customMappings: newParent => {
  14751. return [{ currentNode: expression, newNode: newParent.expression.expression }];
  14752. },
  14753. });
  14754. }
  14755. else {
  14756. const callExpression = this.getCallExpressionOrThrow();
  14757. const expression = callExpression.getExpression();
  14758. const expressionText = expression.getText();
  14759. insertIntoParentTextRange({
  14760. parent: this,
  14761. insertPos: callExpression.getStart(),
  14762. newText: `${expressionText}`,
  14763. replacing: {
  14764. textLength: callExpression.getWidth(),
  14765. },
  14766. customMappings: newParent => {
  14767. return [{ currentNode: expression, newNode: newParent.expression }];
  14768. },
  14769. });
  14770. }
  14771. return this;
  14772. }
  14773. getCallExpressionOrThrow(message) {
  14774. return common.errors.throwIfNullOrUndefined(this.getCallExpression(), message ?? "Expected to find a call expression.", this);
  14775. }
  14776. getCallExpression() {
  14777. const expression = this._getInnerExpression();
  14778. return Node.isCallExpression(expression) ? expression : undefined;
  14779. }
  14780. getArguments() {
  14781. return this.getCallExpression()?.getArguments() ?? [];
  14782. }
  14783. getTypeArguments() {
  14784. return this.getCallExpression()?.getTypeArguments() ?? [];
  14785. }
  14786. addTypeArgument(argumentText) {
  14787. return this.getCallExpressionOrThrow().addTypeArgument(argumentText);
  14788. }
  14789. addTypeArguments(argumentTexts) {
  14790. return this.getCallExpressionOrThrow().addTypeArguments(argumentTexts);
  14791. }
  14792. insertTypeArgument(index, argumentText) {
  14793. return this.getCallExpressionOrThrow().insertTypeArgument(index, argumentText);
  14794. }
  14795. insertTypeArguments(index, argumentTexts) {
  14796. return this.getCallExpressionOrThrow().insertTypeArguments(index, argumentTexts);
  14797. }
  14798. removeTypeArgument(typeArgOrIndex) {
  14799. const callExpression = this.getCallExpression();
  14800. if (callExpression == null)
  14801. throw new common.errors.InvalidOperationError("Cannot remove a type argument from a decorator that has no type arguments.");
  14802. callExpression.removeTypeArgument(typeArgOrIndex);
  14803. return this;
  14804. }
  14805. addArgument(argumentText) {
  14806. return this.addArguments([argumentText])[0];
  14807. }
  14808. addArguments(argumentTexts) {
  14809. return this.insertArguments(this.getArguments().length, argumentTexts);
  14810. }
  14811. insertArgument(index, argumentText) {
  14812. return this.insertArguments(index, [argumentText])[0];
  14813. }
  14814. insertArguments(index, argumentTexts) {
  14815. this.setIsDecoratorFactory(true);
  14816. return this.getCallExpressionOrThrow().insertArguments(index, argumentTexts);
  14817. }
  14818. removeArgument(argOrIndex) {
  14819. const callExpression = this.getCallExpression();
  14820. if (callExpression == null)
  14821. throw new common.errors.InvalidOperationError("Cannot remove an argument from a decorator that has no arguments.");
  14822. callExpression.removeArgument(argOrIndex);
  14823. return this;
  14824. }
  14825. remove() {
  14826. const thisStartLinePos = this.getStartLinePos();
  14827. const previousDecorator = this.getPreviousSiblingIfKind(common.SyntaxKind.Decorator);
  14828. if (previousDecorator != null && previousDecorator.getStartLinePos() === thisStartLinePos) {
  14829. removeChildren({
  14830. children: [this],
  14831. removePrecedingSpaces: true,
  14832. });
  14833. }
  14834. else {
  14835. removeChildrenWithFormattingFromCollapsibleSyntaxList({
  14836. children: [this],
  14837. getSiblingFormatting: (parent, sibling) => sibling.getStartLinePos() === thisStartLinePos ? FormattingKind.Space : FormattingKind.Newline,
  14838. });
  14839. }
  14840. }
  14841. _getInnerExpression() {
  14842. let expr = this.getExpression();
  14843. while (Node.isParenthesizedExpression(expr))
  14844. expr = expr.getExpression();
  14845. return expr;
  14846. }
  14847. set(structure) {
  14848. callBaseSet(DecoratorBase.prototype, this, structure);
  14849. if (structure.name != null)
  14850. this.getNameNode().replaceWithText(structure.name);
  14851. if (structure.arguments != null) {
  14852. this.setIsDecoratorFactory(true);
  14853. this.getArguments().map(a => this.removeArgument(a));
  14854. this.addArguments(structure.arguments);
  14855. }
  14856. if (structure.typeArguments != null && structure.typeArguments.length > 0) {
  14857. this.setIsDecoratorFactory(true);
  14858. this.getTypeArguments().map(a => this.removeTypeArgument(a));
  14859. this.addTypeArguments(structure.typeArguments);
  14860. }
  14861. return this;
  14862. }
  14863. getStructure() {
  14864. const isDecoratorFactory = this.isDecoratorFactory();
  14865. return callBaseGetStructure(DecoratorBase.prototype, this, {
  14866. kind: exports.StructureKind.Decorator,
  14867. name: this.getName(),
  14868. arguments: isDecoratorFactory ? this.getArguments().map(arg => arg.getText()) : undefined,
  14869. typeArguments: isDecoratorFactory ? this.getTypeArguments().map(arg => arg.getText()) : undefined,
  14870. });
  14871. }
  14872. }
  14873. function JSDocPropertyLikeTag(Base) {
  14874. return class extends Base {
  14875. getTypeExpression() {
  14876. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.typeExpression);
  14877. }
  14878. getTypeExpressionOrThrow(message) {
  14879. return common.errors.throwIfNullOrUndefined(this.getTypeExpression(), message ?? `Expected to find a JS doc type expression.`, this);
  14880. }
  14881. getName() {
  14882. return this.getNameNode().getText();
  14883. }
  14884. getNameNode() {
  14885. return this._getNodeFromCompilerNode(this.compilerNode.name);
  14886. }
  14887. isBracketed() {
  14888. return this.compilerNode.isBracketed;
  14889. }
  14890. };
  14891. }
  14892. function JSDocTypeExpressionableTag(Base) {
  14893. return class extends Base {
  14894. getTypeExpression() {
  14895. const result = this._getNodeFromCompilerNodeIfExists(this.compilerNode.typeExpression);
  14896. if (result != null && result.getWidth() === 0)
  14897. return undefined;
  14898. return result;
  14899. }
  14900. getTypeExpressionOrThrow(message) {
  14901. return common.errors.throwIfNullOrUndefined(this.getTypeExpression(), message ?? `Expected to find the JS doc tag's type expression.`, this);
  14902. }
  14903. };
  14904. }
  14905. function JSDocTypeParameteredTag(Base) {
  14906. return class extends Base {
  14907. getTypeParameters() {
  14908. return this.compilerNode.typeParameters
  14909. .map(p => this._getNodeFromCompilerNode(p))
  14910. .filter(p => p.getWidth() > 0);
  14911. }
  14912. };
  14913. }
  14914. function getTextWithoutStars(inputText) {
  14915. const innerTextWithStars = inputText.replace(/^\/\*\*[^\S\n]*\n?/, "").replace(/(\r?\n)?[^\S\n]*\*\/$/, "");
  14916. return innerTextWithStars.split(/\n/).map(line => {
  14917. const starPos = getStarPosIfFirstNonWhitespaceChar(line);
  14918. if (starPos === -1)
  14919. return line;
  14920. const substringStart = line[starPos + 1] === " " ? starPos + 2 : starPos + 1;
  14921. return line.substring(substringStart);
  14922. }).join("\n");
  14923. function getStarPosIfFirstNonWhitespaceChar(text) {
  14924. for (let i = 0; i < text.length; i++) {
  14925. const charCode = text.charCodeAt(i);
  14926. if (charCode === CharCodes.ASTERISK)
  14927. return i;
  14928. else if (!common.StringUtils.isWhitespaceCharCode(charCode))
  14929. break;
  14930. }
  14931. return -1;
  14932. }
  14933. }
  14934. const JSDocBase = Node;
  14935. class JSDoc extends JSDocBase {
  14936. isMultiLine() {
  14937. return this.getText().includes("\n");
  14938. }
  14939. getTags() {
  14940. return this.compilerNode.tags?.map(t => this._getNodeFromCompilerNode(t)) ?? [];
  14941. }
  14942. getInnerText() {
  14943. return getTextWithoutStars(this.getText());
  14944. }
  14945. getComment() {
  14946. if (this.compilerNode.comment == null)
  14947. return undefined;
  14948. else if (typeof this.compilerNode.comment === "string")
  14949. return this.compilerNode.comment;
  14950. else
  14951. return this.compilerNode.comment.map(n => this._getNodeFromCompilerNodeIfExists(n));
  14952. }
  14953. getCommentText() {
  14954. if (typeof this.compilerNode.comment === "string")
  14955. return this.compilerNode.comment;
  14956. else
  14957. return common.ts.getTextOfJSDocComment(this.compilerNode.comment);
  14958. }
  14959. getDescription() {
  14960. const sourceFileText = this.getSourceFile().getFullText();
  14961. const endSearchStart = this.getTags()[0]?.getStart() ?? this.getEnd() - 2;
  14962. const start = getStart(this);
  14963. return getTextWithoutStars(sourceFileText.substring(start, Math.max(start, getEndPos())));
  14964. function getStart(jsDoc) {
  14965. const startOrSpacePos = jsDoc.getStart() + 3;
  14966. if (sourceFileText.charCodeAt(startOrSpacePos) === CharCodes.SPACE)
  14967. return startOrSpacePos + 1;
  14968. return startOrSpacePos;
  14969. }
  14970. function getEndPos() {
  14971. const endOrNewLinePos = getPreviousMatchingPos(sourceFileText, endSearchStart, charCode => charCode === CharCodes.NEWLINE || !common.StringUtils.isWhitespaceCharCode(charCode) && charCode !== CharCodes.ASTERISK);
  14972. return getPreviousMatchingPos(sourceFileText, endOrNewLinePos, charCode => charCode !== CharCodes.NEWLINE && charCode !== CharCodes.CARRIAGE_RETURN);
  14973. }
  14974. }
  14975. setDescription(textOrWriterFunction) {
  14976. const tags = this.getTags();
  14977. const startEditPos = this.getStart() + 3;
  14978. const endEditPos = tags.length > 0
  14979. ? getPreviousMatchingPos(this._sourceFile.getFullText(), tags[0].getStart(), c => c === CharCodes.ASTERISK) - 1
  14980. : this.getEnd() - 2;
  14981. replaceTextPossiblyCreatingChildNodes({
  14982. parent: this,
  14983. newText: getNewText.call(this),
  14984. replacePos: startEditPos,
  14985. replacingLength: endEditPos - startEditPos,
  14986. });
  14987. return this;
  14988. function getNewText() {
  14989. const indentationText = this.getIndentationText();
  14990. const newLineKind = this._context.manipulationSettings.getNewLineKindAsString();
  14991. const rawLines = getTextFromStringOrWriter(this._getWriter(), textOrWriterFunction).split(/\r?\n/);
  14992. const startsWithNewLine = rawLines[0].length === 0;
  14993. const isSingleLine = rawLines.length === 1 && (this.compilerNode.tags?.length ?? 0) === 0;
  14994. const linesText = isSingleLine ? rawLines[0] : rawLines.map(l => l.length === 0 ? `${indentationText} *` : `${indentationText} * ${l}`)
  14995. .slice(startsWithNewLine ? 1 : 0)
  14996. .join(newLineKind);
  14997. return isSingleLine ? " " + linesText + " " : newLineKind + linesText + newLineKind + indentationText + " ";
  14998. }
  14999. }
  15000. addTag(structure) {
  15001. return this.addTags([structure])[0];
  15002. }
  15003. addTags(structures) {
  15004. return this.insertTags(this.compilerNode.tags?.length ?? 0, structures);
  15005. }
  15006. insertTag(index, structure) {
  15007. return this.insertTags(index, [structure])[0];
  15008. }
  15009. insertTags(index, structures) {
  15010. if (common.ArrayUtils.isNullOrEmpty(structures))
  15011. return [];
  15012. const writer = this._getWriterWithQueuedIndentation();
  15013. const tags = this.getTags();
  15014. index = verifyAndGetIndex(index, tags.length);
  15015. if (tags.length === 0 && !this.isMultiLine()) {
  15016. const structurePrinter = this._context.structurePrinterFactory.forJSDoc();
  15017. this.replaceWithText(writer => {
  15018. structurePrinter.printText(writer, {
  15019. description: this.getDescription(),
  15020. tags: structures,
  15021. });
  15022. });
  15023. }
  15024. else {
  15025. const structurePrinter = this._context.structurePrinterFactory.forJSDocTag({ printStarsOnNewLine: true });
  15026. writer.newLine().write(" * ");
  15027. structurePrinter.printTexts(writer, structures);
  15028. writer.newLine().write(" *");
  15029. writer.conditionalWrite(index < tags.length, " ");
  15030. const replaceStart = getReplaceStart.call(this);
  15031. const replaceEnd = getReplaceEnd.call(this);
  15032. insertIntoParentTextRange({
  15033. parent: this,
  15034. insertPos: replaceStart,
  15035. replacing: { textLength: replaceEnd - replaceStart },
  15036. newText: writer.toString(),
  15037. });
  15038. }
  15039. return getNodesToReturn(tags, this.getTags(), index, false);
  15040. function getReplaceStart() {
  15041. const searchStart = index < tags.length ? tags[index].getStart() : this.getEnd() - 2;
  15042. const maxMin = this.getStart() + 3;
  15043. return Math.max(maxMin, getPreviousMatchingPos(this.getSourceFile().getFullText(), searchStart, charCode => !common.StringUtils.isWhitespaceCharCode(charCode) && charCode !== CharCodes.ASTERISK));
  15044. }
  15045. function getReplaceEnd() {
  15046. if (index < tags.length)
  15047. return tags[index].getStart();
  15048. return this.getEnd() - 1;
  15049. }
  15050. }
  15051. remove() {
  15052. removeChildren({
  15053. children: [this],
  15054. removeFollowingSpaces: true,
  15055. removeFollowingNewLines: true,
  15056. });
  15057. }
  15058. set(structure) {
  15059. callBaseSet(JSDocBase.prototype, this, structure);
  15060. if (structure.tags != null) {
  15061. return this.replaceWithText(writer => {
  15062. this._context.structurePrinterFactory.forJSDoc().printText(writer, {
  15063. description: structure.description ?? this.getDescription(),
  15064. tags: structure.tags,
  15065. });
  15066. });
  15067. }
  15068. else if (structure.description != null) {
  15069. this.setDescription(structure.description);
  15070. }
  15071. return this;
  15072. }
  15073. getStructure() {
  15074. return callBaseGetStructure(JSDocBase.prototype, this, {
  15075. kind: exports.StructureKind.JSDoc,
  15076. description: this.getDescription(),
  15077. tags: this.getTags().map(t => t.getStructure()),
  15078. });
  15079. }
  15080. }
  15081. class TypeNode extends Node {
  15082. }
  15083. const NodeWithTypeArgumentsBase = TypeArgumentedNode(TypeNode);
  15084. class NodeWithTypeArguments extends NodeWithTypeArgumentsBase {
  15085. }
  15086. class ArrayTypeNode extends TypeNode {
  15087. getElementTypeNode() {
  15088. return this._getNodeFromCompilerNode(this.compilerNode.elementType);
  15089. }
  15090. }
  15091. class ConditionalTypeNode extends TypeNode {
  15092. getCheckType() {
  15093. return this._getNodeFromCompilerNode(this.compilerNode.checkType);
  15094. }
  15095. getExtendsType() {
  15096. return this._getNodeFromCompilerNode(this.compilerNode.extendsType);
  15097. }
  15098. getTrueType() {
  15099. return this._getNodeFromCompilerNode(this.compilerNode.trueType);
  15100. }
  15101. getFalseType() {
  15102. return this._getNodeFromCompilerNode(this.compilerNode.falseType);
  15103. }
  15104. }
  15105. const FunctionOrConstructorTypeNodeBaseBase = SignaturedDeclaration(TypeNode);
  15106. class FunctionOrConstructorTypeNodeBase extends FunctionOrConstructorTypeNodeBaseBase {
  15107. }
  15108. const ConstructorTypeNodeBase = AbstractableNode(ModifierableNode(FunctionOrConstructorTypeNodeBase));
  15109. class ConstructorTypeNode extends ConstructorTypeNodeBase {
  15110. }
  15111. const ExpressionWithTypeArgumentsBase = LeftHandSideExpressionedNode(NodeWithTypeArguments);
  15112. class ExpressionWithTypeArguments extends ExpressionWithTypeArgumentsBase {
  15113. }
  15114. const FunctionTypeNodeBase = TypeParameteredNode(FunctionOrConstructorTypeNodeBase);
  15115. class FunctionTypeNode extends FunctionTypeNodeBase {
  15116. }
  15117. class ImportTypeNode extends NodeWithTypeArguments {
  15118. setArgument(text) {
  15119. const arg = this.getArgument();
  15120. if (Node.isLiteralTypeNode(arg)) {
  15121. const literal = arg.getLiteral();
  15122. if (Node.isStringLiteral(literal)) {
  15123. literal.setLiteralValue(text);
  15124. return this;
  15125. }
  15126. }
  15127. arg.replaceWithText(writer => writer.quote(text), this._getWriterWithQueuedChildIndentation());
  15128. return this;
  15129. }
  15130. getArgument() {
  15131. return this._getNodeFromCompilerNode(this.compilerNode.argument);
  15132. }
  15133. setQualifier(text) {
  15134. const qualifier = this.getQualifier();
  15135. if (qualifier != null)
  15136. qualifier.replaceWithText(text, this._getWriterWithQueuedChildIndentation());
  15137. else {
  15138. const paren = this.getFirstChildByKindOrThrow(common.SyntaxKind.CloseParenToken);
  15139. insertIntoParentTextRange({
  15140. insertPos: paren.getEnd(),
  15141. parent: this,
  15142. newText: this._getWriterWithQueuedIndentation().write(".").write(text).toString(),
  15143. });
  15144. }
  15145. return this;
  15146. }
  15147. getQualifierOrThrow(message) {
  15148. return common.errors.throwIfNullOrUndefined(this.getQualifier(), message ?? (() => `Expected to find a qualifier for the import type: ${this.getText()}`), this);
  15149. }
  15150. getQualifier() {
  15151. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.qualifier);
  15152. }
  15153. getAttributes() {
  15154. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.attributes);
  15155. }
  15156. getAttributesOrThrow(message) {
  15157. return common.errors.throwIfNullOrUndefined(this._getNodeFromCompilerNodeIfExists(this.compilerNode.attributes), message ?? "Could not find import type assertion container.", this);
  15158. }
  15159. }
  15160. class IndexedAccessTypeNode extends TypeNode {
  15161. getObjectTypeNode() {
  15162. return this._getNodeFromCompilerNode(this.compilerNode.objectType);
  15163. }
  15164. getIndexTypeNode() {
  15165. return this._getNodeFromCompilerNode(this.compilerNode.indexType);
  15166. }
  15167. }
  15168. class InferTypeNode extends TypeNode {
  15169. getTypeParameter() {
  15170. return this._getNodeFromCompilerNode(this.compilerNode.typeParameter);
  15171. }
  15172. }
  15173. class IntersectionTypeNode extends TypeNode {
  15174. getTypeNodes() {
  15175. return this.compilerNode.types.map(t => this._getNodeFromCompilerNode(t));
  15176. }
  15177. }
  15178. class LiteralTypeNode extends TypeNode {
  15179. getLiteral() {
  15180. const tsLiteral = this.compilerNode.literal;
  15181. return this._getNodeFromCompilerNode(tsLiteral);
  15182. }
  15183. }
  15184. class MappedTypeNode extends TypeNode {
  15185. getNameTypeNode() {
  15186. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.nameType);
  15187. }
  15188. getNameTypeNodeOrThrow(message) {
  15189. return common.errors.throwIfNullOrUndefined(this.getNameTypeNode(), message ?? "Type did not exist.", this);
  15190. }
  15191. getReadonlyToken() {
  15192. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.readonlyToken);
  15193. }
  15194. getReadonlyTokenOrThrow(message) {
  15195. return common.errors.throwIfNullOrUndefined(this.getReadonlyToken(), message ?? "Readonly token did not exist.", this);
  15196. }
  15197. getQuestionToken() {
  15198. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.questionToken);
  15199. }
  15200. getQuestionTokenOrThrow(message) {
  15201. return common.errors.throwIfNullOrUndefined(this.getQuestionToken(), message ?? "Question token did not exist.", this);
  15202. }
  15203. getTypeParameter() {
  15204. return this._getNodeFromCompilerNode(this.compilerNode.typeParameter);
  15205. }
  15206. getTypeNode() {
  15207. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.type);
  15208. }
  15209. getTypeNodeOrThrow(message) {
  15210. return common.errors.throwIfNullOrUndefined(this.getTypeNode(), message ?? "Type did not exist, but was expected to exist.", this);
  15211. }
  15212. }
  15213. const createBase$e = (ctor) => TypedNode(QuestionTokenableNode(DotDotDotTokenableNode(JSDocableNode(NamedNode(ctor)))));
  15214. const NamedTupleMemberBase = createBase$e(TypeNode);
  15215. class NamedTupleMember extends NamedTupleMemberBase {
  15216. getTypeNode() {
  15217. return super.getTypeNode();
  15218. }
  15219. removeType() {
  15220. throw new common.errors.InvalidOperationError("Cannot remove the type of a named tuple member.");
  15221. }
  15222. }
  15223. class ParenthesizedTypeNode extends TypeNode {
  15224. getTypeNode() {
  15225. return this._getNodeFromCompilerNode(this.compilerNode.type);
  15226. }
  15227. setType(textOrWriterFunction) {
  15228. this.getTypeNode().replaceWithText(textOrWriterFunction);
  15229. return this;
  15230. }
  15231. }
  15232. class RestTypeNode extends TypeNode {
  15233. getTypeNode() {
  15234. return this._getNodeFromCompilerNode(this.compilerNode.type);
  15235. }
  15236. }
  15237. class TemplateLiteralTypeNode extends TypeNode {
  15238. getHead() {
  15239. return this._getNodeFromCompilerNode(this.compilerNode.head);
  15240. }
  15241. getTemplateSpans() {
  15242. return this.compilerNode.templateSpans.map(s => this._getNodeFromCompilerNode(s));
  15243. }
  15244. setLiteralValue(value) {
  15245. const childIndex = this.getChildIndex();
  15246. const parent = this.getParentSyntaxList() ?? this.getParentOrThrow();
  15247. replaceNodeText({
  15248. sourceFile: this._sourceFile,
  15249. start: this.getStart() + 1,
  15250. replacingLength: this.getWidth() - 2,
  15251. newText: value,
  15252. });
  15253. return parent.getChildAtIndex(childIndex);
  15254. }
  15255. }
  15256. class ThisTypeNode extends TypeNode {
  15257. }
  15258. class TupleTypeNode extends TypeNode {
  15259. getElements() {
  15260. return this.compilerNode.elements.map(t => this._getNodeFromCompilerNode(t));
  15261. }
  15262. }
  15263. const createBase$d = (ctor) => TypeParameteredNode(TypedNode(JSDocableNode(AmbientableNode(ExportableNode(ModifierableNode(NamedNode(ctor)))))));
  15264. const TypeAliasDeclarationBase = createBase$d(Statement);
  15265. class TypeAliasDeclaration extends TypeAliasDeclarationBase {
  15266. set(structure) {
  15267. callBaseSet(TypeAliasDeclarationBase.prototype, this, structure);
  15268. return this;
  15269. }
  15270. getStructure() {
  15271. return callBaseGetStructure(TypeAliasDeclarationBase.prototype, this, {
  15272. kind: exports.StructureKind.TypeAlias,
  15273. type: this.getTypeNodeOrThrow().getText(),
  15274. });
  15275. }
  15276. }
  15277. const TypeLiteralNodeBase = TypeElementMemberedNode(TypeNode);
  15278. class TypeLiteralNode extends TypeLiteralNodeBase {
  15279. }
  15280. class TypeOperatorTypeNode extends TypeNode {
  15281. getOperator() {
  15282. return this.compilerNode.operator;
  15283. }
  15284. getTypeNode() {
  15285. return this._getNodeFromCompilerNode(this.compilerNode.type);
  15286. }
  15287. }
  15288. exports.TypeParameterVariance = void 0;
  15289. (function (TypeParameterVariance) {
  15290. TypeParameterVariance[TypeParameterVariance["None"] = 0] = "None";
  15291. TypeParameterVariance[TypeParameterVariance["In"] = 1] = "In";
  15292. TypeParameterVariance[TypeParameterVariance["Out"] = 2] = "Out";
  15293. TypeParameterVariance[TypeParameterVariance["InOut"] = 3] = "InOut";
  15294. })(exports.TypeParameterVariance || (exports.TypeParameterVariance = {}));
  15295. const createBase$c = (ctor) => ModifierableNode(NamedNode(ctor));
  15296. const TypeParameterDeclarationBase = createBase$c(Node);
  15297. class TypeParameterDeclaration extends TypeParameterDeclarationBase {
  15298. isConst() {
  15299. return this.hasModifier(common.SyntaxKind.ConstKeyword);
  15300. }
  15301. setIsConst(value) {
  15302. return this.toggleModifier("const", value);
  15303. }
  15304. getConstraint() {
  15305. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.constraint);
  15306. }
  15307. getConstraintOrThrow(message) {
  15308. return common.errors.throwIfNullOrUndefined(this.getConstraint(), message ?? "Expected to find the type parameter's constraint.", this);
  15309. }
  15310. setConstraint(text) {
  15311. text = this.getParentOrThrow()._getTextWithQueuedChildIndentation(text);
  15312. if (common.StringUtils.isNullOrWhitespace(text)) {
  15313. this.removeConstraint();
  15314. return this;
  15315. }
  15316. const constraint = this.getConstraint();
  15317. if (constraint != null) {
  15318. constraint.replaceWithText(text);
  15319. return this;
  15320. }
  15321. const nameNode = this.getNameNode();
  15322. insertIntoParentTextRange({
  15323. parent: this,
  15324. insertPos: nameNode.getEnd(),
  15325. newText: ` extends ${text}`,
  15326. });
  15327. return this;
  15328. }
  15329. removeConstraint() {
  15330. removeConstraintOrDefault(this.getConstraint(), common.SyntaxKind.ExtendsKeyword);
  15331. return this;
  15332. }
  15333. getDefault() {
  15334. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.default);
  15335. }
  15336. getDefaultOrThrow(message) {
  15337. return common.errors.throwIfNullOrUndefined(this.getDefault(), message ?? "Expected to find the type parameter's default.", this);
  15338. }
  15339. setDefault(text) {
  15340. text = this.getParentOrThrow()._getTextWithQueuedChildIndentation(text);
  15341. if (common.StringUtils.isNullOrWhitespace(text)) {
  15342. this.removeDefault();
  15343. return this;
  15344. }
  15345. const defaultNode = this.getDefault();
  15346. if (defaultNode != null) {
  15347. defaultNode.replaceWithText(text);
  15348. return this;
  15349. }
  15350. const insertAfterNode = this.getConstraint() || this.getNameNode();
  15351. insertIntoParentTextRange({
  15352. parent: this,
  15353. insertPos: insertAfterNode.getEnd(),
  15354. newText: ` = ${text}`,
  15355. });
  15356. return this;
  15357. }
  15358. removeDefault() {
  15359. removeConstraintOrDefault(this.getDefault(), common.SyntaxKind.EqualsToken);
  15360. return this;
  15361. }
  15362. setVariance(variance) {
  15363. this.toggleModifier("in", (variance & exports.TypeParameterVariance.In) !== 0);
  15364. this.toggleModifier("out", (variance & exports.TypeParameterVariance.Out) !== 0);
  15365. return this;
  15366. }
  15367. getVariance() {
  15368. let variance = exports.TypeParameterVariance.None;
  15369. if (this.hasModifier(common.SyntaxKind.InKeyword))
  15370. variance |= exports.TypeParameterVariance.In;
  15371. if (this.hasModifier(common.SyntaxKind.OutKeyword))
  15372. variance |= exports.TypeParameterVariance.Out;
  15373. return variance;
  15374. }
  15375. remove() {
  15376. const parentSyntaxList = this.getParentSyntaxListOrThrow();
  15377. const typeParameters = parentSyntaxList.getChildrenOfKind(common.SyntaxKind.TypeParameter);
  15378. if (typeParameters.length === 1)
  15379. removeAllTypeParameters();
  15380. else
  15381. removeCommaSeparatedChild(this);
  15382. function removeAllTypeParameters() {
  15383. const children = [
  15384. parentSyntaxList.getPreviousSiblingIfKindOrThrow(common.SyntaxKind.LessThanToken),
  15385. parentSyntaxList,
  15386. parentSyntaxList.getNextSiblingIfKindOrThrow(common.SyntaxKind.GreaterThanToken),
  15387. ];
  15388. removeChildren({ children });
  15389. }
  15390. }
  15391. set(structure) {
  15392. callBaseSet(TypeParameterDeclarationBase.prototype, this, structure);
  15393. if (structure.isConst != null)
  15394. this.setIsConst(structure.isConst);
  15395. if (structure.constraint != null)
  15396. this.setConstraint(structure.constraint);
  15397. else if (structure.hasOwnProperty(common.nameof(structure, "constraint")))
  15398. this.removeConstraint();
  15399. if (structure.default != null)
  15400. this.setDefault(structure.default);
  15401. else if (structure.hasOwnProperty(common.nameof(structure, "default")))
  15402. this.removeDefault();
  15403. if (structure.variance != null)
  15404. this.setVariance(structure.variance);
  15405. return this;
  15406. }
  15407. getStructure() {
  15408. const constraintNode = this.getConstraint();
  15409. const defaultNode = this.getDefault();
  15410. return callBaseGetStructure(TypeParameterDeclarationBase.prototype, this, {
  15411. kind: exports.StructureKind.TypeParameter,
  15412. isConst: this.isConst(),
  15413. constraint: constraintNode != null ? constraintNode.getText({ trimLeadingIndentation: true }) : undefined,
  15414. default: defaultNode ? defaultNode.getText({ trimLeadingIndentation: true }) : undefined,
  15415. variance: this.getVariance(),
  15416. });
  15417. }
  15418. }
  15419. function removeConstraintOrDefault(nodeToRemove, siblingKind) {
  15420. if (nodeToRemove == null)
  15421. return;
  15422. removeChildren({
  15423. children: [nodeToRemove.getPreviousSiblingIfKindOrThrow(siblingKind), nodeToRemove],
  15424. removePrecedingSpaces: true,
  15425. });
  15426. }
  15427. class TypePredicateNode extends TypeNode {
  15428. getParameterNameNode() {
  15429. return this._getNodeFromCompilerNode(this.compilerNode.parameterName);
  15430. }
  15431. hasAssertsModifier() {
  15432. return this.compilerNode.assertsModifier != null;
  15433. }
  15434. getAssertsModifier() {
  15435. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.assertsModifier);
  15436. }
  15437. getAssertsModifierOrThrow(message) {
  15438. return common.errors.throwIfNullOrUndefined(this.getAssertsModifier(), message ?? "Expected to find an asserts modifier.", this);
  15439. }
  15440. getTypeNode() {
  15441. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.type);
  15442. }
  15443. getTypeNodeOrThrow(message) {
  15444. return common.errors.throwIfNullOrUndefined(this.getTypeNode(), message ?? "Expected to find a type node.", this);
  15445. }
  15446. }
  15447. class TypeQueryNode extends NodeWithTypeArguments {
  15448. getExprName() {
  15449. return this._getNodeFromCompilerNode(this.compilerNode.exprName);
  15450. }
  15451. }
  15452. class TypeReferenceNode extends NodeWithTypeArguments {
  15453. getTypeName() {
  15454. return this._getNodeFromCompilerNode(this.compilerNode.typeName);
  15455. }
  15456. }
  15457. class UnionTypeNode extends TypeNode {
  15458. getTypeNodes() {
  15459. return this.compilerNode.types.map(t => this._getNodeFromCompilerNode(t));
  15460. }
  15461. }
  15462. class JSDocType extends TypeNode {
  15463. }
  15464. class JSDocAllType extends JSDocType {
  15465. }
  15466. const JSDocTagBase = Node;
  15467. class JSDocTag extends JSDocTagBase {
  15468. getTagName() {
  15469. return this.getTagNameNode().getText();
  15470. }
  15471. getTagNameNode() {
  15472. return this._getNodeFromCompilerNode(this.compilerNode.tagName);
  15473. }
  15474. setTagName(tagName) {
  15475. return this.set({ tagName });
  15476. }
  15477. getComment() {
  15478. if (this.compilerNode.comment == null)
  15479. return undefined;
  15480. else if (typeof this.compilerNode.comment === "string")
  15481. return this.compilerNode.comment;
  15482. else
  15483. return this.compilerNode.comment.map(n => this._getNodeFromCompilerNodeIfExists(n));
  15484. }
  15485. getCommentText() {
  15486. if (typeof this.compilerNode.comment === "string")
  15487. return this.compilerNode.comment;
  15488. else
  15489. return common.ts.getTextOfJSDocComment(this.compilerNode.comment);
  15490. }
  15491. remove() {
  15492. const jsDocBodyStart = this.getParentOrThrow().getStart() + 3;
  15493. const nextJsDocTag = getNextJsDocTag(this);
  15494. const isLastJsDoc = nextJsDocTag == null;
  15495. const removalStart = getRemovalStart.call(this);
  15496. removeChildren({
  15497. children: [this],
  15498. customRemovalPos: removalStart,
  15499. customRemovalEnd: getNextTagStartOrDocEnd(this, nextJsDocTag),
  15500. replaceTrivia: getReplaceTrivia.call(this),
  15501. });
  15502. function getRemovalStart() {
  15503. return Math.max(jsDocBodyStart, getPreviousNonWhiteSpacePos(this, this.getStart()));
  15504. }
  15505. function getReplaceTrivia() {
  15506. if (removalStart === jsDocBodyStart && isLastJsDoc)
  15507. return "";
  15508. const newLineKind = this._context.manipulationSettings.getNewLineKindAsString();
  15509. const indentationText = this.getParentOrThrow().getIndentationText();
  15510. return `${newLineKind}${indentationText} ` + (isLastJsDoc ? "" : "* ");
  15511. }
  15512. }
  15513. set(structure) {
  15514. callBaseSet(JSDocTagBase.prototype, this, structure);
  15515. if (structure.text != null || structure.tagName != null) {
  15516. return this.replaceWithText(writer => {
  15517. this._context.structurePrinterFactory.forJSDocTag({ printStarsOnNewLine: true }).printText(writer, {
  15518. tagName: structure.tagName ?? this.getTagName(),
  15519. text: structure.text != null ? structure.text : getText(this),
  15520. });
  15521. });
  15522. }
  15523. return this;
  15524. }
  15525. replaceWithText(textOrWriterFunction) {
  15526. const newText = getTextFromStringOrWriter(this._getWriterWithQueuedIndentation(), textOrWriterFunction);
  15527. const parent = this.getParentOrThrow();
  15528. const childIndex = this.getChildIndex();
  15529. const start = this.getStart();
  15530. insertIntoParentTextRange({
  15531. parent,
  15532. insertPos: start,
  15533. newText,
  15534. replacing: {
  15535. textLength: getTagEnd(this) - start,
  15536. },
  15537. });
  15538. return parent.getChildren()[childIndex];
  15539. }
  15540. getStructure() {
  15541. const text = getText(this);
  15542. return callBaseGetStructure(JSDocTagBase.prototype, this, {
  15543. kind: exports.StructureKind.JSDocTag,
  15544. tagName: this.getTagName(),
  15545. text: text.length === 0 ? undefined : text,
  15546. });
  15547. }
  15548. }
  15549. function getText(jsDocTag) {
  15550. const text = jsDocTag.getSourceFile().getFullText();
  15551. const nameEnd = jsDocTag.getTagNameNode().getEnd();
  15552. const tagEnd = getTagEnd(jsDocTag);
  15553. const startPos = Math.min(text.charCodeAt(nameEnd) === CharCodes.SPACE ? nameEnd + 1 : nameEnd, tagEnd);
  15554. return getTextWithoutStars(text.substring(startPos, tagEnd));
  15555. }
  15556. function getTagEnd(jsDocTag) {
  15557. return getPreviousNonWhiteSpacePos(jsDocTag, getNextTagStartOrDocEnd(jsDocTag));
  15558. }
  15559. function getNextTagStartOrDocEnd(jsDocTag, nextJsDocTag) {
  15560. nextJsDocTag = nextJsDocTag ?? getNextJsDocTag(jsDocTag);
  15561. return nextJsDocTag != null
  15562. ? nextJsDocTag.getStart()
  15563. : jsDocTag.getParentOrThrow().getEnd() - 2;
  15564. }
  15565. function getNextJsDocTag(jsDocTag) {
  15566. const parent = jsDocTag.getParentIfKindOrThrow(common.SyntaxKind.JSDoc);
  15567. const tags = parent.getTags();
  15568. const thisIndex = tags.indexOf(jsDocTag);
  15569. return tags[thisIndex + 1];
  15570. }
  15571. function getPreviousNonWhiteSpacePos(jsDocTag, pos) {
  15572. const sourceFileText = jsDocTag.getSourceFile().getFullText();
  15573. return getPreviousMatchingPos(sourceFileText, pos, charCode => charCode !== CharCodes.ASTERISK && !common.StringUtils.isWhitespaceCharCode(charCode));
  15574. }
  15575. class JSDocAugmentsTag extends JSDocTag {
  15576. }
  15577. class JSDocAuthorTag extends JSDocTag {
  15578. }
  15579. class JSDocCallbackTag extends JSDocTag {
  15580. }
  15581. class JSDocClassTag extends JSDocTag {
  15582. }
  15583. class JSDocDeprecatedTag extends JSDocTag {
  15584. }
  15585. class JSDocEnumTag extends JSDocTag {
  15586. }
  15587. const JSDocFunctionTypeBase = SignaturedDeclaration(JSDocType);
  15588. class JSDocFunctionType extends JSDocFunctionTypeBase {
  15589. }
  15590. class JSDocImplementsTag extends JSDocTag {
  15591. }
  15592. class JSDocLink extends Node {
  15593. }
  15594. class JSDocLinkCode extends Node {
  15595. }
  15596. class JSDocLinkPlain extends Node {
  15597. }
  15598. class JSDocMemberName extends Node {
  15599. }
  15600. class JSDocNamepathType extends JSDocType {
  15601. getTypeNode() {
  15602. return this._getNodeFromCompilerNode(this.compilerNode.type);
  15603. }
  15604. }
  15605. class JSDocNameReference extends Node {
  15606. getName() {
  15607. return this._getNodeFromCompilerNode(this.compilerNode.name);
  15608. }
  15609. }
  15610. class JSDocNonNullableType extends JSDocType {
  15611. getTypeNode() {
  15612. return this._getNodeFromCompilerNode(this.compilerNode.type);
  15613. }
  15614. isPostfix() {
  15615. return this.compilerNode.postfix;
  15616. }
  15617. }
  15618. class JSDocNullableType extends JSDocType {
  15619. getTypeNode() {
  15620. return this._getNodeFromCompilerNode(this.compilerNode.type);
  15621. }
  15622. isPostfix() {
  15623. return this.compilerNode.postfix;
  15624. }
  15625. }
  15626. class JSDocOptionalType extends JSDocType {
  15627. getTypeNode() {
  15628. return this._getNodeFromCompilerNode(this.compilerNode.type);
  15629. }
  15630. }
  15631. const JSDocOverloadTagBase = JSDocTypeExpressionableTag(JSDocTag);
  15632. class JSDocOverloadTag extends JSDocOverloadTagBase {
  15633. }
  15634. class JSDocOverrideTag extends JSDocTag {
  15635. }
  15636. const JSDocParameterTagBase = JSDocPropertyLikeTag(JSDocTag);
  15637. class JSDocParameterTag extends JSDocParameterTagBase {
  15638. }
  15639. class JSDocPrivateTag extends JSDocTag {
  15640. }
  15641. const JSDocPropertyTagBase = JSDocPropertyLikeTag(JSDocTag);
  15642. class JSDocPropertyTag extends JSDocPropertyTagBase {
  15643. }
  15644. class JSDocProtectedTag extends JSDocTag {
  15645. }
  15646. class JSDocPublicTag extends JSDocTag {
  15647. }
  15648. class JSDocReadonlyTag extends JSDocTag {
  15649. }
  15650. const JSDocReturnTagBase = JSDocTypeExpressionableTag(JSDocTag);
  15651. class JSDocReturnTag extends JSDocReturnTagBase {
  15652. }
  15653. const JSDocSatisfiesTagBase = JSDocTypeExpressionableTag(JSDocTag);
  15654. class JSDocSatisfiesTag extends JSDocSatisfiesTagBase {
  15655. }
  15656. const JSDocSeeTagBase = JSDocTypeExpressionableTag(JSDocTag);
  15657. class JSDocSeeTag extends JSDocSeeTagBase {
  15658. }
  15659. class JSDocSignature extends JSDocType {
  15660. getTypeNode() {
  15661. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.type);
  15662. }
  15663. }
  15664. class JSDocTagInfo {
  15665. #compilerObject;
  15666. constructor(compilerObject) {
  15667. this.#compilerObject = compilerObject;
  15668. }
  15669. get compilerObject() {
  15670. return this.#compilerObject;
  15671. }
  15672. getName() {
  15673. return this.compilerObject.name;
  15674. }
  15675. getText() {
  15676. return this.compilerObject.text ?? [];
  15677. }
  15678. }
  15679. const JSDocTemplateTagBase = JSDocTypeParameteredTag(JSDocTag);
  15680. class JSDocTemplateTag extends JSDocTemplateTagBase {
  15681. getConstraint() {
  15682. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.constraint);
  15683. }
  15684. getConstraintOrThrow(message) {
  15685. return common.errors.throwIfNullOrUndefined(this.getConstraint(), message ?? "Expected to find the JS doc template tag's constraint.", this);
  15686. }
  15687. }
  15688. class JSDocText extends Node {
  15689. }
  15690. const JSDocThisTagBase = JSDocTypeExpressionableTag(JSDocTag);
  15691. class JSDocThisTag extends JSDocThisTagBase {
  15692. }
  15693. const JSDocThrowsTagBase = JSDocTypeExpressionableTag(JSDocTag);
  15694. class JSDocThrowsTag extends JSDocThrowsTagBase {
  15695. }
  15696. class JSDocTypedefTag extends JSDocTag {
  15697. }
  15698. class JSDocTypeExpression extends TypeNode {
  15699. getTypeNode() {
  15700. return this._getNodeFromCompilerNode(this.compilerNode.type);
  15701. }
  15702. }
  15703. class JSDocTypeLiteral extends JSDocType {
  15704. isArrayType() {
  15705. return this.compilerNode.isArrayType;
  15706. }
  15707. getPropertyTags() {
  15708. return this.compilerNode.jsDocPropertyTags ? this.compilerNode.jsDocPropertyTags.map(t => this._getNodeFromCompilerNode(t)) : undefined;
  15709. }
  15710. }
  15711. class JSDocTypeTag extends JSDocTag {
  15712. getTypeExpression() {
  15713. const node = this.compilerNode.typeExpression;
  15714. if (node != null && node.pos === node.end)
  15715. return undefined;
  15716. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.typeExpression);
  15717. }
  15718. }
  15719. class JSDocUnknownTag extends JSDocTag {
  15720. }
  15721. class JSDocUnknownType extends JSDocType {
  15722. }
  15723. class JSDocVariadicType extends JSDocType {
  15724. getTypeNode() {
  15725. return this._getNodeFromCompilerNode(this.compilerNode.type);
  15726. }
  15727. }
  15728. class CommentEnumMember extends Node {
  15729. remove() {
  15730. removeChildrenWithFormatting({
  15731. children: [this],
  15732. getSiblingFormatting: () => FormattingKind.Newline,
  15733. });
  15734. }
  15735. }
  15736. const createBase$b = (ctor) => TextInsertableNode(ModuleChildableNode(JSDocableNode(AmbientableNode(ExportableNode(ModifierableNode(NamedNode(ctor)))))));
  15737. const EnumDeclarationBase = createBase$b(Statement);
  15738. class EnumDeclaration extends EnumDeclarationBase {
  15739. set(structure) {
  15740. callBaseSet(EnumDeclarationBase.prototype, this, structure);
  15741. if (structure.isConst != null)
  15742. this.setIsConstEnum(structure.isConst);
  15743. if (structure.members != null) {
  15744. this.getMembers().forEach(m => m.remove());
  15745. this.addMembers(structure.members);
  15746. }
  15747. return this;
  15748. }
  15749. addMember(structure) {
  15750. return this.addMembers([structure])[0];
  15751. }
  15752. addMembers(structures) {
  15753. return this.insertMembers(this.getMembers().length, structures);
  15754. }
  15755. insertMember(index, structure) {
  15756. return this.insertMembers(index, [structure])[0];
  15757. }
  15758. insertMembers(index, structures) {
  15759. if (structures.length === 0)
  15760. return [];
  15761. const members = this.getMembersWithComments();
  15762. index = verifyAndGetIndex(index, members.length);
  15763. const writer = this._getWriterWithChildIndentation();
  15764. const structurePrinter = this._context.structurePrinterFactory.forEnumMember();
  15765. structurePrinter.printTexts(writer, structures);
  15766. insertIntoCommaSeparatedNodes({
  15767. parent: this.getChildSyntaxListOrThrow(),
  15768. currentNodes: members,
  15769. insertIndex: index,
  15770. newText: writer.toString(),
  15771. useNewLines: true,
  15772. useTrailingCommas: this._context.manipulationSettings.getUseTrailingCommas(),
  15773. });
  15774. return getNodesToReturn(members, this.getMembersWithComments(), index, !areAllStructuresStructures());
  15775. function areAllStructuresStructures() {
  15776. if (!(structures instanceof Array))
  15777. return false;
  15778. return structures.every(s => typeof s === "object");
  15779. }
  15780. }
  15781. getMember(nameOrFindFunction) {
  15782. return getNodeByNameOrFindFunction(this.getMembers(), nameOrFindFunction);
  15783. }
  15784. getMemberOrThrow(nameOrFindFunction) {
  15785. return common.errors.throwIfNullOrUndefined(this.getMember(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("enum member", nameOrFindFunction));
  15786. }
  15787. getMembers() {
  15788. return this.compilerNode.members.map(m => this._getNodeFromCompilerNode(m));
  15789. }
  15790. getMembersWithComments() {
  15791. const compilerNode = this.compilerNode;
  15792. return ExtendedParser.getContainerArray(compilerNode, this.getSourceFile().compilerNode)
  15793. .map(m => this._getNodeFromCompilerNode(m));
  15794. }
  15795. setIsConstEnum(value) {
  15796. return this.toggleModifier("const", value);
  15797. }
  15798. isConstEnum() {
  15799. return this.getConstKeyword() != null;
  15800. }
  15801. getConstKeyword() {
  15802. return this.getFirstModifierByKind(common.SyntaxKind.ConstKeyword);
  15803. }
  15804. getStructure() {
  15805. return callBaseGetStructure(EnumDeclarationBase.prototype, this, {
  15806. kind: exports.StructureKind.Enum,
  15807. isConst: this.isConstEnum(),
  15808. members: this.getMembers().map(member => member.getStructure()),
  15809. });
  15810. }
  15811. }
  15812. const createBase$a = (ctor) => JSDocableNode(InitializerExpressionableNode(PropertyNamedNode(ctor)));
  15813. const EnumMemberBase = createBase$a(Node);
  15814. class EnumMember extends EnumMemberBase {
  15815. getValue() {
  15816. return this._context.typeChecker.getConstantValue(this);
  15817. }
  15818. setValue(value) {
  15819. let text;
  15820. if (typeof value === "string") {
  15821. const quoteKind = this._context.manipulationSettings.getQuoteKind();
  15822. text = quoteKind + common.StringUtils.escapeForWithinString(value, quoteKind) + quoteKind;
  15823. }
  15824. else {
  15825. text = value.toString();
  15826. }
  15827. this.setInitializer(text);
  15828. return this;
  15829. }
  15830. remove() {
  15831. const childrenToRemove = [this];
  15832. const commaToken = this.getNextSiblingIfKind(common.SyntaxKind.CommaToken);
  15833. if (commaToken != null)
  15834. childrenToRemove.push(commaToken);
  15835. removeChildrenWithFormatting({
  15836. children: childrenToRemove,
  15837. getSiblingFormatting: () => FormattingKind.Newline,
  15838. });
  15839. }
  15840. set(structure) {
  15841. callBaseSet(EnumMemberBase.prototype, this, structure);
  15842. if (structure.value != null)
  15843. this.setValue(structure.value);
  15844. else if (structure.hasOwnProperty(common.nameof(structure, "value")) && structure.initializer == null)
  15845. this.removeInitializer();
  15846. return this;
  15847. }
  15848. getStructure() {
  15849. return callBaseGetStructure(EnumMemberBase.prototype, this, {
  15850. kind: exports.StructureKind.EnumMember,
  15851. value: undefined,
  15852. });
  15853. }
  15854. }
  15855. class HeritageClause extends Node {
  15856. getTypeNodes() {
  15857. return this.compilerNode.types?.map(t => this._getNodeFromCompilerNode(t)) ?? [];
  15858. }
  15859. getToken() {
  15860. return this.compilerNode.token;
  15861. }
  15862. removeExpression(expressionNodeOrIndex) {
  15863. const expressions = this.getTypeNodes();
  15864. const expressionNodeToRemove = typeof expressionNodeOrIndex === "number" ? getExpressionFromIndex(expressionNodeOrIndex) : expressionNodeOrIndex;
  15865. if (expressions.length === 1) {
  15866. const heritageClauses = this.getParentSyntaxListOrThrow().getChildren();
  15867. if (heritageClauses.length === 1)
  15868. removeChildren({ children: [heritageClauses[0].getParentSyntaxListOrThrow()], removePrecedingSpaces: true });
  15869. else
  15870. removeChildren({ children: [this], removePrecedingSpaces: true });
  15871. }
  15872. else {
  15873. removeCommaSeparatedChild(expressionNodeToRemove);
  15874. }
  15875. return this;
  15876. function getExpressionFromIndex(index) {
  15877. return expressions[verifyAndGetIndex(index, expressions.length - 1)];
  15878. }
  15879. }
  15880. }
  15881. class TypeElement extends Node {
  15882. remove() {
  15883. removeInterfaceMember(this);
  15884. }
  15885. }
  15886. const createBase$9 = (ctor) => TypeParameteredNode(ChildOrderableNode(JSDocableNode(SignaturedDeclaration(ctor))));
  15887. const CallSignatureDeclarationBase = createBase$9(TypeElement);
  15888. class CallSignatureDeclaration extends CallSignatureDeclarationBase {
  15889. set(structure) {
  15890. callBaseSet(CallSignatureDeclarationBase.prototype, this, structure);
  15891. return this;
  15892. }
  15893. getStructure() {
  15894. return callBaseGetStructure(CallSignatureDeclarationBase.prototype, this, {
  15895. kind: exports.StructureKind.CallSignature,
  15896. });
  15897. }
  15898. }
  15899. class CommentTypeElement extends TypeElement {
  15900. }
  15901. const createBase$8 = (ctor) => TypeParameteredNode(ChildOrderableNode(JSDocableNode(SignaturedDeclaration(ctor))));
  15902. const ConstructSignatureDeclarationBase = createBase$8(TypeElement);
  15903. class ConstructSignatureDeclaration extends ConstructSignatureDeclarationBase {
  15904. set(structure) {
  15905. callBaseSet(ConstructSignatureDeclarationBase.prototype, this, structure);
  15906. return this;
  15907. }
  15908. getStructure() {
  15909. return callBaseGetStructure(ConstructSignatureDeclarationBase.prototype, this, {
  15910. kind: exports.StructureKind.ConstructSignature,
  15911. });
  15912. }
  15913. }
  15914. const createBase$7 = (ctor) => ReturnTypedNode(ChildOrderableNode(JSDocableNode(ReadonlyableNode(ModifierableNode(ctor)))));
  15915. const IndexSignatureDeclarationBase = createBase$7(TypeElement);
  15916. class IndexSignatureDeclaration extends IndexSignatureDeclarationBase {
  15917. getKeyName() {
  15918. return this.getKeyNameNode().getText();
  15919. }
  15920. setKeyName(name) {
  15921. common.errors.throwIfWhitespaceOrNotString(name, "name");
  15922. if (this.getKeyName() === name)
  15923. return;
  15924. this.getKeyNameNode().replaceWithText(name, this._getWriterWithQueuedChildIndentation());
  15925. }
  15926. getKeyNameNode() {
  15927. const param = this.compilerNode.parameters[0];
  15928. return this._getNodeFromCompilerNode(param.name);
  15929. }
  15930. getKeyType() {
  15931. return this.getKeyNameNode().getType();
  15932. }
  15933. setKeyType(type) {
  15934. common.errors.throwIfWhitespaceOrNotString(type, "type");
  15935. const keyTypeNode = this.getKeyTypeNode();
  15936. if (keyTypeNode.getText() === type)
  15937. return this;
  15938. keyTypeNode.replaceWithText(type, this._getWriterWithQueuedChildIndentation());
  15939. return this;
  15940. }
  15941. getKeyTypeNode() {
  15942. const param = this.compilerNode.parameters[0];
  15943. return this._getNodeFromCompilerNode(param.type);
  15944. }
  15945. set(structure) {
  15946. callBaseSet(IndexSignatureDeclarationBase.prototype, this, structure);
  15947. if (structure.keyName != null)
  15948. this.setKeyName(structure.keyName);
  15949. if (structure.keyType != null)
  15950. this.setKeyType(structure.keyType);
  15951. return this;
  15952. }
  15953. getStructure() {
  15954. const keyTypeNode = this.getKeyTypeNode();
  15955. return callBaseGetStructure(IndexSignatureDeclarationBase.prototype, this, {
  15956. kind: exports.StructureKind.IndexSignature,
  15957. keyName: this.getKeyName(),
  15958. keyType: keyTypeNode.getText(),
  15959. });
  15960. }
  15961. }
  15962. const createBase$6 = (ctor) => TypeElementMemberedNode(TextInsertableNode(ExtendsClauseableNode(HeritageClauseableNode(TypeParameteredNode(JSDocableNode(AmbientableNode(ModuleChildableNode(ExportableNode(ModifierableNode(NamedNode(ctor)))))))))));
  15963. const InterfaceDeclarationBase = createBase$6(Statement);
  15964. class InterfaceDeclaration extends InterfaceDeclarationBase {
  15965. getBaseTypes() {
  15966. return this.getType().getBaseTypes();
  15967. }
  15968. getBaseDeclarations() {
  15969. return this.getType().getBaseTypes().map(t => {
  15970. return t.getSymbol()?.getDeclarations() ?? [];
  15971. }).flat();
  15972. }
  15973. getImplementations() {
  15974. return this.getNameNode().getImplementations();
  15975. }
  15976. set(structure) {
  15977. callBaseSet(InterfaceDeclarationBase.prototype, this, structure);
  15978. return this;
  15979. }
  15980. getStructure() {
  15981. return callBaseGetStructure(InterfaceDeclarationBase.prototype, this, {
  15982. kind: exports.StructureKind.Interface,
  15983. });
  15984. }
  15985. }
  15986. const createBase$5 = (ctor) => ChildOrderableNode(JSDocableNode(QuestionTokenableNode(TypeParameteredNode(SignaturedDeclaration(PropertyNamedNode(ctor))))));
  15987. const MethodSignatureBase = createBase$5(TypeElement);
  15988. class MethodSignature extends MethodSignatureBase {
  15989. set(structure) {
  15990. callBaseSet(MethodSignatureBase.prototype, this, structure);
  15991. return this;
  15992. }
  15993. getStructure() {
  15994. return callBaseGetStructure(MethodSignatureBase.prototype, this, {
  15995. kind: exports.StructureKind.MethodSignature,
  15996. });
  15997. }
  15998. }
  15999. const createBase$4 = (ctor) => ChildOrderableNode(JSDocableNode(ReadonlyableNode(QuestionTokenableNode(InitializerExpressionableNode(TypedNode(PropertyNamedNode(ModifierableNode(ctor))))))));
  16000. const PropertySignatureBase = createBase$4(TypeElement);
  16001. class PropertySignature extends PropertySignatureBase {
  16002. set(structure) {
  16003. callBaseSet(PropertySignatureBase.prototype, this, structure);
  16004. return this;
  16005. }
  16006. getStructure() {
  16007. return callBaseGetStructure(PropertySignatureBase.prototype, this, {
  16008. kind: exports.StructureKind.PropertySignature,
  16009. });
  16010. }
  16011. }
  16012. function JsxAttributedNode(Base) {
  16013. return class extends Base {
  16014. getAttributes() {
  16015. return this.compilerNode.attributes.properties.map(p => this._getNodeFromCompilerNode(p));
  16016. }
  16017. getAttributeOrThrow(nameOrFindFunction) {
  16018. return common.errors.throwIfNullOrUndefined(this.getAttribute(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("attribute", nameOrFindFunction));
  16019. }
  16020. getAttribute(nameOrFindFunction) {
  16021. return getNodeByNameOrFindFunction(this.getAttributes(), nameOrFindFunction);
  16022. }
  16023. addAttribute(structure) {
  16024. return this.addAttributes([structure])[0];
  16025. }
  16026. addAttributes(structures) {
  16027. return this.insertAttributes(this.compilerNode.attributes.properties.length, structures);
  16028. }
  16029. insertAttribute(index, structure) {
  16030. return this.insertAttributes(index, [structure])[0];
  16031. }
  16032. insertAttributes(index, structures) {
  16033. if (structures.length === 0)
  16034. return [];
  16035. const originalChildrenCount = this.compilerNode.attributes.properties.length;
  16036. index = verifyAndGetIndex(index, originalChildrenCount);
  16037. const insertPos = index === 0 ? this.getTagNameNode().getEnd() : this.getAttributes()[index - 1].getEnd();
  16038. const writer = this._getWriterWithQueuedChildIndentation();
  16039. const structuresPrinter = new SpaceFormattingStructuresPrinter(this._context.structurePrinterFactory.forJsxAttributeDecider());
  16040. structuresPrinter.printText(writer, structures);
  16041. insertIntoParentTextRange({
  16042. insertPos,
  16043. newText: " " + writer.toString(),
  16044. parent: this.getNodeProperty("attributes").getFirstChildByKindOrThrow(common.SyntaxKind.SyntaxList),
  16045. });
  16046. return getNodesToReturn(originalChildrenCount, this.getAttributes(), index, false);
  16047. }
  16048. set(structure) {
  16049. callBaseSet(Base.prototype, this, structure);
  16050. if (structure.attributes != null) {
  16051. this.getAttributes().forEach(a => a.remove());
  16052. this.addAttributes(structure.attributes);
  16053. }
  16054. return this;
  16055. }
  16056. getStructure() {
  16057. return callBaseGetStructure(Base.prototype, this, {
  16058. attributes: this.getAttributes().map(a => a.getStructure()),
  16059. });
  16060. }
  16061. };
  16062. }
  16063. function JsxTagNamedNode(Base) {
  16064. return class extends Base {
  16065. getTagNameNode() {
  16066. return this._getNodeFromCompilerNode(this.compilerNode.tagName);
  16067. }
  16068. set(structure) {
  16069. callBaseSet(Base.prototype, this, structure);
  16070. if (structure.name != null)
  16071. this.getTagNameNode().replaceWithText(structure.name);
  16072. return this;
  16073. }
  16074. getStructure() {
  16075. return callBaseGetStructure(Base.prototype, this, {
  16076. name: this.getTagNameNode().getText(),
  16077. });
  16078. }
  16079. };
  16080. }
  16081. function CommonIdentifierBase(Base) {
  16082. return class extends Base {
  16083. getText() {
  16084. return this.compilerNode.text;
  16085. }
  16086. getDefinitionNodes() {
  16087. return this.getDefinitions().map(d => d.getDeclarationNode()).filter(d => d != null);
  16088. }
  16089. getDefinitions() {
  16090. return this._context.languageService.getDefinitions(this);
  16091. }
  16092. };
  16093. }
  16094. const ComputedPropertyNameBase = ExpressionedNode(Node);
  16095. class ComputedPropertyName extends ComputedPropertyNameBase {
  16096. }
  16097. const IdentifierBase = CommonIdentifierBase(ReferenceFindableNode(RenameableNode(PrimaryExpression)));
  16098. class Identifier extends IdentifierBase {
  16099. getImplementations() {
  16100. return this._context.languageService.getImplementations(this);
  16101. }
  16102. }
  16103. const PrivateIdentifierBase = CommonIdentifierBase(ReferenceFindableNode(RenameableNode(Node)));
  16104. class PrivateIdentifier extends PrivateIdentifierBase {
  16105. }
  16106. class QualifiedName extends Node {
  16107. getLeft() {
  16108. return this._getNodeFromCompilerNode(this.compilerNode.left);
  16109. }
  16110. getRight() {
  16111. return this._getNodeFromCompilerNode(this.compilerNode.right);
  16112. }
  16113. }
  16114. const JsxAttributeBase = Node;
  16115. class JsxAttribute extends JsxAttributeBase {
  16116. getNameNode() {
  16117. return this._getNodeFromCompilerNode(this.compilerNode.name);
  16118. }
  16119. setName(name) {
  16120. this.getNameNode().replaceWithText(writer => {
  16121. if (typeof name === "object")
  16122. this._context.structurePrinterFactory.forJsxNamespacedName().printText(writer, name);
  16123. else
  16124. writer.write(name);
  16125. });
  16126. return this;
  16127. }
  16128. getInitializerOrThrow(message) {
  16129. return common.errors.throwIfNullOrUndefined(this.getInitializer(), message ?? `Expected to find an initializer for the JSX attribute '${this.getNameNode().getText()}'`, this);
  16130. }
  16131. getInitializer() {
  16132. return this._getNodeFromCompilerNodeIfExists(this.compilerNode.initializer);
  16133. }
  16134. setInitializer(textOrWriterFunction) {
  16135. const text = getTextFromStringOrWriter(this._getWriterWithQueuedIndentation(), textOrWriterFunction);
  16136. if (common.StringUtils.isNullOrWhitespace(text)) {
  16137. this.removeInitializer();
  16138. return this;
  16139. }
  16140. const initializer = this.getInitializer();
  16141. if (initializer != null) {
  16142. initializer.replaceWithText(text);
  16143. return this;
  16144. }
  16145. insertIntoParentTextRange({
  16146. insertPos: this.getNameNode().getEnd(),
  16147. parent: this,
  16148. newText: `=${text}`,
  16149. });
  16150. return this;
  16151. }
  16152. removeInitializer() {
  16153. const initializer = this.getInitializer();
  16154. if (initializer == null)
  16155. return this;
  16156. removeChildren({
  16157. children: [initializer.getPreviousSiblingIfKindOrThrow(common.SyntaxKind.EqualsToken), initializer],
  16158. removePrecedingSpaces: true,
  16159. removePrecedingNewLines: true,
  16160. });
  16161. return this;
  16162. }
  16163. remove() {
  16164. removeChildren({
  16165. children: [this],
  16166. removePrecedingNewLines: true,
  16167. removePrecedingSpaces: true,
  16168. });
  16169. }
  16170. set(structure) {
  16171. callBaseSet(JsxAttributeBase.prototype, this, structure);
  16172. if (structure.name != null)
  16173. this.setName(structure.name);
  16174. if (structure.initializer != null)
  16175. this.setInitializer(structure.initializer);
  16176. else if (structure.hasOwnProperty(common.nameof(structure, "initializer")))
  16177. this.removeInitializer();
  16178. return this;
  16179. }
  16180. getStructure() {
  16181. const initializer = this.getInitializer();
  16182. const nameNode = this.getNameNode();
  16183. return callBaseGetStructure(JsxAttributeBase.prototype, this, {
  16184. name: nameNode instanceof Identifier ? nameNode.getText() : nameNode.getStructure(),
  16185. kind: exports.StructureKind.JsxAttribute,
  16186. initializer: initializer?.getText(),
  16187. });
  16188. }
  16189. }
  16190. const createBase$3 = (ctor) => JsxTagNamedNode(ctor);
  16191. const JsxClosingElementBase = createBase$3(Node);
  16192. class JsxClosingElement extends JsxClosingElementBase {
  16193. }
  16194. class JsxClosingFragment extends Expression {
  16195. }
  16196. const JsxElementBase = PrimaryExpression;
  16197. class JsxElement extends JsxElementBase {
  16198. getJsxChildren() {
  16199. return this.compilerNode.children.map(c => this._getNodeFromCompilerNode(c));
  16200. }
  16201. getOpeningElement() {
  16202. return this._getNodeFromCompilerNode(this.compilerNode.openingElement);
  16203. }
  16204. getClosingElement() {
  16205. return this._getNodeFromCompilerNode(this.compilerNode.closingElement);
  16206. }
  16207. setBodyText(textOrWriterFunction) {
  16208. const newText = getBodyText(this._getWriterWithIndentation(), textOrWriterFunction);
  16209. setText(this, newText);
  16210. return this;
  16211. }
  16212. setBodyTextInline(textOrWriterFunction) {
  16213. const writer = this._getWriterWithQueuedChildIndentation();
  16214. printTextFromStringOrWriter(writer, textOrWriterFunction);
  16215. if (writer.isLastNewLine()) {
  16216. writer.setIndentationLevel(Math.max(0, this.getIndentationLevel() - 1));
  16217. writer.write("");
  16218. }
  16219. setText(this, writer.toString());
  16220. return this;
  16221. }
  16222. set(structure) {
  16223. callBaseSet(JsxElementBase.prototype, this, structure);
  16224. if (structure.attributes != null) {
  16225. const openingElement = this.getOpeningElement();
  16226. openingElement.getAttributes().forEach(a => a.remove());
  16227. openingElement.addAttributes(structure.attributes);
  16228. }
  16229. if (structure.children != null)
  16230. throw new common.errors.NotImplementedError("Setting JSX children is currently not implemented. Please open an issue if you need this.");
  16231. if (structure.bodyText != null)
  16232. this.setBodyText(structure.bodyText);
  16233. else if (structure.hasOwnProperty(common.nameof(structure, "bodyText")))
  16234. this.setBodyTextInline("");
  16235. if (structure.name != null) {
  16236. this.getOpeningElement().getTagNameNode().replaceWithText(structure.name);
  16237. this.getClosingElement().getTagNameNode().replaceWithText(structure.name);
  16238. }
  16239. return this;
  16240. }
  16241. getStructure() {
  16242. const openingElement = this.getOpeningElement();
  16243. const structure = callBaseGetStructure(JsxElementBase.prototype, this, {
  16244. kind: exports.StructureKind.JsxElement,
  16245. name: openingElement.getTagNameNode().getText(),
  16246. attributes: openingElement.getAttributes().map(a => a.getStructure()),
  16247. children: undefined,
  16248. bodyText: getBodyTextWithoutLeadingIndentation(this),
  16249. });
  16250. delete structure.children;
  16251. return structure;
  16252. }
  16253. }
  16254. function setText(element, newText) {
  16255. const openingElement = element.getOpeningElement();
  16256. const closingElement = element.getClosingElement();
  16257. insertIntoParentTextRange({
  16258. insertPos: openingElement.getEnd(),
  16259. newText,
  16260. parent: element.getChildSyntaxListOrThrow(),
  16261. replacing: {
  16262. textLength: closingElement.getStart() - openingElement.getEnd(),
  16263. },
  16264. });
  16265. }
  16266. const JsxExpressionBase = ExpressionableNode(DotDotDotTokenableNode(Expression));
  16267. class JsxExpression extends JsxExpressionBase {
  16268. }
  16269. class JsxFragment extends PrimaryExpression {
  16270. getJsxChildren() {
  16271. return this.compilerNode.children.map(c => this._getNodeFromCompilerNode(c));
  16272. }
  16273. getOpeningFragment() {
  16274. return this._getNodeFromCompilerNode(this.compilerNode.openingFragment);
  16275. }
  16276. getClosingFragment() {
  16277. return this._getNodeFromCompilerNode(this.compilerNode.closingFragment);
  16278. }
  16279. }
  16280. const JsxNamespacedNameBase = Node;
  16281. class JsxNamespacedName extends JsxNamespacedNameBase {
  16282. getNamespaceNode() {
  16283. return this._getNodeFromCompilerNode(this.compilerNode.namespace);
  16284. }
  16285. getNameNode() {
  16286. return this._getNodeFromCompilerNode(this.compilerNode.name);
  16287. }
  16288. set(structure) {
  16289. this.getNamespaceNode().replaceWithText(structure.namespace);
  16290. this.getNameNode().replaceWithText(structure.name);
  16291. return this;
  16292. }
  16293. getStructure() {
  16294. return {
  16295. namespace: this.getNamespaceNode().getText(),
  16296. name: this.getNameNode().getText(),
  16297. };
  16298. }
  16299. }
  16300. const createBase$2 = (ctor) => JsxAttributedNode(JsxTagNamedNode(ctor));
  16301. const JsxOpeningElementBase = createBase$2(Expression);
  16302. class JsxOpeningElement extends JsxOpeningElementBase {
  16303. }
  16304. class JsxOpeningFragment extends Expression {
  16305. }
  16306. const createBase$1 = (ctor) => JsxAttributedNode(JsxTagNamedNode(ctor));
  16307. const JsxSelfClosingElementBase = createBase$1(PrimaryExpression);
  16308. class JsxSelfClosingElement extends JsxSelfClosingElementBase {
  16309. set(structure) {
  16310. callBaseSet(JsxSelfClosingElementBase.prototype, this, structure);
  16311. return this;
  16312. }
  16313. getStructure() {
  16314. return callBaseGetStructure(JsxSelfClosingElementBase.prototype, this, {
  16315. kind: exports.StructureKind.JsxSelfClosingElement,
  16316. });
  16317. }
  16318. }
  16319. const JsxSpreadAttributeBase = ExpressionedNode(Node);
  16320. class JsxSpreadAttribute extends JsxSpreadAttributeBase {
  16321. remove() {
  16322. removeChildren({
  16323. children: [this],
  16324. removePrecedingNewLines: true,
  16325. removePrecedingSpaces: true,
  16326. });
  16327. }
  16328. set(structure) {
  16329. callBaseSet(JsxSpreadAttributeBase.prototype, this, structure);
  16330. if (structure.expression != null)
  16331. this.setExpression(structure.expression);
  16332. return this;
  16333. }
  16334. getStructure() {
  16335. return callBaseGetStructure(JsxSpreadAttributeBase.prototype, this, {
  16336. kind: exports.StructureKind.JsxSpreadAttribute,
  16337. expression: this.getExpression().getText(),
  16338. });
  16339. }
  16340. }
  16341. const JsxTextBase = LiteralLikeNode(Node);
  16342. class JsxText extends JsxTextBase {
  16343. containsOnlyTriviaWhiteSpaces() {
  16344. const oldCompilerNode = this.compilerNode;
  16345. if (typeof oldCompilerNode.containsOnlyWhiteSpaces === "boolean")
  16346. return oldCompilerNode.containsOnlyWhiteSpaces;
  16347. return this.compilerNode.containsOnlyTriviaWhiteSpaces;
  16348. }
  16349. }
  16350. const BigIntLiteralBase = LiteralExpression;
  16351. class BigIntLiteral extends BigIntLiteralBase {
  16352. getLiteralValue() {
  16353. const text = this.compilerNode.text;
  16354. if (typeof BigInt === "undefined")
  16355. throw new common.errors.InvalidOperationError("Runtime environment does not support BigInts. Perhaps work with the text instead?");
  16356. const textWithoutN = text.substring(0, text.length - 1);
  16357. return BigInt(textWithoutN);
  16358. }
  16359. setLiteralValue(value) {
  16360. if (typeof value !== "bigint")
  16361. throw new common.errors.ArgumentTypeError("value", "bigint", typeof value);
  16362. replaceNodeText({
  16363. sourceFile: this._sourceFile,
  16364. start: this.getStart(),
  16365. replacingLength: this.getWidth(),
  16366. newText: value.toString() + "n",
  16367. });
  16368. return this;
  16369. }
  16370. }
  16371. const TrueLiteralBase = PrimaryExpression;
  16372. class TrueLiteral extends TrueLiteralBase {
  16373. getLiteralValue() {
  16374. return getLiteralValue(this);
  16375. }
  16376. setLiteralValue(value) {
  16377. return setLiteralValue(this, value);
  16378. }
  16379. }
  16380. const FalseLiteralBase = PrimaryExpression;
  16381. class FalseLiteral extends FalseLiteralBase {
  16382. getLiteralValue() {
  16383. return getLiteralValue(this);
  16384. }
  16385. setLiteralValue(value) {
  16386. return setLiteralValue(this, value);
  16387. }
  16388. }
  16389. function setLiteralValue(node, value) {
  16390. if (getLiteralValue(node) === value)
  16391. return node;
  16392. const parent = node.getParentSyntaxList() || node.getParentOrThrow();
  16393. const index = node.getChildIndex();
  16394. node.replaceWithText(value ? "true" : "false");
  16395. return parent.getChildAtIndex(index);
  16396. }
  16397. function getLiteralValue(node) {
  16398. return node.getKind() === common.SyntaxKind.TrueKeyword;
  16399. }
  16400. const NullLiteralBase = PrimaryExpression;
  16401. class NullLiteral extends NullLiteralBase {
  16402. }
  16403. const NumericLiteralBase = LiteralExpression;
  16404. class NumericLiteral extends NumericLiteralBase {
  16405. getLiteralValue() {
  16406. const text = this.compilerNode.text;
  16407. if (text.indexOf(".") >= 0)
  16408. return parseFloat(text);
  16409. return parseInt(text, 10);
  16410. }
  16411. setLiteralValue(value) {
  16412. replaceNodeText({
  16413. sourceFile: this._sourceFile,
  16414. start: this.getStart(),
  16415. replacingLength: this.getWidth(),
  16416. newText: value.toString(10),
  16417. });
  16418. return this;
  16419. }
  16420. }
  16421. exports.QuoteKind = void 0;
  16422. (function (QuoteKind) {
  16423. QuoteKind["Single"] = "'";
  16424. QuoteKind["Double"] = "\"";
  16425. })(exports.QuoteKind || (exports.QuoteKind = {}));
  16426. const RegularExpressionLiteralBase = LiteralExpression;
  16427. class RegularExpressionLiteral extends RegularExpressionLiteralBase {
  16428. getLiteralValue() {
  16429. const pattern = /^\/(.*)\/([^\/]*)$/;
  16430. const text = this.compilerNode.text;
  16431. const matches = pattern.exec(text);
  16432. return new RegExp(matches[1], matches[2]);
  16433. }
  16434. setLiteralValue(regExpOrPattern, flags) {
  16435. let pattern;
  16436. if (typeof regExpOrPattern === "string")
  16437. pattern = regExpOrPattern;
  16438. else {
  16439. pattern = regExpOrPattern.source;
  16440. flags = regExpOrPattern.flags;
  16441. }
  16442. replaceNodeText({
  16443. sourceFile: this._sourceFile,
  16444. start: this.getStart(),
  16445. replacingLength: this.getWidth(),
  16446. newText: `/${pattern}/${flags || ""}`,
  16447. });
  16448. return this;
  16449. }
  16450. }
  16451. const StringLiteralBase = LiteralExpression;
  16452. class StringLiteral extends StringLiteralBase {
  16453. getLiteralValue() {
  16454. return this.compilerNode.text;
  16455. }
  16456. setLiteralValue(value) {
  16457. replaceNodeText({
  16458. sourceFile: this._sourceFile,
  16459. start: this.getStart() + 1,
  16460. replacingLength: this.getWidth() - 2,
  16461. newText: common.StringUtils.escapeForWithinString(value, this.getQuoteKind()),
  16462. });
  16463. return this;
  16464. }
  16465. getQuoteKind() {
  16466. return this.getText()[0] === "'" ? exports.QuoteKind.Single : exports.QuoteKind.Double;
  16467. }
  16468. }
  16469. const NoSubstitutionTemplateLiteralBase = LiteralExpression;
  16470. class NoSubstitutionTemplateLiteral extends NoSubstitutionTemplateLiteralBase {
  16471. getLiteralValue() {
  16472. return this.compilerNode.text;
  16473. }
  16474. setLiteralValue(value) {
  16475. const childIndex = this.getChildIndex();
  16476. const parent = this.getParentSyntaxList() || this.getParentOrThrow();
  16477. replaceNodeText({
  16478. sourceFile: this._sourceFile,
  16479. start: this.getStart() + 1,
  16480. replacingLength: this.getWidth() - 2,
  16481. newText: value,
  16482. });
  16483. return parent.getChildAtIndex(childIndex);
  16484. }
  16485. }
  16486. class TaggedTemplateExpression extends MemberExpression {
  16487. getTag() {
  16488. return this._getNodeFromCompilerNode(this.compilerNode.tag);
  16489. }
  16490. getTemplate() {
  16491. return this._getNodeFromCompilerNode(this.compilerNode.template);
  16492. }
  16493. removeTag() {
  16494. const parent = this.getParentSyntaxList() ?? this.getParentOrThrow();
  16495. const index = this.getChildIndex();
  16496. const template = this.getTemplate();
  16497. insertIntoParentTextRange({
  16498. customMappings: (newParent, newSourceFile) => [{ currentNode: template, newNode: newParent.getChildren(newSourceFile)[index] }],
  16499. parent,
  16500. insertPos: this.getStart(),
  16501. newText: this.getTemplate().getText(),
  16502. replacing: {
  16503. textLength: this.getWidth(),
  16504. nodes: [this],
  16505. },
  16506. });
  16507. return parent.getChildAtIndex(index);
  16508. }
  16509. }
  16510. const TemplateExpressionBase = PrimaryExpression;
  16511. class TemplateExpression extends TemplateExpressionBase {
  16512. getHead() {
  16513. return this._getNodeFromCompilerNode(this.compilerNode.head);
  16514. }
  16515. getTemplateSpans() {
  16516. return this.compilerNode.templateSpans.map(s => this._getNodeFromCompilerNode(s));
  16517. }
  16518. setLiteralValue(value) {
  16519. const childIndex = this.getChildIndex();
  16520. const parent = this.getParentSyntaxList() ?? this.getParentOrThrow();
  16521. replaceNodeText({
  16522. sourceFile: this._sourceFile,
  16523. start: this.getStart() + 1,
  16524. replacingLength: this.getWidth() - 2,
  16525. newText: value,
  16526. });
  16527. return parent.getChildAtIndex(childIndex);
  16528. }
  16529. }
  16530. const TemplateHeadBase = LiteralLikeNode(Node);
  16531. class TemplateHead extends TemplateHeadBase {
  16532. }
  16533. const TemplateMiddleBase = LiteralLikeNode(Node);
  16534. class TemplateMiddle extends TemplateMiddleBase {
  16535. }
  16536. const TemplateSpanBase = ExpressionedNode(Node);
  16537. class TemplateSpan extends TemplateSpanBase {
  16538. getLiteral() {
  16539. return this._getNodeFromCompilerNode(this.compilerNode.literal);
  16540. }
  16541. }
  16542. const TemplateTailBase = LiteralLikeNode(Node);
  16543. class TemplateTail extends TemplateTailBase {
  16544. }
  16545. const createBase = (ctor) => ExportGetableNode(ExclamationTokenableNode(TypedNode(InitializerExpressionableNode(BindingNamedNode(ctor)))));
  16546. const VariableDeclarationBase = createBase(Node);
  16547. class VariableDeclaration extends VariableDeclarationBase {
  16548. remove() {
  16549. const parent = this.getParentOrThrow();
  16550. switch (parent.getKind()) {
  16551. case common.SyntaxKind.VariableDeclarationList:
  16552. removeFromDeclarationList(this);
  16553. break;
  16554. case common.SyntaxKind.CatchClause:
  16555. removeFromCatchClause(this);
  16556. break;
  16557. default:
  16558. throw new common.errors.NotImplementedError(`Not implemented for syntax kind: ${parent.getKindName()}`);
  16559. }
  16560. function removeFromDeclarationList(node) {
  16561. const variableStatement = parent.getParentIfKindOrThrow(common.SyntaxKind.VariableStatement);
  16562. const declarations = variableStatement.getDeclarations();
  16563. if (declarations.length === 1)
  16564. variableStatement.remove();
  16565. else
  16566. removeCommaSeparatedChild(node);
  16567. }
  16568. function removeFromCatchClause(node) {
  16569. removeChildren({
  16570. children: [
  16571. node.getPreviousSiblingIfKindOrThrow(common.SyntaxKind.OpenParenToken),
  16572. node,
  16573. node.getNextSiblingIfKindOrThrow(common.SyntaxKind.CloseParenToken),
  16574. ],
  16575. removePrecedingSpaces: true,
  16576. });
  16577. }
  16578. }
  16579. getVariableStatementOrThrow(message) {
  16580. return common.errors.throwIfNullOrUndefined(this.getVariableStatement(), message ?? "Expected the grandparent to be a variable statement.", this);
  16581. }
  16582. getVariableStatement() {
  16583. const grandParent = this.getParentOrThrow().getParentOrThrow();
  16584. return Node.isVariableStatement(grandParent) ? grandParent : undefined;
  16585. }
  16586. set(structure) {
  16587. callBaseSet(VariableDeclarationBase.prototype, this, structure);
  16588. return this;
  16589. }
  16590. getStructure() {
  16591. return callBaseGetStructure(VariableDeclarationBase.prototype, this, {
  16592. kind: exports.StructureKind.VariableDeclaration,
  16593. });
  16594. }
  16595. }
  16596. const VariableDeclarationListBase = ModifierableNode(Node);
  16597. class VariableDeclarationList extends VariableDeclarationListBase {
  16598. getDeclarations() {
  16599. return this.compilerNode.declarations.map(d => this._getNodeFromCompilerNode(d));
  16600. }
  16601. getDeclarationKind() {
  16602. const nodeFlags = this.compilerNode.flags;
  16603. if (nodeFlags & common.ts.NodeFlags.Let)
  16604. return exports.VariableDeclarationKind.Let;
  16605. else if ((nodeFlags & common.ts.NodeFlags.AwaitUsing) === common.ts.NodeFlags.AwaitUsing)
  16606. return exports.VariableDeclarationKind.AwaitUsing;
  16607. else if ((nodeFlags & common.ts.NodeFlags.Using) === common.ts.NodeFlags.Using)
  16608. return exports.VariableDeclarationKind.Using;
  16609. else if (nodeFlags & common.ts.NodeFlags.Const)
  16610. return exports.VariableDeclarationKind.Const;
  16611. else
  16612. return exports.VariableDeclarationKind.Var;
  16613. }
  16614. getDeclarationKindKeywords() {
  16615. const declarationKind = this.getDeclarationKind();
  16616. switch (declarationKind) {
  16617. case exports.VariableDeclarationKind.Const:
  16618. return [this.getFirstChildByKindOrThrow(common.SyntaxKind.ConstKeyword)];
  16619. case exports.VariableDeclarationKind.Let:
  16620. return [this.getFirstChildByKindOrThrow(common.SyntaxKind.LetKeyword)];
  16621. case exports.VariableDeclarationKind.Var:
  16622. return [this.getFirstChildByKindOrThrow(common.SyntaxKind.VarKeyword)];
  16623. case exports.VariableDeclarationKind.Using:
  16624. return [this.getFirstChildByKindOrThrow(common.SyntaxKind.UsingKeyword)];
  16625. case exports.VariableDeclarationKind.AwaitUsing:
  16626. const awaitKeyword = this.getFirstChildByKindOrThrow(common.SyntaxKind.AwaitKeyword);
  16627. const usingKeyword = awaitKeyword.getNextSiblingIfKindOrThrow(common.SyntaxKind.UsingKeyword);
  16628. return [awaitKeyword, usingKeyword];
  16629. default:
  16630. return common.errors.throwNotImplementedForNeverValueError(declarationKind);
  16631. }
  16632. }
  16633. setDeclarationKind(type) {
  16634. if (this.getDeclarationKind() === type)
  16635. return this;
  16636. const keywords = this.getDeclarationKindKeywords();
  16637. const start = keywords[0].getStart();
  16638. const end = keywords[keywords.length - 1].getEnd();
  16639. insertIntoParentTextRange({
  16640. insertPos: start,
  16641. newText: type,
  16642. parent: this,
  16643. replacing: {
  16644. textLength: end - start,
  16645. },
  16646. });
  16647. return this;
  16648. }
  16649. addDeclaration(structure) {
  16650. return this.addDeclarations([structure])[0];
  16651. }
  16652. addDeclarations(structures) {
  16653. return this.insertDeclarations(this.getDeclarations().length, structures);
  16654. }
  16655. insertDeclaration(index, structure) {
  16656. return this.insertDeclarations(index, [structure])[0];
  16657. }
  16658. insertDeclarations(index, structures) {
  16659. const writer = this._getWriterWithQueuedChildIndentation();
  16660. const structurePrinter = new CommaSeparatedStructuresPrinter(this._context.structurePrinterFactory.forVariableDeclaration());
  16661. const originalChildrenCount = this.compilerNode.declarations.length;
  16662. index = verifyAndGetIndex(index, originalChildrenCount);
  16663. structurePrinter.printText(writer, structures);
  16664. insertIntoCommaSeparatedNodes({
  16665. parent: this.getFirstChildByKindOrThrow(common.SyntaxKind.SyntaxList),
  16666. currentNodes: this.getDeclarations(),
  16667. insertIndex: index,
  16668. newText: writer.toString(),
  16669. useTrailingCommas: false,
  16670. });
  16671. return getNodesToReturn(originalChildrenCount, this.getDeclarations(), index, false);
  16672. }
  16673. }
  16674. class Signature {
  16675. #context;
  16676. #compilerSignature;
  16677. constructor(context, signature) {
  16678. this.#context = context;
  16679. this.#compilerSignature = signature;
  16680. }
  16681. get compilerSignature() {
  16682. return this.#compilerSignature;
  16683. }
  16684. getTypeParameters() {
  16685. const typeParameters = this.compilerSignature.typeParameters || [];
  16686. return typeParameters.map(t => this.#context.compilerFactory.getTypeParameter(t));
  16687. }
  16688. getParameters() {
  16689. return this.compilerSignature.parameters.map(p => this.#context.compilerFactory.getSymbol(p));
  16690. }
  16691. getReturnType() {
  16692. return this.#context.compilerFactory.getType(this.compilerSignature.getReturnType());
  16693. }
  16694. getDocumentationComments() {
  16695. const docs = this.compilerSignature.getDocumentationComment(this.#context.typeChecker.compilerObject);
  16696. return docs.map(d => this.#context.compilerFactory.getSymbolDisplayPart(d));
  16697. }
  16698. getJsDocTags() {
  16699. const tags = this.compilerSignature.getJsDocTags();
  16700. return tags.map(t => this.#context.compilerFactory.getJSDocTagInfo(t));
  16701. }
  16702. getDeclaration() {
  16703. const { compilerFactory } = this.#context;
  16704. const compilerSignatureDeclaration = this.compilerSignature.getDeclaration();
  16705. return compilerFactory.getNodeFromCompilerNode(compilerSignatureDeclaration, compilerFactory.getSourceFileForNode(compilerSignatureDeclaration));
  16706. }
  16707. }
  16708. class Symbol {
  16709. #context;
  16710. #compilerSymbol;
  16711. get compilerSymbol() {
  16712. return this.#compilerSymbol;
  16713. }
  16714. constructor(context, symbol) {
  16715. this.#context = context;
  16716. this.#compilerSymbol = symbol;
  16717. this.getValueDeclaration();
  16718. this.getDeclarations();
  16719. }
  16720. getName() {
  16721. return this.compilerSymbol.getName();
  16722. }
  16723. getEscapedName() {
  16724. return this.compilerSymbol.getEscapedName();
  16725. }
  16726. getAliasedSymbolOrThrow(message) {
  16727. return common.errors.throwIfNullOrUndefined(this.getAliasedSymbol(), message ?? "Expected to find an aliased symbol.");
  16728. }
  16729. getImmediatelyAliasedSymbol() {
  16730. return this.#context.typeChecker.getImmediatelyAliasedSymbol(this);
  16731. }
  16732. getImmediatelyAliasedSymbolOrThrow(message) {
  16733. return common.errors.throwIfNullOrUndefined(this.getImmediatelyAliasedSymbol(), message ?? "Expected to find an immediately aliased symbol.");
  16734. }
  16735. getAliasedSymbol() {
  16736. return this.#context.typeChecker.getAliasedSymbol(this);
  16737. }
  16738. getExportSymbol() {
  16739. return this.#context.typeChecker.getExportSymbolOfSymbol(this);
  16740. }
  16741. isAlias() {
  16742. return (this.getFlags() & common.SymbolFlags.Alias) === common.SymbolFlags.Alias;
  16743. }
  16744. isOptional() {
  16745. return (this.getFlags() & common.SymbolFlags.Optional) === common.SymbolFlags.Optional;
  16746. }
  16747. getFlags() {
  16748. return this.compilerSymbol.getFlags();
  16749. }
  16750. hasFlags(flags) {
  16751. return (this.compilerSymbol.flags & flags) === flags;
  16752. }
  16753. getValueDeclarationOrThrow(message) {
  16754. return common.errors.throwIfNullOrUndefined(this.getValueDeclaration(), message ?? (() => `Expected to find the value declaration of symbol '${this.getName()}'.`));
  16755. }
  16756. getValueDeclaration() {
  16757. const declaration = this.compilerSymbol.valueDeclaration;
  16758. if (declaration == null)
  16759. return undefined;
  16760. return this.#context.compilerFactory.getNodeFromCompilerNode(declaration, this.#context.compilerFactory.getSourceFileForNode(declaration));
  16761. }
  16762. getDeclarations() {
  16763. return (this.compilerSymbol.declarations ?? [])
  16764. .map(d => this.#context.compilerFactory.getNodeFromCompilerNode(d, this.#context.compilerFactory.getSourceFileForNode(d)));
  16765. }
  16766. getExportOrThrow(name, message) {
  16767. return common.errors.throwIfNullOrUndefined(this.getExport(name), message ?? (() => `Expected to find export with name: ${name}`));
  16768. }
  16769. getExport(name) {
  16770. if (this.compilerSymbol.exports == null)
  16771. return undefined;
  16772. const tsSymbol = this.compilerSymbol.exports.get(common.ts.escapeLeadingUnderscores(name));
  16773. return tsSymbol == null ? undefined : this.#context.compilerFactory.getSymbol(tsSymbol);
  16774. }
  16775. getExports() {
  16776. if (this.compilerSymbol.exports == null)
  16777. return [];
  16778. return Array.from(this.compilerSymbol.exports.values()).map(symbol => this.#context.compilerFactory.getSymbol(symbol));
  16779. }
  16780. getGlobalExportOrThrow(name, message) {
  16781. return common.errors.throwIfNullOrUndefined(this.getGlobalExport(name), message ?? (() => `Expected to find global export with name: ${name}`));
  16782. }
  16783. getGlobalExport(name) {
  16784. if (this.compilerSymbol.globalExports == null)
  16785. return undefined;
  16786. const tsSymbol = this.compilerSymbol.globalExports.get(common.ts.escapeLeadingUnderscores(name));
  16787. return tsSymbol == null ? undefined : this.#context.compilerFactory.getSymbol(tsSymbol);
  16788. }
  16789. getGlobalExports() {
  16790. if (this.compilerSymbol.globalExports == null)
  16791. return [];
  16792. return Array.from(this.compilerSymbol.globalExports.values()).map(symbol => this.#context.compilerFactory.getSymbol(symbol));
  16793. }
  16794. getMemberOrThrow(name, message) {
  16795. return common.errors.throwIfNullOrUndefined(this.getMember(name), message ?? `Expected to find member with name: ${name}`);
  16796. }
  16797. getMember(name) {
  16798. if (this.compilerSymbol.members == null)
  16799. return undefined;
  16800. const tsSymbol = this.compilerSymbol.members.get(common.ts.escapeLeadingUnderscores(name));
  16801. return tsSymbol == null ? undefined : this.#context.compilerFactory.getSymbol(tsSymbol);
  16802. }
  16803. getMembers() {
  16804. if (this.compilerSymbol.members == null)
  16805. return [];
  16806. return Array.from(this.compilerSymbol.members.values()).map(symbol => this.#context.compilerFactory.getSymbol(symbol));
  16807. }
  16808. getDeclaredType() {
  16809. return this.#context.typeChecker.getDeclaredTypeOfSymbol(this);
  16810. }
  16811. getTypeAtLocation(node) {
  16812. return this.#context.typeChecker.getTypeOfSymbolAtLocation(this, node);
  16813. }
  16814. getFullyQualifiedName() {
  16815. return this.#context.typeChecker.getFullyQualifiedName(this);
  16816. }
  16817. getJsDocTags() {
  16818. return this.compilerSymbol.getJsDocTags(this.#context.typeChecker.compilerObject)
  16819. .map(info => new JSDocTagInfo(info));
  16820. }
  16821. }
  16822. class TextSpan {
  16823. #compilerObject;
  16824. constructor(compilerObject) {
  16825. this.#compilerObject = compilerObject;
  16826. }
  16827. get compilerObject() {
  16828. return this.#compilerObject;
  16829. }
  16830. getStart() {
  16831. return this.compilerObject.start;
  16832. }
  16833. getEnd() {
  16834. return this.compilerObject.start + this.compilerObject.length;
  16835. }
  16836. getLength() {
  16837. return this.compilerObject.length;
  16838. }
  16839. }
  16840. class TextChange {
  16841. #compilerObject;
  16842. constructor(compilerObject) {
  16843. this.#compilerObject = compilerObject;
  16844. }
  16845. get compilerObject() {
  16846. return this.#compilerObject;
  16847. }
  16848. getSpan() {
  16849. return new TextSpan(this.compilerObject.span);
  16850. }
  16851. getNewText() {
  16852. return this.compilerObject.newText;
  16853. }
  16854. }
  16855. __decorate([
  16856. common.Memoize
  16857. ], TextChange.prototype, "getSpan", null);
  16858. class FileTextChanges {
  16859. #context;
  16860. #compilerObject;
  16861. #sourceFile;
  16862. #existingFileExists;
  16863. #isApplied;
  16864. constructor(context, compilerObject) {
  16865. this.#context = context;
  16866. this.#compilerObject = compilerObject;
  16867. const file = context.compilerFactory
  16868. .addOrGetSourceFileFromFilePath(context.fileSystemWrapper.getStandardizedAbsolutePath(compilerObject.fileName), {
  16869. markInProject: false,
  16870. scriptKind: undefined,
  16871. });
  16872. this.#existingFileExists = file != null;
  16873. if (!compilerObject.isNewFile)
  16874. this.#sourceFile = file;
  16875. }
  16876. getFilePath() {
  16877. return this.#compilerObject.fileName;
  16878. }
  16879. getSourceFile() {
  16880. return this.#sourceFile;
  16881. }
  16882. getTextChanges() {
  16883. return this.#compilerObject.textChanges.map(c => new TextChange(c));
  16884. }
  16885. applyChanges(options = {}) {
  16886. if (this.#isApplied)
  16887. return;
  16888. if (this.isNewFile() && this.#existingFileExists && !options.overwrite) {
  16889. throw new common.errors.InvalidOperationError(`Cannot apply file text change for creating a new file when the `
  16890. + `file exists at path ${this.getFilePath()}. Did you mean to provide the overwrite option?`);
  16891. }
  16892. let file;
  16893. if (this.isNewFile())
  16894. file = this.#context.project.createSourceFile(this.getFilePath(), "", { overwrite: options.overwrite });
  16895. else
  16896. file = this.getSourceFile();
  16897. if (file == null) {
  16898. throw new common.errors.InvalidOperationError(`Cannot apply file text change to modify existing file `
  16899. + `that doesn't exist at path: ${this.getFilePath()}`);
  16900. }
  16901. file.applyTextChanges(this.getTextChanges());
  16902. file._markAsInProject();
  16903. this.#isApplied = true;
  16904. return this;
  16905. }
  16906. isNewFile() {
  16907. return !!this.#compilerObject.isNewFile;
  16908. }
  16909. }
  16910. __decorate([
  16911. common.Memoize
  16912. ], FileTextChanges.prototype, "getTextChanges", null);
  16913. class CodeAction {
  16914. #context;
  16915. #compilerObject;
  16916. constructor(context, compilerObject) {
  16917. this.#context = context;
  16918. this.#compilerObject = compilerObject;
  16919. }
  16920. get compilerObject() {
  16921. return this.#compilerObject;
  16922. }
  16923. getDescription() {
  16924. return this.compilerObject.description;
  16925. }
  16926. getChanges() {
  16927. return this.compilerObject.changes.map(change => new FileTextChanges(this.#context, change));
  16928. }
  16929. }
  16930. class CodeFixAction extends CodeAction {
  16931. getFixName() {
  16932. return this.compilerObject.fixName;
  16933. }
  16934. getFixId() {
  16935. return this.compilerObject.fixId;
  16936. }
  16937. getFixAllDescription() {
  16938. return this.compilerObject.fixAllDescription;
  16939. }
  16940. }
  16941. class CombinedCodeActions {
  16942. #context;
  16943. #compilerObject;
  16944. constructor(context, compilerObject) {
  16945. this.#context = context;
  16946. this.#compilerObject = compilerObject;
  16947. }
  16948. get compilerObject() {
  16949. return this.#compilerObject;
  16950. }
  16951. getChanges() {
  16952. return this.compilerObject.changes.map(change => new FileTextChanges(this.#context, change));
  16953. }
  16954. applyChanges(options) {
  16955. for (const change of this.getChanges())
  16956. change.applyChanges(options);
  16957. return this;
  16958. }
  16959. }
  16960. __decorate([
  16961. common.Memoize
  16962. ], CombinedCodeActions.prototype, "getChanges", null);
  16963. class DocumentSpan {
  16964. _context;
  16965. _compilerObject;
  16966. _sourceFile;
  16967. constructor(context, compilerObject) {
  16968. this._context = context;
  16969. this._compilerObject = compilerObject;
  16970. this._sourceFile = this._context.compilerFactory
  16971. .addOrGetSourceFileFromFilePath(context.fileSystemWrapper.getStandardizedAbsolutePath(this.compilerObject.fileName), {
  16972. markInProject: false,
  16973. scriptKind: undefined,
  16974. });
  16975. this._sourceFile._doActionPreNextModification(() => this.getNode());
  16976. }
  16977. get compilerObject() {
  16978. return this._compilerObject;
  16979. }
  16980. getSourceFile() {
  16981. return this._sourceFile;
  16982. }
  16983. getTextSpan() {
  16984. return new TextSpan(this.compilerObject.textSpan);
  16985. }
  16986. getNode() {
  16987. const textSpan = this.getTextSpan();
  16988. const sourceFile = this.getSourceFile();
  16989. const start = textSpan.getStart();
  16990. const width = textSpan.getEnd();
  16991. return findBestMatchingNode();
  16992. function findBestMatchingNode() {
  16993. let bestNode;
  16994. sourceFile._context.compilerFactory.forgetNodesCreatedInBlock(remember => {
  16995. let foundNode;
  16996. let nextNode = sourceFile;
  16997. while (nextNode != null) {
  16998. if (foundNode == null)
  16999. bestNode = nextNode;
  17000. if (nextNode.getStart() === start && nextNode.getWidth() === width)
  17001. bestNode = foundNode = nextNode;
  17002. else if (foundNode != null)
  17003. break;
  17004. nextNode = nextNode.getChildAtPos(start);
  17005. }
  17006. if (bestNode != null)
  17007. remember(bestNode);
  17008. });
  17009. return bestNode;
  17010. }
  17011. }
  17012. getOriginalTextSpan() {
  17013. const { originalTextSpan } = this.compilerObject;
  17014. return originalTextSpan == null ? undefined : new TextSpan(originalTextSpan);
  17015. }
  17016. getOriginalFileName() {
  17017. return this.compilerObject.originalFileName;
  17018. }
  17019. }
  17020. __decorate([
  17021. common.Memoize
  17022. ], DocumentSpan.prototype, "getTextSpan", null);
  17023. __decorate([
  17024. common.Memoize
  17025. ], DocumentSpan.prototype, "getNode", null);
  17026. __decorate([
  17027. common.Memoize
  17028. ], DocumentSpan.prototype, "getOriginalTextSpan", null);
  17029. class DefinitionInfo extends DocumentSpan {
  17030. constructor(context, compilerObject) {
  17031. super(context, compilerObject);
  17032. this.getSourceFile()._doActionPreNextModification(() => this.getDeclarationNode());
  17033. }
  17034. getKind() {
  17035. return this.compilerObject.kind;
  17036. }
  17037. getName() {
  17038. return this.compilerObject.name;
  17039. }
  17040. getContainerKind() {
  17041. return this.compilerObject.containerKind;
  17042. }
  17043. getContainerName() {
  17044. return this.compilerObject.containerName;
  17045. }
  17046. getDeclarationNode() {
  17047. if (this.getKind() === "module" && this.getTextSpan().getLength() === this.getSourceFile().getFullWidth())
  17048. return this.getSourceFile();
  17049. const start = this.getTextSpan().getStart();
  17050. const identifier = findIdentifier(this.getSourceFile());
  17051. return identifier == null ? undefined : identifier.getParentOrThrow();
  17052. function findIdentifier(node) {
  17053. if (node.getKind() === common.SyntaxKind.Identifier && node.getStart() === start)
  17054. return node;
  17055. for (const child of node._getChildrenIterator()) {
  17056. if (child.getPos() <= start && child.getEnd() > start)
  17057. return findIdentifier(child);
  17058. }
  17059. return undefined;
  17060. }
  17061. }
  17062. }
  17063. __decorate([
  17064. common.Memoize
  17065. ], DefinitionInfo.prototype, "getDeclarationNode", null);
  17066. class DiagnosticMessageChain {
  17067. _compilerObject;
  17068. constructor(compilerObject) {
  17069. this._compilerObject = compilerObject;
  17070. }
  17071. get compilerObject() {
  17072. return this._compilerObject;
  17073. }
  17074. getMessageText() {
  17075. return this.compilerObject.messageText;
  17076. }
  17077. getNext() {
  17078. const next = this.compilerObject.next;
  17079. if (next == null)
  17080. return undefined;
  17081. if (next instanceof Array)
  17082. return next.map(n => new DiagnosticMessageChain(n));
  17083. return [new DiagnosticMessageChain(next)];
  17084. }
  17085. getCode() {
  17086. return this.compilerObject.code;
  17087. }
  17088. getCategory() {
  17089. return this.compilerObject.category;
  17090. }
  17091. }
  17092. class Diagnostic {
  17093. _context;
  17094. _compilerObject;
  17095. constructor(context, compilerObject) {
  17096. this._context = context;
  17097. this._compilerObject = compilerObject;
  17098. this.getSourceFile();
  17099. }
  17100. get compilerObject() {
  17101. return this._compilerObject;
  17102. }
  17103. getSourceFile() {
  17104. if (this._context == null)
  17105. return undefined;
  17106. const file = this.compilerObject.file;
  17107. return file == null ? undefined : this._context.compilerFactory.getSourceFile(file, { markInProject: false });
  17108. }
  17109. getMessageText() {
  17110. const messageText = this._compilerObject.messageText;
  17111. if (typeof messageText === "string")
  17112. return messageText;
  17113. if (this._context == null)
  17114. return new DiagnosticMessageChain(messageText);
  17115. else
  17116. return this._context.compilerFactory.getDiagnosticMessageChain(messageText);
  17117. }
  17118. getLineNumber() {
  17119. const sourceFile = this.getSourceFile();
  17120. const start = this.getStart();
  17121. if (sourceFile == null || start == null)
  17122. return undefined;
  17123. return common.StringUtils.getLineNumberAtPos(sourceFile.getFullText(), start);
  17124. }
  17125. getStart() {
  17126. return this.compilerObject.start;
  17127. }
  17128. getLength() {
  17129. return this.compilerObject.length;
  17130. }
  17131. getCategory() {
  17132. return this.compilerObject.category;
  17133. }
  17134. getCode() {
  17135. return this.compilerObject.code;
  17136. }
  17137. getSource() {
  17138. return this.compilerObject.source;
  17139. }
  17140. }
  17141. __decorate([
  17142. common.Memoize
  17143. ], Diagnostic.prototype, "getSourceFile", null);
  17144. class DiagnosticWithLocation extends Diagnostic {
  17145. constructor(context, compilerObject) {
  17146. super(context, compilerObject);
  17147. }
  17148. getLineNumber() {
  17149. return super.getLineNumber();
  17150. }
  17151. getStart() {
  17152. return super.getStart();
  17153. }
  17154. getLength() {
  17155. return super.getLength();
  17156. }
  17157. getSourceFile() {
  17158. return super.getSourceFile();
  17159. }
  17160. }
  17161. class OutputFile {
  17162. #compilerObject;
  17163. #context;
  17164. constructor(context, compilerObject) {
  17165. this.#compilerObject = compilerObject;
  17166. this.#context = context;
  17167. }
  17168. get compilerObject() {
  17169. return this.#compilerObject;
  17170. }
  17171. getFilePath() {
  17172. return this.#context.fileSystemWrapper.getStandardizedAbsolutePath(this.compilerObject.name);
  17173. }
  17174. getWriteByteOrderMark() {
  17175. return this.compilerObject.writeByteOrderMark || false;
  17176. }
  17177. getText() {
  17178. return this.compilerObject.text;
  17179. }
  17180. }
  17181. class EmitOutput {
  17182. #context;
  17183. #compilerObject;
  17184. constructor(context, compilerObject) {
  17185. this.#context = context;
  17186. this.#compilerObject = compilerObject;
  17187. }
  17188. get compilerObject() {
  17189. return this.#compilerObject;
  17190. }
  17191. getDiagnostics() {
  17192. return this.compilerObject.diagnostics.map(d => this.#context.compilerFactory.getDiagnostic(d));
  17193. }
  17194. getEmitSkipped() {
  17195. return this.compilerObject.emitSkipped;
  17196. }
  17197. getOutputFiles() {
  17198. return this.compilerObject.outputFiles.map(f => new OutputFile(this.#context, f));
  17199. }
  17200. }
  17201. __decorate([
  17202. common.Memoize
  17203. ], EmitOutput.prototype, "getDiagnostics", null);
  17204. __decorate([
  17205. common.Memoize
  17206. ], EmitOutput.prototype, "getOutputFiles", null);
  17207. class EmitResult {
  17208. _context;
  17209. _compilerObject;
  17210. constructor(context, compilerObject) {
  17211. this._context = context;
  17212. this._compilerObject = compilerObject;
  17213. this.getDiagnostics();
  17214. }
  17215. get compilerObject() {
  17216. return this._compilerObject;
  17217. }
  17218. getEmitSkipped() {
  17219. return this.compilerObject.emitSkipped;
  17220. }
  17221. getDiagnostics() {
  17222. return this.compilerObject.diagnostics.map(d => this._context.compilerFactory.getDiagnostic(d));
  17223. }
  17224. }
  17225. __decorate([
  17226. common.Memoize
  17227. ], EmitResult.prototype, "getDiagnostics", null);
  17228. class ImplementationLocation extends DocumentSpan {
  17229. constructor(context, compilerObject) {
  17230. super(context, compilerObject);
  17231. }
  17232. getKind() {
  17233. return this.compilerObject.kind;
  17234. }
  17235. getDisplayParts() {
  17236. return this.compilerObject.displayParts.map(p => this._context.compilerFactory.getSymbolDisplayPart(p));
  17237. }
  17238. }
  17239. __decorate([
  17240. common.Memoize
  17241. ], ImplementationLocation.prototype, "getDisplayParts", null);
  17242. class MemoryEmitResult extends EmitResult {
  17243. #files;
  17244. constructor(context, compilerObject, files) {
  17245. super(context, compilerObject);
  17246. this.#files = files;
  17247. }
  17248. getFiles() {
  17249. return this.#files;
  17250. }
  17251. saveFiles() {
  17252. const fileSystem = this._context.fileSystemWrapper;
  17253. const promises = this.#files.map(f => fileSystem.writeFile(f.filePath, f.writeByteOrderMark ? "\uFEFF" + f.text : f.text));
  17254. return Promise.all(promises);
  17255. }
  17256. saveFilesSync() {
  17257. const fileSystem = this._context.fileSystemWrapper;
  17258. for (const file of this.#files)
  17259. fileSystem.writeFileSync(file.filePath, file.writeByteOrderMark ? "\uFEFF" + file.text : file.text);
  17260. }
  17261. }
  17262. class RefactorEditInfo {
  17263. #context;
  17264. #compilerObject;
  17265. constructor(context, compilerObject) {
  17266. this.#context = context;
  17267. this.#compilerObject = compilerObject;
  17268. }
  17269. get compilerObject() {
  17270. return this.#compilerObject;
  17271. }
  17272. getEdits() {
  17273. return this.compilerObject.edits.map(edit => new FileTextChanges(this.#context, edit));
  17274. }
  17275. getRenameFilePath() {
  17276. return this.compilerObject.renameFilename;
  17277. }
  17278. getRenameLocation() {
  17279. return this.compilerObject.renameLocation;
  17280. }
  17281. applyChanges(options) {
  17282. for (const change of this.getEdits())
  17283. change.applyChanges(options);
  17284. return this;
  17285. }
  17286. }
  17287. __decorate([
  17288. common.Memoize
  17289. ], RefactorEditInfo.prototype, "getEdits", null);
  17290. class ReferencedSymbol {
  17291. _context;
  17292. #compilerObject;
  17293. #references;
  17294. constructor(context, compilerObject) {
  17295. this._context = context;
  17296. this.#compilerObject = compilerObject;
  17297. this.#references = this.compilerObject.references.map(r => context.compilerFactory.getReferencedSymbolEntry(r));
  17298. }
  17299. get compilerObject() {
  17300. return this.#compilerObject;
  17301. }
  17302. getDefinition() {
  17303. return this._context.compilerFactory.getReferencedSymbolDefinitionInfo(this.compilerObject.definition);
  17304. }
  17305. getReferences() {
  17306. return this.#references;
  17307. }
  17308. }
  17309. __decorate([
  17310. common.Memoize
  17311. ], ReferencedSymbol.prototype, "getDefinition", null);
  17312. class ReferencedSymbolDefinitionInfo extends DefinitionInfo {
  17313. constructor(context, compilerObject) {
  17314. super(context, compilerObject);
  17315. }
  17316. getDisplayParts() {
  17317. return this.compilerObject.displayParts.map(p => this._context.compilerFactory.getSymbolDisplayPart(p));
  17318. }
  17319. }
  17320. __decorate([
  17321. common.Memoize
  17322. ], ReferencedSymbolDefinitionInfo.prototype, "getDisplayParts", null);
  17323. class ReferenceEntry extends DocumentSpan {
  17324. constructor(context, compilerObject) {
  17325. super(context, compilerObject);
  17326. }
  17327. isWriteAccess() {
  17328. return this.compilerObject.isWriteAccess;
  17329. }
  17330. isInString() {
  17331. return this.compilerObject.isInString;
  17332. }
  17333. }
  17334. class ReferencedSymbolEntry extends ReferenceEntry {
  17335. constructor(context, compilerObject) {
  17336. super(context, compilerObject);
  17337. }
  17338. isDefinition() {
  17339. return this.compilerObject.isDefinition;
  17340. }
  17341. }
  17342. class RenameLocation extends DocumentSpan {
  17343. getPrefixText() {
  17344. return this._compilerObject.prefixText;
  17345. }
  17346. getSuffixText() {
  17347. return this._compilerObject.suffixText;
  17348. }
  17349. }
  17350. class SymbolDisplayPart {
  17351. #compilerObject;
  17352. constructor(compilerObject) {
  17353. this.#compilerObject = compilerObject;
  17354. }
  17355. get compilerObject() {
  17356. return this.#compilerObject;
  17357. }
  17358. getText() {
  17359. return this.compilerObject.text;
  17360. }
  17361. getKind() {
  17362. return this.compilerObject.kind;
  17363. }
  17364. }
  17365. class TypeChecker {
  17366. #context;
  17367. #getCompilerObject;
  17368. constructor(context) {
  17369. this.#context = context;
  17370. }
  17371. get compilerObject() {
  17372. return this.#getCompilerObject();
  17373. }
  17374. _reset(getTypeChecker) {
  17375. this.#getCompilerObject = getTypeChecker;
  17376. }
  17377. getAmbientModules() {
  17378. return this.compilerObject.getAmbientModules().map(s => this.#context.compilerFactory.getSymbol(s));
  17379. }
  17380. getApparentType(type) {
  17381. return this.#context.compilerFactory.getType(this.compilerObject.getApparentType(type.compilerType));
  17382. }
  17383. getConstantValue(node) {
  17384. return this.compilerObject.getConstantValue(node.compilerNode);
  17385. }
  17386. getFullyQualifiedName(symbol) {
  17387. return this.compilerObject.getFullyQualifiedName(symbol.compilerSymbol);
  17388. }
  17389. getTypeAtLocation(node) {
  17390. return this.#context.compilerFactory.getType(this.compilerObject.getTypeAtLocation(node.compilerNode));
  17391. }
  17392. getContextualType(expression) {
  17393. const contextualType = this.compilerObject.getContextualType(expression.compilerNode);
  17394. return contextualType == null ? undefined : this.#context.compilerFactory.getType(contextualType);
  17395. }
  17396. getTypeOfSymbolAtLocation(symbol, node) {
  17397. return this.#context.compilerFactory.getType(this.compilerObject.getTypeOfSymbolAtLocation(symbol.compilerSymbol, node.compilerNode));
  17398. }
  17399. getDeclaredTypeOfSymbol(symbol) {
  17400. return this.#context.compilerFactory.getType(this.compilerObject.getDeclaredTypeOfSymbol(symbol.compilerSymbol));
  17401. }
  17402. getSymbolAtLocation(node) {
  17403. const compilerSymbol = this.compilerObject.getSymbolAtLocation(node.compilerNode);
  17404. return compilerSymbol == null ? undefined : this.#context.compilerFactory.getSymbol(compilerSymbol);
  17405. }
  17406. getAliasedSymbol(symbol) {
  17407. if (!symbol.hasFlags(common.SymbolFlags.Alias))
  17408. return undefined;
  17409. const tsAliasSymbol = this.compilerObject.getAliasedSymbol(symbol.compilerSymbol);
  17410. return tsAliasSymbol == null ? undefined : this.#context.compilerFactory.getSymbol(tsAliasSymbol);
  17411. }
  17412. getImmediatelyAliasedSymbol(symbol) {
  17413. const tsAliasSymbol = this.compilerObject.getImmediateAliasedSymbol(symbol.compilerSymbol);
  17414. return tsAliasSymbol == null ? undefined : this.#context.compilerFactory.getSymbol(tsAliasSymbol);
  17415. }
  17416. getExportSymbolOfSymbol(symbol) {
  17417. return this.#context.compilerFactory.getSymbol(this.compilerObject.getExportSymbolOfSymbol(symbol.compilerSymbol));
  17418. }
  17419. getPropertiesOfType(type) {
  17420. return this.compilerObject.getPropertiesOfType(type.compilerType).map(p => this.#context.compilerFactory.getSymbol(p));
  17421. }
  17422. getTypeText(type, enclosingNode, typeFormatFlags) {
  17423. if (typeFormatFlags == null)
  17424. typeFormatFlags = this.#getDefaultTypeFormatFlags(enclosingNode);
  17425. return this.compilerObject.typeToString(type.compilerType, enclosingNode?.compilerNode, typeFormatFlags);
  17426. }
  17427. getReturnTypeOfSignature(signature) {
  17428. return this.#context.compilerFactory.getType(this.compilerObject.getReturnTypeOfSignature(signature.compilerSignature));
  17429. }
  17430. getSignatureFromNode(node) {
  17431. const signature = this.compilerObject.getSignatureFromDeclaration(node.compilerNode);
  17432. return signature == null ? undefined : this.#context.compilerFactory.getSignature(signature);
  17433. }
  17434. getExportsOfModule(moduleSymbol) {
  17435. const symbols = this.compilerObject.getExportsOfModule(moduleSymbol.compilerSymbol);
  17436. return (symbols || []).map(s => this.#context.compilerFactory.getSymbol(s));
  17437. }
  17438. getExportSpecifierLocalTargetSymbol(exportSpecifier) {
  17439. const symbol = this.compilerObject.getExportSpecifierLocalTargetSymbol(exportSpecifier.compilerNode);
  17440. return symbol == null ? undefined : this.#context.compilerFactory.getSymbol(symbol);
  17441. }
  17442. getResolvedSignature(node) {
  17443. const resolvedSignature = this.compilerObject.getResolvedSignature(node.compilerNode);
  17444. if (!resolvedSignature || !resolvedSignature.declaration)
  17445. return undefined;
  17446. return this.#context.compilerFactory.getSignature(resolvedSignature);
  17447. }
  17448. getResolvedSignatureOrThrow(node, message) {
  17449. return common.errors.throwIfNullOrUndefined(this.getResolvedSignature(node), message ?? "Signature could not be resolved.", node);
  17450. }
  17451. getBaseTypeOfLiteralType(type) {
  17452. return this.#context.compilerFactory.getType(this.compilerObject.getBaseTypeOfLiteralType(type.compilerType));
  17453. }
  17454. getSymbolsInScope(node, meaning) {
  17455. return this.compilerObject.getSymbolsInScope(node.compilerNode, meaning)
  17456. .map(s => this.#context.compilerFactory.getSymbol(s));
  17457. }
  17458. getTypeArguments(typeReference) {
  17459. return this.compilerObject.getTypeArguments(typeReference.compilerType)
  17460. .map(arg => this.#context.compilerFactory.getType(arg));
  17461. }
  17462. isTypeAssignableTo(sourceType, targetType) {
  17463. return this.compilerObject.isTypeAssignableTo(sourceType.compilerType, targetType.compilerType);
  17464. }
  17465. #getDefaultTypeFormatFlags(enclosingNode) {
  17466. let formatFlags = (common.TypeFormatFlags.UseTypeOfFunction | common.TypeFormatFlags.NoTruncation | common.TypeFormatFlags.UseFullyQualifiedType
  17467. | common.TypeFormatFlags.WriteTypeArgumentsOfSignature);
  17468. if (enclosingNode != null && enclosingNode.getKind() === common.SyntaxKind.TypeAliasDeclaration)
  17469. formatFlags |= common.TypeFormatFlags.InTypeAlias;
  17470. return formatFlags;
  17471. }
  17472. getShorthandAssignmentValueSymbol(node) {
  17473. const symbol = this.compilerObject.getShorthandAssignmentValueSymbol(node.compilerNode);
  17474. return symbol ? this.#context.compilerFactory.getSymbol(symbol) : undefined;
  17475. }
  17476. resolveName(name, location, meaning, excludeGlobals) {
  17477. const symbol = this.compilerObject.resolveName(name, location?.compilerNode, meaning, excludeGlobals);
  17478. return symbol ? this.#context.compilerFactory.getSymbol(symbol) : undefined;
  17479. }
  17480. }
  17481. class Program {
  17482. #context;
  17483. #typeChecker;
  17484. #createdCompilerObject;
  17485. #oldProgram;
  17486. #getOrCreateCompilerObject;
  17487. #configFileParsingDiagnostics;
  17488. constructor(opts) {
  17489. this.#context = opts.context;
  17490. this.#configFileParsingDiagnostics = opts.configFileParsingDiagnostics;
  17491. this.#typeChecker = new TypeChecker(this.#context);
  17492. this._reset(opts.rootNames, opts.host);
  17493. }
  17494. get compilerObject() {
  17495. return this.#getOrCreateCompilerObject();
  17496. }
  17497. _isCompilerProgramCreated() {
  17498. return this.#createdCompilerObject != null;
  17499. }
  17500. _reset(rootNames, host) {
  17501. const compilerOptions = this.#context.compilerOptions.get();
  17502. this.#getOrCreateCompilerObject = () => {
  17503. if (this.#createdCompilerObject == null) {
  17504. this.#createdCompilerObject = common.ts.createProgram(rootNames, compilerOptions, host, this.#oldProgram, this.#configFileParsingDiagnostics);
  17505. this.#oldProgram = undefined;
  17506. }
  17507. return this.#createdCompilerObject;
  17508. };
  17509. if (this.#createdCompilerObject != null) {
  17510. this.#oldProgram = this.#createdCompilerObject;
  17511. this.#createdCompilerObject = undefined;
  17512. }
  17513. this.#typeChecker._reset(() => this.compilerObject.getTypeChecker());
  17514. }
  17515. getTypeChecker() {
  17516. return this.#typeChecker;
  17517. }
  17518. async emit(options = {}) {
  17519. if (options.writeFile) {
  17520. const message = `Cannot specify a ${common.nameof(options, "writeFile")} option when emitting asynchrously. `
  17521. + `Use ${common.nameof(this, "emitSync")}() instead.`;
  17522. throw new common.errors.InvalidOperationError(message);
  17523. }
  17524. const { fileSystemWrapper } = this.#context;
  17525. const promises = [];
  17526. const emitResult = this.#emit({
  17527. writeFile: (filePath, text, writeByteOrderMark) => {
  17528. promises
  17529. .push(fileSystemWrapper.writeFile(fileSystemWrapper.getStandardizedAbsolutePath(filePath), writeByteOrderMark ? "\uFEFF" + text : text));
  17530. },
  17531. ...options,
  17532. });
  17533. await Promise.all(promises);
  17534. return new EmitResult(this.#context, emitResult);
  17535. }
  17536. emitSync(options = {}) {
  17537. return new EmitResult(this.#context, this.#emit(options));
  17538. }
  17539. emitToMemory(options = {}) {
  17540. const sourceFiles = [];
  17541. const { fileSystemWrapper } = this.#context;
  17542. const emitResult = this.#emit({
  17543. writeFile: (filePath, text, writeByteOrderMark) => {
  17544. sourceFiles.push({
  17545. filePath: fileSystemWrapper.getStandardizedAbsolutePath(filePath),
  17546. text,
  17547. writeByteOrderMark: writeByteOrderMark || false,
  17548. });
  17549. },
  17550. ...options,
  17551. });
  17552. return new MemoryEmitResult(this.#context, emitResult, sourceFiles);
  17553. }
  17554. #emit(options = {}) {
  17555. const targetSourceFile = options.targetSourceFile != null ? options.targetSourceFile.compilerNode : undefined;
  17556. const { emitOnlyDtsFiles, customTransformers, writeFile } = options;
  17557. const cancellationToken = undefined;
  17558. return this.compilerObject.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
  17559. }
  17560. getSyntacticDiagnostics(sourceFile) {
  17561. const compilerDiagnostics = this.compilerObject.getSyntacticDiagnostics(sourceFile == null ? undefined : sourceFile.compilerNode);
  17562. return compilerDiagnostics.map(d => this.#context.compilerFactory.getDiagnosticWithLocation(d));
  17563. }
  17564. getSemanticDiagnostics(sourceFile) {
  17565. const compilerDiagnostics = this.compilerObject.getSemanticDiagnostics(sourceFile?.compilerNode);
  17566. return compilerDiagnostics.map(d => this.#context.compilerFactory.getDiagnostic(d));
  17567. }
  17568. getDeclarationDiagnostics(sourceFile) {
  17569. const compilerDiagnostics = this.compilerObject.getDeclarationDiagnostics(sourceFile?.compilerNode);
  17570. return compilerDiagnostics.map(d => this.#context.compilerFactory.getDiagnosticWithLocation(d));
  17571. }
  17572. getGlobalDiagnostics() {
  17573. const compilerDiagnostics = this.compilerObject.getGlobalDiagnostics();
  17574. return compilerDiagnostics.map(d => this.#context.compilerFactory.getDiagnostic(d));
  17575. }
  17576. getConfigFileParsingDiagnostics() {
  17577. const compilerDiagnostics = this.compilerObject.getConfigFileParsingDiagnostics();
  17578. return compilerDiagnostics.map(d => this.#context.compilerFactory.getDiagnostic(d));
  17579. }
  17580. getEmitModuleResolutionKind() {
  17581. return common.getEmitModuleResolutionKind(this.compilerObject.getCompilerOptions());
  17582. }
  17583. isSourceFileFromExternalLibrary(sourceFile) {
  17584. return sourceFile.isFromExternalLibrary();
  17585. }
  17586. }
  17587. class LanguageService {
  17588. #compilerObject;
  17589. #compilerHost;
  17590. #program;
  17591. #context;
  17592. #projectVersion = 0;
  17593. get compilerObject() {
  17594. return this.#compilerObject;
  17595. }
  17596. constructor(params) {
  17597. this.#context = params.context;
  17598. const { languageServiceHost, compilerHost } = common.createHosts({
  17599. transactionalFileSystem: this.#context.fileSystemWrapper,
  17600. sourceFileContainer: this.#context.getSourceFileContainer(),
  17601. compilerOptions: this.#context.compilerOptions,
  17602. getNewLine: () => this.#context.manipulationSettings.getNewLineKindAsString(),
  17603. getProjectVersion: () => `${this.#projectVersion}`,
  17604. resolutionHost: params.resolutionHost ?? {},
  17605. libFolderPath: params.libFolderPath,
  17606. skipLoadingLibFiles: params.skipLoadingLibFiles,
  17607. });
  17608. this.#compilerHost = compilerHost;
  17609. this.#compilerObject = common.ts.createLanguageService(languageServiceHost, this.#context.compilerFactory.documentRegistry);
  17610. this.#program = new Program({
  17611. context: this.#context,
  17612. rootNames: Array.from(this.#context.compilerFactory.getSourceFilePaths()),
  17613. host: this.#compilerHost,
  17614. configFileParsingDiagnostics: params.configFileParsingDiagnostics,
  17615. });
  17616. this.#context.compilerFactory.onSourceFileAdded(sourceFile => {
  17617. if (sourceFile._isInProject())
  17618. this._reset();
  17619. });
  17620. this.#context.compilerFactory.onSourceFileRemoved(() => this._reset());
  17621. }
  17622. _reset() {
  17623. this.#projectVersion += 1;
  17624. this.#program._reset(Array.from(this.#context.compilerFactory.getSourceFilePaths()), this.#compilerHost);
  17625. }
  17626. getProgram() {
  17627. return this.#program;
  17628. }
  17629. getDefinitions(node) {
  17630. return this.getDefinitionsAtPosition(node._sourceFile, node.getStart());
  17631. }
  17632. getDefinitionsAtPosition(sourceFile, pos) {
  17633. const results = this.compilerObject.getDefinitionAtPosition(sourceFile.getFilePath(), pos) || [];
  17634. return results.map(info => this.#context.compilerFactory.getDefinitionInfo(info));
  17635. }
  17636. getImplementations(node) {
  17637. return this.getImplementationsAtPosition(node._sourceFile, node.getStart());
  17638. }
  17639. getImplementationsAtPosition(sourceFile, pos) {
  17640. const results = this.compilerObject.getImplementationAtPosition(sourceFile.getFilePath(), pos) || [];
  17641. return results.map(location => new ImplementationLocation(this.#context, location));
  17642. }
  17643. findReferences(node) {
  17644. return this.findReferencesAtPosition(node._sourceFile, node.getStart());
  17645. }
  17646. findReferencesAsNodes(node) {
  17647. const referencedSymbols = this.findReferences(node);
  17648. return Array.from(getReferencingNodes());
  17649. function* getReferencingNodes() {
  17650. for (const referencedSymbol of referencedSymbols) {
  17651. const isAlias = referencedSymbol.getDefinition().getKind() === common.ts.ScriptElementKind.alias;
  17652. const references = referencedSymbol.getReferences();
  17653. for (let i = 0; i < references.length; i++) {
  17654. const reference = references[i];
  17655. if (isAlias || !reference.isDefinition() || i > 0)
  17656. yield reference.getNode();
  17657. }
  17658. }
  17659. }
  17660. }
  17661. findReferencesAtPosition(sourceFile, pos) {
  17662. const results = this.compilerObject.findReferences(sourceFile.getFilePath(), pos) || [];
  17663. return results.map(s => this.#context.compilerFactory.getReferencedSymbol(s));
  17664. }
  17665. findRenameLocations(node, options = {}) {
  17666. const usePrefixAndSuffixText = options.usePrefixAndSuffixText == null
  17667. ? this.#context.manipulationSettings.getUsePrefixAndSuffixTextForRename()
  17668. : options.usePrefixAndSuffixText;
  17669. const renameLocations = this.compilerObject.findRenameLocations(node._sourceFile.getFilePath(), node.getStart(), options.renameInStrings || false, options.renameInComments || false, usePrefixAndSuffixText) || [];
  17670. return renameLocations.map(l => new RenameLocation(this.#context, l));
  17671. }
  17672. getSuggestionDiagnostics(filePathOrSourceFile) {
  17673. const filePath = this.#getFilePathFromFilePathOrSourceFile(filePathOrSourceFile);
  17674. const suggestionDiagnostics = this.compilerObject.getSuggestionDiagnostics(filePath);
  17675. return suggestionDiagnostics.map(d => this.#context.compilerFactory.getDiagnosticWithLocation(d));
  17676. }
  17677. getFormattingEditsForRange(filePath, range, formatSettings) {
  17678. return (this.compilerObject.getFormattingEditsForRange(filePath, range[0], range[1], this.#getFilledSettings(formatSettings)) || []).map(e => new TextChange(e));
  17679. }
  17680. getFormattingEditsForDocument(filePath, formatSettings) {
  17681. const standardizedFilePath = this.#context.fileSystemWrapper.getStandardizedAbsolutePath(filePath);
  17682. return (this.compilerObject.getFormattingEditsForDocument(standardizedFilePath, this.#getFilledSettings(formatSettings)) || [])
  17683. .map(e => new TextChange(e));
  17684. }
  17685. getFormattedDocumentText(filePath, formatSettings) {
  17686. const standardizedFilePath = this.#context.fileSystemWrapper.getStandardizedAbsolutePath(filePath);
  17687. const sourceFile = this.#context.compilerFactory.getSourceFileFromCacheFromFilePath(standardizedFilePath);
  17688. if (sourceFile == null)
  17689. throw new common.errors.FileNotFoundError(standardizedFilePath);
  17690. formatSettings = this.#getFilledSettings(formatSettings);
  17691. const formattingEdits = this.getFormattingEditsForDocument(standardizedFilePath, formatSettings);
  17692. let newText = getTextFromTextChanges(sourceFile, formattingEdits);
  17693. const newLineChar = formatSettings.newLineCharacter;
  17694. if (formatSettings.ensureNewLineAtEndOfFile && !newText.endsWith(newLineChar))
  17695. newText += newLineChar;
  17696. return newText.replace(/\r?\n/g, newLineChar);
  17697. }
  17698. getEmitOutput(filePathOrSourceFile, emitOnlyDtsFiles) {
  17699. const filePath = this.#getFilePathFromFilePathOrSourceFile(filePathOrSourceFile);
  17700. const compilerObject = this.compilerObject;
  17701. return new EmitOutput(this.#context, getCompilerEmitOutput());
  17702. function getCompilerEmitOutput() {
  17703. const program = compilerObject.getProgram();
  17704. if (program == null || program.getSourceFile(filePath) == null)
  17705. return { emitSkipped: true, outputFiles: [], diagnostics: [] };
  17706. return compilerObject.getEmitOutput(filePath, emitOnlyDtsFiles);
  17707. }
  17708. }
  17709. getIdentationAtPosition(filePathOrSourceFile, position, settings) {
  17710. const filePath = this.#getFilePathFromFilePathOrSourceFile(filePathOrSourceFile);
  17711. if (settings == null)
  17712. settings = this.#context.manipulationSettings.getEditorSettings();
  17713. else
  17714. fillDefaultEditorSettings(settings, this.#context.manipulationSettings);
  17715. return this.compilerObject.getIndentationAtPosition(filePath, position, settings);
  17716. }
  17717. organizeImports(filePathOrSourceFile, formatSettings = {}, userPreferences = {}) {
  17718. const scope = {
  17719. type: "file",
  17720. fileName: this.#getFilePathFromFilePathOrSourceFile(filePathOrSourceFile),
  17721. };
  17722. return this.compilerObject.organizeImports(scope, this.#getFilledSettings(formatSettings), this.#getFilledUserPreferences(userPreferences))
  17723. .map(fileTextChanges => new FileTextChanges(this.#context, fileTextChanges));
  17724. }
  17725. getEditsForRefactor(filePathOrSourceFile, formatSettings, positionOrRange, refactorName, actionName, preferences = {}) {
  17726. const filePath = this.#getFilePathFromFilePathOrSourceFile(filePathOrSourceFile);
  17727. const position = typeof positionOrRange === "number" ? positionOrRange : { pos: positionOrRange.getPos(), end: positionOrRange.getEnd() };
  17728. const compilerObject = this.compilerObject.getEditsForRefactor(filePath, this.#getFilledSettings(formatSettings), position, refactorName, actionName, this.#getFilledUserPreferences(preferences));
  17729. return compilerObject != null ? new RefactorEditInfo(this.#context, compilerObject) : undefined;
  17730. }
  17731. getCombinedCodeFix(filePathOrSourceFile, fixId, formatSettings = {}, preferences = {}) {
  17732. const compilerResult = this.compilerObject.getCombinedCodeFix({
  17733. type: "file",
  17734. fileName: this.#getFilePathFromFilePathOrSourceFile(filePathOrSourceFile),
  17735. }, fixId, this.#getFilledSettings(formatSettings), this.#getFilledUserPreferences(preferences || {}));
  17736. return new CombinedCodeActions(this.#context, compilerResult);
  17737. }
  17738. getCodeFixesAtPosition(filePathOrSourceFile, start, end, errorCodes, formatOptions = {}, preferences = {}) {
  17739. const filePath = this.#getFilePathFromFilePathOrSourceFile(filePathOrSourceFile);
  17740. const compilerResult = this.compilerObject.getCodeFixesAtPosition(filePath, start, end, errorCodes, this.#getFilledSettings(formatOptions), this.#getFilledUserPreferences(preferences || {}));
  17741. return compilerResult.map(compilerObject => new CodeFixAction(this.#context, compilerObject));
  17742. }
  17743. #getFilePathFromFilePathOrSourceFile(filePathOrSourceFile) {
  17744. const filePath = typeof filePathOrSourceFile === "string"
  17745. ? this.#context.fileSystemWrapper.getStandardizedAbsolutePath(filePathOrSourceFile)
  17746. : filePathOrSourceFile.getFilePath();
  17747. if (!this.#context.compilerFactory.containsSourceFileAtPath(filePath))
  17748. throw new common.errors.FileNotFoundError(filePath);
  17749. return filePath;
  17750. }
  17751. #getFilledSettings(settings) {
  17752. if (settings["_filled"])
  17753. return settings;
  17754. settings = Object.assign(this.#context.getFormatCodeSettings(), settings);
  17755. fillDefaultFormatCodeSettings(settings, this.#context.manipulationSettings);
  17756. settings["_filled"] = true;
  17757. return settings;
  17758. }
  17759. #getFilledUserPreferences(userPreferences) {
  17760. return Object.assign(this.#context.getUserPreferences(), userPreferences);
  17761. }
  17762. }
  17763. class Type {
  17764. _context;
  17765. #compilerType;
  17766. get compilerType() {
  17767. return this.#compilerType;
  17768. }
  17769. constructor(context, type) {
  17770. this._context = context;
  17771. this.#compilerType = type;
  17772. }
  17773. getText(enclosingNode, typeFormatFlags) {
  17774. return this._context.typeChecker.getTypeText(this, enclosingNode, typeFormatFlags);
  17775. }
  17776. getAliasSymbol() {
  17777. return this.compilerType.aliasSymbol == null ? undefined : this._context.compilerFactory.getSymbol(this.compilerType.aliasSymbol);
  17778. }
  17779. getAliasSymbolOrThrow(message) {
  17780. return common.errors.throwIfNullOrUndefined(this.getAliasSymbol(), "Expected to find an alias symbol.");
  17781. }
  17782. getAliasTypeArguments() {
  17783. const aliasTypeArgs = this.compilerType.aliasTypeArguments || [];
  17784. return aliasTypeArgs.map(t => this._context.compilerFactory.getType(t));
  17785. }
  17786. getApparentType() {
  17787. return this._context.typeChecker.getApparentType(this);
  17788. }
  17789. getArrayElementTypeOrThrow(message) {
  17790. return common.errors.throwIfNullOrUndefined(this.getArrayElementType(), message ?? "Expected to find an array element type.");
  17791. }
  17792. getArrayElementType() {
  17793. if (!this.isArray())
  17794. return undefined;
  17795. return this.getTypeArguments()[0];
  17796. }
  17797. getBaseTypes() {
  17798. const baseTypes = this.compilerType.getBaseTypes() || [];
  17799. return baseTypes.map(t => this._context.compilerFactory.getType(t));
  17800. }
  17801. getBaseTypeOfLiteralType() {
  17802. return this._context.typeChecker.getBaseTypeOfLiteralType(this);
  17803. }
  17804. getCallSignatures() {
  17805. return this.compilerType.getCallSignatures().map(s => this._context.compilerFactory.getSignature(s));
  17806. }
  17807. getConstructSignatures() {
  17808. return this.compilerType.getConstructSignatures().map(s => this._context.compilerFactory.getSignature(s));
  17809. }
  17810. getConstraintOrThrow(message) {
  17811. return common.errors.throwIfNullOrUndefined(this.getConstraint(), message ?? "Expected to find a constraint.");
  17812. }
  17813. getConstraint() {
  17814. const constraint = this.compilerType.getConstraint();
  17815. return constraint == null ? undefined : this._context.compilerFactory.getType(constraint);
  17816. }
  17817. getDefaultOrThrow(message) {
  17818. return common.errors.throwIfNullOrUndefined(this.getDefault(), message ?? "Expected to find a default type.");
  17819. }
  17820. getDefault() {
  17821. const defaultType = this.compilerType.getDefault();
  17822. return defaultType == null ? undefined : this._context.compilerFactory.getType(defaultType);
  17823. }
  17824. getProperties() {
  17825. return this.compilerType.getProperties().map(s => this._context.compilerFactory.getSymbol(s));
  17826. }
  17827. getPropertyOrThrow(nameOrFindFunction) {
  17828. return common.errors.throwIfNullOrUndefined(this.getProperty(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("symbol property", nameOrFindFunction));
  17829. }
  17830. getProperty(nameOrFindFunction) {
  17831. return getSymbolByNameOrFindFunction(this.getProperties(), nameOrFindFunction);
  17832. }
  17833. getApparentProperties() {
  17834. return this.compilerType.getApparentProperties().map(s => this._context.compilerFactory.getSymbol(s));
  17835. }
  17836. getApparentProperty(nameOrFindFunction) {
  17837. return getSymbolByNameOrFindFunction(this.getApparentProperties(), nameOrFindFunction);
  17838. }
  17839. isNullable() {
  17840. return this.getUnionTypes().some(t => t.isNull() || t.isUndefined());
  17841. }
  17842. getNonNullableType() {
  17843. return this._context.compilerFactory.getType(this.compilerType.getNonNullableType());
  17844. }
  17845. getNumberIndexType() {
  17846. const numberIndexType = this.compilerType.getNumberIndexType();
  17847. return numberIndexType == null ? undefined : this._context.compilerFactory.getType(numberIndexType);
  17848. }
  17849. getStringIndexType() {
  17850. const stringIndexType = this.compilerType.getStringIndexType();
  17851. return stringIndexType == null ? undefined : this._context.compilerFactory.getType(stringIndexType);
  17852. }
  17853. getTargetType() {
  17854. const targetType = this.compilerType.target || undefined;
  17855. return targetType == null ? undefined : this._context.compilerFactory.getType(targetType);
  17856. }
  17857. getTargetTypeOrThrow(message) {
  17858. return common.errors.throwIfNullOrUndefined(this.getTargetType(), message ?? "Expected to find the target type.");
  17859. }
  17860. getTypeArguments() {
  17861. return this._context.typeChecker.getTypeArguments(this);
  17862. }
  17863. getTupleElements() {
  17864. return this.isTuple() ? this.getTypeArguments() : [];
  17865. }
  17866. getUnionTypes() {
  17867. if (!this.isUnion())
  17868. return [];
  17869. return this.compilerType.types.map(t => this._context.compilerFactory.getType(t));
  17870. }
  17871. getIntersectionTypes() {
  17872. if (!this.isIntersection())
  17873. return [];
  17874. return this.compilerType.types.map(t => this._context.compilerFactory.getType(t));
  17875. }
  17876. getLiteralValue() {
  17877. return this.compilerType?.value;
  17878. }
  17879. getLiteralValueOrThrow(message) {
  17880. return common.errors.throwIfNullOrUndefined(this.getLiteralValue(), message ?? "Type was not a literal type.");
  17881. }
  17882. getLiteralFreshType() {
  17883. const type = this.compilerType?.freshType;
  17884. return type == null ? undefined : this._context.compilerFactory.getType(type);
  17885. }
  17886. getLiteralFreshTypeOrThrow(message) {
  17887. return common.errors.throwIfNullOrUndefined(this.getLiteralFreshType(), message ?? "Type was not a literal type.");
  17888. }
  17889. getLiteralRegularType() {
  17890. const type = this.compilerType?.regularType;
  17891. return type == null ? undefined : this._context.compilerFactory.getType(type);
  17892. }
  17893. getLiteralRegularTypeOrThrow(message) {
  17894. return common.errors.throwIfNullOrUndefined(this.getLiteralRegularType(), message ?? "Type was not a literal type.");
  17895. }
  17896. getSymbol() {
  17897. const tsSymbol = this.compilerType.getSymbol();
  17898. return tsSymbol == null ? undefined : this._context.compilerFactory.getSymbol(tsSymbol);
  17899. }
  17900. getSymbolOrThrow(message) {
  17901. return common.errors.throwIfNullOrUndefined(this.getSymbol(), message ?? "Expected to find a symbol.");
  17902. }
  17903. isAssignableTo(target) {
  17904. return this._context.typeChecker.isTypeAssignableTo(this, target);
  17905. }
  17906. isAnonymous() {
  17907. return this.#hasObjectFlag(common.ObjectFlags.Anonymous);
  17908. }
  17909. isAny() {
  17910. return this.#hasTypeFlag(common.TypeFlags.Any);
  17911. }
  17912. isNever() {
  17913. return this.#hasTypeFlag(common.TypeFlags.Never);
  17914. }
  17915. isArray() {
  17916. const symbol = this.getSymbol();
  17917. if (symbol == null)
  17918. return false;
  17919. return (symbol.getName() === "Array" || symbol.getName() === "ReadonlyArray") && this.getTypeArguments().length === 1;
  17920. }
  17921. isReadonlyArray() {
  17922. const symbol = this.getSymbol();
  17923. if (symbol == null)
  17924. return false;
  17925. return symbol.getName() === "ReadonlyArray" && this.getTypeArguments().length === 1;
  17926. }
  17927. isTemplateLiteral() {
  17928. return this.#hasTypeFlag(common.TypeFlags.TemplateLiteral);
  17929. }
  17930. isBoolean() {
  17931. return this.#hasTypeFlag(common.TypeFlags.Boolean);
  17932. }
  17933. isString() {
  17934. return this.#hasTypeFlag(common.TypeFlags.String);
  17935. }
  17936. isNumber() {
  17937. return this.#hasTypeFlag(common.TypeFlags.Number);
  17938. }
  17939. isBigInt() {
  17940. return this.#hasTypeFlag(common.TypeFlags.BigInt);
  17941. }
  17942. isLiteral() {
  17943. const isBooleanLiteralForTs3_0 = this.isBooleanLiteral();
  17944. return this.compilerType.isLiteral() || isBooleanLiteralForTs3_0;
  17945. }
  17946. isBooleanLiteral() {
  17947. return this.#hasTypeFlag(common.TypeFlags.BooleanLiteral);
  17948. }
  17949. isBigIntLiteral() {
  17950. return this.#hasTypeFlag(common.TypeFlags.BigIntLiteral);
  17951. }
  17952. isEnumLiteral() {
  17953. return this.#hasTypeFlag(common.TypeFlags.EnumLiteral) && !this.isUnion();
  17954. }
  17955. isNumberLiteral() {
  17956. return this.#hasTypeFlag(common.TypeFlags.NumberLiteral);
  17957. }
  17958. isStringLiteral() {
  17959. return this.compilerType.isStringLiteral();
  17960. }
  17961. isClass() {
  17962. return this.compilerType.isClass();
  17963. }
  17964. isClassOrInterface() {
  17965. return this.compilerType.isClassOrInterface();
  17966. }
  17967. isEnum() {
  17968. const hasEnumFlag = this.#hasTypeFlag(common.TypeFlags.Enum);
  17969. if (hasEnumFlag)
  17970. return true;
  17971. if (this.isEnumLiteral() && !this.isUnion())
  17972. return false;
  17973. const symbol = this.getSymbol();
  17974. if (symbol == null)
  17975. return false;
  17976. const valueDeclaration = symbol.getValueDeclaration();
  17977. return valueDeclaration != null && Node.isEnumDeclaration(valueDeclaration);
  17978. }
  17979. isInterface() {
  17980. return this.#hasObjectFlag(common.ObjectFlags.Interface);
  17981. }
  17982. isObject() {
  17983. return this.#hasTypeFlag(common.TypeFlags.Object);
  17984. }
  17985. isTypeParameter() {
  17986. return this.compilerType.isTypeParameter();
  17987. }
  17988. isTuple() {
  17989. const targetType = this.getTargetType();
  17990. if (targetType == null)
  17991. return false;
  17992. return targetType.#hasObjectFlag(common.ObjectFlags.Tuple);
  17993. }
  17994. isUnion() {
  17995. return this.compilerType.isUnion();
  17996. }
  17997. isIntersection() {
  17998. return this.compilerType.isIntersection();
  17999. }
  18000. isUnionOrIntersection() {
  18001. return this.compilerType.isUnionOrIntersection();
  18002. }
  18003. isUnknown() {
  18004. return this.#hasTypeFlag(common.TypeFlags.Unknown);
  18005. }
  18006. isNull() {
  18007. return this.#hasTypeFlag(common.TypeFlags.Null);
  18008. }
  18009. isUndefined() {
  18010. return this.#hasTypeFlag(common.TypeFlags.Undefined);
  18011. }
  18012. isVoid() {
  18013. return this.#hasTypeFlag(common.TypeFlags.Void);
  18014. }
  18015. getFlags() {
  18016. return this.compilerType.flags;
  18017. }
  18018. getObjectFlags() {
  18019. if (!this.isObject())
  18020. return 0;
  18021. return this.compilerType.objectFlags || 0;
  18022. }
  18023. #hasTypeFlag(flag) {
  18024. return (this.compilerType.flags & flag) === flag;
  18025. }
  18026. #hasObjectFlag(flag) {
  18027. return (this.getObjectFlags() & flag) === flag;
  18028. }
  18029. }
  18030. class TypeParameter extends Type {
  18031. getConstraintOrThrow(message) {
  18032. return common.errors.throwIfNullOrUndefined(this.getConstraint(), message ?? "Expected type parameter to have a constraint.");
  18033. }
  18034. getConstraint() {
  18035. const declaration = this.#getTypeParameterDeclaration();
  18036. if (declaration == null)
  18037. return undefined;
  18038. const constraintNode = declaration.getConstraint();
  18039. if (constraintNode == null)
  18040. return undefined;
  18041. return this._context.typeChecker.getTypeAtLocation(constraintNode);
  18042. }
  18043. getDefaultOrThrow(message) {
  18044. return common.errors.throwIfNullOrUndefined(this.getDefault(), message ?? "Expected type parameter to have a default type.");
  18045. }
  18046. getDefault() {
  18047. const declaration = this.#getTypeParameterDeclaration();
  18048. if (declaration == null)
  18049. return undefined;
  18050. const defaultNode = declaration.getDefault();
  18051. if (defaultNode == null)
  18052. return undefined;
  18053. return this._context.typeChecker.getTypeAtLocation(defaultNode);
  18054. }
  18055. #getTypeParameterDeclaration() {
  18056. const symbol = this.getSymbol();
  18057. if (symbol == null)
  18058. return undefined;
  18059. const declaration = symbol.getDeclarations()[0];
  18060. if (declaration == null)
  18061. return undefined;
  18062. if (!Node.isTypeParameterDeclaration(declaration))
  18063. return undefined;
  18064. return declaration;
  18065. }
  18066. }
  18067. class DirectoryEmitResult {
  18068. #outputFilePaths;
  18069. #skippedFilePaths;
  18070. constructor(skippedFilePaths, outputFilePaths) {
  18071. this.#skippedFilePaths = skippedFilePaths;
  18072. this.#outputFilePaths = outputFilePaths;
  18073. }
  18074. getSkippedFilePaths() {
  18075. return this.#skippedFilePaths;
  18076. }
  18077. getOutputFilePaths() {
  18078. return this.#outputFilePaths;
  18079. }
  18080. }
  18081. class Directory {
  18082. #context;
  18083. #path;
  18084. #pathParts;
  18085. constructor(context, path) {
  18086. this.#context = context;
  18087. this._setPathInternal(path);
  18088. }
  18089. _setPathInternal(path) {
  18090. this.#path = path;
  18091. this.#pathParts = path.split("/").filter(p => p.length > 0);
  18092. }
  18093. get _context() {
  18094. this.#throwIfDeletedOrRemoved();
  18095. return this.#context;
  18096. }
  18097. isAncestorOf(possibleDescendant) {
  18098. return Directory.#isAncestorOfDir(this, possibleDescendant);
  18099. }
  18100. isDescendantOf(possibleAncestor) {
  18101. return Directory.#isAncestorOfDir(possibleAncestor, this);
  18102. }
  18103. _getDepth() {
  18104. return this.#pathParts.length;
  18105. }
  18106. getPath() {
  18107. this.#throwIfDeletedOrRemoved();
  18108. return this.#path;
  18109. }
  18110. getBaseName() {
  18111. return this.#pathParts[this.#pathParts.length - 1];
  18112. }
  18113. getParentOrThrow(message) {
  18114. return common.errors.throwIfNullOrUndefined(this.getParent(), message ?? (() => `Parent directory of ${this.getPath()} does not exist or was never added.`));
  18115. }
  18116. getParent() {
  18117. if (common.FileUtils.isRootDirPath(this.getPath()))
  18118. return undefined;
  18119. return this.addDirectoryAtPathIfExists(common.FileUtils.getDirPath(this.getPath()));
  18120. }
  18121. getDirectoryOrThrow(pathOrCondition) {
  18122. return common.errors.throwIfNullOrUndefined(this.getDirectory(pathOrCondition), () => {
  18123. if (typeof pathOrCondition === "string")
  18124. return `Could not find a directory at path '${this._context.fileSystemWrapper.getStandardizedAbsolutePath(pathOrCondition, this.getPath())}'.`;
  18125. return "Could not find child directory that matched condition.";
  18126. });
  18127. }
  18128. getDirectory(pathOrCondition) {
  18129. if (typeof pathOrCondition === "string") {
  18130. const path = this._context.fileSystemWrapper.getStandardizedAbsolutePath(pathOrCondition, this.getPath());
  18131. return this._context.compilerFactory.getDirectoryFromCache(path);
  18132. }
  18133. return this.getDirectories().find(pathOrCondition);
  18134. }
  18135. getSourceFileOrThrow(pathOrCondition) {
  18136. return common.errors.throwIfNullOrUndefined(this.getSourceFile(pathOrCondition), () => {
  18137. if (typeof pathOrCondition === "string") {
  18138. const absolutePath = this._context.fileSystemWrapper.getStandardizedAbsolutePath(pathOrCondition, this.getPath());
  18139. return `Could not find child source file at path '${absolutePath}'.`;
  18140. }
  18141. return "Could not find child source file that matched condition.";
  18142. });
  18143. }
  18144. getSourceFile(pathOrCondition) {
  18145. if (typeof pathOrCondition === "string") {
  18146. const path = this._context.fileSystemWrapper.getStandardizedAbsolutePath(pathOrCondition, this.getPath());
  18147. return this._context.compilerFactory.getSourceFileFromCacheFromFilePath(path);
  18148. }
  18149. for (const sourceFile of this._getSourceFilesIterator()) {
  18150. if (pathOrCondition(sourceFile))
  18151. return sourceFile;
  18152. }
  18153. return undefined;
  18154. }
  18155. getDirectories() {
  18156. return Array.from(this._getDirectoriesIterator());
  18157. }
  18158. _getDirectoriesIterator() {
  18159. return this._context.compilerFactory.getChildDirectoriesOfDirectory(this.getPath());
  18160. }
  18161. getSourceFiles(globPatterns) {
  18162. const { compilerFactory, fileSystemWrapper } = this._context;
  18163. const dir = this;
  18164. if (typeof globPatterns === "string" || globPatterns instanceof Array) {
  18165. const finalGlobPatterns = typeof globPatterns === "string" ? [globPatterns] : globPatterns;
  18166. return Array.from(getFilteredSourceFiles(finalGlobPatterns));
  18167. }
  18168. else {
  18169. return Array.from(this._getSourceFilesIterator());
  18170. }
  18171. function* getFilteredSourceFiles(globPatterns) {
  18172. const sourceFilePaths = Array.from(getSourceFilePaths());
  18173. const matchedPaths = common.matchGlobs(sourceFilePaths, globPatterns, dir.getPath());
  18174. for (const matchedPath of matchedPaths)
  18175. yield compilerFactory.getSourceFileFromCacheFromFilePath(fileSystemWrapper.getStandardizedAbsolutePath(matchedPath));
  18176. function* getSourceFilePaths() {
  18177. for (const sourceFile of dir._getDescendantSourceFilesIterator())
  18178. yield sourceFile.getFilePath();
  18179. }
  18180. }
  18181. }
  18182. _getSourceFilesIterator() {
  18183. return this._context.compilerFactory.getChildSourceFilesOfDirectory(this.getPath());
  18184. }
  18185. getDescendantSourceFiles() {
  18186. return Array.from(this._getDescendantSourceFilesIterator());
  18187. }
  18188. *_getDescendantSourceFilesIterator() {
  18189. for (const sourceFile of this._getSourceFilesIterator())
  18190. yield sourceFile;
  18191. for (const directory of this._getDirectoriesIterator())
  18192. yield* directory._getDescendantSourceFilesIterator();
  18193. }
  18194. getDescendantDirectories() {
  18195. return Array.from(this._getDescendantDirectoriesIterator());
  18196. }
  18197. *_getDescendantDirectoriesIterator() {
  18198. for (const directory of this.getDirectories()) {
  18199. yield directory;
  18200. yield* directory._getDescendantDirectoriesIterator();
  18201. }
  18202. }
  18203. addSourceFilesAtPaths(fileGlobs) {
  18204. fileGlobs = typeof fileGlobs === "string" ? [fileGlobs] : fileGlobs;
  18205. fileGlobs = fileGlobs.map(g => {
  18206. if (common.FileUtils.pathIsAbsolute(g))
  18207. return g;
  18208. return common.FileUtils.pathJoin(this.getPath(), g);
  18209. });
  18210. return this._context.directoryCoordinator.addSourceFilesAtPaths(fileGlobs, { markInProject: this._isInProject() });
  18211. }
  18212. addDirectoryAtPathIfExists(relativeOrAbsoluteDirPath, options = {}) {
  18213. const dirPath = this._context.fileSystemWrapper.getStandardizedAbsolutePath(relativeOrAbsoluteDirPath, this.getPath());
  18214. return this._context.directoryCoordinator.addDirectoryAtPathIfExists(dirPath, { ...options, markInProject: this._isInProject() });
  18215. }
  18216. addDirectoryAtPath(relativeOrAbsoluteDirPath, options = {}) {
  18217. const dirPath = this._context.fileSystemWrapper.getStandardizedAbsolutePath(relativeOrAbsoluteDirPath, this.getPath());
  18218. return this._context.directoryCoordinator.addDirectoryAtPath(dirPath, { ...options, markInProject: this._isInProject() });
  18219. }
  18220. createDirectory(relativeOrAbsoluteDirPath) {
  18221. const dirPath = this._context.fileSystemWrapper.getStandardizedAbsolutePath(relativeOrAbsoluteDirPath, this.getPath());
  18222. return this._context.directoryCoordinator.createDirectoryOrAddIfExists(dirPath, { markInProject: this._isInProject() });
  18223. }
  18224. createSourceFile(relativeFilePath, sourceFileText, options) {
  18225. const filePath = this._context.fileSystemWrapper.getStandardizedAbsolutePath(relativeFilePath, this.getPath());
  18226. return this._context.compilerFactory.createSourceFile(filePath, sourceFileText || "", { ...(options || {}), markInProject: this._isInProject() });
  18227. }
  18228. addSourceFileAtPathIfExists(relativeFilePath) {
  18229. const filePath = this._context.fileSystemWrapper.getStandardizedAbsolutePath(relativeFilePath, this.getPath());
  18230. return this._context.directoryCoordinator.addSourceFileAtPathIfExists(filePath, { markInProject: this._isInProject() });
  18231. }
  18232. addSourceFileAtPath(relativeFilePath) {
  18233. const filePath = this._context.fileSystemWrapper.getStandardizedAbsolutePath(relativeFilePath, this.getPath());
  18234. return this._context.directoryCoordinator.addSourceFileAtPath(filePath, { markInProject: this._isInProject() });
  18235. }
  18236. async emit(options = {}) {
  18237. const { fileSystemWrapper } = this._context;
  18238. const writeTasks = [];
  18239. const outputFilePaths = [];
  18240. const skippedFilePaths = [];
  18241. for (const emitResult of this.#emitInternal(options)) {
  18242. if (isStandardizedFilePath(emitResult))
  18243. skippedFilePaths.push(emitResult);
  18244. else {
  18245. writeTasks.push(fileSystemWrapper.writeFile(emitResult.filePath, emitResult.fileText));
  18246. outputFilePaths.push(emitResult.filePath);
  18247. }
  18248. }
  18249. await Promise.all(writeTasks);
  18250. return new DirectoryEmitResult(skippedFilePaths, outputFilePaths);
  18251. }
  18252. emitSync(options = {}) {
  18253. const { fileSystemWrapper } = this._context;
  18254. const outputFilePaths = [];
  18255. const skippedFilePaths = [];
  18256. for (const emitResult of this.#emitInternal(options)) {
  18257. if (isStandardizedFilePath(emitResult))
  18258. skippedFilePaths.push(emitResult);
  18259. else {
  18260. fileSystemWrapper.writeFileSync(emitResult.filePath, emitResult.fileText);
  18261. outputFilePaths.push(emitResult.filePath);
  18262. }
  18263. }
  18264. return new DirectoryEmitResult(skippedFilePaths, outputFilePaths);
  18265. }
  18266. #emitInternal(options = {}) {
  18267. const { emitOnlyDtsFiles = false } = options;
  18268. const isJsFile = options.outDir == null ? undefined : /\.js$/i;
  18269. const isMapFile = options.outDir == null ? undefined : /\.js\.map$/i;
  18270. const isDtsFile = options.declarationDir == null && options.outDir == null ? undefined : /\.d\.ts$/i;
  18271. const getStandardizedPath = (path) => path == null
  18272. ? undefined
  18273. : this._context.fileSystemWrapper.getStandardizedAbsolutePath(path, this.getPath());
  18274. const getSubDirPath = (path, dir) => path == null
  18275. ? undefined
  18276. : common.FileUtils.pathJoin(path, dir.getBaseName());
  18277. const hasDeclarationDir = this._context.compilerOptions.get().declarationDir != null || options.declarationDir != null;
  18278. return emitDirectory(this, getStandardizedPath(options.outDir), getStandardizedPath(options.declarationDir));
  18279. function* emitDirectory(directory, outDir, declarationDir) {
  18280. for (const sourceFile of directory.getSourceFiles()) {
  18281. const output = sourceFile.getEmitOutput({ emitOnlyDtsFiles });
  18282. if (output.getEmitSkipped()) {
  18283. yield sourceFile.getFilePath();
  18284. continue;
  18285. }
  18286. for (const outputFile of output.getOutputFiles()) {
  18287. let filePath = outputFile.getFilePath();
  18288. const fileText = outputFile.getWriteByteOrderMark() ? common.FileUtils.getTextWithByteOrderMark(outputFile.getText()) : outputFile.getText();
  18289. if (outDir != null && (isJsFile.test(filePath) || isMapFile.test(filePath) || (!hasDeclarationDir && isDtsFile.test(filePath))))
  18290. filePath = common.FileUtils.pathJoin(outDir, common.FileUtils.getBaseName(filePath));
  18291. else if (declarationDir != null && isDtsFile.test(filePath))
  18292. filePath = common.FileUtils.pathJoin(declarationDir, common.FileUtils.getBaseName(filePath));
  18293. yield { filePath, fileText };
  18294. }
  18295. }
  18296. for (const dir of directory.getDirectories())
  18297. yield* emitDirectory(dir, getSubDirPath(outDir, dir), getSubDirPath(declarationDir, dir));
  18298. }
  18299. }
  18300. copyToDirectory(dirPathOrDirectory, options) {
  18301. const dirPath = typeof dirPathOrDirectory === "string" ? dirPathOrDirectory : dirPathOrDirectory.getPath();
  18302. return this.copy(common.FileUtils.pathJoin(dirPath, this.getBaseName()), options);
  18303. }
  18304. copy(relativeOrAbsolutePath, options) {
  18305. const originalPath = this.getPath();
  18306. const fileSystem = this._context.fileSystemWrapper;
  18307. const newPath = this._context.fileSystemWrapper.getStandardizedAbsolutePath(relativeOrAbsolutePath, this.getPath());
  18308. if (originalPath === newPath)
  18309. return this;
  18310. options = getDirectoryCopyOptions(options);
  18311. if (options.includeUntrackedFiles)
  18312. fileSystem.queueCopyDirectory(originalPath, newPath);
  18313. return this.#copyInternal(newPath, options);
  18314. }
  18315. async copyImmediately(relativeOrAbsolutePath, options) {
  18316. const fileSystem = this._context.fileSystemWrapper;
  18317. const originalPath = this.getPath();
  18318. const newPath = fileSystem.getStandardizedAbsolutePath(relativeOrAbsolutePath, originalPath);
  18319. if (originalPath === newPath) {
  18320. await this.save();
  18321. return this;
  18322. }
  18323. options = getDirectoryCopyOptions(options);
  18324. const newDir = this.#copyInternal(newPath, options);
  18325. if (options.includeUntrackedFiles)
  18326. await fileSystem.copyDirectoryImmediately(originalPath, newPath);
  18327. await newDir.save();
  18328. return newDir;
  18329. }
  18330. copyImmediatelySync(relativeOrAbsolutePath, options) {
  18331. const fileSystem = this._context.fileSystemWrapper;
  18332. const originalPath = this.getPath();
  18333. const newPath = fileSystem.getStandardizedAbsolutePath(relativeOrAbsolutePath, originalPath);
  18334. if (originalPath === newPath) {
  18335. this.saveSync();
  18336. return this;
  18337. }
  18338. options = getDirectoryCopyOptions(options);
  18339. const newDir = this.#copyInternal(newPath, options);
  18340. if (options.includeUntrackedFiles)
  18341. fileSystem.copyDirectoryImmediatelySync(originalPath, newPath);
  18342. newDir.saveSync();
  18343. return newDir;
  18344. }
  18345. #copyInternal(newPath, options) {
  18346. const originalPath = this.getPath();
  18347. if (originalPath === newPath)
  18348. return this;
  18349. const { fileSystemWrapper: fileSystem, compilerFactory } = this._context;
  18350. const copyingDirectories = [this, ...this.getDescendantDirectories()].map(directory => ({
  18351. newDirPath: directory === this ? newPath : fileSystem.getStandardizedAbsolutePath(this.getRelativePathTo(directory), newPath),
  18352. }));
  18353. const copyingSourceFiles = this.getDescendantSourceFiles().map(sourceFile => ({
  18354. sourceFile,
  18355. newFilePath: fileSystem.getStandardizedAbsolutePath(this.getRelativePathTo(sourceFile), newPath),
  18356. references: this.#getReferencesForCopy(sourceFile),
  18357. }));
  18358. for (const { newDirPath } of copyingDirectories)
  18359. this._context.compilerFactory.createDirectoryOrAddIfExists(newDirPath, { markInProject: this._isInProject() });
  18360. for (const { sourceFile, newFilePath } of copyingSourceFiles)
  18361. sourceFile._copyInternal(newFilePath, options);
  18362. for (const { references, newFilePath } of copyingSourceFiles)
  18363. this.getSourceFileOrThrow(newFilePath)._updateReferencesForCopyInternal(references);
  18364. return compilerFactory.getDirectoryFromCache(newPath);
  18365. }
  18366. moveToDirectory(dirPathOrDirectory, options) {
  18367. const dirPath = typeof dirPathOrDirectory === "string" ? dirPathOrDirectory : dirPathOrDirectory.getPath();
  18368. return this.move(common.FileUtils.pathJoin(dirPath, this.getBaseName()), options);
  18369. }
  18370. move(relativeOrAbsolutePath, options) {
  18371. const fileSystem = this._context.fileSystemWrapper;
  18372. const originalPath = this.getPath();
  18373. const newPath = fileSystem.getStandardizedAbsolutePath(relativeOrAbsolutePath, originalPath);
  18374. if (originalPath === newPath)
  18375. return this;
  18376. return this.#moveInternal(newPath, options, () => fileSystem.queueMoveDirectory(originalPath, newPath));
  18377. }
  18378. async moveImmediately(relativeOrAbsolutePath, options) {
  18379. const fileSystem = this._context.fileSystemWrapper;
  18380. const originalPath = this.getPath();
  18381. const newPath = fileSystem.getStandardizedAbsolutePath(relativeOrAbsolutePath, originalPath);
  18382. if (originalPath === newPath) {
  18383. await this.save();
  18384. return this;
  18385. }
  18386. this.#moveInternal(newPath, options);
  18387. await fileSystem.moveDirectoryImmediately(originalPath, newPath);
  18388. await this.save();
  18389. return this;
  18390. }
  18391. moveImmediatelySync(relativeOrAbsolutePath, options) {
  18392. const fileSystem = this._context.fileSystemWrapper;
  18393. const originalPath = this.getPath();
  18394. const newPath = fileSystem.getStandardizedAbsolutePath(relativeOrAbsolutePath, originalPath);
  18395. if (originalPath === newPath) {
  18396. this.saveSync();
  18397. return this;
  18398. }
  18399. this.#moveInternal(newPath, options);
  18400. fileSystem.moveDirectoryImmediatelySync(originalPath, newPath);
  18401. this.saveSync();
  18402. return this;
  18403. }
  18404. #moveInternal(newPath, options, preAction) {
  18405. const originalPath = this.getPath();
  18406. if (originalPath === newPath)
  18407. return this;
  18408. const existingDir = this._context.compilerFactory.getDirectoryFromCacheOnlyIfInCache(newPath);
  18409. const markInProject = existingDir != null && existingDir._isInProject();
  18410. if (preAction)
  18411. preAction();
  18412. const fileSystem = this._context.fileSystemWrapper;
  18413. const compilerFactory = this._context.compilerFactory;
  18414. const movingDirectories = [this, ...this.getDescendantDirectories()].map(directory => ({
  18415. directory,
  18416. oldPath: directory.getPath(),
  18417. newDirPath: directory === this ? newPath : fileSystem.getStandardizedAbsolutePath(this.getRelativePathTo(directory), newPath),
  18418. }));
  18419. const movingSourceFiles = this.getDescendantSourceFiles().map(sourceFile => ({
  18420. sourceFile,
  18421. newFilePath: fileSystem.getStandardizedAbsolutePath(this.getRelativePathTo(sourceFile), newPath),
  18422. references: this.#getReferencesForMove(sourceFile),
  18423. }));
  18424. for (const { directory, oldPath, newDirPath } of movingDirectories) {
  18425. compilerFactory.removeDirectoryFromCache(oldPath);
  18426. const dirToOverwrite = compilerFactory.getDirectoryFromCache(newDirPath);
  18427. if (dirToOverwrite != null)
  18428. dirToOverwrite._forgetOnlyThis();
  18429. directory._setPathInternal(newDirPath);
  18430. compilerFactory.addDirectoryToCache(directory);
  18431. }
  18432. for (const { sourceFile, newFilePath } of movingSourceFiles)
  18433. sourceFile._moveInternal(newFilePath, options);
  18434. for (const { sourceFile, references } of movingSourceFiles)
  18435. sourceFile._updateReferencesForMoveInternal(references, originalPath);
  18436. if (markInProject)
  18437. this._markAsInProject();
  18438. return this;
  18439. }
  18440. clear() {
  18441. const path = this.getPath();
  18442. this.#deleteDescendants();
  18443. this._context.fileSystemWrapper.queueDirectoryDelete(path);
  18444. this._context.fileSystemWrapper.queueMkdir(path);
  18445. }
  18446. async clearImmediately() {
  18447. const path = this.getPath();
  18448. this.#deleteDescendants();
  18449. await this._context.fileSystemWrapper.clearDirectoryImmediately(path);
  18450. }
  18451. clearImmediatelySync() {
  18452. const path = this.getPath();
  18453. this.#deleteDescendants();
  18454. this._context.fileSystemWrapper.clearDirectoryImmediatelySync(path);
  18455. }
  18456. delete() {
  18457. const path = this.getPath();
  18458. this.#deleteDescendants();
  18459. this._context.fileSystemWrapper.queueDirectoryDelete(path);
  18460. this.forget();
  18461. }
  18462. #deleteDescendants() {
  18463. for (const sourceFile of this.getSourceFiles())
  18464. sourceFile.delete();
  18465. for (const dir of this.getDirectories())
  18466. dir.delete();
  18467. }
  18468. async deleteImmediately() {
  18469. const { fileSystemWrapper } = this._context;
  18470. const path = this.getPath();
  18471. this.forget();
  18472. await fileSystemWrapper.deleteDirectoryImmediately(path);
  18473. }
  18474. deleteImmediatelySync() {
  18475. const { fileSystemWrapper } = this._context;
  18476. const path = this.getPath();
  18477. this.forget();
  18478. fileSystemWrapper.deleteDirectoryImmediatelySync(path);
  18479. }
  18480. forget() {
  18481. if (this.wasForgotten())
  18482. return;
  18483. for (const sourceFile of this.getSourceFiles())
  18484. sourceFile.forget();
  18485. for (const dir of this.getDirectories())
  18486. dir.forget();
  18487. this._forgetOnlyThis();
  18488. }
  18489. _forgetOnlyThis() {
  18490. if (this.wasForgotten())
  18491. return;
  18492. this._context.compilerFactory.removeDirectoryFromCache(this.getPath());
  18493. this.#context = undefined;
  18494. }
  18495. async save() {
  18496. await this._context.fileSystemWrapper.saveForDirectory(this.getPath());
  18497. const unsavedSourceFiles = this.getDescendantSourceFiles().filter(s => !s.isSaved());
  18498. await Promise.all(unsavedSourceFiles.map(s => s.save()));
  18499. }
  18500. saveSync() {
  18501. this._context.fileSystemWrapper.saveForDirectorySync(this.getPath());
  18502. const unsavedSourceFiles = this.getDescendantSourceFiles().filter(s => !s.isSaved());
  18503. unsavedSourceFiles.forEach(s => s.saveSync());
  18504. }
  18505. getRelativePathTo(sourceFileDirOrPath) {
  18506. const thisDirectory = this;
  18507. return common.FileUtils.getRelativePathTo(this.getPath(), getPath());
  18508. function getPath() {
  18509. return sourceFileDirOrPath instanceof SourceFile
  18510. ? sourceFileDirOrPath.getFilePath()
  18511. : sourceFileDirOrPath instanceof Directory
  18512. ? sourceFileDirOrPath.getPath()
  18513. : thisDirectory._context.fileSystemWrapper.getStandardizedAbsolutePath(sourceFileDirOrPath, thisDirectory.getPath());
  18514. }
  18515. }
  18516. getRelativePathAsModuleSpecifierTo(sourceFileDirOrFilePath) {
  18517. const moduleResolution = this._context.program.getEmitModuleResolutionKind();
  18518. const thisDirectory = this;
  18519. const moduleSpecifier = common.FileUtils.getRelativePathTo(this.getPath(), getPath()).replace(/((\.d\.ts$)|(\.[^/.]+$))/i, "");
  18520. return moduleSpecifier.startsWith("../") ? moduleSpecifier : "./" + moduleSpecifier;
  18521. function getPath() {
  18522. return sourceFileDirOrFilePath instanceof SourceFile
  18523. ? getPathForSourceFile(sourceFileDirOrFilePath)
  18524. : sourceFileDirOrFilePath instanceof Directory
  18525. ? getPathForDirectory(sourceFileDirOrFilePath)
  18526. : getPathForFilePath(thisDirectory._context.fileSystemWrapper.getStandardizedAbsolutePath(sourceFileDirOrFilePath, thisDirectory.getPath()));
  18527. function getPathForSourceFile(sourceFile) {
  18528. return getPathForFilePath(sourceFile.getFilePath());
  18529. }
  18530. function getPathForDirectory(dir) {
  18531. switch (moduleResolution) {
  18532. case common.ModuleResolutionKind.Node10:
  18533. if (dir === thisDirectory)
  18534. return common.FileUtils.pathJoin(dir.getPath(), "index.ts");
  18535. return dir.getPath();
  18536. case common.ModuleResolutionKind.Classic:
  18537. case common.ModuleResolutionKind.Node16:
  18538. case common.ModuleResolutionKind.NodeNext:
  18539. case common.ModuleResolutionKind.Bundler:
  18540. return common.FileUtils.pathJoin(dir.getPath(), "index.ts");
  18541. default:
  18542. return common.errors.throwNotImplementedForNeverValueError(moduleResolution);
  18543. }
  18544. }
  18545. function getPathForFilePath(filePath) {
  18546. const dirPath = common.FileUtils.getDirPath(filePath);
  18547. switch (moduleResolution) {
  18548. case common.ModuleResolutionKind.Node10:
  18549. if (dirPath === thisDirectory.getPath())
  18550. return filePath;
  18551. return filePath.replace(/\/index?(\.d\.ts|\.ts|\.js)$/i, "");
  18552. case common.ModuleResolutionKind.Classic:
  18553. case common.ModuleResolutionKind.Node16:
  18554. case common.ModuleResolutionKind.NodeNext:
  18555. case common.ModuleResolutionKind.Bundler:
  18556. return filePath;
  18557. default:
  18558. return common.errors.throwNotImplementedForNeverValueError(moduleResolution);
  18559. }
  18560. }
  18561. }
  18562. }
  18563. getProject() {
  18564. return this._context.project;
  18565. }
  18566. wasForgotten() {
  18567. return this.#context == null;
  18568. }
  18569. _isInProject() {
  18570. return this._context.inProjectCoordinator.isDirectoryInProject(this);
  18571. }
  18572. _markAsInProject() {
  18573. this._context.inProjectCoordinator.markDirectoryAsInProject(this);
  18574. }
  18575. _hasLoadedParent() {
  18576. return this._context.compilerFactory.containsDirectoryAtPath(common.FileUtils.getDirPath(this.getPath()));
  18577. }
  18578. #throwIfDeletedOrRemoved() {
  18579. if (this.wasForgotten())
  18580. throw new common.errors.InvalidOperationError("Cannot use a directory that was deleted, removed, or overwritten.");
  18581. }
  18582. #getReferencesForCopy(sourceFile) {
  18583. const literalReferences = sourceFile._getReferencesForCopyInternal();
  18584. return literalReferences.filter(r => !this.isAncestorOf(r[1]));
  18585. }
  18586. #getReferencesForMove(sourceFile) {
  18587. const { literalReferences, referencingLiterals } = sourceFile._getReferencesForMoveInternal();
  18588. return {
  18589. literalReferences: literalReferences.filter(r => !this.isAncestorOf(r[1])),
  18590. referencingLiterals: referencingLiterals.filter(l => !this.isAncestorOf(l._sourceFile)),
  18591. };
  18592. }
  18593. static #isAncestorOfDir(ancestor, descendant) {
  18594. if (descendant instanceof SourceFile) {
  18595. descendant = descendant.getDirectory();
  18596. if (ancestor === descendant)
  18597. return true;
  18598. }
  18599. if (ancestor.#pathParts.length >= descendant.#pathParts.length)
  18600. return false;
  18601. for (let i = ancestor.#pathParts.length - 1; i >= 0; i--) {
  18602. if (ancestor.#pathParts[i] !== descendant.#pathParts[i])
  18603. return false;
  18604. }
  18605. return true;
  18606. }
  18607. }
  18608. function getDirectoryCopyOptions(options) {
  18609. options = common.ObjectUtils.clone(options || {});
  18610. setValueIfUndefined(options, "includeUntrackedFiles", true);
  18611. return options;
  18612. }
  18613. function isStandardizedFilePath(filePath) {
  18614. return typeof filePath === "string";
  18615. }
  18616. class DirectoryCoordinator {
  18617. #fileSystemWrapper;
  18618. #compilerFactory;
  18619. constructor(compilerFactory, fileSystemWrapper) {
  18620. this.#compilerFactory = compilerFactory;
  18621. this.#fileSystemWrapper = fileSystemWrapper;
  18622. }
  18623. addDirectoryAtPathIfExists(dirPath, options) {
  18624. const directory = this.#compilerFactory.getDirectoryFromPath(dirPath, options);
  18625. if (directory == null)
  18626. return undefined;
  18627. if (options.recursive) {
  18628. for (const descendantDirPath of common.FileUtils.getDescendantDirectories(this.#fileSystemWrapper, dirPath))
  18629. this.#compilerFactory.createDirectoryOrAddIfExists(descendantDirPath, options);
  18630. }
  18631. return directory;
  18632. }
  18633. addDirectoryAtPath(dirPath, options) {
  18634. const directory = this.addDirectoryAtPathIfExists(dirPath, options);
  18635. if (directory == null)
  18636. throw new common.errors.DirectoryNotFoundError(dirPath);
  18637. return directory;
  18638. }
  18639. createDirectoryOrAddIfExists(dirPath, options) {
  18640. return this.#compilerFactory.createDirectoryOrAddIfExists(dirPath, options);
  18641. }
  18642. addSourceFileAtPathIfExists(filePath, options) {
  18643. return this.#compilerFactory.addOrGetSourceFileFromFilePath(filePath, {
  18644. markInProject: options.markInProject,
  18645. scriptKind: undefined,
  18646. });
  18647. }
  18648. addSourceFileAtPath(filePath, options) {
  18649. const sourceFile = this.addSourceFileAtPathIfExists(filePath, options);
  18650. if (sourceFile == null)
  18651. throw new common.errors.FileNotFoundError(this.#fileSystemWrapper.getStandardizedAbsolutePath(filePath));
  18652. return sourceFile;
  18653. }
  18654. addSourceFilesAtPaths(fileGlobs, options) {
  18655. if (typeof fileGlobs === "string")
  18656. fileGlobs = [fileGlobs];
  18657. const sourceFiles = [];
  18658. const globbedDirectories = new Set();
  18659. for (const filePath of this.#fileSystemWrapper.globSync(fileGlobs)) {
  18660. const sourceFile = this.addSourceFileAtPathIfExists(filePath, options);
  18661. if (sourceFile != null)
  18662. sourceFiles.push(sourceFile);
  18663. globbedDirectories.add(common.FileUtils.getDirPath(filePath));
  18664. }
  18665. for (const dirPath of common.FileUtils.getParentMostPaths(Array.from(globbedDirectories)))
  18666. this.addDirectoryAtPathIfExists(dirPath, { recursive: true, markInProject: options.markInProject });
  18667. return sourceFiles;
  18668. }
  18669. }
  18670. class DirectoryCache {
  18671. #context;
  18672. #directoriesByPath = new common.KeyValueCache();
  18673. #sourceFilesByDirPath = new common.KeyValueCache();
  18674. #directoriesByDirPath = new common.KeyValueCache();
  18675. #orphanDirs = new common.KeyValueCache();
  18676. constructor(context) {
  18677. this.#context = context;
  18678. }
  18679. has(dirPath) {
  18680. return this.#directoriesByPath.has(dirPath);
  18681. }
  18682. get(dirPath) {
  18683. if (!this.#directoriesByPath.has(dirPath)) {
  18684. for (const orphanDir of this.#orphanDirs.getValues()) {
  18685. if (common.FileUtils.pathStartsWith(orphanDir.getPath(), dirPath))
  18686. return this.createOrAddIfExists(dirPath);
  18687. }
  18688. return undefined;
  18689. }
  18690. return this.#directoriesByPath.get(dirPath);
  18691. }
  18692. getOrphans() {
  18693. return this.#orphanDirs.getValues();
  18694. }
  18695. getAll() {
  18696. return this.#directoriesByPath.getValuesAsArray();
  18697. }
  18698. *getAllByDepth() {
  18699. const dirLevels = new common.KeyValueCache();
  18700. let depth = 0;
  18701. for (const orphanDir of this.getOrphans())
  18702. addToDirLevels(orphanDir);
  18703. depth = Math.min(...Array.from(dirLevels.getKeys()));
  18704. while (dirLevels.getSize() > 0) {
  18705. for (const dir of dirLevels.get(depth) || []) {
  18706. yield dir;
  18707. dir.getDirectories().forEach(addToDirLevels);
  18708. }
  18709. dirLevels.removeByKey(depth);
  18710. depth++;
  18711. }
  18712. function addToDirLevels(dir) {
  18713. const dirDepth = dir._getDepth();
  18714. if (depth > dirDepth)
  18715. throw new Error(`For some reason a subdirectory had a lower depth than the parent directory: ${dir.getPath()}`);
  18716. const dirs = dirLevels.getOrCreate(dirDepth, () => []);
  18717. dirs.push(dir);
  18718. }
  18719. }
  18720. remove(dirPath) {
  18721. this.#removeFromDirectoriesByDirPath(dirPath);
  18722. this.#directoriesByPath.removeByKey(dirPath);
  18723. this.#orphanDirs.removeByKey(dirPath);
  18724. }
  18725. *getChildDirectoriesOfDirectory(dirPath) {
  18726. const entries = this.#directoriesByDirPath.get(dirPath)?.entries();
  18727. if (entries == null)
  18728. return;
  18729. for (const dir of entries)
  18730. yield dir;
  18731. }
  18732. *getChildSourceFilesOfDirectory(dirPath) {
  18733. const entries = this.#sourceFilesByDirPath.get(dirPath)?.entries();
  18734. if (entries == null)
  18735. return;
  18736. for (const sourceFile of entries)
  18737. yield sourceFile;
  18738. }
  18739. addSourceFile(sourceFile) {
  18740. const dirPath = sourceFile.getDirectoryPath();
  18741. this.createOrAddIfExists(dirPath);
  18742. const sourceFiles = this.#sourceFilesByDirPath.getOrCreate(dirPath, () => new common.SortedKeyValueArray(item => item.getBaseName(), common.LocaleStringComparer.instance));
  18743. sourceFiles.set(sourceFile);
  18744. }
  18745. removeSourceFile(filePath) {
  18746. const dirPath = common.FileUtils.getDirPath(filePath);
  18747. const sourceFiles = this.#sourceFilesByDirPath.get(dirPath);
  18748. if (sourceFiles == null)
  18749. return;
  18750. sourceFiles.removeByKey(common.FileUtils.getBaseName(filePath));
  18751. if (!sourceFiles.hasItems())
  18752. this.#sourceFilesByDirPath.removeByKey(dirPath);
  18753. }
  18754. createOrAddIfExists(dirPath) {
  18755. if (this.has(dirPath))
  18756. return this.get(dirPath);
  18757. this.#fillParentsOfDirPath(dirPath);
  18758. return this.#createDirectory(dirPath);
  18759. }
  18760. #createDirectory(path) {
  18761. const newDirectory = new Directory(this.#context, path);
  18762. this.addDirectory(newDirectory);
  18763. return newDirectory;
  18764. }
  18765. addDirectory(directory) {
  18766. const path = directory.getPath();
  18767. const parentDirPath = common.FileUtils.getDirPath(path);
  18768. const isRootDir = parentDirPath === path;
  18769. for (const orphanDir of this.#orphanDirs.getValues()) {
  18770. const orphanDirPath = orphanDir.getPath();
  18771. const orphanDirParentPath = common.FileUtils.getDirPath(orphanDirPath);
  18772. const isOrphanRootDir = orphanDirParentPath === orphanDirPath;
  18773. if (!isOrphanRootDir && orphanDirParentPath === path)
  18774. this.#orphanDirs.removeByKey(orphanDirPath);
  18775. }
  18776. if (!isRootDir)
  18777. this.#addToDirectoriesByDirPath(directory);
  18778. if (!this.has(parentDirPath))
  18779. this.#orphanDirs.set(path, directory);
  18780. this.#directoriesByPath.set(path, directory);
  18781. if (!this.#context.fileSystemWrapper.directoryExistsSync(path))
  18782. this.#context.fileSystemWrapper.queueMkdir(path);
  18783. for (const orphanDir of this.#orphanDirs.getValues()) {
  18784. if (directory.isAncestorOf(orphanDir))
  18785. this.#fillParentsOfDirPath(orphanDir.getPath());
  18786. }
  18787. }
  18788. #addToDirectoriesByDirPath(directory) {
  18789. if (common.FileUtils.isRootDirPath(directory.getPath()))
  18790. return;
  18791. const parentDirPath = common.FileUtils.getDirPath(directory.getPath());
  18792. const directories = this.#directoriesByDirPath.getOrCreate(parentDirPath, () => new common.SortedKeyValueArray(item => item.getBaseName(), common.LocaleStringComparer.instance));
  18793. directories.set(directory);
  18794. }
  18795. #removeFromDirectoriesByDirPath(dirPath) {
  18796. if (common.FileUtils.isRootDirPath(dirPath))
  18797. return;
  18798. const parentDirPath = common.FileUtils.getDirPath(dirPath);
  18799. const directories = this.#directoriesByDirPath.get(parentDirPath);
  18800. if (directories == null)
  18801. return;
  18802. directories.removeByKey(common.FileUtils.getBaseName(dirPath));
  18803. if (!directories.hasItems())
  18804. this.#directoriesByDirPath.removeByKey(parentDirPath);
  18805. }
  18806. #fillParentsOfDirPath(dirPath) {
  18807. const passedDirPaths = [];
  18808. let parentDir = common.FileUtils.getDirPath(dirPath);
  18809. while (dirPath !== parentDir) {
  18810. dirPath = parentDir;
  18811. parentDir = common.FileUtils.getDirPath(dirPath);
  18812. if (this.#directoriesByPath.has(dirPath)) {
  18813. for (const currentDirPath of passedDirPaths)
  18814. this.#createDirectory(currentDirPath);
  18815. break;
  18816. }
  18817. passedDirPaths.unshift(dirPath);
  18818. }
  18819. }
  18820. }
  18821. class ForgetfulNodeCache extends common.KeyValueCache {
  18822. #forgetStack = [];
  18823. getOrCreate(key, createFunc) {
  18824. return super.getOrCreate(key, () => {
  18825. const node = createFunc();
  18826. if (this.#forgetStack.length > 0)
  18827. this.#forgetStack[this.#forgetStack.length - 1].add(node);
  18828. return node;
  18829. });
  18830. }
  18831. setForgetPoint() {
  18832. this.#forgetStack.push(new Set());
  18833. }
  18834. forgetLastPoint() {
  18835. const nodes = this.#forgetStack.pop();
  18836. if (nodes != null)
  18837. this.#forgetNodes(nodes.values());
  18838. }
  18839. rememberNode(node) {
  18840. if (node.wasForgotten())
  18841. throw new common.errors.InvalidOperationError("Cannot remember a node that was removed or forgotten.");
  18842. let wasInForgetStack = false;
  18843. for (const stackItem of this.#forgetStack) {
  18844. if (stackItem.delete(node)) {
  18845. wasInForgetStack = true;
  18846. break;
  18847. }
  18848. }
  18849. if (wasInForgetStack)
  18850. this.#rememberParentOfNode(node);
  18851. return wasInForgetStack;
  18852. }
  18853. #rememberParentOfNode(node) {
  18854. const parent = node.getParentSyntaxList() || node.getParent();
  18855. if (parent != null)
  18856. this.rememberNode(parent);
  18857. }
  18858. #forgetNodes(nodes) {
  18859. for (const node of nodes) {
  18860. if (node.wasForgotten() || node.getKind() === common.SyntaxKind.SourceFile)
  18861. continue;
  18862. node._forgetOnlyThis();
  18863. }
  18864. }
  18865. }
  18866. const kindToWrapperMappings = {
  18867. [common.SyntaxKind.SourceFile]: SourceFile,
  18868. [common.SyntaxKind.ArrayBindingPattern]: ArrayBindingPattern,
  18869. [common.SyntaxKind.ArrayLiteralExpression]: ArrayLiteralExpression,
  18870. [common.SyntaxKind.ArrayType]: ArrayTypeNode,
  18871. [common.SyntaxKind.ArrowFunction]: ArrowFunction,
  18872. [common.SyntaxKind.AsExpression]: AsExpression,
  18873. [common.SyntaxKind.AwaitExpression]: AwaitExpression,
  18874. [common.SyntaxKind.BigIntLiteral]: BigIntLiteral,
  18875. [common.SyntaxKind.BindingElement]: BindingElement,
  18876. [common.SyntaxKind.BinaryExpression]: BinaryExpression,
  18877. [common.SyntaxKind.Block]: Block,
  18878. [common.SyntaxKind.BreakStatement]: BreakStatement,
  18879. [common.SyntaxKind.CallExpression]: CallExpression,
  18880. [common.SyntaxKind.CallSignature]: CallSignatureDeclaration,
  18881. [common.SyntaxKind.CaseBlock]: CaseBlock,
  18882. [common.SyntaxKind.CaseClause]: CaseClause,
  18883. [common.SyntaxKind.CatchClause]: CatchClause,
  18884. [common.SyntaxKind.ClassDeclaration]: ClassDeclaration,
  18885. [common.SyntaxKind.ClassExpression]: ClassExpression,
  18886. [common.SyntaxKind.ClassStaticBlockDeclaration]: ClassStaticBlockDeclaration,
  18887. [common.SyntaxKind.ConditionalType]: ConditionalTypeNode,
  18888. [common.SyntaxKind.Constructor]: ConstructorDeclaration,
  18889. [common.SyntaxKind.ConstructorType]: ConstructorTypeNode,
  18890. [common.SyntaxKind.ConstructSignature]: ConstructSignatureDeclaration,
  18891. [common.SyntaxKind.ContinueStatement]: ContinueStatement,
  18892. [common.SyntaxKind.CommaListExpression]: CommaListExpression,
  18893. [common.SyntaxKind.ComputedPropertyName]: ComputedPropertyName,
  18894. [common.SyntaxKind.ConditionalExpression]: ConditionalExpression,
  18895. [common.SyntaxKind.DebuggerStatement]: DebuggerStatement,
  18896. [common.SyntaxKind.Decorator]: Decorator,
  18897. [common.SyntaxKind.DefaultClause]: DefaultClause,
  18898. [common.SyntaxKind.DeleteExpression]: DeleteExpression,
  18899. [common.SyntaxKind.DoStatement]: DoStatement,
  18900. [common.SyntaxKind.ElementAccessExpression]: ElementAccessExpression,
  18901. [common.SyntaxKind.EmptyStatement]: EmptyStatement,
  18902. [common.SyntaxKind.EnumDeclaration]: EnumDeclaration,
  18903. [common.SyntaxKind.EnumMember]: EnumMember,
  18904. [common.SyntaxKind.ExportAssignment]: ExportAssignment,
  18905. [common.SyntaxKind.ExportDeclaration]: ExportDeclaration,
  18906. [common.SyntaxKind.ExportSpecifier]: ExportSpecifier,
  18907. [common.SyntaxKind.ExpressionWithTypeArguments]: ExpressionWithTypeArguments,
  18908. [common.SyntaxKind.ExpressionStatement]: ExpressionStatement,
  18909. [common.SyntaxKind.ExternalModuleReference]: ExternalModuleReference,
  18910. [common.SyntaxKind.QualifiedName]: QualifiedName,
  18911. [common.SyntaxKind.ForInStatement]: ForInStatement,
  18912. [common.SyntaxKind.ForOfStatement]: ForOfStatement,
  18913. [common.SyntaxKind.ForStatement]: ForStatement,
  18914. [common.SyntaxKind.FunctionDeclaration]: FunctionDeclaration,
  18915. [common.SyntaxKind.FunctionExpression]: FunctionExpression,
  18916. [common.SyntaxKind.FunctionType]: FunctionTypeNode,
  18917. [common.SyntaxKind.GetAccessor]: GetAccessorDeclaration,
  18918. [common.SyntaxKind.HeritageClause]: HeritageClause,
  18919. [common.SyntaxKind.Identifier]: Identifier,
  18920. [common.SyntaxKind.IfStatement]: IfStatement,
  18921. [common.SyntaxKind.ImportClause]: ImportClause,
  18922. [common.SyntaxKind.ImportDeclaration]: ImportDeclaration,
  18923. [common.SyntaxKind.ImportEqualsDeclaration]: ImportEqualsDeclaration,
  18924. [common.SyntaxKind.ImportSpecifier]: ImportSpecifier,
  18925. [common.SyntaxKind.ImportType]: ImportTypeNode,
  18926. [common.SyntaxKind.ImportAttribute]: ImportAttribute,
  18927. [common.SyntaxKind.ImportAttributes]: ImportAttributes,
  18928. [common.SyntaxKind.IndexedAccessType]: IndexedAccessTypeNode,
  18929. [common.SyntaxKind.IndexSignature]: IndexSignatureDeclaration,
  18930. [common.SyntaxKind.InferType]: InferTypeNode,
  18931. [common.SyntaxKind.InterfaceDeclaration]: InterfaceDeclaration,
  18932. [common.SyntaxKind.IntersectionType]: IntersectionTypeNode,
  18933. [common.SyntaxKind.JSDocAllType]: JSDocAllType,
  18934. [common.SyntaxKind.JSDocAugmentsTag]: JSDocAugmentsTag,
  18935. [common.SyntaxKind.JSDocAuthorTag]: JSDocAuthorTag,
  18936. [common.SyntaxKind.JSDocCallbackTag]: JSDocCallbackTag,
  18937. [common.SyntaxKind.JSDocClassTag]: JSDocClassTag,
  18938. [common.SyntaxKind.JSDocDeprecatedTag]: JSDocDeprecatedTag,
  18939. [common.SyntaxKind.JSDocEnumTag]: JSDocEnumTag,
  18940. [common.SyntaxKind.JSDocFunctionType]: JSDocFunctionType,
  18941. [common.SyntaxKind.JSDocImplementsTag]: JSDocImplementsTag,
  18942. [common.SyntaxKind.JSDocLink]: JSDocLink,
  18943. [common.SyntaxKind.JSDocLinkCode]: JSDocLinkCode,
  18944. [common.SyntaxKind.JSDocLinkPlain]: JSDocLinkPlain,
  18945. [common.SyntaxKind.JSDocMemberName]: JSDocMemberName,
  18946. [common.SyntaxKind.JSDocNamepathType]: JSDocNamepathType,
  18947. [common.SyntaxKind.JSDocNameReference]: JSDocNameReference,
  18948. [common.SyntaxKind.JSDocNonNullableType]: JSDocNonNullableType,
  18949. [common.SyntaxKind.JSDocNullableType]: JSDocNullableType,
  18950. [common.SyntaxKind.JSDocOptionalType]: JSDocOptionalType,
  18951. [common.SyntaxKind.JSDocOverrideTag]: JSDocOverrideTag,
  18952. [common.SyntaxKind.JSDocParameterTag]: JSDocParameterTag,
  18953. [common.SyntaxKind.JSDocPrivateTag]: JSDocPrivateTag,
  18954. [common.SyntaxKind.JSDocPropertyTag]: JSDocPropertyTag,
  18955. [common.SyntaxKind.JSDocProtectedTag]: JSDocProtectedTag,
  18956. [common.SyntaxKind.JSDocPublicTag]: JSDocPublicTag,
  18957. [common.SyntaxKind.JSDocReturnTag]: JSDocReturnTag,
  18958. [common.SyntaxKind.JSDocReadonlyTag]: JSDocReadonlyTag,
  18959. [common.SyntaxKind.JSDocThrowsTag]: JSDocThrowsTag,
  18960. [common.SyntaxKind.JSDocOverloadTag]: JSDocOverloadTag,
  18961. [common.SyntaxKind.JSDocSatisfiesTag]: JSDocSatisfiesTag,
  18962. [common.SyntaxKind.JSDocSeeTag]: JSDocSeeTag,
  18963. [common.SyntaxKind.JSDocSignature]: JSDocSignature,
  18964. [common.SyntaxKind.JSDocTag]: JSDocUnknownTag,
  18965. [common.SyntaxKind.JSDocTemplateTag]: JSDocTemplateTag,
  18966. [common.SyntaxKind.JSDocText]: JSDocText,
  18967. [common.SyntaxKind.JSDocThisTag]: JSDocThisTag,
  18968. [common.SyntaxKind.JSDocTypeExpression]: JSDocTypeExpression,
  18969. [common.SyntaxKind.JSDocTypeLiteral]: JSDocTypeLiteral,
  18970. [common.SyntaxKind.JSDocTypeTag]: JSDocTypeTag,
  18971. [common.SyntaxKind.JSDocTypedefTag]: JSDocTypedefTag,
  18972. [common.SyntaxKind.JSDocUnknownType]: JSDocUnknownType,
  18973. [common.SyntaxKind.JSDocVariadicType]: JSDocVariadicType,
  18974. [common.SyntaxKind.JsxAttribute]: JsxAttribute,
  18975. [common.SyntaxKind.JsxClosingElement]: JsxClosingElement,
  18976. [common.SyntaxKind.JsxClosingFragment]: JsxClosingFragment,
  18977. [common.SyntaxKind.JsxElement]: JsxElement,
  18978. [common.SyntaxKind.JsxExpression]: JsxExpression,
  18979. [common.SyntaxKind.JsxFragment]: JsxFragment,
  18980. [common.SyntaxKind.JsxNamespacedName]: JsxNamespacedName,
  18981. [common.SyntaxKind.JsxOpeningElement]: JsxOpeningElement,
  18982. [common.SyntaxKind.JsxOpeningFragment]: JsxOpeningFragment,
  18983. [common.SyntaxKind.JsxSelfClosingElement]: JsxSelfClosingElement,
  18984. [common.SyntaxKind.JsxSpreadAttribute]: JsxSpreadAttribute,
  18985. [common.SyntaxKind.JsxText]: JsxText,
  18986. [common.SyntaxKind.LabeledStatement]: LabeledStatement,
  18987. [common.SyntaxKind.LiteralType]: LiteralTypeNode,
  18988. [common.SyntaxKind.MappedType]: MappedTypeNode,
  18989. [common.SyntaxKind.MetaProperty]: MetaProperty,
  18990. [common.SyntaxKind.MethodDeclaration]: MethodDeclaration,
  18991. [common.SyntaxKind.MethodSignature]: MethodSignature,
  18992. [common.SyntaxKind.ModuleBlock]: ModuleBlock,
  18993. [common.SyntaxKind.ModuleDeclaration]: ModuleDeclaration,
  18994. [common.SyntaxKind.NamedExports]: NamedExports,
  18995. [common.SyntaxKind.NamedImports]: NamedImports,
  18996. [common.SyntaxKind.NamedTupleMember]: NamedTupleMember,
  18997. [common.SyntaxKind.NamespaceExport]: NamespaceExport,
  18998. [common.SyntaxKind.NamespaceImport]: NamespaceImport,
  18999. [common.SyntaxKind.NewExpression]: NewExpression,
  19000. [common.SyntaxKind.NonNullExpression]: NonNullExpression,
  19001. [common.SyntaxKind.NotEmittedStatement]: NotEmittedStatement,
  19002. [common.SyntaxKind.NoSubstitutionTemplateLiteral]: NoSubstitutionTemplateLiteral,
  19003. [common.SyntaxKind.NumericLiteral]: NumericLiteral,
  19004. [common.SyntaxKind.ObjectBindingPattern]: ObjectBindingPattern,
  19005. [common.SyntaxKind.ObjectLiteralExpression]: ObjectLiteralExpression,
  19006. [common.SyntaxKind.OmittedExpression]: OmittedExpression,
  19007. [common.SyntaxKind.Parameter]: ParameterDeclaration,
  19008. [common.SyntaxKind.ParenthesizedExpression]: ParenthesizedExpression,
  19009. [common.SyntaxKind.ParenthesizedType]: ParenthesizedTypeNode,
  19010. [common.SyntaxKind.PartiallyEmittedExpression]: PartiallyEmittedExpression,
  19011. [common.SyntaxKind.PostfixUnaryExpression]: PostfixUnaryExpression,
  19012. [common.SyntaxKind.PrefixUnaryExpression]: PrefixUnaryExpression,
  19013. [common.SyntaxKind.PrivateIdentifier]: PrivateIdentifier,
  19014. [common.SyntaxKind.PropertyAccessExpression]: PropertyAccessExpression,
  19015. [common.SyntaxKind.PropertyAssignment]: PropertyAssignment,
  19016. [common.SyntaxKind.PropertyDeclaration]: PropertyDeclaration,
  19017. [common.SyntaxKind.PropertySignature]: PropertySignature,
  19018. [common.SyntaxKind.RegularExpressionLiteral]: RegularExpressionLiteral,
  19019. [common.SyntaxKind.RestType]: RestTypeNode,
  19020. [common.SyntaxKind.ReturnStatement]: ReturnStatement,
  19021. [common.SyntaxKind.SatisfiesExpression]: SatisfiesExpression,
  19022. [common.SyntaxKind.SetAccessor]: SetAccessorDeclaration,
  19023. [common.SyntaxKind.ShorthandPropertyAssignment]: ShorthandPropertyAssignment,
  19024. [common.SyntaxKind.SpreadAssignment]: SpreadAssignment,
  19025. [common.SyntaxKind.SpreadElement]: SpreadElement,
  19026. [common.SyntaxKind.StringLiteral]: StringLiteral,
  19027. [common.SyntaxKind.SwitchStatement]: SwitchStatement,
  19028. [common.SyntaxKind.SyntaxList]: SyntaxList,
  19029. [common.SyntaxKind.TaggedTemplateExpression]: TaggedTemplateExpression,
  19030. [common.SyntaxKind.TemplateExpression]: TemplateExpression,
  19031. [common.SyntaxKind.TemplateHead]: TemplateHead,
  19032. [common.SyntaxKind.TemplateLiteralType]: TemplateLiteralTypeNode,
  19033. [common.SyntaxKind.TemplateMiddle]: TemplateMiddle,
  19034. [common.SyntaxKind.TemplateSpan]: TemplateSpan,
  19035. [common.SyntaxKind.TemplateTail]: TemplateTail,
  19036. [common.SyntaxKind.ThisType]: ThisTypeNode,
  19037. [common.SyntaxKind.ThrowStatement]: ThrowStatement,
  19038. [common.SyntaxKind.TryStatement]: TryStatement,
  19039. [common.SyntaxKind.TupleType]: TupleTypeNode,
  19040. [common.SyntaxKind.TypeAliasDeclaration]: TypeAliasDeclaration,
  19041. [common.SyntaxKind.TypeAssertionExpression]: TypeAssertion,
  19042. [common.SyntaxKind.TypeLiteral]: TypeLiteralNode,
  19043. [common.SyntaxKind.TypeOperator]: TypeOperatorTypeNode,
  19044. [common.SyntaxKind.TypeParameter]: TypeParameterDeclaration,
  19045. [common.SyntaxKind.TypePredicate]: TypePredicateNode,
  19046. [common.SyntaxKind.TypeQuery]: TypeQueryNode,
  19047. [common.SyntaxKind.TypeReference]: TypeReferenceNode,
  19048. [common.SyntaxKind.UnionType]: UnionTypeNode,
  19049. [common.SyntaxKind.VariableDeclaration]: VariableDeclaration,
  19050. [common.SyntaxKind.VariableDeclarationList]: VariableDeclarationList,
  19051. [common.SyntaxKind.VariableStatement]: VariableStatement,
  19052. [common.SyntaxKind.JSDoc]: JSDoc,
  19053. [common.SyntaxKind.TypeOfExpression]: TypeOfExpression,
  19054. [common.SyntaxKind.WhileStatement]: WhileStatement,
  19055. [common.SyntaxKind.WithStatement]: WithStatement,
  19056. [common.SyntaxKind.YieldExpression]: YieldExpression,
  19057. [common.SyntaxKind.SemicolonToken]: Node,
  19058. [common.SyntaxKind.AnyKeyword]: Expression,
  19059. [common.SyntaxKind.BooleanKeyword]: Expression,
  19060. [common.SyntaxKind.FalseKeyword]: FalseLiteral,
  19061. [common.SyntaxKind.ImportKeyword]: ImportExpression,
  19062. [common.SyntaxKind.InferKeyword]: Node,
  19063. [common.SyntaxKind.NeverKeyword]: Node,
  19064. [common.SyntaxKind.NullKeyword]: NullLiteral,
  19065. [common.SyntaxKind.NumberKeyword]: Expression,
  19066. [common.SyntaxKind.ObjectKeyword]: Expression,
  19067. [common.SyntaxKind.StringKeyword]: Expression,
  19068. [common.SyntaxKind.SymbolKeyword]: Expression,
  19069. [common.SyntaxKind.SuperKeyword]: SuperExpression,
  19070. [common.SyntaxKind.ThisKeyword]: ThisExpression,
  19071. [common.SyntaxKind.TrueKeyword]: TrueLiteral,
  19072. [common.SyntaxKind.UndefinedKeyword]: Expression,
  19073. [common.SyntaxKind.VoidExpression]: VoidExpression,
  19074. };
  19075. class CompilerFactory {
  19076. #context;
  19077. #sourceFileCacheByFilePath = new Map();
  19078. #diagnosticCache = new common.WeakCache();
  19079. #definitionInfoCache = new common.WeakCache();
  19080. #documentSpanCache = new common.WeakCache();
  19081. #diagnosticMessageChainCache = new common.WeakCache();
  19082. #jsDocTagInfoCache = new common.WeakCache();
  19083. #signatureCache = new common.WeakCache();
  19084. #symbolCache = new common.WeakCache();
  19085. #symbolDisplayPartCache = new common.WeakCache();
  19086. #referencedSymbolEntryCache = new common.WeakCache();
  19087. #referencedSymbolCache = new common.WeakCache();
  19088. #referencedSymbolDefinitionInfoCache = new common.WeakCache();
  19089. #typeCache = new common.WeakCache();
  19090. #typeParameterCache = new common.WeakCache();
  19091. #nodeCache = new ForgetfulNodeCache();
  19092. #directoryCache;
  19093. #sourceFileAddedEventContainer = new common.EventContainer();
  19094. #sourceFileRemovedEventContainer = new common.EventContainer();
  19095. documentRegistry;
  19096. constructor(context) {
  19097. this.documentRegistry = new common.DocumentRegistry(context.fileSystemWrapper);
  19098. this.#directoryCache = new DirectoryCache(context);
  19099. context.compilerOptions.onModified(() => {
  19100. const currentSourceFiles = Array.from(this.#sourceFileCacheByFilePath.values());
  19101. for (const sourceFile of currentSourceFiles) {
  19102. replaceSourceFileForCacheUpdate(sourceFile);
  19103. }
  19104. });
  19105. this.#context = context;
  19106. }
  19107. *getSourceFilesByDirectoryDepth() {
  19108. for (const dir of this.getDirectoriesByDepth())
  19109. yield* dir.getSourceFiles();
  19110. }
  19111. getSourceFilePaths() {
  19112. return this.#sourceFileCacheByFilePath.keys();
  19113. }
  19114. getChildDirectoriesOfDirectory(dirPath) {
  19115. return this.#directoryCache.getChildDirectoriesOfDirectory(dirPath);
  19116. }
  19117. getChildSourceFilesOfDirectory(dirPath) {
  19118. return this.#directoryCache.getChildSourceFilesOfDirectory(dirPath);
  19119. }
  19120. onSourceFileAdded(subscription, subscribe = true) {
  19121. if (subscribe)
  19122. this.#sourceFileAddedEventContainer.subscribe(subscription);
  19123. else
  19124. this.#sourceFileAddedEventContainer.unsubscribe(subscription);
  19125. }
  19126. onSourceFileRemoved(subscription) {
  19127. this.#sourceFileRemovedEventContainer.subscribe(subscription);
  19128. }
  19129. createSourceFile(filePath, sourceFileText, options) {
  19130. sourceFileText = sourceFileText instanceof Function ? getTextFromStringOrWriter(this.#context.createWriter(), sourceFileText) : sourceFileText || "";
  19131. if (typeof sourceFileText === "string")
  19132. return this.createSourceFileFromText(filePath, sourceFileText, options);
  19133. const writer = this.#context.createWriter();
  19134. const structurePrinter = this.#context.structurePrinterFactory.forSourceFile({
  19135. isAmbient: common.FileUtils.getExtension(filePath) === ".d.ts",
  19136. });
  19137. structurePrinter.printText(writer, sourceFileText);
  19138. return this.createSourceFileFromText(filePath, writer.toString(), options);
  19139. }
  19140. createSourceFileFromText(filePath, sourceText, options) {
  19141. filePath = this.#context.fileSystemWrapper.getStandardizedAbsolutePath(filePath);
  19142. if (options.overwrite === true)
  19143. return this.#createOrOverwriteSourceFileFromText(filePath, sourceText, options);
  19144. this.throwIfFileExists(filePath, "Did you mean to provide the overwrite option?");
  19145. return this.#createSourceFileFromTextInternal(filePath, sourceText, options);
  19146. }
  19147. throwIfFileExists(filePath, prefixMessage) {
  19148. if (!this.containsSourceFileAtPath(filePath) && !this.#context.fileSystemWrapper.fileExistsSync(filePath))
  19149. return;
  19150. prefixMessage = prefixMessage == null ? "" : prefixMessage + " ";
  19151. throw new common.errors.InvalidOperationError(`${prefixMessage}A source file already exists at the provided file path: ${filePath}`);
  19152. }
  19153. #createOrOverwriteSourceFileFromText(filePath, sourceText, options) {
  19154. filePath = this.#context.fileSystemWrapper.getStandardizedAbsolutePath(filePath);
  19155. const existingSourceFile = this.addOrGetSourceFileFromFilePath(filePath, options);
  19156. if (existingSourceFile != null) {
  19157. existingSourceFile.getChildren().forEach(c => c.forget());
  19158. this.replaceCompilerNode(existingSourceFile, this.createCompilerSourceFileFromText(filePath, sourceText, options.scriptKind));
  19159. return existingSourceFile;
  19160. }
  19161. return this.#createSourceFileFromTextInternal(filePath, sourceText, options);
  19162. }
  19163. getSourceFileFromCacheFromFilePath(filePath) {
  19164. filePath = this.#context.fileSystemWrapper.getStandardizedAbsolutePath(filePath);
  19165. return this.#sourceFileCacheByFilePath.get(filePath);
  19166. }
  19167. addOrGetSourceFileFromFilePath(filePath, options) {
  19168. filePath = this.#context.fileSystemWrapper.getStandardizedAbsolutePath(filePath);
  19169. let sourceFile = this.#sourceFileCacheByFilePath.get(filePath);
  19170. if (sourceFile == null) {
  19171. const fileText = this.#context.fileSystemWrapper.readFileIfExistsSync(filePath, this.#context.getEncoding());
  19172. if (fileText != null) {
  19173. this.#context.logger.log(`Loaded file: ${filePath}`);
  19174. sourceFile = this.#createSourceFileFromTextInternal(filePath, fileText, options);
  19175. sourceFile._setIsSaved(true);
  19176. }
  19177. }
  19178. if (sourceFile != null && options.markInProject)
  19179. sourceFile._markAsInProject();
  19180. return sourceFile;
  19181. }
  19182. containsSourceFileAtPath(filePath) {
  19183. filePath = this.#context.fileSystemWrapper.getStandardizedAbsolutePath(filePath);
  19184. return this.#sourceFileCacheByFilePath.has(filePath);
  19185. }
  19186. containsDirectoryAtPath(dirPath) {
  19187. dirPath = this.#context.fileSystemWrapper.getStandardizedAbsolutePath(dirPath);
  19188. return this.#directoryCache.has(dirPath);
  19189. }
  19190. getSourceFileForNode(compilerNode) {
  19191. let currentNode = compilerNode;
  19192. while (currentNode.kind !== common.SyntaxKind.SourceFile) {
  19193. if (currentNode.parent == null)
  19194. return undefined;
  19195. currentNode = currentNode.parent;
  19196. }
  19197. return this.getSourceFile(currentNode, { markInProject: false });
  19198. }
  19199. hasCompilerNode(compilerNode) {
  19200. return this.#nodeCache.has(compilerNode);
  19201. }
  19202. getExistingNodeFromCompilerNode(compilerNode) {
  19203. return this.#nodeCache.get(compilerNode);
  19204. }
  19205. getNodeFromCompilerNode(compilerNode, sourceFile) {
  19206. if (compilerNode.kind === common.SyntaxKind.SourceFile)
  19207. return this.getSourceFile(compilerNode, { markInProject: false });
  19208. return this.#nodeCache.getOrCreate(compilerNode, () => {
  19209. const node = createNode.call(this);
  19210. initializeNode.call(this, node);
  19211. return node;
  19212. });
  19213. function createNode() {
  19214. if (isCommentNode(compilerNode)) {
  19215. if (CommentNodeParser.isCommentStatement(compilerNode))
  19216. return new CommentStatement(this.#context, compilerNode, sourceFile);
  19217. if (CommentNodeParser.isCommentClassElement(compilerNode))
  19218. return new CommentClassElement(this.#context, compilerNode, sourceFile);
  19219. if (CommentNodeParser.isCommentTypeElement(compilerNode))
  19220. return new CommentTypeElement(this.#context, compilerNode, sourceFile);
  19221. if (CommentNodeParser.isCommentObjectLiteralElement(compilerNode))
  19222. return new CommentObjectLiteralElement(this.#context, compilerNode, sourceFile);
  19223. if (CommentNodeParser.isCommentEnumMember(compilerNode))
  19224. return new CommentEnumMember(this.#context, compilerNode, sourceFile);
  19225. return common.errors.throwNotImplementedForNeverValueError(compilerNode);
  19226. }
  19227. const ctor = kindToWrapperMappings[compilerNode.kind] || Node;
  19228. return new ctor(this.#context, compilerNode, sourceFile);
  19229. }
  19230. function isCommentNode(node) {
  19231. return node._commentKind != null;
  19232. }
  19233. function initializeNode(node) {
  19234. if (compilerNode.parent != null) {
  19235. const parentNode = this.getNodeFromCompilerNode(compilerNode.parent, sourceFile);
  19236. parentNode._wrappedChildCount++;
  19237. }
  19238. const parentSyntaxList = node._getParentSyntaxListIfWrapped();
  19239. if (parentSyntaxList != null)
  19240. parentSyntaxList._wrappedChildCount++;
  19241. if (compilerNode.kind === common.SyntaxKind.SyntaxList) {
  19242. let count = 0;
  19243. for (const _ of node._getChildrenInCacheIterator())
  19244. count++;
  19245. node._wrappedChildCount = count;
  19246. }
  19247. }
  19248. }
  19249. #createSourceFileFromTextInternal(filePath, text, options) {
  19250. const hasBom = common.StringUtils.hasBom(text);
  19251. if (hasBom)
  19252. text = common.StringUtils.stripBom(text);
  19253. const sourceFile = this.getSourceFile(this.createCompilerSourceFileFromText(filePath, text, options.scriptKind), options);
  19254. if (hasBom)
  19255. sourceFile._hasBom = true;
  19256. return sourceFile;
  19257. }
  19258. createCompilerSourceFileFromText(filePath, text, scriptKind) {
  19259. return this.documentRegistry.createOrUpdateSourceFile(filePath, this.#context.compilerOptions.get(), common.ts.ScriptSnapshot.fromString(text), scriptKind);
  19260. }
  19261. getSourceFile(compilerSourceFile, options) {
  19262. let wasAdded = false;
  19263. const sourceFile = this.#sourceFileCacheByFilePath.get(compilerSourceFile.fileName)
  19264. ?? this.#nodeCache.getOrCreate(compilerSourceFile, () => {
  19265. const createdSourceFile = new SourceFile(this.#context, compilerSourceFile);
  19266. if (!options.markInProject)
  19267. this.#context.inProjectCoordinator.setSourceFileNotInProject(createdSourceFile);
  19268. this.#addSourceFileToCache(createdSourceFile);
  19269. wasAdded = true;
  19270. return createdSourceFile;
  19271. });
  19272. if (options.markInProject)
  19273. sourceFile._markAsInProject();
  19274. if (wasAdded)
  19275. this.#sourceFileAddedEventContainer.fire(sourceFile);
  19276. return sourceFile;
  19277. }
  19278. #addSourceFileToCache(sourceFile) {
  19279. this.#sourceFileCacheByFilePath.set(sourceFile.getFilePath(), sourceFile);
  19280. this.#context.fileSystemWrapper.removeFileDelete(sourceFile.getFilePath());
  19281. this.#directoryCache.addSourceFile(sourceFile);
  19282. }
  19283. getDirectoryFromPath(dirPath, options) {
  19284. dirPath = this.#context.fileSystemWrapper.getStandardizedAbsolutePath(dirPath);
  19285. let directory = this.#directoryCache.get(dirPath);
  19286. if (directory == null && this.#context.fileSystemWrapper.directoryExistsSync(dirPath))
  19287. directory = this.#directoryCache.createOrAddIfExists(dirPath);
  19288. if (directory != null && options.markInProject)
  19289. directory._markAsInProject();
  19290. return directory;
  19291. }
  19292. createDirectoryOrAddIfExists(dirPath, options) {
  19293. const directory = this.#directoryCache.createOrAddIfExists(dirPath);
  19294. if (directory != null && options.markInProject)
  19295. directory._markAsInProject();
  19296. return directory;
  19297. }
  19298. getDirectoryFromCache(dirPath) {
  19299. return this.#directoryCache.get(dirPath);
  19300. }
  19301. getDirectoryFromCacheOnlyIfInCache(dirPath) {
  19302. return this.#directoryCache.has(dirPath)
  19303. ? this.#directoryCache.get(dirPath)
  19304. : undefined;
  19305. }
  19306. getDirectoriesByDepth() {
  19307. return this.#directoryCache.getAllByDepth();
  19308. }
  19309. getOrphanDirectories() {
  19310. return this.#directoryCache.getOrphans();
  19311. }
  19312. getSymbolDisplayPart(compilerObject) {
  19313. return this.#symbolDisplayPartCache.getOrCreate(compilerObject, () => new SymbolDisplayPart(compilerObject));
  19314. }
  19315. getType(type) {
  19316. if ((type.flags & common.TypeFlags.TypeParameter) === common.TypeFlags.TypeParameter)
  19317. return this.getTypeParameter(type);
  19318. return this.#typeCache.getOrCreate(type, () => new Type(this.#context, type));
  19319. }
  19320. getTypeParameter(typeParameter) {
  19321. return this.#typeParameterCache.getOrCreate(typeParameter, () => new TypeParameter(this.#context, typeParameter));
  19322. }
  19323. getSignature(signature) {
  19324. return this.#signatureCache.getOrCreate(signature, () => new Signature(this.#context, signature));
  19325. }
  19326. getSymbol(symbol) {
  19327. return this.#symbolCache.getOrCreate(symbol, () => new Symbol(this.#context, symbol));
  19328. }
  19329. getDefinitionInfo(compilerObject) {
  19330. return this.#definitionInfoCache.getOrCreate(compilerObject, () => new DefinitionInfo(this.#context, compilerObject));
  19331. }
  19332. getDocumentSpan(compilerObject) {
  19333. return this.#documentSpanCache.getOrCreate(compilerObject, () => new DocumentSpan(this.#context, compilerObject));
  19334. }
  19335. getReferencedSymbolEntry(compilerObject) {
  19336. return this.#referencedSymbolEntryCache.getOrCreate(compilerObject, () => new ReferencedSymbolEntry(this.#context, compilerObject));
  19337. }
  19338. getReferencedSymbol(compilerObject) {
  19339. return this.#referencedSymbolCache.getOrCreate(compilerObject, () => new ReferencedSymbol(this.#context, compilerObject));
  19340. }
  19341. getReferencedSymbolDefinitionInfo(compilerObject) {
  19342. return this.#referencedSymbolDefinitionInfoCache.getOrCreate(compilerObject, () => new ReferencedSymbolDefinitionInfo(this.#context, compilerObject));
  19343. }
  19344. getDiagnostic(diagnostic) {
  19345. return this.#diagnosticCache.getOrCreate(diagnostic, () => {
  19346. if (diagnostic.start != null)
  19347. return new DiagnosticWithLocation(this.#context, diagnostic);
  19348. return new Diagnostic(this.#context, diagnostic);
  19349. });
  19350. }
  19351. getDiagnosticWithLocation(diagnostic) {
  19352. return this.#diagnosticCache.getOrCreate(diagnostic, () => new DiagnosticWithLocation(this.#context, diagnostic));
  19353. }
  19354. getDiagnosticMessageChain(compilerObject) {
  19355. return this.#diagnosticMessageChainCache.getOrCreate(compilerObject, () => new DiagnosticMessageChain(compilerObject));
  19356. }
  19357. getJSDocTagInfo(jsDocTagInfo) {
  19358. return this.#jsDocTagInfoCache.getOrCreate(jsDocTagInfo, () => new JSDocTagInfo(jsDocTagInfo));
  19359. }
  19360. replaceCompilerNode(oldNode, newNode) {
  19361. const nodeToReplace = oldNode instanceof Node ? oldNode.compilerNode : oldNode;
  19362. const node = oldNode instanceof Node ? oldNode : this.#nodeCache.get(oldNode);
  19363. if (nodeToReplace.kind === common.SyntaxKind.SourceFile && nodeToReplace.fileName !== newNode.fileName) {
  19364. const sourceFile = node;
  19365. this.#removeCompilerNodeFromCache(nodeToReplace);
  19366. sourceFile._replaceCompilerNodeFromFactory(newNode);
  19367. this.#nodeCache.set(newNode, sourceFile);
  19368. this.#addSourceFileToCache(sourceFile);
  19369. this.#sourceFileAddedEventContainer.fire(sourceFile);
  19370. }
  19371. else {
  19372. this.#nodeCache.replaceKey(nodeToReplace, newNode);
  19373. if (node != null)
  19374. node._replaceCompilerNodeFromFactory(newNode);
  19375. }
  19376. }
  19377. removeNodeFromCache(node) {
  19378. this.#removeCompilerNodeFromCache(node.compilerNode);
  19379. }
  19380. #removeCompilerNodeFromCache(compilerNode) {
  19381. this.#nodeCache.removeByKey(compilerNode);
  19382. if (compilerNode.kind === common.SyntaxKind.SourceFile) {
  19383. const sourceFile = compilerNode;
  19384. const standardizedFilePath = this.#context.fileSystemWrapper.getStandardizedAbsolutePath(sourceFile.fileName);
  19385. this.#directoryCache.removeSourceFile(standardizedFilePath);
  19386. const wrappedSourceFile = this.#sourceFileCacheByFilePath.get(standardizedFilePath);
  19387. this.#sourceFileCacheByFilePath.delete(standardizedFilePath);
  19388. this.documentRegistry.removeSourceFile(standardizedFilePath);
  19389. if (wrappedSourceFile != null)
  19390. this.#sourceFileRemovedEventContainer.fire(wrappedSourceFile);
  19391. }
  19392. }
  19393. addDirectoryToCache(directory) {
  19394. this.#directoryCache.addDirectory(directory);
  19395. }
  19396. removeDirectoryFromCache(dirPath) {
  19397. this.#directoryCache.remove(dirPath);
  19398. }
  19399. forgetNodesCreatedInBlock(block) {
  19400. this.#nodeCache.setForgetPoint();
  19401. let wasPromise = false;
  19402. let result;
  19403. try {
  19404. result = block((...nodes) => {
  19405. for (const node of nodes)
  19406. this.#nodeCache.rememberNode(node);
  19407. });
  19408. if (Node.isNode(result))
  19409. this.#nodeCache.rememberNode(result);
  19410. if (isPromise(result)) {
  19411. wasPromise = true;
  19412. return result.then(value => {
  19413. if (Node.isNode(value))
  19414. this.#nodeCache.rememberNode(value);
  19415. this.#nodeCache.forgetLastPoint();
  19416. return value;
  19417. });
  19418. }
  19419. }
  19420. finally {
  19421. if (!wasPromise)
  19422. this.#nodeCache.forgetLastPoint();
  19423. }
  19424. return result;
  19425. function isPromise(value) {
  19426. return value != null && typeof value.then === "function";
  19427. }
  19428. }
  19429. }
  19430. class InProjectCoordinator {
  19431. #compilerFactory;
  19432. #notInProjectFiles = new Set();
  19433. constructor(compilerFactory) {
  19434. compilerFactory.onSourceFileRemoved(sourceFile => {
  19435. this.#notInProjectFiles.delete(sourceFile);
  19436. });
  19437. this.#compilerFactory = compilerFactory;
  19438. }
  19439. setSourceFileNotInProject(sourceFile) {
  19440. this.#notInProjectFiles.add(sourceFile);
  19441. sourceFile._inProject = false;
  19442. }
  19443. markSourceFileAsInProject(sourceFile) {
  19444. if (this.isSourceFileInProject(sourceFile))
  19445. return;
  19446. this.#internalMarkSourceFileAsInProject(sourceFile);
  19447. this.#notInProjectFiles.delete(sourceFile);
  19448. }
  19449. markSourceFilesAsInProjectForResolution() {
  19450. const nodeModulesSearchName = "/node_modules/";
  19451. const compilerFactory = this.#compilerFactory;
  19452. const changedSourceFiles = [];
  19453. const unchangedSourceFiles = [];
  19454. for (const sourceFile of [...this.#notInProjectFiles.values()]) {
  19455. if (shouldMarkInProject(sourceFile)) {
  19456. this.#internalMarkSourceFileAsInProject(sourceFile);
  19457. this.#notInProjectFiles.delete(sourceFile);
  19458. changedSourceFiles.push(sourceFile);
  19459. }
  19460. else {
  19461. unchangedSourceFiles.push(sourceFile);
  19462. }
  19463. }
  19464. return { changedSourceFiles, unchangedSourceFiles };
  19465. function shouldMarkInProject(sourceFile) {
  19466. const filePath = sourceFile.getFilePath();
  19467. const index = filePath.toLowerCase().lastIndexOf(nodeModulesSearchName);
  19468. if (index === -1)
  19469. return true;
  19470. const nodeModulesPath = filePath.substring(0, index + nodeModulesSearchName.length - 1);
  19471. const nodeModulesDir = compilerFactory.getDirectoryFromCacheOnlyIfInCache(nodeModulesPath);
  19472. if (nodeModulesDir != null && nodeModulesDir._isInProject())
  19473. return true;
  19474. let directory = sourceFile.getDirectory();
  19475. while (directory != null && directory.getPath() !== nodeModulesPath) {
  19476. if (directory._isInProject())
  19477. return true;
  19478. directory = compilerFactory.getDirectoryFromCacheOnlyIfInCache(common.FileUtils.getDirPath(directory.getPath()));
  19479. }
  19480. return false;
  19481. }
  19482. }
  19483. #internalMarkSourceFileAsInProject(sourceFile) {
  19484. sourceFile._inProject = true;
  19485. this.markDirectoryAsInProject(sourceFile.getDirectory());
  19486. }
  19487. isSourceFileInProject(sourceFile) {
  19488. return sourceFile._inProject === true;
  19489. }
  19490. setDirectoryAndFilesAsNotInProjectForTesting(directory) {
  19491. for (const subDir of directory.getDirectories())
  19492. this.setDirectoryAndFilesAsNotInProjectForTesting(subDir);
  19493. for (const file of directory.getSourceFiles()) {
  19494. delete file._inProject;
  19495. this.#notInProjectFiles.add(file);
  19496. }
  19497. delete directory._inProject;
  19498. }
  19499. markDirectoryAsInProject(directory) {
  19500. if (this.isDirectoryInProject(directory))
  19501. return;
  19502. const inProjectCoordinator = this;
  19503. const compilerFactory = this.#compilerFactory;
  19504. directory._inProject = true;
  19505. markAncestorDirs(directory);
  19506. function markAncestorDirs(dir) {
  19507. const ancestorDirs = Array.from(getAncestorsUpToOneInProject(dir));
  19508. const topAncestor = ancestorDirs[ancestorDirs.length - 1];
  19509. if (topAncestor == null || !inProjectCoordinator.isDirectoryInProject(topAncestor))
  19510. return;
  19511. for (const ancestorDir of ancestorDirs)
  19512. ancestorDir._inProject = true;
  19513. }
  19514. function* getAncestorsUpToOneInProject(dir) {
  19515. if (common.FileUtils.isRootDirPath(dir.getPath()))
  19516. return;
  19517. const parentDirPath = common.FileUtils.getDirPath(dir.getPath());
  19518. const parentDir = compilerFactory.getDirectoryFromCacheOnlyIfInCache(parentDirPath);
  19519. if (parentDir == null)
  19520. return;
  19521. yield parentDir;
  19522. if (!inProjectCoordinator.isDirectoryInProject(parentDir))
  19523. yield* getAncestorsUpToOneInProject(parentDir);
  19524. }
  19525. }
  19526. isDirectoryInProject(directory) {
  19527. return directory._inProject === true;
  19528. }
  19529. }
  19530. class StructurePrinterFactory {
  19531. _getFormatCodeSettings;
  19532. constructor(_getFormatCodeSettings) {
  19533. this._getFormatCodeSettings = _getFormatCodeSettings;
  19534. }
  19535. getFormatCodeSettings() {
  19536. return this._getFormatCodeSettings();
  19537. }
  19538. forInitializerExpressionableNode() {
  19539. return new InitializerExpressionableNodeStructurePrinter();
  19540. }
  19541. forModifierableNode() {
  19542. return new ModifierableNodeStructurePrinter();
  19543. }
  19544. forReturnTypedNode(alwaysWrite) {
  19545. return new ReturnTypedNodeStructurePrinter(alwaysWrite);
  19546. }
  19547. forTypedNode(separator, alwaysWrite) {
  19548. return new TypedNodeStructurePrinter(separator, alwaysWrite);
  19549. }
  19550. forClassDeclaration(options) {
  19551. return new ClassDeclarationStructurePrinter(this, options);
  19552. }
  19553. forClassMember(options) {
  19554. return new ClassMemberStructurePrinter(this, options);
  19555. }
  19556. forClassStaticBlockDeclaration() {
  19557. return new ClassStaticBlockDeclarationStructurePrinter(this);
  19558. }
  19559. forConstructorDeclaration(options) {
  19560. return new ConstructorDeclarationStructurePrinter(this, options);
  19561. }
  19562. forGetAccessorDeclaration(options) {
  19563. return new GetAccessorDeclarationStructurePrinter(this, options);
  19564. }
  19565. forMethodDeclaration(options) {
  19566. return new MethodDeclarationStructurePrinter(this, options);
  19567. }
  19568. forPropertyDeclaration() {
  19569. return new PropertyDeclarationStructurePrinter(this);
  19570. }
  19571. forSetAccessorDeclaration(options) {
  19572. return new SetAccessorDeclarationStructurePrinter(this, options);
  19573. }
  19574. forDecorator() {
  19575. return new DecoratorStructurePrinter(this);
  19576. }
  19577. forJSDoc() {
  19578. return new JSDocStructurePrinter(this);
  19579. }
  19580. forJSDocTag(options) {
  19581. return new JSDocTagStructurePrinter(this, options);
  19582. }
  19583. forEnumDeclaration() {
  19584. return new EnumDeclarationStructurePrinter(this);
  19585. }
  19586. forEnumMember() {
  19587. return new EnumMemberStructurePrinter(this);
  19588. }
  19589. forObjectLiteralExpressionProperty() {
  19590. return new ObjectLiteralExpressionPropertyStructurePrinter(this);
  19591. }
  19592. forPropertyAssignment() {
  19593. return new PropertyAssignmentStructurePrinter(this);
  19594. }
  19595. forShorthandPropertyAssignment() {
  19596. return new ShorthandPropertyAssignmentStructurePrinter(this);
  19597. }
  19598. forSpreadAssignment() {
  19599. return new SpreadAssignmentStructurePrinter(this);
  19600. }
  19601. forFunctionDeclaration(options) {
  19602. return new FunctionDeclarationStructurePrinter(this, options);
  19603. }
  19604. forParameterDeclaration() {
  19605. return new ParameterDeclarationStructurePrinter(this);
  19606. }
  19607. forCallSignatureDeclaration() {
  19608. return new CallSignatureDeclarationStructurePrinter(this);
  19609. }
  19610. forConstructSignatureDeclaration() {
  19611. return new ConstructSignatureDeclarationStructurePrinter(this);
  19612. }
  19613. forIndexSignatureDeclaration() {
  19614. return new IndexSignatureDeclarationStructurePrinter(this);
  19615. }
  19616. forInterfaceDeclaration() {
  19617. return new InterfaceDeclarationStructurePrinter(this);
  19618. }
  19619. forMethodSignature() {
  19620. return new MethodSignatureStructurePrinter(this);
  19621. }
  19622. forPropertySignature() {
  19623. return new PropertySignatureStructurePrinter(this);
  19624. }
  19625. forTypeElementMemberedNode() {
  19626. return new TypeElementMemberedNodeStructurePrinter(this);
  19627. }
  19628. forTypeElementMember() {
  19629. return new TypeElementMemberStructurePrinter(this);
  19630. }
  19631. forJsxAttributeDecider() {
  19632. return new JsxAttributeDeciderStructurePrinter(this);
  19633. }
  19634. forJsxAttribute() {
  19635. return new JsxAttributeStructurePrinter(this);
  19636. }
  19637. forJsxChildDecider() {
  19638. return new JsxChildDeciderStructurePrinter(this);
  19639. }
  19640. forJsxElement() {
  19641. return new JsxElementStructurePrinter(this);
  19642. }
  19643. forJsxNamespacedName() {
  19644. return new JsxNamespacedNameStructurePrinter(this);
  19645. }
  19646. forJsxSelfClosingElement() {
  19647. return new JsxSelfClosingElementStructurePrinter(this);
  19648. }
  19649. forJsxSpreadAttribute() {
  19650. return new JsxSpreadAttributeStructurePrinter(this);
  19651. }
  19652. forExportAssignment() {
  19653. return new ExportAssignmentStructurePrinter(this);
  19654. }
  19655. forExportDeclaration() {
  19656. return new ExportDeclarationStructurePrinter(this);
  19657. }
  19658. forImportAttribute() {
  19659. return new ImportAttributeStructurePrinter(this);
  19660. }
  19661. forImportDeclaration() {
  19662. return new ImportDeclarationStructurePrinter(this);
  19663. }
  19664. forModuleDeclaration(options) {
  19665. return new ModuleDeclarationStructurePrinter(this, options);
  19666. }
  19667. forNamedImportExportSpecifier() {
  19668. return new NamedImportExportSpecifierStructurePrinter(this);
  19669. }
  19670. forSourceFile(options) {
  19671. return new SourceFileStructurePrinter(this, options);
  19672. }
  19673. forStatementedNode(options) {
  19674. return new StatementedNodeStructurePrinter(this, options);
  19675. }
  19676. forStatement(options) {
  19677. return new StatementStructurePrinter(this, options);
  19678. }
  19679. forVariableStatement() {
  19680. return new VariableStatementStructurePrinter(this);
  19681. }
  19682. forTypeAliasDeclaration() {
  19683. return new TypeAliasDeclarationStructurePrinter(this);
  19684. }
  19685. forTypeParameterDeclaration() {
  19686. return new TypeParameterDeclarationStructurePrinter(this);
  19687. }
  19688. forVariableDeclaration() {
  19689. return new VariableDeclarationStructurePrinter(this);
  19690. }
  19691. }
  19692. __decorate([
  19693. common.Memoize
  19694. ], StructurePrinterFactory.prototype, "forInitializerExpressionableNode", null);
  19695. __decorate([
  19696. common.Memoize
  19697. ], StructurePrinterFactory.prototype, "forModifierableNode", null);
  19698. __decorate([
  19699. common.Memoize
  19700. ], StructurePrinterFactory.prototype, "forReturnTypedNode", null);
  19701. __decorate([
  19702. common.Memoize
  19703. ], StructurePrinterFactory.prototype, "forTypedNode", null);
  19704. __decorate([
  19705. common.Memoize
  19706. ], StructurePrinterFactory.prototype, "forClassDeclaration", null);
  19707. __decorate([
  19708. common.Memoize
  19709. ], StructurePrinterFactory.prototype, "forClassMember", null);
  19710. __decorate([
  19711. common.Memoize
  19712. ], StructurePrinterFactory.prototype, "forClassStaticBlockDeclaration", null);
  19713. __decorate([
  19714. common.Memoize
  19715. ], StructurePrinterFactory.prototype, "forConstructorDeclaration", null);
  19716. __decorate([
  19717. common.Memoize
  19718. ], StructurePrinterFactory.prototype, "forGetAccessorDeclaration", null);
  19719. __decorate([
  19720. common.Memoize
  19721. ], StructurePrinterFactory.prototype, "forMethodDeclaration", null);
  19722. __decorate([
  19723. common.Memoize
  19724. ], StructurePrinterFactory.prototype, "forPropertyDeclaration", null);
  19725. __decorate([
  19726. common.Memoize
  19727. ], StructurePrinterFactory.prototype, "forSetAccessorDeclaration", null);
  19728. __decorate([
  19729. common.Memoize
  19730. ], StructurePrinterFactory.prototype, "forDecorator", null);
  19731. __decorate([
  19732. common.Memoize
  19733. ], StructurePrinterFactory.prototype, "forJSDoc", null);
  19734. __decorate([
  19735. common.Memoize
  19736. ], StructurePrinterFactory.prototype, "forJSDocTag", null);
  19737. __decorate([
  19738. common.Memoize
  19739. ], StructurePrinterFactory.prototype, "forEnumDeclaration", null);
  19740. __decorate([
  19741. common.Memoize
  19742. ], StructurePrinterFactory.prototype, "forEnumMember", null);
  19743. __decorate([
  19744. common.Memoize
  19745. ], StructurePrinterFactory.prototype, "forObjectLiteralExpressionProperty", null);
  19746. __decorate([
  19747. common.Memoize
  19748. ], StructurePrinterFactory.prototype, "forPropertyAssignment", null);
  19749. __decorate([
  19750. common.Memoize
  19751. ], StructurePrinterFactory.prototype, "forShorthandPropertyAssignment", null);
  19752. __decorate([
  19753. common.Memoize
  19754. ], StructurePrinterFactory.prototype, "forSpreadAssignment", null);
  19755. __decorate([
  19756. common.Memoize
  19757. ], StructurePrinterFactory.prototype, "forFunctionDeclaration", null);
  19758. __decorate([
  19759. common.Memoize
  19760. ], StructurePrinterFactory.prototype, "forParameterDeclaration", null);
  19761. __decorate([
  19762. common.Memoize
  19763. ], StructurePrinterFactory.prototype, "forCallSignatureDeclaration", null);
  19764. __decorate([
  19765. common.Memoize
  19766. ], StructurePrinterFactory.prototype, "forConstructSignatureDeclaration", null);
  19767. __decorate([
  19768. common.Memoize
  19769. ], StructurePrinterFactory.prototype, "forIndexSignatureDeclaration", null);
  19770. __decorate([
  19771. common.Memoize
  19772. ], StructurePrinterFactory.prototype, "forInterfaceDeclaration", null);
  19773. __decorate([
  19774. common.Memoize
  19775. ], StructurePrinterFactory.prototype, "forMethodSignature", null);
  19776. __decorate([
  19777. common.Memoize
  19778. ], StructurePrinterFactory.prototype, "forPropertySignature", null);
  19779. __decorate([
  19780. common.Memoize
  19781. ], StructurePrinterFactory.prototype, "forTypeElementMemberedNode", null);
  19782. __decorate([
  19783. common.Memoize
  19784. ], StructurePrinterFactory.prototype, "forTypeElementMember", null);
  19785. __decorate([
  19786. common.Memoize
  19787. ], StructurePrinterFactory.prototype, "forJsxAttributeDecider", null);
  19788. __decorate([
  19789. common.Memoize
  19790. ], StructurePrinterFactory.prototype, "forJsxAttribute", null);
  19791. __decorate([
  19792. common.Memoize
  19793. ], StructurePrinterFactory.prototype, "forJsxChildDecider", null);
  19794. __decorate([
  19795. common.Memoize
  19796. ], StructurePrinterFactory.prototype, "forJsxElement", null);
  19797. __decorate([
  19798. common.Memoize
  19799. ], StructurePrinterFactory.prototype, "forJsxNamespacedName", null);
  19800. __decorate([
  19801. common.Memoize
  19802. ], StructurePrinterFactory.prototype, "forJsxSelfClosingElement", null);
  19803. __decorate([
  19804. common.Memoize
  19805. ], StructurePrinterFactory.prototype, "forJsxSpreadAttribute", null);
  19806. __decorate([
  19807. common.Memoize
  19808. ], StructurePrinterFactory.prototype, "forExportAssignment", null);
  19809. __decorate([
  19810. common.Memoize
  19811. ], StructurePrinterFactory.prototype, "forExportDeclaration", null);
  19812. __decorate([
  19813. common.Memoize
  19814. ], StructurePrinterFactory.prototype, "forImportAttribute", null);
  19815. __decorate([
  19816. common.Memoize
  19817. ], StructurePrinterFactory.prototype, "forImportDeclaration", null);
  19818. __decorate([
  19819. common.Memoize
  19820. ], StructurePrinterFactory.prototype, "forModuleDeclaration", null);
  19821. __decorate([
  19822. common.Memoize
  19823. ], StructurePrinterFactory.prototype, "forNamedImportExportSpecifier", null);
  19824. __decorate([
  19825. common.Memoize
  19826. ], StructurePrinterFactory.prototype, "forSourceFile", null);
  19827. __decorate([
  19828. common.Memoize
  19829. ], StructurePrinterFactory.prototype, "forStatementedNode", null);
  19830. __decorate([
  19831. common.Memoize
  19832. ], StructurePrinterFactory.prototype, "forStatement", null);
  19833. __decorate([
  19834. common.Memoize
  19835. ], StructurePrinterFactory.prototype, "forVariableStatement", null);
  19836. __decorate([
  19837. common.Memoize
  19838. ], StructurePrinterFactory.prototype, "forTypeAliasDeclaration", null);
  19839. __decorate([
  19840. common.Memoize
  19841. ], StructurePrinterFactory.prototype, "forTypeParameterDeclaration", null);
  19842. __decorate([
  19843. common.Memoize
  19844. ], StructurePrinterFactory.prototype, "forVariableDeclaration", null);
  19845. class ProjectContext {
  19846. #languageService;
  19847. #compilerOptions;
  19848. #customTypeChecker;
  19849. #project;
  19850. get project() {
  19851. if (this.#project == null)
  19852. throw new common.errors.InvalidOperationError("This operation is not permitted in this context.");
  19853. return this.#project;
  19854. }
  19855. logger = new ConsoleLogger();
  19856. lazyReferenceCoordinator;
  19857. directoryCoordinator;
  19858. fileSystemWrapper;
  19859. manipulationSettings = new ManipulationSettingsContainer();
  19860. structurePrinterFactory;
  19861. compilerFactory;
  19862. inProjectCoordinator;
  19863. constructor(params) {
  19864. this.#project = params.project;
  19865. this.fileSystemWrapper = params.fileSystemWrapper;
  19866. this.#compilerOptions = params.compilerOptionsContainer;
  19867. this.compilerFactory = new CompilerFactory(this);
  19868. this.inProjectCoordinator = new InProjectCoordinator(this.compilerFactory);
  19869. this.structurePrinterFactory = new StructurePrinterFactory(() => this.manipulationSettings.getFormatCodeSettings());
  19870. this.lazyReferenceCoordinator = new LazyReferenceCoordinator(this.compilerFactory);
  19871. this.directoryCoordinator = new DirectoryCoordinator(this.compilerFactory, params.fileSystemWrapper);
  19872. this.#languageService = params.createLanguageService
  19873. ? new LanguageService({
  19874. context: this,
  19875. configFileParsingDiagnostics: params.configFileParsingDiagnostics,
  19876. resolutionHost: params.resolutionHost && params.resolutionHost(this.getModuleResolutionHost(), () => this.compilerOptions.get()),
  19877. skipLoadingLibFiles: params.skipLoadingLibFiles,
  19878. libFolderPath: params.libFolderPath,
  19879. })
  19880. : undefined;
  19881. if (params.typeChecker != null) {
  19882. common.errors.throwIfTrue(params.createLanguageService, "Cannot specify a type checker and create a language service.");
  19883. this.#customTypeChecker = new TypeChecker(this);
  19884. this.#customTypeChecker._reset(() => params.typeChecker);
  19885. }
  19886. }
  19887. get compilerOptions() {
  19888. return this.#compilerOptions;
  19889. }
  19890. get languageService() {
  19891. if (this.#languageService == null)
  19892. throw this.#getToolRequiredError("language service");
  19893. return this.#languageService;
  19894. }
  19895. get program() {
  19896. if (this.#languageService == null)
  19897. throw this.#getToolRequiredError("program");
  19898. return this.languageService.getProgram();
  19899. }
  19900. get typeChecker() {
  19901. if (this.#customTypeChecker != null)
  19902. return this.#customTypeChecker;
  19903. if (this.#languageService == null)
  19904. throw this.#getToolRequiredError("type checker");
  19905. return this.program.getTypeChecker();
  19906. }
  19907. hasLanguageService() {
  19908. return this.#languageService != null;
  19909. }
  19910. getEncoding() {
  19911. return this.compilerOptions.getEncoding();
  19912. }
  19913. getFormatCodeSettings() {
  19914. return this.manipulationSettings.getFormatCodeSettings();
  19915. }
  19916. getUserPreferences() {
  19917. return this.manipulationSettings.getUserPreferences();
  19918. }
  19919. resetProgram() {
  19920. this.languageService._reset();
  19921. }
  19922. createWriter() {
  19923. const indentationText = this.manipulationSettings.getIndentationText();
  19924. return new CodeBlockWriter__default.default({
  19925. newLine: this.manipulationSettings.getNewLineKindAsString(),
  19926. indentNumberOfSpaces: indentationText === exports.IndentationText.Tab ? undefined : indentationText.length,
  19927. useTabs: indentationText === exports.IndentationText.Tab,
  19928. useSingleQuote: this.manipulationSettings.getQuoteKind() === exports.QuoteKind.Single,
  19929. });
  19930. }
  19931. getPreEmitDiagnostics(sourceFile) {
  19932. const compilerDiagnostics = common.ts.getPreEmitDiagnostics(this.program.compilerObject, sourceFile?.compilerNode);
  19933. return compilerDiagnostics.map(d => this.compilerFactory.getDiagnostic(d));
  19934. }
  19935. getSourceFileContainer() {
  19936. return {
  19937. addOrGetSourceFileFromFilePath: (filePath, opts) => {
  19938. return Promise.resolve(this.compilerFactory.addOrGetSourceFileFromFilePath(filePath, opts)?.compilerNode);
  19939. },
  19940. addOrGetSourceFileFromFilePathSync: (filePath, opts) => {
  19941. return this.compilerFactory.addOrGetSourceFileFromFilePath(filePath, opts)?.compilerNode;
  19942. },
  19943. containsDirectoryAtPath: dirPath => this.compilerFactory.containsDirectoryAtPath(dirPath),
  19944. containsSourceFileAtPath: filePath => this.compilerFactory.containsSourceFileAtPath(filePath),
  19945. getSourceFileFromCacheFromFilePath: filePath => {
  19946. const sourceFile = this.compilerFactory.getSourceFileFromCacheFromFilePath(filePath);
  19947. return sourceFile?.compilerNode;
  19948. },
  19949. getSourceFilePaths: () => this.compilerFactory.getSourceFilePaths(),
  19950. getSourceFileVersion: sourceFile => this.compilerFactory.documentRegistry.getSourceFileVersion(sourceFile),
  19951. getChildDirectoriesOfDirectory: dirPath => {
  19952. const result = [];
  19953. for (const dir of this.compilerFactory.getChildDirectoriesOfDirectory(dirPath))
  19954. result.push(dir.getPath());
  19955. return result;
  19956. },
  19957. };
  19958. }
  19959. getModuleResolutionHost() {
  19960. return common.createModuleResolutionHost({
  19961. transactionalFileSystem: this.fileSystemWrapper,
  19962. getEncoding: () => this.getEncoding(),
  19963. sourceFileContainer: this.getSourceFileContainer(),
  19964. });
  19965. }
  19966. #getToolRequiredError(name) {
  19967. return new common.errors.InvalidOperationError(`A ${name} is required for this operation. `
  19968. + "This might occur when manipulating or getting type information from a node that was not added "
  19969. + `to a Project object and created via createWrappedNode. `
  19970. + `Please submit a bug report if you don't believe a ${name} should be required for this operation.`);
  19971. }
  19972. }
  19973. __decorate([
  19974. common.Memoize
  19975. ], ProjectContext.prototype, "getSourceFileContainer", null);
  19976. __decorate([
  19977. common.Memoize
  19978. ], ProjectContext.prototype, "getModuleResolutionHost", null);
  19979. class Project {
  19980. _context;
  19981. constructor(options = {}) {
  19982. verifyOptions();
  19983. const fileSystem = getFileSystem();
  19984. const fileSystemWrapper = new common.TransactionalFileSystem({
  19985. fileSystem,
  19986. skipLoadingLibFiles: options.skipLoadingLibFiles,
  19987. libFolderPath: options.libFolderPath,
  19988. });
  19989. const tsConfigResolver = options.tsConfigFilePath == null
  19990. ? undefined
  19991. : new common.TsConfigResolver(fileSystemWrapper, fileSystemWrapper.getStandardizedAbsolutePath(options.tsConfigFilePath), getEncoding());
  19992. const compilerOptions = getCompilerOptions();
  19993. const compilerOptionsContainer = new common.CompilerOptionsContainer(options.defaultCompilerOptions);
  19994. compilerOptionsContainer.set(compilerOptions);
  19995. this._context = new ProjectContext({
  19996. project: this,
  19997. compilerOptionsContainer,
  19998. fileSystemWrapper,
  19999. createLanguageService: true,
  20000. resolutionHost: options.resolutionHost,
  20001. configFileParsingDiagnostics: tsConfigResolver?.getErrors() ?? [],
  20002. skipLoadingLibFiles: options.skipLoadingLibFiles,
  20003. libFolderPath: options.libFolderPath,
  20004. });
  20005. if (options.manipulationSettings != null)
  20006. this._context.manipulationSettings.set(options.manipulationSettings);
  20007. if (tsConfigResolver != null && options.skipAddingFilesFromTsConfig !== true) {
  20008. this.#addSourceFilesForTsConfigResolver(tsConfigResolver, compilerOptions);
  20009. if (!options.skipFileDependencyResolution)
  20010. this.resolveSourceFileDependencies();
  20011. }
  20012. function verifyOptions() {
  20013. if (options.fileSystem != null && options.useInMemoryFileSystem)
  20014. throw new common.errors.InvalidOperationError("Cannot provide a file system when specifying to use an in-memory file system.");
  20015. }
  20016. function getFileSystem() {
  20017. if (options.useInMemoryFileSystem)
  20018. return new common.InMemoryFileSystemHost();
  20019. return options.fileSystem ?? new common.RealFileSystemHost();
  20020. }
  20021. function getCompilerOptions() {
  20022. return {
  20023. ...getTsConfigCompilerOptions(),
  20024. ...(options.compilerOptions ?? {}),
  20025. };
  20026. }
  20027. function getTsConfigCompilerOptions() {
  20028. return tsConfigResolver?.getCompilerOptions() ?? {};
  20029. }
  20030. function getEncoding() {
  20031. const defaultEncoding = "utf-8";
  20032. if (options.compilerOptions != null)
  20033. return options.compilerOptions.charset ?? defaultEncoding;
  20034. return defaultEncoding;
  20035. }
  20036. }
  20037. get manipulationSettings() {
  20038. return this._context.manipulationSettings;
  20039. }
  20040. get compilerOptions() {
  20041. return this._context.compilerOptions;
  20042. }
  20043. resolveSourceFileDependencies() {
  20044. const sourceFiles = new Set();
  20045. const onSourceFileAdded = (sourceFile) => sourceFiles.add(sourceFile);
  20046. const { compilerFactory, inProjectCoordinator } = this._context;
  20047. compilerFactory.onSourceFileAdded(onSourceFileAdded);
  20048. try {
  20049. this.getProgram().compilerObject;
  20050. }
  20051. finally {
  20052. compilerFactory.onSourceFileAdded(onSourceFileAdded, false);
  20053. }
  20054. const result = inProjectCoordinator.markSourceFilesAsInProjectForResolution();
  20055. for (const sourceFile of result.changedSourceFiles)
  20056. sourceFiles.add(sourceFile);
  20057. for (const sourceFile of result.unchangedSourceFiles)
  20058. sourceFiles.delete(sourceFile);
  20059. return Array.from(sourceFiles.values());
  20060. }
  20061. addDirectoryAtPathIfExists(dirPath, options = {}) {
  20062. return this._context.directoryCoordinator.addDirectoryAtPathIfExists(this._context.fileSystemWrapper.getStandardizedAbsolutePath(dirPath), { ...options, markInProject: true });
  20063. }
  20064. addDirectoryAtPath(dirPath, options = {}) {
  20065. return this._context.directoryCoordinator.addDirectoryAtPath(this._context.fileSystemWrapper.getStandardizedAbsolutePath(dirPath), { ...options, markInProject: true });
  20066. }
  20067. createDirectory(dirPath) {
  20068. return this._context.directoryCoordinator.createDirectoryOrAddIfExists(this._context.fileSystemWrapper.getStandardizedAbsolutePath(dirPath), { markInProject: true });
  20069. }
  20070. getDirectoryOrThrow(dirPath, message) {
  20071. return common.errors.throwIfNullOrUndefined(this.getDirectory(dirPath), message ?? (() => `Could not find a directory at the specified path: ${this._context.fileSystemWrapper.getStandardizedAbsolutePath(dirPath)}`));
  20072. }
  20073. getDirectory(dirPath) {
  20074. const { compilerFactory } = this._context;
  20075. return compilerFactory.getDirectoryFromCache(this._context.fileSystemWrapper.getStandardizedAbsolutePath(dirPath));
  20076. }
  20077. getDirectories() {
  20078. return Array.from(this.#getProjectDirectoriesByDirectoryDepth());
  20079. }
  20080. getRootDirectories() {
  20081. const { inProjectCoordinator } = this._context;
  20082. const result = [];
  20083. for (const dir of this._context.compilerFactory.getOrphanDirectories()) {
  20084. for (const inProjectDir of findInProjectDirectories(dir))
  20085. result.push(inProjectDir);
  20086. }
  20087. return result;
  20088. function* findInProjectDirectories(dir) {
  20089. if (inProjectCoordinator.isDirectoryInProject(dir)) {
  20090. yield dir;
  20091. return;
  20092. }
  20093. for (const childDir of dir._getDirectoriesIterator())
  20094. yield* findInProjectDirectories(childDir);
  20095. }
  20096. }
  20097. addSourceFilesAtPaths(fileGlobs) {
  20098. return this._context.directoryCoordinator.addSourceFilesAtPaths(fileGlobs, { markInProject: true });
  20099. }
  20100. addSourceFileAtPathIfExists(filePath) {
  20101. return this._context.directoryCoordinator.addSourceFileAtPathIfExists(this._context.fileSystemWrapper.getStandardizedAbsolutePath(filePath), {
  20102. markInProject: true,
  20103. });
  20104. }
  20105. addSourceFileAtPath(filePath) {
  20106. return this._context.directoryCoordinator.addSourceFileAtPath(this._context.fileSystemWrapper.getStandardizedAbsolutePath(filePath), {
  20107. markInProject: true,
  20108. });
  20109. }
  20110. addSourceFilesFromTsConfig(tsConfigFilePath) {
  20111. const resolver = new common.TsConfigResolver(this._context.fileSystemWrapper, this._context.fileSystemWrapper.getStandardizedAbsolutePath(tsConfigFilePath), this._context.getEncoding());
  20112. return this.#addSourceFilesForTsConfigResolver(resolver, resolver.getCompilerOptions());
  20113. }
  20114. #addSourceFilesForTsConfigResolver(tsConfigResolver, compilerOptions) {
  20115. const paths = tsConfigResolver.getPaths(compilerOptions);
  20116. const addedSourceFiles = paths.filePaths.map(p => this.addSourceFileAtPath(p));
  20117. for (const dirPath of paths.directoryPaths)
  20118. this.addDirectoryAtPathIfExists(dirPath);
  20119. return addedSourceFiles;
  20120. }
  20121. createSourceFile(filePath, sourceFileText, options) {
  20122. return this._context.compilerFactory.createSourceFile(this._context.fileSystemWrapper.getStandardizedAbsolutePath(filePath), sourceFileText ?? "", { ...(options ?? {}), markInProject: true });
  20123. }
  20124. removeSourceFile(sourceFile) {
  20125. const previouslyForgotten = sourceFile.wasForgotten();
  20126. sourceFile.forget();
  20127. return !previouslyForgotten;
  20128. }
  20129. getSourceFileOrThrow(fileNameOrSearchFunction) {
  20130. const sourceFile = this.getSourceFile(fileNameOrSearchFunction);
  20131. if (sourceFile != null)
  20132. return sourceFile;
  20133. if (typeof fileNameOrSearchFunction === "string") {
  20134. const fileNameOrPath = common.FileUtils.standardizeSlashes(fileNameOrSearchFunction);
  20135. if (common.FileUtils.pathIsAbsolute(fileNameOrPath) || fileNameOrPath.indexOf("/") >= 0) {
  20136. const errorFileNameOrPath = this._context.fileSystemWrapper.getStandardizedAbsolutePath(fileNameOrPath);
  20137. throw new common.errors.InvalidOperationError(`Could not find source file in project at the provided path: ${errorFileNameOrPath}`);
  20138. }
  20139. else {
  20140. throw new common.errors.InvalidOperationError(`Could not find source file in project with the provided file name: ${fileNameOrSearchFunction}`);
  20141. }
  20142. }
  20143. else {
  20144. throw new common.errors.InvalidOperationError(`Could not find source file in project based on the provided condition.`);
  20145. }
  20146. }
  20147. getSourceFile(fileNameOrSearchFunction) {
  20148. const filePathOrSearchFunction = getFilePathOrSearchFunction(this._context.fileSystemWrapper);
  20149. if (isStandardizedFilePath(filePathOrSearchFunction)) {
  20150. return this._context.compilerFactory.getSourceFileFromCacheFromFilePath(filePathOrSearchFunction);
  20151. }
  20152. return common.IterableUtils.find(this.#getProjectSourceFilesByDirectoryDepth(), filePathOrSearchFunction);
  20153. function getFilePathOrSearchFunction(fileSystemWrapper) {
  20154. if (fileNameOrSearchFunction instanceof Function)
  20155. return fileNameOrSearchFunction;
  20156. const fileNameOrPath = common.FileUtils.standardizeSlashes(fileNameOrSearchFunction);
  20157. if (common.FileUtils.pathIsAbsolute(fileNameOrPath) || fileNameOrPath.indexOf("/") >= 0)
  20158. return fileSystemWrapper.getStandardizedAbsolutePath(fileNameOrPath);
  20159. else
  20160. return def => common.FileUtils.pathEndsWith(def.getFilePath(), fileNameOrPath);
  20161. }
  20162. function isStandardizedFilePath(obj) {
  20163. return typeof obj === "string";
  20164. }
  20165. }
  20166. getSourceFiles(globPatterns) {
  20167. const { compilerFactory, fileSystemWrapper } = this._context;
  20168. const sourceFiles = this.#getProjectSourceFilesByDirectoryDepth();
  20169. if (typeof globPatterns === "string" || globPatterns instanceof Array)
  20170. return Array.from(getFilteredSourceFiles());
  20171. else
  20172. return Array.from(sourceFiles);
  20173. function* getFilteredSourceFiles() {
  20174. const sourceFilePaths = Array.from(getSourceFilePaths());
  20175. const matchedPaths = common.matchGlobs(sourceFilePaths, globPatterns, fileSystemWrapper.getCurrentDirectory());
  20176. for (const matchedPath of matchedPaths)
  20177. yield compilerFactory.getSourceFileFromCacheFromFilePath(fileSystemWrapper.getStandardizedAbsolutePath(matchedPath));
  20178. function* getSourceFilePaths() {
  20179. for (const sourceFile of sourceFiles)
  20180. yield sourceFile.getFilePath();
  20181. }
  20182. }
  20183. }
  20184. *#getProjectSourceFilesByDirectoryDepth() {
  20185. const { compilerFactory, inProjectCoordinator } = this._context;
  20186. for (const sourceFile of compilerFactory.getSourceFilesByDirectoryDepth()) {
  20187. if (inProjectCoordinator.isSourceFileInProject(sourceFile))
  20188. yield sourceFile;
  20189. }
  20190. }
  20191. *#getProjectDirectoriesByDirectoryDepth() {
  20192. const { compilerFactory, inProjectCoordinator } = this._context;
  20193. for (const directory of compilerFactory.getDirectoriesByDepth()) {
  20194. if (inProjectCoordinator.isDirectoryInProject(directory))
  20195. yield directory;
  20196. }
  20197. }
  20198. getAmbientModule(moduleName) {
  20199. moduleName = normalizeAmbientModuleName(moduleName);
  20200. return this.getAmbientModules().find(s => s.getName() === moduleName);
  20201. }
  20202. getAmbientModuleOrThrow(moduleName, message) {
  20203. return common.errors.throwIfNullOrUndefined(this.getAmbientModule(moduleName), message ?? (() => `Could not find ambient module with name: ${normalizeAmbientModuleName(moduleName)}`));
  20204. }
  20205. getAmbientModules() {
  20206. return this.getTypeChecker().getAmbientModules();
  20207. }
  20208. async save() {
  20209. await this._context.fileSystemWrapper.flush();
  20210. await Promise.all(this.#getUnsavedSourceFiles().map(f => f.save()));
  20211. }
  20212. saveSync() {
  20213. this._context.fileSystemWrapper.flushSync();
  20214. for (const file of this.#getUnsavedSourceFiles())
  20215. file.saveSync();
  20216. }
  20217. enableLogging(enabled = true) {
  20218. this._context.logger.setEnabled(enabled);
  20219. }
  20220. #getUnsavedSourceFiles() {
  20221. return Array.from(getUnsavedIterator(this._context.compilerFactory.getSourceFilesByDirectoryDepth()));
  20222. function* getUnsavedIterator(sourceFiles) {
  20223. for (const sourceFile of sourceFiles) {
  20224. if (!sourceFile.isSaved())
  20225. yield sourceFile;
  20226. }
  20227. }
  20228. }
  20229. getPreEmitDiagnostics() {
  20230. return this._context.getPreEmitDiagnostics();
  20231. }
  20232. getLanguageService() {
  20233. return this._context.languageService;
  20234. }
  20235. getProgram() {
  20236. return this._context.program;
  20237. }
  20238. getTypeChecker() {
  20239. return this._context.typeChecker;
  20240. }
  20241. getFileSystem() {
  20242. return this._context.fileSystemWrapper.getFileSystem();
  20243. }
  20244. emit(emitOptions = {}) {
  20245. return this._context.program.emit(emitOptions);
  20246. }
  20247. emitSync(emitOptions = {}) {
  20248. return this._context.program.emitSync(emitOptions);
  20249. }
  20250. emitToMemory(emitOptions = {}) {
  20251. return this._context.program.emitToMemory(emitOptions);
  20252. }
  20253. getCompilerOptions() {
  20254. return this._context.compilerOptions.get();
  20255. }
  20256. getConfigFileParsingDiagnostics() {
  20257. return this.getProgram().getConfigFileParsingDiagnostics();
  20258. }
  20259. createWriter() {
  20260. return this._context.createWriter();
  20261. }
  20262. forgetNodesCreatedInBlock(block) {
  20263. return this._context.compilerFactory.forgetNodesCreatedInBlock(block);
  20264. }
  20265. formatDiagnosticsWithColorAndContext(diagnostics, opts = {}) {
  20266. return common.ts.formatDiagnosticsWithColorAndContext(diagnostics.map(d => d.compilerObject), {
  20267. getCurrentDirectory: () => this._context.fileSystemWrapper.getCurrentDirectory(),
  20268. getCanonicalFileName: fileName => fileName,
  20269. getNewLine: () => opts.newLineChar ?? common.runtime.getEndOfLine(),
  20270. });
  20271. }
  20272. getModuleResolutionHost() {
  20273. return this._context.getModuleResolutionHost();
  20274. }
  20275. }
  20276. function normalizeAmbientModuleName(moduleName) {
  20277. if (isQuote(moduleName[0]) && isQuote(moduleName[moduleName.length - 1]))
  20278. moduleName = moduleName.substring(1, moduleName.length - 1);
  20279. return `"${moduleName}"`;
  20280. function isQuote(char) {
  20281. return char === `"` || char === "'";
  20282. }
  20283. }
  20284. function createWrappedNode(node, opts = {}) {
  20285. const { compilerOptions = {}, sourceFile, typeChecker } = opts;
  20286. const compilerOptionsContainer = new common.CompilerOptionsContainer();
  20287. compilerOptionsContainer.set(compilerOptions);
  20288. const projectContext = new ProjectContext({
  20289. project: undefined,
  20290. fileSystemWrapper: new common.TransactionalFileSystem({
  20291. fileSystem: new common.RealFileSystemHost(),
  20292. skipLoadingLibFiles: true,
  20293. libFolderPath: undefined,
  20294. }),
  20295. compilerOptionsContainer,
  20296. createLanguageService: false,
  20297. typeChecker,
  20298. configFileParsingDiagnostics: [],
  20299. skipLoadingLibFiles: true,
  20300. libFolderPath: undefined,
  20301. });
  20302. const wrappedSourceFile = projectContext.compilerFactory.getSourceFile(getSourceFileNode(), { markInProject: true });
  20303. return projectContext.compilerFactory.getNodeFromCompilerNode(node, wrappedSourceFile);
  20304. function getSourceFileNode() {
  20305. return sourceFile ?? getSourceFileFromNode(node);
  20306. }
  20307. function getSourceFileFromNode(compilerNode) {
  20308. if (compilerNode.kind === common.SyntaxKind.SourceFile)
  20309. return compilerNode;
  20310. if (compilerNode.parent == null)
  20311. throw new common.errors.InvalidOperationError("Please ensure the node was created from a source file with 'setParentNodes' set to 'true'.");
  20312. let parent = compilerNode;
  20313. while (parent.parent != null)
  20314. parent = parent.parent;
  20315. if (parent.kind !== common.SyntaxKind.SourceFile)
  20316. throw new common.errors.NotImplementedError("For some reason the top parent was not a source file.");
  20317. return parent;
  20318. }
  20319. }
  20320. const structurePrinterFactory = new StructurePrinterFactory(() => {
  20321. throw new common.errors.NotImplementedError("Not implemented scenario for getting code format settings when using a writer function. Please open an issue.");
  20322. });
  20323. class Writers {
  20324. constructor() {
  20325. }
  20326. static object(obj) {
  20327. return (writer) => {
  20328. const keyNames = Object.keys(obj);
  20329. writer.write("{");
  20330. if (keyNames.length > 0) {
  20331. writer.indent(() => {
  20332. writeObject();
  20333. });
  20334. }
  20335. writer.write("}");
  20336. function writeObject() {
  20337. for (let i = 0; i < keyNames.length; i++) {
  20338. if (i > 0)
  20339. writer.write(",").newLine();
  20340. const keyName = keyNames[i];
  20341. const value = obj[keyName];
  20342. writer.write(keyName);
  20343. if (value != null) {
  20344. writer.write(": ");
  20345. writeValue(writer, value);
  20346. }
  20347. }
  20348. writer.newLine();
  20349. }
  20350. };
  20351. }
  20352. static objectType(structure) {
  20353. return (writer) => {
  20354. writer.write("{");
  20355. if (anyPropertyHasValue(structure)) {
  20356. writer.indent(() => {
  20357. structurePrinterFactory.forTypeElementMemberedNode().printText(writer, structure);
  20358. });
  20359. }
  20360. writer.write("}");
  20361. };
  20362. }
  20363. static unionType(firstType, secondType, ...additionalTypes) {
  20364. return getWriteFunctionForUnionOrIntersectionType("|", [firstType, secondType, ...additionalTypes]);
  20365. }
  20366. static intersectionType(firstType, secondType, ...additionalTypes) {
  20367. return getWriteFunctionForUnionOrIntersectionType("&", [firstType, secondType, ...additionalTypes]);
  20368. }
  20369. static assertion(type, assertionType) {
  20370. return (writer) => {
  20371. writeValue(writer, type);
  20372. writer.spaceIfLastNot().write("as ");
  20373. writeValue(writer, assertionType);
  20374. };
  20375. }
  20376. static returnStatement(value) {
  20377. return (writer) => {
  20378. writer.write("return ");
  20379. writer.hangingIndentUnlessBlock(() => {
  20380. writeValue(writer, value);
  20381. writer.write(";");
  20382. });
  20383. };
  20384. }
  20385. }
  20386. function getWriteFunctionForUnionOrIntersectionType(separator, args) {
  20387. return (writer) => {
  20388. writeSeparatedByString(writer, ` ${separator} `, args);
  20389. };
  20390. }
  20391. function anyPropertyHasValue(obj) {
  20392. for (const key of Object.keys(obj)) {
  20393. if (obj[key] == null)
  20394. continue;
  20395. if (obj[key] instanceof Array && obj[key].length === 0)
  20396. continue;
  20397. return true;
  20398. }
  20399. return false;
  20400. }
  20401. function writeSeparatedByString(writer, separator, values) {
  20402. for (let i = 0; i < values.length; i++) {
  20403. writer.conditionalWrite(i > 0, separator);
  20404. writeValue(writer, values[i]);
  20405. }
  20406. }
  20407. function writeValue(writer, value) {
  20408. if (value instanceof Function)
  20409. value(writer);
  20410. else
  20411. writer.write(value.toString());
  20412. }
  20413. const { InvalidOperationError, FileNotFoundError, ArgumentError, ArgumentNullOrWhitespaceError, ArgumentOutOfRangeError, ArgumentTypeError, BaseError, DirectoryNotFoundError, NotImplementedError, NotSupportedError, PathNotFoundError, } = common.errors;
  20414. Object.defineProperty(exports, "CompilerOptionsContainer", {
  20415. enumerable: true,
  20416. get: function () { return common.CompilerOptionsContainer; }
  20417. });
  20418. Object.defineProperty(exports, "DiagnosticCategory", {
  20419. enumerable: true,
  20420. get: function () { return common.DiagnosticCategory; }
  20421. });
  20422. Object.defineProperty(exports, "EmitHint", {
  20423. enumerable: true,
  20424. get: function () { return common.EmitHint; }
  20425. });
  20426. Object.defineProperty(exports, "InMemoryFileSystemHost", {
  20427. enumerable: true,
  20428. get: function () { return common.InMemoryFileSystemHost; }
  20429. });
  20430. Object.defineProperty(exports, "LanguageVariant", {
  20431. enumerable: true,
  20432. get: function () { return common.LanguageVariant; }
  20433. });
  20434. Object.defineProperty(exports, "ModuleKind", {
  20435. enumerable: true,
  20436. get: function () { return common.ModuleKind; }
  20437. });
  20438. Object.defineProperty(exports, "ModuleResolutionKind", {
  20439. enumerable: true,
  20440. get: function () { return common.ModuleResolutionKind; }
  20441. });
  20442. Object.defineProperty(exports, "NewLineKind", {
  20443. enumerable: true,
  20444. get: function () { return common.NewLineKind; }
  20445. });
  20446. Object.defineProperty(exports, "NodeFlags", {
  20447. enumerable: true,
  20448. get: function () { return common.NodeFlags; }
  20449. });
  20450. Object.defineProperty(exports, "ObjectFlags", {
  20451. enumerable: true,
  20452. get: function () { return common.ObjectFlags; }
  20453. });
  20454. Object.defineProperty(exports, "ResolutionHosts", {
  20455. enumerable: true,
  20456. get: function () { return common.ResolutionHosts; }
  20457. });
  20458. Object.defineProperty(exports, "ScriptKind", {
  20459. enumerable: true,
  20460. get: function () { return common.ScriptKind; }
  20461. });
  20462. Object.defineProperty(exports, "ScriptTarget", {
  20463. enumerable: true,
  20464. get: function () { return common.ScriptTarget; }
  20465. });
  20466. Object.defineProperty(exports, "SettingsContainer", {
  20467. enumerable: true,
  20468. get: function () { return common.SettingsContainer; }
  20469. });
  20470. Object.defineProperty(exports, "SymbolFlags", {
  20471. enumerable: true,
  20472. get: function () { return common.SymbolFlags; }
  20473. });
  20474. Object.defineProperty(exports, "SyntaxKind", {
  20475. enumerable: true,
  20476. get: function () { return common.SyntaxKind; }
  20477. });
  20478. Object.defineProperty(exports, "TypeFlags", {
  20479. enumerable: true,
  20480. get: function () { return common.TypeFlags; }
  20481. });
  20482. Object.defineProperty(exports, "TypeFormatFlags", {
  20483. enumerable: true,
  20484. get: function () { return common.TypeFormatFlags; }
  20485. });
  20486. Object.defineProperty(exports, "ts", {
  20487. enumerable: true,
  20488. get: function () { return common.ts; }
  20489. });
  20490. Object.defineProperty(exports, "CodeBlockWriter", {
  20491. enumerable: true,
  20492. get: function () { return CodeBlockWriter__default.default; }
  20493. });
  20494. exports.AbstractableNode = AbstractableNode;
  20495. exports.AmbientableNode = AmbientableNode;
  20496. exports.ArgumentError = ArgumentError;
  20497. exports.ArgumentNullOrWhitespaceError = ArgumentNullOrWhitespaceError;
  20498. exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError;
  20499. exports.ArgumentTypeError = ArgumentTypeError;
  20500. exports.ArgumentedNode = ArgumentedNode;
  20501. exports.ArrayBindingPattern = ArrayBindingPattern;
  20502. exports.ArrayDestructuringAssignment = ArrayDestructuringAssignment;
  20503. exports.ArrayDestructuringAssignmentBase = ArrayDestructuringAssignmentBase;
  20504. exports.ArrayLiteralExpression = ArrayLiteralExpression;
  20505. exports.ArrayTypeNode = ArrayTypeNode;
  20506. exports.ArrowFunction = ArrowFunction;
  20507. exports.ArrowFunctionBase = ArrowFunctionBase;
  20508. exports.AsExpression = AsExpression;
  20509. exports.AsExpressionBase = AsExpressionBase;
  20510. exports.AssignmentExpression = AssignmentExpression;
  20511. exports.AssignmentExpressionBase = AssignmentExpressionBase;
  20512. exports.AsyncableNode = AsyncableNode;
  20513. exports.AwaitExpression = AwaitExpression;
  20514. exports.AwaitExpressionBase = AwaitExpressionBase;
  20515. exports.AwaitableNode = AwaitableNode;
  20516. exports.BaseError = BaseError;
  20517. exports.BaseExpressionedNode = BaseExpressionedNode;
  20518. exports.BigIntLiteral = BigIntLiteral;
  20519. exports.BigIntLiteralBase = BigIntLiteralBase;
  20520. exports.BinaryExpression = BinaryExpression;
  20521. exports.BinaryExpressionBase = BinaryExpressionBase;
  20522. exports.BindingElement = BindingElement;
  20523. exports.BindingElementBase = BindingElementBase;
  20524. exports.BindingNamedNode = BindingNamedNode;
  20525. exports.Block = Block;
  20526. exports.BlockBase = BlockBase;
  20527. exports.BodiedNode = BodiedNode;
  20528. exports.BodyableNode = BodyableNode;
  20529. exports.BreakStatement = BreakStatement;
  20530. exports.CallExpression = CallExpression;
  20531. exports.CallExpressionBase = CallExpressionBase;
  20532. exports.CallSignatureDeclaration = CallSignatureDeclaration;
  20533. exports.CallSignatureDeclarationBase = CallSignatureDeclarationBase;
  20534. exports.CaseBlock = CaseBlock;
  20535. exports.CaseBlockBase = CaseBlockBase;
  20536. exports.CaseClause = CaseClause;
  20537. exports.CaseClauseBase = CaseClauseBase;
  20538. exports.CatchClause = CatchClause;
  20539. exports.CatchClauseBase = CatchClauseBase;
  20540. exports.ChildOrderableNode = ChildOrderableNode;
  20541. exports.ClassDeclaration = ClassDeclaration;
  20542. exports.ClassDeclarationBase = ClassDeclarationBase;
  20543. exports.ClassElement = ClassElement;
  20544. exports.ClassExpression = ClassExpression;
  20545. exports.ClassExpressionBase = ClassExpressionBase;
  20546. exports.ClassLikeDeclarationBase = ClassLikeDeclarationBase;
  20547. exports.ClassLikeDeclarationBaseSpecific = ClassLikeDeclarationBaseSpecific;
  20548. exports.ClassStaticBlockDeclaration = ClassStaticBlockDeclaration;
  20549. exports.ClassStaticBlockDeclarationBase = ClassStaticBlockDeclarationBase;
  20550. exports.CodeAction = CodeAction;
  20551. exports.CodeFixAction = CodeFixAction;
  20552. exports.CombinedCodeActions = CombinedCodeActions;
  20553. exports.CommaListExpression = CommaListExpression;
  20554. exports.CommaListExpressionBase = CommaListExpressionBase;
  20555. exports.CommentClassElement = CommentClassElement;
  20556. exports.CommentEnumMember = CommentEnumMember;
  20557. exports.CommentObjectLiteralElement = CommentObjectLiteralElement;
  20558. exports.CommentRange = CommentRange;
  20559. exports.CommentStatement = CommentStatement;
  20560. exports.CommentTypeElement = CommentTypeElement;
  20561. exports.CommonIdentifierBase = CommonIdentifierBase;
  20562. exports.CompilerCommentClassElement = CompilerCommentClassElement;
  20563. exports.CompilerCommentEnumMember = CompilerCommentEnumMember;
  20564. exports.CompilerCommentNode = CompilerCommentNode;
  20565. exports.CompilerCommentObjectLiteralElement = CompilerCommentObjectLiteralElement;
  20566. exports.CompilerCommentStatement = CompilerCommentStatement;
  20567. exports.CompilerCommentTypeElement = CompilerCommentTypeElement;
  20568. exports.ComputedPropertyName = ComputedPropertyName;
  20569. exports.ComputedPropertyNameBase = ComputedPropertyNameBase;
  20570. exports.ConditionalExpression = ConditionalExpression;
  20571. exports.ConditionalExpressionBase = ConditionalExpressionBase;
  20572. exports.ConditionalTypeNode = ConditionalTypeNode;
  20573. exports.ConstructSignatureDeclaration = ConstructSignatureDeclaration;
  20574. exports.ConstructSignatureDeclarationBase = ConstructSignatureDeclarationBase;
  20575. exports.ConstructorDeclaration = ConstructorDeclaration;
  20576. exports.ConstructorDeclarationBase = ConstructorDeclarationBase;
  20577. exports.ConstructorDeclarationOverloadBase = ConstructorDeclarationOverloadBase;
  20578. exports.ConstructorTypeNode = ConstructorTypeNode;
  20579. exports.ConstructorTypeNodeBase = ConstructorTypeNodeBase;
  20580. exports.ContinueStatement = ContinueStatement;
  20581. exports.DebuggerStatement = DebuggerStatement;
  20582. exports.DebuggerStatementBase = DebuggerStatementBase;
  20583. exports.DecoratableNode = DecoratableNode;
  20584. exports.Decorator = Decorator;
  20585. exports.DecoratorBase = DecoratorBase;
  20586. exports.DefaultClause = DefaultClause;
  20587. exports.DefaultClauseBase = DefaultClauseBase;
  20588. exports.DefinitionInfo = DefinitionInfo;
  20589. exports.DeleteExpression = DeleteExpression;
  20590. exports.DeleteExpressionBase = DeleteExpressionBase;
  20591. exports.Diagnostic = Diagnostic;
  20592. exports.DiagnosticMessageChain = DiagnosticMessageChain;
  20593. exports.DiagnosticWithLocation = DiagnosticWithLocation;
  20594. exports.Directory = Directory;
  20595. exports.DirectoryEmitResult = DirectoryEmitResult;
  20596. exports.DirectoryNotFoundError = DirectoryNotFoundError;
  20597. exports.DoStatement = DoStatement;
  20598. exports.DoStatementBase = DoStatementBase;
  20599. exports.DocumentSpan = DocumentSpan;
  20600. exports.DotDotDotTokenableNode = DotDotDotTokenableNode;
  20601. exports.ElementAccessExpression = ElementAccessExpression;
  20602. exports.ElementAccessExpressionBase = ElementAccessExpressionBase;
  20603. exports.EmitOutput = EmitOutput;
  20604. exports.EmitResult = EmitResult;
  20605. exports.EmptyStatement = EmptyStatement;
  20606. exports.EmptyStatementBase = EmptyStatementBase;
  20607. exports.EnumDeclaration = EnumDeclaration;
  20608. exports.EnumDeclarationBase = EnumDeclarationBase;
  20609. exports.EnumMember = EnumMember;
  20610. exports.EnumMemberBase = EnumMemberBase;
  20611. exports.ExclamationTokenableNode = ExclamationTokenableNode;
  20612. exports.ExportAssignment = ExportAssignment;
  20613. exports.ExportAssignmentBase = ExportAssignmentBase;
  20614. exports.ExportDeclaration = ExportDeclaration;
  20615. exports.ExportDeclarationBase = ExportDeclarationBase;
  20616. exports.ExportGetableNode = ExportGetableNode;
  20617. exports.ExportSpecifier = ExportSpecifier;
  20618. exports.ExportSpecifierBase = ExportSpecifierBase;
  20619. exports.ExportableNode = ExportableNode;
  20620. exports.Expression = Expression;
  20621. exports.ExpressionStatement = ExpressionStatement;
  20622. exports.ExpressionStatementBase = ExpressionStatementBase;
  20623. exports.ExpressionWithTypeArguments = ExpressionWithTypeArguments;
  20624. exports.ExpressionWithTypeArgumentsBase = ExpressionWithTypeArgumentsBase;
  20625. exports.ExpressionableNode = ExpressionableNode;
  20626. exports.ExpressionedNode = ExpressionedNode;
  20627. exports.ExtendsClauseableNode = ExtendsClauseableNode;
  20628. exports.ExternalModuleReference = ExternalModuleReference;
  20629. exports.ExternalModuleReferenceBase = ExternalModuleReferenceBase;
  20630. exports.FalseLiteral = FalseLiteral;
  20631. exports.FalseLiteralBase = FalseLiteralBase;
  20632. exports.FileNotFoundError = FileNotFoundError;
  20633. exports.FileReference = FileReference;
  20634. exports.FileTextChanges = FileTextChanges;
  20635. exports.ForInStatement = ForInStatement;
  20636. exports.ForInStatementBase = ForInStatementBase;
  20637. exports.ForOfStatement = ForOfStatement;
  20638. exports.ForOfStatementBase = ForOfStatementBase;
  20639. exports.ForStatement = ForStatement;
  20640. exports.ForStatementBase = ForStatementBase;
  20641. exports.FunctionDeclaration = FunctionDeclaration;
  20642. exports.FunctionDeclarationBase = FunctionDeclarationBase;
  20643. exports.FunctionDeclarationOverloadBase = FunctionDeclarationOverloadBase;
  20644. exports.FunctionExpression = FunctionExpression;
  20645. exports.FunctionExpressionBase = FunctionExpressionBase;
  20646. exports.FunctionLikeDeclaration = FunctionLikeDeclaration;
  20647. exports.FunctionOrConstructorTypeNodeBase = FunctionOrConstructorTypeNodeBase;
  20648. exports.FunctionOrConstructorTypeNodeBaseBase = FunctionOrConstructorTypeNodeBaseBase;
  20649. exports.FunctionTypeNode = FunctionTypeNode;
  20650. exports.FunctionTypeNodeBase = FunctionTypeNodeBase;
  20651. exports.GeneratorableNode = GeneratorableNode;
  20652. exports.GetAccessorDeclaration = GetAccessorDeclaration;
  20653. exports.GetAccessorDeclarationBase = GetAccessorDeclarationBase;
  20654. exports.HeritageClause = HeritageClause;
  20655. exports.HeritageClauseableNode = HeritageClauseableNode;
  20656. exports.Identifier = Identifier;
  20657. exports.IdentifierBase = IdentifierBase;
  20658. exports.IfStatement = IfStatement;
  20659. exports.IfStatementBase = IfStatementBase;
  20660. exports.ImplementationLocation = ImplementationLocation;
  20661. exports.ImplementsClauseableNode = ImplementsClauseableNode;
  20662. exports.ImportAttribute = ImportAttribute;
  20663. exports.ImportAttributeBase = ImportAttributeBase;
  20664. exports.ImportAttributeNamedNode = ImportAttributeNamedNode;
  20665. exports.ImportAttributes = ImportAttributes;
  20666. exports.ImportAttributesBase = ImportAttributesBase;
  20667. exports.ImportClause = ImportClause;
  20668. exports.ImportClauseBase = ImportClauseBase;
  20669. exports.ImportDeclaration = ImportDeclaration;
  20670. exports.ImportDeclarationBase = ImportDeclarationBase;
  20671. exports.ImportEqualsDeclaration = ImportEqualsDeclaration;
  20672. exports.ImportEqualsDeclarationBase = ImportEqualsDeclarationBase;
  20673. exports.ImportExpression = ImportExpression;
  20674. exports.ImportExpressionBase = ImportExpressionBase;
  20675. exports.ImportExpressionedNode = ImportExpressionedNode;
  20676. exports.ImportSpecifier = ImportSpecifier;
  20677. exports.ImportSpecifierBase = ImportSpecifierBase;
  20678. exports.ImportTypeNode = ImportTypeNode;
  20679. exports.IndexSignatureDeclaration = IndexSignatureDeclaration;
  20680. exports.IndexSignatureDeclarationBase = IndexSignatureDeclarationBase;
  20681. exports.IndexedAccessTypeNode = IndexedAccessTypeNode;
  20682. exports.InferTypeNode = InferTypeNode;
  20683. exports.InitializerExpressionGetableNode = InitializerExpressionGetableNode;
  20684. exports.InitializerExpressionableNode = InitializerExpressionableNode;
  20685. exports.InterfaceDeclaration = InterfaceDeclaration;
  20686. exports.InterfaceDeclarationBase = InterfaceDeclarationBase;
  20687. exports.IntersectionTypeNode = IntersectionTypeNode;
  20688. exports.InvalidOperationError = InvalidOperationError;
  20689. exports.IterationStatement = IterationStatement;
  20690. exports.JSDoc = JSDoc;
  20691. exports.JSDocAllType = JSDocAllType;
  20692. exports.JSDocAugmentsTag = JSDocAugmentsTag;
  20693. exports.JSDocAuthorTag = JSDocAuthorTag;
  20694. exports.JSDocBase = JSDocBase;
  20695. exports.JSDocCallbackTag = JSDocCallbackTag;
  20696. exports.JSDocClassTag = JSDocClassTag;
  20697. exports.JSDocDeprecatedTag = JSDocDeprecatedTag;
  20698. exports.JSDocEnumTag = JSDocEnumTag;
  20699. exports.JSDocFunctionType = JSDocFunctionType;
  20700. exports.JSDocFunctionTypeBase = JSDocFunctionTypeBase;
  20701. exports.JSDocImplementsTag = JSDocImplementsTag;
  20702. exports.JSDocLink = JSDocLink;
  20703. exports.JSDocLinkCode = JSDocLinkCode;
  20704. exports.JSDocLinkPlain = JSDocLinkPlain;
  20705. exports.JSDocMemberName = JSDocMemberName;
  20706. exports.JSDocNameReference = JSDocNameReference;
  20707. exports.JSDocNamepathType = JSDocNamepathType;
  20708. exports.JSDocNonNullableType = JSDocNonNullableType;
  20709. exports.JSDocNullableType = JSDocNullableType;
  20710. exports.JSDocOptionalType = JSDocOptionalType;
  20711. exports.JSDocOverloadTag = JSDocOverloadTag;
  20712. exports.JSDocOverloadTagBase = JSDocOverloadTagBase;
  20713. exports.JSDocOverrideTag = JSDocOverrideTag;
  20714. exports.JSDocParameterTag = JSDocParameterTag;
  20715. exports.JSDocParameterTagBase = JSDocParameterTagBase;
  20716. exports.JSDocPrivateTag = JSDocPrivateTag;
  20717. exports.JSDocPropertyLikeTag = JSDocPropertyLikeTag;
  20718. exports.JSDocPropertyTag = JSDocPropertyTag;
  20719. exports.JSDocPropertyTagBase = JSDocPropertyTagBase;
  20720. exports.JSDocProtectedTag = JSDocProtectedTag;
  20721. exports.JSDocPublicTag = JSDocPublicTag;
  20722. exports.JSDocReadonlyTag = JSDocReadonlyTag;
  20723. exports.JSDocReturnTag = JSDocReturnTag;
  20724. exports.JSDocReturnTagBase = JSDocReturnTagBase;
  20725. exports.JSDocSatisfiesTag = JSDocSatisfiesTag;
  20726. exports.JSDocSatisfiesTagBase = JSDocSatisfiesTagBase;
  20727. exports.JSDocSeeTag = JSDocSeeTag;
  20728. exports.JSDocSeeTagBase = JSDocSeeTagBase;
  20729. exports.JSDocSignature = JSDocSignature;
  20730. exports.JSDocTag = JSDocTag;
  20731. exports.JSDocTagBase = JSDocTagBase;
  20732. exports.JSDocTagInfo = JSDocTagInfo;
  20733. exports.JSDocTemplateTag = JSDocTemplateTag;
  20734. exports.JSDocTemplateTagBase = JSDocTemplateTagBase;
  20735. exports.JSDocText = JSDocText;
  20736. exports.JSDocThisTag = JSDocThisTag;
  20737. exports.JSDocThisTagBase = JSDocThisTagBase;
  20738. exports.JSDocThrowsTag = JSDocThrowsTag;
  20739. exports.JSDocThrowsTagBase = JSDocThrowsTagBase;
  20740. exports.JSDocType = JSDocType;
  20741. exports.JSDocTypeExpression = JSDocTypeExpression;
  20742. exports.JSDocTypeExpressionableTag = JSDocTypeExpressionableTag;
  20743. exports.JSDocTypeLiteral = JSDocTypeLiteral;
  20744. exports.JSDocTypeParameteredTag = JSDocTypeParameteredTag;
  20745. exports.JSDocTypeTag = JSDocTypeTag;
  20746. exports.JSDocTypedefTag = JSDocTypedefTag;
  20747. exports.JSDocUnknownTag = JSDocUnknownTag;
  20748. exports.JSDocUnknownType = JSDocUnknownType;
  20749. exports.JSDocVariadicType = JSDocVariadicType;
  20750. exports.JSDocableNode = JSDocableNode;
  20751. exports.JsxAttribute = JsxAttribute;
  20752. exports.JsxAttributeBase = JsxAttributeBase;
  20753. exports.JsxAttributedNode = JsxAttributedNode;
  20754. exports.JsxClosingElement = JsxClosingElement;
  20755. exports.JsxClosingElementBase = JsxClosingElementBase;
  20756. exports.JsxClosingFragment = JsxClosingFragment;
  20757. exports.JsxElement = JsxElement;
  20758. exports.JsxElementBase = JsxElementBase;
  20759. exports.JsxExpression = JsxExpression;
  20760. exports.JsxExpressionBase = JsxExpressionBase;
  20761. exports.JsxFragment = JsxFragment;
  20762. exports.JsxNamespacedName = JsxNamespacedName;
  20763. exports.JsxNamespacedNameBase = JsxNamespacedNameBase;
  20764. exports.JsxOpeningElement = JsxOpeningElement;
  20765. exports.JsxOpeningElementBase = JsxOpeningElementBase;
  20766. exports.JsxOpeningFragment = JsxOpeningFragment;
  20767. exports.JsxSelfClosingElement = JsxSelfClosingElement;
  20768. exports.JsxSelfClosingElementBase = JsxSelfClosingElementBase;
  20769. exports.JsxSpreadAttribute = JsxSpreadAttribute;
  20770. exports.JsxSpreadAttributeBase = JsxSpreadAttributeBase;
  20771. exports.JsxTagNamedNode = JsxTagNamedNode;
  20772. exports.JsxText = JsxText;
  20773. exports.JsxTextBase = JsxTextBase;
  20774. exports.LabeledStatement = LabeledStatement;
  20775. exports.LabeledStatementBase = LabeledStatementBase;
  20776. exports.LanguageService = LanguageService;
  20777. exports.LeftHandSideExpression = LeftHandSideExpression;
  20778. exports.LeftHandSideExpressionedNode = LeftHandSideExpressionedNode;
  20779. exports.LiteralExpression = LiteralExpression;
  20780. exports.LiteralExpressionBase = LiteralExpressionBase;
  20781. exports.LiteralLikeNode = LiteralLikeNode;
  20782. exports.LiteralTypeNode = LiteralTypeNode;
  20783. exports.ManipulationError = ManipulationError;
  20784. exports.ManipulationSettingsContainer = ManipulationSettingsContainer;
  20785. exports.MappedTypeNode = MappedTypeNode;
  20786. exports.MemberExpression = MemberExpression;
  20787. exports.MemoryEmitResult = MemoryEmitResult;
  20788. exports.MetaProperty = MetaProperty;
  20789. exports.MetaPropertyBase = MetaPropertyBase;
  20790. exports.MethodDeclaration = MethodDeclaration;
  20791. exports.MethodDeclarationBase = MethodDeclarationBase;
  20792. exports.MethodDeclarationOverloadBase = MethodDeclarationOverloadBase;
  20793. exports.MethodSignature = MethodSignature;
  20794. exports.MethodSignatureBase = MethodSignatureBase;
  20795. exports.ModifierableNode = ModifierableNode;
  20796. exports.ModuleBlock = ModuleBlock;
  20797. exports.ModuleBlockBase = ModuleBlockBase;
  20798. exports.ModuleChildableNode = ModuleChildableNode;
  20799. exports.ModuleDeclaration = ModuleDeclaration;
  20800. exports.ModuleDeclarationBase = ModuleDeclarationBase;
  20801. exports.ModuleNamedNode = ModuleNamedNode;
  20802. exports.ModuledNode = ModuledNode;
  20803. exports.NameableNode = NameableNode;
  20804. exports.NamedExports = NamedExports;
  20805. exports.NamedExportsBase = NamedExportsBase;
  20806. exports.NamedImports = NamedImports;
  20807. exports.NamedImportsBase = NamedImportsBase;
  20808. exports.NamedNode = NamedNode;
  20809. exports.NamedNodeBase = NamedNodeBase;
  20810. exports.NamedTupleMember = NamedTupleMember;
  20811. exports.NamedTupleMemberBase = NamedTupleMemberBase;
  20812. exports.NamespaceExport = NamespaceExport;
  20813. exports.NamespaceExportBase = NamespaceExportBase;
  20814. exports.NamespaceImport = NamespaceImport;
  20815. exports.NamespaceImportBase = NamespaceImportBase;
  20816. exports.NewExpression = NewExpression;
  20817. exports.NewExpressionBase = NewExpressionBase;
  20818. exports.NoSubstitutionTemplateLiteral = NoSubstitutionTemplateLiteral;
  20819. exports.NoSubstitutionTemplateLiteralBase = NoSubstitutionTemplateLiteralBase;
  20820. exports.Node = Node;
  20821. exports.NodeWithTypeArguments = NodeWithTypeArguments;
  20822. exports.NodeWithTypeArgumentsBase = NodeWithTypeArgumentsBase;
  20823. exports.NonNullExpression = NonNullExpression;
  20824. exports.NonNullExpressionBase = NonNullExpressionBase;
  20825. exports.NotEmittedStatement = NotEmittedStatement;
  20826. exports.NotEmittedStatementBase = NotEmittedStatementBase;
  20827. exports.NotImplementedError = NotImplementedError;
  20828. exports.NotSupportedError = NotSupportedError;
  20829. exports.NullLiteral = NullLiteral;
  20830. exports.NullLiteralBase = NullLiteralBase;
  20831. exports.NumericLiteral = NumericLiteral;
  20832. exports.NumericLiteralBase = NumericLiteralBase;
  20833. exports.ObjectBindingPattern = ObjectBindingPattern;
  20834. exports.ObjectDestructuringAssignment = ObjectDestructuringAssignment;
  20835. exports.ObjectDestructuringAssignmentBase = ObjectDestructuringAssignmentBase;
  20836. exports.ObjectLiteralElement = ObjectLiteralElement;
  20837. exports.ObjectLiteralExpression = ObjectLiteralExpression;
  20838. exports.ObjectLiteralExpressionBase = ObjectLiteralExpressionBase;
  20839. exports.OmittedExpression = OmittedExpression;
  20840. exports.OmittedExpressionBase = OmittedExpressionBase;
  20841. exports.OutputFile = OutputFile;
  20842. exports.OverloadableNode = OverloadableNode;
  20843. exports.OverrideableNode = OverrideableNode;
  20844. exports.ParameterDeclaration = ParameterDeclaration;
  20845. exports.ParameterDeclarationBase = ParameterDeclarationBase;
  20846. exports.ParameteredNode = ParameteredNode;
  20847. exports.ParenthesizedExpression = ParenthesizedExpression;
  20848. exports.ParenthesizedExpressionBase = ParenthesizedExpressionBase;
  20849. exports.ParenthesizedTypeNode = ParenthesizedTypeNode;
  20850. exports.PartiallyEmittedExpression = PartiallyEmittedExpression;
  20851. exports.PartiallyEmittedExpressionBase = PartiallyEmittedExpressionBase;
  20852. exports.PathNotFoundError = PathNotFoundError;
  20853. exports.PostfixUnaryExpression = PostfixUnaryExpression;
  20854. exports.PostfixUnaryExpressionBase = PostfixUnaryExpressionBase;
  20855. exports.PrefixUnaryExpression = PrefixUnaryExpression;
  20856. exports.PrefixUnaryExpressionBase = PrefixUnaryExpressionBase;
  20857. exports.PrimaryExpression = PrimaryExpression;
  20858. exports.PrivateIdentifier = PrivateIdentifier;
  20859. exports.PrivateIdentifierBase = PrivateIdentifierBase;
  20860. exports.Program = Program;
  20861. exports.Project = Project;
  20862. exports.PropertyAccessExpression = PropertyAccessExpression;
  20863. exports.PropertyAccessExpressionBase = PropertyAccessExpressionBase;
  20864. exports.PropertyAssignment = PropertyAssignment;
  20865. exports.PropertyAssignmentBase = PropertyAssignmentBase;
  20866. exports.PropertyDeclaration = PropertyDeclaration;
  20867. exports.PropertyDeclarationBase = PropertyDeclarationBase;
  20868. exports.PropertyNamedNode = PropertyNamedNode;
  20869. exports.PropertySignature = PropertySignature;
  20870. exports.PropertySignatureBase = PropertySignatureBase;
  20871. exports.QualifiedName = QualifiedName;
  20872. exports.QuestionDotTokenableNode = QuestionDotTokenableNode;
  20873. exports.QuestionTokenableNode = QuestionTokenableNode;
  20874. exports.ReadonlyableNode = ReadonlyableNode;
  20875. exports.RefactorEditInfo = RefactorEditInfo;
  20876. exports.ReferenceEntry = ReferenceEntry;
  20877. exports.ReferenceFindableNode = ReferenceFindableNode;
  20878. exports.ReferencedSymbol = ReferencedSymbol;
  20879. exports.ReferencedSymbolDefinitionInfo = ReferencedSymbolDefinitionInfo;
  20880. exports.ReferencedSymbolEntry = ReferencedSymbolEntry;
  20881. exports.RegularExpressionLiteral = RegularExpressionLiteral;
  20882. exports.RegularExpressionLiteralBase = RegularExpressionLiteralBase;
  20883. exports.RenameLocation = RenameLocation;
  20884. exports.RenameableNode = RenameableNode;
  20885. exports.RestTypeNode = RestTypeNode;
  20886. exports.ReturnStatement = ReturnStatement;
  20887. exports.ReturnStatementBase = ReturnStatementBase;
  20888. exports.ReturnTypedNode = ReturnTypedNode;
  20889. exports.SatisfiesExpression = SatisfiesExpression;
  20890. exports.SatisfiesExpressionBase = SatisfiesExpressionBase;
  20891. exports.ScopeableNode = ScopeableNode;
  20892. exports.ScopedNode = ScopedNode;
  20893. exports.SetAccessorDeclaration = SetAccessorDeclaration;
  20894. exports.SetAccessorDeclarationBase = SetAccessorDeclarationBase;
  20895. exports.ShorthandPropertyAssignment = ShorthandPropertyAssignment;
  20896. exports.ShorthandPropertyAssignmentBase = ShorthandPropertyAssignmentBase;
  20897. exports.Signature = Signature;
  20898. exports.SignaturedDeclaration = SignaturedDeclaration;
  20899. exports.SourceFile = SourceFile;
  20900. exports.SourceFileBase = SourceFileBase;
  20901. exports.SpreadAssignment = SpreadAssignment;
  20902. exports.SpreadAssignmentBase = SpreadAssignmentBase;
  20903. exports.SpreadElement = SpreadElement;
  20904. exports.SpreadElementBase = SpreadElementBase;
  20905. exports.Statement = Statement;
  20906. exports.StatementBase = StatementBase;
  20907. exports.StatementedNode = StatementedNode;
  20908. exports.StaticableNode = StaticableNode;
  20909. exports.StringLiteral = StringLiteral;
  20910. exports.StringLiteralBase = StringLiteralBase;
  20911. exports.Structure = Structure;
  20912. exports.SuperElementAccessExpression = SuperElementAccessExpression;
  20913. exports.SuperElementAccessExpressionBase = SuperElementAccessExpressionBase;
  20914. exports.SuperExpression = SuperExpression;
  20915. exports.SuperExpressionBase = SuperExpressionBase;
  20916. exports.SuperExpressionedNode = SuperExpressionedNode;
  20917. exports.SuperPropertyAccessExpression = SuperPropertyAccessExpression;
  20918. exports.SuperPropertyAccessExpressionBase = SuperPropertyAccessExpressionBase;
  20919. exports.SwitchStatement = SwitchStatement;
  20920. exports.SwitchStatementBase = SwitchStatementBase;
  20921. exports.Symbol = Symbol;
  20922. exports.SymbolDisplayPart = SymbolDisplayPart;
  20923. exports.SyntaxList = SyntaxList;
  20924. exports.TaggedTemplateExpression = TaggedTemplateExpression;
  20925. exports.TemplateExpression = TemplateExpression;
  20926. exports.TemplateExpressionBase = TemplateExpressionBase;
  20927. exports.TemplateHead = TemplateHead;
  20928. exports.TemplateHeadBase = TemplateHeadBase;
  20929. exports.TemplateLiteralTypeNode = TemplateLiteralTypeNode;
  20930. exports.TemplateMiddle = TemplateMiddle;
  20931. exports.TemplateMiddleBase = TemplateMiddleBase;
  20932. exports.TemplateSpan = TemplateSpan;
  20933. exports.TemplateSpanBase = TemplateSpanBase;
  20934. exports.TemplateTail = TemplateTail;
  20935. exports.TemplateTailBase = TemplateTailBase;
  20936. exports.TextChange = TextChange;
  20937. exports.TextInsertableNode = TextInsertableNode;
  20938. exports.TextRange = TextRange;
  20939. exports.TextSpan = TextSpan;
  20940. exports.ThisExpression = ThisExpression;
  20941. exports.ThisExpressionBase = ThisExpressionBase;
  20942. exports.ThisTypeNode = ThisTypeNode;
  20943. exports.ThrowStatement = ThrowStatement;
  20944. exports.ThrowStatementBase = ThrowStatementBase;
  20945. exports.TrueLiteral = TrueLiteral;
  20946. exports.TrueLiteralBase = TrueLiteralBase;
  20947. exports.TryStatement = TryStatement;
  20948. exports.TryStatementBase = TryStatementBase;
  20949. exports.TupleTypeNode = TupleTypeNode;
  20950. exports.Type = Type;
  20951. exports.TypeAliasDeclaration = TypeAliasDeclaration;
  20952. exports.TypeAliasDeclarationBase = TypeAliasDeclarationBase;
  20953. exports.TypeArgumentedNode = TypeArgumentedNode;
  20954. exports.TypeAssertion = TypeAssertion;
  20955. exports.TypeAssertionBase = TypeAssertionBase;
  20956. exports.TypeChecker = TypeChecker;
  20957. exports.TypeElement = TypeElement;
  20958. exports.TypeElementMemberedNode = TypeElementMemberedNode;
  20959. exports.TypeLiteralNode = TypeLiteralNode;
  20960. exports.TypeLiteralNodeBase = TypeLiteralNodeBase;
  20961. exports.TypeNode = TypeNode;
  20962. exports.TypeOfExpression = TypeOfExpression;
  20963. exports.TypeOfExpressionBase = TypeOfExpressionBase;
  20964. exports.TypeOperatorTypeNode = TypeOperatorTypeNode;
  20965. exports.TypeParameter = TypeParameter;
  20966. exports.TypeParameterDeclaration = TypeParameterDeclaration;
  20967. exports.TypeParameterDeclarationBase = TypeParameterDeclarationBase;
  20968. exports.TypeParameteredNode = TypeParameteredNode;
  20969. exports.TypePredicateNode = TypePredicateNode;
  20970. exports.TypeQueryNode = TypeQueryNode;
  20971. exports.TypeReferenceNode = TypeReferenceNode;
  20972. exports.TypedNode = TypedNode;
  20973. exports.UnaryExpression = UnaryExpression;
  20974. exports.UnaryExpressionedNode = UnaryExpressionedNode;
  20975. exports.UnionTypeNode = UnionTypeNode;
  20976. exports.UnwrappableNode = UnwrappableNode;
  20977. exports.UpdateExpression = UpdateExpression;
  20978. exports.VariableDeclaration = VariableDeclaration;
  20979. exports.VariableDeclarationBase = VariableDeclarationBase;
  20980. exports.VariableDeclarationList = VariableDeclarationList;
  20981. exports.VariableDeclarationListBase = VariableDeclarationListBase;
  20982. exports.VariableStatement = VariableStatement;
  20983. exports.VariableStatementBase = VariableStatementBase;
  20984. exports.VoidExpression = VoidExpression;
  20985. exports.VoidExpressionBase = VoidExpressionBase;
  20986. exports.WhileStatement = WhileStatement;
  20987. exports.WhileStatementBase = WhileStatementBase;
  20988. exports.WithStatement = WithStatement;
  20989. exports.WithStatementBase = WithStatementBase;
  20990. exports.Writers = Writers;
  20991. exports.YieldExpression = YieldExpression;
  20992. exports.YieldExpressionBase = YieldExpressionBase;
  20993. exports.createWrappedNode = createWrappedNode;
  20994. exports.forEachStructureChild = forEachStructureChild;
  20995. exports.getCompilerOptionsFromTsConfig = getCompilerOptionsFromTsConfig;
  20996. exports.getScopeForNode = getScopeForNode;
  20997. exports.insertOverloads = insertOverloads;
  20998. exports.printNode = printNode;
  20999. exports.setScopeForNode = setScopeForNode;