ts-morph.js 462 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087
  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