12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281 |
- 'use strict';
- var obsidian = require('obsidian');
- var extendStatics = function(d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- function __extends(d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- }
- function __awaiter(thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- }
- function __generator(thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- }
- var CardStyle;
- (function (CardStyle) {
- CardStyle[CardStyle["Folder"] = 0] = "Folder";
- CardStyle[CardStyle["Note"] = 1] = "Note";
- CardStyle[CardStyle["Image"] = 2] = "Image";
- })(CardStyle || (CardStyle = {}));
- var CardBlock = (function () {
- function CardBlock() {
- this.style = 'card';
- this.cards = [];
- this.col = -1;
- this.imagePrefix = '';
- }
- CardBlock.prototype.addCard = function (card) {
- this.cards.push(card);
- };
- CardBlock.prototype.clear = function () {
- this.cards = [];
- };
- CardBlock.prototype.getCardNum = function () {
- return this.cards.length;
- };
- CardBlock.prototype.getDocElement = function (app) {
- var cardDiv = document.createElement('div');
- if (this.style == 'strip') {
- cardDiv.addClass('strip-card-band');
- for (var i in this.cards) {
- var cardEl = this.cards[i].getBoxElement(app, this.imagePrefix);
- cardEl.addClass('strip-card-view');
- cardDiv.appendChild(cardEl);
- }
- }
- else {
- cardDiv.addClass('cute-card-band');
- for (var i in this.cards) {
- var cardEl = this.cards[i].getBoxElement(app, this.imagePrefix);
- cardEl.addClass('cute-card-view');
- cardDiv.appendChild(cardEl);
- }
- if (this.col > 0) {
- cardDiv.setAttr('style', "grid-template-columns: repeat(" + this.col + ", 1fr);");
- }
- }
- return cardDiv;
- };
- CardBlock.prototype.getYamlCode = function () {
- var yamlStr = '';
- var nCard = this.getCardNum();
- if (nCard > 0) {
- yamlStr = '\n```ccard\nitems: [';
- for (var i in this.cards) {
- yamlStr += '\n {\n';
- yamlStr += this.cards[i].getYamlCode(' ');
- yamlStr += ' },';
- }
-
- yamlStr = yamlStr.substring(0, yamlStr.length - 1);
- yamlStr += '\n]\n';
- if (this.col > 0) {
- yamlStr += "col: " + this.col + "\n";
- }
- yamlStr += '```\n';
- }
- return yamlStr;
- };
- CardBlock.prototype.fromYamlCards = function (yaml) {
-
- this.fromYamlOptions(yaml);
-
- if (yaml.items) {
- this.clear();
- var allItems = yaml.items;
- for (var i in allItems) {
- var cardInfo = allItems[i];
- if ('title' in cardInfo) {
- var cardItem = new CardItem(cardInfo['title'], CardStyle.Note);
- cardItem.fromDict(cardInfo);
- this.addCard(cardItem);
- }
- }
- }
-
- return (this.getCardNum() > 0);
- };
- CardBlock.prototype.fromYamlOptions = function (yaml) {
- if (yaml.style) {
- this.style = yaml.style;
- }
- if (yaml.col) {
- this.col = yaml.col;
- }
- if (yaml.imagePrefix) {
- this.imagePrefix = yaml.imagePrefix;
- }
- };
- return CardBlock;
- }());
- var CardItem = (function () {
- function CardItem(title, style) {
- this.title = title;
- this.abstract = "No abstract.";
- this.cardStyle = style;
- }
- CardItem.prototype.setHeadText = function (text) {
- this.headText = text;
- };
- CardItem.prototype.setHeadImage = function (linkUrl) {
- this.headImage = linkUrl;
- };
- CardItem.prototype.setTitle = function (title) {
- this.title = title;
- };
- CardItem.prototype.setTitleLink = function (linkUrl) {
- this.titleLink = linkUrl;
- };
- CardItem.prototype.setAbstract = function (abstract) {
- this.abstract = abstract;
- };
- CardItem.prototype.setFootnote = function (footnote) {
- this.footnote = footnote;
- };
- CardItem.prototype.fromDict = function (dict) {
- if ('head' in dict) {
- this.headText = dict['head'];
- if (this.headText == 'Folder') {
- this.cardStyle = CardStyle.Folder;
- }
- else if (this.headText == 'Note') {
- this.cardStyle = CardStyle.Note;
- }
- }
- if ('image' in dict)
- this.headImage = dict['image'];
- if ('link' in dict)
- this.titleLink = dict['link'];
- if ('brief' in dict)
- this.abstract = dict['brief'];
- if ('foot' in dict)
- this.footnote = dict['foot'];
- };
- CardItem.prototype.yamlEscapeQuotes = function (org) {
- return org.replace(/'/gi, "''");
- };
- CardItem.prototype.getYamlCode = function (prefix) {
- var yamlStr = '';
- yamlStr += prefix + "title: '" + this.yamlEscapeQuotes(this.title) + "'";
- if (this.titleLink)
- yamlStr += ",\n" + prefix + "link: '" + this.yamlEscapeQuotes(this.titleLink) + "'";
- if (this.abstract)
- yamlStr += ",\n" + prefix + "brief: '" + this.yamlEscapeQuotes(this.abstract) + "'";
- if (this.footnote)
- yamlStr += ",\n" + prefix + "foot: '" + this.yamlEscapeQuotes(this.footnote) + "'";
- if (this.headImage) {
- yamlStr += ",\n" + prefix + "image: '" + this.yamlEscapeQuotes(this.headImage) + "'";
- }
- else if (this.headText) {
- yamlStr += ",\n" + prefix + "head: '" + this.yamlEscapeQuotes(this.headText) + "'";
- }
- else {
- if (this.cardStyle == CardStyle.Folder) {
- yamlStr += ",\n" + prefix + "head: 'Folder'";
- }
- else if (this.cardStyle == CardStyle.Note) {
- yamlStr += ",\n" + prefix + "head: 'Note'";
- }
- else {
- yamlStr += ",\n" + prefix + "head: 'Card'";
- }
- }
- yamlStr += '\n';
- return yamlStr;
- };
- CardItem.prototype.getBoxElement = function (app, imagePrefix) {
- var cardEl = document.createElement('div');
-
- var headEl = cardEl.appendChild(document.createElement('div'));
- if (this.headImage) {
- this.cardStyle = CardStyle.Image;
- if (this.headImage.startsWith("#")) {
-
- headEl.addClass('thumb-color');
- headEl.setAttr('style', "background-color: " + this.headImage + ";");
- }
- else if (this.headImage.contains("://")) {
-
- headEl.addClass('thumb');
- headEl.setAttr('style', "background-image: url(" + this.headImage + ");");
- }
- else {
-
- var imageUrl = this.headImage;
- if (imagePrefix.length > 0) {
-
- var urlPathList = imageUrl.split('/').join(' ').trimStart();
- var fixPathList = imagePrefix.split('/').join(' ').trimStart();
- if (!urlPathList.startsWith(fixPathList)) {
- imageUrl = imagePrefix + this.headImage;
- }
- }
- if (!imageUrl.contains('://')) {
- imageUrl = app.vault.adapter.getResourcePath(imageUrl);
- }
- headEl.addClass('thumb');
- headEl.setAttr('style', "background-image: url(" + imageUrl + ");");
- }
- if (this.headText) {
- headEl.textContent = this.headText;
- }
- }
- else if (this.cardStyle == CardStyle.Folder) {
- headEl.addClasses(['thumb-color', 'thumb-color-folder']);
- headEl.textContent = 'Folder';
- }
- else if (this.cardStyle == CardStyle.Note) {
- headEl.addClasses(['thumb-color', 'thumb-color-note']);
- headEl.textContent = 'Note';
- }
-
- var articleEl = cardEl.appendChild(document.createElement('article'));
-
- if (this.titleLink) {
- var titleEl = articleEl.appendChild(document.createElement('a'));
- if (this.titleLink.endsWith('.md')) {
- titleEl.addClass('internal-link');
- }
- titleEl.href = this.titleLink;
- var h1El = document.createElement('h1');
- h1El.textContent = this.title;
- titleEl.appendChild(h1El);
- }
- else {
- var titleEl = articleEl.appendChild(document.createElement('h1'));
- titleEl.textContent = this.title;
- }
-
- var briefEl = articleEl.appendChild(document.createElement('p'));
- briefEl.textContent = this.abstract;
-
- if (this.footnote) {
- var footEl = articleEl.appendChild(document.createElement('span'));
- footEl.textContent = this.footnote;
- }
-
- return cardEl;
- };
- return CardItem;
- }());
- var FolderBrief = (function () {
- function FolderBrief(app) {
- this.app = app;
- this.folderPath = '';
- this.briefMax = 64;
- this.noteOnly = false;
- }
-
- FolderBrief.prototype.yamlFolderBrief = function (yaml) {
- return __awaiter(this, void 0, void 0, function () {
- var folderPath, activeFile, notePath, folderExist, view, briefCards, cardsElem;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- folderPath = '';
- activeFile = this.app.workspace.getActiveFile();
- notePath = activeFile.path;
- if (!yaml.cards.folder) return [3 , 2];
- folderPath = yaml.cards.folder;
- return [4 , this.app.vault.adapter.exists(folderPath)];
- case 1:
- folderExist = _a.sent();
- if (!folderExist)
- folderPath = '';
- return [3 , 3];
- case 2:
- folderPath = activeFile.parent.path;
- _a.label = 3;
- case 3:
- if (!(folderPath.length > 0)) return [3 , 5];
- view = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView);
- if (!view) return [3 , 5];
- return [4 , this.makeBriefCards(folderPath, notePath)];
- case 4:
- briefCards = _a.sent();
- cardsElem = briefCards.getDocElement(this.app);
- return [2 , cardsElem];
- case 5: return [2 , null];
- }
- });
- });
- };
-
- FolderBrief.prototype.makeBriefCards = function (folderPath, activeNotePath) {
- return __awaiter(this, void 0, void 0, function () {
- var cardBlock, pathList, subFolderList, subFileList, i, subFolderPath, noteExists, folderCard, i, subFilePath, noteCard;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- cardBlock = new CardBlock();
- return [4 , this.app.vault.adapter.list(folderPath)];
- case 1:
- pathList = _a.sent();
- subFolderList = pathList.folders;
- subFileList = pathList.files;
- if (!!this.noteOnly) return [3 , 6];
- i = 0;
- _a.label = 2;
- case 2:
- if (!(i < subFolderList.length)) return [3 , 6];
- subFolderPath = subFolderList[i];
- return [4 , this.app.vault.adapter.exists(subFolderPath + '.md')];
- case 3:
- noteExists = _a.sent();
- if (!!noteExists) return [3 , 5];
- return [4 , this.makeFolderCard(folderPath, subFolderPath)];
- case 4:
- folderCard = _a.sent();
- cardBlock.addCard(folderCard);
- _a.label = 5;
- case 5:
- i++;
- return [3 , 2];
- case 6:
- i = 0;
- _a.label = 7;
- case 7:
- if (!(i < subFileList.length)) return [3 , 10];
- subFilePath = subFileList[i];
- if (!subFilePath.endsWith('.md'))
- return [3 , 9];
- if (subFilePath == activeNotePath)
- return [3 , 9];
- return [4 , this.makeNoteCard(folderPath, subFilePath)];
- case 8:
- noteCard = _a.sent();
- cardBlock.addCard(noteCard);
- _a.label = 9;
- case 9:
- i++;
- return [3 , 7];
- case 10:
-
- return [2 , cardBlock];
- }
- });
- });
- };
-
- FolderBrief.prototype.makeFolderCard = function (folderPath, subFolderPath) {
- return __awaiter(this, void 0, void 0, function () {
- var subFolderName, card, subPathList, folderBrief;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- subFolderName = subFolderPath.split('/').pop();
- card = new CardItem(subFolderName, CardStyle.Folder);
- return [4 , this.app.vault.adapter.list(subFolderPath)];
- case 1:
- subPathList = _a.sent();
- folderBrief = 'Contains ';
- folderBrief += subPathList.folders.length.toString() + ' folders, ';
- folderBrief += subPathList.files.length.toString() + ' notes.';
- card.setAbstract(folderBrief);
-
- card.setFootnote(subFolderPath.replace(folderPath + '/', ''));
-
- return [2 , card];
- }
- });
- });
- };
-
- FolderBrief.prototype.makeNoteCard = function (folderPath, notePath) {
- return __awaiter(this, void 0, void 0, function () {
- var noteName, noteTitle, card, file, contentOrg, imageUrl, contentBrief, fileSt, date;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- noteName = notePath.split('/').pop();
- noteTitle = noteName.substring(0, noteName.length - 3);
- card = new CardItem(noteTitle, CardStyle.Note);
- card.setTitleLink(notePath);
- file = this.app.vault.getAbstractFileByPath(notePath);
- if (!(file && file instanceof obsidian.TFile)) return [3 , 2];
- return [4 , this.app.vault.cachedRead(file)];
- case 1:
- contentOrg = _a.sent();
- imageUrl = this.getContentImage(contentOrg, folderPath);
- if (imageUrl.length > 0) {
- card.setHeadImage(imageUrl);
- }
- contentBrief = this.getContentBrief(contentOrg);
- if (contentBrief.length > 0) {
- if (contentBrief.length > this.briefMax) {
- contentBrief = contentBrief.substring(0, this.briefMax);
- contentBrief += '...';
- }
- card.setAbstract(contentBrief);
- }
- fileSt = file;
- if (fileSt.stat) {
- date = new Date(fileSt.stat.mtime);
- card.setFootnote(date.toLocaleString());
- }
- else {
- card.setFootnote(notePath.replace(folderPath + '/', ''));
- }
- _a.label = 2;
- case 2:
-
- return [2 , card];
- }
- });
- });
- };
- FolderBrief.prototype.getContentImage = function (contentOrg, folderPath) {
- var imageUrl = '';
-
- var regexImg = new RegExp('!\\[(.*?)\\]\\((.*?)\\)');
- var match = regexImg.exec(contentOrg);
- if (match != null) {
- imageUrl = match[2];
- }
- else {
-
- var regexImg2 = new RegExp('!\\[\\[(.*?)\\]\\]');
- match = regexImg2.exec(contentOrg);
- if (match != null)
- imageUrl = match[1];
- }
-
- if (imageUrl.length > 0) {
- if (!imageUrl.startsWith('http')) {
- var headPath = folderPath;
- var relativePath = false;
- while (imageUrl.startsWith('../')) {
- imageUrl = imageUrl.substring(3);
- headPath = headPath.substring(0, headPath.lastIndexOf('/'));
- relativePath = true;
- }
- if (relativePath) {
- imageUrl = headPath + '/' + imageUrl;
- }
- imageUrl = imageUrl.replace(/\%20/g, ' ');
-
- }
- }
- return imageUrl;
- };
- FolderBrief.prototype.getContentBrief = function (contentOrg) {
-
- var content = contentOrg.trim();
-
- if (content.startsWith('---\r') || content.startsWith('---\n')) {
- var hPos2 = content.indexOf('---', 4);
- if (hPos2 >= 0 && (content[hPos2 - 1] == '\n' || (content[hPos2 - 1] == '\r'))) {
- content = content.substring(hPos2 + 4).trim();
- }
- }
- content = content
-
-
-
- .replace(/<[^>]*>/g, '')
-
- .replace(/\!\[\[(.*?)\]\]/g, '')
- .replace(/\[\[(.*?)\]\]/g, '$1')
-
- .replace(/\!\[(.*?)\][\[\(].*?[\]\)]/g, '')
-
- .replace(/\[(.*?)\][\[\(].*?[\]\)]/g, '$1')
-
- .replace(/([\*_]{1,3})(\S.*?\S{0,1})\1/g, '$2')
-
- .replace(/\n(>|\>)(.*)/g, '')
-
- .replace(/(```[^\s]*\n[\s\S]*?\n```)/g, '')
-
- .replace(/`(.+?)`/g, '$1')
- .trim();
-
- var contentBrief = '';
- content = '\n' + content + '\n';
- var regexP1 = new RegExp('\n([^\n|^#|^>])([^\n]+)\n', 'g');
- var match = null;
- if ((match = regexP1.exec(content)) !== null) {
- contentBrief = match[1] + match[2];
- }
-
- contentBrief = contentBrief.trim();
-
- if (contentBrief.length == 0) {
- var regexHead = new RegExp('^#{1,6}(?!#)(.*)[\r\n]', 'mg');
- while ((match = regexHead.exec(content)) !== null) {
- contentBrief += match[1] + ', ';
- if (contentBrief.length > this.briefMax) {
- break;
- }
- }
- if (contentBrief.endsWith(', ')) {
- contentBrief = contentBrief.substring(0, contentBrief.length - 2);
- }
- }
-
- return contentBrief;
- };
- return FolderBrief;
- }());
- var NoteFileMethod;
- (function (NoteFileMethod) {
- NoteFileMethod[NoteFileMethod["Index"] = 0] = "Index";
- NoteFileMethod[NoteFileMethod["Inside"] = 1] = "Inside";
- NoteFileMethod[NoteFileMethod["Outside"] = 2] = "Outside";
- })(NoteFileMethod || (NoteFileMethod = {}));
- var FolderNote = (function () {
- function FolderNote(app, methodStr, indexBase) {
- this.app = app;
- this.setMethod(methodStr, indexBase);
- this.emptyPath();
-
- this.filesToRename = [];
- this.filesToRenameSet = false;
- }
-
- FolderNote.prototype.setMethod = function (methodStr, indexBase) {
- if (methodStr == 'index') {
- this.method = NoteFileMethod.Index;
- this.indexBase = indexBase;
- }
- else if (methodStr == 'inside') {
- this.method = NoteFileMethod.Inside;
- }
- else if (methodStr == 'outside') {
- this.method = NoteFileMethod.Outside;
- }
- };
-
- FolderNote.prototype.emptyPath = function () {
- this.folderPath = '';
- this.notePath = '';
- this.noteBase = '';
- };
-
- FolderNote.prototype.setByFolderPath = function (path) {
- this.emptyPath();
- var folderPath = path.trim();
- if (folderPath.length == 0)
- return;
-
- this.folderPath = folderPath;
- var notePaths = this.getFolderNotePath(folderPath);
- this.notePath = notePaths[0];
- this.noteBase = notePaths[1];
- };
-
- FolderNote.prototype.setByNotePath = function (path) {
- this.emptyPath();
- var notePath = path.trim();
- if (notePath.length == 0)
- return;
- if (!notePath.endsWith('.md'))
- return;
-
- this.notePath = notePath;
- this.noteBase = this.getFileBaseName(notePath);
- this.folderPath = this.getNoteFolderPath(notePath);
- };
-
- FolderNote.prototype.setByFolderElement = function (folderItemEl) {
- var folderPath = '';
- var folderName = '';
- var className = folderItemEl.className.toString();
- var folderElem = folderItemEl;
- if (className.contains('nav-folder-title-content')) {
- folderName = folderElem.getText();
- folderElem = folderItemEl.parentElement;
- folderPath = folderElem.attributes.getNamedItem('data-path').textContent;
- }
- else if (className.contains('nav-folder-title')) {
- folderPath = folderItemEl.attributes.getNamedItem('data-path').textContent;
- folderName = folderItemEl.lastElementChild.getText();
- }
-
- if (folderPath.length > 0) {
- var slashLast = folderPath.lastIndexOf('/');
- var folderPathLast = folderPath.split('/').pop();
- if (folderPathLast != folderName) {
- folderPath = folderPath.substring(0, slashLast + 1) + folderName;
- }
- }
-
- this.setByFolderPath(folderPath);
-
- return folderElem;
- };
-
- FolderNote.prototype.getFileBaseName = function (filePath) {
- var baseName = filePath.split('/').pop();
- var dotPos = baseName.lastIndexOf('.');
- if (dotPos > 0)
- baseName = baseName.substring(0, dotPos);
- return baseName;
- };
-
- FolderNote.prototype.getFolderNotePath = function (folderPath) {
- var notePath = '';
- var noteBaseName = this.indexBase;
- if (this.method == NoteFileMethod.Index) {
- notePath = folderPath + '/' + noteBaseName + '.md';
- }
- else {
- noteBaseName = folderPath.split('/').pop();
- if (this.method == NoteFileMethod.Inside) {
- notePath = folderPath + '/' + noteBaseName + '.md';
- }
- else if (this.method == NoteFileMethod.Outside) {
- notePath = folderPath + '.md';
- }
- }
-
- return [notePath, noteBaseName];
- };
-
- FolderNote.prototype.getNoteFolderPath = function (notePath) {
- var folderPath = '';
- if (this.method == NoteFileMethod.Index) {
- folderPath = notePath.substring(0, notePath.lastIndexOf('/'));
- }
- else if (this.method == NoteFileMethod.Inside) {
- folderPath = notePath.substring(0, notePath.lastIndexOf('/'));
- }
- else if (this.method == NoteFileMethod.Outside) {
- folderPath = notePath.substring(0, notePath.length - 3);
- }
- return folderPath;
- };
-
- FolderNote.prototype.isFolderNotePath = function (notePath) {
- return __awaiter(this, void 0, void 0, function () {
- var isFN, noteBaseName, folderPath;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- isFN = false;
- if (!notePath.endsWith('.md'))
- return [2 , false];
- if (!(this.method == NoteFileMethod.Index)) return [3 , 1];
- isFN = notePath.endsWith("/" + this.indexBase + ".md");
- return [3 , 4];
- case 1:
- if (!(this.method == NoteFileMethod.Inside)) return [3 , 2];
- noteBaseName = this.getFileBaseName(notePath);
- if (notePath.endsWith(noteBaseName + '/' + noteBaseName + '.md')) {
- isFN = true;
- }
- return [3 , 4];
- case 2:
- if (!(this.method == NoteFileMethod.Outside)) return [3 , 4];
- folderPath = notePath.substring(0, notePath.length - 3);
- return [4 , this.app.vault.adapter.exists(folderPath)];
- case 3:
- isFN = _a.sent();
- _a.label = 4;
- case 4: return [2 , isFN];
- }
- });
- });
- };
-
- FolderNote.prototype.isFolderNote = function (notePath) {
- return __awaiter(this, void 0, void 0, function () {
- var isFN, noteBaseName, folderPath;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- isFN = false;
- if (!(this.method == NoteFileMethod.Index)) return [3 , 1];
- isFN = notePath.endsWith("/" + this.indexBase + ".md");
- return [3 , 4];
- case 1:
- if (!(this.method == NoteFileMethod.Inside)) return [3 , 2];
- noteBaseName = this.getFileBaseName(notePath);
- isFN = notePath.endsWith(noteBaseName + "/" + noteBaseName + ".md");
- return [3 , 4];
- case 2:
- if (!(this.method == NoteFileMethod.Outside)) return [3 , 4];
- folderPath = notePath.substring(0, notePath.length - 3);
- return [4 , this.app.vault.adapter.exists(folderPath)];
- case 3:
- isFN = _a.sent();
- _a.label = 4;
- case 4: return [2 , isFN];
- }
- });
- });
- };
-
- FolderNote.prototype.openFolderNote = function (folderElem, doCreate) {
- return __awaiter(this, void 0, void 0, function () {
- var folderNoteExists;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 , this.app.vault.adapter.exists(this.notePath)];
- case 1:
- folderNoteExists = _a.sent();
- if (!(!folderNoteExists && doCreate)) return [3 , 3];
- return [4 , this.newFolderNote()];
- case 2:
- _a.sent();
- folderNoteExists = true;
- _a.label = 3;
- case 3:
-
- if (folderNoteExists) {
- this.hideFolderNote(folderElem);
-
- this.app.workspace.openLinkText(this.notePath, '', false, { active: true });
- }
- else if (folderElem.hasClass('has-folder-note')) {
- folderElem.removeClass('has-folder-note');
- }
- return [2 ];
- }
- });
- });
- };
-
- FolderNote.prototype.newFolderNote = function () {
- return __awaiter(this, void 0, void 0, function () {
- var noteInitContent;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 , this.expandContent(this.initContent)];
- case 1:
- noteInitContent = _a.sent();
- return [4 , this.app.vault.adapter.write(this.notePath, noteInitContent)];
- case 2:
- _a.sent();
- return [2 ];
- }
- });
- });
- };
-
- FolderNote.prototype.newNoteFolder = function () {
- return __awaiter(this, void 0, void 0, function () {
- var folderExists, folderPath, folderExists, newNotePath;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!(this.method == NoteFileMethod.Outside)) return [3 , 4];
- return [4 , this.app.vault.adapter.exists(this.folderPath)];
- case 1:
- folderExists = _a.sent();
- if (!!folderExists) return [3 , 3];
- return [4 , this.app.vault.adapter.mkdir(this.folderPath)];
- case 2:
- _a.sent();
- _a.label = 3;
- case 3: return [3 , 8];
- case 4:
- if (!(this.method == NoteFileMethod.Inside)) return [3 , 8];
- folderPath = this.notePath.substring(0, this.notePath.length - 3);
- return [4 , this.app.vault.adapter.exists(folderPath)];
- case 5:
- folderExists = _a.sent();
- if (!!folderExists) return [3 , 8];
- return [4 , this.app.vault.adapter.mkdir(folderPath)];
- case 6:
- _a.sent();
- newNotePath = folderPath + '/' + this.noteBase + '.md';
- return [4 , this.app.vault.adapter.rename(this.notePath, newNotePath)];
- case 7:
- _a.sent();
- this.app.workspace.openLinkText(newNotePath, '', false, { active: true });
- _a.label = 8;
- case 8: return [2 ];
- }
- });
- });
- };
-
- FolderNote.prototype.expandContent = function (template) {
- return __awaiter(this, void 0, void 0, function () {
- var folderName, content, folderBrief, briefCards, briefLiveCode;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- folderName = this.folderPath.split('/').pop();
- content = template
- .replace(/{{FOLDER_NAME}}/g, folderName)
- .replace(/{{FOLDER_PATH}}/g, this.folderPath);
- if (!content.contains('{{FOLDER_BRIEF}}')) return [3 , 2];
- folderBrief = new FolderBrief(this.app);
- return [4 , folderBrief.makeBriefCards(this.folderPath, this.notePath)];
- case 1:
- briefCards = _a.sent();
- content = content.replace('{{FOLDER_BRIEF}}', briefCards.getYamlCode());
- _a.label = 2;
- case 2:
-
- if (content.contains('{{FOLDER_BRIEF_LIVE}}')) {
- briefLiveCode = '\n```ccard\ntype: folder_brief_live\n```\n';
- content = content.replace('{{FOLDER_BRIEF_LIVE}}', briefLiveCode);
- }
- return [2 , content];
- }
- });
- });
- };
-
- FolderNote.prototype.hideFolderNote = function (folderElem) {
-
- var hideSetting = this.hideNoteFile;
- folderElem.addClass('has-folder-note');
- var parentElem = folderElem.parentElement;
- var fileSelector = ':scope > div.nav-folder-children > div.nav-file > div.nav-file-title';
- var isOutsideMethod = (this.method == NoteFileMethod.Outside);
- if (isOutsideMethod) {
- parentElem = parentElem.parentElement;
- fileSelector = ':scope > div.nav-file > div.nav-file-title';
- }
- var noteBase = this.noteBase;
- parentElem.querySelectorAll(fileSelector)
- .forEach(function (fileElem) {
- var fileNodeTitle = fileElem.firstElementChild.textContent;
-
- if (hideSetting && (fileNodeTitle == noteBase)) {
- fileElem.addClass('is-folder-note');
- }
- else if (!isOutsideMethod) {
- fileElem.removeClass('is-folder-note');
- }
-
- });
- };
-
- FolderNote.prototype.getNoteFolderBriefPath = function (notePath) {
- return __awaiter(this, void 0, void 0, function () {
- var folderPath, isFN;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- folderPath = '';
- return [4 , this.isFolderNote(notePath)];
- case 1:
- isFN = _a.sent();
- if (isFN) {
- folderPath = this.getNoteFolderPath(notePath);
- }
- else {
- folderPath = notePath.substring(0, notePath.lastIndexOf('/'));
- }
- return [2 , folderPath];
- }
- });
- });
- };
-
- FolderNote.prototype.deleteFolder = function (pathToDel) {
- return __awaiter(this, void 0, void 0, function () {
- var myNotePath, noteExists;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!(this.method == NoteFileMethod.Outside && !pathToDel.endsWith('.md'))) return [3 , 3];
- myNotePath = pathToDel + '.md';
- return [4 , this.app.vault.adapter.exists(myNotePath)];
- case 1:
- noteExists = _a.sent();
- if (!noteExists) return [3 , 3];
- return [4 , this.app.vault.adapter.trashLocal(myNotePath)];
- case 2:
- _a.sent();
- _a.label = 3;
- case 3: return [2 ];
- }
- });
- });
- };
-
- FolderNote.prototype.syncName = function (newPath, oldPath) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!(this.method == NoteFileMethod.Outside)) return [3 , 2];
- return [4 , this.syncNameOutside(newPath, oldPath)];
- case 1:
- _a.sent();
- return [3 , 4];
- case 2:
- if (!(this.method == NoteFileMethod.Inside)) return [3 , 4];
- return [4 , this.syncNameInside(newPath, oldPath)];
- case 3:
- _a.sent();
- _a.label = 4;
- case 4: return [2 ];
- }
- });
- });
- };
-
- FolderNote.prototype.syncNameOutside = function (newPath, oldPath) {
- return __awaiter(this, void 0, void 0, function () {
- var noteExists, oldNotePaths, newNotePaths, isFN, oldFolderPath, newFolderPath;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!!oldPath.endsWith('.md')) return [3 , 4];
- return [4 , this.app.vault.adapter.exists(oldPath + '.md')];
- case 1:
- noteExists = _a.sent();
- if (!noteExists) return [3 , 3];
- oldNotePaths = this.getFolderNotePath(oldPath);
- newNotePaths = this.getFolderNotePath(newPath.path);
- if (!(oldNotePaths[1] != newNotePaths[1])) return [3 , 3];
- return [4 , this.app.vault.adapter.rename(oldNotePaths[0], newNotePaths[0])];
- case 2:
- _a.sent();
- _a.label = 3;
- case 3: return [3 , 7];
- case 4: return [4 , this.isFolderNote(oldPath)];
- case 5:
- isFN = _a.sent();
- if (!isFN) return [3 , 7];
- oldFolderPath = this.getNoteFolderPath(oldPath);
- newFolderPath = this.getNoteFolderPath(newPath.path);
- return [4 , this.app.vault.adapter.rename(oldFolderPath, newFolderPath)];
- case 6:
- _a.sent();
- _a.label = 7;
- case 7: return [2 ];
- }
- });
- });
- };
-
- FolderNote.prototype.syncNameInside = function (newPath, oldPath) {
- return __awaiter(this, void 0, void 0, function () {
- var oldNotePaths, newNotePaths, oldNotePathNew, noteExists, isFN, oldFolderPath, noteDir, noteBase, newFolderPath;
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!!oldPath.endsWith('.md')) return [3 , 2];
- oldNotePaths = this.getFolderNotePath(oldPath);
- newNotePaths = this.getFolderNotePath(newPath.path);
- oldNotePathNew = newPath.path + '/' + oldNotePaths[1] + '.md';
- return [4 , this.app.vault.adapter.exists(oldNotePathNew)];
- case 1:
- noteExists = _a.sent();
- if (noteExists) {
- if (newNotePaths[0] != oldNotePathNew) {
-
- this.filesToRename.push(oldNotePathNew);
- this.filesToRename.push(newNotePaths[0]);
- }
- }
- return [3 , 4];
- case 2:
- if (!(this.filesToRename.length == 0)) return [3 , 4];
- return [4 , this.isFolderNote(oldPath)];
- case 3:
- isFN = _a.sent();
- if (isFN) {
- oldFolderPath = this.getNoteFolderPath(oldPath);
- noteDir = newPath.path;
- noteDir = noteDir.substring(0, noteDir.lastIndexOf('/'));
- noteDir = noteDir.substring(0, noteDir.lastIndexOf('/'));
- noteBase = newPath.path.split('/').pop();
- noteBase = noteBase.substring(0, noteBase.length - 3);
- newFolderPath = '';
- if (noteDir.length > 0) {
- newFolderPath = noteDir + '/' + noteBase;
- }
- else {
- newFolderPath = noteBase;
- }
-
- if (oldFolderPath != newFolderPath) {
- this.filesToRename.push(oldFolderPath);
- this.filesToRename.push(newFolderPath);
- }
- }
- _a.label = 4;
- case 4:
-
- if (!this.filesToRenameSet && this.filesToRename.length > 0) {
- this.filesToRenameSet = true;
- setTimeout(function () {
-
- if (_this.filesToRename.length) {
- var oldFolderPath = _this.filesToRename[0];
- var newFolderPath = _this.filesToRename[1];
-
-
- _this.app.vault.adapter.rename(oldFolderPath, newFolderPath);
- _this.filesToRename = [];
- _this.filesToRenameSet = false;
- }
- }, 1000);
- }
- return [2 ];
- }
- });
- });
- };
- return FolderNote;
- }());
- function _typeof(obj) {
- "@babel/helpers - typeof";
- if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
- _typeof = function (obj) {
- return typeof obj;
- };
- } else {
- _typeof = function (obj) {
- return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
- };
- }
- return _typeof(obj);
- }
- function _classCallCheck(instance, Constructor) {
- if (!(instance instanceof Constructor)) {
- throw new TypeError("Cannot call a class as a function");
- }
- }
- function _defineProperties(target, props) {
- for (var i = 0; i < props.length; i++) {
- var descriptor = props[i];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, descriptor.key, descriptor);
- }
- }
- function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- return Constructor;
- }
- function _defineProperty(obj, key, value) {
- if (key in obj) {
- Object.defineProperty(obj, key, {
- value: value,
- enumerable: true,
- configurable: true,
- writable: true
- });
- } else {
- obj[key] = value;
- }
- return obj;
- }
- function _inherits(subClass, superClass) {
- if (typeof superClass !== "function" && superClass !== null) {
- throw new TypeError("Super expression must either be null or a function");
- }
- subClass.prototype = Object.create(superClass && superClass.prototype, {
- constructor: {
- value: subClass,
- writable: true,
- configurable: true
- }
- });
- if (superClass) _setPrototypeOf(subClass, superClass);
- }
- function _getPrototypeOf(o) {
- _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
- return o.__proto__ || Object.getPrototypeOf(o);
- };
- return _getPrototypeOf(o);
- }
- function _setPrototypeOf(o, p) {
- _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
- return _setPrototypeOf(o, p);
- }
- function _isNativeReflectConstruct() {
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
- if (Reflect.construct.sham) return false;
- if (typeof Proxy === "function") return true;
- try {
- Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
- return true;
- } catch (e) {
- return false;
- }
- }
- function _construct(Parent, args, Class) {
- if (_isNativeReflectConstruct()) {
- _construct = Reflect.construct;
- } else {
- _construct = function _construct(Parent, args, Class) {
- var a = [null];
- a.push.apply(a, args);
- var Constructor = Function.bind.apply(Parent, a);
- var instance = new Constructor();
- if (Class) _setPrototypeOf(instance, Class.prototype);
- return instance;
- };
- }
- return _construct.apply(null, arguments);
- }
- function _isNativeFunction(fn) {
- return Function.toString.call(fn).indexOf("[native code]") !== -1;
- }
- function _wrapNativeSuper(Class) {
- var _cache = typeof Map === "function" ? new Map() : undefined;
- _wrapNativeSuper = function _wrapNativeSuper(Class) {
- if (Class === null || !_isNativeFunction(Class)) return Class;
- if (typeof Class !== "function") {
- throw new TypeError("Super expression must either be null or a function");
- }
- if (typeof _cache !== "undefined") {
- if (_cache.has(Class)) return _cache.get(Class);
- _cache.set(Class, Wrapper);
- }
- function Wrapper() {
- return _construct(Class, arguments, _getPrototypeOf(this).constructor);
- }
- Wrapper.prototype = Object.create(Class.prototype, {
- constructor: {
- value: Wrapper,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- return _setPrototypeOf(Wrapper, Class);
- };
- return _wrapNativeSuper(Class);
- }
- function _assertThisInitialized(self) {
- if (self === void 0) {
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
- }
- return self;
- }
- function _possibleConstructorReturn(self, call) {
- if (call && (typeof call === "object" || typeof call === "function")) {
- return call;
- }
- return _assertThisInitialized(self);
- }
- function _createSuper(Derived) {
- var hasNativeReflectConstruct = _isNativeReflectConstruct();
- return function () {
- var Super = _getPrototypeOf(Derived),
- result;
- if (hasNativeReflectConstruct) {
- var NewTarget = _getPrototypeOf(this).constructor;
- result = Reflect.construct(Super, arguments, NewTarget);
- } else {
- result = Super.apply(this, arguments);
- }
- return _possibleConstructorReturn(this, result);
- };
- }
- function _superPropBase(object, property) {
- while (!Object.prototype.hasOwnProperty.call(object, property)) {
- object = _getPrototypeOf(object);
- if (object === null) break;
- }
- return object;
- }
- function _get(target, property, receiver) {
- if (typeof Reflect !== "undefined" && Reflect.get) {
- _get = Reflect.get;
- } else {
- _get = function _get(target, property, receiver) {
- var base = _superPropBase(target, property);
- if (!base) return;
- var desc = Object.getOwnPropertyDescriptor(base, property);
- if (desc.get) {
- return desc.get.call(receiver);
- }
- return desc.value;
- };
- }
- return _get(target, property, receiver || target);
- }
- function _slicedToArray(arr, i) {
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
- }
- function _toArray(arr) {
- return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest();
- }
- function _arrayWithHoles(arr) {
- if (Array.isArray(arr)) return arr;
- }
- function _iterableToArray(iter) {
- if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
- }
- function _iterableToArrayLimit(arr, i) {
- if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
- var _arr = [];
- var _n = true;
- var _d = false;
- var _e = undefined;
- try {
- for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
- _arr.push(_s.value);
- if (i && _arr.length === i) break;
- }
- } catch (err) {
- _d = true;
- _e = err;
- } finally {
- try {
- if (!_n && _i["return"] != null) _i["return"]();
- } finally {
- if (_d) throw _e;
- }
- }
- return _arr;
- }
- function _unsupportedIterableToArray(o, minLen) {
- if (!o) return;
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
- var n = Object.prototype.toString.call(o).slice(8, -1);
- if (n === "Object" && o.constructor) n = o.constructor.name;
- if (n === "Map" || n === "Set") return Array.from(o);
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
- }
- function _arrayLikeToArray(arr, len) {
- if (len == null || len > arr.length) len = arr.length;
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
- return arr2;
- }
- function _nonIterableRest() {
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
- }
- function _createForOfIteratorHelper(o) {
- if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
- if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {
- var i = 0;
- var F = function () {};
- return {
- s: F,
- n: function () {
- if (i >= o.length) return {
- done: true
- };
- return {
- done: false,
- value: o[i++]
- };
- },
- e: function (e) {
- throw e;
- },
- f: F
- };
- }
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
- }
- var it,
- normalCompletion = true,
- didErr = false,
- err;
- return {
- s: function () {
- it = o[Symbol.iterator]();
- },
- n: function () {
- var step = it.next();
- normalCompletion = step.done;
- return step;
- },
- e: function (e) {
- didErr = true;
- err = e;
- },
- f: function () {
- try {
- if (!normalCompletion && it.return != null) it.return();
- } finally {
- if (didErr) throw err;
- }
- }
- };
- }
- var Char = {
- ANCHOR: '&',
- COMMENT: '#',
- TAG: '!',
- DIRECTIVES_END: '-',
- DOCUMENT_END: '.'
- };
- var Type = {
- ALIAS: 'ALIAS',
- BLANK_LINE: 'BLANK_LINE',
- BLOCK_FOLDED: 'BLOCK_FOLDED',
- BLOCK_LITERAL: 'BLOCK_LITERAL',
- COMMENT: 'COMMENT',
- DIRECTIVE: 'DIRECTIVE',
- DOCUMENT: 'DOCUMENT',
- FLOW_MAP: 'FLOW_MAP',
- FLOW_SEQ: 'FLOW_SEQ',
- MAP: 'MAP',
- MAP_KEY: 'MAP_KEY',
- MAP_VALUE: 'MAP_VALUE',
- PLAIN: 'PLAIN',
- QUOTE_DOUBLE: 'QUOTE_DOUBLE',
- QUOTE_SINGLE: 'QUOTE_SINGLE',
- SEQ: 'SEQ',
- SEQ_ITEM: 'SEQ_ITEM'
- };
- var defaultTagPrefix = 'tag:yaml.org,2002:';
- var defaultTags = {
- MAP: 'tag:yaml.org,2002:map',
- SEQ: 'tag:yaml.org,2002:seq',
- STR: 'tag:yaml.org,2002:str'
- };
- function findLineStarts(src) {
- var ls = [0];
- var offset = src.indexOf('\n');
- while (offset !== -1) {
- offset += 1;
- ls.push(offset);
- offset = src.indexOf('\n', offset);
- }
- return ls;
- }
- function getSrcInfo(cst) {
- var lineStarts, src;
- if (typeof cst === 'string') {
- lineStarts = findLineStarts(cst);
- src = cst;
- } else {
- if (Array.isArray(cst)) cst = cst[0];
- if (cst && cst.context) {
- if (!cst.lineStarts) cst.lineStarts = findLineStarts(cst.context.src);
- lineStarts = cst.lineStarts;
- src = cst.context.src;
- }
- }
- return {
- lineStarts: lineStarts,
- src: src
- };
- }
- function getLinePos(offset, cst) {
- if (typeof offset !== 'number' || offset < 0) return null;
- var _getSrcInfo = getSrcInfo(cst),
- lineStarts = _getSrcInfo.lineStarts,
- src = _getSrcInfo.src;
- if (!lineStarts || !src || offset > src.length) return null;
- for (var i = 0; i < lineStarts.length; ++i) {
- var start = lineStarts[i];
- if (offset < start) {
- return {
- line: i,
- col: offset - lineStarts[i - 1] + 1
- };
- }
- if (offset === start) return {
- line: i + 1,
- col: 1
- };
- }
- var line = lineStarts.length;
- return {
- line: line,
- col: offset - lineStarts[line - 1] + 1
- };
- }
- function getLine(line, cst) {
- var _getSrcInfo2 = getSrcInfo(cst),
- lineStarts = _getSrcInfo2.lineStarts,
- src = _getSrcInfo2.src;
- if (!lineStarts || !(line >= 1) || line > lineStarts.length) return null;
- var start = lineStarts[line - 1];
- var end = lineStarts[line];
- while (end && end > start && src[end - 1] === '\n') {
- --end;
- }
- return src.slice(start, end);
- }
- function getPrettyContext(_ref, cst) {
- var start = _ref.start,
- end = _ref.end;
- var maxWidth = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 80;
- var src = getLine(start.line, cst);
- if (!src) return null;
- var col = start.col;
- if (src.length > maxWidth) {
- if (col <= maxWidth - 10) {
- src = src.substr(0, maxWidth - 1) + '…';
- } else {
- var halfWidth = Math.round(maxWidth / 2);
- if (src.length > col + halfWidth) src = src.substr(0, col + halfWidth - 1) + '…';
- col -= src.length - maxWidth;
- src = '…' + src.substr(1 - maxWidth);
- }
- }
- var errLen = 1;
- var errEnd = '';
- if (end) {
- if (end.line === start.line && col + (end.col - start.col) <= maxWidth + 1) {
- errLen = end.col - start.col;
- } else {
- errLen = Math.min(src.length + 1, maxWidth) - col;
- errEnd = '…';
- }
- }
- var offset = col > 1 ? ' '.repeat(col - 1) : '';
- var err = '^'.repeat(errLen);
- return "".concat(src, "\n").concat(offset).concat(err).concat(errEnd);
- }
- var Range = function () {
- _createClass(Range, null, [{
- key: "copy",
- value: function copy(orig) {
- return new Range(orig.start, orig.end);
- }
- }]);
- function Range(start, end) {
- _classCallCheck(this, Range);
- this.start = start;
- this.end = end || start;
- }
- _createClass(Range, [{
- key: "isEmpty",
- value: function isEmpty() {
- return typeof this.start !== 'number' || !this.end || this.end <= this.start;
- }
-
- }, {
- key: "setOrigRange",
- value: function setOrigRange(cr, offset) {
- var start = this.start,
- end = this.end;
- if (cr.length === 0 || end <= cr[0]) {
- this.origStart = start;
- this.origEnd = end;
- return offset;
- }
- var i = offset;
- while (i < cr.length) {
- if (cr[i] > start) break;else ++i;
- }
- this.origStart = start + i;
- var nextOffset = i;
- while (i < cr.length) {
-
- if (cr[i] >= end) break;else ++i;
- }
- this.origEnd = end + i;
- return nextOffset;
- }
- }]);
- return Range;
- }();
- var Node = function () {
- _createClass(Node, null, [{
- key: "addStringTerminator",
- value: function addStringTerminator(src, offset, str) {
- if (str[str.length - 1] === '\n') return str;
- var next = Node.endOfWhiteSpace(src, offset);
- return next >= src.length || src[next] === '\n' ? str + '\n' : str;
- }
- }, {
- key: "atDocumentBoundary",
- value: function atDocumentBoundary(src, offset, sep) {
- var ch0 = src[offset];
- if (!ch0) return true;
- var prev = src[offset - 1];
- if (prev && prev !== '\n') return false;
- if (sep) {
- if (ch0 !== sep) return false;
- } else {
- if (ch0 !== Char.DIRECTIVES_END && ch0 !== Char.DOCUMENT_END) return false;
- }
- var ch1 = src[offset + 1];
- var ch2 = src[offset + 2];
- if (ch1 !== ch0 || ch2 !== ch0) return false;
- var ch3 = src[offset + 3];
- return !ch3 || ch3 === '\n' || ch3 === '\t' || ch3 === ' ';
- }
- }, {
- key: "endOfIdentifier",
- value: function endOfIdentifier(src, offset) {
- var ch = src[offset];
- var isVerbatim = ch === '<';
- var notOk = isVerbatim ? ['\n', '\t', ' ', '>'] : ['\n', '\t', ' ', '[', ']', '{', '}', ','];
- while (ch && notOk.indexOf(ch) === -1) {
- ch = src[offset += 1];
- }
- if (isVerbatim && ch === '>') offset += 1;
- return offset;
- }
- }, {
- key: "endOfIndent",
- value: function endOfIndent(src, offset) {
- var ch = src[offset];
- while (ch === ' ') {
- ch = src[offset += 1];
- }
- return offset;
- }
- }, {
- key: "endOfLine",
- value: function endOfLine(src, offset) {
- var ch = src[offset];
- while (ch && ch !== '\n') {
- ch = src[offset += 1];
- }
- return offset;
- }
- }, {
- key: "endOfWhiteSpace",
- value: function endOfWhiteSpace(src, offset) {
- var ch = src[offset];
- while (ch === '\t' || ch === ' ') {
- ch = src[offset += 1];
- }
- return offset;
- }
- }, {
- key: "startOfLine",
- value: function startOfLine(src, offset) {
- var ch = src[offset - 1];
- if (ch === '\n') return offset;
- while (ch && ch !== '\n') {
- ch = src[offset -= 1];
- }
- return offset + 1;
- }
-
- }, {
- key: "endOfBlockIndent",
- value: function endOfBlockIndent(src, indent, lineStart) {
- var inEnd = Node.endOfIndent(src, lineStart);
- if (inEnd > lineStart + indent) {
- return inEnd;
- } else {
- var wsEnd = Node.endOfWhiteSpace(src, inEnd);
- var ch = src[wsEnd];
- if (!ch || ch === '\n') return wsEnd;
- }
- return null;
- }
- }, {
- key: "atBlank",
- value: function atBlank(src, offset, endAsBlank) {
- var ch = src[offset];
- return ch === '\n' || ch === '\t' || ch === ' ' || endAsBlank && !ch;
- }
- }, {
- key: "nextNodeIsIndented",
- value: function nextNodeIsIndented(ch, indentDiff, indicatorAsIndent) {
- if (!ch || indentDiff < 0) return false;
- if (indentDiff > 0) return true;
- return indicatorAsIndent && ch === '-';
- }
- }, {
- key: "normalizeOffset",
- value: function normalizeOffset(src, offset) {
- var ch = src[offset];
- return !ch ? offset : ch !== '\n' && src[offset - 1] === '\n' ? offset - 1 : Node.endOfWhiteSpace(src, offset);
- }
-
- }, {
- key: "foldNewline",
- value: function foldNewline(src, offset, indent) {
- var inCount = 0;
- var error = false;
- var fold = '';
- var ch = src[offset + 1];
- while (ch === ' ' || ch === '\t' || ch === '\n') {
- switch (ch) {
- case '\n':
- inCount = 0;
- offset += 1;
- fold += '\n';
- break;
- case '\t':
- if (inCount <= indent) error = true;
- offset = Node.endOfWhiteSpace(src, offset + 2) - 1;
- break;
- case ' ':
- inCount += 1;
- offset += 1;
- break;
- }
- ch = src[offset + 1];
- }
- if (!fold) fold = ' ';
- if (ch && inCount <= indent) error = true;
- return {
- fold: fold,
- offset: offset,
- error: error
- };
- }
- }]);
- function Node(type, props, context) {
- _classCallCheck(this, Node);
- Object.defineProperty(this, 'context', {
- value: context || null,
- writable: true
- });
- this.error = null;
- this.range = null;
- this.valueRange = null;
- this.props = props || [];
- this.type = type;
- this.value = null;
- }
- _createClass(Node, [{
- key: "getPropValue",
- value: function getPropValue(idx, key, skipKey) {
- if (!this.context) return null;
- var src = this.context.src;
- var prop = this.props[idx];
- return prop && src[prop.start] === key ? src.slice(prop.start + (skipKey ? 1 : 0), prop.end) : null;
- }
- }, {
- key: "commentHasRequiredWhitespace",
- value: function commentHasRequiredWhitespace(start) {
- var src = this.context.src;
- if (this.header && start === this.header.end) return false;
- if (!this.valueRange) return false;
- var end = this.valueRange.end;
- return start !== end || Node.atBlank(src, end - 1);
- }
- }, {
- key: "parseComment",
- value: function parseComment(start) {
- var src = this.context.src;
- if (src[start] === Char.COMMENT) {
- var end = Node.endOfLine(src, start + 1);
- var commentRange = new Range(start, end);
- this.props.push(commentRange);
- return end;
- }
- return start;
- }
-
- }, {
- key: "setOrigRanges",
- value: function setOrigRanges(cr, offset) {
- if (this.range) offset = this.range.setOrigRange(cr, offset);
- if (this.valueRange) this.valueRange.setOrigRange(cr, offset);
- this.props.forEach(function (prop) {
- return prop.setOrigRange(cr, offset);
- });
- return offset;
- }
- }, {
- key: "toString",
- value: function toString() {
- var src = this.context.src,
- range = this.range,
- value = this.value;
- if (value != null) return value;
- var str = src.slice(range.start, range.end);
- return Node.addStringTerminator(src, range.end, str);
- }
- }, {
- key: "anchor",
- get: function get() {
- for (var i = 0; i < this.props.length; ++i) {
- var anchor = this.getPropValue(i, Char.ANCHOR, true);
- if (anchor != null) return anchor;
- }
- return null;
- }
- }, {
- key: "comment",
- get: function get() {
- var comments = [];
- for (var i = 0; i < this.props.length; ++i) {
- var comment = this.getPropValue(i, Char.COMMENT, true);
- if (comment != null) comments.push(comment);
- }
- return comments.length > 0 ? comments.join('\n') : null;
- }
- }, {
- key: "hasComment",
- get: function get() {
- if (this.context) {
- var src = this.context.src;
- for (var i = 0; i < this.props.length; ++i) {
- if (src[this.props[i].start] === Char.COMMENT) return true;
- }
- }
- return false;
- }
- }, {
- key: "hasProps",
- get: function get() {
- if (this.context) {
- var src = this.context.src;
- for (var i = 0; i < this.props.length; ++i) {
- if (src[this.props[i].start] !== Char.COMMENT) return true;
- }
- }
- return false;
- }
- }, {
- key: "includesTrailingLines",
- get: function get() {
- return false;
- }
- }, {
- key: "jsonLike",
- get: function get() {
- var jsonLikeTypes = [Type.FLOW_MAP, Type.FLOW_SEQ, Type.QUOTE_DOUBLE, Type.QUOTE_SINGLE];
- return jsonLikeTypes.indexOf(this.type) !== -1;
- }
- }, {
- key: "rangeAsLinePos",
- get: function get() {
- if (!this.range || !this.context) return undefined;
- var start = getLinePos(this.range.start, this.context.root);
- if (!start) return undefined;
- var end = getLinePos(this.range.end, this.context.root);
- return {
- start: start,
- end: end
- };
- }
- }, {
- key: "rawValue",
- get: function get() {
- if (!this.valueRange || !this.context) return null;
- var _this$valueRange = this.valueRange,
- start = _this$valueRange.start,
- end = _this$valueRange.end;
- return this.context.src.slice(start, end);
- }
- }, {
- key: "tag",
- get: function get() {
- for (var i = 0; i < this.props.length; ++i) {
- var tag = this.getPropValue(i, Char.TAG, false);
- if (tag != null) {
- if (tag[1] === '<') {
- return {
- verbatim: tag.slice(2, -1)
- };
- } else {
-
- var _tag$match = tag.match(/^(.*!)([^!]*)$/),
- _tag$match2 = _slicedToArray(_tag$match, 3);
- _tag$match2[0];
- var handle = _tag$match2[1],
- suffix = _tag$match2[2];
- return {
- handle: handle,
- suffix: suffix
- };
- }
- }
- }
- return null;
- }
- }, {
- key: "valueRangeContainsNewline",
- get: function get() {
- if (!this.valueRange || !this.context) return false;
- var _this$valueRange2 = this.valueRange,
- start = _this$valueRange2.start,
- end = _this$valueRange2.end;
- var src = this.context.src;
- for (var i = start; i < end; ++i) {
- if (src[i] === '\n') return true;
- }
- return false;
- }
- }]);
- return Node;
- }();
- var YAMLError = function (_Error) {
- _inherits(YAMLError, _Error);
- var _super = _createSuper(YAMLError);
- function YAMLError(name, source, message) {
- var _this;
- _classCallCheck(this, YAMLError);
- if (!message || !(source instanceof Node)) throw new Error("Invalid arguments for new ".concat(name));
- _this = _super.call(this);
- _this.name = name;
- _this.message = message;
- _this.source = source;
- return _this;
- }
- _createClass(YAMLError, [{
- key: "makePretty",
- value: function makePretty() {
- if (!this.source) return;
- this.nodeType = this.source.type;
- var cst = this.source.context && this.source.context.root;
- if (typeof this.offset === 'number') {
- this.range = new Range(this.offset, this.offset + 1);
- var start = cst && getLinePos(this.offset, cst);
- if (start) {
- var end = {
- line: start.line,
- col: start.col + 1
- };
- this.linePos = {
- start: start,
- end: end
- };
- }
- delete this.offset;
- } else {
- this.range = this.source.range;
- this.linePos = this.source.rangeAsLinePos;
- }
- if (this.linePos) {
- var _this$linePos$start = this.linePos.start,
- line = _this$linePos$start.line,
- col = _this$linePos$start.col;
- this.message += " at line ".concat(line, ", column ").concat(col);
- var ctx = cst && getPrettyContext(this.linePos, cst);
- if (ctx) this.message += ":\n\n".concat(ctx, "\n");
- }
- delete this.source;
- }
- }]);
- return YAMLError;
- }( _wrapNativeSuper(Error));
- var YAMLReferenceError = function (_YAMLError) {
- _inherits(YAMLReferenceError, _YAMLError);
- var _super2 = _createSuper(YAMLReferenceError);
- function YAMLReferenceError(source, message) {
- _classCallCheck(this, YAMLReferenceError);
- return _super2.call(this, 'YAMLReferenceError', source, message);
- }
- return YAMLReferenceError;
- }(YAMLError);
- var YAMLSemanticError = function (_YAMLError2) {
- _inherits(YAMLSemanticError, _YAMLError2);
- var _super3 = _createSuper(YAMLSemanticError);
- function YAMLSemanticError(source, message) {
- _classCallCheck(this, YAMLSemanticError);
- return _super3.call(this, 'YAMLSemanticError', source, message);
- }
- return YAMLSemanticError;
- }(YAMLError);
- var YAMLSyntaxError = function (_YAMLError3) {
- _inherits(YAMLSyntaxError, _YAMLError3);
- var _super4 = _createSuper(YAMLSyntaxError);
- function YAMLSyntaxError(source, message) {
- _classCallCheck(this, YAMLSyntaxError);
- return _super4.call(this, 'YAMLSyntaxError', source, message);
- }
- return YAMLSyntaxError;
- }(YAMLError);
- var YAMLWarning = function (_YAMLError4) {
- _inherits(YAMLWarning, _YAMLError4);
- var _super5 = _createSuper(YAMLWarning);
- function YAMLWarning(source, message) {
- _classCallCheck(this, YAMLWarning);
- return _super5.call(this, 'YAMLWarning', source, message);
- }
- return YAMLWarning;
- }(YAMLError);
- var PlainValue = function (_Node) {
- _inherits(PlainValue, _Node);
- var _super = _createSuper(PlainValue);
- function PlainValue() {
- _classCallCheck(this, PlainValue);
- return _super.apply(this, arguments);
- }
- _createClass(PlainValue, [{
- key: "parseBlockValue",
- value: function parseBlockValue(start) {
- var _this$context = this.context,
- indent = _this$context.indent,
- inFlow = _this$context.inFlow,
- src = _this$context.src;
- var offset = start;
- var valueEnd = start;
- for (var ch = src[offset]; ch === '\n'; ch = src[offset]) {
- if (Node.atDocumentBoundary(src, offset + 1)) break;
- var end = Node.endOfBlockIndent(src, indent, offset + 1);
- if (end === null || src[end] === '#') break;
- if (src[end] === '\n') {
- offset = end;
- } else {
- valueEnd = PlainValue.endOfLine(src, end, inFlow);
- offset = valueEnd;
- }
- }
- if (this.valueRange.isEmpty()) this.valueRange.start = start;
- this.valueRange.end = valueEnd;
- return valueEnd;
- }
-
- }, {
- key: "parse",
- value: function parse(context, start) {
- this.context = context;
- var inFlow = context.inFlow,
- src = context.src;
- var offset = start;
- var ch = src[offset];
- if (ch && ch !== '#' && ch !== '\n') {
- offset = PlainValue.endOfLine(src, start, inFlow);
- }
- this.valueRange = new Range(start, offset);
- offset = Node.endOfWhiteSpace(src, offset);
- offset = this.parseComment(offset);
- if (!this.hasComment || this.valueRange.isEmpty()) {
- offset = this.parseBlockValue(offset);
- }
- return offset;
- }
- }, {
- key: "strValue",
- get: function get() {
- if (!this.valueRange || !this.context) return null;
- var _this$valueRange = this.valueRange,
- start = _this$valueRange.start,
- end = _this$valueRange.end;
- var src = this.context.src;
- var ch = src[end - 1];
- while (start < end && (ch === '\n' || ch === '\t' || ch === ' ')) {
- ch = src[--end - 1];
- }
- var str = '';
- for (var i = start; i < end; ++i) {
- var _ch = src[i];
- if (_ch === '\n') {
- var _Node$foldNewline = Node.foldNewline(src, i, -1),
- fold = _Node$foldNewline.fold,
- offset = _Node$foldNewline.offset;
- str += fold;
- i = offset;
- } else if (_ch === ' ' || _ch === '\t') {
-
- var wsStart = i;
- var next = src[i + 1];
- while (i < end && (next === ' ' || next === '\t')) {
- i += 1;
- next = src[i + 1];
- }
- if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : _ch;
- } else {
- str += _ch;
- }
- }
- var ch0 = src[start];
- switch (ch0) {
- case '\t':
- {
- var msg = 'Plain value cannot start with a tab character';
- var errors = [new YAMLSemanticError(this, msg)];
- return {
- errors: errors,
- str: str
- };
- }
- case '@':
- case '`':
- {
- var _msg = "Plain value cannot start with reserved character ".concat(ch0);
- var _errors = [new YAMLSemanticError(this, _msg)];
- return {
- errors: _errors,
- str: str
- };
- }
- default:
- return str;
- }
- }
- }], [{
- key: "endOfLine",
- value: function endOfLine(src, start, inFlow) {
- var ch = src[start];
- var offset = start;
- while (ch && ch !== '\n') {
- if (inFlow && (ch === '[' || ch === ']' || ch === '{' || ch === '}' || ch === ',')) break;
- var next = src[offset + 1];
- if (ch === ':' && (!next || next === '\n' || next === '\t' || next === ' ' || inFlow && next === ',')) break;
- if ((ch === ' ' || ch === '\t') && next === '#') break;
- offset += 1;
- ch = next;
- }
- return offset;
- }
- }]);
- return PlainValue;
- }(Node);
- var BlankLine = function (_Node) {
- _inherits(BlankLine, _Node);
- var _super = _createSuper(BlankLine);
- function BlankLine() {
- _classCallCheck(this, BlankLine);
- return _super.call(this, Type.BLANK_LINE);
- }
-
- _createClass(BlankLine, [{
- key: "parse",
-
- value: function parse(context, start) {
- this.context = context;
- this.range = new Range(start, start + 1);
- return start + 1;
- }
- }, {
- key: "includesTrailingLines",
- get: function get() {
-
-
- return true;
- }
- }]);
- return BlankLine;
- }(Node);
- var CollectionItem = function (_Node) {
- _inherits(CollectionItem, _Node);
- var _super = _createSuper(CollectionItem);
- function CollectionItem(type, props) {
- var _this;
- _classCallCheck(this, CollectionItem);
- _this = _super.call(this, type, props);
- _this.node = null;
- return _this;
- }
- _createClass(CollectionItem, [{
- key: "parse",
-
- value: function parse(context, start) {
- this.context = context;
- var parseNode = context.parseNode,
- src = context.src;
- var atLineStart = context.atLineStart,
- lineStart = context.lineStart;
- if (!atLineStart && this.type === Type.SEQ_ITEM) this.error = new YAMLSemanticError(this, 'Sequence items must not have preceding content on the same line');
- var indent = atLineStart ? start - lineStart : context.indent;
- var offset = Node.endOfWhiteSpace(src, start + 1);
- var ch = src[offset];
- var inlineComment = ch === '#';
- var comments = [];
- var blankLine = null;
- while (ch === '\n' || ch === '#') {
- if (ch === '#') {
- var _end = Node.endOfLine(src, offset + 1);
- comments.push(new Range(offset, _end));
- offset = _end;
- } else {
- atLineStart = true;
- lineStart = offset + 1;
- var wsEnd = Node.endOfWhiteSpace(src, lineStart);
- if (src[wsEnd] === '\n' && comments.length === 0) {
- blankLine = new BlankLine();
- lineStart = blankLine.parse({
- src: src
- }, lineStart);
- }
- offset = Node.endOfIndent(src, lineStart);
- }
- ch = src[offset];
- }
- if (Node.nextNodeIsIndented(ch, offset - (lineStart + indent), this.type !== Type.SEQ_ITEM)) {
- this.node = parseNode({
- atLineStart: atLineStart,
- inCollection: false,
- indent: indent,
- lineStart: lineStart,
- parent: this
- }, offset);
- } else if (ch && lineStart > start + 1) {
- offset = lineStart - 1;
- }
- if (this.node) {
- if (blankLine) {
-
-
-
- var items = context.parent.items || context.parent.contents;
- if (items) items.push(blankLine);
- }
- if (comments.length) Array.prototype.push.apply(this.props, comments);
- offset = this.node.range.end;
- } else {
- if (inlineComment) {
- var c = comments[0];
- this.props.push(c);
- offset = c.end;
- } else {
- offset = Node.endOfLine(src, start + 1);
- }
- }
- var end = this.node ? this.node.valueRange.end : offset;
- this.valueRange = new Range(start, end);
- return offset;
- }
- }, {
- key: "setOrigRanges",
- value: function setOrigRanges(cr, offset) {
- offset = _get(_getPrototypeOf(CollectionItem.prototype), "setOrigRanges", this).call(this, cr, offset);
- return this.node ? this.node.setOrigRanges(cr, offset) : offset;
- }
- }, {
- key: "toString",
- value: function toString() {
- var src = this.context.src,
- node = this.node,
- range = this.range,
- value = this.value;
- if (value != null) return value;
- var str = node ? src.slice(range.start, node.range.start) + String(node) : src.slice(range.start, range.end);
- return Node.addStringTerminator(src, range.end, str);
- }
- }, {
- key: "includesTrailingLines",
- get: function get() {
- return !!this.node && this.node.includesTrailingLines;
- }
- }]);
- return CollectionItem;
- }(Node);
- var Comment = function (_Node) {
- _inherits(Comment, _Node);
- var _super = _createSuper(Comment);
- function Comment() {
- _classCallCheck(this, Comment);
- return _super.call(this, Type.COMMENT);
- }
-
- _createClass(Comment, [{
- key: "parse",
- value: function parse(context, start) {
- this.context = context;
- var offset = this.parseComment(start);
- this.range = new Range(start, offset);
- return offset;
- }
- }]);
- return Comment;
- }(Node);
- function grabCollectionEndComments(node) {
- var cnode = node;
- while (cnode instanceof CollectionItem) {
- cnode = cnode.node;
- }
- if (!(cnode instanceof Collection)) return null;
- var len = cnode.items.length;
- var ci = -1;
- for (var i = len - 1; i >= 0; --i) {
- var n = cnode.items[i];
- if (n.type === Type.COMMENT) {
-
- var _n$context = n.context,
- indent = _n$context.indent,
- lineStart = _n$context.lineStart;
- if (indent > 0 && n.range.start >= lineStart + indent) break;
- ci = i;
- } else if (n.type === Type.BLANK_LINE) ci = i;else break;
- }
- if (ci === -1) return null;
- var ca = cnode.items.splice(ci, len - ci);
- var prevEnd = ca[0].range.start;
- while (true) {
- cnode.range.end = prevEnd;
- if (cnode.valueRange && cnode.valueRange.end > prevEnd) cnode.valueRange.end = prevEnd;
- if (cnode === node) break;
- cnode = cnode.context.parent;
- }
- return ca;
- }
- var Collection = function (_Node) {
- _inherits(Collection, _Node);
- var _super = _createSuper(Collection);
- _createClass(Collection, null, [{
- key: "nextContentHasIndent",
- value: function nextContentHasIndent(src, offset, indent) {
- var lineStart = Node.endOfLine(src, offset) + 1;
- offset = Node.endOfWhiteSpace(src, lineStart);
- var ch = src[offset];
- if (!ch) return false;
- if (offset >= lineStart + indent) return true;
- if (ch !== '#' && ch !== '\n') return false;
- return Collection.nextContentHasIndent(src, offset, indent);
- }
- }]);
- function Collection(firstItem) {
- var _this;
- _classCallCheck(this, Collection);
- _this = _super.call(this, firstItem.type === Type.SEQ_ITEM ? Type.SEQ : Type.MAP);
- for (var i = firstItem.props.length - 1; i >= 0; --i) {
- if (firstItem.props[i].start < firstItem.context.lineStart) {
-
- _this.props = firstItem.props.slice(0, i + 1);
- firstItem.props = firstItem.props.slice(i + 1);
- var itemRange = firstItem.props[0] || firstItem.valueRange;
- firstItem.range.start = itemRange.start;
- break;
- }
- }
- _this.items = [firstItem];
- var ec = grabCollectionEndComments(firstItem);
- if (ec) Array.prototype.push.apply(_this.items, ec);
- return _this;
- }
- _createClass(Collection, [{
- key: "parse",
-
- value: function parse(context, start) {
- this.context = context;
- var parseNode = context.parseNode,
- src = context.src;
-
- var lineStart = Node.startOfLine(src, start);
- var firstItem = this.items[0];
-
- firstItem.context.parent = this;
- this.valueRange = Range.copy(firstItem.valueRange);
- var indent = firstItem.range.start - firstItem.context.lineStart;
- var offset = start;
- offset = Node.normalizeOffset(src, offset);
- var ch = src[offset];
- var atLineStart = Node.endOfWhiteSpace(src, lineStart) === offset;
- var prevIncludesTrailingLines = false;
- while (ch) {
- while (ch === '\n' || ch === '#') {
- if (atLineStart && ch === '\n' && !prevIncludesTrailingLines) {
- var blankLine = new BlankLine();
- offset = blankLine.parse({
- src: src
- }, offset);
- this.valueRange.end = offset;
- if (offset >= src.length) {
- ch = null;
- break;
- }
- this.items.push(blankLine);
- offset -= 1;
- } else if (ch === '#') {
- if (offset < lineStart + indent && !Collection.nextContentHasIndent(src, offset, indent)) {
- return offset;
- }
- var comment = new Comment();
- offset = comment.parse({
- indent: indent,
- lineStart: lineStart,
- src: src
- }, offset);
- this.items.push(comment);
- this.valueRange.end = offset;
- if (offset >= src.length) {
- ch = null;
- break;
- }
- }
- lineStart = offset + 1;
- offset = Node.endOfIndent(src, lineStart);
- if (Node.atBlank(src, offset)) {
- var wsEnd = Node.endOfWhiteSpace(src, offset);
- var next = src[wsEnd];
- if (!next || next === '\n' || next === '#') {
- offset = wsEnd;
- }
- }
- ch = src[offset];
- atLineStart = true;
- }
- if (!ch) {
- break;
- }
- if (offset !== lineStart + indent && (atLineStart || ch !== ':')) {
- if (offset < lineStart + indent) {
- if (lineStart > start) offset = lineStart;
- break;
- } else if (!this.error) {
- var msg = 'All collection items must start at the same column';
- this.error = new YAMLSyntaxError(this, msg);
- }
- }
- if (firstItem.type === Type.SEQ_ITEM) {
- if (ch !== '-') {
- if (lineStart > start) offset = lineStart;
- break;
- }
- } else if (ch === '-' && !this.error) {
-
- var _next = src[offset + 1];
- if (!_next || _next === '\n' || _next === '\t' || _next === ' ') {
- var _msg = 'A collection cannot be both a mapping and a sequence';
- this.error = new YAMLSyntaxError(this, _msg);
- }
- }
- var node = parseNode({
- atLineStart: atLineStart,
- inCollection: true,
- indent: indent,
- lineStart: lineStart,
- parent: this
- }, offset);
- if (!node) return offset;
- this.items.push(node);
- this.valueRange.end = node.valueRange.end;
- offset = Node.normalizeOffset(src, node.range.end);
- ch = src[offset];
- atLineStart = false;
- prevIncludesTrailingLines = node.includesTrailingLines;
-
-
- if (ch) {
- var ls = offset - 1;
- var prev = src[ls];
- while (prev === ' ' || prev === '\t') {
- prev = src[--ls];
- }
- if (prev === '\n') {
- lineStart = ls + 1;
- atLineStart = true;
- }
- }
- var ec = grabCollectionEndComments(node);
- if (ec) Array.prototype.push.apply(this.items, ec);
- }
- return offset;
- }
- }, {
- key: "setOrigRanges",
- value: function setOrigRanges(cr, offset) {
- offset = _get(_getPrototypeOf(Collection.prototype), "setOrigRanges", this).call(this, cr, offset);
- this.items.forEach(function (node) {
- offset = node.setOrigRanges(cr, offset);
- });
- return offset;
- }
- }, {
- key: "toString",
- value: function toString() {
- var src = this.context.src,
- items = this.items,
- range = this.range,
- value = this.value;
- if (value != null) return value;
- var str = src.slice(range.start, items[0].range.start) + String(items[0]);
- for (var i = 1; i < items.length; ++i) {
- var item = items[i];
- var _item$context = item.context,
- atLineStart = _item$context.atLineStart,
- indent = _item$context.indent;
- if (atLineStart) for (var _i = 0; _i < indent; ++_i) {
- str += ' ';
- }
- str += String(item);
- }
- return Node.addStringTerminator(src, range.end, str);
- }
- }, {
- key: "includesTrailingLines",
- get: function get() {
- return this.items.length > 0;
- }
- }]);
- return Collection;
- }(Node);
- var Directive = function (_Node) {
- _inherits(Directive, _Node);
- var _super = _createSuper(Directive);
- function Directive() {
- var _this;
- _classCallCheck(this, Directive);
- _this = _super.call(this, Type.DIRECTIVE);
- _this.name = null;
- return _this;
- }
- _createClass(Directive, [{
- key: "parseName",
- value: function parseName(start) {
- var src = this.context.src;
- var offset = start;
- var ch = src[offset];
- while (ch && ch !== '\n' && ch !== '\t' && ch !== ' ') {
- ch = src[offset += 1];
- }
- this.name = src.slice(start, offset);
- return offset;
- }
- }, {
- key: "parseParameters",
- value: function parseParameters(start) {
- var src = this.context.src;
- var offset = start;
- var ch = src[offset];
- while (ch && ch !== '\n' && ch !== '#') {
- ch = src[offset += 1];
- }
- this.valueRange = new Range(start, offset);
- return offset;
- }
- }, {
- key: "parse",
- value: function parse(context, start) {
- this.context = context;
- var offset = this.parseName(start + 1);
- offset = this.parseParameters(offset);
- offset = this.parseComment(offset);
- this.range = new Range(start, offset);
- return offset;
- }
- }, {
- key: "parameters",
- get: function get() {
- var raw = this.rawValue;
- return raw ? raw.trim().split(/[ \t]+/) : [];
- }
- }]);
- return Directive;
- }(Node);
- var Document = function (_Node) {
- _inherits(Document, _Node);
- var _super = _createSuper(Document);
- _createClass(Document, null, [{
- key: "startCommentOrEndBlankLine",
- value: function startCommentOrEndBlankLine(src, start) {
- var offset = Node.endOfWhiteSpace(src, start);
- var ch = src[offset];
- return ch === '#' || ch === '\n' ? offset : start;
- }
- }]);
- function Document() {
- var _this;
- _classCallCheck(this, Document);
- _this = _super.call(this, Type.DOCUMENT);
- _this.directives = null;
- _this.contents = null;
- _this.directivesEndMarker = null;
- _this.documentEndMarker = null;
- return _this;
- }
- _createClass(Document, [{
- key: "parseDirectives",
- value: function parseDirectives(start) {
- var src = this.context.src;
- this.directives = [];
- var atLineStart = true;
- var hasDirectives = false;
- var offset = start;
- while (!Node.atDocumentBoundary(src, offset, Char.DIRECTIVES_END)) {
- offset = Document.startCommentOrEndBlankLine(src, offset);
- switch (src[offset]) {
- case '\n':
- if (atLineStart) {
- var blankLine = new BlankLine();
- offset = blankLine.parse({
- src: src
- }, offset);
- if (offset < src.length) {
- this.directives.push(blankLine);
- }
- } else {
- offset += 1;
- atLineStart = true;
- }
- break;
- case '#':
- {
- var comment = new Comment();
- offset = comment.parse({
- src: src
- }, offset);
- this.directives.push(comment);
- atLineStart = false;
- }
- break;
- case '%':
- {
- var directive = new Directive();
- offset = directive.parse({
- parent: this,
- src: src
- }, offset);
- this.directives.push(directive);
- hasDirectives = true;
- atLineStart = false;
- }
- break;
- default:
- if (hasDirectives) {
- this.error = new YAMLSemanticError(this, 'Missing directives-end indicator line');
- } else if (this.directives.length > 0) {
- this.contents = this.directives;
- this.directives = [];
- }
- return offset;
- }
- }
- if (src[offset]) {
- this.directivesEndMarker = new Range(offset, offset + 3);
- return offset + 3;
- }
- if (hasDirectives) {
- this.error = new YAMLSemanticError(this, 'Missing directives-end indicator line');
- } else if (this.directives.length > 0) {
- this.contents = this.directives;
- this.directives = [];
- }
- return offset;
- }
- }, {
- key: "parseContents",
- value: function parseContents(start) {
- var _this$context = this.context,
- parseNode = _this$context.parseNode,
- src = _this$context.src;
- if (!this.contents) this.contents = [];
- var lineStart = start;
- while (src[lineStart - 1] === '-') {
- lineStart -= 1;
- }
- var offset = Node.endOfWhiteSpace(src, start);
- var atLineStart = lineStart === start;
- this.valueRange = new Range(offset);
- while (!Node.atDocumentBoundary(src, offset, Char.DOCUMENT_END)) {
- switch (src[offset]) {
- case '\n':
- if (atLineStart) {
- var blankLine = new BlankLine();
- offset = blankLine.parse({
- src: src
- }, offset);
- if (offset < src.length) {
- this.contents.push(blankLine);
- }
- } else {
- offset += 1;
- atLineStart = true;
- }
- lineStart = offset;
- break;
- case '#':
- {
- var comment = new Comment();
- offset = comment.parse({
- src: src
- }, offset);
- this.contents.push(comment);
- atLineStart = false;
- }
- break;
- default:
- {
- var iEnd = Node.endOfIndent(src, offset);
- var context = {
- atLineStart: atLineStart,
- indent: -1,
- inFlow: false,
- inCollection: false,
- lineStart: lineStart,
- parent: this
- };
- var node = parseNode(context, iEnd);
- if (!node) return this.valueRange.end = iEnd;
- this.contents.push(node);
- offset = node.range.end;
- atLineStart = false;
- var ec = grabCollectionEndComments(node);
- if (ec) Array.prototype.push.apply(this.contents, ec);
- }
- }
- offset = Document.startCommentOrEndBlankLine(src, offset);
- }
- this.valueRange.end = offset;
- if (src[offset]) {
- this.documentEndMarker = new Range(offset, offset + 3);
- offset += 3;
- if (src[offset]) {
- offset = Node.endOfWhiteSpace(src, offset);
- if (src[offset] === '#') {
- var _comment = new Comment();
- offset = _comment.parse({
- src: src
- }, offset);
- this.contents.push(_comment);
- }
- switch (src[offset]) {
- case '\n':
- offset += 1;
- break;
- case undefined:
- break;
- default:
- this.error = new YAMLSyntaxError(this, 'Document end marker line cannot have a non-comment suffix');
- }
- }
- }
- return offset;
- }
-
- }, {
- key: "parse",
- value: function parse(context, start) {
- context.root = this;
- this.context = context;
- var src = context.src;
- var offset = src.charCodeAt(start) === 0xfeff ? start + 1 : start;
- offset = this.parseDirectives(offset);
- offset = this.parseContents(offset);
- return offset;
- }
- }, {
- key: "setOrigRanges",
- value: function setOrigRanges(cr, offset) {
- offset = _get(_getPrototypeOf(Document.prototype), "setOrigRanges", this).call(this, cr, offset);
- this.directives.forEach(function (node) {
- offset = node.setOrigRanges(cr, offset);
- });
- if (this.directivesEndMarker) offset = this.directivesEndMarker.setOrigRange(cr, offset);
- this.contents.forEach(function (node) {
- offset = node.setOrigRanges(cr, offset);
- });
- if (this.documentEndMarker) offset = this.documentEndMarker.setOrigRange(cr, offset);
- return offset;
- }
- }, {
- key: "toString",
- value: function toString() {
- var contents = this.contents,
- directives = this.directives,
- value = this.value;
- if (value != null) return value;
- var str = directives.join('');
- if (contents.length > 0) {
- if (directives.length > 0 || contents[0].type === Type.COMMENT) str += '---\n';
- str += contents.join('');
- }
- if (str[str.length - 1] !== '\n') str += '\n';
- return str;
- }
- }]);
- return Document;
- }(Node);
- var Alias = function (_Node) {
- _inherits(Alias, _Node);
- var _super = _createSuper(Alias);
- function Alias() {
- _classCallCheck(this, Alias);
- return _super.apply(this, arguments);
- }
- _createClass(Alias, [{
- key: "parse",
-
- value: function parse(context, start) {
- this.context = context;
- var src = context.src;
- var offset = Node.endOfIdentifier(src, start + 1);
- this.valueRange = new Range(start + 1, offset);
- offset = Node.endOfWhiteSpace(src, offset);
- offset = this.parseComment(offset);
- return offset;
- }
- }]);
- return Alias;
- }(Node);
- var Chomp = {
- CLIP: 'CLIP',
- KEEP: 'KEEP',
- STRIP: 'STRIP'
- };
- var BlockValue = function (_Node) {
- _inherits(BlockValue, _Node);
- var _super = _createSuper(BlockValue);
- function BlockValue(type, props) {
- var _this;
- _classCallCheck(this, BlockValue);
- _this = _super.call(this, type, props);
- _this.blockIndent = null;
- _this.chomping = Chomp.CLIP;
- _this.header = null;
- return _this;
- }
- _createClass(BlockValue, [{
- key: "parseBlockHeader",
- value: function parseBlockHeader(start) {
- var src = this.context.src;
- var offset = start + 1;
- var bi = '';
- while (true) {
- var ch = src[offset];
- switch (ch) {
- case '-':
- this.chomping = Chomp.STRIP;
- break;
- case '+':
- this.chomping = Chomp.KEEP;
- break;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- bi += ch;
- break;
- default:
- this.blockIndent = Number(bi) || null;
- this.header = new Range(start, offset);
- return offset;
- }
- offset += 1;
- }
- }
- }, {
- key: "parseBlockValue",
- value: function parseBlockValue(start) {
- var _this$context = this.context,
- indent = _this$context.indent,
- src = _this$context.src;
- var explicit = !!this.blockIndent;
- var offset = start;
- var valueEnd = start;
- var minBlockIndent = 1;
- for (var ch = src[offset]; ch === '\n'; ch = src[offset]) {
- offset += 1;
- if (Node.atDocumentBoundary(src, offset)) break;
- var end = Node.endOfBlockIndent(src, indent, offset);
- if (end === null) break;
- var _ch = src[end];
- var lineIndent = end - (offset + indent);
- if (!this.blockIndent) {
-
- if (src[end] !== '\n') {
-
- if (lineIndent < minBlockIndent) {
- var msg = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';
- this.error = new YAMLSemanticError(this, msg);
- }
- this.blockIndent = lineIndent;
- } else if (lineIndent > minBlockIndent) {
-
- minBlockIndent = lineIndent;
- }
- } else if (_ch && _ch !== '\n' && lineIndent < this.blockIndent) {
- if (src[end] === '#') break;
- if (!this.error) {
- var _src = explicit ? 'explicit indentation indicator' : 'first line';
- var _msg = "Block scalars must not be less indented than their ".concat(_src);
- this.error = new YAMLSemanticError(this, _msg);
- }
- }
- if (src[end] === '\n') {
- offset = end;
- } else {
- offset = valueEnd = Node.endOfLine(src, end);
- }
- }
- if (this.chomping !== Chomp.KEEP) {
- offset = src[valueEnd] ? valueEnd + 1 : valueEnd;
- }
- this.valueRange = new Range(start + 1, offset);
- return offset;
- }
-
- }, {
- key: "parse",
- value: function parse(context, start) {
- this.context = context;
- var src = context.src;
- var offset = this.parseBlockHeader(start);
- offset = Node.endOfWhiteSpace(src, offset);
- offset = this.parseComment(offset);
- offset = this.parseBlockValue(offset);
- return offset;
- }
- }, {
- key: "setOrigRanges",
- value: function setOrigRanges(cr, offset) {
- offset = _get(_getPrototypeOf(BlockValue.prototype), "setOrigRanges", this).call(this, cr, offset);
- return this.header ? this.header.setOrigRange(cr, offset) : offset;
- }
- }, {
- key: "includesTrailingLines",
- get: function get() {
- return this.chomping === Chomp.KEEP;
- }
- }, {
- key: "strValue",
- get: function get() {
- if (!this.valueRange || !this.context) return null;
- var _this$valueRange = this.valueRange,
- start = _this$valueRange.start,
- end = _this$valueRange.end;
- var _this$context2 = this.context,
- indent = _this$context2.indent,
- src = _this$context2.src;
- if (this.valueRange.isEmpty()) return '';
- var lastNewLine = null;
- var ch = src[end - 1];
- while (ch === '\n' || ch === '\t' || ch === ' ') {
- end -= 1;
- if (end <= start) {
- if (this.chomping === Chomp.KEEP) break;else return '';
- }
- if (ch === '\n') lastNewLine = end;
- ch = src[end - 1];
- }
- var keepStart = end + 1;
- if (lastNewLine) {
- if (this.chomping === Chomp.KEEP) {
- keepStart = lastNewLine;
- end = this.valueRange.end;
- } else {
- end = lastNewLine;
- }
- }
- var bi = indent + this.blockIndent;
- var folded = this.type === Type.BLOCK_FOLDED;
- var atStart = true;
- var str = '';
- var sep = '';
- var prevMoreIndented = false;
- for (var i = start; i < end; ++i) {
- for (var j = 0; j < bi; ++j) {
- if (src[i] !== ' ') break;
- i += 1;
- }
- var _ch2 = src[i];
- if (_ch2 === '\n') {
- if (sep === '\n') str += '\n';else sep = '\n';
- } else {
- var lineEnd = Node.endOfLine(src, i);
- var line = src.slice(i, lineEnd);
- i = lineEnd;
- if (folded && (_ch2 === ' ' || _ch2 === '\t') && i < keepStart) {
- if (sep === ' ') sep = '\n';else if (!prevMoreIndented && !atStart && sep === '\n') sep = '\n\n';
- str += sep + line;
- sep = lineEnd < end && src[lineEnd] || '';
- prevMoreIndented = true;
- } else {
- str += sep + line;
- sep = folded && i < keepStart ? ' ' : '\n';
- prevMoreIndented = false;
- }
- if (atStart && line !== '') atStart = false;
- }
- }
- return this.chomping === Chomp.STRIP ? str : str + '\n';
- }
- }]);
- return BlockValue;
- }(Node);
- var FlowCollection = function (_Node) {
- _inherits(FlowCollection, _Node);
- var _super = _createSuper(FlowCollection);
- function FlowCollection(type, props) {
- var _this;
- _classCallCheck(this, FlowCollection);
- _this = _super.call(this, type, props);
- _this.items = null;
- return _this;
- }
- _createClass(FlowCollection, [{
- key: "prevNodeIsJsonLike",
- value: function prevNodeIsJsonLike() {
- var idx = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.items.length;
- var node = this.items[idx - 1];
- return !!node && (node.jsonLike || node.type === Type.COMMENT && this.prevNodeIsJsonLike(idx - 1));
- }
-
- }, {
- key: "parse",
- value: function parse(context, start) {
- this.context = context;
- var parseNode = context.parseNode,
- src = context.src;
- var indent = context.indent,
- lineStart = context.lineStart;
- var char = src[start];
- this.items = [{
- char: char,
- offset: start
- }];
- var offset = Node.endOfWhiteSpace(src, start + 1);
- char = src[offset];
- while (char && char !== ']' && char !== '}') {
- switch (char) {
- case '\n':
- {
- lineStart = offset + 1;
- var wsEnd = Node.endOfWhiteSpace(src, lineStart);
- if (src[wsEnd] === '\n') {
- var blankLine = new BlankLine();
- lineStart = blankLine.parse({
- src: src
- }, lineStart);
- this.items.push(blankLine);
- }
- offset = Node.endOfIndent(src, lineStart);
- if (offset <= lineStart + indent) {
- char = src[offset];
- if (offset < lineStart + indent || char !== ']' && char !== '}') {
- var msg = 'Insufficient indentation in flow collection';
- this.error = new YAMLSemanticError(this, msg);
- }
- }
- }
- break;
- case ',':
- {
- this.items.push({
- char: char,
- offset: offset
- });
- offset += 1;
- }
- break;
- case '#':
- {
- var comment = new Comment();
- offset = comment.parse({
- src: src
- }, offset);
- this.items.push(comment);
- }
- break;
- case '?':
- case ':':
- {
- var next = src[offset + 1];
- if (next === '\n' || next === '\t' || next === ' ' || next === ',' ||
- char === ':' && this.prevNodeIsJsonLike()) {
- this.items.push({
- char: char,
- offset: offset
- });
- offset += 1;
- break;
- }
- }
-
- default:
- {
- var node = parseNode({
- atLineStart: false,
- inCollection: false,
- inFlow: true,
- indent: -1,
- lineStart: lineStart,
- parent: this
- }, offset);
- if (!node) {
-
- this.valueRange = new Range(start, offset);
- return offset;
- }
- this.items.push(node);
- offset = Node.normalizeOffset(src, node.range.end);
- }
- }
- offset = Node.endOfWhiteSpace(src, offset);
- char = src[offset];
- }
- this.valueRange = new Range(start, offset + 1);
- if (char) {
- this.items.push({
- char: char,
- offset: offset
- });
- offset = Node.endOfWhiteSpace(src, offset + 1);
- offset = this.parseComment(offset);
- }
- return offset;
- }
- }, {
- key: "setOrigRanges",
- value: function setOrigRanges(cr, offset) {
- offset = _get(_getPrototypeOf(FlowCollection.prototype), "setOrigRanges", this).call(this, cr, offset);
- this.items.forEach(function (node) {
- if (node instanceof Node) {
- offset = node.setOrigRanges(cr, offset);
- } else if (cr.length === 0) {
- node.origOffset = node.offset;
- } else {
- var i = offset;
- while (i < cr.length) {
- if (cr[i] > node.offset) break;else ++i;
- }
- node.origOffset = node.offset + i;
- offset = i;
- }
- });
- return offset;
- }
- }, {
- key: "toString",
- value: function toString() {
- var src = this.context.src,
- items = this.items,
- range = this.range,
- value = this.value;
- if (value != null) return value;
- var nodes = items.filter(function (item) {
- return item instanceof Node;
- });
- var str = '';
- var prevEnd = range.start;
- nodes.forEach(function (node) {
- var prefix = src.slice(prevEnd, node.range.start);
- prevEnd = node.range.end;
- str += prefix + String(node);
- if (str[str.length - 1] === '\n' && src[prevEnd - 1] !== '\n' && src[prevEnd] === '\n') {
-
-
-
- prevEnd += 1;
- }
- });
- str += src.slice(prevEnd, range.end);
- return Node.addStringTerminator(src, range.end, str);
- }
- }]);
- return FlowCollection;
- }(Node);
- var QuoteDouble = function (_Node) {
- _inherits(QuoteDouble, _Node);
- var _super = _createSuper(QuoteDouble);
- function QuoteDouble() {
- _classCallCheck(this, QuoteDouble);
- return _super.apply(this, arguments);
- }
- _createClass(QuoteDouble, [{
- key: "parseCharCode",
- value: function parseCharCode(offset, length, errors) {
- var src = this.context.src;
- var cc = src.substr(offset, length);
- var ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
- var code = ok ? parseInt(cc, 16) : NaN;
- if (isNaN(code)) {
- errors.push(new YAMLSyntaxError(this, "Invalid escape sequence ".concat(src.substr(offset - 2, length + 2))));
- return src.substr(offset - 2, length + 2);
- }
- return String.fromCodePoint(code);
- }
-
- }, {
- key: "parse",
- value: function parse(context, start) {
- this.context = context;
- var src = context.src;
- var offset = QuoteDouble.endOfQuote(src, start + 1);
- this.valueRange = new Range(start, offset);
- offset = Node.endOfWhiteSpace(src, offset);
- offset = this.parseComment(offset);
- return offset;
- }
- }, {
- key: "strValue",
-
- get: function get() {
- if (!this.valueRange || !this.context) return null;
- var errors = [];
- var _this$valueRange = this.valueRange,
- start = _this$valueRange.start,
- end = _this$valueRange.end;
- var _this$context = this.context,
- indent = _this$context.indent,
- src = _this$context.src;
- if (src[end - 1] !== '"') errors.push(new YAMLSyntaxError(this, 'Missing closing "quote'));
-
- var str = '';
- for (var i = start + 1; i < end - 1; ++i) {
- var ch = src[i];
- if (ch === '\n') {
- if (Node.atDocumentBoundary(src, i + 1)) errors.push(new YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values'));
- var _Node$foldNewline = Node.foldNewline(src, i, indent),
- fold = _Node$foldNewline.fold,
- offset = _Node$foldNewline.offset,
- error = _Node$foldNewline.error;
- str += fold;
- i = offset;
- if (error) errors.push(new YAMLSemanticError(this, 'Multi-line double-quoted string needs to be sufficiently indented'));
- } else if (ch === '\\') {
- i += 1;
- switch (src[i]) {
- case '0':
- str += '\0';
- break;
-
- case 'a':
- str += '\x07';
- break;
-
- case 'b':
- str += '\b';
- break;
-
- case 'e':
- str += '\x1b';
- break;
-
- case 'f':
- str += '\f';
- break;
-
- case 'n':
- str += '\n';
- break;
-
- case 'r':
- str += '\r';
- break;
-
- case 't':
- str += '\t';
- break;
-
- case 'v':
- str += '\v';
- break;
-
- case 'N':
- str += "\x85";
- break;
-
- case '_':
- str += "\xA0";
- break;
-
- case 'L':
- str += "\u2028";
- break;
-
- case 'P':
- str += "\u2029";
- break;
-
- case ' ':
- str += ' ';
- break;
- case '"':
- str += '"';
- break;
- case '/':
- str += '/';
- break;
- case '\\':
- str += '\\';
- break;
- case '\t':
- str += '\t';
- break;
- case 'x':
- str += this.parseCharCode(i + 1, 2, errors);
- i += 2;
- break;
- case 'u':
- str += this.parseCharCode(i + 1, 4, errors);
- i += 4;
- break;
- case 'U':
- str += this.parseCharCode(i + 1, 8, errors);
- i += 8;
- break;
- case '\n':
-
- while (src[i + 1] === ' ' || src[i + 1] === '\t') {
- i += 1;
- }
- break;
- default:
- errors.push(new YAMLSyntaxError(this, "Invalid escape sequence ".concat(src.substr(i - 1, 2))));
- str += '\\' + src[i];
- }
- } else if (ch === ' ' || ch === '\t') {
-
- var wsStart = i;
- var next = src[i + 1];
- while (next === ' ' || next === '\t') {
- i += 1;
- next = src[i + 1];
- }
- if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
- } else {
- str += ch;
- }
- }
- return errors.length > 0 ? {
- errors: errors,
- str: str
- } : str;
- }
- }], [{
- key: "endOfQuote",
- value: function endOfQuote(src, offset) {
- var ch = src[offset];
- while (ch && ch !== '"') {
- offset += ch === '\\' ? 2 : 1;
- ch = src[offset];
- }
- return offset + 1;
- }
- }]);
- return QuoteDouble;
- }(Node);
- var QuoteSingle = function (_Node) {
- _inherits(QuoteSingle, _Node);
- var _super = _createSuper(QuoteSingle);
- function QuoteSingle() {
- _classCallCheck(this, QuoteSingle);
- return _super.apply(this, arguments);
- }
- _createClass(QuoteSingle, [{
- key: "parse",
-
- value: function parse(context, start) {
- this.context = context;
- var src = context.src;
- var offset = QuoteSingle.endOfQuote(src, start + 1);
- this.valueRange = new Range(start, offset);
- offset = Node.endOfWhiteSpace(src, offset);
- offset = this.parseComment(offset);
- return offset;
- }
- }, {
- key: "strValue",
-
- get: function get() {
- if (!this.valueRange || !this.context) return null;
- var errors = [];
- var _this$valueRange = this.valueRange,
- start = _this$valueRange.start,
- end = _this$valueRange.end;
- var _this$context = this.context,
- indent = _this$context.indent,
- src = _this$context.src;
- if (src[end - 1] !== "'") errors.push(new YAMLSyntaxError(this, "Missing closing 'quote"));
- var str = '';
- for (var i = start + 1; i < end - 1; ++i) {
- var ch = src[i];
- if (ch === '\n') {
- if (Node.atDocumentBoundary(src, i + 1)) errors.push(new YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values'));
- var _Node$foldNewline = Node.foldNewline(src, i, indent),
- fold = _Node$foldNewline.fold,
- offset = _Node$foldNewline.offset,
- error = _Node$foldNewline.error;
- str += fold;
- i = offset;
- if (error) errors.push(new YAMLSemanticError(this, 'Multi-line single-quoted string needs to be sufficiently indented'));
- } else if (ch === "'") {
- str += ch;
- i += 1;
- if (src[i] !== "'") errors.push(new YAMLSyntaxError(this, 'Unescaped single quote? This should not happen.'));
- } else if (ch === ' ' || ch === '\t') {
-
- var wsStart = i;
- var next = src[i + 1];
- while (next === ' ' || next === '\t') {
- i += 1;
- next = src[i + 1];
- }
- if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
- } else {
- str += ch;
- }
- }
- return errors.length > 0 ? {
- errors: errors,
- str: str
- } : str;
- }
- }], [{
- key: "endOfQuote",
- value: function endOfQuote(src, offset) {
- var ch = src[offset];
- while (ch) {
- if (ch === "'") {
- if (src[offset + 1] !== "'") break;
- ch = src[offset += 2];
- } else {
- ch = src[offset += 1];
- }
- }
- return offset + 1;
- }
- }]);
- return QuoteSingle;
- }(Node);
- function createNewNode(type, props) {
- switch (type) {
- case Type.ALIAS:
- return new Alias(type, props);
- case Type.BLOCK_FOLDED:
- case Type.BLOCK_LITERAL:
- return new BlockValue(type, props);
- case Type.FLOW_MAP:
- case Type.FLOW_SEQ:
- return new FlowCollection(type, props);
- case Type.MAP_KEY:
- case Type.MAP_VALUE:
- case Type.SEQ_ITEM:
- return new CollectionItem(type, props);
- case Type.COMMENT:
- case Type.PLAIN:
- return new PlainValue(type, props);
- case Type.QUOTE_DOUBLE:
- return new QuoteDouble(type, props);
- case Type.QUOTE_SINGLE:
- return new QuoteSingle(type, props);
-
- default:
- return null;
-
- }
- }
- var ParseContext = function () {
- _createClass(ParseContext, null, [{
- key: "parseType",
- value: function parseType(src, offset, inFlow) {
- switch (src[offset]) {
- case '*':
- return Type.ALIAS;
- case '>':
- return Type.BLOCK_FOLDED;
- case '|':
- return Type.BLOCK_LITERAL;
- case '{':
- return Type.FLOW_MAP;
- case '[':
- return Type.FLOW_SEQ;
- case '?':
- return !inFlow && Node.atBlank(src, offset + 1, true) ? Type.MAP_KEY : Type.PLAIN;
- case ':':
- return !inFlow && Node.atBlank(src, offset + 1, true) ? Type.MAP_VALUE : Type.PLAIN;
- case '-':
- return !inFlow && Node.atBlank(src, offset + 1, true) ? Type.SEQ_ITEM : Type.PLAIN;
- case '"':
- return Type.QUOTE_DOUBLE;
- case "'":
- return Type.QUOTE_SINGLE;
- default:
- return Type.PLAIN;
- }
- }
- }]);
- function ParseContext() {
- var _this = this;
- var orig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
- atLineStart = _ref.atLineStart,
- inCollection = _ref.inCollection,
- inFlow = _ref.inFlow,
- indent = _ref.indent,
- lineStart = _ref.lineStart,
- parent = _ref.parent;
- _classCallCheck(this, ParseContext);
- _defineProperty(this, "parseNode", function (overlay, start) {
- if (Node.atDocumentBoundary(_this.src, start)) return null;
- var context = new ParseContext(_this, overlay);
- var _context$parseProps = context.parseProps(start),
- props = _context$parseProps.props,
- type = _context$parseProps.type,
- valueStart = _context$parseProps.valueStart;
- var node = createNewNode(type, props);
- var offset = node.parse(context, valueStart);
- node.range = new Range(start, offset);
-
- if (offset <= start) {
-
-
- node.error = new Error("Node#parse consumed no characters");
- node.error.parseEnd = offset;
- node.error.source = node;
- node.range.end = start + 1;
- }
- if (context.nodeStartsCollection(node)) {
- if (!node.error && !context.atLineStart && context.parent.type === Type.DOCUMENT) {
- node.error = new YAMLSyntaxError(node, 'Block collection must not have preceding content here (e.g. directives-end indicator)');
- }
- var collection = new Collection(node);
- offset = collection.parse(new ParseContext(context), offset);
- collection.range = new Range(start, offset);
- return collection;
- }
- return node;
- });
- this.atLineStart = atLineStart != null ? atLineStart : orig.atLineStart || false;
- this.inCollection = inCollection != null ? inCollection : orig.inCollection || false;
- this.inFlow = inFlow != null ? inFlow : orig.inFlow || false;
- this.indent = indent != null ? indent : orig.indent;
- this.lineStart = lineStart != null ? lineStart : orig.lineStart;
- this.parent = parent != null ? parent : orig.parent || {};
- this.root = orig.root;
- this.src = orig.src;
- }
- _createClass(ParseContext, [{
- key: "nodeStartsCollection",
- value: function nodeStartsCollection(node) {
- var inCollection = this.inCollection,
- inFlow = this.inFlow,
- src = this.src;
- if (inCollection || inFlow) return false;
- if (node instanceof CollectionItem) return true;
- var offset = node.range.end;
- if (src[offset] === '\n' || src[offset - 1] === '\n') return false;
- offset = Node.endOfWhiteSpace(src, offset);
- return src[offset] === ':';
- }
-
- }, {
- key: "parseProps",
- value: function parseProps(offset) {
- var inFlow = this.inFlow,
- parent = this.parent,
- src = this.src;
- var props = [];
- var lineHasProps = false;
- offset = this.atLineStart ? Node.endOfIndent(src, offset) : Node.endOfWhiteSpace(src, offset);
- var ch = src[offset];
- while (ch === Char.ANCHOR || ch === Char.COMMENT || ch === Char.TAG || ch === '\n') {
- if (ch === '\n') {
- var lineStart = offset + 1;
- var inEnd = Node.endOfIndent(src, lineStart);
- var indentDiff = inEnd - (lineStart + this.indent);
- var noIndicatorAsIndent = parent.type === Type.SEQ_ITEM && parent.context.atLineStart;
- if (!Node.nextNodeIsIndented(src[inEnd], indentDiff, !noIndicatorAsIndent)) break;
- this.atLineStart = true;
- this.lineStart = lineStart;
- lineHasProps = false;
- offset = inEnd;
- } else if (ch === Char.COMMENT) {
- var end = Node.endOfLine(src, offset + 1);
- props.push(new Range(offset, end));
- offset = end;
- } else {
- var _end = Node.endOfIdentifier(src, offset + 1);
- if (ch === Char.TAG && src[_end] === ',' && /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(src.slice(offset + 1, _end + 13))) {
-
-
-
-
- _end = Node.endOfIdentifier(src, _end + 5);
- }
- props.push(new Range(offset, _end));
- lineHasProps = true;
- offset = Node.endOfWhiteSpace(src, _end);
- }
- ch = src[offset];
- }
- if (lineHasProps && ch === ':' && Node.atBlank(src, offset + 1, true)) offset -= 1;
- var type = ParseContext.parseType(src, offset, inFlow);
- return {
- props: props,
- type: type,
- valueStart: offset
- };
- }
-
- }]);
- return ParseContext;
- }();
- function parse(src) {
- var cr = [];
- if (src.indexOf('\r') !== -1) {
- src = src.replace(/\r\n?/g, function (match, offset) {
- if (match.length > 1) cr.push(offset);
- return '\n';
- });
- }
- var documents = [];
- var offset = 0;
- do {
- var doc = new Document();
- var context = new ParseContext({
- src: src
- });
- offset = doc.parse(context, offset);
- documents.push(doc);
- } while (offset < src.length);
- documents.setOrigRanges = function () {
- if (cr.length === 0) return false;
- for (var i = 1; i < cr.length; ++i) {
- cr[i] -= i;
- }
- var crOffset = 0;
- for (var _i = 0; _i < documents.length; ++_i) {
- crOffset = documents[_i].setOrigRanges(cr, crOffset);
- }
- cr.splice(0, cr.length);
- return true;
- };
- documents.toString = function () {
- return documents.join('...\n');
- };
- return documents;
- }
- function addCommentBefore(str, indent, comment) {
- if (!comment) return str;
- var cc = comment.replace(/[\s\S]^/gm, "$&".concat(indent, "#"));
- return "#".concat(cc, "\n").concat(indent).concat(str);
- }
- function addComment(str, indent, comment) {
- return !comment ? str : comment.indexOf('\n') === -1 ? "".concat(str, " #").concat(comment) : "".concat(str, "\n") + comment.replace(/^/gm, "".concat(indent || '', "#"));
- }
- var Node$1 = function Node() {
- _classCallCheck(this, Node);
- };
- function toJSON(value, arg, ctx) {
- if (Array.isArray(value)) return value.map(function (v, i) {
- return toJSON(v, String(i), ctx);
- });
- if (value && typeof value.toJSON === 'function') {
- var anchor = ctx && ctx.anchors && ctx.anchors.get(value);
- if (anchor) ctx.onCreate = function (res) {
- anchor.res = res;
- delete ctx.onCreate;
- };
- var res = value.toJSON(arg, ctx);
- if (anchor && ctx.onCreate) ctx.onCreate(res);
- return res;
- }
- if ((!ctx || !ctx.keep) && typeof value === 'bigint') return Number(value);
- return value;
- }
- var Scalar = function (_Node) {
- _inherits(Scalar, _Node);
- var _super = _createSuper(Scalar);
- function Scalar(value) {
- var _this;
- _classCallCheck(this, Scalar);
- _this = _super.call(this);
- _this.value = value;
- return _this;
- }
- _createClass(Scalar, [{
- key: "toJSON",
- value: function toJSON$1(arg, ctx) {
- return ctx && ctx.keep ? this.value : toJSON(this.value, arg, ctx);
- }
- }, {
- key: "toString",
- value: function toString() {
- return String(this.value);
- }
- }]);
- return Scalar;
- }(Node$1);
- function collectionFromPath(schema, path, value) {
- var v = value;
- for (var i = path.length - 1; i >= 0; --i) {
- var k = path[i];
- var o = Number.isInteger(k) && k >= 0 ? [] : {};
- o[k] = v;
- v = o;
- }
- return schema.createNode(v, false);
- }
- var isEmptyPath = function isEmptyPath(path) {
- return path == null || _typeof(path) === 'object' && path[Symbol.iterator]().next().done;
- };
- var Collection$1 = function (_Node) {
- _inherits(Collection, _Node);
- var _super = _createSuper(Collection);
- function Collection(schema) {
- var _this;
- _classCallCheck(this, Collection);
- _this = _super.call(this);
- _defineProperty(_assertThisInitialized(_this), "items", []);
- _this.schema = schema;
- return _this;
- }
- _createClass(Collection, [{
- key: "addIn",
- value: function addIn(path, value) {
- if (isEmptyPath(path)) this.add(value);else {
- var _path = _toArray(path),
- key = _path[0],
- rest = _path.slice(1);
- var node = this.get(key, true);
- if (node instanceof Collection) node.addIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error("Expected YAML collection at ".concat(key, ". Remaining path: ").concat(rest));
- }
- }
- }, {
- key: "deleteIn",
- value: function deleteIn(_ref) {
- var _ref2 = _toArray(_ref),
- key = _ref2[0],
- rest = _ref2.slice(1);
- if (rest.length === 0) return this.delete(key);
- var node = this.get(key, true);
- if (node instanceof Collection) return node.deleteIn(rest);else throw new Error("Expected YAML collection at ".concat(key, ". Remaining path: ").concat(rest));
- }
- }, {
- key: "getIn",
- value: function getIn(_ref3, keepScalar) {
- var _ref4 = _toArray(_ref3),
- key = _ref4[0],
- rest = _ref4.slice(1);
- var node = this.get(key, true);
- if (rest.length === 0) return !keepScalar && node instanceof Scalar ? node.value : node;else return node instanceof Collection ? node.getIn(rest, keepScalar) : undefined;
- }
- }, {
- key: "hasAllNullValues",
- value: function hasAllNullValues() {
- return this.items.every(function (node) {
- if (!node || node.type !== 'PAIR') return false;
- var n = node.value;
- return n == null || n instanceof Scalar && n.value == null && !n.commentBefore && !n.comment && !n.tag;
- });
- }
- }, {
- key: "hasIn",
- value: function hasIn(_ref5) {
- var _ref6 = _toArray(_ref5),
- key = _ref6[0],
- rest = _ref6.slice(1);
- if (rest.length === 0) return this.has(key);
- var node = this.get(key, true);
- return node instanceof Collection ? node.hasIn(rest) : false;
- }
- }, {
- key: "setIn",
- value: function setIn(_ref7, value) {
- var _ref8 = _toArray(_ref7),
- key = _ref8[0],
- rest = _ref8.slice(1);
- if (rest.length === 0) {
- this.set(key, value);
- } else {
- var node = this.get(key, true);
- if (node instanceof Collection) node.setIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error("Expected YAML collection at ".concat(key, ". Remaining path: ").concat(rest));
- }
- }
-
- }, {
- key: "toJSON",
- value: function toJSON() {
- return null;
- }
- }, {
- key: "toString",
- value: function toString(ctx, _ref9, onComment, onChompKeep) {
- var _this2 = this;
- var blockItem = _ref9.blockItem,
- flowChars = _ref9.flowChars,
- isMap = _ref9.isMap,
- itemIndent = _ref9.itemIndent;
- var _ctx = ctx,
- indent = _ctx.indent,
- indentStep = _ctx.indentStep,
- stringify = _ctx.stringify;
- var inFlow = this.type === Type.FLOW_MAP || this.type === Type.FLOW_SEQ || ctx.inFlow;
- if (inFlow) itemIndent += indentStep;
- var allNullValues = isMap && this.hasAllNullValues();
- ctx = Object.assign({}, ctx, {
- allNullValues: allNullValues,
- indent: itemIndent,
- inFlow: inFlow,
- type: null
- });
- var chompKeep = false;
- var hasItemWithNewLine = false;
- var nodes = this.items.reduce(function (nodes, item, i) {
- var comment;
- if (item) {
- if (!chompKeep && item.spaceBefore) nodes.push({
- type: 'comment',
- str: ''
- });
- if (item.commentBefore) item.commentBefore.match(/^.*$/gm).forEach(function (line) {
- nodes.push({
- type: 'comment',
- str: "#".concat(line)
- });
- });
- if (item.comment) comment = item.comment;
- if (inFlow && (!chompKeep && item.spaceBefore || item.commentBefore || item.comment || item.key && (item.key.commentBefore || item.key.comment) || item.value && (item.value.commentBefore || item.value.comment))) hasItemWithNewLine = true;
- }
- chompKeep = false;
- var str = stringify(item, ctx, function () {
- return comment = null;
- }, function () {
- return chompKeep = true;
- });
- if (inFlow && !hasItemWithNewLine && str.includes('\n')) hasItemWithNewLine = true;
- if (inFlow && i < _this2.items.length - 1) str += ',';
- str = addComment(str, itemIndent, comment);
- if (chompKeep && (comment || inFlow)) chompKeep = false;
- nodes.push({
- type: 'item',
- str: str
- });
- return nodes;
- }, []);
- var str;
- if (nodes.length === 0) {
- str = flowChars.start + flowChars.end;
- } else if (inFlow) {
- var start = flowChars.start,
- end = flowChars.end;
- var strings = nodes.map(function (n) {
- return n.str;
- });
- if (hasItemWithNewLine || strings.reduce(function (sum, str) {
- return sum + str.length + 2;
- }, 2) > Collection.maxFlowStringSingleLineLength) {
- str = start;
- var _iterator = _createForOfIteratorHelper(strings),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var s = _step.value;
- str += s ? "\n".concat(indentStep).concat(indent).concat(s) : '\n';
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- str += "\n".concat(indent).concat(end);
- } else {
- str = "".concat(start, " ").concat(strings.join(' '), " ").concat(end);
- }
- } else {
- var _strings = nodes.map(blockItem);
- str = _strings.shift();
- var _iterator2 = _createForOfIteratorHelper(_strings),
- _step2;
- try {
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
- var _s = _step2.value;
- str += _s ? "\n".concat(indent).concat(_s) : '\n';
- }
- } catch (err) {
- _iterator2.e(err);
- } finally {
- _iterator2.f();
- }
- }
- if (this.comment) {
- str += '\n' + this.comment.replace(/^/gm, "".concat(indent, "#"));
- if (onComment) onComment();
- } else if (chompKeep && onChompKeep) onChompKeep();
- return str;
- }
- }]);
- return Collection;
- }(Node$1);
- _defineProperty(Collection$1, "maxFlowStringSingleLineLength", 60);
- function asItemIndex(key) {
- var idx = key instanceof Scalar ? key.value : key;
- if (idx && typeof idx === 'string') idx = Number(idx);
- return Number.isInteger(idx) && idx >= 0 ? idx : null;
- }
- var YAMLSeq = function (_Collection) {
- _inherits(YAMLSeq, _Collection);
- var _super = _createSuper(YAMLSeq);
- function YAMLSeq() {
- _classCallCheck(this, YAMLSeq);
- return _super.apply(this, arguments);
- }
- _createClass(YAMLSeq, [{
- key: "add",
- value: function add(value) {
- this.items.push(value);
- }
- }, {
- key: "delete",
- value: function _delete(key) {
- var idx = asItemIndex(key);
- if (typeof idx !== 'number') return false;
- var del = this.items.splice(idx, 1);
- return del.length > 0;
- }
- }, {
- key: "get",
- value: function get(key, keepScalar) {
- var idx = asItemIndex(key);
- if (typeof idx !== 'number') return undefined;
- var it = this.items[idx];
- return !keepScalar && it instanceof Scalar ? it.value : it;
- }
- }, {
- key: "has",
- value: function has(key) {
- var idx = asItemIndex(key);
- return typeof idx === 'number' && idx < this.items.length;
- }
- }, {
- key: "set",
- value: function set(key, value) {
- var idx = asItemIndex(key);
- if (typeof idx !== 'number') throw new Error("Expected a valid index, not ".concat(key, "."));
- this.items[idx] = value;
- }
- }, {
- key: "toJSON",
- value: function toJSON$1(_, ctx) {
- var seq = [];
- if (ctx && ctx.onCreate) ctx.onCreate(seq);
- var i = 0;
- var _iterator = _createForOfIteratorHelper(this.items),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var item = _step.value;
- seq.push(toJSON(item, String(i++), ctx));
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- return seq;
- }
- }, {
- key: "toString",
- value: function toString(ctx, onComment, onChompKeep) {
- if (!ctx) return JSON.stringify(this);
- return _get(_getPrototypeOf(YAMLSeq.prototype), "toString", this).call(this, ctx, {
- blockItem: function blockItem(n) {
- return n.type === 'comment' ? n.str : "- ".concat(n.str);
- },
- flowChars: {
- start: '[',
- end: ']'
- },
- isMap: false,
- itemIndent: (ctx.indent || '') + ' '
- }, onComment, onChompKeep);
- }
- }]);
- return YAMLSeq;
- }(Collection$1);
- var stringifyKey = function stringifyKey(key, jsKey, ctx) {
- if (jsKey === null) return '';
- if (_typeof(jsKey) !== 'object') return String(jsKey);
- if (key instanceof Node$1 && ctx && ctx.doc) return key.toString({
- anchors: {},
- doc: ctx.doc,
- indent: '',
- indentStep: ctx.indentStep,
- inFlow: true,
- inStringifyKey: true,
- stringify: ctx.stringify
- });
- return JSON.stringify(jsKey);
- };
- var Pair = function (_Node) {
- _inherits(Pair, _Node);
- var _super = _createSuper(Pair);
- function Pair(key) {
- var _this;
- var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
- _classCallCheck(this, Pair);
- _this = _super.call(this);
- _this.key = key;
- _this.value = value;
- _this.type = Pair.Type.PAIR;
- return _this;
- }
- _createClass(Pair, [{
- key: "addToJSMap",
- value: function addToJSMap(ctx, map) {
- var key = toJSON(this.key, '', ctx);
- if (map instanceof Map) {
- var value = toJSON(this.value, key, ctx);
- map.set(key, value);
- } else if (map instanceof Set) {
- map.add(key);
- } else {
- var stringKey = stringifyKey(this.key, key, ctx);
- map[stringKey] = toJSON(this.value, stringKey, ctx);
- }
- return map;
- }
- }, {
- key: "toJSON",
- value: function toJSON(_, ctx) {
- var pair = ctx && ctx.mapAsMap ? new Map() : {};
- return this.addToJSMap(ctx, pair);
- }
- }, {
- key: "toString",
- value: function toString(ctx, onComment, onChompKeep) {
- if (!ctx || !ctx.doc) return JSON.stringify(this);
- var _ctx$doc$options = ctx.doc.options,
- indentSize = _ctx$doc$options.indent,
- indentSeq = _ctx$doc$options.indentSeq,
- simpleKeys = _ctx$doc$options.simpleKeys;
- var key = this.key,
- value = this.value;
- var keyComment = key instanceof Node$1 && key.comment;
- if (simpleKeys) {
- if (keyComment) {
- throw new Error('With simple keys, key nodes cannot have comments');
- }
- if (key instanceof Collection$1) {
- var msg = 'With simple keys, collection cannot be used as a key value';
- throw new Error(msg);
- }
- }
- var explicitKey = !simpleKeys && (!key || keyComment || key instanceof Collection$1 || key.type === Type.BLOCK_FOLDED || key.type === Type.BLOCK_LITERAL);
- var _ctx = ctx,
- doc = _ctx.doc,
- indent = _ctx.indent,
- indentStep = _ctx.indentStep,
- stringify = _ctx.stringify;
- ctx = Object.assign({}, ctx, {
- implicitKey: !explicitKey,
- indent: indent + indentStep
- });
- var chompKeep = false;
- var str = stringify(key, ctx, function () {
- return keyComment = null;
- }, function () {
- return chompKeep = true;
- });
- str = addComment(str, ctx.indent, keyComment);
- if (ctx.allNullValues && !simpleKeys) {
- if (this.comment) {
- str = addComment(str, ctx.indent, this.comment);
- if (onComment) onComment();
- } else if (chompKeep && !keyComment && onChompKeep) onChompKeep();
- return ctx.inFlow ? str : "? ".concat(str);
- }
- str = explicitKey ? "? ".concat(str, "\n").concat(indent, ":") : "".concat(str, ":");
- if (this.comment) {
-
- str = addComment(str, ctx.indent, this.comment);
- if (onComment) onComment();
- }
- var vcb = '';
- var valueComment = null;
- if (value instanceof Node$1) {
- if (value.spaceBefore) vcb = '\n';
- if (value.commentBefore) {
- var cs = value.commentBefore.replace(/^/gm, "".concat(ctx.indent, "#"));
- vcb += "\n".concat(cs);
- }
- valueComment = value.comment;
- } else if (value && _typeof(value) === 'object') {
- value = doc.schema.createNode(value, true);
- }
- ctx.implicitKey = false;
- if (!explicitKey && !this.comment && value instanceof Scalar) ctx.indentAtStart = str.length + 1;
- chompKeep = false;
- if (!indentSeq && indentSize >= 2 && !ctx.inFlow && !explicitKey && value instanceof YAMLSeq && value.type !== Type.FLOW_SEQ && !value.tag && !doc.anchors.getName(value)) {
-
- ctx.indent = ctx.indent.substr(2);
- }
- var valueStr = stringify(value, ctx, function () {
- return valueComment = null;
- }, function () {
- return chompKeep = true;
- });
- var ws = ' ';
- if (vcb || this.comment) {
- ws = "".concat(vcb, "\n").concat(ctx.indent);
- } else if (!explicitKey && value instanceof Collection$1) {
- var flow = valueStr[0] === '[' || valueStr[0] === '{';
- if (!flow || valueStr.includes('\n')) ws = "\n".concat(ctx.indent);
- }
- if (chompKeep && !valueComment && onChompKeep) onChompKeep();
- return addComment(str + ws + valueStr, ctx.indent, valueComment);
- }
- }, {
- key: "commentBefore",
- get: function get() {
- return this.key instanceof Node$1 ? this.key.commentBefore : undefined;
- },
- set: function set(cb) {
- if (this.key == null) this.key = new Scalar(null);
- if (this.key instanceof Node$1) this.key.commentBefore = cb;else {
- var msg = 'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.';
- throw new Error(msg);
- }
- }
- }]);
- return Pair;
- }(Node$1);
- _defineProperty(Pair, "Type", {
- PAIR: 'PAIR',
- MERGE_PAIR: 'MERGE_PAIR'
- });
- var getAliasCount = function getAliasCount(node, anchors) {
- if (node instanceof Alias$1) {
- var anchor = anchors.get(node.source);
- return anchor.count * anchor.aliasCount;
- } else if (node instanceof Collection$1) {
- var count = 0;
- var _iterator = _createForOfIteratorHelper(node.items),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var item = _step.value;
- var c = getAliasCount(item, anchors);
- if (c > count) count = c;
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- return count;
- } else if (node instanceof Pair) {
- var kc = getAliasCount(node.key, anchors);
- var vc = getAliasCount(node.value, anchors);
- return Math.max(kc, vc);
- }
- return 1;
- };
- var Alias$1 = function (_Node) {
- _inherits(Alias, _Node);
- var _super = _createSuper(Alias);
- _createClass(Alias, null, [{
- key: "stringify",
- value: function stringify(_ref, _ref2) {
- var range = _ref.range,
- source = _ref.source;
- var anchors = _ref2.anchors,
- doc = _ref2.doc,
- implicitKey = _ref2.implicitKey,
- inStringifyKey = _ref2.inStringifyKey;
- var anchor = Object.keys(anchors).find(function (a) {
- return anchors[a] === source;
- });
- if (!anchor && inStringifyKey) anchor = doc.anchors.getName(source) || doc.anchors.newName();
- if (anchor) return "*".concat(anchor).concat(implicitKey ? ' ' : '');
- var msg = doc.anchors.getName(source) ? 'Alias node must be after source node' : 'Source node not found for alias node';
- throw new Error("".concat(msg, " [").concat(range, "]"));
- }
- }]);
- function Alias(source) {
- var _this;
- _classCallCheck(this, Alias);
- _this = _super.call(this);
- _this.source = source;
- _this.type = Type.ALIAS;
- return _this;
- }
- _createClass(Alias, [{
- key: "toJSON",
- value: function toJSON$1(arg, ctx) {
- if (!ctx) return toJSON(this.source, arg, ctx);
- var anchors = ctx.anchors,
- maxAliasCount = ctx.maxAliasCount;
- var anchor = anchors.get(this.source);
-
- if (!anchor || anchor.res === undefined) {
- var msg = 'This should not happen: Alias anchor was not resolved?';
- if (this.cstNode) throw new YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg);
- }
- if (maxAliasCount >= 0) {
- anchor.count += 1;
- if (anchor.aliasCount === 0) anchor.aliasCount = getAliasCount(this.source, anchors);
- if (anchor.count * anchor.aliasCount > maxAliasCount) {
- var _msg = 'Excessive alias count indicates a resource exhaustion attack';
- if (this.cstNode) throw new YAMLReferenceError(this.cstNode, _msg);else throw new ReferenceError(_msg);
- }
- }
- return anchor.res;
- }
-
- }, {
- key: "toString",
- value: function toString(ctx) {
- return Alias.stringify(this, ctx);
- }
- }, {
- key: "tag",
- set: function set(t) {
- throw new Error('Alias nodes cannot have tags');
- }
- }]);
- return Alias;
- }(Node$1);
- _defineProperty(Alias$1, "default", true);
- function findPair(items, key) {
- var k = key instanceof Scalar ? key.value : key;
- var _iterator = _createForOfIteratorHelper(items),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var it = _step.value;
- if (it instanceof Pair) {
- if (it.key === key || it.key === k) return it;
- if (it.key && it.key.value === k) return it;
- }
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- return undefined;
- }
- var YAMLMap = function (_Collection) {
- _inherits(YAMLMap, _Collection);
- var _super = _createSuper(YAMLMap);
- function YAMLMap() {
- _classCallCheck(this, YAMLMap);
- return _super.apply(this, arguments);
- }
- _createClass(YAMLMap, [{
- key: "add",
- value: function add(pair, overwrite) {
- if (!pair) pair = new Pair(pair);else if (!(pair instanceof Pair)) pair = new Pair(pair.key || pair, pair.value);
- var prev = findPair(this.items, pair.key);
- var sortEntries = this.schema && this.schema.sortMapEntries;
- if (prev) {
- if (overwrite) prev.value = pair.value;else throw new Error("Key ".concat(pair.key, " already set"));
- } else if (sortEntries) {
- var i = this.items.findIndex(function (item) {
- return sortEntries(pair, item) < 0;
- });
- if (i === -1) this.items.push(pair);else this.items.splice(i, 0, pair);
- } else {
- this.items.push(pair);
- }
- }
- }, {
- key: "delete",
- value: function _delete(key) {
- var it = findPair(this.items, key);
- if (!it) return false;
- var del = this.items.splice(this.items.indexOf(it), 1);
- return del.length > 0;
- }
- }, {
- key: "get",
- value: function get(key, keepScalar) {
- var it = findPair(this.items, key);
- var node = it && it.value;
- return !keepScalar && node instanceof Scalar ? node.value : node;
- }
- }, {
- key: "has",
- value: function has(key) {
- return !!findPair(this.items, key);
- }
- }, {
- key: "set",
- value: function set(key, value) {
- this.add(new Pair(key, value), true);
- }
-
- }, {
- key: "toJSON",
- value: function toJSON(_, ctx, Type) {
- var map = Type ? new Type() : ctx && ctx.mapAsMap ? new Map() : {};
- if (ctx && ctx.onCreate) ctx.onCreate(map);
- var _iterator2 = _createForOfIteratorHelper(this.items),
- _step2;
- try {
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
- var item = _step2.value;
- item.addToJSMap(ctx, map);
- }
- } catch (err) {
- _iterator2.e(err);
- } finally {
- _iterator2.f();
- }
- return map;
- }
- }, {
- key: "toString",
- value: function toString(ctx, onComment, onChompKeep) {
- if (!ctx) return JSON.stringify(this);
- var _iterator3 = _createForOfIteratorHelper(this.items),
- _step3;
- try {
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
- var item = _step3.value;
- if (!(item instanceof Pair)) throw new Error("Map items must all be pairs; found ".concat(JSON.stringify(item), " instead"));
- }
- } catch (err) {
- _iterator3.e(err);
- } finally {
- _iterator3.f();
- }
- return _get(_getPrototypeOf(YAMLMap.prototype), "toString", this).call(this, ctx, {
- blockItem: function blockItem(n) {
- return n.str;
- },
- flowChars: {
- start: '{',
- end: '}'
- },
- isMap: true,
- itemIndent: ctx.indent || ''
- }, onComment, onChompKeep);
- }
- }]);
- return YAMLMap;
- }(Collection$1);
- var MERGE_KEY = '<<';
- var Merge = function (_Pair) {
- _inherits(Merge, _Pair);
- var _super = _createSuper(Merge);
- function Merge(pair) {
- var _this;
- _classCallCheck(this, Merge);
- if (pair instanceof Pair) {
- var seq = pair.value;
- if (!(seq instanceof YAMLSeq)) {
- seq = new YAMLSeq();
- seq.items.push(pair.value);
- seq.range = pair.value.range;
- }
- _this = _super.call(this, pair.key, seq);
- _this.range = pair.range;
- } else {
- _this = _super.call(this, new Scalar(MERGE_KEY), new YAMLSeq());
- }
- _this.type = Pair.Type.MERGE_PAIR;
- return _possibleConstructorReturn(_this);
- }
-
-
-
-
-
-
- _createClass(Merge, [{
- key: "addToJSMap",
- value: function addToJSMap(ctx, map) {
- var _iterator = _createForOfIteratorHelper(this.value.items),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var source = _step.value.source;
- if (!(source instanceof YAMLMap)) throw new Error('Merge sources must be maps');
- var srcMap = source.toJSON(null, ctx, Map);
- var _iterator2 = _createForOfIteratorHelper(srcMap),
- _step2;
- try {
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
- var _step2$value = _slicedToArray(_step2.value, 2),
- key = _step2$value[0],
- value = _step2$value[1];
- if (map instanceof Map) {
- if (!map.has(key)) map.set(key, value);
- } else if (map instanceof Set) {
- map.add(key);
- } else {
- if (!Object.prototype.hasOwnProperty.call(map, key)) map[key] = value;
- }
- }
- } catch (err) {
- _iterator2.e(err);
- } finally {
- _iterator2.f();
- }
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- return map;
- }
- }, {
- key: "toString",
- value: function toString(ctx, onComment) {
- var seq = this.value;
- if (seq.items.length > 1) return _get(_getPrototypeOf(Merge.prototype), "toString", this).call(this, ctx, onComment);
- this.value = seq.items[0];
- var str = _get(_getPrototypeOf(Merge.prototype), "toString", this).call(this, ctx, onComment);
- this.value = seq;
- return str;
- }
- }]);
- return Merge;
- }(Pair);
- var binaryOptions = {
- defaultType: Type.BLOCK_LITERAL,
- lineWidth: 76
- };
- var boolOptions = {
- trueStr: 'true',
- falseStr: 'false'
- };
- var intOptions = {
- asBigInt: false
- };
- var nullOptions = {
- nullStr: 'null'
- };
- var strOptions = {
- defaultType: Type.PLAIN,
- doubleQuoted: {
- jsonEncoding: false,
- minMultiLineLength: 40
- },
- fold: {
- lineWidth: 80,
- minContentWidth: 20
- }
- };
- function resolveScalar(str, tags, scalarFallback) {
- var _iterator = _createForOfIteratorHelper(tags),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var _step$value = _step.value,
- format = _step$value.format,
- test = _step$value.test,
- resolve = _step$value.resolve;
- if (test) {
- var match = str.match(test);
- if (match) {
- var res = resolve.apply(null, match);
- if (!(res instanceof Scalar)) res = new Scalar(res);
- if (format) res.format = format;
- return res;
- }
- }
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- if (scalarFallback) str = scalarFallback(str);
- return new Scalar(str);
- }
- var FOLD_FLOW = 'flow';
- var FOLD_BLOCK = 'block';
- var FOLD_QUOTED = 'quoted';
- var consumeMoreIndentedLines = function consumeMoreIndentedLines(text, i) {
- var ch = text[i + 1];
- while (ch === ' ' || ch === '\t') {
- do {
- ch = text[i += 1];
- } while (ch && ch !== '\n');
- ch = text[i + 1];
- }
- return i;
- };
- function foldFlowLines(text, indent, mode, _ref) {
- var indentAtStart = _ref.indentAtStart,
- _ref$lineWidth = _ref.lineWidth,
- lineWidth = _ref$lineWidth === void 0 ? 80 : _ref$lineWidth,
- _ref$minContentWidth = _ref.minContentWidth,
- minContentWidth = _ref$minContentWidth === void 0 ? 20 : _ref$minContentWidth,
- onFold = _ref.onFold,
- onOverflow = _ref.onOverflow;
- if (!lineWidth || lineWidth < 0) return text;
- var endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
- if (text.length <= endStep) return text;
- var folds = [];
- var escapedFolds = {};
- var end = lineWidth - (typeof indentAtStart === 'number' ? indentAtStart : indent.length);
- var split = undefined;
- var prev = undefined;
- var overflow = false;
- var i = -1;
- if (mode === FOLD_BLOCK) {
- i = consumeMoreIndentedLines(text, i);
- if (i !== -1) end = i + endStep;
- }
- for (var ch; ch = text[i += 1];) {
- if (mode === FOLD_QUOTED && ch === '\\') {
- switch (text[i + 1]) {
- case 'x':
- i += 3;
- break;
- case 'u':
- i += 5;
- break;
- case 'U':
- i += 9;
- break;
- default:
- i += 1;
- }
- }
- if (ch === '\n') {
- if (mode === FOLD_BLOCK) i = consumeMoreIndentedLines(text, i);
- end = i + endStep;
- split = undefined;
- } else {
- if (ch === ' ' && prev && prev !== ' ' && prev !== '\n' && prev !== '\t') {
-
- var next = text[i + 1];
- if (next && next !== ' ' && next !== '\n' && next !== '\t') split = i;
- }
- if (i >= end) {
- if (split) {
- folds.push(split);
- end = split + endStep;
- split = undefined;
- } else if (mode === FOLD_QUOTED) {
-
- while (prev === ' ' || prev === '\t') {
- prev = ch;
- ch = text[i += 1];
- overflow = true;
- }
- folds.push(i - 2);
- escapedFolds[i - 2] = true;
- end = i - 2 + endStep;
- split = undefined;
- } else {
- overflow = true;
- }
- }
- }
- prev = ch;
- }
- if (overflow && onOverflow) onOverflow();
- if (folds.length === 0) return text;
- if (onFold) onFold();
- var res = text.slice(0, folds[0]);
- for (var _i = 0; _i < folds.length; ++_i) {
- var fold = folds[_i];
- var _end = folds[_i + 1] || text.length;
- if (mode === FOLD_QUOTED && escapedFolds[fold]) res += "".concat(text[fold], "\\");
- res += "\n".concat(indent).concat(text.slice(fold + 1, _end));
- }
- return res;
- }
- var getFoldOptions = function getFoldOptions(_ref) {
- var indentAtStart = _ref.indentAtStart;
- return indentAtStart ? Object.assign({
- indentAtStart: indentAtStart
- }, strOptions.fold) : strOptions.fold;
- };
- var containsDocumentMarker = function containsDocumentMarker(str) {
- return /^(%|---|\.\.\.)/m.test(str);
- };
- function lineLengthOverLimit(str, limit) {
- var strLen = str.length;
- if (strLen <= limit) return false;
- for (var i = 0, start = 0; i < strLen; ++i) {
- if (str[i] === '\n') {
- if (i - start > limit) return true;
- start = i + 1;
- if (strLen - start <= limit) return false;
- }
- }
- return true;
- }
- function doubleQuotedString(value, ctx) {
- var implicitKey = ctx.implicitKey;
- var _strOptions$doubleQuo = strOptions.doubleQuoted,
- jsonEncoding = _strOptions$doubleQuo.jsonEncoding,
- minMultiLineLength = _strOptions$doubleQuo.minMultiLineLength;
- var json = JSON.stringify(value);
- if (jsonEncoding) return json;
- var indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
- var str = '';
- var start = 0;
- for (var i = 0, ch = json[i]; ch; ch = json[++i]) {
- if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') {
-
- str += json.slice(start, i) + '\\ ';
- i += 1;
- start = i;
- ch = '\\';
- }
- if (ch === '\\') switch (json[i + 1]) {
- case 'u':
- {
- str += json.slice(start, i);
- var code = json.substr(i + 2, 4);
- switch (code) {
- case '0000':
- str += '\\0';
- break;
- case '0007':
- str += '\\a';
- break;
- case '000b':
- str += '\\v';
- break;
- case '001b':
- str += '\\e';
- break;
- case '0085':
- str += '\\N';
- break;
- case '00a0':
- str += '\\_';
- break;
- case '2028':
- str += '\\L';
- break;
- case '2029':
- str += '\\P';
- break;
- default:
- if (code.substr(0, 2) === '00') str += '\\x' + code.substr(2);else str += json.substr(i, 6);
- }
- i += 5;
- start = i + 1;
- }
- break;
- case 'n':
- if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) {
- i += 1;
- } else {
-
- str += json.slice(start, i) + '\n\n';
- while (json[i + 2] === '\\' && json[i + 3] === 'n' && json[i + 4] !== '"') {
- str += '\n';
- i += 2;
- }
- str += indent;
- if (json[i + 2] === ' ') str += '\\';
- i += 1;
- start = i + 1;
- }
- break;
- default:
- i += 1;
- }
- }
- str = start ? str + json.slice(start) : json;
- return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx));
- }
- function singleQuotedString(value, ctx) {
- if (ctx.implicitKey) {
- if (/\n/.test(value)) return doubleQuotedString(value, ctx);
- } else {
-
- if (/[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, ctx);
- }
- var indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
- var res = "'" + value.replace(/'/g, "''").replace(/\n+/g, "$&\n".concat(indent)) + "'";
- return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx));
- }
- function blockString(_ref2, ctx, onComment, onChompKeep) {
- var comment = _ref2.comment,
- type = _ref2.type,
- value = _ref2.value;
-
-
- if (/\n[\t ]+$/.test(value) || /^\s*$/.test(value)) {
- return doubleQuotedString(value, ctx);
- }
- var indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : '');
- var indentSize = indent ? '2' : '1';
- var literal = type === Type.BLOCK_FOLDED ? false : type === Type.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, strOptions.fold.lineWidth - indent.length);
- var header = literal ? '|' : '>';
- if (!value) return header + '\n';
- var wsStart = '';
- var wsEnd = '';
- value = value.replace(/[\n\t ]*$/, function (ws) {
- var n = ws.indexOf('\n');
- if (n === -1) {
- header += '-';
- } else if (value === ws || n !== ws.length - 1) {
- header += '+';
- if (onChompKeep) onChompKeep();
- }
- wsEnd = ws.replace(/\n$/, '');
- return '';
- }).replace(/^[\n ]*/, function (ws) {
- if (ws.indexOf(' ') !== -1) header += indentSize;
- var m = ws.match(/ +$/);
- if (m) {
- wsStart = ws.slice(0, -m[0].length);
- return m[0];
- } else {
- wsStart = ws;
- return '';
- }
- });
- if (wsEnd) wsEnd = wsEnd.replace(/\n+(?!\n|$)/g, "$&".concat(indent));
- if (wsStart) wsStart = wsStart.replace(/\n+/g, "$&".concat(indent));
- if (comment) {
- header += ' #' + comment.replace(/ ?[\r\n]+/g, ' ');
- if (onComment) onComment();
- }
- if (!value) return "".concat(header).concat(indentSize, "\n").concat(indent).concat(wsEnd);
- if (literal) {
- value = value.replace(/\n+/g, "$&".concat(indent));
- return "".concat(header, "\n").concat(indent).concat(wsStart).concat(value).concat(wsEnd);
- }
- value = value.replace(/\n+/g, '\n$&').replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2')
-
- .replace(/\n+/g, "$&".concat(indent));
- var body = foldFlowLines("".concat(wsStart).concat(value).concat(wsEnd), indent, FOLD_BLOCK, strOptions.fold);
- return "".concat(header, "\n").concat(indent).concat(body);
- }
- function plainString(item, ctx, onComment, onChompKeep) {
- var comment = item.comment,
- type = item.type,
- value = item.value;
- var actualString = ctx.actualString,
- implicitKey = ctx.implicitKey,
- indent = ctx.indent,
- inFlow = ctx.inFlow;
- if (implicitKey && /[\n[\]{},]/.test(value) || inFlow && /[[\]{},]/.test(value)) {
- return doubleQuotedString(value, ctx);
- }
- if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
-
-
-
-
-
-
- return implicitKey || inFlow || value.indexOf('\n') === -1 ? value.indexOf('"') !== -1 && value.indexOf("'") === -1 ? singleQuotedString(value, ctx) : doubleQuotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep);
- }
- if (!implicitKey && !inFlow && type !== Type.PLAIN && value.indexOf('\n') !== -1) {
-
- return blockString(item, ctx, onComment, onChompKeep);
- }
- if (indent === '' && containsDocumentMarker(value)) {
- ctx.forceBlockIndent = true;
- return blockString(item, ctx, onComment, onChompKeep);
- }
- var str = value.replace(/\n+/g, "$&\n".concat(indent));
-
-
- if (actualString) {
- var tags = ctx.doc.schema.tags;
- var resolved = resolveScalar(str, tags, tags.scalarFallback).value;
- if (typeof resolved !== 'string') return doubleQuotedString(value, ctx);
- }
- var body = implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx));
- if (comment && !inFlow && (body.indexOf('\n') !== -1 || comment.indexOf('\n') !== -1)) {
- if (onComment) onComment();
- return addCommentBefore(body, indent, comment);
- }
- return body;
- }
- function stringifyString(item, ctx, onComment, onChompKeep) {
- var defaultType = strOptions.defaultType;
- var implicitKey = ctx.implicitKey,
- inFlow = ctx.inFlow;
- var _item = item,
- type = _item.type,
- value = _item.value;
- if (typeof value !== 'string') {
- value = String(value);
- item = Object.assign({}, item, {
- value: value
- });
- }
- var _stringify = function _stringify(_type) {
- switch (_type) {
- case Type.BLOCK_FOLDED:
- case Type.BLOCK_LITERAL:
- return blockString(item, ctx, onComment, onChompKeep);
- case Type.QUOTE_DOUBLE:
- return doubleQuotedString(value, ctx);
- case Type.QUOTE_SINGLE:
- return singleQuotedString(value, ctx);
- case Type.PLAIN:
- return plainString(item, ctx, onComment, onChompKeep);
- default:
- return null;
- }
- };
- if (type !== Type.QUOTE_DOUBLE && /[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value)) {
-
- type = Type.QUOTE_DOUBLE;
- } else if ((implicitKey || inFlow) && (type === Type.BLOCK_FOLDED || type === Type.BLOCK_LITERAL)) {
-
- type = Type.QUOTE_DOUBLE;
- }
- var res = _stringify(type);
- if (res === null) {
- res = _stringify(defaultType);
- if (res === null) throw new Error("Unsupported default string type ".concat(defaultType));
- }
- return res;
- }
- function stringifyNumber(_ref) {
- var format = _ref.format,
- minFractionDigits = _ref.minFractionDigits,
- tag = _ref.tag,
- value = _ref.value;
- if (typeof value === 'bigint') return String(value);
- if (!isFinite(value)) return isNaN(value) ? '.nan' : value < 0 ? '-.inf' : '.inf';
- var n = JSON.stringify(value);
- if (!format && minFractionDigits && (!tag || tag === 'tag:yaml.org,2002:float') && /^\d/.test(n)) {
- var i = n.indexOf('.');
- if (i < 0) {
- i = n.length;
- n += '.';
- }
- var d = minFractionDigits - (n.length - i - 1);
- while (d-- > 0) {
- n += '0';
- }
- }
- return n;
- }
- function checkFlowCollectionEnd(errors, cst) {
- var char, name;
- switch (cst.type) {
- case Type.FLOW_MAP:
- char = '}';
- name = 'flow map';
- break;
- case Type.FLOW_SEQ:
- char = ']';
- name = 'flow sequence';
- break;
- default:
- errors.push(new YAMLSemanticError(cst, 'Not a flow collection!?'));
- return;
- }
- var lastItem;
- for (var i = cst.items.length - 1; i >= 0; --i) {
- var item = cst.items[i];
- if (!item || item.type !== Type.COMMENT) {
- lastItem = item;
- break;
- }
- }
- if (lastItem && lastItem.char !== char) {
- var msg = "Expected ".concat(name, " to end with ").concat(char);
- var err;
- if (typeof lastItem.offset === 'number') {
- err = new YAMLSemanticError(cst, msg);
- err.offset = lastItem.offset + 1;
- } else {
- err = new YAMLSemanticError(lastItem, msg);
- if (lastItem.range && lastItem.range.end) err.offset = lastItem.range.end - lastItem.range.start;
- }
- errors.push(err);
- }
- }
- function checkFlowCommentSpace(errors, comment) {
- var prev = comment.context.src[comment.range.start - 1];
- if (prev !== '\n' && prev !== '\t' && prev !== ' ') {
- var msg = 'Comments must be separated from other tokens by white space characters';
- errors.push(new YAMLSemanticError(comment, msg));
- }
- }
- function getLongKeyError(source, key) {
- var sk = String(key);
- var k = sk.substr(0, 8) + '...' + sk.substr(-8);
- return new YAMLSemanticError(source, "The \"".concat(k, "\" key is too long"));
- }
- function resolveComments(collection, comments) {
- var _iterator = _createForOfIteratorHelper(comments),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var _step$value = _step.value,
- afterKey = _step$value.afterKey,
- before = _step$value.before,
- comment = _step$value.comment;
- var item = collection.items[before];
- if (!item) {
- if (comment !== undefined) {
- if (collection.comment) collection.comment += '\n' + comment;else collection.comment = comment;
- }
- } else {
- if (afterKey && item.value) item = item.value;
- if (comment === undefined) {
- if (afterKey || !item.commentBefore) item.spaceBefore = true;
- } else {
- if (item.commentBefore) item.commentBefore += '\n' + comment;else item.commentBefore = comment;
- }
- }
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- }
- function resolveString(doc, node) {
- var res = node.strValue;
- if (!res) return '';
- if (typeof res === 'string') return res;
- res.errors.forEach(function (error) {
- if (!error.source) error.source = node;
- doc.errors.push(error);
- });
- return res.str;
- }
- function resolveTagHandle(doc, node) {
- var _node$tag = node.tag,
- handle = _node$tag.handle,
- suffix = _node$tag.suffix;
- var prefix = doc.tagPrefixes.find(function (p) {
- return p.handle === handle;
- });
- if (!prefix) {
- var dtp = doc.getDefaults().tagPrefixes;
- if (dtp) prefix = dtp.find(function (p) {
- return p.handle === handle;
- });
- if (!prefix) throw new YAMLSemanticError(node, "The ".concat(handle, " tag handle is non-default and was not declared."));
- }
- if (!suffix) throw new YAMLSemanticError(node, "The ".concat(handle, " tag has no suffix."));
- if (handle === '!' && (doc.version || doc.options.version) === '1.0') {
- if (suffix[0] === '^') {
- doc.warnings.push(new YAMLWarning(node, 'YAML 1.0 ^ tag expansion is not supported'));
- return suffix;
- }
- if (/[:/]/.test(suffix)) {
-
- var vocab = suffix.match(/^([a-z0-9-]+)\/(.*)/i);
- return vocab ? "tag:".concat(vocab[1], ".yaml.org,2002:").concat(vocab[2]) : "tag:".concat(suffix);
- }
- }
- return prefix.prefix + decodeURIComponent(suffix);
- }
- function resolveTagName(doc, node) {
- var tag = node.tag,
- type = node.type;
- var nonSpecific = false;
- if (tag) {
- var handle = tag.handle,
- suffix = tag.suffix,
- verbatim = tag.verbatim;
- if (verbatim) {
- if (verbatim !== '!' && verbatim !== '!!') return verbatim;
- var msg = "Verbatim tags aren't resolved, so ".concat(verbatim, " is invalid.");
- doc.errors.push(new YAMLSemanticError(node, msg));
- } else if (handle === '!' && !suffix) {
- nonSpecific = true;
- } else {
- try {
- return resolveTagHandle(doc, node);
- } catch (error) {
- doc.errors.push(error);
- }
- }
- }
- switch (type) {
- case Type.BLOCK_FOLDED:
- case Type.BLOCK_LITERAL:
- case Type.QUOTE_DOUBLE:
- case Type.QUOTE_SINGLE:
- return defaultTags.STR;
- case Type.FLOW_MAP:
- case Type.MAP:
- return defaultTags.MAP;
- case Type.FLOW_SEQ:
- case Type.SEQ:
- return defaultTags.SEQ;
- case Type.PLAIN:
- return nonSpecific ? defaultTags.STR : null;
- default:
- return null;
- }
- }
- function resolveByTagName(doc, node, tagName) {
- var tags = doc.schema.tags;
- var matchWithTest = [];
- var _iterator = _createForOfIteratorHelper(tags),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var tag = _step.value;
- if (tag.tag === tagName) {
- if (tag.test) matchWithTest.push(tag);else {
- var res = tag.resolve(doc, node);
- return res instanceof Collection$1 ? res : new Scalar(res);
- }
- }
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- var str = resolveString(doc, node);
- if (typeof str === 'string' && matchWithTest.length > 0) return resolveScalar(str, matchWithTest, tags.scalarFallback);
- return null;
- }
- function getFallbackTagName(_ref) {
- var type = _ref.type;
- switch (type) {
- case Type.FLOW_MAP:
- case Type.MAP:
- return defaultTags.MAP;
- case Type.FLOW_SEQ:
- case Type.SEQ:
- return defaultTags.SEQ;
- default:
- return defaultTags.STR;
- }
- }
- function resolveTag(doc, node, tagName) {
- try {
- var res = resolveByTagName(doc, node, tagName);
- if (res) {
- if (tagName && node.tag) res.tag = tagName;
- return res;
- }
- } catch (error) {
-
- if (!error.source) error.source = node;
- doc.errors.push(error);
- return null;
- }
- try {
- var fallback = getFallbackTagName(node);
- if (!fallback) throw new Error("The tag ".concat(tagName, " is unavailable"));
- var msg = "The tag ".concat(tagName, " is unavailable, falling back to ").concat(fallback);
- doc.warnings.push(new YAMLWarning(node, msg));
- var _res = resolveByTagName(doc, node, fallback);
- _res.tag = tagName;
- return _res;
- } catch (error) {
- var refError = new YAMLReferenceError(node, error.message);
- refError.stack = error.stack;
- doc.errors.push(refError);
- return null;
- }
- }
- var isCollectionItem = function isCollectionItem(node) {
- if (!node) return false;
- var type = node.type;
- return type === Type.MAP_KEY || type === Type.MAP_VALUE || type === Type.SEQ_ITEM;
- };
- function resolveNodeProps(errors, node) {
- var comments = {
- before: [],
- after: []
- };
- var hasAnchor = false;
- var hasTag = false;
- var props = isCollectionItem(node.context.parent) ? node.context.parent.props.concat(node.props) : node.props;
- var _iterator = _createForOfIteratorHelper(props),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var _step$value = _step.value,
- start = _step$value.start,
- end = _step$value.end;
- switch (node.context.src[start]) {
- case Char.COMMENT:
- {
- if (!node.commentHasRequiredWhitespace(start)) {
- var msg = 'Comments must be separated from other tokens by white space characters';
- errors.push(new YAMLSemanticError(node, msg));
- }
- var header = node.header,
- valueRange = node.valueRange;
- var cc = valueRange && (start > valueRange.start || header && start > header.start) ? comments.after : comments.before;
- cc.push(node.context.src.slice(start + 1, end));
- break;
- }
-
- case Char.ANCHOR:
- if (hasAnchor) {
- var _msg = 'A node can have at most one anchor';
- errors.push(new YAMLSemanticError(node, _msg));
- }
- hasAnchor = true;
- break;
- case Char.TAG:
- if (hasTag) {
- var _msg2 = 'A node can have at most one tag';
- errors.push(new YAMLSemanticError(node, _msg2));
- }
- hasTag = true;
- break;
- }
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- return {
- comments: comments,
- hasAnchor: hasAnchor,
- hasTag: hasTag
- };
- }
- function resolveNodeValue(doc, node) {
- var anchors = doc.anchors,
- errors = doc.errors,
- schema = doc.schema;
- if (node.type === Type.ALIAS) {
- var name = node.rawValue;
- var src = anchors.getNode(name);
- if (!src) {
- var msg = "Aliased anchor not found: ".concat(name);
- errors.push(new YAMLReferenceError(node, msg));
- return null;
- }
- var res = new Alias$1(src);
- anchors._cstAliases.push(res);
- return res;
- }
- var tagName = resolveTagName(doc, node);
- if (tagName) return resolveTag(doc, node, tagName);
- if (node.type !== Type.PLAIN) {
- var _msg3 = "Failed to resolve ".concat(node.type, " node here");
- errors.push(new YAMLSyntaxError(node, _msg3));
- return null;
- }
- try {
- var str = resolveString(doc, node);
- return resolveScalar(str, schema.tags, schema.tags.scalarFallback);
- } catch (error) {
- if (!error.source) error.source = node;
- errors.push(error);
- return null;
- }
- }
- function resolveNode(doc, node) {
- if (!node) return null;
- if (node.error) doc.errors.push(node.error);
- var _resolveNodeProps = resolveNodeProps(doc.errors, node),
- comments = _resolveNodeProps.comments,
- hasAnchor = _resolveNodeProps.hasAnchor,
- hasTag = _resolveNodeProps.hasTag;
- if (hasAnchor) {
- var anchors = doc.anchors;
- var name = node.anchor;
- var prev = anchors.getNode(name);
-
- if (prev) anchors.map[anchors.newName(name)] = prev;
-
-
- anchors.map[name] = node;
- }
- if (node.type === Type.ALIAS && (hasAnchor || hasTag)) {
- var msg = 'An alias node must not specify any properties';
- doc.errors.push(new YAMLSemanticError(node, msg));
- }
- var res = resolveNodeValue(doc, node);
- if (res) {
- res.range = [node.range.start, node.range.end];
- if (doc.options.keepCstNodes) res.cstNode = node;
- if (doc.options.keepNodeTypes) res.type = node.type;
- var cb = comments.before.join('\n');
- if (cb) {
- res.commentBefore = res.commentBefore ? "".concat(res.commentBefore, "\n").concat(cb) : cb;
- }
- var ca = comments.after.join('\n');
- if (ca) res.comment = res.comment ? "".concat(res.comment, "\n").concat(ca) : ca;
- }
- return node.resolved = res;
- }
- function resolveMap(doc, cst) {
- if (cst.type !== Type.MAP && cst.type !== Type.FLOW_MAP) {
- var msg = "A ".concat(cst.type, " node cannot be resolved as a mapping");
- doc.errors.push(new YAMLSyntaxError(cst, msg));
- return null;
- }
- var _ref = cst.type === Type.FLOW_MAP ? resolveFlowMapItems(doc, cst) : resolveBlockMapItems(doc, cst),
- comments = _ref.comments,
- items = _ref.items;
- var map = new YAMLMap();
- map.items = items;
- resolveComments(map, comments);
- var hasCollectionKey = false;
- for (var i = 0; i < items.length; ++i) {
- var iKey = items[i].key;
- if (iKey instanceof Collection$1) hasCollectionKey = true;
- if (doc.schema.merge && iKey && iKey.value === MERGE_KEY) {
- items[i] = new Merge(items[i]);
- var sources = items[i].value.items;
- var error = null;
- sources.some(function (node) {
- if (node instanceof Alias$1) {
-
-
- var type = node.source.type;
- if (type === Type.MAP || type === Type.FLOW_MAP) return false;
- return error = 'Merge nodes aliases can only point to maps';
- }
- return error = 'Merge nodes can only have Alias nodes as values';
- });
- if (error) doc.errors.push(new YAMLSemanticError(cst, error));
- } else {
- for (var j = i + 1; j < items.length; ++j) {
- var jKey = items[j].key;
- if (iKey === jKey || iKey && jKey && Object.prototype.hasOwnProperty.call(iKey, 'value') && iKey.value === jKey.value) {
- var _msg = "Map keys must be unique; \"".concat(iKey, "\" is repeated");
- doc.errors.push(new YAMLSemanticError(cst, _msg));
- break;
- }
- }
- }
- }
- if (hasCollectionKey && !doc.options.mapAsMap) {
- var warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.';
- doc.warnings.push(new YAMLWarning(cst, warn));
- }
- cst.resolved = map;
- return map;
- }
- var valueHasPairComment = function valueHasPairComment(_ref2) {
- var _ref2$context = _ref2.context,
- lineStart = _ref2$context.lineStart,
- node = _ref2$context.node,
- src = _ref2$context.src,
- props = _ref2.props;
- if (props.length === 0) return false;
- var start = props[0].start;
- if (node && start > node.valueRange.start) return false;
- if (src[start] !== Char.COMMENT) return false;
- for (var i = lineStart; i < start; ++i) {
- if (src[i] === '\n') return false;
- }
- return true;
- };
- function resolvePairComment(item, pair) {
- if (!valueHasPairComment(item)) return;
- var comment = item.getPropValue(0, Char.COMMENT, true);
- var found = false;
- var cb = pair.value.commentBefore;
- if (cb && cb.startsWith(comment)) {
- pair.value.commentBefore = cb.substr(comment.length + 1);
- found = true;
- } else {
- var cc = pair.value.comment;
- if (!item.node && cc && cc.startsWith(comment)) {
- pair.value.comment = cc.substr(comment.length + 1);
- found = true;
- }
- }
- if (found) pair.comment = comment;
- }
- function resolveBlockMapItems(doc, cst) {
- var comments = [];
- var items = [];
- var key = undefined;
- var keyStart = null;
- for (var i = 0; i < cst.items.length; ++i) {
- var item = cst.items[i];
- switch (item.type) {
- case Type.BLANK_LINE:
- comments.push({
- afterKey: !!key,
- before: items.length
- });
- break;
- case Type.COMMENT:
- comments.push({
- afterKey: !!key,
- before: items.length,
- comment: item.comment
- });
- break;
- case Type.MAP_KEY:
- if (key !== undefined) items.push(new Pair(key));
- if (item.error) doc.errors.push(item.error);
- key = resolveNode(doc, item.node);
- keyStart = null;
- break;
- case Type.MAP_VALUE:
- {
- if (key === undefined) key = null;
- if (item.error) doc.errors.push(item.error);
- if (!item.context.atLineStart && item.node && item.node.type === Type.MAP && !item.node.context.atLineStart) {
- var msg = 'Nested mappings are not allowed in compact mappings';
- doc.errors.push(new YAMLSemanticError(item.node, msg));
- }
- var valueNode = item.node;
- if (!valueNode && item.props.length > 0) {
-
-
-
- valueNode = new PlainValue(Type.PLAIN, []);
- valueNode.context = {
- parent: item,
- src: item.context.src
- };
- var pos = item.range.start + 1;
- valueNode.range = {
- start: pos,
- end: pos
- };
- valueNode.valueRange = {
- start: pos,
- end: pos
- };
- if (typeof item.range.origStart === 'number') {
- var origPos = item.range.origStart + 1;
- valueNode.range.origStart = valueNode.range.origEnd = origPos;
- valueNode.valueRange.origStart = valueNode.valueRange.origEnd = origPos;
- }
- }
- var pair = new Pair(key, resolveNode(doc, valueNode));
- resolvePairComment(item, pair);
- items.push(pair);
- if (key && typeof keyStart === 'number') {
- if (item.range.start > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key));
- }
- key = undefined;
- keyStart = null;
- }
- break;
- default:
- if (key !== undefined) items.push(new Pair(key));
- key = resolveNode(doc, item);
- keyStart = item.range.start;
- if (item.error) doc.errors.push(item.error);
- next: for (var j = i + 1;; ++j) {
- var nextItem = cst.items[j];
- switch (nextItem && nextItem.type) {
- case Type.BLANK_LINE:
- case Type.COMMENT:
- continue next;
- case Type.MAP_VALUE:
- break next;
- default:
- {
- var _msg2 = 'Implicit map keys need to be followed by map values';
- doc.errors.push(new YAMLSemanticError(item, _msg2));
- break next;
- }
- }
- }
- if (item.valueRangeContainsNewline) {
- var _msg3 = 'Implicit map keys need to be on a single line';
- doc.errors.push(new YAMLSemanticError(item, _msg3));
- }
- }
- }
- if (key !== undefined) items.push(new Pair(key));
- return {
- comments: comments,
- items: items
- };
- }
- function resolveFlowMapItems(doc, cst) {
- var comments = [];
- var items = [];
- var key = undefined;
- var explicitKey = false;
- var next = '{';
- for (var i = 0; i < cst.items.length; ++i) {
- var item = cst.items[i];
- if (typeof item.char === 'string') {
- var char = item.char,
- offset = item.offset;
- if (char === '?' && key === undefined && !explicitKey) {
- explicitKey = true;
- next = ':';
- continue;
- }
- if (char === ':') {
- if (key === undefined) key = null;
- if (next === ':') {
- next = ',';
- continue;
- }
- } else {
- if (explicitKey) {
- if (key === undefined && char !== ',') key = null;
- explicitKey = false;
- }
- if (key !== undefined) {
- items.push(new Pair(key));
- key = undefined;
- if (char === ',') {
- next = ':';
- continue;
- }
- }
- }
- if (char === '}') {
- if (i === cst.items.length - 1) continue;
- } else if (char === next) {
- next = ':';
- continue;
- }
- var msg = "Flow map contains an unexpected ".concat(char);
- var err = new YAMLSyntaxError(cst, msg);
- err.offset = offset;
- doc.errors.push(err);
- } else if (item.type === Type.BLANK_LINE) {
- comments.push({
- afterKey: !!key,
- before: items.length
- });
- } else if (item.type === Type.COMMENT) {
- checkFlowCommentSpace(doc.errors, item);
- comments.push({
- afterKey: !!key,
- before: items.length,
- comment: item.comment
- });
- } else if (key === undefined) {
- if (next === ',') doc.errors.push(new YAMLSemanticError(item, 'Separator , missing in flow map'));
- key = resolveNode(doc, item);
- } else {
- if (next !== ',') doc.errors.push(new YAMLSemanticError(item, 'Indicator : missing in flow map entry'));
- items.push(new Pair(key, resolveNode(doc, item)));
- key = undefined;
- explicitKey = false;
- }
- }
- checkFlowCollectionEnd(doc.errors, cst);
- if (key !== undefined) items.push(new Pair(key));
- return {
- comments: comments,
- items: items
- };
- }
- function resolveSeq(doc, cst) {
- if (cst.type !== Type.SEQ && cst.type !== Type.FLOW_SEQ) {
- var msg = "A ".concat(cst.type, " node cannot be resolved as a sequence");
- doc.errors.push(new YAMLSyntaxError(cst, msg));
- return null;
- }
- var _ref = cst.type === Type.FLOW_SEQ ? resolveFlowSeqItems(doc, cst) : resolveBlockSeqItems(doc, cst),
- comments = _ref.comments,
- items = _ref.items;
- var seq = new YAMLSeq();
- seq.items = items;
- resolveComments(seq, comments);
- if (!doc.options.mapAsMap && items.some(function (it) {
- return it instanceof Pair && it.key instanceof Collection$1;
- })) {
- var warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.';
- doc.warnings.push(new YAMLWarning(cst, warn));
- }
- cst.resolved = seq;
- return seq;
- }
- function resolveBlockSeqItems(doc, cst) {
- var comments = [];
- var items = [];
- for (var i = 0; i < cst.items.length; ++i) {
- var item = cst.items[i];
- switch (item.type) {
- case Type.BLANK_LINE:
- comments.push({
- before: items.length
- });
- break;
- case Type.COMMENT:
- comments.push({
- comment: item.comment,
- before: items.length
- });
- break;
- case Type.SEQ_ITEM:
- if (item.error) doc.errors.push(item.error);
- items.push(resolveNode(doc, item.node));
- if (item.hasProps) {
- var msg = 'Sequence items cannot have tags or anchors before the - indicator';
- doc.errors.push(new YAMLSemanticError(item, msg));
- }
- break;
- default:
- if (item.error) doc.errors.push(item.error);
- doc.errors.push(new YAMLSyntaxError(item, "Unexpected ".concat(item.type, " node in sequence")));
- }
- }
- return {
- comments: comments,
- items: items
- };
- }
- function resolveFlowSeqItems(doc, cst) {
- var comments = [];
- var items = [];
- var explicitKey = false;
- var key = undefined;
- var keyStart = null;
- var next = '[';
- var prevItem = null;
- for (var i = 0; i < cst.items.length; ++i) {
- var item = cst.items[i];
- if (typeof item.char === 'string') {
- var char = item.char,
- offset = item.offset;
- if (char !== ':' && (explicitKey || key !== undefined)) {
- if (explicitKey && key === undefined) key = next ? items.pop() : null;
- items.push(new Pair(key));
- explicitKey = false;
- key = undefined;
- keyStart = null;
- }
- if (char === next) {
- next = null;
- } else if (!next && char === '?') {
- explicitKey = true;
- } else if (next !== '[' && char === ':' && key === undefined) {
- if (next === ',') {
- key = items.pop();
- if (key instanceof Pair) {
- var msg = 'Chaining flow sequence pairs is invalid';
- var err = new YAMLSemanticError(cst, msg);
- err.offset = offset;
- doc.errors.push(err);
- }
- if (!explicitKey && typeof keyStart === 'number') {
- var keyEnd = item.range ? item.range.start : item.offset;
- if (keyEnd > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key));
- var src = prevItem.context.src;
- for (var _i = keyStart; _i < keyEnd; ++_i) {
- if (src[_i] === '\n') {
- var _msg = 'Implicit keys of flow sequence pairs need to be on a single line';
- doc.errors.push(new YAMLSemanticError(prevItem, _msg));
- break;
- }
- }
- }
- } else {
- key = null;
- }
- keyStart = null;
- explicitKey = false;
- next = null;
- } else if (next === '[' || char !== ']' || i < cst.items.length - 1) {
- var _msg2 = "Flow sequence contains an unexpected ".concat(char);
- var _err = new YAMLSyntaxError(cst, _msg2);
- _err.offset = offset;
- doc.errors.push(_err);
- }
- } else if (item.type === Type.BLANK_LINE) {
- comments.push({
- before: items.length
- });
- } else if (item.type === Type.COMMENT) {
- checkFlowCommentSpace(doc.errors, item);
- comments.push({
- comment: item.comment,
- before: items.length
- });
- } else {
- if (next) {
- var _msg3 = "Expected a ".concat(next, " in flow sequence");
- doc.errors.push(new YAMLSemanticError(item, _msg3));
- }
- var value = resolveNode(doc, item);
- if (key === undefined) {
- items.push(value);
- prevItem = item;
- } else {
- items.push(new Pair(key, value));
- key = undefined;
- }
- keyStart = item.range.start;
- next = ',';
- }
- }
- checkFlowCollectionEnd(doc.errors, cst);
- if (key !== undefined) items.push(new Pair(key));
- return {
- comments: comments,
- items: items
- };
- }
- var binary = {
- identify: function identify(value) {
- return value instanceof Uint8Array;
- },
-
- default: false,
- tag: 'tag:yaml.org,2002:binary',
-
- resolve: function resolve(doc, node) {
- var src = resolveString(doc, node);
- if (typeof Buffer === 'function') {
- return Buffer.from(src, 'base64');
- } else if (typeof atob === 'function') {
-
- var str = atob(src.replace(/[\n\r]/g, ''));
- var buffer = new Uint8Array(str.length);
- for (var i = 0; i < str.length; ++i) {
- buffer[i] = str.charCodeAt(i);
- }
- return buffer;
- } else {
- var msg = 'This environment does not support reading binary tags; either Buffer or atob is required';
- doc.errors.push(new YAMLReferenceError(node, msg));
- return null;
- }
- },
- options: binaryOptions,
- stringify: function stringify(_ref, ctx, onComment, onChompKeep) {
- var comment = _ref.comment,
- type = _ref.type,
- value = _ref.value;
- var src;
- if (typeof Buffer === 'function') {
- src = value instanceof Buffer ? value.toString('base64') : Buffer.from(value.buffer).toString('base64');
- } else if (typeof btoa === 'function') {
- var s = '';
- for (var i = 0; i < value.length; ++i) {
- s += String.fromCharCode(value[i]);
- }
- src = btoa(s);
- } else {
- throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');
- }
- if (!type) type = binaryOptions.defaultType;
- if (type === Type.QUOTE_DOUBLE) {
- value = src;
- } else {
- var lineWidth = binaryOptions.lineWidth;
- var n = Math.ceil(src.length / lineWidth);
- var lines = new Array(n);
- for (var _i = 0, o = 0; _i < n; ++_i, o += lineWidth) {
- lines[_i] = src.substr(o, lineWidth);
- }
- value = lines.join(type === Type.BLOCK_LITERAL ? '\n' : ' ');
- }
- return stringifyString({
- comment: comment,
- type: type,
- value: value
- }, ctx, onComment, onChompKeep);
- }
- };
- function parsePairs(doc, cst) {
- var seq = resolveSeq(doc, cst);
- for (var i = 0; i < seq.items.length; ++i) {
- var item = seq.items[i];
- if (item instanceof Pair) continue;else if (item instanceof YAMLMap) {
- if (item.items.length > 1) {
- var msg = 'Each pair must have its own sequence indicator';
- throw new YAMLSemanticError(cst, msg);
- }
- var pair = item.items[0] || new Pair();
- if (item.commentBefore) pair.commentBefore = pair.commentBefore ? "".concat(item.commentBefore, "\n").concat(pair.commentBefore) : item.commentBefore;
- if (item.comment) pair.comment = pair.comment ? "".concat(item.comment, "\n").concat(pair.comment) : item.comment;
- item = pair;
- }
- seq.items[i] = item instanceof Pair ? item : new Pair(item);
- }
- return seq;
- }
- function createPairs(schema, iterable, ctx) {
- var pairs = new YAMLSeq(schema);
- pairs.tag = 'tag:yaml.org,2002:pairs';
- var _iterator = _createForOfIteratorHelper(iterable),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var it = _step.value;
- var key = void 0,
- value = void 0;
- if (Array.isArray(it)) {
- if (it.length === 2) {
- key = it[0];
- value = it[1];
- } else throw new TypeError("Expected [key, value] tuple: ".concat(it));
- } else if (it && it instanceof Object) {
- var keys = Object.keys(it);
- if (keys.length === 1) {
- key = keys[0];
- value = it[key];
- } else throw new TypeError("Expected { key: value } tuple: ".concat(it));
- } else {
- key = it;
- }
- var pair = schema.createPair(key, value, ctx);
- pairs.items.push(pair);
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- return pairs;
- }
- var pairs = {
- default: false,
- tag: 'tag:yaml.org,2002:pairs',
- resolve: parsePairs,
- createNode: createPairs
- };
- var YAMLOMap = function (_YAMLSeq) {
- _inherits(YAMLOMap, _YAMLSeq);
- var _super = _createSuper(YAMLOMap);
- function YAMLOMap() {
- var _this;
- _classCallCheck(this, YAMLOMap);
- _this = _super.call(this);
- _defineProperty(_assertThisInitialized(_this), "add", YAMLMap.prototype.add.bind(_assertThisInitialized(_this)));
- _defineProperty(_assertThisInitialized(_this), "delete", YAMLMap.prototype.delete.bind(_assertThisInitialized(_this)));
- _defineProperty(_assertThisInitialized(_this), "get", YAMLMap.prototype.get.bind(_assertThisInitialized(_this)));
- _defineProperty(_assertThisInitialized(_this), "has", YAMLMap.prototype.has.bind(_assertThisInitialized(_this)));
- _defineProperty(_assertThisInitialized(_this), "set", YAMLMap.prototype.set.bind(_assertThisInitialized(_this)));
- _this.tag = YAMLOMap.tag;
- return _this;
- }
- _createClass(YAMLOMap, [{
- key: "toJSON",
- value: function toJSON$1(_, ctx) {
- var map = new Map();
- if (ctx && ctx.onCreate) ctx.onCreate(map);
- var _iterator = _createForOfIteratorHelper(this.items),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var pair = _step.value;
- var key = void 0,
- value = void 0;
- if (pair instanceof Pair) {
- key = toJSON(pair.key, '', ctx);
- value = toJSON(pair.value, key, ctx);
- } else {
- key = toJSON(pair, '', ctx);
- }
- if (map.has(key)) throw new Error('Ordered maps must not include duplicate keys');
- map.set(key, value);
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- return map;
- }
- }]);
- return YAMLOMap;
- }(YAMLSeq);
- _defineProperty(YAMLOMap, "tag", 'tag:yaml.org,2002:omap');
- function parseOMap(doc, cst) {
- var pairs = parsePairs(doc, cst);
- var seenKeys = [];
- var _iterator2 = _createForOfIteratorHelper(pairs.items),
- _step2;
- try {
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
- var key = _step2.value.key;
- if (key instanceof Scalar) {
- if (seenKeys.includes(key.value)) {
- var msg = 'Ordered maps must not include duplicate keys';
- throw new YAMLSemanticError(cst, msg);
- } else {
- seenKeys.push(key.value);
- }
- }
- }
- } catch (err) {
- _iterator2.e(err);
- } finally {
- _iterator2.f();
- }
- return Object.assign(new YAMLOMap(), pairs);
- }
- function createOMap(schema, iterable, ctx) {
- var pairs = createPairs(schema, iterable, ctx);
- var omap = new YAMLOMap();
- omap.items = pairs.items;
- return omap;
- }
- var omap = {
- identify: function identify(value) {
- return value instanceof Map;
- },
- nodeClass: YAMLOMap,
- default: false,
- tag: 'tag:yaml.org,2002:omap',
- resolve: parseOMap,
- createNode: createOMap
- };
- var YAMLSet = function (_YAMLMap) {
- _inherits(YAMLSet, _YAMLMap);
- var _super = _createSuper(YAMLSet);
- function YAMLSet() {
- var _this;
- _classCallCheck(this, YAMLSet);
- _this = _super.call(this);
- _this.tag = YAMLSet.tag;
- return _this;
- }
- _createClass(YAMLSet, [{
- key: "add",
- value: function add(key) {
- var pair = key instanceof Pair ? key : new Pair(key);
- var prev = findPair(this.items, pair.key);
- if (!prev) this.items.push(pair);
- }
- }, {
- key: "get",
- value: function get(key, keepPair) {
- var pair = findPair(this.items, key);
- return !keepPair && pair instanceof Pair ? pair.key instanceof Scalar ? pair.key.value : pair.key : pair;
- }
- }, {
- key: "set",
- value: function set(key, value) {
- if (typeof value !== 'boolean') throw new Error("Expected boolean value for set(key, value) in a YAML set, not ".concat(_typeof(value)));
- var prev = findPair(this.items, key);
- if (prev && !value) {
- this.items.splice(this.items.indexOf(prev), 1);
- } else if (!prev && value) {
- this.items.push(new Pair(key));
- }
- }
- }, {
- key: "toJSON",
- value: function toJSON(_, ctx) {
- return _get(_getPrototypeOf(YAMLSet.prototype), "toJSON", this).call(this, _, ctx, Set);
- }
- }, {
- key: "toString",
- value: function toString(ctx, onComment, onChompKeep) {
- if (!ctx) return JSON.stringify(this);
- if (this.hasAllNullValues()) return _get(_getPrototypeOf(YAMLSet.prototype), "toString", this).call(this, ctx, onComment, onChompKeep);else throw new Error('Set items must all have null values');
- }
- }]);
- return YAMLSet;
- }(YAMLMap);
- _defineProperty(YAMLSet, "tag", 'tag:yaml.org,2002:set');
- function parseSet(doc, cst) {
- var map = resolveMap(doc, cst);
- if (!map.hasAllNullValues()) throw new YAMLSemanticError(cst, 'Set items must all have null values');
- return Object.assign(new YAMLSet(), map);
- }
- function createSet(schema, iterable, ctx) {
- var set = new YAMLSet();
- var _iterator = _createForOfIteratorHelper(iterable),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var value = _step.value;
- set.items.push(schema.createPair(value, null, ctx));
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- return set;
- }
- var set = {
- identify: function identify(value) {
- return value instanceof Set;
- },
- nodeClass: YAMLSet,
- default: false,
- tag: 'tag:yaml.org,2002:set',
- resolve: parseSet,
- createNode: createSet
- };
- var parseSexagesimal = function parseSexagesimal(sign, parts) {
- var n = parts.split(':').reduce(function (n, p) {
- return n * 60 + Number(p);
- }, 0);
- return sign === '-' ? -n : n;
- };
- var stringifySexagesimal = function stringifySexagesimal(_ref) {
- var value = _ref.value;
- if (isNaN(value) || !isFinite(value)) return stringifyNumber(value);
- var sign = '';
- if (value < 0) {
- sign = '-';
- value = Math.abs(value);
- }
- var parts = [value % 60];
- if (value < 60) {
- parts.unshift(0);
- } else {
- value = Math.round((value - parts[0]) / 60);
- parts.unshift(value % 60);
- if (value >= 60) {
- value = Math.round((value - parts[0]) / 60);
- parts.unshift(value);
- }
- }
- return sign + parts.map(function (n) {
- return n < 10 ? '0' + String(n) : String(n);
- }).join(':').replace(/000000\d*$/, '')
- ;
- };
- var intTime = {
- identify: function identify(value) {
- return typeof value === 'number';
- },
- default: true,
- tag: 'tag:yaml.org,2002:int',
- format: 'TIME',
- test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/,
- resolve: function resolve(str, sign, parts) {
- return parseSexagesimal(sign, parts.replace(/_/g, ''));
- },
- stringify: stringifySexagesimal
- };
- var floatTime = {
- identify: function identify(value) {
- return typeof value === 'number';
- },
- default: true,
- tag: 'tag:yaml.org,2002:float',
- format: 'TIME',
- test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/,
- resolve: function resolve(str, sign, parts) {
- return parseSexagesimal(sign, parts.replace(/_/g, ''));
- },
- stringify: stringifySexagesimal
- };
- var timestamp = {
- identify: function identify(value) {
- return value instanceof Date;
- },
- default: true,
- tag: 'tag:yaml.org,2002:timestamp',
-
-
-
- test: RegExp('^(?:' + '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' +
- '(?:(?:t|T|[ \\t]+)' +
- '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' +
- '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' +
- ')?' + ')$'),
- resolve: function resolve(str, year, month, day, hour, minute, second, millisec, tz) {
- if (millisec) millisec = (millisec + '00').substr(1, 3);
- var date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec || 0);
- if (tz && tz !== 'Z') {
- var d = parseSexagesimal(tz[0], tz.slice(1));
- if (Math.abs(d) < 30) d *= 60;
- date -= 60000 * d;
- }
- return new Date(date);
- },
- stringify: function stringify(_ref2) {
- var value = _ref2.value;
- return value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, '');
- }
- };
- function shouldWarn(deprecation) {
- var env = typeof process !== 'undefined' && process.env || {};
- if (deprecation) {
- if (typeof YAML_SILENCE_DEPRECATION_WARNINGS !== 'undefined') return !YAML_SILENCE_DEPRECATION_WARNINGS;
- return !env.YAML_SILENCE_DEPRECATION_WARNINGS;
- }
- if (typeof YAML_SILENCE_WARNINGS !== 'undefined') return !YAML_SILENCE_WARNINGS;
- return !env.YAML_SILENCE_WARNINGS;
- }
- function warn(warning, type) {
- if (shouldWarn(false)) {
- var emit = typeof process !== 'undefined' && process.emitWarning;
-
- if (emit) emit(warning, type);else {
-
- console.warn(type ? "".concat(type, ": ").concat(warning) : warning);
- }
- }
- }
- var warned = {};
- function warnOptionDeprecation(name, alternative) {
- if (!warned[name] && shouldWarn(true)) {
- warned[name] = true;
- var msg = "The option '".concat(name, "' will be removed in a future release");
- msg += alternative ? ", use '".concat(alternative, "' instead.") : '.';
- warn(msg, 'DeprecationWarning');
- }
- }
- function createMap(schema, obj, ctx) {
- var map = new YAMLMap(schema);
- if (obj instanceof Map) {
- var _iterator = _createForOfIteratorHelper(obj),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var _step$value = _slicedToArray(_step.value, 2),
- key = _step$value[0],
- value = _step$value[1];
- map.items.push(schema.createPair(key, value, ctx));
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- } else if (obj && _typeof(obj) === 'object') {
- for (var _i = 0, _Object$keys = Object.keys(obj); _i < _Object$keys.length; _i++) {
- var _key = _Object$keys[_i];
- map.items.push(schema.createPair(_key, obj[_key], ctx));
- }
- }
- if (typeof schema.sortMapEntries === 'function') {
- map.items.sort(schema.sortMapEntries);
- }
- return map;
- }
- var map = {
- createNode: createMap,
- default: true,
- nodeClass: YAMLMap,
- tag: 'tag:yaml.org,2002:map',
- resolve: resolveMap
- };
- function createSeq(schema, obj, ctx) {
- var seq = new YAMLSeq(schema);
- if (obj && obj[Symbol.iterator]) {
- var _iterator = _createForOfIteratorHelper(obj),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var it = _step.value;
- var v = schema.createNode(it, ctx.wrapScalars, null, ctx);
- seq.items.push(v);
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- }
- return seq;
- }
- var seq = {
- createNode: createSeq,
- default: true,
- nodeClass: YAMLSeq,
- tag: 'tag:yaml.org,2002:seq',
- resolve: resolveSeq
- };
- var string = {
- identify: function identify(value) {
- return typeof value === 'string';
- },
- default: true,
- tag: 'tag:yaml.org,2002:str',
- resolve: resolveString,
- stringify: function stringify(item, ctx, onComment, onChompKeep) {
- ctx = Object.assign({
- actualString: true
- }, ctx);
- return stringifyString(item, ctx, onComment, onChompKeep);
- },
- options: strOptions
- };
- var failsafe = [map, seq, string];
- var intIdentify = function intIdentify(value) {
- return typeof value === 'bigint' || Number.isInteger(value);
- };
- var intResolve = function intResolve(src, part, radix) {
- return intOptions.asBigInt ? BigInt(src) : parseInt(part, radix);
- };
- function intStringify(node, radix, prefix) {
- var value = node.value;
- if (intIdentify(value) && value >= 0) return prefix + value.toString(radix);
- return stringifyNumber(node);
- }
- var nullObj = {
- identify: function identify(value) {
- return value == null;
- },
- createNode: function createNode(schema, value, ctx) {
- return ctx.wrapScalars ? new Scalar(null) : null;
- },
- default: true,
- tag: 'tag:yaml.org,2002:null',
- test: /^(?:~|[Nn]ull|NULL)?$/,
- resolve: function resolve() {
- return null;
- },
- options: nullOptions,
- stringify: function stringify() {
- return nullOptions.nullStr;
- }
- };
- var boolObj = {
- identify: function identify(value) {
- return typeof value === 'boolean';
- },
- default: true,
- tag: 'tag:yaml.org,2002:bool',
- test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
- resolve: function resolve(str) {
- return str[0] === 't' || str[0] === 'T';
- },
- options: boolOptions,
- stringify: function stringify(_ref) {
- var value = _ref.value;
- return value ? boolOptions.trueStr : boolOptions.falseStr;
- }
- };
- var octObj = {
- identify: function identify(value) {
- return intIdentify(value) && value >= 0;
- },
- default: true,
- tag: 'tag:yaml.org,2002:int',
- format: 'OCT',
- test: /^0o([0-7]+)$/,
- resolve: function resolve(str, oct) {
- return intResolve(str, oct, 8);
- },
- options: intOptions,
- stringify: function stringify(node) {
- return intStringify(node, 8, '0o');
- }
- };
- var intObj = {
- identify: intIdentify,
- default: true,
- tag: 'tag:yaml.org,2002:int',
- test: /^[-+]?[0-9]+$/,
- resolve: function resolve(str) {
- return intResolve(str, str, 10);
- },
- options: intOptions,
- stringify: stringifyNumber
- };
- var hexObj = {
- identify: function identify(value) {
- return intIdentify(value) && value >= 0;
- },
- default: true,
- tag: 'tag:yaml.org,2002:int',
- format: 'HEX',
- test: /^0x([0-9a-fA-F]+)$/,
- resolve: function resolve(str, hex) {
- return intResolve(str, hex, 16);
- },
- options: intOptions,
- stringify: function stringify(node) {
- return intStringify(node, 16, '0x');
- }
- };
- var nanObj = {
- identify: function identify(value) {
- return typeof value === 'number';
- },
- default: true,
- tag: 'tag:yaml.org,2002:float',
- test: /^(?:[-+]?\.inf|(\.nan))$/i,
- resolve: function resolve(str, nan) {
- return nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
- },
- stringify: stringifyNumber
- };
- var expObj = {
- identify: function identify(value) {
- return typeof value === 'number';
- },
- default: true,
- tag: 'tag:yaml.org,2002:float',
- format: 'EXP',
- test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
- resolve: function resolve(str) {
- return parseFloat(str);
- },
- stringify: function stringify(_ref2) {
- var value = _ref2.value;
- return Number(value).toExponential();
- }
- };
- var floatObj = {
- identify: function identify(value) {
- return typeof value === 'number';
- },
- default: true,
- tag: 'tag:yaml.org,2002:float',
- test: /^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/,
- resolve: function resolve(str, frac1, frac2) {
- var frac = frac1 || frac2;
- var node = new Scalar(parseFloat(str));
- if (frac && frac[frac.length - 1] === '0') node.minFractionDigits = frac.length;
- return node;
- },
- stringify: stringifyNumber
- };
- var core = failsafe.concat([nullObj, boolObj, octObj, intObj, hexObj, nanObj, expObj, floatObj]);
- var intIdentify$1 = function intIdentify(value) {
- return typeof value === 'bigint' || Number.isInteger(value);
- };
- var stringifyJSON = function stringifyJSON(_ref) {
- var value = _ref.value;
- return JSON.stringify(value);
- };
- var json = [map, seq, {
- identify: function identify(value) {
- return typeof value === 'string';
- },
- default: true,
- tag: 'tag:yaml.org,2002:str',
- resolve: resolveString,
- stringify: stringifyJSON
- }, {
- identify: function identify(value) {
- return value == null;
- },
- createNode: function createNode(schema, value, ctx) {
- return ctx.wrapScalars ? new Scalar(null) : null;
- },
- default: true,
- tag: 'tag:yaml.org,2002:null',
- test: /^null$/,
- resolve: function resolve() {
- return null;
- },
- stringify: stringifyJSON
- }, {
- identify: function identify(value) {
- return typeof value === 'boolean';
- },
- default: true,
- tag: 'tag:yaml.org,2002:bool',
- test: /^true|false$/,
- resolve: function resolve(str) {
- return str === 'true';
- },
- stringify: stringifyJSON
- }, {
- identify: intIdentify$1,
- default: true,
- tag: 'tag:yaml.org,2002:int',
- test: /^-?(?:0|[1-9][0-9]*)$/,
- resolve: function resolve(str) {
- return intOptions.asBigInt ? BigInt(str) : parseInt(str, 10);
- },
- stringify: function stringify(_ref2) {
- var value = _ref2.value;
- return intIdentify$1(value) ? value.toString() : JSON.stringify(value);
- }
- }, {
- identify: function identify(value) {
- return typeof value === 'number';
- },
- default: true,
- tag: 'tag:yaml.org,2002:float',
- test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
- resolve: function resolve(str) {
- return parseFloat(str);
- },
- stringify: stringifyJSON
- }];
- json.scalarFallback = function (str) {
- throw new SyntaxError("Unresolved plain scalar ".concat(JSON.stringify(str)));
- };
- var boolStringify = function boolStringify(_ref) {
- var value = _ref.value;
- return value ? boolOptions.trueStr : boolOptions.falseStr;
- };
- var intIdentify$2 = function intIdentify(value) {
- return typeof value === 'bigint' || Number.isInteger(value);
- };
- function intResolve$1(sign, src, radix) {
- var str = src.replace(/_/g, '');
- if (intOptions.asBigInt) {
- switch (radix) {
- case 2:
- str = "0b".concat(str);
- break;
- case 8:
- str = "0o".concat(str);
- break;
- case 16:
- str = "0x".concat(str);
- break;
- }
- var _n = BigInt(str);
- return sign === '-' ? BigInt(-1) * _n : _n;
- }
- var n = parseInt(str, radix);
- return sign === '-' ? -1 * n : n;
- }
- function intStringify$1(node, radix, prefix) {
- var value = node.value;
- if (intIdentify$2(value)) {
- var str = value.toString(radix);
- return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;
- }
- return stringifyNumber(node);
- }
- var yaml11 = failsafe.concat([{
- identify: function identify(value) {
- return value == null;
- },
- createNode: function createNode(schema, value, ctx) {
- return ctx.wrapScalars ? new Scalar(null) : null;
- },
- default: true,
- tag: 'tag:yaml.org,2002:null',
- test: /^(?:~|[Nn]ull|NULL)?$/,
- resolve: function resolve() {
- return null;
- },
- options: nullOptions,
- stringify: function stringify() {
- return nullOptions.nullStr;
- }
- }, {
- identify: function identify(value) {
- return typeof value === 'boolean';
- },
- default: true,
- tag: 'tag:yaml.org,2002:bool',
- test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
- resolve: function resolve() {
- return true;
- },
- options: boolOptions,
- stringify: boolStringify
- }, {
- identify: function identify(value) {
- return typeof value === 'boolean';
- },
- default: true,
- tag: 'tag:yaml.org,2002:bool',
- test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,
- resolve: function resolve() {
- return false;
- },
- options: boolOptions,
- stringify: boolStringify
- }, {
- identify: intIdentify$2,
- default: true,
- tag: 'tag:yaml.org,2002:int',
- format: 'BIN',
- test: /^([-+]?)0b([0-1_]+)$/,
- resolve: function resolve(str, sign, bin) {
- return intResolve$1(sign, bin, 2);
- },
- stringify: function stringify(node) {
- return intStringify$1(node, 2, '0b');
- }
- }, {
- identify: intIdentify$2,
- default: true,
- tag: 'tag:yaml.org,2002:int',
- format: 'OCT',
- test: /^([-+]?)0([0-7_]+)$/,
- resolve: function resolve(str, sign, oct) {
- return intResolve$1(sign, oct, 8);
- },
- stringify: function stringify(node) {
- return intStringify$1(node, 8, '0');
- }
- }, {
- identify: intIdentify$2,
- default: true,
- tag: 'tag:yaml.org,2002:int',
- test: /^([-+]?)([0-9][0-9_]*)$/,
- resolve: function resolve(str, sign, abs) {
- return intResolve$1(sign, abs, 10);
- },
- stringify: stringifyNumber
- }, {
- identify: intIdentify$2,
- default: true,
- tag: 'tag:yaml.org,2002:int',
- format: 'HEX',
- test: /^([-+]?)0x([0-9a-fA-F_]+)$/,
- resolve: function resolve(str, sign, hex) {
- return intResolve$1(sign, hex, 16);
- },
- stringify: function stringify(node) {
- return intStringify$1(node, 16, '0x');
- }
- }, {
- identify: function identify(value) {
- return typeof value === 'number';
- },
- default: true,
- tag: 'tag:yaml.org,2002:float',
- test: /^(?:[-+]?\.inf|(\.nan))$/i,
- resolve: function resolve(str, nan) {
- return nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
- },
- stringify: stringifyNumber
- }, {
- identify: function identify(value) {
- return typeof value === 'number';
- },
- default: true,
- tag: 'tag:yaml.org,2002:float',
- format: 'EXP',
- test: /^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/,
- resolve: function resolve(str) {
- return parseFloat(str.replace(/_/g, ''));
- },
- stringify: function stringify(_ref2) {
- var value = _ref2.value;
- return Number(value).toExponential();
- }
- }, {
- identify: function identify(value) {
- return typeof value === 'number';
- },
- default: true,
- tag: 'tag:yaml.org,2002:float',
- test: /^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/,
- resolve: function resolve(str, frac) {
- var node = new Scalar(parseFloat(str.replace(/_/g, '')));
- if (frac) {
- var f = frac.replace(/_/g, '');
- if (f[f.length - 1] === '0') node.minFractionDigits = f.length;
- }
- return node;
- },
- stringify: stringifyNumber
- }], binary, omap, pairs, set, intTime, floatTime, timestamp);
- var schemas = {
- core: core,
- failsafe: failsafe,
- json: json,
- yaml11: yaml11
- };
- var tags = {
- binary: binary,
- bool: boolObj,
- float: floatObj,
- floatExp: expObj,
- floatNaN: nanObj,
- floatTime: floatTime,
- int: intObj,
- intHex: hexObj,
- intOct: octObj,
- intTime: intTime,
- map: map,
- null: nullObj,
- omap: omap,
- pairs: pairs,
- seq: seq,
- set: set,
- timestamp: timestamp
- };
- function findTagObject(value, tagName, tags) {
- if (tagName) {
- var match = tags.filter(function (t) {
- return t.tag === tagName;
- });
- var tagObj = match.find(function (t) {
- return !t.format;
- }) || match[0];
- if (!tagObj) throw new Error("Tag ".concat(tagName, " not found"));
- return tagObj;
- }
- return tags.find(function (t) {
- return (t.identify && t.identify(value) || t.class && value instanceof t.class) && !t.format;
- });
- }
- function createNode(value, tagName, ctx) {
- if (value instanceof Node$1) return value;
- var defaultPrefix = ctx.defaultPrefix,
- onTagObj = ctx.onTagObj,
- prevObjects = ctx.prevObjects,
- schema = ctx.schema,
- wrapScalars = ctx.wrapScalars;
- if (tagName && tagName.startsWith('!!')) tagName = defaultPrefix + tagName.slice(2);
- var tagObj = findTagObject(value, tagName, schema.tags);
- if (!tagObj) {
- if (typeof value.toJSON === 'function') value = value.toJSON();
- if (_typeof(value) !== 'object') return wrapScalars ? new Scalar(value) : value;
- tagObj = value instanceof Map ? map : value[Symbol.iterator] ? seq : map;
- }
- if (onTagObj) {
- onTagObj(tagObj);
- delete ctx.onTagObj;
- }
-
- var obj = {};
- if (value && _typeof(value) === 'object' && prevObjects) {
- var prev = prevObjects.get(value);
- if (prev) {
- var alias = new Alias$1(prev);
- ctx.aliasNodes.push(alias);
- return alias;
- }
- obj.value = value;
- prevObjects.set(value, obj);
- }
- obj.node = tagObj.createNode ? tagObj.createNode(ctx.schema, value, ctx) : wrapScalars ? new Scalar(value) : value;
- if (tagName && obj.node instanceof Node$1) obj.node.tag = tagName;
- return obj.node;
- }
- function getSchemaTags(schemas, knownTags, customTags, schemaId) {
- var tags = schemas[schemaId.replace(/\W/g, '')];
- if (!tags) {
- var keys = Object.keys(schemas).map(function (key) {
- return JSON.stringify(key);
- }).join(', ');
- throw new Error("Unknown schema \"".concat(schemaId, "\"; use one of ").concat(keys));
- }
- if (Array.isArray(customTags)) {
- var _iterator = _createForOfIteratorHelper(customTags),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var tag = _step.value;
- tags = tags.concat(tag);
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- } else if (typeof customTags === 'function') {
- tags = customTags(tags.slice());
- }
- for (var i = 0; i < tags.length; ++i) {
- var _tag = tags[i];
- if (typeof _tag === 'string') {
- var tagObj = knownTags[_tag];
- if (!tagObj) {
- var _keys = Object.keys(knownTags).map(function (key) {
- return JSON.stringify(key);
- }).join(', ');
- throw new Error("Unknown custom tag \"".concat(_tag, "\"; use one of ").concat(_keys));
- }
- tags[i] = tagObj;
- }
- }
- return tags;
- }
- var sortMapEntriesByKey = function sortMapEntriesByKey(a, b) {
- return a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
- };
- var Schema = function () {
-
-
- function Schema(_ref) {
- var customTags = _ref.customTags,
- merge = _ref.merge,
- schema = _ref.schema,
- sortMapEntries = _ref.sortMapEntries,
- deprecatedCustomTags = _ref.tags;
- _classCallCheck(this, Schema);
- this.merge = !!merge;
- this.name = schema;
- this.sortMapEntries = sortMapEntries === true ? sortMapEntriesByKey : sortMapEntries || null;
- if (!customTags && deprecatedCustomTags) warnOptionDeprecation('tags', 'customTags');
- this.tags = getSchemaTags(schemas, tags, customTags || deprecatedCustomTags, schema);
- }
- _createClass(Schema, [{
- key: "createNode",
- value: function createNode$1(value, wrapScalars, tagName, ctx) {
- var baseCtx = {
- defaultPrefix: Schema.defaultPrefix,
- schema: this,
- wrapScalars: wrapScalars
- };
- var createCtx = ctx ? Object.assign(ctx, baseCtx) : baseCtx;
- return createNode(value, tagName, createCtx);
- }
- }, {
- key: "createPair",
- value: function createPair(key, value, ctx) {
- if (!ctx) ctx = {
- wrapScalars: true
- };
- var k = this.createNode(key, ctx.wrapScalars, null, ctx);
- var v = this.createNode(value, ctx.wrapScalars, null, ctx);
- return new Pair(k, v);
- }
- }]);
- return Schema;
- }();
- _defineProperty(Schema, "defaultPrefix", defaultTagPrefix);
- _defineProperty(Schema, "defaultTags", defaultTags);
- var defaultOptions = {
- anchorPrefix: 'a',
- customTags: null,
- indent: 2,
- indentSeq: true,
- keepCstNodes: false,
- keepNodeTypes: true,
- keepBlobsInJSON: true,
- mapAsMap: false,
- maxAliasCount: 100,
- prettyErrors: false,
-
- simpleKeys: false,
- version: '1.2'
- };
- var scalarOptions = {
- get binary() {
- return binaryOptions;
- },
- set binary(opt) {
- Object.assign(binaryOptions, opt);
- },
- get bool() {
- return boolOptions;
- },
- set bool(opt) {
- Object.assign(boolOptions, opt);
- },
- get int() {
- return intOptions;
- },
- set int(opt) {
- Object.assign(intOptions, opt);
- },
- get null() {
- return nullOptions;
- },
- set null(opt) {
- Object.assign(nullOptions, opt);
- },
- get str() {
- return strOptions;
- },
- set str(opt) {
- Object.assign(strOptions, opt);
- }
- };
- var documentOptions = {
- '1.0': {
- schema: 'yaml-1.1',
- merge: true,
- tagPrefixes: [{
- handle: '!',
- prefix: defaultTagPrefix
- }, {
- handle: '!!',
- prefix: 'tag:private.yaml.org,2002:'
- }]
- },
- '1.1': {
- schema: 'yaml-1.1',
- merge: true,
- tagPrefixes: [{
- handle: '!',
- prefix: '!'
- }, {
- handle: '!!',
- prefix: defaultTagPrefix
- }]
- },
- '1.2': {
- schema: 'core',
- merge: false,
- tagPrefixes: [{
- handle: '!',
- prefix: '!'
- }, {
- handle: '!!',
- prefix: defaultTagPrefix
- }]
- }
- };
- function stringifyTag(doc, tag) {
- if ((doc.version || doc.options.version) === '1.0') {
- var priv = tag.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);
- if (priv) return '!' + priv[1];
- var vocab = tag.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);
- return vocab ? "!".concat(vocab[1], "/").concat(vocab[2]) : "!".concat(tag.replace(/^tag:/, ''));
- }
- var p = doc.tagPrefixes.find(function (p) {
- return tag.indexOf(p.prefix) === 0;
- });
- if (!p) {
- var dtp = doc.getDefaults().tagPrefixes;
- p = dtp && dtp.find(function (p) {
- return tag.indexOf(p.prefix) === 0;
- });
- }
- if (!p) return tag[0] === '!' ? tag : "!<".concat(tag, ">");
- var suffix = tag.substr(p.prefix.length).replace(/[!,[\]{}]/g, function (ch) {
- return {
- '!': '%21',
- ',': '%2C',
- '[': '%5B',
- ']': '%5D',
- '{': '%7B',
- '}': '%7D'
- }[ch];
- });
- return p.handle + suffix;
- }
- function getTagObject(tags, item) {
- if (item instanceof Alias$1) return Alias$1;
- if (item.tag) {
- var match = tags.filter(function (t) {
- return t.tag === item.tag;
- });
- if (match.length > 0) return match.find(function (t) {
- return t.format === item.format;
- }) || match[0];
- }
- var tagObj, obj;
- if (item instanceof Scalar) {
- obj = item.value;
- var _match = tags.filter(function (t) {
- return t.identify && t.identify(obj) || t.class && obj instanceof t.class;
- });
- tagObj = _match.find(function (t) {
- return t.format === item.format;
- }) || _match.find(function (t) {
- return !t.format;
- });
- } else {
- obj = item;
- tagObj = tags.find(function (t) {
- return t.nodeClass && obj instanceof t.nodeClass;
- });
- }
- if (!tagObj) {
- var name = obj && obj.constructor ? obj.constructor.name : _typeof(obj);
- throw new Error("Tag not resolved for ".concat(name, " value"));
- }
- return tagObj;
- }
- function stringifyProps(node, tagObj, _ref) {
- var anchors = _ref.anchors,
- doc = _ref.doc;
- var props = [];
- var anchor = doc.anchors.getName(node);
- if (anchor) {
- anchors[anchor] = node;
- props.push("&".concat(anchor));
- }
- if (node.tag) {
- props.push(stringifyTag(doc, node.tag));
- } else if (!tagObj.default) {
- props.push(stringifyTag(doc, tagObj.tag));
- }
- return props.join(' ');
- }
- function stringify(item, ctx, onComment, onChompKeep) {
- var _ctx$doc = ctx.doc,
- anchors = _ctx$doc.anchors,
- schema = _ctx$doc.schema;
- var tagObj;
- if (!(item instanceof Node$1)) {
- var createCtx = {
- aliasNodes: [],
- onTagObj: function onTagObj(o) {
- return tagObj = o;
- },
- prevObjects: new Map()
- };
- item = schema.createNode(item, true, null, createCtx);
- var _iterator = _createForOfIteratorHelper(createCtx.aliasNodes),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var alias = _step.value;
- alias.source = alias.source.node;
- var name = anchors.getName(alias.source);
- if (!name) {
- name = anchors.newName();
- anchors.map[name] = alias.source;
- }
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- }
- if (item instanceof Pair) return item.toString(ctx, onComment, onChompKeep);
- if (!tagObj) tagObj = getTagObject(schema.tags, item);
- var props = stringifyProps(item, tagObj, ctx);
- if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart || 0) + props.length + 1;
- var str = typeof tagObj.stringify === 'function' ? tagObj.stringify(item, ctx, onComment, onChompKeep) : item instanceof Scalar ? stringifyString(item, ctx, onComment, onChompKeep) : item.toString(ctx, onComment, onChompKeep);
- if (!props) return str;
- return item instanceof Scalar || str[0] === '{' || str[0] === '[' ? "".concat(props, " ").concat(str) : "".concat(props, "\n").concat(ctx.indent).concat(str);
- }
- var Anchors = function () {
- _createClass(Anchors, null, [{
- key: "validAnchorNode",
- value: function validAnchorNode(node) {
- return node instanceof Scalar || node instanceof YAMLSeq || node instanceof YAMLMap;
- }
- }]);
- function Anchors(prefix) {
- _classCallCheck(this, Anchors);
- _defineProperty(this, "map", {});
- this.prefix = prefix;
- }
- _createClass(Anchors, [{
- key: "createAlias",
- value: function createAlias(node, name) {
- this.setAnchor(node, name);
- return new Alias$1(node);
- }
- }, {
- key: "createMergePair",
- value: function createMergePair() {
- var _this = this;
- var merge = new Merge();
- for (var _len = arguments.length, sources = new Array(_len), _key = 0; _key < _len; _key++) {
- sources[_key] = arguments[_key];
- }
- merge.value.items = sources.map(function (s) {
- if (s instanceof Alias$1) {
- if (s.source instanceof YAMLMap) return s;
- } else if (s instanceof YAMLMap) {
- return _this.createAlias(s);
- }
- throw new Error('Merge sources must be Map nodes or their Aliases');
- });
- return merge;
- }
- }, {
- key: "getName",
- value: function getName(node) {
- var map = this.map;
- return Object.keys(map).find(function (a) {
- return map[a] === node;
- });
- }
- }, {
- key: "getNames",
- value: function getNames() {
- return Object.keys(this.map);
- }
- }, {
- key: "getNode",
- value: function getNode(name) {
- return this.map[name];
- }
- }, {
- key: "newName",
- value: function newName(prefix) {
- if (!prefix) prefix = this.prefix;
- var names = Object.keys(this.map);
- for (var i = 1; true; ++i) {
- var name = "".concat(prefix).concat(i);
- if (!names.includes(name)) return name;
- }
- }
- }, {
- key: "resolveNodes",
- value: function resolveNodes() {
- var map = this.map,
- _cstAliases = this._cstAliases;
- Object.keys(map).forEach(function (a) {
- map[a] = map[a].resolved;
- });
- _cstAliases.forEach(function (a) {
- a.source = a.source.resolved;
- });
- delete this._cstAliases;
- }
- }, {
- key: "setAnchor",
- value: function setAnchor(node, name) {
- if (node != null && !Anchors.validAnchorNode(node)) {
- throw new Error('Anchors may only be set for Scalar, Seq and Map nodes');
- }
- if (name && /[\x00-\x19\s,[\]{}]/.test(name)) {
- throw new Error('Anchor names must not contain whitespace or control characters');
- }
- var map = this.map;
- var prev = node && Object.keys(map).find(function (a) {
- return map[a] === node;
- });
- if (prev) {
- if (!name) {
- return prev;
- } else if (prev !== name) {
- delete map[prev];
- map[name] = node;
- }
- } else {
- if (!name) {
- if (!node) return null;
- name = this.newName();
- }
- map[name] = node;
- }
- return name;
- }
- }]);
- return Anchors;
- }();
- var visit = function visit(node, tags) {
- if (node && _typeof(node) === 'object') {
- var tag = node.tag;
- if (node instanceof Collection$1) {
- if (tag) tags[tag] = true;
- node.items.forEach(function (n) {
- return visit(n, tags);
- });
- } else if (node instanceof Pair) {
- visit(node.key, tags);
- visit(node.value, tags);
- } else if (node instanceof Scalar) {
- if (tag) tags[tag] = true;
- }
- }
- return tags;
- };
- var listTagNames = function listTagNames(node) {
- return Object.keys(visit(node, {}));
- };
- function parseContents(doc, contents) {
- var comments = {
- before: [],
- after: []
- };
- var body = undefined;
- var spaceBefore = false;
- var _iterator = _createForOfIteratorHelper(contents),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var node = _step.value;
- if (node.valueRange) {
- if (body !== undefined) {
- var msg = 'Document contains trailing content not separated by a ... or --- line';
- doc.errors.push(new YAMLSyntaxError(node, msg));
- break;
- }
- var res = resolveNode(doc, node);
- if (spaceBefore) {
- res.spaceBefore = true;
- spaceBefore = false;
- }
- body = res;
- } else if (node.comment !== null) {
- var cc = body === undefined ? comments.before : comments.after;
- cc.push(node.comment);
- } else if (node.type === Type.BLANK_LINE) {
- spaceBefore = true;
- if (body === undefined && comments.before.length > 0 && !doc.commentBefore) {
-
- doc.commentBefore = comments.before.join('\n');
- comments.before = [];
- }
- }
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- doc.contents = body || null;
- if (!body) {
- doc.comment = comments.before.concat(comments.after).join('\n') || null;
- } else {
- var cb = comments.before.join('\n');
- if (cb) {
- var cbNode = body instanceof Collection$1 && body.items[0] ? body.items[0] : body;
- cbNode.commentBefore = cbNode.commentBefore ? "".concat(cb, "\n").concat(cbNode.commentBefore) : cb;
- }
- doc.comment = comments.after.join('\n') || null;
- }
- }
- function resolveTagDirective(_ref, directive) {
- var tagPrefixes = _ref.tagPrefixes;
- var _directive$parameters = _slicedToArray(directive.parameters, 2),
- handle = _directive$parameters[0],
- prefix = _directive$parameters[1];
- if (!handle || !prefix) {
- var msg = 'Insufficient parameters given for %TAG directive';
- throw new YAMLSemanticError(directive, msg);
- }
- if (tagPrefixes.some(function (p) {
- return p.handle === handle;
- })) {
- var _msg = 'The %TAG directive must only be given at most once per handle in the same document.';
- throw new YAMLSemanticError(directive, _msg);
- }
- return {
- handle: handle,
- prefix: prefix
- };
- }
- function resolveYamlDirective(doc, directive) {
- var _directive$parameters2 = _slicedToArray(directive.parameters, 1),
- version = _directive$parameters2[0];
- if (directive.name === 'YAML:1.0') version = '1.0';
- if (!version) {
- var msg = 'Insufficient parameters given for %YAML directive';
- throw new YAMLSemanticError(directive, msg);
- }
- if (!documentOptions[version]) {
- var v0 = doc.version || doc.options.version;
- var _msg2 = "Document will be parsed as YAML ".concat(v0, " rather than YAML ").concat(version);
- doc.warnings.push(new YAMLWarning(directive, _msg2));
- }
- return version;
- }
- function parseDirectives(doc, directives, prevDoc) {
- var directiveComments = [];
- var hasDirectives = false;
- var _iterator = _createForOfIteratorHelper(directives),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var directive = _step.value;
- var comment = directive.comment,
- name = directive.name;
- switch (name) {
- case 'TAG':
- try {
- doc.tagPrefixes.push(resolveTagDirective(doc, directive));
- } catch (error) {
- doc.errors.push(error);
- }
- hasDirectives = true;
- break;
- case 'YAML':
- case 'YAML:1.0':
- if (doc.version) {
- var msg = 'The %YAML directive must only be given at most once per document.';
- doc.errors.push(new YAMLSemanticError(directive, msg));
- }
- try {
- doc.version = resolveYamlDirective(doc, directive);
- } catch (error) {
- doc.errors.push(error);
- }
- hasDirectives = true;
- break;
- default:
- if (name) {
- var _msg3 = "YAML only supports %TAG and %YAML directives, and not %".concat(name);
- doc.warnings.push(new YAMLWarning(directive, _msg3));
- }
- }
- if (comment) directiveComments.push(comment);
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- if (prevDoc && !hasDirectives && '1.1' === (doc.version || prevDoc.version || doc.options.version)) {
- var copyTagPrefix = function copyTagPrefix(_ref2) {
- var handle = _ref2.handle,
- prefix = _ref2.prefix;
- return {
- handle: handle,
- prefix: prefix
- };
- };
- doc.tagPrefixes = prevDoc.tagPrefixes.map(copyTagPrefix);
- doc.version = prevDoc.version;
- }
- doc.commentBefore = directiveComments.join('\n') || null;
- }
- function assertCollection(contents) {
- if (contents instanceof Collection$1) return true;
- throw new Error('Expected a YAML collection as document contents');
- }
- var Document$1 = function () {
- function Document(options) {
- _classCallCheck(this, Document);
- this.anchors = new Anchors(options.anchorPrefix);
- this.commentBefore = null;
- this.comment = null;
- this.contents = null;
- this.directivesEndMarker = null;
- this.errors = [];
- this.options = options;
- this.schema = null;
- this.tagPrefixes = [];
- this.version = null;
- this.warnings = [];
- }
- _createClass(Document, [{
- key: "add",
- value: function add(value) {
- assertCollection(this.contents);
- return this.contents.add(value);
- }
- }, {
- key: "addIn",
- value: function addIn(path, value) {
- assertCollection(this.contents);
- this.contents.addIn(path, value);
- }
- }, {
- key: "delete",
- value: function _delete(key) {
- assertCollection(this.contents);
- return this.contents.delete(key);
- }
- }, {
- key: "deleteIn",
- value: function deleteIn(path) {
- if (isEmptyPath(path)) {
- if (this.contents == null) return false;
- this.contents = null;
- return true;
- }
- assertCollection(this.contents);
- return this.contents.deleteIn(path);
- }
- }, {
- key: "getDefaults",
- value: function getDefaults() {
- return Document.defaults[this.version] || Document.defaults[this.options.version] || {};
- }
- }, {
- key: "get",
- value: function get(key, keepScalar) {
- return this.contents instanceof Collection$1 ? this.contents.get(key, keepScalar) : undefined;
- }
- }, {
- key: "getIn",
- value: function getIn(path, keepScalar) {
- if (isEmptyPath(path)) return !keepScalar && this.contents instanceof Scalar ? this.contents.value : this.contents;
- return this.contents instanceof Collection$1 ? this.contents.getIn(path, keepScalar) : undefined;
- }
- }, {
- key: "has",
- value: function has(key) {
- return this.contents instanceof Collection$1 ? this.contents.has(key) : false;
- }
- }, {
- key: "hasIn",
- value: function hasIn(path) {
- if (isEmptyPath(path)) return this.contents !== undefined;
- return this.contents instanceof Collection$1 ? this.contents.hasIn(path) : false;
- }
- }, {
- key: "set",
- value: function set(key, value) {
- assertCollection(this.contents);
- this.contents.set(key, value);
- }
- }, {
- key: "setIn",
- value: function setIn(path, value) {
- if (isEmptyPath(path)) this.contents = value;else {
- assertCollection(this.contents);
- this.contents.setIn(path, value);
- }
- }
- }, {
- key: "setSchema",
- value: function setSchema(id, customTags) {
- if (!id && !customTags && this.schema) return;
- if (typeof id === 'number') id = id.toFixed(1);
- if (id === '1.0' || id === '1.1' || id === '1.2') {
- if (this.version) this.version = id;else this.options.version = id;
- delete this.options.schema;
- } else if (id && typeof id === 'string') {
- this.options.schema = id;
- }
- if (Array.isArray(customTags)) this.options.customTags = customTags;
- var opt = Object.assign({}, this.getDefaults(), this.options);
- this.schema = new Schema(opt);
- }
- }, {
- key: "parse",
- value: function parse(node, prevDoc) {
- if (this.options.keepCstNodes) this.cstNode = node;
- if (this.options.keepNodeTypes) this.type = 'DOCUMENT';
- var _node$directives = node.directives,
- directives = _node$directives === void 0 ? [] : _node$directives,
- _node$contents = node.contents,
- contents = _node$contents === void 0 ? [] : _node$contents,
- directivesEndMarker = node.directivesEndMarker,
- error = node.error,
- valueRange = node.valueRange;
- if (error) {
- if (!error.source) error.source = this;
- this.errors.push(error);
- }
- parseDirectives(this, directives, prevDoc);
- if (directivesEndMarker) this.directivesEndMarker = true;
- this.range = valueRange ? [valueRange.start, valueRange.end] : null;
- this.setSchema();
- this.anchors._cstAliases = [];
- parseContents(this, contents);
- this.anchors.resolveNodes();
- if (this.options.prettyErrors) {
- var _iterator = _createForOfIteratorHelper(this.errors),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var _error = _step.value;
- if (_error instanceof YAMLError) _error.makePretty();
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- var _iterator2 = _createForOfIteratorHelper(this.warnings),
- _step2;
- try {
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
- var warn = _step2.value;
- if (warn instanceof YAMLError) warn.makePretty();
- }
- } catch (err) {
- _iterator2.e(err);
- } finally {
- _iterator2.f();
- }
- }
- return this;
- }
- }, {
- key: "listNonDefaultTags",
- value: function listNonDefaultTags() {
- return listTagNames(this.contents).filter(function (t) {
- return t.indexOf(Schema.defaultPrefix) !== 0;
- });
- }
- }, {
- key: "setTagPrefix",
- value: function setTagPrefix(handle, prefix) {
- if (handle[0] !== '!' || handle[handle.length - 1] !== '!') throw new Error('Handle must start and end with !');
- if (prefix) {
- var prev = this.tagPrefixes.find(function (p) {
- return p.handle === handle;
- });
- if (prev) prev.prefix = prefix;else this.tagPrefixes.push({
- handle: handle,
- prefix: prefix
- });
- } else {
- this.tagPrefixes = this.tagPrefixes.filter(function (p) {
- return p.handle !== handle;
- });
- }
- }
- }, {
- key: "toJSON",
- value: function toJSON$1(arg, onAnchor) {
- var _this = this;
- var _this$options = this.options,
- keepBlobsInJSON = _this$options.keepBlobsInJSON,
- mapAsMap = _this$options.mapAsMap,
- maxAliasCount = _this$options.maxAliasCount;
- var keep = keepBlobsInJSON && (typeof arg !== 'string' || !(this.contents instanceof Scalar));
- var ctx = {
- doc: this,
- indentStep: ' ',
- keep: keep,
- mapAsMap: keep && !!mapAsMap,
- maxAliasCount: maxAliasCount,
- stringify: stringify
- };
- var anchorNames = Object.keys(this.anchors.map);
- if (anchorNames.length > 0) ctx.anchors = new Map(anchorNames.map(function (name) {
- return [_this.anchors.map[name], {
- alias: [],
- aliasCount: 0,
- count: 1
- }];
- }));
- var res = toJSON(this.contents, arg, ctx);
- if (typeof onAnchor === 'function' && ctx.anchors) {
- var _iterator3 = _createForOfIteratorHelper(ctx.anchors.values()),
- _step3;
- try {
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
- var _step3$value = _step3.value,
- count = _step3$value.count,
- _res = _step3$value.res;
- onAnchor(_res, count);
- }
- } catch (err) {
- _iterator3.e(err);
- } finally {
- _iterator3.f();
- }
- }
- return res;
- }
- }, {
- key: "toString",
- value: function toString() {
- if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified');
- var indentSize = this.options.indent;
- if (!Number.isInteger(indentSize) || indentSize <= 0) {
- var s = JSON.stringify(indentSize);
- throw new Error("\"indent\" option must be a positive integer, not ".concat(s));
- }
- this.setSchema();
- var lines = [];
- var hasDirectives = false;
- if (this.version) {
- var vd = '%YAML 1.2';
- if (this.schema.name === 'yaml-1.1') {
- if (this.version === '1.0') vd = '%YAML:1.0';else if (this.version === '1.1') vd = '%YAML 1.1';
- }
- lines.push(vd);
- hasDirectives = true;
- }
- var tagNames = this.listNonDefaultTags();
- this.tagPrefixes.forEach(function (_ref) {
- var handle = _ref.handle,
- prefix = _ref.prefix;
- if (tagNames.some(function (t) {
- return t.indexOf(prefix) === 0;
- })) {
- lines.push("%TAG ".concat(handle, " ").concat(prefix));
- hasDirectives = true;
- }
- });
- if (hasDirectives || this.directivesEndMarker) lines.push('---');
- if (this.commentBefore) {
- if (hasDirectives || !this.directivesEndMarker) lines.unshift('');
- lines.unshift(this.commentBefore.replace(/^/gm, '#'));
- }
- var ctx = {
- anchors: {},
- doc: this,
- indent: '',
- indentStep: ' '.repeat(indentSize),
- stringify: stringify
- };
- var chompKeep = false;
- var contentComment = null;
- if (this.contents) {
- if (this.contents instanceof Node$1) {
- if (this.contents.spaceBefore && (hasDirectives || this.directivesEndMarker)) lines.push('');
- if (this.contents.commentBefore) lines.push(this.contents.commentBefore.replace(/^/gm, '#'));
- ctx.forceBlockIndent = !!this.comment;
- contentComment = this.contents.comment;
- }
- var onChompKeep = contentComment ? null : function () {
- return chompKeep = true;
- };
- var body = stringify(this.contents, ctx, function () {
- return contentComment = null;
- }, onChompKeep);
- lines.push(addComment(body, '', contentComment));
- } else if (this.contents !== undefined) {
- lines.push(stringify(this.contents, ctx));
- }
- if (this.comment) {
- if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '') lines.push('');
- lines.push(this.comment.replace(/^/gm, '#'));
- }
- return lines.join('\n') + '\n';
- }
- }]);
- return Document;
- }();
- _defineProperty(Document$1, "defaults", documentOptions);
- function createNode$1(value) {
- var wrapScalars = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
- var tag = arguments.length > 2 ? arguments[2] : undefined;
- if (tag === undefined && typeof wrapScalars === 'string') {
- tag = wrapScalars;
- wrapScalars = true;
- }
- var options = Object.assign({}, Document$1.defaults[defaultOptions.version], defaultOptions);
- var schema = new Schema(options);
- return schema.createNode(value, wrapScalars, tag);
- }
- var Document$1$1 = function (_YAMLDocument) {
- _inherits(Document, _YAMLDocument);
- var _super = _createSuper(Document);
- function Document(options) {
- _classCallCheck(this, Document);
- return _super.call(this, Object.assign({}, defaultOptions, options));
- }
- return Document;
- }(Document$1);
- function parseAllDocuments(src, options) {
- var stream = [];
- var prev;
- var _iterator = _createForOfIteratorHelper(parse(src)),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var cstDoc = _step.value;
- var doc = new Document$1$1(options);
- doc.parse(cstDoc, prev);
- stream.push(doc);
- prev = doc;
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- return stream;
- }
- function parseDocument(src, options) {
- var cst = parse(src);
- var doc = new Document$1$1(options).parse(cst[0]);
- if (cst.length > 1) {
- var errMsg = 'Source contains multiple documents; please use YAML.parseAllDocuments()';
- doc.errors.unshift(new YAMLSemanticError(cst[1], errMsg));
- }
- return doc;
- }
- function parse$1(src, options) {
- var doc = parseDocument(src, options);
- doc.warnings.forEach(function (warning) {
- return warn(warning);
- });
- if (doc.errors.length > 0) throw doc.errors[0];
- return doc.toJSON();
- }
- function stringify$1(value, options) {
- var doc = new Document$1$1(options);
- doc.contents = value;
- return String(doc);
- }
- var YAML = {
- createNode: createNode$1,
- defaultOptions: defaultOptions,
- Document: Document$1$1,
- parse: parse$1,
- parseAllDocuments: parseAllDocuments,
- parseCST: parse,
- parseDocument: parseDocument,
- scalarOptions: scalarOptions,
- stringify: stringify$1
- };
- var dist = Object.freeze({
- __proto__: null,
- YAML: YAML
- });
- function getAugmentedNamespace(n) {
- if (n.__esModule) return n;
- var a = Object.defineProperty({}, '__esModule', {value: true});
- Object.keys(n).forEach(function (k) {
- var d = Object.getOwnPropertyDescriptor(n, k);
- Object.defineProperty(a, k, d.get ? d : {
- enumerable: true,
- get: function () {
- return n[k];
- }
- });
- });
- return a;
- }
- var require$$0 = getAugmentedNamespace(dist);
- var browser = require$$0.YAML;
- var ccardProcessor = (function () {
- function ccardProcessor(app) {
- this.app = app;
- }
- ccardProcessor.prototype.run = function (source, el, ctx, folderNote) {
- return __awaiter(this, void 0, void 0, function () {
- var yaml, docEl, docEl, error_1;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- _a.trys.push([0, 5, , 6]);
- yaml = browser.parse(source);
- if (!yaml)
- return [2 ];
-
- if (yaml.type === undefined)
- yaml.type = 'static';
- if (yaml.style === undefined)
- yaml.style = 'card';
- if (!(yaml.type == 'static')) return [3 , 2];
- return [4 , this.docElemStatic(yaml)];
- case 1:
- docEl = _a.sent();
- if (docEl) {
- el.appendChild(docEl);
- }
- return [3 , 4];
- case 2:
- if (!(yaml.type == 'folder_brief_live')) return [3 , 4];
- return [4 , this.docElemFolderBriefLive(yaml, folderNote)];
- case 3:
- docEl = _a.sent();
- if (docEl) {
- el.appendChild(docEl);
- }
- _a.label = 4;
- case 4: return [3 , 6];
- case 5:
- error_1 = _a.sent();
- console.log('Code Block: ccard', error_1);
- return [3 , 6];
- case 6: return [2 ];
- }
- });
- });
- };
-
- ccardProcessor.prototype.docElemStatic = function (yaml) {
- return __awaiter(this, void 0, void 0, function () {
- var cardBlock, cardsElem;
- return __generator(this, function (_a) {
- if (yaml.items && (yaml.items instanceof Array)) {
- cardBlock = new CardBlock();
- cardBlock.fromYamlCards(yaml);
- cardsElem = cardBlock.getDocElement(this.app);
- return [2 , cardsElem];
- }
- return [2 , null];
- });
- });
- };
-
- ccardProcessor.prototype.docElemFolderBriefLive = function (yaml, folderNote) {
- return __awaiter(this, void 0, void 0, function () {
- var folderPath, activeFile, notePath, folderExist, view, folderBrief, briefCards, ccardElem;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- folderPath = '';
- activeFile = this.app.workspace.getActiveFile();
- notePath = activeFile.path;
- if (!yaml.folder) return [3 , 2];
- return [4 , this.app.vault.adapter.exists(yaml.folder)];
- case 1:
- folderExist = _a.sent();
- if (folderExist)
- folderPath = yaml.folder;
- return [3 , 4];
- case 2: return [4 , folderNote.getNoteFolderBriefPath(notePath)];
- case 3:
- folderPath = _a.sent();
- _a.label = 4;
- case 4:
- if (!(folderPath.length > 0)) return [3 , 6];
- view = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView);
- if (!view) return [3 , 6];
- folderBrief = new FolderBrief(this.app);
-
- if (yaml.briefMax) {
- folderBrief.briefMax = yaml.briefMax;
- }
- if (yaml.noteOnly != undefined) {
- folderBrief.noteOnly = yaml.noteOnly;
- }
- return [4 , folderBrief.makeBriefCards(folderPath, notePath)];
- case 5:
- briefCards = _a.sent();
- briefCards.fromYamlOptions(yaml);
- ccardElem = briefCards.getDocElement(this.app);
- return [2 , ccardElem];
- case 6: return [2 , null];
- }
- });
- });
- };
- return ccardProcessor;
- }());
- var FOLDER_NOTE_DEFAULT_SETTINGS = {
- folderNoteHide: true,
- folderNoteType: 'inside',
- folderNoteName: '_about_',
- folderNoteKey: 'ctrl',
- folderNoteAutoRename: true,
- folderDelete2Note: false,
- folderNoteStrInit: '# {{FOLDER_NAME}} Overview\n {{FOLDER_BRIEF_LIVE}} \n'
- };
- var FolderNoteSettingTab = (function (_super) {
- __extends(FolderNoteSettingTab, _super);
- function FolderNoteSettingTab(app, plugin) {
- var _this = _super.call(this, app, plugin) || this;
- _this.plugin = plugin;
- return _this;
- }
- FolderNoteSettingTab.prototype.display = function () {
- var _this = this;
- var containerEl = this.containerEl;
- containerEl.empty();
- containerEl.createEl('h2', { text: 'Folder Note Plugin: Settings.' });
- new obsidian.Setting(containerEl)
- .setName('Note File Method')
- .setDesc('Select the method to put your folder note file. (Read doc for more information.)')
- .addDropdown(function (dropDown) {
- return dropDown
- .addOption('index', 'Index File')
- .addOption('inside', 'Folder Name Inside')
- .addOption('outside', 'Folder Name Outside')
- .setValue(_this.plugin.settings.folderNoteType || 'inside')
- .onChange(function (value) {
- _this.plugin.settings.folderNoteType = value;
- _this.plugin.saveSettings();
- _this.display();
- });
- });
- if (this.plugin.settings.folderNoteType == 'index') {
- new obsidian.Setting(containerEl)
- .setName('Index File Name')
- .setDesc('Set the index file name for folder note. (only for the Index method)')
- .addText(function (text) { return text
- .setValue(_this.plugin.settings.folderNoteName)
- .onChange(function (value) { return __awaiter(_this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
-
- this.plugin.settings.folderNoteName = value;
- return [4 , this.plugin.saveSettings()];
- case 1:
- _a.sent();
- return [2 ];
- }
- });
- }); }); });
- }
- new obsidian.Setting(containerEl)
- .setName('Inital Content')
- .setDesc('Set the inital content for new folder note. {{FOLDER_NAME}} will be replaced with current folder name.')
- .addTextArea(function (text) {
- text
- .setPlaceholder('About the folder.')
- .setValue(_this.plugin.settings.folderNoteStrInit)
- .onChange(function (value) { return __awaiter(_this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- _a.trys.push([0, 2, , 3]);
- this.plugin.settings.folderNoteStrInit = value;
- return [4 , this.plugin.saveSettings()];
- case 1:
- _a.sent();
- return [3 , 3];
- case 2:
- _a.sent();
- return [2 , false];
- case 3: return [2 ];
- }
- });
- }); });
- text.inputEl.rows = 8;
- text.inputEl.cols = 50;
- });
- new obsidian.Setting(containerEl)
- .setName('Key for New Note')
- .setDesc('Key + Click a folder to create folder note file. ')
- .addDropdown(function (dropDown) {
- return dropDown
- .addOption('ctrl', 'Ctrl + Click')
- .addOption('alt', 'Alt + Click')
- .setValue(_this.plugin.settings.folderNoteKey || 'ctrl')
- .onChange(function (value) {
- _this.plugin.settings.folderNoteKey = value;
- _this.plugin.saveSettings();
- });
- });
- new obsidian.Setting(containerEl)
- .setName('Hide Folder Note')
- .setDesc('Hide the folder note file in the file explorer panel.')
- .addToggle(function (toggle) {
- toggle.setValue(_this.plugin.settings.folderNoteHide);
- toggle.onChange(function (value) { return __awaiter(_this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- this.plugin.settings.folderNoteHide = value;
- return [4 , this.plugin.saveSettings()];
- case 1:
- _a.sent();
- return [2 ];
- }
- });
- }); });
- });
- if (this.plugin.settings.folderNoteType != 'index') {
- new obsidian.Setting(containerEl)
- .setName('Auto Rename')
- .setDesc('Try to automatically rename the folder note if a folder name is changed. (Experimental)')
- .addToggle(function (toggle) {
- toggle.setValue(_this.plugin.settings.folderNoteAutoRename);
- toggle.onChange(function (value) { return __awaiter(_this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- this.plugin.settings.folderNoteAutoRename = value;
- return [4 , this.plugin.saveSettings()];
- case 1:
- _a.sent();
- return [2 ];
- }
- });
- }); });
- });
- }
- if (this.plugin.settings.folderNoteType == 'outside') {
- new obsidian.Setting(containerEl)
- .setName('Delete Folder Note')
- .setDesc('Try to delete folder note when a folder is deleted. (Dangerous)')
- .addToggle(function (toggle) {
- toggle.setValue(_this.plugin.settings.folderDelete2Note);
- toggle.onChange(function (value) { return __awaiter(_this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- this.plugin.settings.folderDelete2Note = value;
- return [4 , this.plugin.saveSettings()];
- case 1:
- _a.sent();
- return [2 ];
- }
- });
- }); });
- });
- }
- };
- return FolderNoteSettingTab;
- }(obsidian.PluginSettingTab));
- var NoteFileMethod$1;
- (function (NoteFileMethod) {
- NoteFileMethod[NoteFileMethod["Index"] = 0] = "Index";
- NoteFileMethod[NoteFileMethod["Inside"] = 1] = "Inside";
- NoteFileMethod[NoteFileMethod["Outside"] = 2] = "Outside";
- })(NoteFileMethod$1 || (NoteFileMethod$1 = {}));
- var FolderNotePlugin = (function (_super) {
- __extends(FolderNotePlugin, _super);
- function FolderNotePlugin() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- FolderNotePlugin.prototype.onload = function () {
- return __awaiter(this, void 0, void 0, function () {
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- console.log('Loading Folder Note plugin.');
-
- return [4 , this.loadSettings()];
- case 1:
-
- _a.sent();
-
- this.registerMarkdownCodeBlockProcessor('ccard', function (source, el, ctx) { return __awaiter(_this, void 0, void 0, function () {
- var proc;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- proc = new ccardProcessor(this.app);
- return [4 , proc.run(source, el, ctx, this.folderNote)];
- case 1:
- _a.sent();
- return [2 ];
- }
- });
- }); });
-
- this.registerEvent(this.app.vault.on('rename', function (newPath, oldPath) { return _this.handleFileRename(newPath, oldPath); }));
-
- this.registerEvent(this.app.vault.on('delete', function (file) { return _this.handleFileDelete(file); }));
-
- this.addSettingTab(new FolderNoteSettingTab(this.app, this));
-
- this.registerDomEvent(document, 'click', function (evt) {
-
- var elemTarget = evt.target;
- var folderElem = _this.folderNote.setByFolderElement(elemTarget);
-
- if (_this.folderNote.folderPath.length > 0) {
-
- var newKey = false;
- if (_this.settings.folderNoteKey == 'ctrl') {
- newKey = (evt.ctrlKey || evt.metaKey);
- }
- else if (_this.settings.folderNoteKey == 'alt') {
- newKey = evt.altKey;
- }
-
- _this.folderNote.openFolderNote(folderElem, newKey);
- }
- });
- this.addCommand({
- id: 'insert-folder-brief',
- name: 'Insert Folder Brief',
- callback: function () { return __awaiter(_this, void 0, void 0, function () {
- var view, editor, activeFile, folderBrief, folderPath, briefCards;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- view = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView);
- if (!view) return [3 , 3];
- editor = view.sourceMode.cmEditor;
- activeFile = this.app.workspace.getActiveFile();
- folderBrief = new FolderBrief(this.app);
- return [4 , this.folderNote.getNoteFolderBriefPath(activeFile.path)];
- case 1:
- folderPath = _a.sent();
- return [4 , folderBrief.makeBriefCards(folderPath, activeFile.path)];
- case 2:
- briefCards = _a.sent();
- editor.replaceSelection(briefCards.getYamlCode(), "end");
- _a.label = 3;
- case 3: return [2 ];
- }
- });
- }); },
- hotkeys: []
- });
- this.addCommand({
- id: 'note-to-folder',
- name: 'Make Current Note to Folder',
- callback: function () { return __awaiter(_this, void 0, void 0, function () {
- var view, activeFile;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- view = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView);
- if (!view) return [3 , 2];
- activeFile = this.app.workspace.getActiveFile();
- this.folderNote.setByNotePath(activeFile.path);
- return [4 , this.folderNote.newNoteFolder()];
- case 1:
- _a.sent();
- _a.label = 2;
- case 2: return [2 ];
- }
- });
- }); },
- hotkeys: []
- });
- return [2 ];
- }
- });
- });
- };
- FolderNotePlugin.prototype.onunload = function () {
- console.log('Unloading Folder Note plugin');
- };
- FolderNotePlugin.prototype.updateFolderNote = function () {
- this.folderNote = new FolderNote(this.app, this.settings.folderNoteType, this.settings.folderNoteName);
- this.folderNote.initContent = this.settings.folderNoteStrInit;
- this.folderNote.hideNoteFile = this.settings.folderNoteHide;
- };
- FolderNotePlugin.prototype.loadSettings = function () {
- return __awaiter(this, void 0, void 0, function () {
- var _a, _b, _c, _d;
- return __generator(this, function (_e) {
- switch (_e.label) {
- case 0:
- _a = this;
- _c = (_b = Object).assign;
- _d = [FOLDER_NOTE_DEFAULT_SETTINGS];
- return [4 , this.loadData()];
- case 1:
- _a.settings = _c.apply(_b, _d.concat([_e.sent()]));
- this.updateFolderNote();
- return [2 ];
- }
- });
- });
- };
- FolderNotePlugin.prototype.saveSettings = function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 , this.saveData(this.settings)];
- case 1:
- _a.sent();
- this.updateFolderNote();
- return [2 ];
- }
- });
- });
- };
-
- FolderNotePlugin.prototype.handleFileRename = function (newPath, oldPath) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- if (!this.settings.folderNoteAutoRename)
- return [2 ];
- this.folderNote.syncName(newPath, oldPath);
- return [2 ];
- });
- });
- };
-
- FolderNotePlugin.prototype.handleFileDelete = function (pathToDel) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- if (!this.settings.folderDelete2Note)
- return [2 ];
- this.folderNote.deleteFolder(pathToDel.path);
- return [2 ];
- });
- });
- };
- return FolderNotePlugin;
- }(obsidian.Plugin));
- module.exports = FolderNotePlugin;
|